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