sort.c 29.1 KB
Newer Older
unknown's avatar
unknown committed
1
/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB
2

unknown's avatar
unknown committed
3 4 5 6
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
7

unknown's avatar
unknown committed
8 9 10 11
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
12

unknown's avatar
unknown committed
13 14 15 16 17 18 19 20 21
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

/*
  Creates a index for a database by reading keys, sorting them and outputing
  them in sorted order through SORT_INFO functions.
*/

22
#include "fulltext.h"
unknown's avatar
unknown committed
23 24 25 26 27 28 29
#if defined(MSDOS) || defined(__WIN__)
#include <fcntl.h>
#else
#include <stddef.h>
#endif
#include <queues.h>

unknown's avatar
unknown committed
30 31
/* static variables */

unknown's avatar
unknown committed
32 33 34
#undef MIN_SORT_MEMORY
#undef MYF_RW
#undef DISK_BUFFER_SIZE
unknown's avatar
unknown committed
35 36 37 38

#define MERGEBUFF 15
#define MERGEBUFF2 31
#define MIN_SORT_MEMORY (4096-MALLOC_OVERHEAD)
unknown's avatar
unknown committed
39
#define MYF_RW  MYF(MY_NABP | MY_WME | MY_WAIT_IF_FULL)
40
#define DISK_BUFFER_SIZE (IO_SIZE*16)
unknown's avatar
unknown committed
41

42 43 44 45

/*
 Pointers of functions for store and read keys from temp file
*/
unknown's avatar
unknown committed
46 47 48

extern void print_error _VARARGS((const char *fmt,...));

unknown's avatar
unknown committed
49
/* Functions defined in this file */
unknown's avatar
unknown committed
50 51

static ha_rows NEAR_F find_all_keys(MI_SORT_PARAM *info,uint keys,
unknown's avatar
unknown committed
52 53 54 55
                                    uchar **sort_keys,
                                    DYNAMIC_ARRAY *buffpek,int *maxbuffer,
                                    IO_CACHE *tempfile,
                                    IO_CACHE *tempfile_for_exceptions);
56
static int NEAR_F write_keys(MI_SORT_PARAM *info,uchar **sort_keys,
unknown's avatar
unknown committed
57
                             uint count, BUFFPEK *buffpek,IO_CACHE *tempfile);
unknown's avatar
unknown committed
58 59
static int NEAR_F write_key(MI_SORT_PARAM *info, uchar *key,
			    IO_CACHE *tempfile);
unknown's avatar
unknown committed
60
static int NEAR_F write_index(MI_SORT_PARAM *info,uchar * *sort_keys,
unknown's avatar
unknown committed
61
                              uint count);
unknown's avatar
unknown committed
62
static int NEAR_F merge_many_buff(MI_SORT_PARAM *info,uint keys,
unknown's avatar
unknown committed
63 64 65
                                  uchar * *sort_keys,
                                  BUFFPEK *buffpek,int *maxbuffer,
                                  IO_CACHE *t_file);
66
static uint NEAR_F read_to_buffer(IO_CACHE *fromfile,BUFFPEK *buffpek,
unknown's avatar
unknown committed
67
                                  uint sort_length);
68
static int NEAR_F merge_buffers(MI_SORT_PARAM *info,uint keys,
unknown's avatar
unknown committed
69 70 71
                                IO_CACHE *from_file, IO_CACHE *to_file,
                                uchar * *sort_keys, BUFFPEK *lastbuff,
                                BUFFPEK *Fb, BUFFPEK *Tb);
unknown's avatar
unknown committed
72
static int NEAR_F merge_index(MI_SORT_PARAM *,uint,uchar **,BUFFPEK *, int,
unknown's avatar
unknown committed
73
                              IO_CACHE *);
74 75
static int flush_ft_buf(MI_SORT_PARAM *info);

76
static int NEAR_F write_keys_varlen(MI_SORT_PARAM *info,uchar **sort_keys,
77 78
                                    uint count, BUFFPEK *buffpek,
                                    IO_CACHE *tempfile);
79 80
static uint NEAR_F read_to_buffer_varlen(IO_CACHE *fromfile,BUFFPEK *buffpek,
                                         uint sort_length);
81
static int NEAR_F write_merge_key(MI_SORT_PARAM *info, IO_CACHE *to_file,
82 83 84 85 86
                                  char *key, uint sort_length, uint count);
static int NEAR_F write_merge_key_varlen(MI_SORT_PARAM *info,
					 IO_CACHE *to_file,
					 char* key, uint sort_length,
					 uint count);
unknown's avatar
unknown committed
87
inline int my_var_write(MI_SORT_PARAM *info,IO_CACHE *to_file, byte *bufs);
unknown's avatar
unknown committed
88 89 90 91 92 93 94 95 96 97 98 99 100
/*
  Creates a index of sorted keys

  SYNOPSIS
    _create_index_by_sort()
    info		Sort parameters
    no_messages		Set to 1 if no output
    sortbuff_size	Size if sortbuffer to allocate

  RESULT
    0	ok
   <> 0 Error
*/
unknown's avatar
unknown committed
101 102 103 104 105 106

