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