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