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