]> pd.if.org Git - btree/blob - fosterbtreeg.c
Merge branch 'master' of https://github.com/malbrain/Btree-source-code
[btree] / fosterbtreeg.c
1 // foster btree version g
2 // 02 JAN 2014
3
4 // author: karl malbrain, malbrain@cal.berkeley.edu
5
6 /*
7 This work, including the source code, documentation
8 and related data, is placed into the public domain.
9
10 The orginal author is Karl Malbrain.
11
12 THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY
13 OF ANY KIND, NOT EVEN THE IMPLIED WARRANTY OF
14 MERCHANTABILITY. THE AUTHOR OF THIS SOFTWARE,
15 ASSUMES _NO_ RESPONSIBILITY FOR ANY CONSEQUENCE
16 RESULTING FROM THE USE, MODIFICATION, OR
17 REDISTRIBUTION OF THIS SOFTWARE.
18 */
19
20 // Please see the project home page for documentation
21 // code.google.com/p/high-concurrency-btree
22
23 #define _FILE_OFFSET_BITS 64
24 #define _LARGEFILE64_SOURCE
25
26 #ifdef linux
27 #define _GNU_SOURCE
28 #endif
29
30 #ifdef unix
31 #include <unistd.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <fcntl.h>
35 #include <sys/time.h>
36 #include <sys/mman.h>
37 #include <errno.h>
38 #include <pthread.h>
39 #else
40 #define WIN32_LEAN_AND_MEAN
41 #include <windows.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <time.h>
45 #include <fcntl.h>
46 #include <process.h>
47 #include <intrin.h>
48 #endif
49
50 #include <memory.h>
51 #include <string.h>
52
53 typedef unsigned long long      uid;
54
55 #ifndef unix
56 typedef unsigned long long      off64_t;
57 typedef unsigned short          ushort;
58 typedef unsigned int            uint;
59 #endif
60
61 #define BT_ro 0x6f72    // ro
62 #define BT_rw 0x7772    // rw
63
64 #define BT_maxbits              24                                      // maximum page size in bits
65 #define BT_minbits              9                                       // minimum page size in bits
66 #define BT_minpage              (1 << BT_minbits)       // minimum page size
67 #define BT_maxpage              (1 << BT_maxbits)       // maximum page size
68
69 /*
70 There are five lock types for each node in three independent sets: 
71 1. (set 1) AccessIntent: Sharable. Going to Read the node. Incompatible with NodeDelete. 
72 2. (set 1) NodeDelete: Exclusive. About to release the node. Incompatible with AccessIntent. 
73 3. (set 2) ReadLock: Sharable. Read the node. Incompatible with WriteLock. 
74 4. (set 2) WriteLock: Exclusive. Modify the node. Incompatible with ReadLock and other WriteLocks. 
75 5. (set 3) ParentLock: Exclusive. Have parent adopt/delete maximum foster child from the node.
76 */
77
78 typedef enum{
79         BtLockAccess,
80         BtLockDelete,
81         BtLockRead,
82         BtLockWrite,
83         BtLockParent
84 }BtLock;
85
86 //      Define the length of the page and key pointers
87
88 #define BtId 6
89
90 //      Page key slot definition.
91
92 //      If BT_maxbits is 15 or less, you can save 4 bytes
93 //      for each key stored by making the first two uints
94 //      into ushorts.  You can also save 4 bytes by removing
95 //      the tod field from the key.
96
97 //      Keys are marked dead, but remain on the page until
98 //      it cleanup is called. The fence key (highest key) for
99 //      the page is always present, even after cleanup.
100
101 typedef struct {
102         uint off:BT_maxbits;            // page offset for key start
103         uint dead:1;                            // set for deleted key
104         uint tod;                                       // time-stamp for key
105         unsigned char id[BtId];         // id associated with key
106 } BtSlot;
107
108 //      The key structure occupies space at the upper end of
109 //      each page.  It's a length byte followed by the value
110 //      bytes.
111
112 typedef struct {
113         unsigned char len;
114         unsigned char key[1];
115 } *BtKey;
116
117 //      mode & definition for spin latch implementation
118
119 enum {
120         Mutex = 1,
121         Write = 2,
122         Pending = 4,
123         Share = 8
124 } LockMode;
125
126 // mutex locks the other fields
127 // exclusive is set for write access
128 // share is count of read accessors
129
130 typedef struct {
131         volatile ushort mutex:1;
132         volatile ushort exclusive:1;
133         volatile ushort pending:1;
134         volatile ushort share:13;
135 } BtSpinLatch;
136
137 //      The first part of an index page.
138 //      It is immediately followed
139 //      by the BtSlot array of keys.
140
141 typedef struct Page {
142         BtSpinLatch readwr[1];          // read/write lock
143         BtSpinLatch access[1];          // access intent lock
144         BtSpinLatch parent[1];          // parent SMO lock
145         uint cnt;                                       // count of keys in page
146         uint act;                                       // count of active keys
147         uint min;                                       // next key offset
148         uint foster;                            // count of foster children
149         unsigned char bits;                     // page size in bits
150         unsigned char lvl:6;            // level of page
151         unsigned char kill:1;           // page is being deleted
152         unsigned char dirty:1;          // page needs to be cleaned
153         unsigned char right[BtId];      // page number to right
154 } *BtPage;
155
156 //      The memory mapping pool table buffer manager entry
157
158 typedef struct {
159         unsigned long long int lru;     // number of times accessed
160         uid  basepage;                          // mapped base page number
161         char *map;                                      // mapped memory pointer
162         ushort pin;                                     // mapped page pin counter
163         ushort slot;                            // slot index in this array
164         void *hashprev;                         // previous pool entry for the same hash idx
165         void *hashnext;                         // next pool entry for the same hash idx
166 #ifndef unix
167         HANDLE hmap;                            // Windows memory mapping handle
168 #endif
169 } BtPool;
170
171 //      The object structure for Btree access
172
173 typedef struct {
174         uint page_size;                         // page size    
175         uint page_bits;                         // page size in bits    
176         uint seg_bits;                          // seg size in pages in bits
177         uint mode;                                      // read-write mode
178 #ifdef unix
179         int idx;
180         char *pooladvise;                       // bit maps for pool page advisements
181 #else
182         HANDLE idx;
183 #endif
184         ushort poolcnt;                         // highest page pool node in use
185         ushort poolmax;                         // highest page pool node allocated
186         ushort poolmask;                        // total size of pages in mmap segment - 1
187         ushort hashsize;                        // size of Hash Table for pool entries
188         ushort evicted;                         // last evicted hash table slot
189         ushort *hash;                           // hash table of pool entries
190         BtPool *pool;                           // memory pool page segments
191         BtSpinLatch *latch;                     // latches for pool hash slots
192 #ifndef unix
193         HANDLE halloc, hlatch;          // allocation and latch table handles
194 #endif
195 } BtMgr;
196
197 typedef struct {
198         BtMgr *mgr;                     // buffer manager for thread
199         BtPage temp;            // temporary frame buffer (memory mapped/file IO)
200         BtPage alloc;           // frame buffer for alloc page ( page 0 )
201         BtPage cursor;          // cached frame for start/next (never mapped)
202         BtPage frame;           // spare frame for the page split (never mapped)
203         BtPage zero;            // page frame for zeroes at end of file
204         BtPage page;            // current page
205         uid page_no;            // current page number  
206         uid cursor_page;        // current cursor page number   
207         unsigned char *mem;     // frame, cursor, page memory buffer
208         int err;                        // last error
209 } BtDb;
210
211 typedef enum {
212         BTERR_ok = 0,
213         BTERR_struct,
214         BTERR_ovflw,
215         BTERR_lock,
216         BTERR_map,
217         BTERR_wrt,
218         BTERR_hash,
219         BTERR_latch
220 } BTERR;
221
222 // B-Tree functions
223 extern void bt_close (BtDb *bt);
224 extern BtDb *bt_open (BtMgr *mgr);
225 extern BTERR  bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod);
226 extern BTERR  bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl);
227 extern uid bt_findkey    (BtDb *bt, unsigned char *key, uint len);
228 extern uint bt_startkey  (BtDb *bt, unsigned char *key, uint len);
229 extern uint bt_nextkey   (BtDb *bt, uint slot);
230
231 //      manager functions
232 extern BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolsize, uint segsize, uint hashsize);
233 void bt_mgrclose (BtMgr *mgr);
234
235 //  Helper functions to return cursor slot values
236
237 extern BtKey bt_key (BtDb *bt, uint slot);
238 extern uid bt_uid (BtDb *bt, uint slot);
239 extern uint bt_tod (BtDb *bt, uint slot);
240
241 //  BTree page number constants
242 #define ALLOC_page              0       // allocation of new pages
243 #define ROOT_page               1       // root of the btree
244 #define LEAF_page               2       // first page of leaves
245
246 //      Number of levels to create in a new BTree
247
248 #define MIN_lvl                 2
249
250 //  The page is allocated from low and hi ends.
251 //  The key offsets and row-id's are allocated
252 //  from the bottom, while the text of the key
253 //  is allocated from the top.  When the two
254 //  areas meet, the page is split into two.
255
256 //  A key consists of a length byte, two bytes of
257 //  index number (0 - 65534), and up to 253 bytes
258 //  of key value.  Duplicate keys are discarded.
259 //  Associated with each key is a 48 bit row-id.
260
261 //  The b-tree root is always located at page 1.
262 //      The first leaf page of level zero is always
263 //      located on page 2.
264
265 //      When to root page fills, it is split in two and
266 //      the tree height is raised by a new root at page
267 //      one with two keys.
268
269 //      Deleted keys are marked with a dead bit until
270 //      page cleanup The fence key for a node is always
271 //      present, even after deletion and cleanup.
272
273 //  Groups of pages called segments from the btree are
274 //  cached with memory mapping. A hash table is used to keep
275 //  track of the cached segments.  This behaviour is controlled
276 //  by the cache block size parameter to bt_open.
277
278 //  To achieve maximum concurrency one page is locked at a time
279 //  as the tree is traversed to find leaf key in question.
280
281 //      An adoption traversal leaves the parent node locked as the
282 //      tree is traversed to the level in quesiton.
283
284 //  Page 0 is dedicated to lock for new page extensions,
285 //      and chains empty pages together for reuse.
286
287 //      Empty pages are chained together through the ALLOC page and reused.
288
289 //      Access macros to address slot and key values from the page
290
291 #define slotptr(page, slot) (((BtSlot *)(page+1)) + (slot-1))
292 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
293
294 void bt_putid(unsigned char *dest, uid id)
295 {
296 int i = BtId;
297
298         while( i-- )
299                 dest[i] = (unsigned char)id, id >>= 8;
300 }
301
302 uid bt_getid(unsigned char *src)
303 {
304 uid id = 0;
305 int i;
306
307         for( i = 0; i < BtId; i++ )
308                 id <<= 8, id |= *src++; 
309
310         return id;
311 }
312
313 //      wait until write lock mode is clear
314 //      and add 1 to the share count
315
316 void bt_spinreadlock(BtSpinLatch *latch)
317 {
318 ushort prev;
319
320   do {
321 #ifdef unix
322         do prev = __sync_fetch_and_or((ushort *)latch, Mutex);
323         while( prev & Mutex );
324 #else
325         do prev = _InterlockedOr16((ushort *)latch, Mutex);
326         while( prev & Mutex );
327 #endif
328
329         //  see if exclusive request is pending, or granted
330
331         if( prev = !(latch->exclusive | latch->pending) )
332                 latch->share++;
333
334         latch->mutex = 0;
335
336         if( prev )
337                 return;
338 #ifdef  unix
339   } while( sched_yield(), 1 );
340 #else
341   } while( SwitchToThread(), 1 );
342 #endif
343 }
344
345 //      wait for other read and write latches to relinquish
346
347 void bt_spinwritelock(BtSpinLatch *latch)
348 {
349 ushort prev;
350
351   do {
352 #ifdef  unix
353         do prev = __sync_fetch_and_or((ushort *)latch, (Pending | Mutex));
354         while( prev & Mutex );
355 #else
356         do prev = _InterlockedOr16((ushort *)latch, (Pending | Mutex));
357         while( prev & Mutex );
358 #endif
359         if( prev = !(latch->share | latch->exclusive) )
360                 latch->exclusive = 1, latch->pending = 0;
361
362         latch->mutex = 0;
363
364         if( prev )
365                 return;
366 #ifdef  unix
367         sched_yield();
368 #else
369         SwitchToThread();
370 #endif
371   } while( 1 );
372 }
373
374 //      try to obtain write lock
375
376 //      return 1 if obtained,
377 //              0 otherwise
378
379 int bt_spinwritetry(BtSpinLatch *latch)
380 {
381 ushort prev;
382
383 #ifdef unix
384         do prev = __sync_fetch_and_or((ushort *)latch, Mutex);
385         while( prev & Mutex );
386 #else
387         do prev = _InterlockedOr16((ushort *)latch, Mutex);
388         while( prev & Mutex );
389 #endif
390         //      take write access if all bits are clear
391
392         if( !prev )
393                 latch->exclusive = 1;
394
395         latch->mutex = 0;
396         return !prev;
397 }
398
399 //      clear write mode
400
401 void bt_spinreleasewrite(BtSpinLatch *latch)
402 {
403 ushort prev;
404
405 #ifdef unix
406         do prev = __sync_fetch_and_or((ushort *)latch, Mutex);
407         while( prev & Mutex );
408 #else
409         do prev = _InterlockedOr16((ushort *)latch, Mutex);
410         while( prev & Mutex );
411 #endif
412
413         latch->exclusive = 0;
414         latch->mutex = 0;
415 }
416
417 //      decrement reader count
418
419 void bt_spinreleaseread(BtSpinLatch *latch)
420 {
421 ushort prev;
422
423 #ifdef unix
424         do prev = __sync_fetch_and_or((ushort *)latch, Mutex);
425         while( prev & Mutex );
426 #else
427         do prev = _InterlockedOr16((ushort *)latch, Mutex);
428         while( prev & Mutex );
429 #endif
430
431         latch->share--;
432         latch->mutex = 0;
433 }
434
435 void bt_mgrclose (BtMgr *mgr)
436 {
437 BtPool *pool;
438 uint slot;
439
440         // release mapped pages
441         //      note that slot zero is never used
442
443         for( slot = 1; slot < mgr->poolmax; slot++ ) {
444                 pool = mgr->pool + slot;
445                 if( pool->slot )
446 #ifdef unix
447                         munmap (pool->map, (mgr->poolmask+1) << mgr->page_bits);
448 #else
449                 {
450                         FlushViewOfFile(pool->map, 0);
451                         UnmapViewOfFile(pool->map);
452                         CloseHandle(pool->hmap);
453                 }
454 #endif
455         }
456
457 #ifdef unix
458         close (mgr->idx);
459         free (mgr->pool);
460         free (mgr->hash);
461         free (mgr->pooladvise);
462         free (mgr);
463 #else
464         FlushFileBuffers(mgr->idx);
465         CloseHandle(mgr->idx);
466         GlobalFree (mgr->pool);
467         GlobalFree (mgr->hash);
468         GlobalFree (mgr);
469 #endif
470 }
471
472 //      close and release memory
473
474 void bt_close (BtDb *bt)
475 {
476 #ifdef unix
477         if ( bt->mem )
478                 free (bt->mem);
479 #else
480         if ( bt->mem)
481                 VirtualFree (bt->mem, 0, MEM_RELEASE);
482 #endif
483         free (bt);
484 }
485
486 //  open/create new btree buffer manager
487
488 //      call with file_name, BT_openmode, bits in page size (e.g. 16),
489 //              size of mapped page pool (e.g. 8192)
490
491 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
492 {
493 uint lvl, attr, cacheblk, last, slot, idx;
494 BtPage alloc;
495 int lockmode;
496 off64_t size;
497 uint amt[1];
498 BtMgr* mgr;
499 BtKey key;
500
501 #ifndef unix
502 SYSTEM_INFO sysinfo[1];
503 #endif
504
505         // determine sanity of page size and buffer pool
506
507         if( bits > BT_maxbits )
508                 bits = BT_maxbits;
509         else if( bits < BT_minbits )
510                 bits = BT_minbits;
511
512         if( !poolmax )
513                 return NULL;    // must have buffer pool
514
515 #ifdef unix
516         mgr = calloc (1, sizeof(BtMgr));
517
518         switch (mode & 0x7fff)
519         {
520         case BT_rw:
521                 mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
522                 lockmode = 1;
523                 break;
524
525         case BT_ro:
526         default:
527                 mgr->idx = open ((char*)name, O_RDONLY);
528                 lockmode = 0;
529                 break;
530         }
531         if( mgr->idx == -1 )
532                 return free(mgr), NULL;
533         
534         cacheblk = 4096;        // minimum mmap segment size for unix
535
536 #else
537         mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
538         attr = FILE_ATTRIBUTE_NORMAL;
539         switch (mode & 0x7fff)
540         {
541         case BT_rw:
542                 mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
543                 lockmode = 1;
544                 break;
545
546         case BT_ro:
547         default:
548                 mgr->idx = CreateFile(name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, attr, NULL);
549                 lockmode = 0;
550                 break;
551         }
552         if( mgr->idx == INVALID_HANDLE_VALUE )
553                 return GlobalFree(mgr), NULL;
554
555         // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
556         GetSystemInfo(sysinfo);
557         cacheblk = sysinfo->dwAllocationGranularity;
558 #endif
559
560 #ifdef unix
561         alloc = malloc (BT_maxpage);
562         *amt = 0;
563
564         // read minimum page size to get root info
565
566         if( size = lseek (mgr->idx, 0L, 2) ) {
567                 if( pread(mgr->idx, alloc, BT_minpage, 0) == BT_minpage )
568                         bits = alloc->bits;
569                 else
570                         return free(mgr), free(alloc), NULL;
571         } else if( mode == BT_ro )
572                 return bt_mgrclose (mgr), NULL;
573 #else
574         alloc = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
575         size = GetFileSize(mgr->idx, amt);
576
577         if( size || *amt ) {
578                 if( !ReadFile(mgr->idx, (char *)alloc, BT_minpage, amt, NULL) )
579                         return bt_mgrclose (mgr), NULL;
580                 bits = alloc->bits;
581         } else if( mode == BT_ro )
582                 return bt_mgrclose (mgr), NULL;
583 #endif
584
585         mgr->page_size = 1 << bits;
586         mgr->page_bits = bits;
587
588         mgr->poolmax = poolmax;
589         mgr->mode = mode;
590
591         if( cacheblk < mgr->page_size )
592                 cacheblk = mgr->page_size;
593
594         //  mask for partial memmaps
595
596         mgr->poolmask = (cacheblk >> bits) - 1;
597
598         //      see if requested size of pages per memmap is greater
599
600         if( (1 << segsize) > mgr->poolmask )
601                 mgr->poolmask = (1 << segsize) - 1;
602
603         mgr->seg_bits = 0;
604
605         while( (1 << mgr->seg_bits) <= mgr->poolmask )
606                 mgr->seg_bits++;
607
608         mgr->hashsize = hashsize;
609
610 #ifdef unix
611         mgr->pool = calloc (poolmax, sizeof(BtPool));
612         mgr->hash = calloc (hashsize, sizeof(ushort));
613         mgr->latch = calloc (hashsize, sizeof(BtSpinLatch));
614         mgr->pooladvise = calloc (poolmax, (mgr->poolmask + 8) / 8);
615 #else
616         mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * (sizeof(BtPool)));
617         mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
618         mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtSpinLatch));
619 #endif
620         if( size || *amt )
621                 goto mgrxit;
622
623         // initializes an empty b-tree with root page and page of leaves
624
625         memset (alloc, 0, 1 << bits);
626         bt_putid(alloc->right, MIN_lvl+1);
627         alloc->bits = mgr->page_bits;
628
629 #ifdef unix
630         if( write (mgr->idx, alloc, mgr->page_size) < mgr->page_size )
631                 return bt_mgrclose (mgr), NULL;
632 #else
633         if( !WriteFile (mgr->idx, (char *)alloc, mgr->page_size, amt, NULL) )
634                 return bt_mgrclose (mgr), NULL;
635
636         if( *amt < mgr->page_size )
637                 return bt_mgrclose (mgr), NULL;
638 #endif
639
640         memset (alloc, 0, 1 << bits);
641         alloc->bits = mgr->page_bits;
642
643         for( lvl=MIN_lvl; lvl--; ) {
644                 slotptr(alloc, 1)->off = mgr->page_size - 3;
645                 bt_putid(slotptr(alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0);           // next(lower) page number
646                 key = keyptr(alloc, 1);
647                 key->len = 2;                   // create stopper key
648                 key->key[0] = 0xff;
649                 key->key[1] = 0xff;
650                 alloc->min = mgr->page_size - 3;
651                 alloc->lvl = lvl;
652                 alloc->cnt = 1;
653                 alloc->act = 1;
654 #ifdef unix
655                 if( write (mgr->idx, alloc, mgr->page_size) < mgr->page_size )
656                         return bt_mgrclose (mgr), NULL;
657 #else
658                 if( !WriteFile (mgr->idx, (char *)alloc, mgr->page_size, amt, NULL) )
659                         return bt_mgrclose (mgr), NULL;
660
661                 if( *amt < mgr->page_size )
662                         return bt_mgrclose (mgr), NULL;
663 #endif
664         }
665
666         // create empty page area by writing last page of first
667         // segment area (other pages are zeroed by O/S)
668
669         if( mgr->poolmask ) {
670                 memset(alloc, 0, mgr->page_size);
671                 last = mgr->poolmask;
672
673                 while( last < MIN_lvl + 1 )
674                         last += mgr->poolmask + 1;
675
676 #ifdef unix
677                 pwrite(mgr->idx, alloc, mgr->page_size, last << mgr->page_bits);
678 #else
679                 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
680                 if( !WriteFile (mgr->idx, (char *)alloc, mgr->page_size, amt, NULL) )
681                         return bt_mgrclose (mgr), NULL;
682                 if( *amt < mgr->page_size )
683                         return bt_mgrclose (mgr), NULL;
684 #endif
685         }
686
687 mgrxit:
688 #ifdef unix
689         free (alloc);
690 #else
691         VirtualFree (alloc, 0, MEM_RELEASE);
692 #endif
693         return mgr;
694 }
695
696 //      open BTree access method
697 //      based on buffer manager
698
699 BtDb *bt_open (BtMgr *mgr)
700 {
701 BtDb *bt = malloc (sizeof(*bt));
702
703         memset (bt, 0, sizeof(*bt));
704         bt->mgr = mgr;
705 #ifdef unix
706         bt->mem = malloc (3 *mgr->page_size);
707 #else
708         bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
709 #endif
710         bt->frame = (BtPage)bt->mem;
711         bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
712         bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
713         return bt;
714 }
715
716 //  compare two keys, returning > 0, = 0, or < 0
717 //  as the comparison value
718
719 int keycmp (BtKey key1, unsigned char *key2, uint len2)
720 {
721 uint len1 = key1->len;
722 int ans;
723
724         if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
725                 return ans;
726
727         if( len1 > len2 )
728                 return 1;
729         if( len1 < len2 )
730                 return -1;
731
732         return 0;
733 }
734
735 //      Buffer Pool mgr
736
737 // find segment in pool
738 // must be called with hashslot idx locked
739 //      return NULL if not there
740 //      otherwise return node
741
742 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
743 {
744 BtPool *pool;
745 uint slot;
746
747         // compute start of hash chain in pool
748
749         if( slot = bt->mgr->hash[idx] ) 
750                 pool = bt->mgr->pool + slot;
751         else
752                 return NULL;
753
754         page_no &= ~bt->mgr->poolmask;
755
756         while( pool->basepage != page_no )
757           if( pool = pool->hashnext )
758                 continue;
759           else
760                 return NULL;
761
762         return pool;
763 }
764
765 // add segment to hash table
766
767 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
768 {
769 BtPool *node;
770 uint slot;
771
772         pool->hashprev = pool->hashnext = NULL;
773         pool->basepage = page_no & ~bt->mgr->poolmask;
774         pool->lru = 1;
775
776         if( slot = bt->mgr->hash[idx] ) {
777                 node = bt->mgr->pool + slot;
778                 pool->hashnext = node;
779                 node->hashprev = pool;
780         }
781
782         bt->mgr->hash[idx] = pool->slot;
783 }
784
785 //      find best segment to evict from buffer pool
786
787 BtPool *bt_findlru (BtDb *bt, uint hashslot)
788 {
789 unsigned long long int target = ~0LL;
790 BtPool *pool = NULL, *node;
791
792         if( !hashslot )
793                 return NULL;
794
795         node = bt->mgr->pool + hashslot;
796
797         //      scan pool entries under hash table slot
798
799         do {
800           if( node->pin )
801                 continue;
802           if( node->lru > target )
803                 continue;
804           target = node->lru;
805           pool = node;
806         } while( node = node->hashnext );
807
808         return pool;
809 }
810
811 //  map new buffer pool segment to virtual memory
812
813 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
814 {
815 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
816 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
817 int flag;
818
819 #ifdef unix
820         flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
821         pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED, bt->mgr->idx, off);
822         if( pool->map == MAP_FAILED )
823                 return bt->err = BTERR_map;
824         // clear out madvise issued bits
825         memset (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8) / 8), 0, (bt->mgr->poolmask + 8)/8);
826 #else
827         flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
828         pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
829         if( !pool->hmap )
830                 return bt->err = BTERR_map;
831
832         flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
833         pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
834         if( !pool->map )
835                 return bt->err = BTERR_map;
836 #endif
837         return bt->err = 0;
838 }
839
840 //      find or place requested page in segment-pool
841 //      return pool table entry, incrementing pin
842
843 BtPool *bt_pinpage(BtDb *bt, uid page_no)
844 {
845 BtPool *pool, *node, *next;
846 uint slot, idx, victim;
847
848         //      lock hash table chain
849
850         idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
851         bt_spinreadlock (&bt->mgr->latch[idx]);
852
853         //      look up in hash table
854
855         if( pool = bt_findpool(bt, page_no, idx) ) {
856 #ifdef unix
857                 __sync_fetch_and_add(&pool->pin, 1);
858 #else
859                 _InterlockedIncrement16 (&pool->pin);
860 #endif
861                 bt_spinreleaseread (&bt->mgr->latch[idx]);
862                 pool->lru++;
863                 return pool;
864         }
865
866         //      upgrade to write lock
867
868         bt_spinreleaseread (&bt->mgr->latch[idx]);
869         bt_spinwritelock (&bt->mgr->latch[idx]);
870
871         // try to find page in pool with write lock
872
873         if( pool = bt_findpool(bt, page_no, idx) ) {
874 #ifdef unix
875                 __sync_fetch_and_add(&pool->pin, 1);
876 #else
877                 _InterlockedIncrement16 (&pool->pin);
878 #endif
879                 bt_spinreleasewrite (&bt->mgr->latch[idx]);
880                 pool->lru++;
881                 return pool;
882         }
883
884         // allocate a new pool node
885         // and add to hash table
886
887 #ifdef unix
888         slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
889 #else
890         slot = _InterlockedIncrement16 (&bt->mgr->poolcnt) - 1;
891 #endif
892
893         if( ++slot < bt->mgr->poolmax ) {
894                 pool = bt->mgr->pool + slot;
895                 pool->slot = slot;
896
897                 if( bt_mapsegment(bt, pool, page_no) )
898                         return NULL;
899
900                 bt_linkhash(bt, pool, page_no, idx);
901 #ifdef unix
902                 __sync_fetch_and_add(&pool->pin, 1);
903 #else
904                 _InterlockedIncrement16 (&pool->pin);
905 #endif
906                 bt_spinreleasewrite (&bt->mgr->latch[idx]);
907                 return pool;
908         }
909
910         // pool table is full
911         //      find best pool entry to evict
912
913 #ifdef unix
914         __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
915 #else
916         _InterlockedDecrement16 (&bt->mgr->poolcnt);
917 #endif
918
919         while( 1 ) {
920 #ifdef unix
921                 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
922 #else
923                 victim = _InterlockedIncrement16 (&bt->mgr->evicted) - 1;
924 #endif
925                 victim %= bt->mgr->hashsize;
926
927                 // try to get write lock
928                 //      skip entry if not obtained
929
930                 if( !bt_spinwritetry (&bt->mgr->latch[victim]) )
931                         continue;
932
933                 //  if cache entry is empty
934                 //      or no slots are unpinned
935                 //      skip this entry
936
937                 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
938                         bt_spinreleasewrite (&bt->mgr->latch[victim]);
939                         continue;
940                 }
941
942                 // unlink victim pool node from hash table
943
944                 if( node = pool->hashprev )
945                         node->hashnext = pool->hashnext;
946                 else if( node = pool->hashnext )
947                         bt->mgr->hash[victim] = node->slot;
948                 else
949                         bt->mgr->hash[victim] = 0;
950
951                 if( node = pool->hashnext )
952                         node->hashprev = pool->hashprev;
953
954                 bt_spinreleasewrite (&bt->mgr->latch[victim]);
955
956                 //      remove old file mapping
957 #ifdef unix
958                 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
959 #else
960                 FlushViewOfFile(pool->map, 0);
961                 UnmapViewOfFile(pool->map);
962                 CloseHandle(pool->hmap);
963 #endif
964                 pool->map = NULL;
965
966                 //  create new pool mapping
967                 //  and link into hash table
968
969                 if( bt_mapsegment(bt, pool, page_no) )
970                         return NULL;
971
972                 bt_linkhash(bt, pool, page_no, idx);
973 #ifdef unix
974                 __sync_fetch_and_add(&pool->pin, 1);
975 #else
976                 _InterlockedIncrement16 (&pool->pin);
977 #endif
978                 bt_spinreleasewrite (&bt->mgr->latch[idx]);
979                 return pool;
980         }
981 }
982
983 // place write, read, or parent lock on requested page_no.
984 //      pin to buffer pool and return page pointer
985
986 BTERR bt_lockpage(BtDb *bt, uid page_no, BtLock mode, BtPage *pageptr)
987 {
988 BtPool *pool;
989 uint subpage;
990 BtPage page;
991
992         //      find/create maping in pool table
993         //        and pin our pool slot
994
995         if( pool = bt_pinpage(bt, page_no) )
996                 subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
997         else
998                 return bt->err;
999
1000         page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1001
1002 #ifdef unix
1003         {
1004         uint idx = subpage / 8;
1005         uint bit = subpage % 8;
1006
1007                 if( ~((bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] >> bit) & 1 ) {
1008                   madvise (page, bt->mgr->page_size, MADV_WILLNEED);
1009                   (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] |= 1 << bit;
1010                 }
1011         }
1012 #endif
1013
1014         switch( mode ) {
1015         case BtLockRead:
1016                 bt_spinreadlock (page->readwr);
1017                 break;
1018         case BtLockWrite:
1019                 bt_spinwritelock (page->readwr);
1020                 break;
1021         case BtLockAccess:
1022                 bt_spinreadlock (page->access);
1023                 break;
1024         case BtLockDelete:
1025                 bt_spinwritelock (page->access);
1026                 break;
1027         case BtLockParent:
1028                 bt_spinwritelock (page->parent);
1029                 break;
1030         default:
1031                 return bt->err = BTERR_lock;
1032         }
1033
1034         if( pageptr )
1035                 *pageptr = page;
1036
1037         return bt->err = 0;
1038 }
1039
1040 // remove write, read, or parent lock on requested page_no.
1041
1042 BTERR bt_unlockpage(BtDb *bt, uid page_no, BtLock mode)
1043 {
1044 BtPool *pool;
1045 uint subpage;
1046 BtPage page;
1047 uint idx;
1048
1049         //      since page is pinned
1050         //      it should still be in the buffer pool
1051         //      and is in no danger of being a victim for reuse
1052
1053         idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1054         bt_spinreadlock (&bt->mgr->latch[idx]);
1055
1056         if( !(pool = bt_findpool(bt, page_no, idx)) )
1057                 return bt->err = BTERR_hash;
1058
1059         bt_spinreleaseread (&bt->mgr->latch[idx]);
1060
1061         subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1062         page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1063
1064         switch( mode ) {
1065         case BtLockRead:
1066                 bt_spinreleaseread (page->readwr);
1067                 break;
1068         case BtLockWrite:
1069                 bt_spinreleasewrite (page->readwr);
1070                 break;
1071         case BtLockAccess:
1072                 bt_spinreleaseread (page->access);
1073                 break;
1074         case BtLockDelete:
1075                 bt_spinreleasewrite (page->access);
1076                 break;
1077         case BtLockParent:
1078                 bt_spinreleasewrite (page->parent);
1079                 break;
1080         default:
1081                 return bt->err = BTERR_lock;
1082         }
1083
1084 #ifdef  unix
1085         __sync_fetch_and_add(&pool->pin, -1);
1086 #else
1087         _InterlockedDecrement16 (&pool->pin);
1088 #endif
1089         return bt->err = 0;
1090 }
1091
1092 //      deallocate a deleted page
1093 //      place on free chain out of allocator page
1094 //  fence key must already be removed from parent
1095
1096 BTERR bt_freepage(BtDb *bt, uid page_no)
1097 {
1098         //  obtain delete lock on deleted page
1099
1100         if( bt_lockpage(bt, page_no, BtLockDelete, NULL) )
1101                 return bt->err;
1102
1103         //  obtain write lock on deleted page
1104
1105         if( bt_lockpage(bt, page_no, BtLockWrite, &bt->temp) )
1106                 return bt->err;
1107
1108         //      lock allocation page
1109
1110         if ( bt_lockpage(bt, ALLOC_page, BtLockWrite, &bt->alloc) )
1111                 return bt->err;
1112
1113         //      store free chain in allocation page second right
1114         bt_putid(bt->temp->right, bt_getid(bt->alloc[1].right));
1115         bt_putid(bt->alloc[1].right, page_no);
1116
1117         // unlock allocation page
1118
1119         if( bt_unlockpage(bt, ALLOC_page, BtLockWrite) )
1120                 return bt->err;
1121
1122         //  remove write lock on deleted node
1123
1124         if( bt_unlockpage(bt, page_no, BtLockWrite) )
1125                 return bt->err;
1126
1127         //  remove delete lock on deleted node
1128
1129         if( bt_unlockpage(bt, page_no, BtLockDelete) )
1130                 return bt->err;
1131
1132         return 0;
1133 }
1134
1135 //      allocate a new page and write page into it
1136
1137 uid bt_newpage(BtDb *bt, BtPage page)
1138 {
1139 uid new_page;
1140 BtPage pmap;
1141 int reuse;
1142
1143         //      lock allocation page
1144
1145         if ( bt_lockpage(bt, ALLOC_page, BtLockWrite, &bt->alloc) )
1146                 return 0;
1147
1148         // use empty chain first
1149         // else allocate empty page
1150
1151         if( new_page = bt_getid(bt->alloc[1].right) ) {
1152                 if( bt_lockpage (bt, new_page, BtLockWrite, &bt->temp) )
1153                         return 0;
1154                 bt_putid(bt->alloc[1].right, bt_getid(bt->temp->right));
1155                 if( bt_unlockpage (bt, new_page, BtLockWrite) )
1156                         return 0;
1157                 reuse = 1;
1158         } else {
1159                 new_page = bt_getid(bt->alloc->right);
1160                 bt_putid(bt->alloc->right, new_page+1);
1161                 reuse = 0;
1162         }
1163 #ifdef unix
1164         memset(bt->zero, 0, 3 * sizeof(BtSpinLatch)); // clear locks
1165         memcpy((char *)bt->zero + 3 * sizeof(BtSpinLatch), (char *)page + 3 * sizeof(BtSpinLatch), bt->mgr->page_size - 3 * sizeof(BtSpinLatch));
1166         if ( pwrite(bt->mgr->idx, bt->zero, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1167                 return bt->err = BTERR_wrt, 0;
1168
1169         // if writing first page of pool block, zero last page in the block
1170
1171         if ( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1172         {
1173                 // use zero buffer to write zeros
1174                 memset(bt->zero, 0, bt->mgr->page_size);
1175                 if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1176                         return bt->err = BTERR_wrt, 0;
1177         }
1178 #else
1179         //      bring new page into pool and copy page.
1180         //      this will extend the file into the new pages.
1181
1182         if( bt_lockpage(bt, new_page, BtLockWrite, &pmap) )
1183                 return 0;
1184
1185         memcpy(pmap, page, bt->mgr->page_size);
1186
1187         if( bt_unlockpage (bt, new_page, BtLockWrite) )
1188                 return 0;
1189 #endif
1190         // unlock allocation latch and return new page no
1191
1192         if ( bt_unlockpage(bt, ALLOC_page, BtLockWrite) )
1193                 return 0;
1194
1195         return new_page;
1196 }
1197
1198 //  find slot in page for given key at a given level
1199
1200 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1201 {
1202 uint diff, higher = bt->page->cnt, low = 1, slot;
1203
1204         //      low is the lowest candidate, higher is already
1205         //      tested as .ge. the given key, loop ends when they meet
1206
1207         while( diff = higher - low ) {
1208                 slot = low + ( diff >> 1 );
1209                 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1210                         low = slot + 1;
1211                 else
1212                         higher = slot;
1213         }
1214
1215         return higher;
1216 }
1217
1218 //  find and load page at given level for given key
1219 //      leave page rd or wr locked as requested
1220
1221 int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, uint lock)
1222 {
1223 uid page_no = ROOT_page, prevpage = 0;
1224 uint drill = 0xff, slot;
1225 uint mode, prevmode;
1226
1227   //  start at root of btree and drill down
1228
1229   do {
1230         // determine lock mode of drill level
1231         mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead; 
1232
1233         bt->page_no = page_no;
1234
1235         // obtain access lock using lock chaining with Access mode
1236
1237         if( page_no > ROOT_page )
1238           if( bt_lockpage(bt, page_no, BtLockAccess, NULL) )
1239                 return 0;                                                                       
1240
1241         //  now unlock our (possibly foster) parent
1242
1243         if( prevpage )
1244           if( bt_unlockpage(bt, prevpage, prevmode) )
1245                 return 0;
1246           else
1247                 prevpage = 0;
1248
1249         // obtain read lock using lock chaining
1250         // and pin page contents
1251
1252         if( bt_lockpage(bt, page_no, mode, &bt->page) )
1253                 return 0;                                                                       
1254
1255         if( page_no > ROOT_page )
1256           if( bt_unlockpage(bt, page_no, BtLockAccess) )
1257                 return 0;                                                                       
1258
1259         // re-read and re-lock root after determining actual level of root
1260
1261         if( bt->page_no == ROOT_page )
1262           if( bt->page->lvl != drill) {
1263                 drill = bt->page->lvl;
1264
1265             if( lock == BtLockWrite && drill == lvl )
1266                   if( bt_unlockpage(bt, page_no, mode) )
1267                         return 0;
1268                   else
1269                         continue;
1270           }
1271
1272         prevpage = bt->page_no;
1273         prevmode = mode;
1274
1275         //      if page is being deleted,
1276         //      move back to preceeding page
1277
1278         if( bt->page->kill ) {
1279                 page_no = bt_getid (bt->page->right);
1280                 continue;
1281         }
1282
1283         //  find key on page at this level
1284         //  and descend to requested level
1285
1286         slot = bt_findslot (bt, key, len);
1287
1288         //      is this slot a foster child?
1289
1290         if( slot <= bt->page->cnt - bt->page->foster )
1291           if( drill == lvl )
1292                 return slot;
1293
1294         while( slotptr(bt->page, slot)->dead )
1295           if( slot++ < bt->page->cnt )
1296                 continue;
1297           else
1298                 goto slideright;
1299
1300         if( slot <= bt->page->cnt - bt->page->foster )
1301                 drill--;
1302
1303         //  continue down / right using overlapping locks
1304         //  to protect pages being killed or split.
1305
1306         page_no = bt_getid(slotptr(bt->page, slot)->id);
1307         continue;
1308
1309 slideright:
1310         page_no = bt_getid(bt->page->right);
1311
1312   } while( page_no );
1313
1314   // return error on end of chain
1315
1316   bt->err = BTERR_struct;
1317   return 0;     // return error
1318 }
1319
1320 //  find and delete key on page by marking delete flag bit
1321 //  when page becomes empty, delete it from the btree
1322
1323 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl)
1324 {
1325 unsigned char leftkey[256], rightkey[256];
1326 uid page_no, right;
1327 uint slot, tod;
1328 BtKey ptr;
1329
1330         if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1331                 ptr = keyptr(bt->page, slot);
1332         else
1333                 return bt->err;
1334
1335         // if key is found delete it, otherwise ignore request
1336
1337         if( !keycmp (ptr, key, len) )
1338                 if( slotptr(bt->page, slot)->dead == 0 ) {
1339                         slotptr(bt->page,slot)->dead = 1;
1340                         if( slot < bt->page->cnt )
1341                                 bt->page->dirty = 1;
1342                         bt->page->act--;
1343                 }
1344
1345         // return if page is not empty, or it has no right sibling
1346
1347         right = bt_getid(bt->page->right);
1348         page_no = bt->page_no;
1349
1350         if( !right || bt->page->act )
1351                 return bt_unlockpage(bt, page_no, BtLockWrite);
1352
1353         // obtain Parent lock over write lock
1354
1355         if( bt_lockpage(bt, page_no, BtLockParent, NULL) )
1356                 return bt->err;
1357
1358         // cache copy of key to delete
1359
1360         ptr = keyptr(bt->page, bt->page->cnt);
1361         memcpy(leftkey, ptr, ptr->len + 1);
1362
1363         // lock and map right page
1364
1365         if( bt_lockpage(bt, right, BtLockWrite, &bt->temp) )
1366                 return bt->err;
1367
1368         // pull contents of next page into current empty page 
1369         memcpy (bt->page, bt->temp, bt->mgr->page_size);
1370
1371         //      cache copy of key to update
1372         ptr = keyptr(bt->temp, bt->temp->cnt);
1373         memcpy(rightkey, ptr, ptr->len + 1);
1374
1375         //  Mark right page as deleted and point it to left page
1376         //      until we can post updates at higher level.
1377
1378         bt_putid(bt->temp->right, page_no);
1379         bt->temp->kill = 1;
1380         bt->temp->cnt = 0;
1381
1382         if( bt_unlockpage(bt, right, BtLockWrite) )
1383                 return bt->err;
1384         if( bt_unlockpage(bt, page_no, BtLockWrite) )
1385                 return bt->err;
1386
1387         //  delete old lower key to consolidated node
1388
1389         if( bt_deletekey (bt, leftkey + 1, *leftkey, lvl + 1) )
1390                 return bt->err;
1391
1392         //  redirect higher key directly to consolidated node
1393
1394         if( slot = bt_loadpage (bt, rightkey+1, *rightkey, lvl+1, BtLockWrite) )
1395                 ptr = keyptr(bt->page, slot);
1396         else
1397                 return bt->err;
1398
1399         // since key already exists, update id
1400
1401         if( keycmp (ptr, rightkey+1, *rightkey) )
1402                 return bt->err = BTERR_struct;
1403
1404         slotptr(bt->page, slot)->dead = 0;
1405         bt_putid(slotptr(bt->page,slot)->id, page_no);
1406
1407         if( bt_unlockpage(bt, bt->page_no, BtLockWrite) )
1408                 return bt->err;
1409
1410         //      obtain write lock and
1411         //      add right block to free chain
1412
1413         if( bt_freepage (bt, right) )
1414                 return bt->err;
1415
1416         //      remove ParentModify lock
1417
1418         if( bt_unlockpage(bt, page_no, BtLockParent) )
1419                 return bt->err;
1420         
1421         return 0;
1422 }
1423
1424 //      find key in leaf level and return row-id
1425
1426 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1427 {
1428 uint  slot;
1429 BtKey ptr;
1430 uid id;
1431
1432         if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1433                 ptr = keyptr(bt->page, slot);
1434         else
1435                 return 0;
1436
1437         // if key exists, return row-id
1438         //      otherwise return 0
1439
1440         if( ptr->len == len && !memcmp (ptr->key, key, len) )
1441                 id = bt_getid(slotptr(bt->page,slot)->id);
1442         else
1443                 id = 0;
1444
1445         if( bt_unlockpage (bt, bt->page_no, BtLockRead) )
1446                 return 0;
1447
1448         return id;
1449 }
1450
1451 //      check page for space available,
1452 //      clean if necessary and return
1453 //      0 - page needs splitting
1454 //      1 - go ahead
1455
1456 uint bt_cleanpage(BtDb *bt, uint amt)
1457 {
1458 uint nxt = bt->mgr->page_size;
1459 BtPage page = bt->page;
1460 uint cnt = 0, idx = 0;
1461 uint max = page->cnt;
1462 BtKey key;
1463
1464         if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1465                 return 1;
1466
1467         //      skip cleanup if nothing to reclaim
1468
1469         if( !page->dirty )
1470                 return 0;
1471
1472         memcpy (bt->frame, page, bt->mgr->page_size);
1473
1474         // skip page info and set rest of page to zero
1475
1476         memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1477         page->dirty = 0;
1478         page->act = 0;
1479
1480         // try cleaning up page first
1481
1482         while( cnt++ < max ) {
1483                 // always leave fence key and foster children in list
1484                 if( cnt < max - page->foster && slotptr(bt->frame,cnt)->dead )
1485                         continue;
1486
1487                 // copy key
1488                 key = keyptr(bt->frame, cnt);
1489                 nxt -= key->len + 1;
1490                 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1491
1492                 // copy slot
1493                 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1494                 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1495                         page->act++;
1496                 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1497                 slotptr(page, idx)->off = nxt;
1498         }
1499
1500         page->min = nxt;
1501         page->cnt = idx;
1502
1503         //      see if page has enough space now, or does it need splitting?
1504
1505         if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1506                 return 1;
1507
1508         return 0;
1509 }
1510
1511 //      add key to current page
1512 //      page must already be writelocked
1513
1514 void bt_addkeytopage (BtDb *bt, uint slot, unsigned char *key, uint len, uid id, uint tod)
1515 {
1516 BtPage page = bt->page;
1517 uint idx;
1518
1519         // calculate next available slot and copy key into page
1520
1521         page->min -= len + 1;
1522         ((unsigned char *)page)[page->min] = len;
1523         memcpy ((unsigned char *)page + page->min +1, key, len );
1524
1525         for( idx = slot; idx < page->cnt; idx++ )
1526           if( slotptr(page, idx)->dead )
1527                 break;
1528
1529         // now insert key into array before slot
1530         // preserving the fence slot
1531
1532         if( idx == page->cnt )
1533                 idx++, page->cnt++;
1534
1535         page->act++;
1536
1537         while( idx > slot )
1538                 *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
1539
1540         bt_putid(slotptr(page,slot)->id, id);
1541         slotptr(page, slot)->off = page->min;
1542         slotptr(page, slot)->tod = tod;
1543         slotptr(page, slot)->dead = 0;
1544 }
1545
1546 // split the root and raise the height of the btree
1547 //      call with current page locked and page no of foster child
1548 //      return with current page (root) unlocked
1549
1550 BTERR bt_splitroot(BtDb *bt, uid right)
1551 {
1552 uint nxt = bt->mgr->page_size;
1553 unsigned char fencekey[256];
1554 BtPage root = bt->page;
1555 uid new_page;
1556 BtKey key;
1557
1558         //  Obtain an empty page to use, and copy the left page
1559         //  contents into it from the root.  Strip foster child key.
1560         //      (it's the stopper key)
1561
1562         root->act--;
1563         root->cnt--;
1564         root->foster--;
1565
1566         //      Save left fence key.
1567
1568         key = keyptr(root, root->cnt);
1569         memcpy (fencekey, key, key->len + 1);
1570
1571         //  copy the lower keys into a new left page
1572
1573         if( !(new_page = bt_newpage(bt, root)) )
1574                 return bt->err;
1575
1576         // preserve the page info at the bottom
1577         // and set rest of the root to zero
1578
1579         memset (root+1, 0, bt->mgr->page_size - sizeof(*root));
1580
1581         // insert left fence key on empty newroot page
1582
1583         nxt -= *fencekey + 1;
1584         memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
1585         bt_putid(slotptr(root, 1)->id, new_page);
1586         slotptr(root, 1)->off = nxt;
1587         
1588         // insert stopper key on newroot page
1589         // and increase the root height
1590
1591         nxt -= 3;
1592         fencekey[0] = 2;
1593         fencekey[1] = 0xff;
1594         fencekey[2] = 0xff;
1595         memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
1596         bt_putid(slotptr(root, 2)->id, right);
1597         slotptr(root, 2)->off = nxt;
1598
1599         bt_putid(root->right, 0);
1600         root->min = nxt;                // reset lowest used offset and key count
1601         root->cnt = 2;
1602         root->act = 2;
1603         root->lvl++;
1604
1605         // release root (bt->page)
1606
1607         return bt_unlockpage(bt, ROOT_page, BtLockWrite);
1608 }
1609
1610 //  split already locked full node
1611 //      in current page variables
1612 //      return unlocked.
1613
1614 BTERR bt_splitpage (BtDb *bt)
1615 {
1616 uint slot, cnt, idx, max, nxt = bt->mgr->page_size;
1617 unsigned char fencekey[256];
1618 uid page_no = bt->page_no;
1619 BtPage page = bt->page;
1620 uint tod = time(NULL);
1621 uint lvl = page->lvl;
1622 uid new_page, right;
1623 BtKey key;
1624
1625         //      initialize frame buffer
1626
1627         memset (bt->frame, 0, bt->mgr->page_size);
1628         max = page->cnt - page->foster;
1629         tod = (uint)time(NULL);
1630         cnt = max / 2;
1631         idx = 0;
1632
1633         //  split higher half of keys to bt->frame
1634         //      leaving foster children in the left node.
1635
1636         while( cnt++ < max ) {
1637                 key = keyptr(page, cnt);
1638                 nxt -= key->len + 1;
1639                 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
1640                 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
1641                 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
1642                 slotptr(bt->frame, idx)->off = nxt;
1643                 bt->frame->act++;
1644         }
1645
1646         // transfer right link node
1647
1648         if( page_no > ROOT_page ) {
1649                 right = bt_getid (page->right);
1650                 bt_putid(bt->frame->right, right);
1651         }
1652
1653         bt->frame->bits = bt->mgr->page_bits;
1654         bt->frame->min = nxt;
1655         bt->frame->cnt = idx;
1656         bt->frame->lvl = lvl;
1657
1658         //      get new free page and write frame to it.
1659
1660         if( !(new_page = bt_newpage(bt, bt->frame)) )
1661                 return bt->err;
1662
1663         //      remember fence key for new page to add
1664         //      as foster child
1665
1666         key = keyptr(bt->frame, idx);
1667         memcpy (fencekey, key, key->len + 1);
1668
1669         //      update lower keys and foster children to continue in old page
1670
1671         memcpy (bt->frame, page, bt->mgr->page_size);
1672         memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1673         nxt = bt->mgr->page_size;
1674         page->act = 0;
1675         cnt = 0;
1676         idx = 0;
1677
1678         //  assemble page of smaller keys
1679         //      to remain in the old page
1680
1681         while( cnt++ < max / 2 ) {
1682                 key = keyptr(bt->frame, cnt);
1683                 nxt -= key->len + 1;
1684                 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1685                 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1686                 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1687                 slotptr(page, idx)->off = nxt;
1688                 page->act++;
1689         }
1690
1691         //      insert new foster child at beginning of the current foster children
1692
1693         nxt -= *fencekey + 1;
1694         memcpy ((unsigned char *)page + nxt, fencekey, *fencekey + 1);
1695         bt_putid (slotptr(page,++idx)->id, new_page);
1696         slotptr(page, idx)->tod = tod;
1697         slotptr(page, idx)->off = nxt;
1698         page->foster++;
1699         page->act++;
1700
1701         //  continue with old foster child keys if any
1702
1703         cnt = bt->frame->cnt - bt->frame->foster;
1704
1705         while( cnt++ < bt->frame->cnt ) {
1706                 key = keyptr(bt->frame, cnt);
1707                 nxt -= key->len + 1;
1708                 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1709                 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1710                 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1711                 slotptr(page, idx)->off = nxt;
1712                 page->act++;
1713         }
1714
1715         page->min = nxt;
1716         page->cnt = idx;
1717
1718         //      link new right page
1719
1720         bt_putid (page->right, new_page);
1721
1722         // if current page is the root page, split it
1723
1724         if( page_no == ROOT_page )
1725                 return bt_splitroot (bt, new_page);
1726
1727         //  release wr lock on our page
1728
1729         if( bt_unlockpage (bt, page_no, BtLockWrite) )
1730                 return bt->err;
1731
1732         //  obtain ParentModification lock for current page
1733         //      to fix fence key and highest foster child on page
1734
1735         if( bt_lockpage (bt, page_no, BtLockParent, NULL) )
1736                 return bt->err;
1737
1738         //  get our highest foster child key to find in parent node
1739
1740         if( bt_lockpage (bt, page_no, BtLockRead, &page) )
1741                 return bt->err;
1742
1743         key = keyptr(page, page->cnt);
1744         memcpy (fencekey, key, key->len+1);
1745
1746         if( bt_unlockpage (bt, page_no, BtLockRead) )
1747                 return bt->err;
1748
1749           //  update our parent
1750 try_again:
1751
1752         do {
1753           slot = bt_loadpage (bt, fencekey + 1, *fencekey, lvl + 1, BtLockWrite);
1754
1755           if( !slot )
1756                 return bt->err;
1757
1758           // check if parent page has enough space for any possible key
1759
1760           if( bt_cleanpage (bt, 256) )
1761                 break;
1762
1763           if( bt_splitpage (bt) )
1764                 return bt->err;
1765         } while( 1 );
1766
1767         //  see if we are still a foster child from another node
1768
1769         if( bt_getid (slotptr(bt->page, slot)->id) != page_no ) {
1770                 if( bt_unlockpage (bt, bt->page_no, BtLockWrite) )
1771                         return bt->err;
1772 #ifdef  unix
1773                 sched_yield();
1774 #else
1775                 SwitchToThread();
1776 #endif
1777                 goto try_again;
1778         }
1779
1780         //      wait until readers from parent get their locks
1781         //      on our page
1782
1783         if( bt_lockpage (bt, page_no, BtLockDelete, NULL) )
1784                 return bt->err;
1785
1786         //      lock our page for writing
1787
1788         if( bt_lockpage (bt, page_no, BtLockWrite, &page) )
1789                 return bt->err;
1790
1791         //      switch parent fence key to foster child
1792
1793         if( slotptr(page, page->cnt)->dead )
1794                 slotptr(bt->page, slot)->dead = 1;
1795         else
1796                 bt_putid (slotptr(bt->page, slot)->id, bt_getid(slotptr(page, page->cnt)->id));
1797
1798         //      remove highest foster child from our page
1799
1800         page->cnt--;
1801         page->act--;
1802         page->foster--;
1803         page->dirty = 1;
1804         key = keyptr(page, page->cnt);
1805
1806         //      add our new fence key for foster child to our parent
1807
1808         bt_addkeytopage (bt, slot, key->key, key->len, page_no, tod);
1809
1810         if( bt_unlockpage (bt, bt->page_no, BtLockWrite) )
1811                 return bt->err;
1812
1813         if( bt_unlockpage (bt, page_no, BtLockDelete) )
1814                 return bt->err;
1815
1816         if( bt_unlockpage (bt, page_no, BtLockWrite) )
1817                 return bt->err;
1818
1819         return bt_unlockpage (bt, page_no, BtLockParent);
1820 }
1821
1822 //  Insert new key into the btree at leaf level.
1823
1824 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod)
1825 {
1826 uint slot, idx;
1827 BtPage page;
1828 BtKey ptr;
1829
1830         while( 1 ) {
1831                 if( slot = bt_loadpage (bt, key, len, 0, BtLockWrite) )
1832                         ptr = keyptr(bt->page, slot);
1833                 else
1834                 {
1835                         if ( !bt->err )
1836                                 bt->err = BTERR_ovflw;
1837                         return bt->err;
1838                 }
1839
1840                 // if key already exists, update id and return
1841
1842                 page = bt->page;
1843
1844                 if( !keycmp (ptr, key, len) ) {
1845                         slotptr(page, slot)->dead = 0;
1846                         slotptr(page, slot)->tod = tod;
1847                         bt_putid(slotptr(page,slot)->id, id);
1848                         return bt_unlockpage(bt, bt->page_no, BtLockWrite);
1849                 }
1850
1851                 // check if page has enough space
1852
1853                 if( bt_cleanpage (bt, len) )
1854                         break;
1855
1856                 if( bt_splitpage (bt) )
1857                         return bt->err;
1858         }
1859
1860         bt_addkeytopage (bt, slot, key, len, id, tod);
1861
1862         return bt_unlockpage (bt, bt->page_no, BtLockWrite);
1863 }
1864
1865 //  cache page of keys into cursor and return starting slot for given key
1866
1867 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
1868 {
1869 uint slot;
1870
1871         // cache page for retrieval
1872         if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1873                 memcpy (bt->cursor, bt->page, bt->mgr->page_size);
1874         bt->cursor_page = bt->page_no;
1875         if ( bt_unlockpage(bt, bt->page_no, BtLockRead) )
1876                 return 0;
1877
1878         return slot;
1879 }
1880
1881 //  return next slot for cursor page
1882 //  or slide cursor right into next page
1883
1884 uint bt_nextkey (BtDb *bt, uint slot)
1885 {
1886 BtPage page;
1887 uid right;
1888
1889   do {
1890         right = bt_getid(bt->cursor->right);
1891         while( slot++ < bt->cursor->cnt - bt->cursor->foster )
1892           if( slotptr(bt->cursor,slot)->dead )
1893                 continue;
1894           else if( right || (slot < bt->cursor->cnt - bt->cursor->foster) )
1895                 return slot;
1896           else
1897                 break;
1898
1899         if( !right )
1900                 break;
1901
1902         bt->cursor_page = right;
1903
1904     if( bt_lockpage(bt, right, BtLockRead, &page) )
1905                 return 0;
1906
1907         memcpy (bt->cursor, page, bt->mgr->page_size);
1908
1909         if ( bt_unlockpage(bt, right, BtLockRead) )
1910                 return 0;
1911
1912         slot = 0;
1913   } while( 1 );
1914
1915   return bt->err = 0;
1916 }
1917
1918 BtKey bt_key(BtDb *bt, uint slot)
1919 {
1920         return keyptr(bt->cursor, slot);
1921 }
1922
1923 uid bt_uid(BtDb *bt, uint slot)
1924 {
1925         return bt_getid(slotptr(bt->cursor,slot)->id);
1926 }
1927
1928 uint bt_tod(BtDb *bt, uint slot)
1929 {
1930         return slotptr(bt->cursor,slot)->tod;
1931 }
1932
1933
1934 #ifdef STANDALONE
1935
1936 typedef struct {
1937         char type, idx;
1938         char *infile;
1939         BtMgr *mgr;
1940         int num;
1941 } ThreadArg;
1942
1943 //  standalone program to index file of keys
1944 //  then list them onto std-out
1945
1946 #ifdef unix
1947 void *index_file (void *arg)
1948 #else
1949 uint __stdcall index_file (void *arg)
1950 #endif
1951 {
1952 int line = 0, found = 0, cnt = 0;
1953 uid next, page_no = LEAF_page;  // start on first page of leaves
1954 unsigned char key[256];
1955 ThreadArg *args = arg;
1956 int ch, len = 0, slot;
1957 time_t tod[1];
1958 BtPage page;
1959 BtKey ptr;
1960 BtDb *bt;
1961 FILE *in;
1962
1963         bt = bt_open (args->mgr);
1964         time (tod);
1965
1966         switch(args->type | 0x20)
1967         {
1968         case 'w':
1969                 fprintf(stderr, "started indexing for %s\n", args->infile);
1970                 if( in = fopen (args->infile, "rb") )
1971                   while( ch = getc(in), ch != EOF )
1972                         if( ch == '\n' )
1973                         {
1974                           line++;
1975
1976                           if( args->num == 1 )
1977                                 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
1978
1979                           else if( args->num )
1980                                 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
1981
1982                           if( bt_insertkey (bt, key, len, line, *tod) )
1983                                 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
1984                           len = 0;
1985                         }
1986                         else if( len < 255 )
1987                                 key[len++] = ch;
1988                 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
1989                 break;
1990
1991         case 'd':
1992                 fprintf(stderr, "started deleting keys for %s\n", args->infile);
1993                 if( in = fopen (args->infile, "rb") )
1994                   while( ch = getc(in), ch != EOF )
1995                         if( ch == '\n' )
1996                         {
1997                           line++;
1998                           if( args->num == 1 )
1999                                 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2000
2001                           else if( args->num )
2002                                 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2003
2004                           if( bt_deletekey (bt, key, len, 0) )
2005                                 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2006                           len = 0;
2007                         }
2008                         else if( len < 255 )
2009                                 key[len++] = ch;
2010                 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2011                 break;
2012
2013         case 'f':
2014                 fprintf(stderr, "started finding keys for %s\n", args->infile);
2015                 if( in = fopen (args->infile, "rb") )
2016                   while( ch = getc(in), ch != EOF )
2017                         if( ch == '\n' )
2018                         {
2019                           line++;
2020                           if( args->num == 1 )
2021                                 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2022
2023                           else if( args->num )
2024                                 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2025
2026                           if( bt_findkey (bt, key, len) )
2027                                 found++;
2028                           else if( bt->err )
2029                                 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2030                           len = 0;
2031                         }
2032                         else if( len < 255 )
2033                                 key[len++] = ch;
2034                 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2035                 break;
2036
2037         case 's':
2038                 len = key[0] = 0;
2039
2040                 fprintf(stderr, "started reading\n");
2041
2042                 if( slot = bt_startkey (bt, key, len) )
2043                   slot--;
2044                 else
2045                   fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
2046
2047                 while( slot = bt_nextkey (bt, slot) ) {
2048                         ptr = bt_key(bt, slot);
2049                         fwrite (ptr->key, ptr->len, 1, stdout);
2050                         fputc ('\n', stdout);
2051                 }
2052
2053                 break;
2054
2055         case 'c':
2056                 fprintf(stderr, "started reading\n");
2057
2058                 do {
2059                         bt_lockpage (bt, page_no, BtLockRead, &page);
2060                         cnt += page->act;
2061                         next = bt_getid (page->right);
2062                         bt_unlockpage (bt, page_no, BtLockRead);
2063                 } while( page_no = next );
2064
2065                 cnt--;  // remove stopper key
2066                 fprintf(stderr, " Total keys read %d\n", cnt);
2067                 break;
2068         }
2069
2070         bt_close (bt);
2071 #ifdef unix
2072         return NULL;
2073 #else
2074         return 0;
2075 #endif
2076 }
2077
2078 typedef struct timeval timer;
2079
2080 int main (int argc, char **argv)
2081 {
2082 int idx, cnt, len, slot, err;
2083 int segsize, bits = 16;
2084 #ifdef unix
2085 pthread_t *threads;
2086 timer start, stop;
2087 #else
2088 time_t start[1], stop[1];
2089 HANDLE *threads;
2090 #endif
2091 double real_time;
2092 ThreadArg *args;
2093 uint poolsize = 0;
2094 int num = 0;
2095 char key[1];
2096 BtMgr *mgr;
2097 BtKey ptr;
2098 BtDb *bt;
2099
2100         if( argc < 3 ) {
2101                 fprintf (stderr, "Usage: %s idx_file Read/Write/Scan/Delete/Find [page_bits mapped_segments seg_bits line_numbers src_file1 src_file2 ... ]\n", argv[0]);
2102                 fprintf (stderr, "  where page_bits is the page size in bits\n");
2103                 fprintf (stderr, "  mapped_segments is the number of mmap segments in buffer pool\n");
2104                 fprintf (stderr, "  seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2105                 fprintf (stderr, "  line_numbers = 1 to append line numbers to keys\n");
2106                 fprintf (stderr, "  src_file1 thru src_filen are files of keys separated by newline\n");
2107                 exit(0);
2108         }
2109
2110 #ifdef unix
2111         gettimeofday(&start, NULL);
2112 #else
2113         time(start);
2114 #endif
2115
2116         if( argc > 3 )
2117                 bits = atoi(argv[3]);
2118
2119         if( argc > 4 )
2120                 poolsize = atoi(argv[4]);
2121
2122         if( !poolsize )
2123                 fprintf (stderr, "Warning: no mapped_pool\n");
2124
2125         if( poolsize > 65535 )
2126                 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2127
2128         if( argc > 5 )
2129                 segsize = atoi(argv[5]);
2130         else
2131                 segsize = 4;    // 16 pages per mmap segment
2132
2133         if( argc > 6 )
2134                 num = atoi(argv[6]);
2135
2136         cnt = argc - 7;
2137 #ifdef unix
2138         threads = malloc (cnt * sizeof(pthread_t));
2139 #else
2140         threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2141 #endif
2142         args = malloc (cnt * sizeof(ThreadArg));
2143
2144         mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2145
2146         if( !mgr ) {
2147                 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2148                 exit (1);
2149         }
2150
2151         //      fire off threads
2152
2153         for( idx = 0; idx < cnt; idx++ ) {
2154                 args[idx].infile = argv[idx + 7];
2155                 args[idx].type = argv[2][0];
2156                 args[idx].mgr = mgr;
2157                 args[idx].num = num;
2158                 args[idx].idx = idx;
2159 #ifdef unix
2160                 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2161                         fprintf(stderr, "Error creating thread %d\n", err);
2162 #else
2163                 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2164 #endif
2165         }
2166
2167         //      wait for termination
2168
2169 #ifdef unix
2170         for( idx = 0; idx < cnt; idx++ )
2171                 pthread_join (threads[idx], NULL);
2172         gettimeofday(&stop, NULL);
2173         real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2174 #else
2175         WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2176
2177         for( idx = 0; idx < cnt; idx++ )
2178                 CloseHandle(threads[idx]);
2179
2180         time (stop);
2181         real_time = 1000 * (*stop - *start);
2182 #endif
2183         fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);
2184         bt_mgrclose (mgr);
2185 }
2186
2187 #endif  //STANDALONE