int _create_index_by_sort(MI_SORT_PARAM *info,my_bool no_messages,
			  ulong sortbuff_size)
{
  int error,maxbuffer,skr;
  uint memavl,old_memavl,keys,sort_length;
107
  DYNAMIC_ARRAY buffpek;
unknown's avatar
unknown committed
108 109
  ha_rows records;
  uchar **sort_keys;
110
  IO_CACHE tempfile, tempfile_for_exceptions;
unknown's avatar
unknown committed
111 112 113
  DBUG_ENTER("_create_index_by_sort");
  DBUG_PRINT("enter",("sort_length: %d", info->key_length));

114
  if (info->keyinfo->flag & HA_VAR_LENGTH_KEY)
115
  {
116 117 118
    info->write_keys=write_keys_varlen;
    info->read_to_buffer=read_to_buffer_varlen;
    info->write_key=write_merge_key_varlen;
119 120 121
  }
  else
  {
122 123 124
    info->write_keys=write_keys;
    info->read_to_buffer=read_to_buffer;
    info->write_key=write_merge_key;
125
  }
126

127
  my_b_clear(&tempfile);
128 129 130
  my_b_clear(&tempfile_for_exceptions);
  bzero((char*) &buffpek,sizeof(buffpek));
  sort_keys= (uchar **) NULL; error= 1;
unknown's avatar
unknown committed
131 132 133
  maxbuffer=1;

  memavl=max(sortbuff_size,MIN_SORT_MEMORY);
unknown's avatar
unknown committed
134
  records=	info->sort_info->max_records;
unknown's avatar
unknown committed
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
  sort_length=	info->key_length;
  LINT_INIT(keys);

  while (memavl >= MIN_SORT_MEMORY)
  {
    if ((my_off_t) (records+1)*(sort_length+sizeof(char*)) <=
	(my_off_t) memavl)
      keys= records+1;
    else
      do
      {
	skr=maxbuffer;
	if (memavl < sizeof(BUFFPEK)*(uint) maxbuffer ||
	    (keys=(memavl-sizeof(BUFFPEK)*(uint) maxbuffer)/
	     (sort_length+sizeof(char*))) <= 1)
	{
	  mi_check_print_error(info->sort_info->param,
			       "sort_buffer_size is to small");
	  goto err;
	}
      }
      while ((maxbuffer= (int) (records/(keys-1)+1)) != skr);

158
    if ((sort_keys=(uchar **)my_malloc(keys*(sort_length+sizeof(char*))+
159
				       HA_FT_MAXBYTELEN, MYF(0))))
unknown's avatar
unknown committed
160
    {
161
      if (my_init_dynamic_array(&buffpek, sizeof(BUFFPEK), maxbuffer,
162
			     maxbuffer/2))
unknown's avatar
unknown committed
163
	my_free((gptr) sort_keys,MYF(0));
164 165
      else
	break;
unknown's avatar
unknown committed
166 167 168 169 170 171 172
    }
    old_memavl=memavl;
    if ((memavl=memavl/4*3) < MIN_SORT_MEMORY && old_memavl > MIN_SORT_MEMORY)
      memavl=MIN_SORT_MEMORY;
  }
  if (memavl < MIN_SORT_MEMORY)
  {
173 174
    mi_check_print_error(info->sort_info->param,"Sort buffer to small"); /* purecov: tested */
    goto err; /* purecov: tested */
unknown's avatar
unknown committed
175 176 177 178 179 180
  }
  (*info->lock_in_memory)(info->sort_info->param);/* Everything is allocated */

  if (!no_messages)
    printf("  - Searching for keys, allocating buffer for %d keys\n",keys);

181 182
  if ((records=find_all_keys(info,keys,sort_keys,&buffpek,&maxbuffer,
                                  &tempfile,&tempfile_for_exceptions))
unknown's avatar
unknown committed
183
      == HA_POS_ERROR)
184
    goto err; /* purecov: tested */
unknown's avatar
unknown committed
185 186 187
  if (maxbuffer == 0)
  {
    if (!no_messages)
188 189
      printf("  - Dumping %lu keys\n", (ulong) records);
    if (write_index(info,sort_keys, (uint) records))
190
      goto err; /* purecov: inspected */
unknown's avatar
unknown committed
191 192 193 194 195 196 197
  }
  else
  {
    keys=(keys*(sort_length+sizeof(char*)))/sort_length;
    if (maxbuffer >= MERGEBUFF2)
    {
      if (!no_messages)
198
	printf("  - Merging %lu keys\n", (ulong) records); /* purecov: tested */
199 200
      if (merge_many_buff(info,keys,sort_keys,
                  dynamic_element(&buffpek,0,BUFFPEK *),&maxbuffer,&tempfile))
unknown's avatar
unknown committed
201
	goto err;				/* purecov: inspected */
unknown's avatar
unknown committed
202
    }
203 204
    if (flush_io_cache(&tempfile) ||
	reinit_io_cache(&tempfile,READ_CACHE,0L,0,0))
unknown's avatar
unknown committed
205
      goto err;					/* purecov: inspected */
unknown's avatar
unknown committed
206
    if (!no_messages)
207
      puts("  - Last merge and dumping keys\n"); /* purecov: tested */
208 209
    if (merge_index(info,keys,sort_keys,dynamic_element(&buffpek,0,BUFFPEK *),
                    maxbuffer,&tempfile))
unknown's avatar
unknown committed
210
      goto err;					/* purecov: inspected */
unknown's avatar
unknown committed
211
  }
212

213
  if (flush_ft_buf(info) || flush_pending_blocks(info))
214 215 216 217 218
    goto err;

  if (my_b_inited(&tempfile_for_exceptions))
  {
    MI_INFO *index=info->sort_info->info;
unknown's avatar
unknown committed
219
    uint     keyno=info->key;
220 221 222 223 224 225
    uint     key_length, ref_length=index->s->rec_reflength;

    if (flush_io_cache(&tempfile_for_exceptions) ||
	reinit_io_cache(&tempfile_for_exceptions,READ_CACHE,0L,0,0))
      goto err;

unknown's avatar
unknown committed
226 227 228 229
    while (!my_b_read(&tempfile_for_exceptions,(byte*)&key_length,
		      sizeof(key_length))
        && !my_b_read(&tempfile_for_exceptions,(byte*)sort_keys,
		      (uint) key_length))
230
    {
unknown's avatar
unknown committed
231 232
	if (_mi_ck_write(index,keyno,(uchar*) sort_keys,key_length-ref_length))
	  goto err;
233 234 235
    }
  }

unknown's avatar
unknown committed
236 237 238 239 240
  error =0;

err:
  if (sort_keys)
    my_free((gptr) sort_keys,MYF(0));
241
  delete_dynamic(&buffpek);
242
  close_cached_file(&tempfile);
243
  close_cached_file(&tempfile_for_exceptions);
unknown's avatar
unknown committed
244 245 246 247 248

  DBUG_RETURN(error ? -1 : 0);
} /* _create_index_by_sort */


