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