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