unknown's avatar
unknown committed
249
/* Search after all keys and place them in a temp. file */
unknown's avatar
unknown committed
250 251

static ha_rows NEAR_F find_all_keys(MI_SORT_PARAM *info, uint keys,
252 253 254
				    uchar **sort_keys, DYNAMIC_ARRAY *buffpek,
				    int *maxbuffer, IO_CACHE *tempfile,
				    IO_CACHE *tempfile_for_exceptions)
unknown's avatar
unknown committed
255 256
{
  int error;
257
  uint idx;
unknown's avatar
unknown committed
258 259
  DBUG_ENTER("find_all_keys");

260
  idx=error=0;
unknown's avatar
unknown committed
261
  sort_keys[0]=(uchar*) (sort_keys+keys);
unknown's avatar
unknown committed
262

unknown's avatar
unknown committed
263
  while (!(error=(*info->key_read)(info,sort_keys[idx])))
unknown's avatar
unknown committed
264
  {
unknown's avatar
unknown committed
265
    if (info->real_key_length > info->key_length)
unknown's avatar
unknown committed
266
    {
267
      if (write_key(info,sort_keys[idx],tempfile_for_exceptions))
unknown's avatar
unknown committed
268
        DBUG_RETURN(HA_POS_ERROR);		/* purecov: inspected */
269 270 271 272 273
      continue;
    }

    if (++idx == keys)
    {
274
      if (info->write_keys(info,sort_keys,idx-1,(BUFFPEK *)alloc_dynamic(buffpek),
unknown's avatar
unknown committed
275 276
		     tempfile))
      DBUG_RETURN(HA_POS_ERROR);		/* purecov: inspected */
277

unknown's avatar
unknown committed
278
      sort_keys[0]=(uchar*) (sort_keys+keys);
unknown's avatar
unknown committed
279
      memcpy(sort_keys[0],sort_keys[idx-1],(size_t) info->key_length);
280
      idx=1;
unknown's avatar
unknown committed
281
    }
282
    sort_keys[idx]=sort_keys[idx-1]+info->key_length;
unknown's avatar
unknown committed
283 284
  }
  if (error > 0)
285
    DBUG_RETURN(HA_POS_ERROR);		/* Aborted by get_key */ /* purecov: inspected */
286 287
  if (buffpek->elements)
  {
288
    if (info->write_keys(info,sort_keys,idx,(BUFFPEK *)alloc_dynamic(buffpek),
unknown's avatar
unknown committed
289
		   tempfile))
unknown's avatar
unknown committed
290
      DBUG_RETURN(HA_POS_ERROR);		/* purecov: inspected */
291 292 293 294
    *maxbuffer=buffpek->elements-1;
  }
  else
    *maxbuffer=0;
unknown's avatar
unknown committed
295

296 297
  DBUG_RETURN((*maxbuffer)*(keys-1)+idx);
} /* find_all_keys */
unknown's avatar
unknown committed
298

unknown's avatar
unknown committed
299

300
#ifdef THREAD
unknown's avatar
unknown committed
301
/* Search after all keys and place them in a temp. file */
unknown's avatar
unknown committed
302

