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