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