303
pthread_handler_decl(thr_find_all_keys,arg)
unknown's avatar
unknown committed
304
{
305
  MI_SORT_PARAM *info= (MI_SORT_PARAM*) arg;
unknown's avatar
unknown committed
306
  int error;
unknown's avatar
unknown committed
307 308
  uint memavl,old_memavl,keys,sort_length;
  uint idx, maxbuffer;
309
  uchar **sort_keys=0;
unknown's avatar
unknown committed
310

unknown's avatar
unknown committed
311 312
  LINT_INIT(keys);

313 314 315 316 317 318
  error=1;

  if (my_thread_init())
    goto err;
  if (info->sort_info->got_error)
    goto err;
unknown's avatar
unknown committed
319

320
  if (info->keyinfo->flag && HA_VAR_LENGTH_KEY)
321
  {
322 323 324
    info->write_keys=write_keys_varlen;
    info->read_to_buffer=read_to_buffer_varlen;
    info->write_key=write_merge_key_varlen;
325 326 327
  }
  else
  {
328 329 330
    info->write_keys=write_keys;
    info->read_to_buffer=read_to_buffer;
    info->write_key=write_merge_key;
331 332
  }

unknown's avatar
unknown committed
333 334 335 336
  my_b_clear(&info->tempfile);
  my_b_clear(&info->tempfile_for_exceptions);
  bzero((char*) &info->buffpek,sizeof(info->buffpek));
  bzero((char*) &info->unique, sizeof(info->unique));
unknown's avatar
unknown committed
337
  sort_keys= (uchar **) NULL;
unknown's avatar
unknown committed
338 339 340 341

  memavl=max(info->sortbuff_size, MIN_SORT_MEMORY);
  idx=      info->sort_info->max_records;
  sort_length=  info->key_length;
342
  maxbuffer= 1;
unknown's avatar
unknown committed
343 344 345 346 347 348 349

  while (memavl >= MIN_SORT_MEMORY)
  {
    if ((my_off_t) (idx+1)*(sort_length+sizeof(char*)) <=
        (my_off_t) memavl)
      keys= idx+1;
    else
unknown's avatar
unknown committed
350 351
    {
      uint skr;
unknown's avatar
unknown committed
352 353 354 355 356 357 358 359 360 361 362 363 364
      do
      {
        skr=maxbuffer;
        if (memavl < sizeof(BUFFPEK)*maxbuffer ||
            (keys=(memavl-sizeof(BUFFPEK)*maxbuffer)/
             (sort_length+sizeof(char*))) <= 1)
        {
          mi_check_print_error(info->sort_info->param,
                               "sort_buffer_size is to small");
          goto err;
        }
      }
      while ((maxbuffer= (int) (idx/(keys-1)+1)) != skr);
unknown's avatar
unknown committed
365
    }
unknown's avatar
unknown committed
366
    if ((sort_keys=(uchar **)my_malloc(keys*(sort_length+sizeof(char*))+
unknown's avatar
unknown committed
367
				       ((info->keyinfo->flag & HA_FULLTEXT) ?
368
					HA_FT_MAXBYTELEN : 0), MYF(0))))
unknown's avatar
unknown committed
369 370
    {
      if (my_init_dynamic_array(&info->buffpek, sizeof(BUFFPEK),
unknown's avatar
unknown committed
371
				maxbuffer, maxbuffer/2))
unknown's avatar
unknown committed
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
        my_free((gptr) sort_keys,MYF(0));
      else
        break;
    }
    old_memavl=memavl;
    if ((memavl=memavl/4*3) < MIN_SORT_MEMORY && old_memavl > MIN_SORT_MEMORY)
      memavl=MIN_SORT_MEMORY;
  }
  if (memavl < MIN_SORT_MEMORY)
  {
    mi_check_print_error(info->sort_info->param,"Sort buffer to small"); /* purecov: tested */
    goto err; /* purecov: tested */
  }

  if (info->sort_info->param->testflag & T_VERBOSE)
    printf("Key %d - Allocating buffer for %d keys\n",info->key+1,keys);
  info->sort_keys=sort_keys;

  idx=error=0;
  sort_keys[0]=(uchar*) (sort_keys+keys);

unknown's avatar
unknown committed
393 394
  while (!(error=info->sort_info->got_error) &&
         !(error=(*info->key_read)(info,sort_keys[idx])))
unknown's avatar
unknown committed
395 396 397
  {
    if (info->real_key_length > info->key_length)
    {
unknown's avatar
unknown committed
398
      if (write_key(info,sort_keys[idx], &info->tempfile_for_exceptions))
unknown's avatar
unknown committed
399 400 401 402 403 404
        goto err;
      continue;
    }

    if (++idx == keys)
    {
405
      if (info->write_keys(info,sort_keys,idx-1,
unknown's avatar
unknown committed
406 407
		     (BUFFPEK *)alloc_dynamic(&info->buffpek),
		     &info->tempfile))
unknown's avatar
unknown committed
408 409 410 411 412 413 414 415 416 417 418
        goto err;
      sort_keys[0]=(uchar*) (sort_keys+keys);
      memcpy(sort_keys[0],sort_keys[idx-1],(size_t) info->key_length);
      idx=1;
    }
    sort_keys[idx]=sort_keys[idx-1]+info->key_length;
  }
  if (error > 0)
    goto err;
  if (info->buffpek.elements)
  {
419
    if (info->write_keys(info,sort_keys, idx,
unknown's avatar
unknown committed
420
		   (BUFFPEK *) alloc_dynamic(&info->buffpek), &info->tempfile))
unknown's avatar
unknown committed
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
      goto err;
    info->keys=(info->buffpek.elements-1)*(keys-1)+idx;
  }
  else
    info->keys=idx;

  info->sort_keys_length=keys;
  goto ok;

err:
  info->sort_info->got_error=1; /* no need to protect this with a mutex */
  if (sort_keys)
    my_free((gptr) sort_keys,MYF(0));
  info->sort_keys=0;
  delete_dynamic(& info->buffpek);
unknown's avatar
unknown committed
436 437 438
  close_cached_file(&info->tempfile);
  close_cached_file(&info->tempfile_for_exceptions);

unknown's avatar
unknown committed
439
ok:
unknown's avatar
unknown committed
440 441
  remove_io_thread(&info->read_cache);
  pthread_mutex_lock(&info->sort_info->mutex);
unknown's avatar
unknown committed
442
  info->sort_info->threads_running--;
unknown's avatar
unknown committed
443 444
  pthread_cond_signal(&info->sort_info->cond);
  pthread_mutex_unlock(&info->sort_info->mutex);
445
  my_thread_end();
unknown's avatar
unknown committed
446
  return NULL;
447
}
unknown's avatar
unknown committed
448

unknown's avatar
unknown committed
449

