]> pd.if.org Git - btree/blob - threads2i.c
fix original problem with bt_deletekey, obviating need for btree2t.c
[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   next->page_no = bt_getid(slotptr(set->page, set->page->cnt)->id);
1549
1550   while( !set->page->kill && set->page->lvl ) {
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   while( 1 ) {
1765         if( !(slot = bt_loadpage (bt, parent, pagefence+1, *pagefence, lvl+1, BtLockWrite)) )
1766                 return bt->err;
1767
1768         //      do we show up in our parent yet?
1769
1770         if( set->page_no != bt_getid (slotptr (parent->page, slot)->id) ) {
1771                 bt_unlockpage (BtLockWrite, parent->latch);
1772                 bt_unpinlatch (parent->latch);
1773                 bt_unpinpool (parent->pool);
1774 #ifdef linux
1775                 sched_yield();
1776 #else
1777                 SwitchToThread();
1778 #endif
1779                 continue;
1780         }
1781
1782         //      can we do a simple merge entirely
1783         //      between siblings on the parent page?
1784
1785         if( slot < parent->page->cnt ) {
1786                 // find our right neighbor
1787                 //      right must exist because the stopper prevents
1788                 //      the rightmost page from deleting
1789
1790                 for( idx = slot; idx++ < parent->page->cnt; )
1791                   if( !slotptr(parent->page, idx)->dead )
1792                         break;
1793
1794                 sibling->page_no = bt_getid (slotptr (parent->page, idx)->id);
1795
1796                 bt_lockpage (BtLockDelete, set->latch);
1797                 bt_lockpage (BtLockWrite, set->latch);
1798
1799                 //      merge right if sibling shows up in
1800                 //  our parent and is not being killed
1801
1802                 if( sibling->page_no == bt_getid (set->page->right) ) {
1803                   sibling->latch = bt_pinlatch (bt, sibling->page_no);
1804                   bt_lockpage (BtLockParent, sibling->latch);
1805                   bt_lockpage (BtLockDelete, sibling->latch);
1806                   bt_lockpage (BtLockWrite, sibling->latch);
1807
1808                   if( sibling->pool = bt_pinpool (bt, sibling->page_no) )
1809                         sibling->page = bt_page (bt, sibling->pool, sibling->page_no);
1810                   else
1811                         return bt->err;
1812
1813                   if( !sibling->page->kill )
1814                         return bt_mergeright(bt, set, parent, sibling, slot, idx);
1815
1816                   //  try again later
1817
1818                   bt_unlockpage (BtLockWrite, sibling->latch);
1819                   bt_unlockpage (BtLockParent, sibling->latch);
1820                   bt_unlockpage (BtLockDelete, sibling->latch);
1821                   bt_unpinlatch (sibling->latch);
1822                   bt_unpinpool (sibling->pool);
1823                 }
1824
1825                 bt_unlockpage (BtLockDelete, set->latch);
1826                 bt_unlockpage (BtLockWrite, set->latch);
1827                 bt_unlockpage (BtLockWrite, parent->latch);
1828                 bt_unpinlatch (parent->latch);
1829                 bt_unpinpool (parent->pool);
1830 #ifdef linux
1831                 sched_yield();
1832 #else
1833                 SwitchToThread();
1834 #endif
1835                 continue;
1836         }
1837
1838         //  find our left neighbor in our parent page
1839
1840         for( idx = slot; --idx; )
1841           if( !slotptr(parent->page, idx)->dead )
1842                 break;
1843
1844         //      if no left neighbor, delete ourselves and our parent
1845
1846         if( !idx ) {
1847                 bt_lockpage (BtLockAccess, set->latch);
1848                 bt_lockpage (BtLockWrite, set->latch);
1849                 bt_unlockpage (BtLockAccess, set->latch);
1850
1851                 rparent->page_no = bt_getid (parent->page->right);
1852                 rparent->latch = bt_pinlatch (bt, rparent->page_no);
1853
1854                 bt_lockpage (BtLockAccess, rparent->latch);
1855                 bt_lockpage (BtLockWrite, rparent->latch);
1856                 bt_unlockpage (BtLockAccess, rparent->latch);
1857
1858                 if( rparent->pool = bt_pinpool (bt, rparent->page_no) )
1859                         rparent->page = bt_page (bt, rparent->pool, rparent->page_no);
1860                 else
1861                         return bt->err;
1862
1863                 if( !rparent->page->kill ) {
1864                   sibling->page_no = bt_getid (set->page->right);
1865                   sibling->latch = bt_pinlatch (bt, sibling->page_no);
1866
1867                   bt_lockpage (BtLockAccess, sibling->latch);
1868                   bt_lockpage (BtLockWrite, sibling->latch);
1869                   bt_unlockpage (BtLockAccess, sibling->latch);
1870
1871                   if( sibling->pool = bt_pinpool (bt, sibling->page_no) )
1872                         sibling->page = bt_page (bt, sibling->pool, sibling->page_no);
1873                   else
1874                         return bt->err;
1875
1876                   if( !sibling->page->kill )
1877                         return bt_removeparent (bt, set, parent, sibling, rparent, lvl+1);
1878
1879                   //  try again later
1880
1881                   bt_unlockpage (BtLockWrite, sibling->latch);
1882                   bt_unpinlatch (sibling->latch);
1883                   bt_unpinpool (sibling->pool);
1884                 }
1885
1886                 bt_unlockpage (BtLockWrite, set->latch);
1887                 bt_unlockpage (BtLockWrite, rparent->latch);
1888                 bt_unpinlatch (rparent->latch);
1889                 bt_unpinpool (rparent->pool);
1890
1891                 bt_unlockpage (BtLockWrite, parent->latch);
1892                 bt_unpinlatch (parent->latch);
1893                 bt_unpinpool (parent->pool);
1894 #ifdef linux
1895                 sched_yield();
1896 #else
1897                 SwitchToThread();
1898 #endif
1899                 continue;
1900         }
1901
1902         // redirect parent to our left sibling
1903         // lock and map our left sibling's page
1904
1905         sibling->page_no = bt_getid (slotptr(parent->page, idx)->id);
1906         sibling->latch = bt_pinlatch (bt, sibling->page_no);
1907
1908         //      wait our turn on fence key maintenance
1909
1910         bt_lockpage(BtLockParent, sibling->latch);
1911         bt_lockpage(BtLockAccess, sibling->latch);
1912         bt_lockpage(BtLockWrite, sibling->latch);
1913         bt_unlockpage(BtLockAccess, sibling->latch);
1914
1915         if( sibling->pool = bt_pinpool (bt, sibling->page_no) )
1916                 sibling->page = bt_page (bt, sibling->pool, sibling->page_no);
1917         else
1918                 return bt->err;
1919
1920         //  wait until left sibling is in our parent
1921
1922         if( bt_getid (sibling->page->right) != set->page_no ) {
1923                 bt_unlockpage (BtLockWrite, parent->latch);
1924                 bt_unlockpage (BtLockWrite, sibling->latch);
1925                 bt_unlockpage (BtLockParent, sibling->latch);
1926                 bt_unpinlatch (parent->latch);
1927                 bt_unpinpool (parent->pool);
1928                 bt_unpinlatch (sibling->latch);
1929                 bt_unpinpool (sibling->pool);
1930 #ifdef linux
1931                 sched_yield();
1932 #else
1933                 SwitchToThread();
1934 #endif
1935                 continue;
1936         }
1937
1938         //      delete our left sibling from parent
1939
1940         slotptr(parent->page,idx)->dead = 1;
1941         parent->page->dirty = 1;
1942         parent->page->act--;
1943
1944         //      redirect our parent slot to our left sibling
1945
1946         bt_putid (slotptr(parent->page, slot)->id, sibling->page_no);
1947         memcpy (sibling->page->right, set->page->right, BtId);
1948
1949         //      collapse dead slots from parent
1950
1951         while( idx = parent->page->cnt - 1 )
1952           if( slotptr(parent->page, idx)->dead ) {
1953                 *slotptr(parent->page, idx) = *slotptr(parent->page, parent->page->cnt);
1954                 memset (slotptr(parent->page, parent->page->cnt--), 0, sizeof(BtSlot));
1955           } else
1956                   break;
1957
1958         //  free our original page
1959
1960         bt_lockpage (BtLockDelete, set->latch);
1961         bt_lockpage (BtLockWrite, set->latch);
1962         bt_freepage (bt, set);
1963
1964         //      go down the left node's fence keys to the leaf level
1965         //      and update the fence keys in each page
1966
1967         memcpy (newfence, parent->page->fence, 256);
1968
1969         if( bt_fixfences (bt, sibling, newfence) )
1970                 return bt->err;
1971
1972         //  promote sibling as new root?
1973
1974         if( parent->page_no == ROOT_page && parent->page->cnt == 1 )
1975          if( sibling->page->lvl ) {
1976           sibling->latch = bt_pinlatch (bt, sibling->page_no);
1977           bt_lockpage (BtLockDelete, sibling->latch);
1978           bt_lockpage (BtLockWrite, sibling->latch);
1979
1980           if( sibling->pool = bt_pinpool (bt, sibling->page_no) )
1981                 sibling->page = bt_page (bt, sibling->pool, sibling->page_no);
1982           else
1983                 return bt->err;
1984
1985           return bt_removeroot (bt, parent, sibling);
1986          }
1987
1988         bt_unlockpage (BtLockWrite, parent->latch);
1989         bt_unpinlatch (parent->latch);
1990         bt_unpinpool (parent->pool);
1991
1992         return 0;
1993   }
1994 }
1995
1996 //  find and delete key on page by marking delete flag bit
1997 //  if page becomes empty, delete it from the btree
1998
1999 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len)
2000 {
2001 unsigned char pagefence[256];
2002 uint slot, idx, found;
2003 BtPageSet set[1];
2004 BtKey ptr;
2005
2006         if( slot = bt_loadpage (bt, set, key, len, 0, BtLockWrite) )
2007                 ptr = keyptr(set->page, slot);
2008         else
2009                 return bt->err;
2010
2011         // if key is found delete it, otherwise ignore request
2012
2013         if( found = slot <= set->page->cnt )
2014           if( found = !keycmp (ptr, key, len) )
2015                 if( found = slotptr(set->page, slot)->dead == 0 ) {
2016                   slotptr(set->page,slot)->dead = 1;
2017                   set->page->dirty = 1;
2018                   set->page->act--;
2019
2020                   // collapse empty slots
2021
2022                   while( idx = set->page->cnt - 1 )
2023                         if( slotptr(set->page, idx)->dead ) {
2024                           *slotptr(set->page, idx) = *slotptr(set->page, idx + 1);
2025                           memset (slotptr(set->page, set->page->cnt--), 0, sizeof(BtSlot));
2026                         } else
2027                                 break;
2028                 }
2029
2030         if( set->page->act ) {
2031                 bt_unlockpage(BtLockWrite, set->latch);
2032                 bt_unpinlatch (set->latch);
2033                 bt_unpinpool (set->pool);
2034                 return bt->found = found, 0;
2035         }
2036
2037         memcpy (pagefence, set->page->fence, 256);
2038         set->page->kill = 1;
2039
2040         bt_unlockpage (BtLockWrite, set->latch);
2041
2042         if( bt_removepage (bt, set, 0, pagefence) )
2043                 return bt->err;
2044
2045         bt->found = found;
2046         return 0;
2047 }
2048
2049 //      find key in leaf level and return row-id
2050
2051 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
2052 {
2053 BtPageSet set[1];
2054 uint  slot;
2055 uid id = 0;
2056 BtKey ptr;
2057
2058         if( slot = bt_loadpage (bt, set, key, len, 0, BtLockRead) )
2059                 ptr = keyptr(set->page, slot);
2060         else
2061                 return 0;
2062
2063         // if key exists, return row-id
2064         //      otherwise return 0
2065
2066         if( slot <= set->page->cnt )
2067           if( !keycmp (ptr, key, len) )
2068                 id = bt_getid(slotptr(set->page,slot)->id);
2069
2070         bt_unlockpage (BtLockRead, set->latch);
2071         bt_unpinlatch (set->latch);
2072         bt_unpinpool (set->pool);
2073         return id;
2074 }
2075
2076 //      check page for space available,
2077 //      clean if necessary and return
2078 //      0 - page needs splitting
2079 //      >0  new slot value
2080
2081 uint bt_cleanpage(BtDb *bt, BtPage page, uint amt, uint slot)
2082 {
2083 uint nxt = bt->mgr->page_size, off;
2084 uint cnt = 0, idx = 0;
2085 uint max = page->cnt;
2086 uint newslot = max;
2087 BtKey key;
2088
2089         if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
2090                 return slot;
2091
2092         //      skip cleanup if nothing to reclaim
2093
2094         if( !page->dirty )
2095                 return 0;
2096
2097         memcpy (bt->frame, page, bt->mgr->page_size);
2098
2099         // skip page info and set rest of page to zero
2100
2101         memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
2102         page->dirty = 0;
2103         page->act = 0;
2104
2105         // try cleaning up page first
2106         // by removing deleted keys
2107
2108         while( cnt++ < max ) {
2109                 if( cnt == slot )
2110                         newslot = idx + 1;
2111                 if( slotptr(bt->frame,cnt)->dead )
2112                         continue;
2113
2114                 // if its not the fence key,
2115                 // copy the key across
2116
2117                 off = slotptr(bt->frame,cnt)->off;
2118
2119                 if( off >= sizeof(*page) ) {
2120                         key = keyptr(bt->frame, cnt);
2121                         off = nxt -= key->len + 1;
2122                         memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2123                 }
2124
2125                 // copy slot
2126
2127                 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
2128                 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2129                 slotptr(page, idx)->off = off;
2130                 page->act++;
2131         }
2132
2133         page->min = nxt;
2134         page->cnt = idx;
2135
2136         //      see if page has enough space now, or does it need splitting?
2137
2138         if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
2139                 return newslot;
2140
2141         return 0;
2142 }
2143
2144 // split the root and raise the height of the btree
2145
2146 BTERR bt_splitroot(BtDb *bt, BtPageSet *root, uid page_no2)
2147 {
2148 uint nxt = bt->mgr->page_size;
2149 unsigned char leftkey[256];
2150 uid new_page;
2151
2152         //  Obtain an empty page to use, and copy the current
2153         //  root contents into it, e.g. lower keys
2154
2155         memcpy (leftkey, root->page->fence, 256);
2156         root->page->posted = 1;
2157
2158         if( !(new_page = bt_newpage(bt, root->page)) )
2159                 return bt->err;
2160
2161         // preserve the page info at the bottom
2162         // of higher keys and set rest to zero
2163
2164         memset(root->page+1, 0, bt->mgr->page_size - sizeof(*root->page));
2165         memset(root->page->fence, 0, 256);
2166         root->page->fence[0] = 2;
2167         root->page->fence[1] = 0xff;
2168         root->page->fence[2] = 0xff;
2169
2170         // insert lower keys page fence key on newroot page
2171
2172         nxt -= *leftkey + 1;
2173         memcpy ((unsigned char *)root->page + nxt, leftkey, *leftkey + 1);
2174         bt_putid(slotptr(root->page, 1)->id, new_page);
2175         slotptr(root->page, 1)->off = nxt;
2176         
2177         // insert stopper key on newroot page
2178         // and increase the root height
2179
2180         bt_putid(slotptr(root->page, 2)->id, page_no2);
2181         slotptr(root->page, 2)->off = offsetof(struct BtPage_, fence);
2182
2183         bt_putid(root->page->right, 0);
2184         root->page->min = nxt;          // reset lowest used offset and key count
2185         root->page->cnt = 2;
2186         root->page->act = 2;
2187         root->page->lvl++;
2188
2189         // release and unpin root
2190
2191         bt_unlockpage(BtLockWrite, root->latch);
2192         bt_unpinlatch (root->latch);
2193         bt_unpinpool (root->pool);
2194         return 0;
2195 }
2196
2197 //  split already locked full node
2198 //      return unlocked.
2199
2200 BTERR bt_splitpage (BtDb *bt, BtPageSet *set)
2201 {
2202 uint cnt = 0, idx = 0, max, nxt = bt->mgr->page_size, off;
2203 unsigned char fencekey[256];
2204 uint lvl = set->page->lvl;
2205 uid right;
2206 BtKey key;
2207
2208         //  split higher half of keys to bt->frame
2209
2210         memset (bt->frame, 0, bt->mgr->page_size);
2211         max = set->page->cnt;
2212         cnt = max / 2;
2213         idx = 0;
2214
2215         while( cnt++ < max ) {
2216                 if( !lvl || cnt < max ) {
2217                         key = keyptr(set->page, cnt);
2218                         off = nxt -= key->len + 1;
2219                         memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
2220                 } else
2221                         off = offsetof(struct BtPage_, fence);
2222
2223                 memcpy(slotptr(bt->frame,++idx)->id, slotptr(set->page,cnt)->id, BtId);
2224                 slotptr(bt->frame, idx)->tod = slotptr(set->page, cnt)->tod;
2225                 slotptr(bt->frame, idx)->off = off;
2226                 bt->frame->act++;
2227         }
2228
2229         if( set->page_no == ROOT_page )
2230                 bt->frame->posted = 1;
2231
2232         memcpy (bt->frame->fence, set->page->fence, 256);
2233         bt->frame->bits = bt->mgr->page_bits;
2234         bt->frame->min = nxt;
2235         bt->frame->cnt = idx;
2236         bt->frame->lvl = lvl;
2237
2238         // link right node
2239
2240         if( set->page_no > ROOT_page )
2241                 memcpy (bt->frame->right, set->page->right, BtId);
2242
2243         //      get new free page and write higher keys to it.
2244
2245         if( !(right = bt_newpage(bt, bt->frame)) )
2246                 return bt->err;
2247
2248         //      update lower keys to continue in old page
2249
2250         memcpy (bt->frame, set->page, bt->mgr->page_size);
2251         memset (set->page+1, 0, bt->mgr->page_size - sizeof(*set->page));
2252         nxt = bt->mgr->page_size;
2253         set->page->posted = 0;
2254         set->page->dirty = 0;
2255         set->page->act = 0;
2256         cnt = 0;
2257         idx = 0;
2258
2259         //  assemble page of smaller keys
2260
2261         while( cnt++ < max / 2 ) {
2262                 key = keyptr(bt->frame, cnt);
2263
2264                 if( !lvl || cnt < max / 2 ) {
2265                         off = nxt -= key->len + 1;
2266                         memcpy ((unsigned char *)set->page + nxt, key, key->len + 1);
2267                 } else 
2268                         off = offsetof(struct BtPage_, fence);
2269
2270                 memcpy(slotptr(set->page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
2271                 slotptr(set->page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2272                 slotptr(set->page, idx)->off = off;
2273                 set->page->act++;
2274         }
2275
2276         // install fence key for smaller key page
2277
2278         memset(set->page->fence, 0, 256);
2279         memcpy(set->page->fence, key, key->len + 1);
2280
2281         bt_putid(set->page->right, right);
2282         set->page->min = nxt;
2283         set->page->cnt = idx;
2284
2285         // if current page is the root page, split it
2286
2287         if( set->page_no == ROOT_page )
2288                 return bt_splitroot (bt, set, right);
2289
2290         bt_unlockpage (BtLockWrite, set->latch);
2291
2292         // insert new fences in their parent pages
2293
2294         while( 1 ) {
2295                 bt_lockpage (BtLockParent, set->latch);
2296                 bt_lockpage (BtLockWrite, set->latch);
2297
2298                 memcpy (fencekey, set->page->fence, 256);
2299                 right = bt_getid (set->page->right);
2300
2301                 if( set->page->posted ) {
2302                         bt_unlockpage (BtLockParent, set->latch);
2303                         bt_unlockpage (BtLockWrite, set->latch);
2304                         bt_unpinlatch (set->latch);
2305                         bt_unpinpool (set->pool);
2306                         return 0;
2307                 }
2308
2309                 set->page->posted = 1;
2310                 bt_unlockpage (BtLockWrite, set->latch);
2311
2312                 if( bt_insertkey (bt, fencekey+1, *fencekey, set->page_no, time(NULL), lvl+1) )
2313                         return bt->err;
2314
2315                 bt_unlockpage (BtLockParent, set->latch);
2316                 bt_unpinlatch (set->latch);
2317                 bt_unpinpool (set->pool);
2318
2319                 if( !(set->page_no = right) )
2320                         break;
2321
2322                 set->latch = bt_pinlatch (bt, right);
2323
2324                 if( set->pool = bt_pinpool (bt, right) )
2325                         set->page = bt_page (bt, set->pool, right);
2326                 else
2327                         return bt->err;
2328         }
2329
2330         return 0;
2331 }
2332
2333 //  Insert new key into the btree at given level.
2334
2335 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod, uint lvl)
2336 {
2337 BtPageSet set[1];
2338 uint slot, idx;
2339 BtKey ptr;
2340
2341         while( 1 ) {
2342                 if( slot = bt_loadpage (bt, set, key, len, lvl, BtLockWrite) )
2343                         ptr = keyptr(set->page, slot);
2344                 else
2345                 {
2346                         if ( !bt->err )
2347                                 bt->err = BTERR_ovflw;
2348                         return bt->err;
2349                 }
2350
2351                 // if key already exists, update id and return
2352
2353                 if( slot <= set->page->cnt )
2354                   if( !keycmp (ptr, key, len) ) {
2355                         if( slotptr(set->page, slot)->dead )
2356                                 set->page->act++;
2357                         slotptr(set->page, slot)->dead = 0;
2358                         slotptr(set->page, slot)->tod = tod;
2359                         bt_putid(slotptr(set->page,slot)->id, id);
2360                         bt_unlockpage(BtLockWrite, set->latch);
2361                         bt_unpinlatch (set->latch);
2362                         bt_unpinpool (set->pool);
2363                         return 0;
2364                 }
2365
2366                 // check if page has enough space
2367
2368                 if( slot = bt_cleanpage (bt, set->page, len, slot) )
2369                         break;
2370
2371                 if( bt_splitpage (bt, set) )
2372                         return bt->err;
2373         }
2374
2375         // calculate next available slot and copy key into page
2376
2377         set->page->min -= len + 1; // reset lowest used offset
2378         ((unsigned char *)set->page)[set->page->min] = len;
2379         memcpy ((unsigned char *)set->page + set->page->min +1, key, len );
2380
2381         for( idx = slot; idx <= set->page->cnt; idx++ )
2382           if( slotptr(set->page, idx)->dead )
2383                 break;
2384
2385         // now insert key into array before slot
2386
2387         if( idx > set->page->cnt )
2388                 set->page->cnt++;
2389
2390         set->page->act++;
2391
2392         while( idx > slot )
2393                 *slotptr(set->page, idx) = *slotptr(set->page, idx -1), idx--;
2394
2395         bt_putid(slotptr(set->page,slot)->id, id);
2396         slotptr(set->page, slot)->off = set->page->min;
2397         slotptr(set->page, slot)->tod = tod;
2398         slotptr(set->page, slot)->dead = 0;
2399
2400         bt_unlockpage (BtLockWrite, set->latch);
2401         bt_unpinlatch (set->latch);
2402         bt_unpinpool (set->pool);
2403         return 0;
2404 }
2405
2406 //  cache page of keys into cursor and return starting slot for given key
2407
2408 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2409 {
2410 BtPageSet set[1];
2411 uint slot;
2412
2413         // cache page for retrieval
2414
2415         if( slot = bt_loadpage (bt, set, key, len, 0, BtLockRead) )
2416           memcpy (bt->cursor, set->page, bt->mgr->page_size);
2417         else
2418           return 0;
2419
2420         bt->cursor_page = set->page_no;
2421
2422         bt_unlockpage(BtLockRead, set->latch);
2423         bt_unpinlatch (set->latch);
2424         bt_unpinpool (set->pool);
2425         return slot;
2426 }
2427
2428 //  return next slot for cursor page
2429 //  or slide cursor right into next page
2430
2431 uint bt_nextkey (BtDb *bt, uint slot)
2432 {
2433 BtPageSet set[1];
2434 uid right;
2435
2436   do {
2437         right = bt_getid(bt->cursor->right);
2438         while( slot++ < bt->cursor->cnt )
2439           if( slotptr(bt->cursor,slot)->dead )
2440                 continue;
2441           else if( right || (slot < bt->cursor->cnt) ) // skip infinite stopper
2442                 return slot;
2443           else
2444                 break;
2445
2446         if( !right )
2447                 break;
2448
2449         bt->cursor_page = right;
2450
2451         if( set->pool = bt_pinpool (bt, right) )
2452                 set->page = bt_page (bt, set->pool, right);
2453         else
2454                 return 0;
2455
2456         set->latch = bt_pinlatch (bt, right);
2457     bt_lockpage(BtLockRead, set->latch);
2458
2459         memcpy (bt->cursor, set->page, bt->mgr->page_size);
2460
2461         bt_unlockpage(BtLockRead, set->latch);
2462         bt_unpinlatch (set->latch);
2463         bt_unpinpool (set->pool);
2464         slot = 0;
2465   } while( 1 );
2466
2467   return bt->err = 0;
2468 }
2469
2470 BtKey bt_key(BtDb *bt, uint slot)
2471 {
2472         return keyptr(bt->cursor, slot);
2473 }
2474
2475 uid bt_uid(BtDb *bt, uint slot)
2476 {
2477         return bt_getid(slotptr(bt->cursor,slot)->id);
2478 }
2479
2480 uint bt_tod(BtDb *bt, uint slot)
2481 {
2482         return slotptr(bt->cursor,slot)->tod;
2483 }
2484
2485
2486 #ifdef STANDALONE
2487
2488 void bt_latchaudit (BtDb *bt)
2489 {
2490 ushort idx, hashidx;
2491 BtLatchSet *latch;
2492 BtPool *pool;
2493 BtPage page;
2494 uid page_no;
2495
2496 #ifdef unix
2497         for( idx = 1; idx < bt->mgr->latchmgr->latchdeployed; idx++ ) {
2498                 latch = bt->mgr->latchsets + idx;
2499                 if( *(ushort *)latch->readwr ) {
2500                         fprintf(stderr, "latchset %d r/w locked for page %.8x\n", idx, latch->page_no);
2501                         *(ushort *)latch->readwr = 0;
2502                 }
2503                 if( *(ushort *)latch->access ) {
2504                         fprintf(stderr, "latchset %d access locked for page %.8x\n", idx, latch->page_no);
2505                         *(ushort *)latch->access = 0;
2506                 }
2507                 if( *(ushort *)latch->parent ) {
2508                         fprintf(stderr, "latchset %d parent locked for page %.8x\n", idx, latch->page_no);
2509                         *(ushort *)latch->parent = 0;
2510                 }
2511                 if( *(ushort *)latch->busy ) {
2512                         fprintf(stderr, "latchset %d busy locked for page %.8x\n", idx, latch->page_no);
2513                         *(ushort *)latch->parent = 0;
2514                 }
2515                 if( latch->pin ) {
2516                         fprintf(stderr, "latchset %d pinned for page %.8x\n", idx, latch->page_no);
2517                         latch->pin = 0;
2518                 }
2519         }
2520
2521         for( hashidx = 0; hashidx < bt->mgr->latchmgr->latchhash; hashidx++ ) {
2522           if( idx = bt->mgr->latchmgr->table[hashidx].slot ) do {
2523                 latch = bt->mgr->latchsets + idx;
2524                 if( latch->hash != hashidx ) {
2525                         fprintf(stderr, "latchset %d wrong hashidx\n", idx);
2526                         latch->hash = hashidx;
2527                 }
2528           } while( idx = latch->next );
2529         }
2530
2531         page_no = bt_getid(bt->mgr->latchmgr->alloc[1].right);
2532
2533         while( page_no ) {
2534                 fprintf(stderr, "free: %.6x\n", (uint)page_no);
2535
2536                 if( pool = bt_pinpool (bt, page_no) )
2537                         page = bt_page (bt, pool, page_no);
2538                 else
2539                         return;
2540
2541             page_no = bt_getid(page->right);
2542                 bt_unpinpool (pool);
2543         }
2544 #endif
2545 }
2546
2547 typedef struct {
2548         char type, idx;
2549         char *infile;
2550         BtMgr *mgr;
2551         int num;
2552 } ThreadArg;
2553
2554 //  standalone program to index file of keys
2555 //  then list them onto std-out
2556
2557 #ifdef unix
2558 void *index_file (void *arg)
2559 #else
2560 uint __stdcall index_file (void *arg)
2561 #endif
2562 {
2563 int line = 0, found = 0, cnt = 0;
2564 uid next, page_no = LEAF_page;  // start on first page of leaves
2565 unsigned char key[256];
2566 ThreadArg *args = arg;
2567 int ch, len = 0, slot;
2568 BtPageSet set[1];
2569 time_t tod[1];
2570 BtKey ptr;
2571 BtDb *bt;
2572 FILE *in;
2573
2574         bt = bt_open (args->mgr);
2575         time (tod);
2576
2577         switch(args->type | 0x20)
2578         {
2579         case 'a':
2580                 fprintf(stderr, "started latch mgr audit\n");
2581                 bt_latchaudit (bt);
2582                 fprintf(stderr, "finished latch mgr audit\n");
2583                 break;
2584
2585         case 'w':
2586                 fprintf(stderr, "started indexing for %s\n", args->infile);
2587                 if( in = fopen (args->infile, "rb") )
2588                   while( ch = getc(in), ch != EOF )
2589                         if( ch == '\n' )
2590                         {
2591                           line++;
2592
2593                           if( args->num == 1 )
2594                                 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2595
2596                           else if( args->num )
2597                                 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2598
2599                           if( bt_insertkey (bt, key, len, line, *tod, 0) )
2600                                 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2601                           len = 0;
2602                         }
2603                         else if( len < 255 )
2604                                 key[len++] = ch;
2605                 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
2606                 break;
2607
2608         case 'd':
2609                 fprintf(stderr, "started deleting keys for %s\n", args->infile);
2610                 if( in = fopen (args->infile, "rb") )
2611                   while( ch = getc(in), ch != EOF )
2612                         if( ch == '\n' )
2613                         {
2614                           line++;
2615                           if( args->num == 1 )
2616                                 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2617
2618                           else if( args->num )
2619                                 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2620
2621                           if( bt_deletekey (bt, key, len) )
2622                                 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2623                           len = 0;
2624                         }
2625                         else if( len < 255 )
2626                                 key[len++] = ch;
2627                 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2628                 break;
2629
2630         case 'f':
2631                 fprintf(stderr, "started finding keys for %s\n", args->infile);
2632                 if( in = fopen (args->infile, "rb") )
2633                   while( ch = getc(in), ch != EOF )
2634                         if( ch == '\n' )
2635                         {
2636                           line++;
2637                           if( args->num == 1 )
2638                                 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2639
2640                           else if( args->num )
2641                                 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2642
2643                           if( bt_findkey (bt, key, len) )
2644                                 found++;
2645                           else if( bt->err )
2646                                 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2647                           len = 0;
2648                         }
2649                         else if( len < 255 )
2650                                 key[len++] = ch;
2651                 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2652                 break;
2653
2654         case 's':
2655                 fprintf(stderr, "started scanning\n");
2656                 do {
2657                         if( set->pool = bt_pinpool (bt, page_no) )
2658                                 set->page = bt_page (bt, set->pool, page_no);
2659                         else
2660                                 break;
2661                         set->latch = bt_pinlatch (bt, page_no);
2662                         bt_lockpage (BtLockRead, set->latch);
2663                         next = bt_getid (set->page->right);
2664                         cnt += set->page->act;
2665
2666                         for( slot = 0; slot++ < set->page->cnt; )
2667                          if( next || slot < set->page->cnt )
2668                           if( !slotptr(set->page, slot)->dead ) {
2669                                 ptr = keyptr(set->page, slot);
2670                                 fwrite (ptr->key, ptr->len, 1, stdout);
2671                                 fputc ('\n', stdout);
2672                           }
2673
2674                         bt_unlockpage (BtLockRead, set->latch);
2675                         bt_unpinlatch (set->latch);
2676                         bt_unpinpool (set->pool);
2677                 } while( page_no = next );
2678
2679                 cnt--;  // remove stopper key
2680                 fprintf(stderr, " Total keys read %d\n", cnt);
2681                 break;
2682
2683         case 'c':
2684                 fprintf(stderr, "started counting\n");
2685                 next = bt->mgr->latchmgr->nlatchpage + LATCH_page;
2686                 page_no = LEAF_page;
2687
2688                 while( page_no < bt_getid(bt->mgr->latchmgr->alloc->right) ) {
2689                         pread (bt->mgr->idx, bt->frame, bt->mgr->page_size, page_no << bt->mgr->page_bits);
2690                         if( !bt->frame->free && !bt->frame->lvl )
2691                                 cnt += bt->frame->act;
2692                         if( page_no > LEAF_page )
2693                                 next = page_no + 1;
2694                         page_no = next;
2695                 }
2696                 
2697                 cnt--;  // remove stopper key
2698                 fprintf(stderr, " Total keys read %d\n", cnt);
2699                 break;
2700         }
2701
2702         bt_close (bt);
2703 #ifdef unix
2704         return NULL;
2705 #else
2706         return 0;
2707 #endif
2708 }
2709
2710 typedef struct timeval timer;
2711
2712 int main (int argc, char **argv)
2713 {
2714 int idx, cnt, len, slot, err;
2715 int segsize, bits = 16;
2716 #ifdef unix
2717 pthread_t *threads;
2718 timer start, stop;
2719 #else
2720 time_t start[1], stop[1];
2721 HANDLE *threads;
2722 #endif
2723 double real_time;
2724 ThreadArg *args;
2725 uint poolsize = 0;
2726 int num = 0;
2727 char key[1];
2728 BtMgr *mgr;
2729 BtKey ptr;
2730 BtDb *bt;
2731
2732         if( argc < 3 ) {
2733                 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]);
2734                 fprintf (stderr, "  where page_bits is the page size in bits\n");
2735                 fprintf (stderr, "  mapped_segments is the number of mmap segments in buffer pool\n");
2736                 fprintf (stderr, "  seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2737                 fprintf (stderr, "  line_numbers = 1 to append line numbers to keys\n");
2738                 fprintf (stderr, "  src_file1 thru src_filen are files of keys separated by newline\n");
2739                 exit(0);
2740         }
2741
2742 #ifdef unix
2743         gettimeofday(&start, NULL);
2744 #else
2745         time(start);
2746 #endif
2747
2748         if( argc > 3 )
2749                 bits = atoi(argv[3]);
2750
2751         if( argc > 4 )
2752                 poolsize = atoi(argv[4]);
2753
2754         if( !poolsize )
2755                 fprintf (stderr, "Warning: no mapped_pool\n");
2756
2757         if( poolsize > 65535 )
2758                 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2759
2760         if( argc > 5 )
2761                 segsize = atoi(argv[5]);
2762         else
2763                 segsize = 4;    // 16 pages per mmap segment
2764
2765         if( argc > 6 )
2766                 num = atoi(argv[6]);
2767
2768         cnt = argc - 7;
2769 #ifdef unix
2770         threads = malloc (cnt * sizeof(pthread_t));
2771 #else
2772         threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2773 #endif
2774         args = malloc (cnt * sizeof(ThreadArg));
2775
2776         mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2777
2778         if( !mgr ) {
2779                 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2780                 exit (1);
2781         }
2782
2783         //      fire off threads
2784
2785         for( idx = 0; idx < cnt; idx++ ) {
2786                 args[idx].infile = argv[idx + 7];
2787                 args[idx].type = argv[2][0];
2788                 args[idx].mgr = mgr;
2789                 args[idx].num = num;
2790                 args[idx].idx = idx;
2791 #ifdef unix
2792                 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2793                         fprintf(stderr, "Error creating thread %d\n", err);
2794 #else
2795                 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2796 #endif
2797         }
2798
2799         //      wait for termination
2800
2801 #ifdef unix
2802         for( idx = 0; idx < cnt; idx++ )
2803                 pthread_join (threads[idx], NULL);
2804         gettimeofday(&stop, NULL);
2805         real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2806 #else
2807         WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2808
2809         for( idx = 0; idx < cnt; idx++ )
2810                 CloseHandle(threads[idx]);
2811
2812         time (stop);
2813         real_time = 1000 * (*stop - *start);
2814 #endif
2815         fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);
2816         bt_mgrclose (mgr);
2817 }
2818
2819 #endif  //STANDALONE