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