450
int thr_write_keys(MI_SORT_PARAM *sort_param)
unknown's avatar
unknown committed
451 452 453 454 455
{
  SORT_INFO *sort_info=sort_param->sort_info;
  MI_CHECK *param=sort_info->param;
  ulong length, keys;
  ulong *rec_per_key_part=param->rec_per_key_part;
unknown's avatar
unknown committed
456 457
  int got_error=sort_info->got_error;
  uint i;
unknown's avatar
unknown committed
458
  MI_INFO *info=sort_info->info;
459
  MYISAM_SHARE *share=info->s;
unknown's avatar
unknown committed
460 461
  MI_SORT_PARAM *sinfo;
  byte *mergebuf=0;
unknown's avatar
unknown committed
462
  LINT_INIT(length);
unknown's avatar
unknown committed
463

unknown's avatar
unknown committed
464 465 466
  for (i= 0, sinfo= sort_param ;
       i < sort_info->total_keys ;
       i++, rec_per_key_part+=sinfo->keyinfo->keysegs, sinfo++)
unknown's avatar
unknown committed
467 468 469 470 471 472
  {
    if (!sinfo->sort_keys)
    {
      got_error=1;
      continue;
    }
473
    if (!got_error)
unknown's avatar
unknown committed
474
    {
475 476 477 478 479
      share->state.key_map|=(ulonglong) 1 << sinfo->key;
      if (param->testflag & T_STATISTICS)
        update_key_parts(sinfo->keyinfo, rec_per_key_part,
                         sinfo->unique, (ulonglong) info->state->records);
      if (!sinfo->buffpek.elements)
unknown's avatar
unknown committed
480
      {
481 482 483 484 485 486
        if (param->testflag & T_VERBOSE)
        {
          printf("Key %d  - Dumping %u keys\n",sinfo->key+1, sinfo->keys);
          fflush(stdout);
        }
        if (write_index(sinfo, sinfo->sort_keys, sinfo->keys) ||
487
            flush_ft_buf(sinfo) || flush_pending_blocks(sinfo))
488
          got_error=1;
unknown's avatar
unknown committed
489
      }
unknown's avatar
unknown committed
490 491
    }
    my_free((gptr) sinfo->sort_keys,MYF(0));
unknown's avatar
unknown committed
492 493
    my_free(mi_get_rec_buff_ptr(info, sinfo->rec_buff),
	    MYF(MY_ALLOW_ZERO_PTR));
unknown's avatar
unknown committed
494 495 496
    sinfo->sort_keys=0;
  }

unknown's avatar
unknown committed
497 498 499 500 501 502 503
  for (i= 0, sinfo= sort_param ;
       i < sort_info->total_keys ;
       i++,
	 delete_dynamic(&sinfo->buffpek),
	 close_cached_file(&sinfo->tempfile),
	 close_cached_file(&sinfo->tempfile_for_exceptions),
	 sinfo++)
unknown's avatar
unknown committed
504
  {
unknown's avatar
unknown committed
505 506
    if (got_error)
      continue;
507
    if (sinfo->keyinfo->flag && HA_VAR_LENGTH_KEY)
508
    {
509 510 511
      sinfo->write_keys=write_keys_varlen;
      sinfo->read_to_buffer=read_to_buffer_varlen;
      sinfo->write_key=write_merge_key_varlen;
512 513 514
    }
    else
    {
515 516 517
      sinfo->write_keys=write_keys;
      sinfo->read_to_buffer=read_to_buffer;
      sinfo->write_key=write_merge_key;
518
    }
unknown's avatar
unknown committed
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
    if (sinfo->buffpek.elements)
    {
      uint maxbuffer=sinfo->buffpek.elements-1;
      if (!mergebuf)
      {
        length=param->sort_buffer_length;
        while (length >= MIN_SORT_MEMORY && !mergebuf)
        {
          mergebuf=my_malloc(length, MYF(0));
          length=length*3/4;
        }
        if (!mergebuf)
        {
          got_error=1;
          continue;
        }
      }
      keys=length/sinfo->key_length;
      if (maxbuffer >= MERGEBUFF2)
      {
        if (param->testflag & T_VERBOSE)
unknown's avatar
unknown committed
540
          printf("Key %d  - Merging %u keys\n",sinfo->key+1, sinfo->keys);
unknown's avatar
unknown committed
541
        if (merge_many_buff(sinfo, keys, (uchar **)mergebuf,
unknown's avatar
unknown committed
542
			    dynamic_element(&sinfo->buffpek, 0, BUFFPEK *),
543
			    (int*) &maxbuffer, &sinfo->tempfile))
unknown's avatar
unknown committed
544 545 546 547 548 549 550 551 552 553 554 555
        {
          got_error=1;
          continue;
        }
      }
      if (flush_io_cache(&sinfo->tempfile) ||
          reinit_io_cache(&sinfo->tempfile,READ_CACHE,0L,0,0))
      {
        got_error=1;
        continue;
      }
      if (param->testflag & T_VERBOSE)
556
        printf("Key %d  - Last merge and dumping keys\n", sinfo->key+1);
unknown's avatar
unknown committed
557 558
      if (merge_index(sinfo, keys, (uchar **)mergebuf,
                      dynamic_element(&sinfo->buffpek,0,BUFFPEK *),
unknown's avatar
unknown committed
559
                      maxbuffer,&sinfo->tempfile) ||
560
          flush_ft_buf(sinfo) ||
unknown's avatar
unknown committed
561
	  flush_pending_blocks(sinfo))
unknown's avatar
unknown committed
562 563 564 565 566 567 568 569 570 571
      {
        got_error=1;
        continue;
      }
    }
    if (my_b_inited(&sinfo->tempfile_for_exceptions))
    {
      uint key_length;

      if (param->testflag & T_VERBOSE)
572
        printf("Key %d  - Dumping 'long' keys\n", sinfo->key+1);
unknown's avatar
unknown committed
573 574 575 576 577 578 579 580

      if (flush_io_cache(&sinfo->tempfile_for_exceptions) ||
          reinit_io_cache(&sinfo->tempfile_for_exceptions,READ_CACHE,0L,0,0))
      {
        got_error=1;
        continue;
      }

unknown's avatar
unknown committed
581 582 583 584 585
      while (!got_error &&
	     !my_b_read(&sinfo->tempfile_for_exceptions,(byte*)&key_length,
			sizeof(key_length)) &&
	     !my_b_read(&sinfo->tempfile_for_exceptions,(byte*)mergebuf,
			(uint) key_length))
unknown's avatar
unknown committed
586
      {
unknown's avatar
unknown committed
587 588 589
	if (_mi_ck_write(info,sinfo->key,(uchar*) mergebuf,
			 key_length - info->s->rec_reflength))
	  got_error=1;
unknown's avatar
unknown committed
590 591 592 593 594 595
      }
    }
  }
  my_free((gptr) mergebuf,MYF(MY_ALLOW_ZERO_PTR));
  return got_error;
}
596
#endif /* THREAD */
unknown's avatar
unknown committed
597 598

        /* Write all keys in memory to file for later merge */
unknown's avatar
unknown committed
599 600

static int NEAR_F write_keys(MI_SORT_PARAM *info, register uchar **sort_keys,
unknown's avatar
unknown committed
601
                             uint count, BUFFPEK *buffpek, IO_CACHE *tempfile)
unknown's avatar
unknown committed
602
{
603 604
  uchar **end;
  uint sort_length=info->key_length;
unknown's avatar
unknown committed
605 606 607
  DBUG_ENTER("write_keys");

  qsort2((byte*) sort_keys,count,sizeof(byte*),(qsort2_cmp) info->key_cmp,
unknown's avatar
unknown committed
608
         info);
609
  if (!my_b_inited(tempfile) &&
610 611
      open_cached_file(tempfile, my_tmpdir(info->tmpdir), "ST",
                       DISK_BUFFER_SIZE, info->sort_info->param->myf_rw))
612
    DBUG_RETURN(1); /* purecov: inspected */
613

614
  buffpek->file_pos=my_b_tell(tempfile);
unknown's avatar
unknown committed
615
  buffpek->count=count;
616 617

  for (end=sort_keys+count ; sort_keys != end ; sort_keys++)
618
  {
619
    if (my_b_write(tempfile,(byte*) *sort_keys,(uint) sort_length))
620
      DBUG_RETURN(1); /* purecov: inspected */
621
  }
unknown's avatar
unknown committed
622 623 624
  DBUG_RETURN(0);
} /* write_keys */

