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