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