unknown's avatar
unknown committed
625 626

inline int my_var_write(MI_SORT_PARAM *info, IO_CACHE *to_file, byte *bufs)
627 628
{
  int err;
unknown's avatar
unknown committed
629
  uint16 len = _mi_keylength(info->keyinfo, (uchar*) bufs);
630

unknown's avatar
unknown committed
631 632
  /* The following is safe as this is a local file */
  if ((err= my_b_write(to_file, (byte*)&len, sizeof(len))))
633
    return (err);
unknown's avatar
unknown committed
634
  if ((err= my_b_write(to_file,bufs, (uint) len)))
635 636
    return (err);
  return (0);
637 638 639
}


unknown's avatar
unknown committed
640 641 642 643
static int NEAR_F write_keys_varlen(MI_SORT_PARAM *info,
				    register uchar **sort_keys,
                                    uint count, BUFFPEK *buffpek,
				    IO_CACHE *tempfile)
644 645
{
  uchar **end;
646
  int err;
647 648 649 650 651
  DBUG_ENTER("write_keys_varlen");

  qsort2((byte*) sort_keys,count,sizeof(byte*),(qsort2_cmp) info->key_cmp,
         info);
  if (!my_b_inited(tempfile) &&
652
      open_cached_file(tempfile, my_tmpdir(info->tmpdir), "ST",
653 654 655 656 657 658 659
                       DISK_BUFFER_SIZE, info->sort_info->param->myf_rw))
    DBUG_RETURN(1); /* purecov: inspected */

  buffpek->file_pos=my_b_tell(tempfile);
  buffpek->count=count;
  for (end=sort_keys+count ; sort_keys != end ; sort_keys++)
  {
unknown's avatar
unknown committed
660
    if ((err= my_var_write(info,tempfile, (byte*) *sort_keys)))
661
      DBUG_RETURN(err);
662 663 664 665
  }
  DBUG_RETURN(0);
} /* write_keys_varlen */

unknown's avatar
unknown committed
666

unknown's avatar
unknown committed
667 668
static int NEAR_F write_key(MI_SORT_PARAM *info, uchar *key,
			    IO_CACHE *tempfile)
669
{
unknown's avatar
unknown committed
670
  uint key_length=info->real_key_length;
671 672 673
  DBUG_ENTER("write_key");

  if (!my_b_inited(tempfile) &&
674 675
      open_cached_file(tempfile, my_tmpdir(info->tmpdir), "ST",
                       DISK_BUFFER_SIZE, info->sort_info->param->myf_rw))
676 677 678 679 680 681 682 683
    DBUG_RETURN(1);

  if (my_b_write(tempfile,(byte*)&key_length,sizeof(key_length)) ||
      my_b_write(tempfile,(byte*)key,(uint) key_length))
    DBUG_RETURN(1);
  DBUG_RETURN(0);
} /* write_key */

unknown's avatar
unknown committed
684

unknown's avatar
unknown committed
685
/* Write index */
unknown's avatar
unknown committed
686

687
static int NEAR_F write_index(MI_SORT_PARAM *info, register uchar **sort_keys,
unknown's avatar
unknown committed
688
                              register uint count)
unknown's avatar
unknown committed
689 690 691 692
{
  DBUG_ENTER("write_index");

  qsort2((gptr) sort_keys,(size_t) count,sizeof(byte*),
unknown's avatar
unknown committed
693
        (qsort2_cmp) info->key_cmp,info);
unknown's avatar
unknown committed
694
  while (count--)
unknown's avatar
unknown committed
695
  {
unknown's avatar
unknown committed
696
    if ((*info->key_write)(info,*sort_keys++))
697
      DBUG_RETURN(-1); /* purecov: inspected */
unknown's avatar
unknown committed
698
  }
unknown's avatar
unknown committed
699 700 701 702
  DBUG_RETURN(0);
} /* write_index */


unknown's avatar
unknown committed
703
        /* Merge buffers to make < MERGEBUFF2 buffers */
unknown's avatar
unknown committed
704 705

static int NEAR_F merge_many_buff(MI_SORT_PARAM *info, uint keys,
unknown's avatar
unknown committed
706 707
                                  uchar **sort_keys, BUFFPEK *buffpek,
                                  int *maxbuffer, IO_CACHE *t_file)
unknown's avatar
unknown committed
708 709
{
  register int i;
710
  IO_CACHE t_file2, *from_file, *to_file, *temp;
unknown's avatar
unknown committed
711 712 713
  BUFFPEK *lastbuff;
  DBUG_ENTER("merge_many_buff");

714
  if (*maxbuffer < MERGEBUFF2)
unknown's avatar
unknown committed
715
    DBUG_RETURN(0);                             /* purecov: inspected */
716
  if (flush_io_cache(t_file) ||
717 718
      open_cached_file(&t_file2,my_tmpdir(info->tmpdir),"ST",
                       DISK_BUFFER_SIZE, info->sort_info->param->myf_rw))
unknown's avatar
unknown committed
719
    DBUG_RETURN(1);                             /* purecov: inspected */
unknown's avatar
unknown committed
720

721
  from_file= t_file ; to_file= &t_file2;
unknown's avatar
unknown committed
722 723
  while (*maxbuffer >= MERGEBUFF2)
  {
724 725
    reinit_io_cache(from_file,READ_CACHE,0L,0,0);
    reinit_io_cache(to_file,WRITE_CACHE,0L,0,0);
unknown's avatar
unknown committed
726 727 728 729
    lastbuff=buffpek;
    for (i=0 ; i <= *maxbuffer-MERGEBUFF*3/2 ; i+=MERGEBUFF)
    {
      if (merge_buffers(info,keys,from_file,to_file,sort_keys,lastbuff++,
unknown's avatar
unknown committed
730 731
                        buffpek+i,buffpek+i+MERGEBUFF-1))
        break; /* purecov: inspected */
unknown's avatar
unknown committed
732 733
    }
    if (merge_buffers(info,keys,from_file,to_file,sort_keys,lastbuff++,
unknown's avatar
unknown committed
734
                      buffpek+i,buffpek+ *maxbuffer))
735
      break; /* purecov: inspected */
736
    if (flush_io_cache(to_file))
unknown's avatar
unknown committed
737
      break;                                    /* purecov: inspected */
unknown's avatar
unknown committed
738
    temp=from_file; from_file=to_file; to_file=temp;
739
    *maxbuffer= (int) (lastbuff-buffpek)-1;
unknown's avatar
unknown committed
740
  }
unknown's avatar
unknown committed
741
  close_cached_file(to_file);                   /* This holds old result */
742
  if (to_file == t_file)
unknown's avatar
unknown committed
743
    *t_file=t_file2;                            /* Copy result file */
unknown's avatar
unknown committed
744

unknown's avatar
unknown committed
745
  DBUG_RETURN(*maxbuffer >= MERGEBUFF2);        /* Return 1 if interrupted */
unknown's avatar
unknown committed
746 747 748
} /* merge_many_buff */


