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