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