unknown's avatar
unknown committed
749 750 751 752 753 754 755 756 757 758 759 760
/*
   Read data to buffer

  SYNOPSIS
    read_to_buffer()
    fromfile		File to read from
    buffpek		Where to read from
    sort_length		max length to read
  RESULT
    > 0	Ammount of bytes read
    -1	Error
*/
unknown's avatar
unknown committed
761

762
static uint NEAR_F read_to_buffer(IO_CACHE *fromfile, BUFFPEK *buffpek,
unknown's avatar
unknown committed
763
                                  uint sort_length)
unknown's avatar
unknown committed
764 765 766 767
{
  register uint count;
  uint length;

768
  if ((count=(uint) min((ha_rows) buffpek->max_keys,buffpek->count)))
unknown's avatar
unknown committed
769
  {
770
    if (my_pread(fromfile->file,(byte*) buffpek->base,
unknown's avatar
unknown committed
771 772
                 (length= sort_length*count),buffpek->file_pos,MYF_RW))
      return((uint) -1);                        /* purecov: inspected */
unknown's avatar
unknown committed
773
    buffpek->key=buffpek->base;
unknown's avatar
unknown committed
774 775
    buffpek->file_pos+= length;                 /* New filepos */
    buffpek->count-=    count;
unknown's avatar
unknown committed
776 777 778 779 780
    buffpek->mem_count= count;
  }
  return (count*sort_length);
} /* read_to_buffer */

781 782 783 784 785 786 787
static uint NEAR_F read_to_buffer_varlen(IO_CACHE *fromfile, BUFFPEK *buffpek,
                                         uint sort_length)
{
  register uint count;
  uint16 length_of_key = 0;
  uint idx;
  uchar *buffp;
788

789 790 791 792 793 794 795 796
  if ((count=(uint) min((ha_rows) buffpek->max_keys,buffpek->count)))
  {
    buffp = buffpek->base;

    for (idx=1;idx<=count;idx++)
    {
      if (my_pread(fromfile->file,(byte*)&length_of_key,sizeof(length_of_key),
                   buffpek->file_pos,MYF_RW))
797
        return((uint) -1);
798 799 800
      buffpek->file_pos+=sizeof(length_of_key);
      if (my_pread(fromfile->file,(byte*) buffp,length_of_key,
                   buffpek->file_pos,MYF_RW))
801
        return((uint) -1);
802 803
      buffpek->file_pos+=length_of_key;
      buffp = buffp + sort_length;
804
    }
805 806 807 808 809 810 811 812
    buffpek->key=buffpek->base;
    buffpek->count-=    count;
    buffpek->mem_count= count;
  }
  return (count*sort_length);
} /* read_to_buffer_varlen */


813 814
static int NEAR_F write_merge_key_varlen(MI_SORT_PARAM *info,
					 IO_CACHE *to_file,char* key,
815 816 817 818
                                         uint sort_length, uint count)
{
  uint idx;

819
  char *bufs = key;
820 821
  for (idx=1;idx<=count;idx++)
  {
822
    int err;
unknown's avatar
unknown committed
823
    if ((err= my_var_write(info,to_file, (byte*) bufs)))
824
      return (err);
825 826 827 828 829
    bufs=bufs+sort_length;
  }
  return(0);
}

830 831 832 833

static int NEAR_F write_merge_key(MI_SORT_PARAM *info __attribute__((unused)),
				  IO_CACHE *to_file, char* key,
				  uint sort_length, uint count)
834
{
835
  return my_b_write(to_file,(byte*) key,(uint) sort_length*count);
836
}
unknown's avatar
unknown committed
837

unknown's avatar
unknown committed
838 839 840 841
/*
  Merge buffers to one buffer
  If to_file == 0 then use info->key_write
*/
unknown's avatar
unknown committed
842 843

static int NEAR_F
844
merge_buffers(MI_SORT_PARAM *info, uint keys, IO_CACHE *from_file,
unknown's avatar
unknown committed
845 846
              IO_CACHE *to_file, uchar **sort_keys, BUFFPEK *lastbuff,
              BUFFPEK *Fb, BUFFPEK *Tb)
