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