]> pd.if.org Git - btree/blob - threads2i.c
Finish rework of bt_deletekey, w/bug fixes
[btree] / threads2i.c
1 // btree version threads2i sched_yield version
2 //      with reworked bt_deletekey code
3 // 12 FEB 2014
4
5 // author: karl malbrain, malbrain@cal.berkeley.edu
6
7 /*
8 This work, including the source code, documentation
9 and related data, is placed into the public domain.
10
11 The orginal author is Karl Malbrain.
12
13 THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY
14 OF ANY KIND, NOT EVEN THE IMPLIED WARRANTY OF
15 MERCHANTABILITY. THE AUTHOR OF THIS SOFTWARE,
16 ASSUMES _NO_ RESPONSIBILITY FOR ANY CONSEQUENCE
17 RESULTING FROM THE USE, MODIFICATION, OR
18 REDISTRIBUTION OF THIS SOFTWARE.
19 */
20
21 // Please see the project home page for documentation
22 // code.google.com/p/high-concurrency-btree
23
24 #define _FILE_OFFSET_BITS 64
25 #define _LARGEFILE64_SOURCE
26
27 #ifdef linux
28 #define _GNU_SOURCE
29 #endif
30
31 #ifdef unix
32 #include <unistd.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <fcntl.h>
36 #include <sys/time.h>
37 #include <sys/mman.h>
38 #include <errno.h>
39 #include <pthread.h>
40 #else
41 #define WIN32_LEAN_AND_MEAN
42 #include <windows.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <time.h>
46 #include <fcntl.h>
47 #include <process.h>
48 #include <intrin.h>
49 #endif
50
51 #include <memory.h>
52 #include <string.h>
53 #include <stddef.h>
54
55 typedef unsigned long long      uid;
56
57 #ifndef unix
58 typedef unsigned long long      off64_t;
59 typedef unsigned short          ushort;
60 typedef unsigned int            uint;
61 #endif
62
63 #define BT_latchtable   128                                     // number of latch manager slots
64
65 #define BT_ro 0x6f72    // ro
66 #define BT_rw 0x7772    // rw
67
68 #define BT_maxbits              24                                      // maximum page size in bits
69 #define BT_minbits              9                                       // minimum page size in bits
70 #define BT_minpage              (1 << BT_minbits)       // minimum page size
71 #define BT_maxpage              (1 << BT_maxbits)       // maximum page size
72
73 /*
74 There are five lock types for each node in three independent sets: 
75 1. (set 1) AccessIntent: Sharable. Going to Read the node. Incompatible with NodeDelete. 
76 2. (set 1) NodeDelete: Exclusive. About to release the node. Incompatible with AccessIntent. 
77 3. (set 2) ReadLock: Sharable. Read the node. Incompatible with WriteLock. 
78 4. (set 2) WriteLock: Exclusive. Modify the node. Incompatible with ReadLock and other WriteLocks. 
79 5. (set 3) ParentModification: Exclusive. Change the node's parent keys. Incompatible with another ParentModification. 
80 */
81
82 typedef enum{
83         BtLockAccess,
84         BtLockDelete,
85         BtLockRead,
86         BtLockWrite,
87         BtLockParent
88 } BtLock;
89
90 //      mode & definition for latch implementation
91
92 enum {
93         Mutex = 1,
94         Write = 2,
95         Pending = 4,
96         Share = 8
97 } LockMode;
98
99 // exclusive is set for write access
100 // share is count of read accessors
101 // grant write lock when share == 0
102
103 typedef struct {
104         volatile ushort mutex:1;
105         volatile ushort exclusive:1;
106         volatile ushort pending:1;
107         volatile ushort share:13;
108 } BtSpinLatch;
109
110 //  hash table entries
111
112 typedef struct {
113         BtSpinLatch latch[1];
114         volatile ushort slot;           // Latch table entry at head of chain
115 } BtHashEntry;
116
117 //      latch manager table structure
118
119 typedef struct {
120         BtSpinLatch readwr[1];          // read/write page lock
121         BtSpinLatch access[1];          // Access Intent/Page delete
122         BtSpinLatch parent[1];          // Posting of fence key in parent
123         BtSpinLatch busy[1];            // slot is being moved between chains
124         volatile ushort next;           // next entry in hash table chain
125         volatile ushort prev;           // prev entry in hash table chain
126         volatile ushort pin;            // number of outstanding locks
127         volatile ushort hash;           // hash slot entry is under
128         volatile uid page_no;           // latch set page number
129 } BtLatchSet;
130
131 //      Define the length of the page and key pointers
132
133 #define BtId 6
134
135 //      Page key slot definition.
136
137 //      If BT_maxbits is 15 or less, you can save 4 bytes
138 //      for each key stored by making the first two uints
139 //      into ushorts.  You can also save 4 bytes by removing
140 //      the tod field from the key.
141
142 //      Keys are marked dead, but remain on the page until
143 //      it cleanup is called. The fence key (highest key) for
144 //      the page is always present, even after cleanup.
145
146 typedef struct {
147         uint off:BT_maxbits;            // page offset for key start
148         uint dead:1;                            // set for deleted key
149         uint tod;                                       // time-stamp for key
150         unsigned char id[BtId];         // id associated with key
151 } BtSlot;
152
153 //      The key structure occupies space at the upper end of
154 //      each page.  It's a length byte followed by the value
155 //      bytes.
156
157 typedef struct {
158         unsigned char len;
159         unsigned char key[1];
160 } *BtKey;
161
162 //      The first part of an index page.
163 //      It is immediately followed
164 //      by the BtSlot array of keys.
165
166 typedef struct BtPage_ {
167         uint cnt;                                       // count of keys in page
168         uint act;                                       // count of active keys
169         uint min;                                       // next key offset
170         unsigned char bits:7;           // page size in bits
171         unsigned char free:1;           // page is on free chain
172         unsigned char lvl:4;            // level of page
173         unsigned char kill:1;           // page is being deleted
174         unsigned char dirty:1;          // page has deleted keys
175         unsigned char posted:1;         // page fence is posted
176         unsigned char goright:1;        // page is being deleted, go right
177         unsigned char right[BtId];      // page number to right
178         unsigned char fence[256];       // page fence key
179 } *BtPage;
180
181 //      The memory mapping pool table buffer manager entry
182
183 typedef struct {
184         unsigned long long int lru;     // number of times accessed
185         uid  basepage;                          // mapped base page number
186         char *map;                                      // mapped memory pointer
187         ushort slot;                            // slot index in this array
188         ushort pin;                                     // mapped page pin counter
189         void *hashprev;                         // previous pool entry for the same hash idx
190         void *hashnext;                         // next pool entry for the same hash idx
191 #ifndef unix
192         HANDLE hmap;                            // Windows memory mapping handle
193 #endif
194 } BtPool;
195
196 //  The loadpage interface object
197
198 typedef struct {
199         uid page_no;            // current page number
200         BtPage page;            // current page pointer
201         BtPool *pool;           // current page pool
202         BtLatchSet *latch;      // current page latch set
203 } BtPageSet;
204
205 //      structure for latch manager on ALLOC_page
206
207 typedef struct {
208         struct BtPage_ alloc[2];        // next & free page_nos in right ptr
209         BtSpinLatch lock[1];            // allocation area lite latch
210         ushort latchdeployed;           // highest number of latch entries deployed
211         ushort nlatchpage;                      // number of latch pages at BT_latch
212         ushort latchtotal;                      // number of page latch entries
213         ushort latchhash;                       // number of latch hash table slots
214         ushort latchvictim;                     // next latch entry to examine
215         BtHashEntry table[0];           // the hash table
216 } BtLatchMgr;
217
218 //      The object structure for Btree access
219
220 typedef struct {
221         uint page_size;                         // page size    
222         uint page_bits;                         // page size in bits    
223         uint seg_bits;                          // seg size in pages in bits
224         uint mode;                                      // read-write mode
225 #ifdef unix
226         int idx;
227 #else
228         HANDLE idx;
229 #endif
230         ushort poolcnt;                         // highest page pool node in use
231         ushort poolmax;                         // highest page pool node allocated
232         ushort poolmask;                        // total number of pages in mmap segment - 1
233         ushort hashsize;                        // size of Hash Table for pool entries
234         volatile uint evicted;          // last evicted hash table slot
235         ushort *hash;                           // pool index for hash entries
236         BtSpinLatch *latch;                     // latches for hash table slots
237         BtLatchMgr *latchmgr;           // mapped latch page from allocation page
238         BtLatchSet *latchsets;          // mapped latch set from latch pages
239         BtPool *pool;                           // memory pool page segments
240 #ifndef unix
241         HANDLE halloc;                          // allocation and latch table handle
242 #endif
243 } BtMgr;
244
245 typedef struct {
246         BtMgr *mgr;                     // buffer manager for thread
247         BtPage cursor;          // cached frame for start/next (never mapped)
248         BtPage frame;           // spare frame for the page split (never mapped)
249         BtPage zero;            // page frame for zeroes at end of file
250         uid cursor_page;        // current cursor page number   
251         unsigned char *mem;     // frame, cursor, page memory buffer
252         int found;                      // last delete or insert was found
253         int err;                        // last error
254 } BtDb;
255
256 typedef enum {
257         BTERR_ok = 0,
258         BTERR_struct,
259         BTERR_ovflw,
260         BTERR_lock,
261         BTERR_map,
262         BTERR_wrt,
263         BTERR_hash
264 } BTERR;
265
266 // B-Tree functions
267 extern void bt_close (BtDb *bt);
268 extern BtDb *bt_open (BtMgr *mgr);
269 extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod, uint lvl);
270 extern BTERR  bt_deletekey (BtDb *bt, unsigned char *key, uint len);
271 extern uid bt_findkey    (BtDb *bt, unsigned char *key, uint len);
272 extern uint bt_startkey  (BtDb *bt, unsigned char *key, uint len);
273 extern uint bt_nextkey   (BtDb *bt, uint slot);
274
275 //      internal functions
276 BTERR bt_removepage (BtDb *bt, BtPageSet *set, uint lvl, unsigned char *pagefence);
277
278 //      manager functions
279 extern BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolsize, uint segsize, uint hashsize);
280 void bt_mgrclose (BtMgr *mgr);
281
282 //  Helper functions to return slot values
283
284 extern BtKey bt_key (BtDb *bt, uint slot);
285 extern uid bt_uid (BtDb *bt, uint slot);
286 extern uint bt_tod (BtDb *bt, uint slot);
287
288 //  BTree page number constants
289 #define ALLOC_page              0       // allocation & lock manager hash table
290 #define ROOT_page               1       // root of the btree
291 #define LEAF_page               2       // first page of leaves
292 #define LATCH_page              3       // pages for lock manager
293
294 //      Number of levels to create in a new BTree
295
296 #define MIN_lvl                 2
297
298 //  The page is allocated from low and hi ends.
299 //  The key offsets and row-id's are allocated
300 //  from the bottom, while the text of the key
301 //  is allocated from the top.  When the two
302 //  areas meet, the page is split into two.
303
304 //  A key consists of a length byte, two bytes of
305 //  index number (0 - 65534), and up to 253 bytes
306 //  of key value.  Duplicate keys are discarded.
307 //  Associated with each key is a 48 bit row-id.
308
309 //  The b-tree root is always located at page 1.
310 //      The first leaf page of level zero is always
311 //      located on page 2.
312
313 //      The b-tree pages are linked with next
314 //      pointers to facilitate enumerators,
315 //      and provide for concurrency.
316
317 //      When to root page fills, it is split in two and
318 //      the tree height is raised by a new root at page
319 //      one with two keys.
320
321 //      Deleted keys are marked with a dead bit until
322 //      page cleanup. The fence key for a node is
323 //      present in a special array
324
325 //  Groups of pages called segments from the btree are optionally
326 //  cached with a memory mapped pool. A hash table is used to keep
327 //  track of the cached segments.  This behaviour is controlled
328 //  by the cache block size parameter to bt_open.
329
330 //  To achieve maximum concurrency one page is locked at a time
331 //  as the tree is traversed to find leaf key in question. The right
332 //  page numbers are used in cases where the page is being split,
333 //      or consolidated.
334
335 //  Page 0 is dedicated to lock for new page extensions,
336 //      and chains empty pages together for reuse.
337
338 //      The ParentModification lock on a node is obtained to serialize posting
339 //      or changing the fence key for a node.
340
341 //      Empty pages are chained together through the ALLOC page and reused.
342
343 //      Access macros to address slot and key values from the page
344 //      Page slots use 1 based indexing.
345
346 #define slotptr(page, slot) (((BtSlot *)(page+1)) + (slot-1))
347 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
348
349 void bt_putid(unsigned char *dest, uid id)
350 {
351 int i = BtId;
352
353         while( i-- )
354                 dest[i] = (unsigned char)id, id >>= 8;
355 }
356
357 uid bt_getid(unsigned char *src)
358 {
359 uid id = 0;
360 int i;
361
362         for( i = 0; i < BtId; i++ )
363                 id <<= 8, id |= *src++; 
364
365         return id;
366 }
367
368 //      Latch Manager
369
370 //      wait until write lock mode is clear
371 //      and add 1 to the share count
372
373 void bt_spinreadlock(BtSpinLatch *latch)
374 {
375 ushort prev;
376
377   do {
378         //      obtain latch mutex
379 #ifdef unix
380         if( __sync_fetch_and_or((ushort *)latch, Mutex) & Mutex )
381                 continue;
382 #else
383         if( prev = _InterlockedOr16((ushort *)latch, Mutex) & Mutex )
384                 continue;
385 #endif
386         //  see if exclusive request is granted or pending
387
388         if( prev = !(latch->exclusive | latch->pending) )
389 #ifdef unix
390                 __sync_fetch_and_add((ushort *)latch, Share);
391 #else
392                 _InterlockedExchangeAdd16 ((ushort *)latch, Share);
393 #endif
394
395 #ifdef unix
396         __sync_fetch_and_and ((ushort *)latch, ~Mutex);
397 #else
398         _InterlockedAnd16((ushort *)latch, ~Mutex);
399 #endif
400
401         if( prev )
402                 return;
403 #ifdef  unix
404   } while( sched_yield(), 1 );
405 #else
406   } while( SwitchToThread(), 1 );
407 #endif
408 }
409
410 //      wait for other read and write latches to relinquish
411
412 void bt_spinwritelock(BtSpinLatch *latch)
413 {
414   do {
415 #ifdef  unix
416         if( __sync_fetch_and_or((ushort *)latch, Mutex | Pending) & Mutex )
417                 continue;
418 #else
419         if( _InterlockedOr16((ushort *)latch, Mutex | Pending) & Mutex )
420                 continue;
421 #endif
422         if( !(latch->share | latch->exclusive) ) {
423 #ifdef unix
424                 __sync_fetch_and_or((ushort *)latch, Write);
425                 __sync_fetch_and_and ((ushort *)latch, ~(Mutex | Pending));
426 #else
427                 _InterlockedOr16((ushort *)latch, Write);
428                 _InterlockedAnd16((ushort *)latch, ~(Mutex | Pending));
429 #endif
430                 return;
431         }
432
433 #ifdef unix
434         __sync_fetch_and_and ((ushort *)latch, ~Mutex);
435 #else
436         _InterlockedAnd16((ushort *)latch, ~Mutex);
437 #endif
438
439 #ifdef  unix
440   } while( sched_yield(), 1 );
441 #else
442   } while( SwitchToThread(), 1 );
443 #endif
444 }
445
446 //      try to obtain write lock
447
448 //      return 1 if obtained,
449 //              0 otherwise
450
451 int bt_spinwritetry(BtSpinLatch *latch)
452 {
453 ushort prev;
454
455 #ifdef unix
456         if( prev = __sync_fetch_and_or((ushort *)latch, Mutex), prev & Mutex )
457                 return 0;
458 #else
459         if( prev = _InterlockedOr16((ushort *)latch, Mutex), prev & Mutex )
460                 return 0;
461 #endif
462         //      take write access if all bits are clear
463
464         if( !prev )
465 #ifdef unix
466                 __sync_fetch_and_or ((ushort *)latch, Write);
467 #else
468                 _InterlockedOr16((ushort *)latch, Write);
469 #endif
470
471 #ifdef unix
472         __sync_fetch_and_and ((ushort *)latch, ~Mutex);
473 #else
474         _InterlockedAnd16((ushort *)latch, ~Mutex);
475 #endif
476         return !prev;
477 }
478
479 //      clear write mode
480
481 void bt_spinreleasewrite(BtSpinLatch *latch)
482 {
483 #ifdef unix
484         __sync_fetch_and_and ((ushort *)latch, ~Write);
485 #else
486         _InterlockedAnd16((ushort *)latch, ~Write);
487 #endif
488 }
489
490 //      decrement reader count
491
492 void bt_spinreleaseread(BtSpinLatch *latch)
493 {
494 #ifdef unix
495         __sync_fetch_and_add((ushort *)latch, -Share);
496 #else
497         _InterlockedExchangeAdd16 ((ushort *)latch, -Share);
498 #endif
499 }
500
501 //      link latch table entry into latch hash table
502
503 void bt_latchlink (BtDb *bt, ushort hashidx, ushort victim, uid page_no)
504 {
505 BtLatchSet *set = bt->mgr->latchsets + victim;
506
507         if( set->next = bt->mgr->latchmgr->table[hashidx].slot )
508                 bt->mgr->latchsets[set->next].prev = victim;
509
510         bt->mgr->latchmgr->table[hashidx].slot = victim;
511         set->page_no = page_no;
512         set->hash = hashidx;
513         set->prev = 0;
514 }
515
516 //      release latch pin
517
518 void bt_unpinlatch (BtLatchSet *set)
519 {
520 #ifdef unix
521         __sync_fetch_and_add(&set->pin, -1);
522 #else
523         _InterlockedDecrement16 (&set->pin);
524 #endif
525 }
526
527 //      find existing latchset or inspire new one
528 //      return with latchset pinned
529
530 BtLatchSet *bt_pinlatch (BtDb *bt, uid page_no)
531 {
532 ushort hashidx = page_no % bt->mgr->latchmgr->latchhash;
533 ushort slot, avail = 0, victim, idx;
534 BtLatchSet *set;
535
536         //  obtain read lock on hash table entry
537
538         bt_spinreadlock(bt->mgr->latchmgr->table[hashidx].latch);
539
540         if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
541         {
542                 set = bt->mgr->latchsets + slot;
543                 if( page_no == set->page_no )
544                         break;
545         } while( slot = set->next );
546
547         if( slot ) {
548 #ifdef unix
549                 __sync_fetch_and_add(&set->pin, 1);
550 #else
551                 _InterlockedIncrement16 (&set->pin);
552 #endif
553         }
554
555     bt_spinreleaseread (bt->mgr->latchmgr->table[hashidx].latch);
556
557         if( slot )
558                 return set;
559
560   //  try again, this time with write lock
561
562   bt_spinwritelock(bt->mgr->latchmgr->table[hashidx].latch);
563
564   if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
565   {
566         set = bt->mgr->latchsets + slot;
567         if( page_no == set->page_no )
568                 break;
569         if( !set->pin && !avail )
570                 avail = slot;
571   } while( slot = set->next );
572
573   //  found our entry, or take over an unpinned one
574
575   if( slot || (slot = avail) ) {
576         set = bt->mgr->latchsets + slot;
577 #ifdef unix
578         __sync_fetch_and_add(&set->pin, 1);
579 #else
580         _InterlockedIncrement16 (&set->pin);
581 #endif
582         set->page_no = page_no;
583         bt_spinreleasewrite(bt->mgr->latchmgr->table[hashidx].latch);
584         return set;
585   }
586
587         //  see if there are any unused entries
588 #ifdef unix
589         victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, 1) + 1;
590 #else
591         victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchdeployed);
592 #endif
593
594         if( victim < bt->mgr->latchmgr->latchtotal ) {
595                 set = bt->mgr->latchsets + victim;
596 #ifdef unix
597                 __sync_fetch_and_add(&set->pin, 1);
598 #else
599                 _InterlockedIncrement16 (&set->pin);
600 #endif
601                 bt_latchlink (bt, hashidx, victim, page_no);
602                 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
603                 return set;
604         }
605
606 #ifdef unix
607         victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, -1);
608 #else
609         victim = _InterlockedDecrement16 (&bt->mgr->latchmgr->latchdeployed);
610 #endif
611   //  find and reuse previous lock entry
612
613   while( 1 ) {
614 #ifdef unix
615         victim = __sync_fetch_and_add(&bt->mgr->latchmgr->latchvictim, 1);
616 #else
617         victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchvictim) - 1;
618 #endif
619         //      we don't use slot zero
620
621         if( victim %= bt->mgr->latchmgr->latchtotal )
622                 set = bt->mgr->latchsets + victim;
623         else
624                 continue;
625
626         //      take control of our slot
627         //      from other threads
628
629         if( set->pin || !bt_spinwritetry (set->busy) )
630                 continue;
631
632         idx = set->hash;
633
634         // try to get write lock on hash chain
635         //      skip entry if not obtained
636         //      or has outstanding locks
637
638         if( !bt_spinwritetry (bt->mgr->latchmgr->table[idx].latch) ) {
639                 bt_spinreleasewrite (set->busy);
640                 continue;
641         }
642
643         if( set->pin ) {
644                 bt_spinreleasewrite (set->busy);
645                 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
646                 continue;
647         }
648
649         //  unlink our available victim from its hash chain
650
651         if( set->prev )
652                 bt->mgr->latchsets[set->prev].next = set->next;
653         else
654                 bt->mgr->latchmgr->table[idx].slot = set->next;
655
656         if( set->next )
657                 bt->mgr->latchsets[set->next].prev = set->prev;
658
659         bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
660 #ifdef unix
661         __sync_fetch_and_add(&set->pin, 1);
662 #else
663         _InterlockedIncrement16 (&set->pin);
664 #endif
665         bt_latchlink (bt, hashidx, victim, page_no);
666         bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
667         bt_spinreleasewrite (set->busy);
668         return set;
669   }
670 }
671
672 void bt_mgrclose (BtMgr *mgr)
673 {
674 BtPool *pool;
675 uint slot;
676
677         // release mapped pages
678         //      note that slot zero is never used
679
680         for( slot = 1; slot < mgr->poolmax; slot++ ) {
681                 pool = mgr->pool + slot;
682                 if( pool->slot )
683 #ifdef unix
684                         munmap (pool->map, (mgr->poolmask+1) << mgr->page_bits);
685 #else
686                 {
687                         FlushViewOfFile(pool->map, 0);
688                         UnmapViewOfFile(pool->map);
689                         CloseHandle(pool->hmap);
690                 }
691 #endif
692         }
693
694 #ifdef unix
695         munmap (mgr->latchsets, mgr->latchmgr->nlatchpage * mgr->page_size);
696         munmap (mgr->latchmgr, mgr->page_size);
697 #else
698         FlushViewOfFile(mgr->latchmgr, 0);
699         UnmapViewOfFile(mgr->latchmgr);
700         CloseHandle(mgr->halloc);
701 #endif
702 #ifdef unix
703         close (mgr->idx);
704         free (mgr->pool);
705         free (mgr->hash);
706         free (mgr->latch);
707         free (mgr);
708 #else
709         FlushFileBuffers(mgr->idx);
710         CloseHandle(mgr->idx);
711         GlobalFree (mgr->pool);
712         GlobalFree (mgr->hash);
713         GlobalFree (mgr->latch);
714         GlobalFree (mgr);
715 #endif
716 }
717
718 //      close and release memory
719
720 void bt_close (BtDb *bt)
721 {
722 #ifdef unix
723         if ( bt->mem )
724                 free (bt->mem);
725 #else
726         if ( bt->mem)
727                 VirtualFree (bt->mem, 0, MEM_RELEASE);
728 #endif
729         free (bt);
730 }
731
732 //  open/create new btree buffer manager
733
734 //      call with file_name, BT_openmode, bits in page size (e.g. 16),
735 //              size of mapped page pool (e.g. 8192)
736
737 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
738 {
739 uint lvl, attr, cacheblk, last, slot, idx;
740 uint nlatchpage, latchhash;
741 BtLatchMgr *latchmgr;
742 off64_t size;
743 uint amt[1];
744 BtMgr* mgr;
745 BtKey key;
746 int flag;
747
748 #ifndef unix
749 SYSTEM_INFO sysinfo[1];
750 #endif
751
752         // determine sanity of page size and buffer pool
753
754         if( bits > BT_maxbits )
755                 bits = BT_maxbits;
756         else if( bits < BT_minbits )
757                 bits = BT_minbits;
758
759         if( !poolmax )
760                 return NULL;    // must have buffer pool
761
762 #ifdef unix
763         mgr = calloc (1, sizeof(BtMgr));
764
765         mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
766
767         if( mgr->idx == -1 )
768                 return free(mgr), NULL;
769         
770         cacheblk = 4096;        // minimum mmap segment size for unix
771
772 #else
773         mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
774         attr = FILE_ATTRIBUTE_NORMAL;
775         mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
776
777         if( mgr->idx == INVALID_HANDLE_VALUE )
778                 return GlobalFree(mgr), NULL;
779
780         // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
781         GetSystemInfo(sysinfo);
782         cacheblk = sysinfo->dwAllocationGranularity;
783 #endif
784
785 #ifdef unix
786         latchmgr = malloc (BT_maxpage);
787         *amt = 0;
788
789         // read minimum page size to get root info
790
791         if( size = lseek (mgr->idx, 0L, 2) ) {
792                 if( pread(mgr->idx, latchmgr, BT_minpage, 0) == BT_minpage )
793                         bits = latchmgr->alloc->bits;
794                 else
795                         return free(mgr), free(latchmgr), NULL;
796         } else if( mode == BT_ro )
797                 return free(latchmgr), bt_mgrclose (mgr), NULL;
798 #else
799         latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
800         size = GetFileSize(mgr->idx, amt);
801
802         if( size || *amt ) {
803                 if( !ReadFile(mgr->idx, (char *)latchmgr, BT_minpage, amt, NULL) )
804                         return bt_mgrclose (mgr), NULL;
805                 bits = latchmgr->alloc->bits;
806         } else if( mode == BT_ro )
807                 return bt_mgrclose (mgr), NULL;
808 #endif
809
810         mgr->page_size = 1 << bits;
811         mgr->page_bits = bits;
812
813         mgr->poolmax = poolmax;
814         mgr->mode = mode;
815
816         if( cacheblk < mgr->page_size )
817                 cacheblk = mgr->page_size;
818
819         //  mask for partial memmaps
820
821         mgr->poolmask = (cacheblk >> bits) - 1;
822
823         //      see if requested size of pages per memmap is greater
824
825         if( (1 << segsize) > mgr->poolmask )
826                 mgr->poolmask = (1 << segsize) - 1;
827
828         mgr->seg_bits = 0;
829
830         while( (1 << mgr->seg_bits) <= mgr->poolmask )
831                 mgr->seg_bits++;
832
833         mgr->hashsize = hashsize;
834
835 #ifdef unix
836         mgr->pool = calloc (poolmax, sizeof(BtPool));
837         mgr->hash = calloc (hashsize, sizeof(ushort));
838         mgr->latch = calloc (hashsize, sizeof(BtSpinLatch));
839 #else
840         mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * sizeof(BtPool));
841         mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
842         mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtSpinLatch));
843 #endif
844
845         if( size || *amt )
846                 goto mgrlatch;
847
848         // initialize an empty b-tree with latch page, root page, page of leaves
849         // and page(s) of latches
850
851         memset (latchmgr, 0, 1 << bits);
852         nlatchpage = BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1; 
853         bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
854         latchmgr->alloc->bits = mgr->page_bits;
855
856         latchmgr->nlatchpage = nlatchpage;
857         latchmgr->latchtotal = nlatchpage * (mgr->page_size / sizeof(BtLatchSet));
858
859         //  initialize latch manager
860
861         latchhash = (mgr->page_size - sizeof(BtLatchMgr)) / sizeof(BtHashEntry);
862
863         //      size of hash table = total number of latchsets
864
865         if( latchhash > latchmgr->latchtotal )
866                 latchhash = latchmgr->latchtotal;
867
868         latchmgr->latchhash = latchhash;
869
870 #ifdef unix
871         if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
872                 return bt_mgrclose (mgr), NULL;
873 #else
874         if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
875                 return bt_mgrclose (mgr), NULL;
876
877         if( *amt < mgr->page_size )
878                 return bt_mgrclose (mgr), NULL;
879 #endif
880
881         memset (latchmgr, 0, 1 << bits);
882         latchmgr->alloc->bits = mgr->page_bits;
883
884         for( lvl=MIN_lvl; lvl--; ) {
885                 slotptr(latchmgr->alloc, 1)->off = offsetof(struct BtPage_, fence);
886                 bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0);         // next(lower) page number
887                 latchmgr->alloc->fence[0] = 2;                  // create stopper key
888                 latchmgr->alloc->fence[1] = 0xff;
889                 latchmgr->alloc->fence[2] = 0xff;
890                 latchmgr->alloc->min = mgr->page_size;
891                 latchmgr->alloc->lvl = lvl;
892                 latchmgr->alloc->cnt = 1;
893                 latchmgr->alloc->act = 1;
894 #ifdef unix
895                 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
896                         return bt_mgrclose (mgr), NULL;
897 #else
898                 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
899                         return bt_mgrclose (mgr), NULL;
900
901                 if( *amt < mgr->page_size )
902                         return bt_mgrclose (mgr), NULL;
903 #endif
904         }
905
906         // clear out latch manager locks
907         //      and rest of pages to round out segment
908
909         memset(latchmgr, 0, mgr->page_size);
910         last = MIN_lvl + 1;
911
912         while( last <= ((MIN_lvl + 1 + nlatchpage) | mgr->poolmask) ) {
913 #ifdef unix
914                 pwrite(mgr->idx, latchmgr, mgr->page_size, last << mgr->page_bits);
915 #else
916                 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
917                 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
918                         return bt_mgrclose (mgr), NULL;
919                 if( *amt < mgr->page_size )
920                         return bt_mgrclose (mgr), NULL;
921 #endif
922                 last++;
923         }
924
925 mgrlatch:
926 #ifdef unix
927         flag = PROT_READ | PROT_WRITE;
928         mgr->latchmgr = mmap (0, mgr->page_size, flag, MAP_SHARED, mgr->idx, ALLOC_page * mgr->page_size);
929         if( mgr->latchmgr == MAP_FAILED )
930                 return bt_mgrclose (mgr), NULL;
931         mgr->latchsets = (BtLatchSet *)mmap (0, mgr->latchmgr->nlatchpage * mgr->page_size, flag, MAP_SHARED, mgr->idx, LATCH_page * mgr->page_size);
932         if( mgr->latchsets == MAP_FAILED )
933                 return bt_mgrclose (mgr), NULL;
934 #else
935         flag = PAGE_READWRITE;
936         mgr->halloc = CreateFileMapping(mgr->idx, NULL, flag, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size, NULL);
937         if( !mgr->halloc )
938                 return bt_mgrclose (mgr), NULL;
939
940         flag = FILE_MAP_WRITE;
941         mgr->latchmgr = MapViewOfFile(mgr->halloc, flag, 0, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size);
942         if( !mgr->latchmgr )
943                 return GetLastError(), bt_mgrclose (mgr), NULL;
944
945         mgr->latchsets = (void *)((char *)mgr->latchmgr + LATCH_page * mgr->page_size);
946 #endif
947
948 #ifdef unix
949         free (latchmgr);
950 #else
951         VirtualFree (latchmgr, 0, MEM_RELEASE);
952 #endif
953         return mgr;
954 }
955
956 //      open BTree access method
957 //      based on buffer manager
958
959 BtDb *bt_open (BtMgr *mgr)
960 {
961 BtDb *bt = malloc (sizeof(*bt));
962
963         memset (bt, 0, sizeof(*bt));
964         bt->mgr = mgr;
965 #ifdef unix
966         bt->mem = malloc (3 *mgr->page_size);
967 #else
968         bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
969 #endif
970         bt->frame = (BtPage)bt->mem;
971         bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
972         bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
973
974         memset (bt->zero, 0, mgr->page_size);
975         return bt;
976 }
977
978 //  compare two keys, returning > 0, = 0, or < 0
979 //  as the comparison value
980
981 int keycmp (BtKey key1, unsigned char *key2, uint len2)
982 {
983 uint len1 = key1->len;
984 int ans;
985
986         if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
987                 return ans;
988
989         if( len1 > len2 )
990                 return 1;
991         if( len1 < len2 )
992                 return -1;
993
994         return 0;
995 }
996
997 //      Buffer Pool mgr
998
999 // find segment in pool
1000 // must be called with hashslot idx locked
1001 //      return NULL if not there
1002 //      otherwise return node
1003
1004 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
1005 {
1006 BtPool *pool;
1007 uint slot;
1008
1009         // compute start of hash chain in pool
1010
1011         if( slot = bt->mgr->hash[idx] ) 
1012                 pool = bt->mgr->pool + slot;
1013         else
1014                 return NULL;
1015
1016         page_no &= ~bt->mgr->poolmask;
1017
1018         while( pool->basepage != page_no )
1019           if( pool = pool->hashnext )
1020                 continue;
1021           else
1022                 return NULL;
1023
1024         return pool;
1025 }
1026
1027 // add segment to hash table
1028
1029 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
1030 {
1031 BtPool *node;
1032 uint slot;
1033
1034         pool->hashprev = pool->hashnext = NULL;
1035         pool->basepage = page_no & ~bt->mgr->poolmask;
1036         pool->lru = 1;
1037
1038         if( slot = bt->mgr->hash[idx] ) {
1039                 node = bt->mgr->pool + slot;
1040                 pool->hashnext = node;
1041                 node->hashprev = pool;
1042         }
1043
1044         bt->mgr->hash[idx] = pool->slot;
1045 }
1046
1047 //      find best segment to evict from buffer pool
1048
1049 BtPool *bt_findlru (BtDb *bt, uint hashslot)
1050 {
1051 unsigned long long int target = ~0LL;
1052 BtPool *pool = NULL, *node;
1053
1054         if( !hashslot )
1055                 return NULL;
1056
1057         node = bt->mgr->pool + hashslot;
1058
1059         //  scan pool entries under hash table slot
1060
1061         do {
1062           if( node->pin )
1063                 continue;
1064           if( node->lru > target )
1065                 continue;
1066           target = node->lru;
1067           pool = node;
1068         } while( node = node->hashnext );
1069
1070         return pool;
1071 }
1072
1073 //  map new buffer pool segment to virtual memory
1074
1075 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
1076 {
1077 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
1078 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
1079 int flag;
1080
1081 #ifdef unix
1082         flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
1083         pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED | MAP_POPULATE, bt->mgr->idx, off);
1084         if( pool->map == MAP_FAILED )
1085                 return bt->err = BTERR_map;
1086
1087 #else
1088         flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
1089         pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
1090         if( !pool->hmap )
1091                 return bt->err = BTERR_map;
1092
1093         flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
1094         pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1095         if( !pool->map )
1096                 return bt->err = BTERR_map;
1097 #endif
1098         return bt->err = 0;
1099 }
1100
1101 //      calculate page within pool
1102
1103 BtPage bt_page (BtDb *bt, BtPool *pool, uid page_no)
1104 {
1105 uint subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1106 BtPage page;
1107
1108         page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1109         return page;
1110 }
1111
1112 //  release pool pin
1113
1114 void bt_unpinpool (BtPool *pool)
1115 {
1116 #ifdef unix
1117         __sync_fetch_and_add(&pool->pin, -1);
1118 #else
1119         _InterlockedDecrement16 (&pool->pin);
1120 #endif
1121 }
1122
1123 //      find or place requested page in segment-pool
1124 //      return pool table entry, incrementing pin
1125
1126 BtPool *bt_pinpool(BtDb *bt, uid page_no)
1127 {
1128 BtPool *pool, *node, *next;
1129 uint slot, idx, victim;
1130
1131         //      lock hash table chain
1132
1133         idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1134         bt_spinreadlock (&bt->mgr->latch[idx]);
1135
1136         //      look up in hash table
1137
1138         if( pool = bt_findpool(bt, page_no, idx) ) {
1139 #ifdef unix
1140                 __sync_fetch_and_add(&pool->pin, 1);
1141 #else
1142                 _InterlockedIncrement16 (&pool->pin);
1143 #endif
1144                 bt_spinreleaseread (&bt->mgr->latch[idx]);
1145                 pool->lru++;
1146                 return pool;
1147         }
1148
1149         //      upgrade to write lock
1150
1151         bt_spinreleaseread (&bt->mgr->latch[idx]);
1152         bt_spinwritelock (&bt->mgr->latch[idx]);
1153
1154         // try to find page in pool with write lock
1155
1156         if( pool = bt_findpool(bt, page_no, idx) ) {
1157 #ifdef unix
1158                 __sync_fetch_and_add(&pool->pin, 1);
1159 #else
1160                 _InterlockedIncrement16 (&pool->pin);
1161 #endif
1162                 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1163                 pool->lru++;
1164                 return pool;
1165         }
1166
1167         // allocate a new pool node
1168         // and add to hash table
1169
1170 #ifdef unix
1171         slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
1172 #else
1173         slot = _InterlockedIncrement16 (&bt->mgr->poolcnt) - 1;
1174 #endif
1175
1176         if( ++slot < bt->mgr->poolmax ) {
1177                 pool = bt->mgr->pool + slot;
1178                 pool->slot = slot;
1179
1180                 if( bt_mapsegment(bt, pool, page_no) )
1181                         return NULL;
1182
1183                 bt_linkhash(bt, pool, page_no, idx);
1184 #ifdef unix
1185                 __sync_fetch_and_add(&pool->pin, 1);
1186 #else
1187                 _InterlockedIncrement16 (&pool->pin);
1188 #endif
1189                 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1190                 return pool;
1191         }
1192
1193         // pool table is full
1194         //      find best pool entry to evict
1195
1196 #ifdef unix
1197         __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
1198 #else
1199         _InterlockedDecrement16 (&bt->mgr->poolcnt);
1200 #endif
1201
1202         while( 1 ) {
1203 #ifdef unix
1204                 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
1205 #else
1206                 victim = _InterlockedIncrement (&bt->mgr->evicted) - 1;
1207 #endif
1208                 victim %= bt->mgr->hashsize;
1209
1210                 // try to get write lock
1211                 //      skip entry if not obtained
1212
1213                 if( !bt_spinwritetry (&bt->mgr->latch[victim]) )
1214                         continue;
1215
1216                 //  if pool entry is empty
1217                 //      or any pages are pinned
1218                 //      skip this entry
1219
1220                 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
1221                         bt_spinreleasewrite (&bt->mgr->latch[victim]);
1222                         continue;
1223                 }
1224
1225                 // unlink victim pool node from hash table
1226
1227                 if( node = pool->hashprev )
1228                         node->hashnext = pool->hashnext;
1229                 else if( node = pool->hashnext )
1230                         bt->mgr->hash[victim] = node->slot;
1231                 else
1232                         bt->mgr->hash[victim] = 0;
1233
1234                 if( node = pool->hashnext )
1235                         node->hashprev = pool->hashprev;
1236
1237                 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1238
1239                 //      remove old file mapping
1240 #ifdef unix
1241                 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1242 #else
1243                 FlushViewOfFile(pool->map, 0);
1244                 UnmapViewOfFile(pool->map);
1245                 CloseHandle(pool->hmap);
1246 #endif
1247                 pool->map = NULL;
1248
1249                 //  create new pool mapping
1250                 //  and link into hash table
1251
1252                 if( bt_mapsegment(bt, pool, page_no) )
1253                         return NULL;
1254
1255                 bt_linkhash(bt, pool, page_no, idx);
1256 #ifdef unix
1257                 __sync_fetch_and_add(&pool->pin, 1);
1258 #else
1259                 _InterlockedIncrement16 (&pool->pin);
1260 #endif
1261                 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1262                 return pool;
1263         }
1264 }
1265
1266 // place write, read, or parent lock on requested page_no.
1267
1268 void bt_lockpage(BtLock mode, BtLatchSet *set)
1269 {
1270         switch( mode ) {
1271         case BtLockRead:
1272                 bt_spinreadlock (set->readwr);
1273                 break;
1274         case BtLockWrite:
1275                 bt_spinwritelock (set->readwr);
1276                 break;
1277         case BtLockAccess:
1278                 bt_spinreadlock (set->access);
1279                 break;
1280         case BtLockDelete:
1281                 bt_spinwritelock (set->access);
1282                 break;
1283         case BtLockParent:
1284                 bt_spinwritelock (set->parent);
1285                 break;
1286         }
1287 }
1288
1289 // remove write, read, or parent lock on requested page
1290
1291 void bt_unlockpage(BtLock mode, BtLatchSet *set)
1292 {
1293         switch( mode ) {
1294         case BtLockRead:
1295                 bt_spinreleaseread (set->readwr);
1296                 break;
1297         case BtLockWrite:
1298                 bt_spinreleasewrite (set->readwr);
1299                 break;
1300         case BtLockAccess:
1301                 bt_spinreleaseread (set->access);
1302                 break;
1303         case BtLockDelete:
1304                 bt_spinreleasewrite (set->access);
1305                 break;
1306         case BtLockParent:
1307                 bt_spinreleasewrite (set->parent);
1308                 break;
1309         }
1310 }
1311
1312 //      allocate a new page and write page into it
1313
1314 uid bt_newpage(BtDb *bt, BtPage page)
1315 {
1316 BtPageSet set[1];
1317 uid new_page;
1318 int reuse;
1319
1320         //      lock allocation page
1321
1322         bt_spinwritelock(bt->mgr->latchmgr->lock);
1323
1324         // use empty chain first
1325         // else allocate empty page
1326
1327         if( new_page = bt_getid(bt->mgr->latchmgr->alloc[1].right) ) {
1328                 if( set->pool = bt_pinpool (bt, new_page) )
1329                         set->page = bt_page (bt, set->pool, new_page);
1330                 else
1331                         return 0;
1332
1333                 bt_putid(bt->mgr->latchmgr->alloc[1].right, bt_getid(set->page->right));
1334                 bt_unpinpool (set->pool);
1335                 reuse = 1;
1336         } else {
1337                 new_page = bt_getid(bt->mgr->latchmgr->alloc->right);
1338                 bt_putid(bt->mgr->latchmgr->alloc->right, new_page+1);
1339                 reuse = 0;
1340         }
1341 #ifdef unix
1342         if ( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1343                 return bt->err = BTERR_wrt, 0;
1344
1345         // if writing first page of pool block, zero last page in the block
1346
1347         if ( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1348         {
1349                 // use zero buffer to write zeros
1350                 if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1351                         return bt->err = BTERR_wrt, 0;
1352         }
1353 #else
1354         //      bring new page into pool and copy page.
1355         //      this will extend the file into the new pages.
1356
1357         if( set->pool = bt_pinpool (bt, new_page) )
1358                 set->page = bt_page (bt, set->pool, new_page);
1359         else
1360                 return 0;
1361
1362         memcpy(set->page, page, bt->mgr->page_size);
1363         bt_unpinpool (set->pool);
1364 #endif
1365         // unlock allocation latch and return new page no
1366
1367         bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1368         return new_page;
1369 }
1370
1371 //  find slot in page for given key at a given level
1372
1373 int bt_findslot (BtPageSet *set, unsigned char *key, uint len)
1374 {
1375 uint diff, higher = set->page->cnt, low = 1, slot;
1376
1377         //        make stopper key an infinite fence value
1378
1379         if( bt_getid (set->page->right) )
1380                 higher++;
1381
1382         //      low is the lowest candidate.
1383         //  loop ends when they meet
1384
1385         //  higher is already
1386         //      tested as .ge. the given key.
1387
1388         while( diff = higher - low ) {
1389                 slot = low + ( diff >> 1 );
1390                 if( keycmp (keyptr(set->page, slot), key, len) < 0 )
1391                         low = slot + 1;
1392                 else
1393                         higher = slot;
1394         }
1395
1396         if( higher <= set->page->cnt )
1397                 return higher;
1398
1399         //      if leaf page, compare against fence value
1400
1401         //      return zero if key is on right link page
1402         //      or return slot beyond last key
1403
1404         if( set->page->lvl || keycmp ((BtKey)set->page->fence, key, len) < 0 )
1405                 return 0;
1406
1407         return higher;
1408 }
1409
1410 //  find and load page at given level for given key
1411 //      leave page rd or wr locked as requested
1412
1413 int bt_loadpage (BtDb *bt, BtPageSet *set, unsigned char *key, uint len, uint lvl, uint lock)
1414 {
1415 uid page_no = ROOT_page, prevpage = 0;
1416 uint drill = 0xff, slot;
1417 BtLatchSet *prevlatch;
1418 uint mode, prevmode;
1419 BtPool *prevpool;
1420
1421   //  start at root of btree and drill down
1422
1423   do {
1424         // determine lock mode of drill level
1425         mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead; 
1426
1427         set->latch = bt_pinlatch (bt, page_no);
1428         set->page_no = page_no;
1429
1430         // pin page contents
1431
1432         if( set->pool = bt_pinpool (bt, page_no) )
1433                 set->page = bt_page (bt, set->pool, page_no);
1434         else
1435                 return 0;
1436
1437         // obtain access lock using lock chaining with Access mode
1438
1439         if( page_no > ROOT_page )
1440           bt_lockpage(BtLockAccess, set->latch);
1441
1442         //      release & unpin parent page
1443
1444         if( prevpage ) {
1445           bt_unlockpage(prevmode, prevlatch);
1446           bt_unpinlatch (prevlatch);
1447           bt_unpinpool (prevpool);
1448           prevpage = 0;
1449         }
1450
1451         // obtain read lock using lock chaining
1452
1453         bt_lockpage(mode, set->latch);
1454
1455         if( page_no > ROOT_page )
1456           bt_unlockpage(BtLockAccess, set->latch);
1457
1458         // re-read and re-lock root after determining actual level of root
1459
1460         if( set->page->lvl != drill) {
1461                 if ( set->page_no != ROOT_page )
1462                         return bt->err = BTERR_struct, 0;
1463                         
1464                 drill = set->page->lvl;
1465
1466                 if( lock == BtLockWrite && drill == lvl ) {
1467                   bt_unlockpage(mode, set->latch);
1468                   bt_unpinlatch (set->latch);
1469                   bt_unpinpool (set->pool);
1470                   continue;
1471                 }
1472         }
1473
1474         prevpage = set->page_no;
1475         prevlatch = set->latch;
1476         prevpool = set->pool;
1477         prevmode = mode;
1478
1479         //      if page is being deleted and we should continue right
1480
1481         if( set->page->kill && set->page->goright ) {
1482                 page_no = bt_getid (set->page->right);
1483                 continue;
1484         }
1485
1486         //      otherwise, wait for deleted node to clear
1487
1488         if( set->page->kill ) {
1489                 bt_unlockpage(mode, set->latch);
1490                 bt_unpinlatch (set->latch);
1491                 bt_unpinpool (set->pool);
1492                 page_no = ROOT_page;
1493                 prevpage = 0;
1494                 drill = 0xff;
1495 #ifdef unix
1496                 sched_yield();
1497 #else
1498                 SwitchToThread();
1499 #endif
1500                 continue;
1501         }
1502         
1503         //  find key on page at this level
1504         //  and descend to requested level
1505
1506         if( slot = bt_findslot (set, key, len) ) {
1507           if( drill == lvl )
1508                 return slot;
1509
1510           if( slot > set->page->cnt )
1511                 return bt->err = BTERR_struct;
1512
1513           while( slotptr(set->page, slot)->dead )
1514                 if( slot++ < set->page->cnt )
1515                         continue;
1516                 else
1517                         return bt->err = BTERR_struct, 0;
1518
1519           page_no = bt_getid(slotptr(set->page, slot)->id);
1520           drill--;
1521           continue;
1522         }
1523
1524         //  or slide right into next page
1525
1526         page_no = bt_getid(set->page->right);
1527
1528   } while( page_no );
1529
1530   // return error on end of right chain
1531
1532   bt->err = BTERR_struct;
1533   return 0;     // return error
1534 }
1535
1536 // drill down fixing fence values for left sibling tree
1537
1538 //  call with set write locked
1539 //      return with set unlocked & unpinned.
1540
1541 BTERR bt_fixfences (BtDb *bt, BtPageSet *set, unsigned char *newfence)
1542 {
1543 unsigned char oldfence[256];
1544 BtPageSet next[1];
1545 int chk;
1546
1547   memcpy (oldfence, set->page->fence, 256);
1548
1549   while( !set->page->kill && set->page->lvl ) {
1550         next->page_no = bt_getid(slotptr(set->page, set->page->cnt)->id);
1551         next->latch = bt_pinlatch (bt, next->page_no);
1552         bt_lockpage (BtLockParent, next->latch);
1553         bt_lockpage (BtLockAccess, next->latch);
1554         bt_lockpage (BtLockWrite, next->latch);
1555         bt_unlockpage (BtLockAccess, next->latch);
1556
1557         if( next->pool = bt_pinpool (bt, next->page_no) )
1558                 next->page = bt_page (bt, next->pool, next->page_no);
1559         else
1560                 return bt->err;
1561
1562         chk = keycmp ((BtKey)next->page->fence, oldfence + 1, *oldfence);
1563
1564         if( chk < 0 ) {
1565           next->page_no = bt_getid (next->page->right);
1566           bt_unlockpage (BtLockWrite, next->latch);
1567           bt_unlockpage (BtLockParent, next->latch);
1568           bt_unpinlatch (next->latch);
1569           bt_unpinpool (next->pool);
1570           continue;
1571         }
1572
1573         if( chk > 0 )
1574                 return bt->err = BTERR_struct;
1575
1576         if( bt_fixfences (bt, next, newfence) )
1577                 return bt->err;
1578
1579         break;
1580   }
1581
1582   memcpy (set->page->fence, newfence, 256);
1583
1584   bt_unlockpage (BtLockWrite, set->latch);
1585   bt_unlockpage (BtLockParent, set->latch);
1586   bt_unpinlatch (set->latch);
1587   bt_unpinpool (set->pool);
1588   return 0;
1589 }
1590
1591 //      return page to free list
1592 //      page must be delete & write locked
1593
1594 void bt_freepage (BtDb *bt, BtPageSet *set)
1595 {
1596         //      lock allocation page
1597
1598         bt_spinwritelock (bt->mgr->latchmgr->lock);
1599
1600         //      store chain in second right
1601         bt_putid(set->page->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1602         bt_putid(bt->mgr->latchmgr->alloc[1].right, set->page_no);
1603         set->page->free = 1;
1604
1605         // unlock released page
1606
1607         bt_unlockpage (BtLockDelete, set->latch);
1608         bt_unlockpage (BtLockWrite, set->latch);
1609         bt_unpinlatch (set->latch);
1610         bt_unpinpool (set->pool);
1611
1612         // unlock allocation page
1613
1614         bt_spinreleasewrite (bt->mgr->latchmgr->lock);
1615 }
1616
1617 //      remove the root level by promoting its only child
1618 //      call with parent and child pages
1619
1620 BTERR bt_removeroot (BtDb *bt, BtPageSet *root, BtPageSet *child)
1621 {
1622 uid next = 0;
1623
1624   do {
1625         if( next ) {
1626           child->latch = bt_pinlatch (bt, next);
1627           bt_lockpage (BtLockDelete, child->latch);
1628           bt_lockpage (BtLockWrite, child->latch);
1629
1630           if( child->pool = bt_pinpool (bt, next) )
1631                 child->page = bt_page (bt, child->pool, next);
1632           else
1633                 return bt->err;
1634
1635           child->page_no = next;
1636         }
1637
1638         memcpy (root->page, child->page, bt->mgr->page_size);
1639         next = bt_getid (slotptr(child->page, child->page->cnt)->id);
1640         bt_freepage (bt, child);
1641   } while( root->page->lvl > 1 && root->page->cnt == 1 );
1642
1643   bt_unlockpage (BtLockWrite, root->latch);
1644   bt_unpinlatch (root->latch);
1645   bt_unpinpool (root->pool);
1646   return 0;
1647 }
1648
1649 //  pull right page over ourselves in simple merge
1650
1651 BTERR bt_mergeright (BtDb *bt, BtPageSet *set, BtPageSet *parent, BtPageSet *right, uint slot, uint idx)
1652 {
1653         //  install ourselves as child page
1654         //      and delete ourselves from parent
1655
1656         bt_putid (slotptr(parent->page, idx)->id, set->page_no);
1657         slotptr(parent->page, slot)->dead = 1;
1658         parent->page->act--;
1659
1660         //      collapse any empty slots
1661
1662         while( idx = parent->page->cnt - 1 )
1663           if( slotptr(parent->page, idx)->dead ) {
1664                 *slotptr(parent->page, idx) = *slotptr(parent->page, idx + 1);
1665                 memset (slotptr(parent->page, parent->page->cnt--), 0, sizeof(BtSlot));
1666           } else
1667                   break;
1668
1669         memcpy (set->page, right->page, bt->mgr->page_size);
1670         bt_unlockpage (BtLockParent, right->latch);
1671
1672         bt_freepage (bt, right);
1673
1674         //      do we need to remove a btree level?
1675         //      (leave the first page of leaves alone)
1676
1677         if( parent->page_no == ROOT_page && parent->page->cnt == 1 )
1678           if( set->page->lvl )
1679                 return bt_removeroot (bt, parent, set);
1680
1681         bt_unlockpage (BtLockWrite, parent->latch);
1682         bt_unlockpage (BtLockDelete, set->latch);
1683         bt_unlockpage (BtLockWrite, set->latch);
1684         bt_unpinlatch (parent->latch);
1685         bt_unpinpool (parent->pool);
1686         bt_unpinlatch (set->latch);
1687         bt_unpinpool (set->pool);
1688         return 0;
1689 }
1690
1691 //      remove both child and parent from the btree
1692 //      from the fence position in the parent
1693 //      call with both pages locked for writing
1694
1695 BTERR bt_removeparent (BtDb *bt, BtPageSet *child, BtPageSet *parent, BtPageSet *right, BtPageSet *rparent, uint lvl)
1696 {
1697 unsigned char pagefence[256];
1698 uint idx;
1699
1700         //  pull right sibling over ourselves and unlock
1701
1702         memcpy (child->page, right->page, bt->mgr->page_size);
1703
1704         bt_unlockpage (BtLockWrite, child->latch);
1705         bt_unpinlatch (child->latch);
1706         bt_unpinpool (child->pool);
1707
1708         //  install ourselves into right link of old right page
1709
1710         bt_putid (right->page->right, child->page_no);
1711         right->page->goright = 1;       // tell bt_loadpage to go right to us
1712         right->page->kill = 1;
1713
1714         bt_unlockpage (BtLockWrite, right->latch);
1715
1716         //      remove our slot from our parent
1717         //      signal to move right
1718
1719         parent->page->goright = 1;      // tell bt_loadpage to go right to rparent
1720         parent->page->kill = 1;
1721         parent->page->act--;
1722
1723         //      redirect right page pointer in right parent to us
1724
1725         for( idx = 0; idx++ < rparent->page->cnt; )
1726           if( !slotptr(rparent->page, idx)->dead )
1727                 break;
1728
1729         if( bt_getid (slotptr(rparent->page, idx)->id) != right->page_no )
1730                 return bt->err = BTERR_struct;
1731
1732         bt_putid (slotptr(rparent->page, idx)->id, child->page_no);
1733         bt_unlockpage (BtLockWrite, rparent->latch);
1734         bt_unpinlatch (rparent->latch);
1735         bt_unpinpool (rparent->pool);
1736
1737         //      free the right page
1738
1739         bt_lockpage (BtLockDelete, right->latch);
1740         bt_lockpage (BtLockWrite, right->latch);
1741         bt_freepage (bt, right);
1742
1743         //      save parent page fence value
1744
1745         memcpy (pagefence, parent->page->fence, 256);
1746         bt_unlockpage (BtLockWrite, parent->latch);
1747
1748         return bt_removepage (bt, parent, lvl, pagefence);
1749 }
1750
1751 //      remove page from btree
1752 //      call with page unlocked
1753 //      returns with page on free list
1754
1755 BTERR bt_removepage (BtDb *bt, BtPageSet *set, uint lvl, unsigned char *pagefence)
1756 {
1757 BtPageSet parent[1], sibling[1], rparent[1];
1758 unsigned char newfence[256];
1759 uint slot, idx;
1760 BtKey ptr;
1761
1762         //      load and lock our parent
1763
1764 retry:
1765         if( !(slot = bt_loadpage (bt, parent, pagefence+1, *pagefence, lvl+1, BtLockWrite)) )
1766                 return bt->err;
1767
1768         //      can we do a simple merge entirely
1769         //      between siblings on the parent page?
1770
1771         if( slot < parent->page->cnt ) {
1772                 // find our right neighbor
1773                 //      right must exist because the stopper prevents
1774                 //      the rightmost page from deleting
1775
1776                 for( idx = slot; idx++ < parent->page->cnt; )
1777                   if( !slotptr(parent->page, idx)->dead )
1778                         break;
1779
1780                 sibling->page_no = bt_getid (slotptr (parent->page, idx)->id);
1781
1782                 bt_lockpage (BtLockDelete, set->latch);
1783                 bt_lockpage (BtLockWrite, set->latch);
1784
1785                 //      merge right if sibling shows up in
1786                 //  our parent and is not being killed
1787
1788                 if( sibling->page_no == bt_getid (set->page->right) ) {
1789                   sibling->latch = bt_pinlatch (bt, sibling->page_no);
1790                   bt_lockpage (BtLockParent, sibling->latch);
1791                   bt_lockpage (BtLockDelete, sibling->latch);
1792                   bt_lockpage (BtLockWrite, sibling->latch);
1793
1794                   if( sibling->pool = bt_pinpool (bt, sibling->page_no) )
1795                         sibling->page = bt_page (bt, sibling->pool, sibling->page_no);
1796                   else
1797                         return bt->err;
1798
1799                   if( !sibling->page->kill )
1800                         return bt_mergeright(bt, set, parent, sibling, slot, idx);
1801
1802                   //  try again later
1803
1804                   bt_unlockpage (BtLockWrite, sibling->latch);
1805                   bt_unlockpage (BtLockParent, sibling->latch);
1806                   bt_unlockpage (BtLockDelete, sibling->latch);
1807                   bt_unpinlatch (sibling->latch);
1808                   bt_unpinpool (sibling->pool);
1809                 }
1810
1811                 bt_unlockpage (BtLockDelete, set->latch);
1812                 bt_unlockpage (BtLockWrite, set->latch);
1813                 bt_unlockpage (BtLockWrite, parent->latch);
1814                 bt_unpinlatch (parent->latch);
1815                 bt_unpinpool (parent->pool);
1816 #ifdef linux
1817                 sched_yield();
1818 #else
1819                 SwitchToThread();
1820 #endif
1821                 goto retry;
1822         }
1823
1824         //  find our left neighbor in our parent page
1825
1826         for( idx = slot; --idx; )
1827           if( !slotptr(parent->page, idx)->dead )
1828                 break;
1829
1830         //      if no left neighbor, delete ourselves and our parent
1831
1832         if( !idx ) {
1833                 bt_lockpage (BtLockAccess, set->latch);
1834                 bt_lockpage (BtLockWrite, set->latch);
1835                 bt_unlockpage (BtLockAccess, set->latch);
1836
1837                 rparent->page_no = bt_getid (parent->page->right);
1838                 rparent->latch = bt_pinlatch (bt, rparent->page_no);
1839
1840                 bt_lockpage (BtLockAccess, rparent->latch);
1841                 bt_lockpage (BtLockWrite, rparent->latch);
1842                 bt_unlockpage (BtLockAccess, rparent->latch);
1843
1844                 if( rparent->pool = bt_pinpool (bt, rparent->page_no) )
1845                         rparent->page = bt_page (bt, rparent->pool, rparent->page_no);
1846                 else
1847                         return bt->err;
1848
1849                 if( !rparent->page->kill ) {
1850                   sibling->page_no = bt_getid (set->page->right);
1851                   sibling->latch = bt_pinlatch (bt, sibling->page_no);
1852
1853                   bt_lockpage (BtLockAccess, sibling->latch);
1854                   bt_lockpage (BtLockWrite, sibling->latch);
1855                   bt_unlockpage (BtLockAccess, sibling->latch);
1856
1857                   if( sibling->pool = bt_pinpool (bt, sibling->page_no) )
1858                         sibling->page = bt_page (bt, sibling->pool, sibling->page_no);
1859                   else
1860                         return bt->err;
1861
1862                   if( !sibling->page->kill )
1863                         return bt_removeparent (bt, set, parent, sibling, rparent, lvl+1);
1864
1865                   //  try again later
1866
1867                   bt_unlockpage (BtLockWrite, sibling->latch);
1868                   bt_unpinlatch (sibling->latch);
1869                   bt_unpinpool (sibling->pool);
1870                 }
1871
1872                 bt_unlockpage (BtLockWrite, set->latch);
1873                 bt_unlockpage (BtLockWrite, rparent->latch);
1874                 bt_unpinlatch (rparent->latch);
1875                 bt_unpinpool (rparent->pool);
1876
1877                 bt_unlockpage (BtLockWrite, parent->latch);
1878                 bt_unpinlatch (parent->latch);
1879                 bt_unpinpool (parent->pool);
1880 #ifdef linux
1881                 sched_yield();
1882 #else
1883                 SwitchToThread();
1884 #endif
1885                 goto retry;
1886         }
1887
1888         // redirect parent to our left sibling
1889         // lock and map our left sibling's page
1890
1891         sibling->page_no = bt_getid (slotptr(parent->page, idx)->id);
1892         sibling->latch = bt_pinlatch (bt, sibling->page_no);
1893
1894         //      wait our turn on fence key maintenance
1895
1896         bt_lockpage(BtLockParent, sibling->latch);
1897         bt_lockpage(BtLockAccess, sibling->latch);
1898         bt_lockpage(BtLockWrite, sibling->latch);
1899         bt_unlockpage(BtLockAccess, sibling->latch);
1900
1901         if( sibling->pool = bt_pinpool (bt, sibling->page_no) )
1902                 sibling->page = bt_page (bt, sibling->pool, sibling->page_no);
1903         else
1904                 return bt->err;
1905
1906         //  wait until left sibling is in our parent
1907
1908         if( bt_getid (sibling->page->right) != set->page_no ) {
1909                 bt_unlockpage (BtLockWrite, parent->latch);
1910                 bt_unlockpage (BtLockWrite, sibling->latch);
1911                 bt_unlockpage (BtLockParent, sibling->latch);
1912                 bt_unpinlatch (parent->latch);
1913                 bt_unpinpool (parent->pool);
1914                 bt_unpinlatch (sibling->latch);
1915                 bt_unpinpool (sibling->pool);
1916 #ifdef linux
1917                 sched_yield();
1918 #else
1919                 SwitchToThread();
1920 #endif
1921                 goto retry;
1922         }
1923
1924         //      delete our left sibling from parent
1925
1926         slotptr(parent->page,idx)->dead = 1;
1927         parent->page->dirty = 1;
1928         parent->page->act--;
1929
1930         //      redirect our parent slot to our left sibling
1931
1932         bt_putid (slotptr(parent->page, slot)->id, sibling->page_no);
1933         memcpy (sibling->page->right, set->page->right, BtId);
1934
1935         //      collapse dead slots from parent
1936
1937         while( idx = parent->page->cnt - 1 )
1938           if( slotptr(parent->page, idx)->dead ) {
1939                 *slotptr(parent->page, idx) = *slotptr(parent->page, parent->page->cnt);
1940                 memset (slotptr(parent->page, parent->page->cnt--), 0, sizeof(BtSlot));
1941           } else
1942                   break;
1943
1944         //  free our original page
1945
1946         bt_lockpage (BtLockDelete, set->latch);
1947         bt_lockpage (BtLockWrite, set->latch);
1948         bt_freepage (bt, set);
1949
1950         //      go down the left node's fence keys to the leaf level
1951         //      and update the fence keys in each page
1952
1953         memcpy (newfence, parent->page->fence, 256);
1954
1955         if( bt_fixfences (bt, sibling, newfence) )
1956                 return bt->err;
1957
1958         //  promote sibling as new root?
1959
1960         if( parent->page_no == ROOT_page && parent->page->cnt == 1 )
1961          if( sibling->page->lvl ) {
1962           sibling->latch = bt_pinlatch (bt, sibling->page_no);
1963           bt_lockpage (BtLockDelete, sibling->latch);
1964           bt_lockpage (BtLockWrite, sibling->latch);
1965
1966           if( sibling->pool = bt_pinpool (bt, sibling->page_no) )
1967                 sibling->page = bt_page (bt, sibling->pool, sibling->page_no);
1968           else
1969                 return bt->err;
1970
1971           return bt_removeroot (bt, parent, sibling);
1972          }
1973
1974         bt_unlockpage (BtLockWrite, parent->latch);
1975         bt_unpinlatch (parent->latch);
1976         bt_unpinpool (parent->pool);
1977
1978         return 0;
1979 }
1980
1981 //  find and delete key on page by marking delete flag bit
1982 //  if page becomes empty, delete it from the btree
1983
1984 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len)
1985 {
1986 unsigned char pagefence[256];
1987 uint slot, idx, found;
1988 BtPageSet set[1];
1989 BtKey ptr;
1990
1991         if( slot = bt_loadpage (bt, set, key, len, 0, BtLockWrite) )
1992                 ptr = keyptr(set->page, slot);
1993         else
1994                 return bt->err;
1995
1996         // if key is found delete it, otherwise ignore request
1997
1998         if( found = slot <= set->page->cnt )
1999           if( found = !keycmp (ptr, key, len) )
2000                 if( found = slotptr(set->page, slot)->dead == 0 ) {
2001                   slotptr(set->page,slot)->dead = 1;
2002                   set->page->dirty = 1;
2003                   set->page->act--;
2004
2005                   // collapse empty slots
2006
2007                   while( idx = set->page->cnt - 1 )
2008                         if( slotptr(set->page, idx)->dead ) {
2009                           *slotptr(set->page, idx) = *slotptr(set->page, idx + 1);
2010                           memset (slotptr(set->page, set->page->cnt--), 0, sizeof(BtSlot));
2011                         } else
2012                                 break;
2013                 }
2014
2015         if( set->page->act ) {
2016                 bt_unlockpage(BtLockWrite, set->latch);
2017                 bt_unpinlatch (set->latch);
2018                 bt_unpinpool (set->pool);
2019                 return bt->found = found, 0;
2020         }
2021
2022         memcpy (pagefence, set->page->fence, 256);
2023         set->page->kill = 1;
2024
2025         bt_unlockpage (BtLockWrite, set->latch);
2026
2027         if( bt_removepage (bt, set, 0, pagefence) )
2028                 return bt->err;
2029
2030         bt->found = found;
2031         return 0;
2032 }
2033
2034 //      find key in leaf level and return row-id
2035
2036 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
2037 {
2038 BtPageSet set[1];
2039 uint  slot;
2040 BtKey ptr;
2041 uid id;
2042
2043         if( slot = bt_loadpage (bt, set, key, len, 0, BtLockRead) )
2044                 ptr = keyptr(set->page, slot);
2045         else
2046                 return 0;
2047
2048         // if key exists, return row-id
2049         //      otherwise return 0
2050
2051         if( !keycmp (ptr, key, len) )
2052                 id = bt_getid(slotptr(set->page,slot)->id);
2053         else
2054                 id = 0;
2055
2056         bt_unlockpage (BtLockRead, set->latch);
2057         bt_unpinlatch (set->latch);
2058         bt_unpinpool (set->pool);
2059         return id;
2060 }
2061
2062 //      check page for space available,
2063 //      clean if necessary and return
2064 //      0 - page needs splitting
2065 //      >0  new slot value
2066
2067 uint bt_cleanpage(BtDb *bt, BtPage page, uint amt, uint slot)
2068 {
2069 uint nxt = bt->mgr->page_size, off;
2070 uint cnt = 0, idx = 0;
2071 uint max = page->cnt;
2072 uint newslot = max;
2073 BtKey key;
2074
2075         if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
2076                 return slot;
2077
2078         //      skip cleanup if nothing to reclaim
2079
2080         if( !page->dirty )
2081                 return 0;
2082
2083         memcpy (bt->frame, page, bt->mgr->page_size);
2084
2085         // skip page info and set rest of page to zero
2086
2087         memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
2088         page->dirty = 0;
2089         page->act = 0;
2090
2091         // try cleaning up page first
2092         // by removing deleted keys
2093
2094         while( cnt++ < max ) {
2095                 if( cnt == slot )
2096                         newslot = idx + 1;
2097                 if( slotptr(bt->frame,cnt)->dead )
2098                         continue;
2099
2100                 // if its not the fence key,
2101                 // copy the key across
2102
2103                 off = slotptr(bt->frame,cnt)->off;
2104
2105                 if( off >= sizeof(*page) ) {
2106                         key = keyptr(bt->frame, cnt);
2107                         off = nxt -= key->len + 1;
2108                         memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2109                 }
2110
2111                 // copy slot
2112
2113                 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
2114                 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2115                 slotptr(page, idx)->off = off;
2116                 page->act++;
2117         }
2118
2119         page->min = nxt;
2120         page->cnt = idx;
2121
2122         //      see if page has enough space now, or does it need splitting?
2123
2124         if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
2125                 return newslot;
2126
2127         return 0;
2128 }
2129
2130 // split the root and raise the height of the btree
2131
2132 BTERR bt_splitroot(BtDb *bt, BtPageSet *root, uid page_no2)
2133 {
2134 uint nxt = bt->mgr->page_size;
2135 unsigned char leftkey[256];
2136 uid new_page;
2137
2138         //  Obtain an empty page to use, and copy the current
2139         //  root contents into it, e.g. lower keys
2140
2141         memcpy (leftkey, root->page->fence, 256);
2142         root->page->posted = 1;
2143
2144         if( !(new_page = bt_newpage(bt, root->page)) )
2145                 return bt->err;
2146
2147         // preserve the page info at the bottom
2148         // of higher keys and set rest to zero
2149
2150         memset(root->page+1, 0, bt->mgr->page_size - sizeof(*root->page));
2151         memset(root->page->fence, 0, 256);
2152         root->page->fence[0] = 2;
2153         root->page->fence[1] = 0xff;
2154         root->page->fence[2] = 0xff;
2155
2156         // insert lower keys page fence key on newroot page
2157
2158         nxt -= *leftkey + 1;
2159         memcpy ((unsigned char *)root->page + nxt, leftkey, *leftkey + 1);
2160         bt_putid(slotptr(root->page, 1)->id, new_page);
2161         slotptr(root->page, 1)->off = nxt;
2162         
2163         // insert stopper key on newroot page
2164         // and increase the root height
2165
2166         bt_putid(slotptr(root->page, 2)->id, page_no2);
2167         slotptr(root->page, 2)->off = offsetof(struct BtPage_, fence);
2168
2169         bt_putid(root->page->right, 0);
2170         root->page->min = nxt;          // reset lowest used offset and key count
2171         root->page->cnt = 2;
2172         root->page->act = 2;
2173         root->page->lvl++;
2174
2175         // release and unpin root
2176
2177         bt_unlockpage(BtLockWrite, root->latch);
2178         bt_unpinlatch (root->latch);
2179         bt_unpinpool (root->pool);
2180         return 0;
2181 }
2182
2183 //  split already locked full node
2184 //      return unlocked.
2185
2186 BTERR bt_splitpage (BtDb *bt, BtPageSet *set)
2187 {
2188 uint cnt = 0, idx = 0, max, nxt = bt->mgr->page_size, off;
2189 unsigned char fencekey[256];
2190 uint lvl = set->page->lvl;
2191 uid right;
2192 BtKey key;
2193
2194         //  split higher half of keys to bt->frame
2195
2196         memset (bt->frame, 0, bt->mgr->page_size);
2197         max = set->page->cnt;
2198         cnt = max / 2;
2199         idx = 0;
2200
2201         while( cnt++ < max ) {
2202                 if( !lvl || cnt < max ) {
2203                         key = keyptr(set->page, cnt);
2204                         off = nxt -= key->len + 1;
2205                         memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
2206                 } else
2207                         off = offsetof(struct BtPage_, fence);
2208
2209                 memcpy(slotptr(bt->frame,++idx)->id, slotptr(set->page,cnt)->id, BtId);
2210                 slotptr(bt->frame, idx)->tod = slotptr(set->page, cnt)->tod;
2211                 slotptr(bt->frame, idx)->off = off;
2212                 bt->frame->act++;
2213         }
2214
2215         if( set->page_no == ROOT_page )
2216                 bt->frame->posted = 1;
2217
2218         memcpy (bt->frame->fence, set->page->fence, 256);
2219         bt->frame->bits = bt->mgr->page_bits;
2220         bt->frame->min = nxt;
2221         bt->frame->cnt = idx;
2222         bt->frame->lvl = lvl;
2223
2224         // link right node
2225
2226         if( set->page_no > ROOT_page )
2227                 memcpy (bt->frame->right, set->page->right, BtId);
2228
2229         //      get new free page and write higher keys to it.
2230
2231         if( !(right = bt_newpage(bt, bt->frame)) )
2232                 return bt->err;
2233
2234         //      update lower keys to continue in old page
2235
2236         memcpy (bt->frame, set->page, bt->mgr->page_size);
2237         memset (set->page+1, 0, bt->mgr->page_size - sizeof(*set->page));
2238         nxt = bt->mgr->page_size;
2239         set->page->posted = 0;
2240         set->page->dirty = 0;
2241         set->page->act = 0;
2242         cnt = 0;
2243         idx = 0;
2244
2245         //  assemble page of smaller keys
2246
2247         while( cnt++ < max / 2 ) {
2248                 key = keyptr(bt->frame, cnt);
2249
2250                 if( !lvl || cnt < max / 2 ) {
2251                         off = nxt -= key->len + 1;
2252                         memcpy ((unsigned char *)set->page + nxt, key, key->len + 1);
2253                 } else 
2254                         off = offsetof(struct BtPage_, fence);
2255
2256                 memcpy(slotptr(set->page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
2257                 slotptr(set->page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2258                 slotptr(set->page, idx)->off = off;
2259                 set->page->act++;
2260         }
2261
2262         // install fence key for smaller key page
2263
2264         memset(set->page->fence, 0, 256);
2265         memcpy(set->page->fence, key, key->len + 1);
2266
2267         bt_putid(set->page->right, right);
2268         set->page->min = nxt;
2269         set->page->cnt = idx;
2270
2271         // if current page is the root page, split it
2272
2273         if( set->page_no == ROOT_page )
2274                 return bt_splitroot (bt, set, right);
2275
2276         bt_unlockpage (BtLockWrite, set->latch);
2277
2278         // insert new fences in their parent pages
2279
2280         while( 1 ) {
2281                 bt_lockpage (BtLockParent, set->latch);
2282                 bt_lockpage (BtLockWrite, set->latch);
2283
2284                 memcpy (fencekey, set->page->fence, 256);
2285                 right = bt_getid (set->page->right);
2286
2287                 if( set->page->posted ) {
2288                         bt_unlockpage (BtLockParent, set->latch);
2289                         bt_unlockpage (BtLockWrite, set->latch);
2290                         bt_unpinlatch (set->latch);
2291                         bt_unpinpool (set->pool);
2292                         return 0;
2293                 }
2294
2295                 set->page->posted = 1;
2296                 bt_unlockpage (BtLockWrite, set->latch);
2297
2298                 if( bt_insertkey (bt, fencekey+1, *fencekey, set->page_no, time(NULL), lvl+1) )
2299                         return bt->err;
2300
2301                 bt_unlockpage (BtLockParent, set->latch);
2302                 bt_unpinlatch (set->latch);
2303                 bt_unpinpool (set->pool);
2304
2305                 if( !(set->page_no = right) )
2306                         break;
2307
2308                 set->latch = bt_pinlatch (bt, right);
2309
2310                 if( set->pool = bt_pinpool (bt, right) )
2311                         set->page = bt_page (bt, set->pool, right);
2312                 else
2313                         return bt->err;
2314         }
2315
2316         return 0;
2317 }
2318
2319 //  Insert new key into the btree at given level.
2320
2321 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod, uint lvl)
2322 {
2323 BtPageSet set[1];
2324 uint slot, idx;
2325 BtKey ptr;
2326
2327         while( 1 ) {
2328                 if( slot = bt_loadpage (bt, set, key, len, lvl, BtLockWrite) )
2329                         ptr = keyptr(set->page, slot);
2330                 else
2331                 {
2332                         if ( !bt->err )
2333                                 bt->err = BTERR_ovflw;
2334                         return bt->err;
2335                 }
2336
2337                 // if key already exists, update id and return
2338
2339                 if( slot <= set->page->cnt )
2340                   if( !keycmp (ptr, key, len) ) {
2341                         if( slotptr(set->page, slot)->dead )
2342                                 set->page->act++;
2343                         slotptr(set->page, slot)->dead = 0;
2344                         slotptr(set->page, slot)->tod = tod;
2345                         bt_putid(slotptr(set->page,slot)->id, id);
2346                         bt_unlockpage(BtLockWrite, set->latch);
2347                         bt_unpinlatch (set->latch);
2348                         bt_unpinpool (set->pool);
2349                         return 0;
2350                 }
2351
2352                 // check if page has enough space
2353
2354                 if( slot = bt_cleanpage (bt, set->page, len, slot) )
2355                         break;
2356
2357                 if( bt_splitpage (bt, set) )
2358                         return bt->err;
2359         }
2360
2361         // calculate next available slot and copy key into page
2362
2363         set->page->min -= len + 1; // reset lowest used offset
2364         ((unsigned char *)set->page)[set->page->min] = len;
2365         memcpy ((unsigned char *)set->page + set->page->min +1, key, len );
2366
2367         for( idx = slot; idx <= set->page->cnt; idx++ )
2368           if( slotptr(set->page, idx)->dead )
2369                 break;
2370
2371         // now insert key into array before slot
2372
2373         if( idx > set->page->cnt )
2374                 set->page->cnt++;
2375
2376         set->page->act++;
2377
2378         while( idx > slot )
2379                 *slotptr(set->page, idx) = *slotptr(set->page, idx -1), idx--;
2380
2381         bt_putid(slotptr(set->page,slot)->id, id);
2382         slotptr(set->page, slot)->off = set->page->min;
2383         slotptr(set->page, slot)->tod = tod;
2384         slotptr(set->page, slot)->dead = 0;
2385
2386         bt_unlockpage (BtLockWrite, set->latch);
2387         bt_unpinlatch (set->latch);
2388         bt_unpinpool (set->pool);
2389         return 0;
2390 }
2391
2392 //  cache page of keys into cursor and return starting slot for given key
2393
2394 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2395 {
2396 BtPageSet set[1];
2397 uint slot;
2398
2399         // cache page for retrieval
2400
2401         if( slot = bt_loadpage (bt, set, key, len, 0, BtLockRead) )
2402           memcpy (bt->cursor, set->page, bt->mgr->page_size);
2403         else
2404           return 0;
2405
2406         bt->cursor_page = set->page_no;
2407
2408         bt_unlockpage(BtLockRead, set->latch);
2409         bt_unpinlatch (set->latch);
2410         bt_unpinpool (set->pool);
2411         return slot;
2412 }
2413
2414 //  return next slot for cursor page
2415 //  or slide cursor right into next page
2416
2417 uint bt_nextkey (BtDb *bt, uint slot)
2418 {
2419 BtPageSet set[1];
2420 uid right;
2421
2422   do {
2423         right = bt_getid(bt->cursor->right);
2424         while( slot++ < bt->cursor->cnt )
2425           if( slotptr(bt->cursor,slot)->dead )
2426                 continue;
2427           else if( right || (slot < bt->cursor->cnt) ) // skip infinite stopper
2428                 return slot;
2429           else
2430                 break;
2431
2432         if( !right )
2433                 break;
2434
2435         bt->cursor_page = right;
2436
2437         if( set->pool = bt_pinpool (bt, right) )
2438                 set->page = bt_page (bt, set->pool, right);
2439         else
2440                 return 0;
2441
2442         set->latch = bt_pinlatch (bt, right);
2443     bt_lockpage(BtLockRead, set->latch);
2444
2445         memcpy (bt->cursor, set->page, bt->mgr->page_size);
2446
2447         bt_unlockpage(BtLockRead, set->latch);
2448         bt_unpinlatch (set->latch);
2449         bt_unpinpool (set->pool);
2450         slot = 0;
2451   } while( 1 );
2452
2453   return bt->err = 0;
2454 }
2455
2456 BtKey bt_key(BtDb *bt, uint slot)
2457 {
2458         return keyptr(bt->cursor, slot);
2459 }
2460
2461 uid bt_uid(BtDb *bt, uint slot)
2462 {
2463         return bt_getid(slotptr(bt->cursor,slot)->id);
2464 }
2465
2466 uint bt_tod(BtDb *bt, uint slot)
2467 {
2468         return slotptr(bt->cursor,slot)->tod;
2469 }
2470
2471
2472 #ifdef STANDALONE
2473
2474 void bt_latchaudit (BtDb *bt)
2475 {
2476 ushort idx, hashidx;
2477 BtLatchSet *latch;
2478 BtPool *pool;
2479 BtPage page;
2480 uid page_no;
2481
2482 #ifdef unix
2483         for( idx = 1; idx < bt->mgr->latchmgr->latchdeployed; idx++ ) {
2484                 latch = bt->mgr->latchsets + idx;
2485                 if( *(ushort *)latch->readwr ) {
2486                         fprintf(stderr, "latchset %d r/w locked for page %.8x\n", idx, latch->page_no);
2487                         *(ushort *)latch->readwr = 0;
2488                 }
2489                 if( *(ushort *)latch->access ) {
2490                         fprintf(stderr, "latchset %d access locked for page %.8x\n", idx, latch->page_no);
2491                         *(ushort *)latch->access = 0;
2492                 }
2493                 if( *(ushort *)latch->parent ) {
2494                         fprintf(stderr, "latchset %d parent locked for page %.8x\n", idx, latch->page_no);
2495                         *(ushort *)latch->parent = 0;
2496                 }
2497                 if( *(ushort *)latch->busy ) {
2498                         fprintf(stderr, "latchset %d busy locked for page %.8x\n", idx, latch->page_no);
2499                         *(ushort *)latch->parent = 0;
2500                 }
2501                 if( latch->pin ) {
2502                         fprintf(stderr, "latchset %d pinned for page %.8x\n", idx, latch->page_no);
2503                         latch->pin = 0;
2504                 }
2505         }
2506
2507         for( hashidx = 0; hashidx < bt->mgr->latchmgr->latchhash; hashidx++ ) {
2508           if( idx = bt->mgr->latchmgr->table[hashidx].slot ) do {
2509                 latch = bt->mgr->latchsets + idx;
2510                 if( latch->hash != hashidx ) {
2511                         fprintf(stderr, "latchset %d wrong hashidx\n", idx);
2512                         latch->hash = hashidx;
2513                 }
2514           } while( idx = latch->next );
2515         }
2516
2517         page_no = bt_getid(bt->mgr->latchmgr->alloc[1].right);
2518
2519         while( page_no ) {
2520                 fprintf(stderr, "free: %.6x\n", (uint)page_no);
2521
2522                 if( pool = bt_pinpool (bt, page_no) )
2523                         page = bt_page (bt, pool, page_no);
2524                 else
2525                         return;
2526
2527             page_no = bt_getid(page->right);
2528                 bt_unpinpool (pool);
2529         }
2530 #endif
2531 }
2532
2533 typedef struct {
2534         char type, idx;
2535         char *infile;
2536         BtMgr *mgr;
2537         int num;
2538 } ThreadArg;
2539
2540 //  standalone program to index file of keys
2541 //  then list them onto std-out
2542
2543 #ifdef unix
2544 void *index_file (void *arg)
2545 #else
2546 uint __stdcall index_file (void *arg)
2547 #endif
2548 {
2549 int line = 0, found = 0, cnt = 0;
2550 uid next, page_no = LEAF_page;  // start on first page of leaves
2551 unsigned char key[256];
2552 ThreadArg *args = arg;
2553 int ch, len = 0, slot;
2554 BtPageSet set[1];
2555 time_t tod[1];
2556 BtKey ptr;
2557 BtDb *bt;
2558 FILE *in;
2559
2560         bt = bt_open (args->mgr);
2561         time (tod);
2562
2563         switch(args->type | 0x20)
2564         {
2565         case 'a':
2566                 fprintf(stderr, "started latch mgr audit\n");
2567                 bt_latchaudit (bt);
2568                 fprintf(stderr, "finished latch mgr audit\n");
2569                 break;
2570
2571         case 'w':
2572                 fprintf(stderr, "started indexing for %s\n", args->infile);
2573                 if( in = fopen (args->infile, "rb") )
2574                   while( ch = getc(in), ch != EOF )
2575                         if( ch == '\n' )
2576                         {
2577                           line++;
2578
2579                           if( args->num == 1 )
2580                                 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2581
2582                           else if( args->num )
2583                                 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2584
2585                           if( bt_insertkey (bt, key, len, line, *tod, 0) )
2586                                 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2587                           len = 0;
2588                         }
2589                         else if( len < 255 )
2590                                 key[len++] = ch;
2591                 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
2592                 break;
2593
2594         case 'd':
2595                 fprintf(stderr, "started deleting keys for %s\n", args->infile);
2596                 if( in = fopen (args->infile, "rb") )
2597                   while( ch = getc(in), ch != EOF )
2598                         if( ch == '\n' )
2599                         {
2600                           line++;
2601                           if( args->num == 1 )
2602                                 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2603
2604                           else if( args->num )
2605                                 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2606
2607                           if( bt_deletekey (bt, key, len) )
2608                                 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2609                           len = 0;
2610                         }
2611                         else if( len < 255 )
2612                                 key[len++] = ch;
2613                 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2614                 break;
2615
2616         case 'f':
2617                 fprintf(stderr, "started finding keys for %s\n", args->infile);
2618                 if( in = fopen (args->infile, "rb") )
2619                   while( ch = getc(in), ch != EOF )
2620                         if( ch == '\n' )
2621                         {
2622                           line++;
2623                           if( args->num == 1 )
2624                                 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2625
2626                           else if( args->num )
2627                                 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2628
2629                           if( bt_findkey (bt, key, len) )
2630                                 found++;
2631                           else if( bt->err )
2632                                 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2633                           len = 0;
2634                         }
2635                         else if( len < 255 )
2636                                 key[len++] = ch;
2637                 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2638                 break;
2639
2640         case 's':
2641                 fprintf(stderr, "started scanning\n");
2642                 do {
2643                         if( set->pool = bt_pinpool (bt, page_no) )
2644                                 set->page = bt_page (bt, set->pool, page_no);
2645                         else
2646                                 break;
2647                         set->latch = bt_pinlatch (bt, page_no);
2648                         bt_lockpage (BtLockRead, set->latch);
2649                         next = bt_getid (set->page->right);
2650                         cnt += set->page->act;
2651
2652                         for( slot = 0; slot++ < set->page->cnt; )
2653                          if( next || slot < set->page->cnt )
2654                           if( !slotptr(set->page, slot)->dead ) {
2655                                 ptr = keyptr(set->page, slot);
2656                                 fwrite (ptr->key, ptr->len, 1, stdout);
2657                                 fputc ('\n', stdout);
2658                           }
2659
2660                         bt_unlockpage (BtLockRead, set->latch);
2661                         bt_unpinlatch (set->latch);
2662                         bt_unpinpool (set->pool);
2663                 } while( page_no = next );
2664
2665                 cnt--;  // remove stopper key
2666                 fprintf(stderr, " Total keys read %d\n", cnt);
2667                 break;
2668
2669         case 'c':
2670                 fprintf(stderr, "started counting\n");
2671
2672                 do {
2673                         if( set->pool = bt_pinpool (bt, page_no) )
2674                                 set->page = bt_page (bt, set->pool, page_no);
2675                         else
2676                                 break;
2677                         set->latch = bt_pinlatch (bt, page_no);
2678                         bt_lockpage (BtLockRead, set->latch);
2679                         cnt += set->page->act;
2680                         next = bt_getid (set->page->right);
2681                         bt_unlockpage (BtLockRead, set->latch);
2682                         bt_unpinlatch (set->latch);
2683                         bt_unpinpool (set->pool);
2684                 } while( page_no = next );
2685
2686                 cnt--;  // remove stopper key
2687                 fprintf(stderr, " Total keys read %d\n", cnt);
2688                 break;
2689         }
2690
2691         bt_close (bt);
2692 #ifdef unix
2693         return NULL;
2694 #else
2695         return 0;
2696 #endif
2697 }
2698
2699 typedef struct timeval timer;
2700
2701 int main (int argc, char **argv)
2702 {
2703 int idx, cnt, len, slot, err;
2704 int segsize, bits = 16;
2705 #ifdef unix
2706 pthread_t *threads;
2707 timer start, stop;
2708 #else
2709 time_t start[1], stop[1];
2710 HANDLE *threads;
2711 #endif
2712 double real_time;
2713 ThreadArg *args;
2714 uint poolsize = 0;
2715 int num = 0;
2716 char key[1];
2717 BtMgr *mgr;
2718 BtKey ptr;
2719 BtDb *bt;
2720
2721         if( argc < 3 ) {
2722                 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]);
2723                 fprintf (stderr, "  where page_bits is the page size in bits\n");
2724                 fprintf (stderr, "  mapped_segments is the number of mmap segments in buffer pool\n");
2725                 fprintf (stderr, "  seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2726                 fprintf (stderr, "  line_numbers = 1 to append line numbers to keys\n");
2727                 fprintf (stderr, "  src_file1 thru src_filen are files of keys separated by newline\n");
2728                 exit(0);
2729         }
2730
2731 #ifdef unix
2732         gettimeofday(&start, NULL);
2733 #else
2734         time(start);
2735 #endif
2736
2737         if( argc > 3 )
2738                 bits = atoi(argv[3]);
2739
2740         if( argc > 4 )
2741                 poolsize = atoi(argv[4]);
2742
2743         if( !poolsize )
2744                 fprintf (stderr, "Warning: no mapped_pool\n");
2745
2746         if( poolsize > 65535 )
2747                 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2748
2749         if( argc > 5 )
2750                 segsize = atoi(argv[5]);
2751         else
2752                 segsize = 4;    // 16 pages per mmap segment
2753
2754         if( argc > 6 )
2755                 num = atoi(argv[6]);
2756
2757         cnt = argc - 7;
2758 #ifdef unix
2759         threads = malloc (cnt * sizeof(pthread_t));
2760 #else
2761         threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2762 #endif
2763         args = malloc (cnt * sizeof(ThreadArg));
2764
2765         mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2766
2767         if( !mgr ) {
2768                 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2769                 exit (1);
2770         }
2771
2772         //      fire off threads
2773
2774         for( idx = 0; idx < cnt; idx++ ) {
2775                 args[idx].infile = argv[idx + 7];
2776                 args[idx].type = argv[2][0];
2777                 args[idx].mgr = mgr;
2778                 args[idx].num = num;
2779                 args[idx].idx = idx;
2780 #ifdef unix
2781                 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2782                         fprintf(stderr, "Error creating thread %d\n", err);
2783 #else
2784                 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2785 #endif
2786         }
2787
2788         //      wait for termination
2789
2790 #ifdef unix
2791         for( idx = 0; idx < cnt; idx++ )
2792                 pthread_join (threads[idx], NULL);
2793         gettimeofday(&stop, NULL);
2794         real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2795 #else
2796         WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2797
2798         for( idx = 0; idx < cnt; idx++ )
2799                 CloseHandle(threads[idx]);
2800
2801         time (stop);
2802         real_time = 1000 * (*stop - *start);
2803 #endif
2804         fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);
2805         bt_mgrclose (mgr);
2806 }
2807
2808 #endif  //STANDALONE