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