unknown's avatar
unknown committed
847 848 849 850 851 852 853 854
{
  int error;
  uint sort_length,maxcount;
  ha_rows count;
  my_off_t to_start_filepos;
  uchar *strpos;
  BUFFPEK *buffpek,**refpek;
  QUEUE queue;
unknown's avatar
unknown committed
855
  volatile bool *killed= killed_ptr(info->sort_info->param);
unknown's avatar
unknown committed
856 857 858 859 860 861
  DBUG_ENTER("merge_buffers");

  count=error=0;
  maxcount=keys/((uint) (Tb-Fb) +1);
  LINT_INIT(to_start_filepos);
  if (to_file)
862
    to_start_filepos=my_b_tell(to_file);
unknown's avatar
unknown committed
863
  strpos=(uchar*) sort_keys;
864
  sort_length=info->key_length;
unknown's avatar
unknown committed
865 866

  if (init_queue(&queue,(uint) (Tb-Fb)+1,offsetof(BUFFPEK,key),0,
unknown's avatar
unknown committed
867
                 (int (*)(void*, byte *,byte*)) info->key_cmp,
unknown's avatar
unknown committed
868
                 (void*) info))
869
    DBUG_RETURN(1); /* purecov: inspected */
unknown's avatar
unknown committed
870

871
  for (buffpek= Fb ; buffpek <= Tb ; buffpek++)
unknown's avatar
unknown committed
872 873 874 875
  {
    count+= buffpek->count;
    buffpek->base= strpos;
    buffpek->max_keys=maxcount;
876
    strpos+= (uint) (error=(int) info->read_to_buffer(from_file,buffpek,sort_length));
877 878
    if (error == -1)
      goto err; /* purecov: inspected */
unknown's avatar
unknown committed
879
    queue_insert(&queue,(char*) buffpek);
unknown's avatar
unknown committed
880 881 882 883 884 885
  }

  while (queue.elements > 1)
  {
    for (;;)
    {
unknown's avatar
unknown committed
886 887 888 889
      if (*killed)
      {
        error=1; goto err;
      }
unknown's avatar
unknown committed
890 891 892
      buffpek=(BUFFPEK*) queue_top(&queue);
      if (to_file)
      {
893
        if (info->write_key(info,to_file,(byte*) buffpek->key,(uint) sort_length,1))
unknown's avatar
unknown committed
894 895 896
        {
          error=1; goto err; /* purecov: inspected */
        }
unknown's avatar
unknown committed
897 898 899
      }
      else
      {
unknown's avatar
unknown committed
900 901 902 903
        if ((*info->key_write)(info,(void*) buffpek->key))
        {
          error=1; goto err; /* purecov: inspected */
        }
unknown's avatar
unknown committed
904 905 906 907
      }
      buffpek->key+=sort_length;
      if (! --buffpek->mem_count)
      {
908
        if (!(error=(int) info->read_to_buffer(from_file,buffpek,sort_length)))
unknown's avatar
unknown committed
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
        {
          uchar *base=buffpek->base;
          uint max_keys=buffpek->max_keys;

          VOID(queue_remove(&queue,0));

          /* Put room used by buffer to use in other buffer */
          for (refpek= (BUFFPEK**) &queue_top(&queue);
               refpek <= (BUFFPEK**) &queue_end(&queue);
               refpek++)
          {
            buffpek= *refpek;
            if (buffpek->base+buffpek->max_keys*sort_length == base)
            {
              buffpek->max_keys+=max_keys;
              break;
            }
            else if (base+max_keys*sort_length == buffpek->base)
            {
              buffpek->base=base;
              buffpek->max_keys+=max_keys;
              break;
            }
          }
          break;                /* One buffer have been removed */
        }
unknown's avatar
unknown committed
935
      }
936
      else if (error == -1)
unknown's avatar
unknown committed
937 938
        goto err;               /* purecov: inspected */
      queue_replaced(&queue);   /* Top element has been replaced */
unknown's avatar
unknown committed
939 940 941 942 943 944 945 946 947
    }
  }
  buffpek=(BUFFPEK*) queue_top(&queue);
  buffpek->base=(uchar *) sort_keys;
  buffpek->max_keys=keys;
  do
  {
    if (to_file)
    {
948
      if (info->write_key(info,to_file,(byte*) buffpek->key,
949
                         sort_length,buffpek->mem_count))
unknown's avatar
unknown committed
950
      {
unknown's avatar
unknown committed
951
        error=1; goto err; /* purecov: inspected */
unknown's avatar
unknown committed
952 953 954 955 956 957 958
      }
    }
    else
    {
      register uchar *end;
      strpos= buffpek->key;
      for (end=strpos+buffpek->mem_count*sort_length;
unknown's avatar
unknown committed
959 960
           strpos != end ;
           strpos+=sort_length)
unknown's avatar
unknown committed
961
      {
unknown's avatar
unknown committed
962 963 964 965
        if ((*info->key_write)(info,(void*) strpos))
        {
          error=1; goto err; /* purecov: inspected */
        }
unknown's avatar
unknown committed
966 967 968
      }
    }
  }
969
  while ((error=(int) info->read_to_buffer(from_file,buffpek,sort_length)) != -1 &&
unknown's avatar
unknown committed
970
         error != 0);
unknown's avatar
unknown committed
971 972 973

  lastbuff->count=count;
  if (to_file)
974
    lastbuff->file_pos=to_start_filepos;
unknown's avatar
unknown committed
975 976 977 978 979 980
err:
  delete_queue(&queue);
  DBUG_RETURN(error);
} /* merge_buffers */


unknown's avatar
unknown committed
981
        /* Do a merge to output-file (save only positions) */
unknown's avatar
unknown committed
982 983 984

static int NEAR_F
merge_index(MI_SORT_PARAM *info, uint keys, uchar **sort_keys,
unknown's avatar
unknown committed
985
            BUFFPEK *buffpek, int maxbuffer, IO_CACHE *tempfile)
unknown's avatar
unknown committed
986 987
{
  DBUG_ENTER("merge_index");
988
  if (merge_buffers(info,keys,tempfile,(IO_CACHE*) 0,sort_keys,buffpek,buffpek,
unknown's avatar
unknown committed
989
                    buffpek+maxbuffer))
990
    DBUG_RETURN(1); /* purecov: inspected */
unknown's avatar
unknown committed
991 992 993
  DBUG_RETURN(0);
} /* merge_index */

994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
static int
flush_ft_buf(MI_SORT_PARAM *info)
{
  int err=0;
  if (info->sort_info->ft_buf)
  {
    err=sort_ft_buf_flush(info);
    my_free((gptr)info->sort_info->ft_buf, MYF(0));
    info->sort_info->ft_buf=0;
  }
  return err;
}