]> pd.if.org Git - btree/blob - threads2j.c
install latest threads2 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         BtSlot table[0];                        // array of key slots
162 } *BtPage;
163
164 //  hash table entries
165
166 typedef struct {
167         BtLatch latch[1];
168         volatile ushort slot;           // Latch table entry at head of chain
169 } BtHashEntry;
170
171 //      latch manager table structure
172
173 typedef struct {
174         BtLatch readwr[1];                      // read/write page lock
175         BtLatch access[1];                      // Access Intent/Page delete
176         BtLatch parent[1];                      // adoption of foster children
177         BtLatch busy[1];                        // slot is being moved between chains
178         volatile ushort next;           // next entry in hash table chain
179         volatile ushort prev;           // prev entry in hash table chain
180         volatile ushort pin;            // number of outstanding locks
181         volatile ushort hash;           // hash slot entry is under
182         volatile uid page_no;           // latch set page number
183 } BtLatchSet;
184
185 //      The memory mapping pool table buffer manager entry
186
187 typedef struct {
188         unsigned long long int lru;     // number of times accessed
189         uid  basepage;                          // mapped base page number
190         char *map;                                      // mapped memory pointer
191         ushort slot;                            // slot index in this array
192         ushort pin;                                     // mapped page pin counter
193         void *hashprev;                         // previous pool entry for the same hash idx
194         void *hashnext;                         // next pool entry for the same hash idx
195 #ifndef unix
196         HANDLE hmap;                            // Windows memory mapping handle
197 #endif
198 } BtPool;
199
200 //      structure for latch manager on ALLOC_page
201
202 typedef struct {
203         struct Page alloc[2];           // next & free page_nos in right ptr
204         BtLatch lock[1];                        // allocation area lite latch
205         ushort latchdeployed;           // highest number of latch entries deployed
206         ushort nlatchpage;                      // number of latch pages at BT_latch
207         ushort latchtotal;                      // number of page latch entries
208         ushort latchhash;                       // number of latch hash table slots
209         ushort latchvictim;                     // next latch entry to examine
210         BtHashEntry table[0];           // the hash table
211 } BtLatchMgr;
212
213 //      The object structure for Btree access
214
215 typedef struct {
216         uint page_size;                         // page size    
217         uint page_bits;                         // page size in bits    
218         uint seg_bits;                          // seg size in pages in bits
219         uint mode;                                      // read-write mode
220 #ifdef unix
221         char *pooladvise;                       // bit maps for pool page advisements
222         int idx;
223 #else
224         HANDLE idx;
225 #endif
226         ushort poolcnt;                         // highest page pool node in use
227         ushort poolmax;                         // highest page pool node allocated
228         ushort poolmask;                        // total number of pages in mmap segment - 1
229         ushort evicted;                         // last evicted hash table slot
230         ushort hashsize;                        // size of Hash Table for pool entries
231         ushort *hash;                           // pool index for hash entries
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         BtPool *pool;                           // memory pool page segments
236 #ifndef unix
237         HANDLE halloc;                          // allocation and latch table handle
238 #endif
239 } BtMgr;
240
241 typedef struct {
242         BtMgr *mgr;                     // buffer manager for thread
243         BtPage cursor;          // cached frame for start/next (never mapped)
244         BtPage frame;           // spare frame for the page split (never mapped)
245         BtPage zero;            // page of zeroes to extend the file (never mapped)
246         BtPage page;            // current page mapped from file
247         uid page_no;            // current page number  
248         uid cursor_page;        // current cursor page number   
249         BtLatchSet *set;        // current page latchset
250         BtPool *pool;           // current page pool
251         unsigned char *mem;     // frame, cursor, page memory buffer
252         int found;                      // last delete or insert was found
253         int err;                        // last error
254 } BtDb;
255
256 typedef enum {
257         BTERR_ok = 0,
258         BTERR_struct,
259         BTERR_ovflw,
260         BTERR_lock,
261         BTERR_map,
262         BTERR_wrt,
263         BTERR_hash
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) (page->table + 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 mgrlatch:
951 #ifdef unix
952         flag = PROT_READ | PROT_WRITE;
953         mgr->latchmgr = mmap (0, mgr->page_size, flag, MAP_SHARED, mgr->idx, ALLOC_page * mgr->page_size);
954         if( mgr->latchmgr == MAP_FAILED )
955                 return bt_mgrclose (mgr), NULL;
956         mgr->latchsets = (BtLatchSet *)mmap (0, mgr->latchmgr->nlatchpage * mgr->page_size, flag, MAP_SHARED, mgr->idx, LATCH_page * mgr->page_size);
957         if( mgr->latchsets == MAP_FAILED )
958                 return bt_mgrclose (mgr), NULL;
959 #else
960         flag = PAGE_READWRITE;
961         mgr->halloc = CreateFileMapping(mgr->idx, NULL, flag, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size, NULL);
962         if( !mgr->halloc )
963                 return bt_mgrclose (mgr), NULL;
964
965         flag = FILE_MAP_WRITE;
966         mgr->latchmgr = MapViewOfFile(mgr->halloc, flag, 0, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size);
967         if( !mgr->latchmgr )
968                 return GetLastError(), bt_mgrclose (mgr), NULL;
969
970         mgr->latchsets = (void *)((char *)mgr->latchmgr + LATCH_page * mgr->page_size);
971 #endif
972
973 #ifdef unix
974         free (latchmgr);
975 #else
976         VirtualFree (latchmgr, 0, MEM_RELEASE);
977 #endif
978         return mgr;
979 }
980
981 //      open BTree access method
982 //      based on buffer manager
983
984 BtDb *bt_open (BtMgr *mgr)
985 {
986 BtDb *bt = malloc (sizeof(*bt));
987
988         memset (bt, 0, sizeof(*bt));
989         bt->mgr = mgr;
990 #ifdef unix
991         bt->mem = malloc (3 *mgr->page_size);
992 #else
993         bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
994 #endif
995         bt->frame = (BtPage)bt->mem;
996         bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
997         bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
998
999         memset (bt->zero, 0, mgr->page_size);
1000         return bt;
1001 }
1002
1003 //  compare two keys, returning > 0, = 0, or < 0
1004 //  as the comparison value
1005
1006 int keycmp (BtKey key1, unsigned char *key2, uint len2)
1007 {
1008 uint len1 = key1->len;
1009 int ans;
1010
1011         if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
1012                 return ans;
1013
1014         if( len1 > len2 )
1015                 return 1;
1016         if( len1 < len2 )
1017                 return -1;
1018
1019         return 0;
1020 }
1021
1022 //      Buffer Pool mgr
1023
1024 // find segment in pool
1025 // must be called with hashslot idx locked
1026 //      return NULL if not there
1027 //      otherwise return node
1028
1029 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
1030 {
1031 BtPool *pool;
1032 uint slot;
1033
1034         // compute start of hash chain in pool
1035
1036         if( slot = bt->mgr->hash[idx] ) 
1037                 pool = bt->mgr->pool + slot;
1038         else
1039                 return NULL;
1040
1041         page_no &= ~bt->mgr->poolmask;
1042
1043         while( pool->basepage != page_no )
1044           if( pool = pool->hashnext )
1045                 continue;
1046           else
1047                 return NULL;
1048
1049         return pool;
1050 }
1051
1052 // add segment to hash table
1053
1054 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
1055 {
1056 BtPool *node;
1057 uint slot;
1058
1059         pool->hashprev = pool->hashnext = NULL;
1060         pool->basepage = page_no & ~bt->mgr->poolmask;
1061         pool->lru = 1;
1062
1063         if( slot = bt->mgr->hash[idx] ) {
1064                 node = bt->mgr->pool + slot;
1065                 pool->hashnext = node;
1066                 node->hashprev = pool;
1067         }
1068
1069         bt->mgr->hash[idx] = pool->slot;
1070 }
1071
1072 //      find best segment to evict from buffer pool
1073
1074 BtPool *bt_findlru (BtDb *bt, uint hashslot)
1075 {
1076 unsigned long long int target = ~0LL;
1077 BtPool *pool = NULL, *node;
1078
1079         if( !hashslot )
1080                 return NULL;
1081
1082         node = bt->mgr->pool + hashslot;
1083
1084         //  scan pool entries under hash table slot
1085
1086         do {
1087           if( node->pin )
1088                 continue;
1089           if( node->lru > target )
1090                 continue;
1091           target = node->lru;
1092           pool = node;
1093         } while( node = node->hashnext );
1094
1095         return pool;
1096 }
1097
1098 //  map new buffer pool segment to virtual memory
1099
1100 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
1101 {
1102 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
1103 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
1104 int flag;
1105
1106 #ifdef unix
1107         flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
1108         pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED, bt->mgr->idx, off);
1109         if( pool->map == MAP_FAILED )
1110                 return bt->err = BTERR_map;
1111
1112         // clear out madvise issued bits
1113         memset (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8) / 8), 0, (bt->mgr->poolmask + 8)/8);
1114 #else
1115         flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
1116         pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
1117         if( !pool->hmap )
1118                 return bt->err = BTERR_map;
1119
1120         flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
1121         pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1122         if( !pool->map )
1123                 return bt->err = BTERR_map;
1124 #endif
1125         return bt->err = 0;
1126 }
1127
1128 //      calculate page within pool
1129
1130 BtPage bt_page (BtDb *bt, BtPool *pool, uid page_no)
1131 {
1132 uint subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1133 BtPage page;
1134
1135         page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1136 #ifdef unix
1137         {
1138         uint idx = subpage / 8;
1139         uint bit = subpage % 8;
1140
1141                 if( ~((bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] >> bit) & 1 ) {
1142                   madvise (page, bt->mgr->page_size, MADV_WILLNEED);
1143                   (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] |= 1 << bit;
1144                 }
1145         }
1146 #endif
1147         return page;
1148 }
1149
1150 //  release pool pin
1151
1152 void bt_unpinpool (BtPool *pool)
1153 {
1154 #ifdef unix
1155         __sync_fetch_and_add(&pool->pin, -1);
1156 #else
1157         _InterlockedDecrement16 (&pool->pin);
1158 #endif
1159 }
1160
1161 //      find or place requested page in segment-pool
1162 //      return pool table entry, incrementing pin
1163
1164 BtPool *bt_pinpool(BtDb *bt, uid page_no)
1165 {
1166 BtPool *pool, *node, *next;
1167 uint slot, idx, victim;
1168
1169         //      lock hash table chain
1170
1171         idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1172         bt_spinreadlock (&bt->mgr->latch[idx], 1);
1173
1174         //      look up in hash table
1175
1176         if( pool = bt_findpool(bt, page_no, idx) ) {
1177 #ifdef unix
1178                 __sync_fetch_and_add(&pool->pin, 1);
1179 #else
1180                 _InterlockedIncrement16 (&pool->pin);
1181 #endif
1182                 bt_spinreleaseread (&bt->mgr->latch[idx], 1);
1183                 pool->lru++;
1184                 return pool;
1185         }
1186
1187         //      upgrade to write lock
1188
1189         bt_spinreleaseread (&bt->mgr->latch[idx], 1);
1190         bt_spinwritelock (&bt->mgr->latch[idx], 1);
1191
1192         // try to find page in pool with write lock
1193
1194         if( pool = bt_findpool(bt, page_no, idx) ) {
1195 #ifdef unix
1196                 __sync_fetch_and_add(&pool->pin, 1);
1197 #else
1198                 _InterlockedIncrement16 (&pool->pin);
1199 #endif
1200                 bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
1201                 pool->lru++;
1202                 return pool;
1203         }
1204
1205         // allocate a new pool node
1206         // and add to hash table
1207
1208 #ifdef unix
1209         slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
1210 #else
1211         slot = _InterlockedIncrement16 (&bt->mgr->poolcnt) - 1;
1212 #endif
1213
1214         if( ++slot < bt->mgr->poolmax ) {
1215                 pool = bt->mgr->pool + slot;
1216                 pool->slot = slot;
1217
1218                 if( bt_mapsegment(bt, pool, page_no) )
1219                         return NULL;
1220
1221                 bt_linkhash(bt, pool, page_no, idx);
1222 #ifdef unix
1223                 __sync_fetch_and_add(&pool->pin, 1);
1224 #else
1225                 _InterlockedIncrement16 (&pool->pin);
1226 #endif
1227                 bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
1228                 return pool;
1229         }
1230
1231         // pool table is full
1232         //      find best pool entry to evict
1233
1234 #ifdef unix
1235         __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
1236 #else
1237         _InterlockedDecrement16 (&bt->mgr->poolcnt);
1238 #endif
1239
1240         while( 1 ) {
1241 #ifdef unix
1242                 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
1243 #else
1244                 victim = _InterlockedIncrement16 (&bt->mgr->evicted) - 1;
1245 #endif
1246                 victim %= bt->mgr->hashsize;
1247
1248                 // try to get write lock
1249                 //      skip entry if not obtained
1250
1251                 if( !bt_spinwritetry (&bt->mgr->latch[victim]) )
1252                         continue;
1253
1254                 //  if pool entry is empty
1255                 //      or any pages are pinned
1256                 //      skip this entry
1257
1258                 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
1259                         bt_spinreleasewrite (&bt->mgr->latch[victim], 1);
1260                         continue;
1261                 }
1262
1263                 // unlink victim pool node from hash table
1264
1265                 if( node = pool->hashprev )
1266                         node->hashnext = pool->hashnext;
1267                 else if( node = pool->hashnext )
1268                         bt->mgr->hash[victim] = node->slot;
1269                 else
1270                         bt->mgr->hash[victim] = 0;
1271
1272                 if( node = pool->hashnext )
1273                         node->hashprev = pool->hashprev;
1274
1275                 bt_spinreleasewrite (&bt->mgr->latch[victim], 1);
1276
1277                 //      remove old file mapping
1278 #ifdef unix
1279                 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1280 #else
1281                 FlushViewOfFile(pool->map, 0);
1282                 UnmapViewOfFile(pool->map);
1283                 CloseHandle(pool->hmap);
1284 #endif
1285                 pool->map = NULL;
1286
1287                 //  create new pool mapping
1288                 //  and link into hash table
1289
1290                 if( bt_mapsegment(bt, pool, page_no) )
1291                         return NULL;
1292
1293                 bt_linkhash(bt, pool, page_no, idx);
1294 #ifdef unix
1295                 __sync_fetch_and_add(&pool->pin, 1);
1296 #else
1297                 _InterlockedIncrement16 (&pool->pin);
1298 #endif
1299                 bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
1300                 return pool;
1301         }
1302 }
1303
1304 // place write, read, or parent lock on requested page_no.
1305
1306 void bt_lockpage(BtLock mode, BtLatchSet *set)
1307 {
1308         switch( mode ) {
1309         case BtLockRead:
1310                 bt_spinreadlock (set->readwr, 0);
1311                 break;
1312         case BtLockWrite:
1313                 bt_spinwritelock (set->readwr, 0);
1314                 break;
1315         case BtLockAccess:
1316                 bt_spinreadlock (set->access, 0);
1317                 break;
1318         case BtLockDelete:
1319                 bt_spinwritelock (set->access, 0);
1320                 break;
1321         case BtLockParent:
1322                 bt_spinwritelock (set->parent, 0);
1323                 break;
1324         }
1325 }
1326
1327 // remove write, read, or parent lock on requested page
1328
1329 void bt_unlockpage(BtLock mode, BtLatchSet *set)
1330 {
1331         switch( mode ) {
1332         case BtLockRead:
1333                 bt_spinreleaseread (set->readwr, 0);
1334                 break;
1335         case BtLockWrite:
1336                 bt_spinreleasewrite (set->readwr, 0);
1337                 break;
1338         case BtLockAccess:
1339                 bt_spinreleaseread (set->access, 0);
1340                 break;
1341         case BtLockDelete:
1342                 bt_spinreleasewrite (set->access, 0);
1343                 break;
1344         case BtLockParent:
1345                 bt_spinreleasewrite (set->parent, 0);
1346                 break;
1347         }
1348 }
1349
1350 //      allocate a new page and write page into it
1351
1352 uid bt_newpage(BtDb *bt, BtPage page)
1353 {
1354 BtLatchSet *set;
1355 BtPool *pool;
1356 uid new_page;
1357 BtPage pmap;
1358 int reuse;
1359
1360         //      lock allocation page
1361
1362         bt_spinwritelock(bt->mgr->latchmgr->lock, 0);
1363
1364         // use empty chain first
1365         // else allocate empty page
1366
1367         if( new_page = bt_getid(bt->mgr->latchmgr->alloc[1].right) ) {
1368                 if( pool = bt_pinpool (bt, new_page) )
1369                         pmap = bt_page (bt, pool, new_page);
1370                 else
1371                         return 0;
1372                 bt_putid(bt->mgr->latchmgr->alloc[1].right, bt_getid(pmap->right));
1373                 bt_unpinpool (pool);
1374                 reuse = 1;
1375         } else {
1376                 new_page = bt_getid(bt->mgr->latchmgr->alloc->right);
1377                 bt_putid(bt->mgr->latchmgr->alloc->right, new_page+1);
1378                 reuse = 0;
1379         }
1380 #ifdef unix
1381         if ( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1382                 return bt->err = BTERR_wrt, 0;
1383
1384         // if writing first page of pool block, zero last page in the block
1385
1386         if ( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1387         {
1388                 // use zero buffer to write zeros
1389                 memset(bt->zero, 0, bt->mgr->page_size);
1390                 if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1391                         return bt->err = BTERR_wrt, 0;
1392         }
1393 #else
1394         //      bring new page into pool and copy page.
1395         //      this will extend the file into the new pages.
1396
1397         if( pool = bt_pinpool (bt, new_page) )
1398                 pmap = bt_page (bt, pool, new_page);
1399         else
1400                 return 0;
1401
1402         memcpy(pmap, page, bt->mgr->page_size);
1403         bt_unpinpool (pool);
1404 #endif
1405         // unlock allocation latch and return new page no
1406
1407         bt_spinreleasewrite(bt->mgr->latchmgr->lock, 0);
1408         return new_page;
1409 }
1410
1411 //  find slot in page for given key at a given level
1412
1413 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1414 {
1415 uint diff, higher = bt->page->cnt, low = 1, slot;
1416 uint good = 0;
1417
1418         //      make stopper key an infinite fence value
1419
1420         if( bt_getid (bt->page->right) )
1421                 higher++;
1422         else
1423                 good++;
1424
1425         //      low is the next candidate, higher is already
1426         //      tested as .ge. the given key, loop ends when they meet
1427
1428         while( diff = higher - low ) {
1429                 slot = low + ( diff >> 1 );
1430                 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1431                         low = slot + 1;
1432                 else
1433                         higher = slot, good++;
1434         }
1435
1436         //      return zero if key is on right link page
1437
1438         return good ? higher : 0;
1439 }
1440
1441 //  find and load page at given level for given key
1442 //      leave page rd or wr locked as requested
1443
1444 int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, uint lock)
1445 {
1446 uid page_no = ROOT_page, prevpage = 0;
1447 BtLatchSet *set, *prevset;
1448 uint drill = 0xff, slot;
1449 uint mode, prevmode;
1450 BtPool *prevpool;
1451
1452   //  start at root of btree and drill down
1453
1454   bt->set = NULL;
1455
1456   do {
1457         // determine lock mode of drill level
1458         mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead; 
1459
1460         bt->set = bt_pinlatch (bt, page_no);
1461         bt->page_no = page_no;
1462
1463         // pin page contents
1464
1465         if( bt->pool = bt_pinpool (bt, page_no) )
1466                 bt->page = bt_page (bt, bt->pool, page_no);
1467         else
1468                 return 0;
1469
1470         // obtain access lock using lock chaining with Access mode
1471
1472         if( page_no > ROOT_page )
1473           bt_lockpage(BtLockAccess, bt->set);
1474
1475         //      release & unpin parent page
1476
1477         if( prevpage ) {
1478           bt_unlockpage(prevmode, prevset);
1479           bt_unpinlatch (prevset);
1480           bt_unpinpool (prevpool);
1481           prevpage = 0;
1482         }
1483
1484         // obtain read lock using lock chaining
1485
1486         bt_lockpage(mode, bt->set);
1487
1488         if( page_no > ROOT_page )
1489           bt_unlockpage(BtLockAccess, bt->set);
1490
1491         // re-read and re-lock root after determining actual level of root
1492
1493         if( bt->page->lvl != drill) {
1494                 if ( bt->page_no != ROOT_page )
1495                         return bt->err = BTERR_struct, 0;
1496                         
1497                 drill = bt->page->lvl;
1498
1499                 if( lock == BtLockWrite && drill == lvl ) {
1500                   bt_unlockpage(mode, bt->set);
1501                   bt_unpinlatch (bt->set);
1502                   bt_unpinpool (bt->pool);
1503                   continue;
1504                 }
1505         }
1506
1507         //  find key on page at this level
1508         //  and descend to requested level
1509
1510         if( !bt->page->kill && (slot = bt_findslot (bt, key, len)) ) {
1511           if( drill == lvl )
1512                 return slot;
1513
1514           while( slotptr(bt->page, slot)->dead )
1515                 if( slot++ < bt->page->cnt )
1516                         continue;
1517                 else {
1518                         page_no = bt_getid(bt->page->right);
1519                         goto slideright;
1520                 }
1521
1522           page_no = bt_getid(slotptr(bt->page, slot)->id);
1523           drill--;
1524         }
1525
1526         //  or slide right into next page
1527         //  (slide left from deleted page)
1528
1529         else
1530                 page_no = bt_getid(bt->page->right);
1531
1532         //  continue down / right using overlapping locks
1533         //  to protect pages being killed or split.
1534
1535 slideright:
1536         prevpage = bt->page_no;
1537         prevpool = bt->pool;
1538         prevset = bt->set;
1539         prevmode = mode;
1540   } while( page_no );
1541
1542   // return error on end of right chain
1543
1544   bt->err = BTERR_struct;
1545   return 0;     // return error
1546 }
1547
1548 //  find and delete key on page by marking delete flag bit
1549 //  when page becomes empty, delete it
1550
1551 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl)
1552 {
1553 unsigned char lowerkey[256], higherkey[256];
1554 BtLatchSet *rset, *set;
1555 BtPool *pool, *rpool;
1556 uid page_no, right;
1557 uint slot, tod;
1558 BtPage rpage;
1559 BtKey ptr;
1560
1561         if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1562                 ptr = keyptr(bt->page, slot);
1563         else
1564                 return bt->err;
1565
1566         // if key is found delete it, otherwise ignore request
1567
1568         if( bt->found = !keycmp (ptr, key, len) )
1569                 if( bt->found = slotptr(bt->page, slot)->dead == 0 ) {
1570                         slotptr(bt->page,slot)->dead = 1;
1571                         if( slot < bt->page->cnt )
1572                                 bt->page->dirty = 1;
1573                         bt->page->act--;
1574                 }
1575
1576         // return if page is not empty, or it has no right sibling
1577
1578         right = bt_getid(bt->page->right);
1579         page_no = bt->page_no;
1580         pool = bt->pool;
1581         set = bt->set;
1582
1583         if( !right || bt->page->act ) {
1584                 bt_unlockpage(BtLockWrite, set);
1585                 bt_unpinlatch (set);
1586                 bt_unpinpool (pool);
1587                 return bt->err;
1588         }
1589
1590         // obtain Parent lock over write lock
1591
1592         bt_lockpage(BtLockParent, set);
1593
1594         // keep copy of key to delete
1595
1596         ptr = keyptr(bt->page, bt->page->cnt);
1597         memcpy(lowerkey, ptr, ptr->len + 1);
1598
1599         // lock and map right page
1600
1601         if( rpool = bt_pinpool (bt, right) )
1602                 rpage = bt_page (bt, rpool, right);
1603         else
1604                 return bt->err;
1605
1606         rset = bt_pinlatch (bt, right);
1607         bt_lockpage(BtLockWrite, rset);
1608
1609         // pull contents of next page into current empty page 
1610
1611         memcpy (bt->page, rpage, bt->mgr->page_size);
1612
1613         //      keep copy of key to update
1614
1615         ptr = keyptr(rpage, rpage->cnt);
1616         memcpy(higherkey, ptr, ptr->len + 1);
1617
1618         //  Mark right page as deleted and point it to left page
1619         //      until we can post updates at higher level.
1620
1621         bt_putid(rpage->right, page_no);
1622         rpage->kill = 1;
1623         rpage->cnt = 0;
1624
1625         bt_unlockpage(BtLockWrite, rset);
1626         bt_unlockpage(BtLockWrite, set);
1627
1628         //  delete old lower key to consolidated node
1629
1630         if( bt_deletekey (bt, lowerkey + 1, *lowerkey, lvl + 1) )
1631                 return bt->err;
1632
1633         //  redirect higher key directly to consolidated node
1634
1635         tod = (uint)time(NULL);
1636
1637         if( bt_insertkey (bt, higherkey+1, *higherkey, lvl + 1, page_no, tod) )
1638                 return bt->err;
1639
1640         //      add killed right block to free chain
1641         //      lock latch mgr
1642
1643         bt_spinwritelock(bt->mgr->latchmgr->lock, 0);
1644
1645         //      store free chain in allocation page second right
1646         bt_putid(rpage->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1647         bt_putid(bt->mgr->latchmgr->alloc[1].right, right);
1648
1649         // unlock latch mgr and unpin right page
1650
1651         bt_spinreleasewrite(bt->mgr->latchmgr->lock, 0);
1652         bt_unpinlatch (rset);
1653         bt_unpinpool (rpool);
1654
1655         //      remove ParentModify lock
1656
1657         bt_unlockpage(BtLockParent, set);
1658         bt_unpinlatch (set);
1659         bt_unpinpool (pool);
1660         return 0;
1661 }
1662
1663 //      find key in leaf level and return row-id
1664
1665 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1666 {
1667 uint  slot;
1668 BtKey ptr;
1669 uid id;
1670
1671         if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1672                 ptr = keyptr(bt->page, slot);
1673         else
1674                 return 0;
1675
1676         // if key exists, return row-id
1677         //      otherwise return 0
1678
1679         if( ptr->len == len && !memcmp (ptr->key, key, len) )
1680                 id = bt_getid(slotptr(bt->page,slot)->id);
1681         else
1682                 id = 0;
1683
1684         bt_unlockpage (BtLockRead, bt->set);
1685         bt_unpinlatch (bt->set);
1686         bt_unpinpool (bt->pool);
1687         return id;
1688 }
1689
1690 //      check page for space available,
1691 //      clean if necessary and return
1692 //      =0 - page needs splitting
1693 //      >0 - go ahead at returned slot
1694
1695 uint bt_cleanpage(BtDb *bt, uint amt, uint slot)
1696 {
1697 uint nxt = bt->mgr->page_size;
1698 BtPage page = bt->page;
1699 uint cnt = 0, idx = 0;
1700 uint max = page->cnt;
1701 uint newslot;
1702 BtKey key;
1703
1704         if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1705                 return slot;
1706
1707         //      skip cleanup if nothing to reclaim
1708
1709         if( !page->dirty )
1710                 return 0;
1711
1712         memcpy (bt->frame, page, bt->mgr->page_size);
1713
1714         // skip page info and set rest of page to zero
1715
1716         memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1717         page->dirty = 0;
1718         page->act = 0;
1719
1720         // always leave fence key in list
1721
1722         while( cnt++ < max ) {
1723                 if( cnt == slot )
1724                         newslot = idx + 1;
1725                 else if( cnt < max && slotptr(bt->frame,cnt)->dead )
1726                         continue;
1727
1728                 // copy key
1729                 key = keyptr(bt->frame, cnt);
1730                 nxt -= key->len + 1;
1731                 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1732
1733                 // copy slot
1734                 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1735                 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1736                         page->act++;
1737                 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1738                 slotptr(page, idx)->off = nxt;
1739         }
1740         page->min = nxt;
1741         page->cnt = idx;
1742
1743         if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1744                 return newslot;
1745
1746         return 0;
1747 }
1748
1749 // split the root and raise the height of the btree
1750
1751 BTERR bt_splitroot(BtDb *bt,  unsigned char *newkey, unsigned char *oldkey, uid page_no2)
1752 {
1753 uint nxt = bt->mgr->page_size;
1754 BtPage root = bt->page;
1755 uid new_page;
1756
1757         //  Obtain an empty page to use, and copy the current
1758         //  root contents into it which is the lower half of
1759         //      the old root.
1760
1761         if( !(new_page = bt_newpage(bt, root)) )
1762                 return bt->err;
1763
1764         // preserve the page info at the bottom
1765         // and set rest to zero
1766
1767         memset(root+1, 0, bt->mgr->page_size - sizeof(*root));
1768
1769         // insert first key on newroot page
1770
1771         nxt -= *newkey + 1;
1772         memcpy ((unsigned char *)root + nxt, newkey, *newkey + 1);
1773         bt_putid(slotptr(root, 1)->id, new_page);
1774         slotptr(root, 1)->off = nxt;
1775         
1776         // insert second key on newroot page
1777         // and increase the root height
1778
1779         nxt -= *oldkey + 1;
1780         memcpy ((unsigned char *)root + nxt, oldkey, *oldkey + 1);
1781         bt_putid(slotptr(root, 2)->id, page_no2);
1782         slotptr(root, 2)->off = nxt;
1783
1784         bt_putid(root->right, 0);
1785         root->min = nxt;                // reset lowest used offset and key count
1786         root->cnt = 2;
1787         root->act = 2;
1788         root->lvl++;
1789
1790         // release and unpin root (bt->page)
1791
1792         bt_unlockpage(BtLockWrite, bt->set);
1793         bt_unpinlatch (bt->set);
1794         bt_unpinpool (bt->pool);
1795         return 0;
1796 }
1797
1798 //  split already locked full node
1799 //      return unlocked.
1800
1801 BTERR bt_splitpage (BtDb *bt)
1802 {
1803 uint cnt = 0, idx = 0, max, nxt = bt->mgr->page_size;
1804 unsigned char oldkey[256], lowerkey[256];
1805 uid page_no = bt->page_no, right;
1806 BtLatchSet *nset, *set = bt->set;
1807 BtPool *pool = bt->pool;
1808 BtPage page = bt->page;
1809 uint lvl = page->lvl;
1810 uid new_page;
1811 BtKey key;
1812 uint tod;
1813
1814         //  split higher half of keys to bt->frame
1815         //      the last key (fence key) might be dead
1816
1817         tod = (uint)time(NULL);
1818
1819         memset (bt->frame, 0, bt->mgr->page_size);
1820         max = (int)page->cnt;
1821         cnt = max / 2;
1822         idx = 0;
1823
1824         while( cnt++ < max ) {
1825                 key = keyptr(page, cnt);
1826                 nxt -= key->len + 1;
1827                 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
1828                 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
1829                 if( !(slotptr(bt->frame, idx)->dead = slotptr(page, cnt)->dead) )
1830                         bt->frame->act++;
1831                 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
1832                 slotptr(bt->frame, idx)->off = nxt;
1833         }
1834
1835         // remember existing fence key for new page to the right
1836
1837         memcpy (oldkey, key, key->len + 1);
1838
1839         bt->frame->bits = bt->mgr->page_bits;
1840         bt->frame->min = nxt;
1841         bt->frame->cnt = idx;
1842         bt->frame->lvl = lvl;
1843
1844         // link right node
1845
1846         if( page_no > ROOT_page ) {
1847                 right = bt_getid (page->right);
1848                 bt_putid(bt->frame->right, right);
1849         }
1850
1851         //      get new free page and write frame to it.
1852
1853         if( !(new_page = bt_newpage(bt, bt->frame)) )
1854                 return bt->err;
1855
1856         //      update lower keys to continue in old page
1857
1858         memcpy (bt->frame, page, bt->mgr->page_size);
1859         memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1860         nxt = bt->mgr->page_size;
1861         page->act = 0;
1862         cnt = 0;
1863         idx = 0;
1864
1865         //  assemble page of smaller keys
1866         //      (they're all active keys)
1867
1868         while( cnt++ < max / 2 ) {
1869                 key = keyptr(bt->frame, cnt);
1870                 nxt -= key->len + 1;
1871                 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1872                 memcpy(slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1873                 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1874                 slotptr(page, idx)->off = nxt;
1875                 page->act++;
1876         }
1877
1878         // remember fence key for old page
1879
1880         memcpy(lowerkey, key, key->len + 1);
1881         bt_putid(page->right, new_page);
1882         page->min = nxt;
1883         page->cnt = idx;
1884
1885         // if current page is the root page, split it
1886
1887         if( page_no == ROOT_page )
1888                 return bt_splitroot (bt, lowerkey, oldkey, new_page);
1889
1890         // obtain Parent/Write locks
1891         // for left and right node pages
1892
1893         nset = bt_pinlatch (bt, new_page);
1894
1895         bt_lockpage (BtLockParent, nset);
1896         bt_lockpage (BtLockParent, set);
1897
1898         //  release wr lock on left page
1899         //  (keep the SMO in sequence)
1900
1901         bt_unlockpage (BtLockWrite, set);
1902
1903         // insert new fence for reformulated left block
1904
1905         if( bt_insertkey (bt, lowerkey+1, *lowerkey, lvl + 1, page_no, tod) )
1906                 return bt->err;
1907
1908         // fix old fence for newly allocated right block page
1909
1910         if( bt_insertkey (bt, oldkey+1, *oldkey, lvl + 1, new_page, tod) )
1911                 return bt->err;
1912
1913         // release Parent locks
1914
1915         bt_unlockpage (BtLockParent, nset);
1916         bt_unlockpage (BtLockParent, set);
1917         bt_unpinlatch (nset);
1918         bt_unpinlatch (set);
1919         bt_unpinpool (pool);
1920         return 0;
1921 }
1922
1923 //  Insert new key into the btree at requested level.
1924 //  Level zero pages are leaf pages. Page is unlocked at exit.
1925
1926 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod)
1927 {
1928 uint slot, idx;
1929 BtPage page;
1930 BtKey ptr;
1931
1932   while( 1 ) {
1933         if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1934                 ptr = keyptr(bt->page, slot);
1935         else
1936         {
1937                 if ( !bt->err )
1938                         bt->err = BTERR_ovflw;
1939                 return bt->err;
1940         }
1941
1942         // if key already exists, update id and return
1943
1944         page = bt->page;
1945
1946         if( bt->found = !keycmp (ptr, key, len) ) {
1947                 slotptr(page, slot)->dead = 0;
1948                 slotptr(page, slot)->tod = tod;
1949                 bt_putid(slotptr(page,slot)->id, id);
1950                 bt_unlockpage(BtLockWrite, bt->set);
1951                 bt_unpinlatch(bt->set);
1952                 bt_unpinpool (bt->pool);
1953                 return bt->err;
1954         }
1955
1956         // check if page has enough space
1957
1958         if( slot = bt_cleanpage (bt, len, slot) )
1959                 break;
1960
1961         if( bt_splitpage (bt) )
1962                 return bt->err;
1963   }
1964
1965   // calculate next available slot and copy key into page
1966
1967   page->min -= len + 1; // reset lowest used offset
1968   ((unsigned char *)page)[page->min] = len;
1969   memcpy ((unsigned char *)page + page->min +1, key, len );
1970
1971   for( idx = slot; idx < page->cnt; idx++ )
1972         if( slotptr(page, idx)->dead )
1973                 break;
1974
1975   // now insert key into array before slot
1976   // preserving the fence slot
1977
1978   if( idx == page->cnt )
1979         idx++, page->cnt++;
1980
1981   page->act++;
1982
1983   while( idx > slot )
1984         *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
1985
1986   bt_putid(slotptr(page,slot)->id, id);
1987   slotptr(page, slot)->off = page->min;
1988   slotptr(page, slot)->tod = tod;
1989   slotptr(page, slot)->dead = 0;
1990
1991   bt_unlockpage (BtLockWrite, bt->set);
1992   bt_unpinlatch (bt->set);
1993   bt_unpinpool (bt->pool);
1994   return 0;
1995 }
1996
1997 //  cache page of keys into cursor and return starting slot for given key
1998
1999 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2000 {
2001 uint slot;
2002
2003         // cache page for retrieval
2004         if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
2005                 memcpy (bt->cursor, bt->page, bt->mgr->page_size);
2006         bt->cursor_page = bt->page_no;
2007         bt_unlockpage(BtLockRead, bt->set);
2008         bt_unpinlatch (bt->set);
2009         bt_unpinpool (bt->pool);
2010         return slot;
2011 }
2012
2013 //  return next slot for cursor page
2014 //  or slide cursor right into next page
2015
2016 uint bt_nextkey (BtDb *bt, uint slot)
2017 {
2018 BtPool *pool;
2019 BtPage page;
2020 uid right;
2021
2022   do {
2023         right = bt_getid(bt->cursor->right);
2024         while( slot++ < bt->cursor->cnt )
2025           if( slotptr(bt->cursor,slot)->dead )
2026                 continue;
2027           else if( right || (slot < bt->cursor->cnt))
2028                 return slot;
2029           else
2030                 break;
2031
2032         if( !right )
2033                 break;
2034
2035         bt->cursor_page = right;
2036
2037         if( pool = bt_pinpool (bt, right) )
2038                 page = bt_page (bt, pool, right);
2039         else
2040                 return 0;
2041
2042         bt->set = bt_pinlatch (bt, right);
2043     bt_lockpage(BtLockRead, bt->set);
2044
2045         memcpy (bt->cursor, page, bt->mgr->page_size);
2046
2047         bt_unlockpage(BtLockRead, bt->set);
2048         bt_unpinlatch (bt->set);
2049         bt_unpinpool (pool);
2050         slot = 0;
2051   } while( 1 );
2052
2053   return bt->err = 0;
2054 }
2055
2056 BtKey bt_key(BtDb *bt, uint slot)
2057 {
2058         return keyptr(bt->cursor, slot);
2059 }
2060
2061 uid bt_uid(BtDb *bt, uint slot)
2062 {
2063         return bt_getid(slotptr(bt->cursor,slot)->id);
2064 }
2065
2066 uint bt_tod(BtDb *bt, uint slot)
2067 {
2068         return slotptr(bt->cursor,slot)->tod;
2069 }
2070
2071 #ifdef STANDALONE
2072
2073 void bt_latchaudit (BtDb *bt)
2074 {
2075 ushort idx, hashidx;
2076 BtLatchSet *set;
2077 BtPool *pool;
2078 BtPage page;
2079 uid page_no;
2080
2081 #ifdef unix
2082         for( idx = 1; idx < bt->mgr->latchmgr->latchdeployed; idx++ ) {
2083                 set = bt->mgr->latchsets + idx;
2084                 if( *(ushort *)set->readwr || *(ushort *)set->access || *(ushort *)set->parent ) {
2085                         fprintf(stderr, "latchset %d locked for page %6x\n", idx, set->page_no);
2086                         *(ushort *)set->readwr = 0;
2087                         *(ushort *)set->access = 0;
2088                         *(ushort *)set->parent = 0;
2089                 }
2090                 if( set->pin ) {
2091                         fprintf(stderr, "latchset %d pinned\n", idx);
2092                         set->pin = 0;
2093                 }
2094         }
2095
2096         for( hashidx = 0; hashidx < bt->mgr->latchmgr->latchhash; hashidx++ ) {
2097           if( *(uint *)bt->mgr->latchmgr->table[hashidx].latch )
2098                 fprintf(stderr, "latchmgr locked\n");
2099           if( idx = bt->mgr->latchmgr->table[hashidx].slot ) do {
2100                 set = bt->mgr->latchsets + idx;
2101                 if( *(uint *)set->readwr || *(ushort *)set->access || *(ushort *)set->parent )
2102                         fprintf(stderr, "latchset %d locked\n", idx);
2103                 if( set->hash != hashidx )
2104                         fprintf(stderr, "latchset %d wrong hashidx\n", idx);
2105                 if( set->pin )
2106                         fprintf(stderr, "latchset %d pinned\n", idx);
2107           } while( idx = set->next );
2108         }
2109         page_no = bt_getid(bt->mgr->latchmgr->alloc[1].right);
2110
2111         while( page_no ) {
2112                 fprintf(stderr, "free: %.6x\n", (uint)page_no);
2113                 pool = bt_pinpool (bt, page_no);
2114                 page = bt_page (bt, pool, page_no);
2115             page_no = bt_getid(page->right);
2116                 bt_unpinpool (pool);
2117         }
2118 #endif
2119 }
2120
2121 typedef struct {
2122         char type, idx;
2123         char *infile;
2124         BtMgr *mgr;
2125         int num;
2126 } ThreadArg;
2127
2128 //  standalone program to index file of keys
2129 //  then list them onto std-out
2130
2131 #ifdef unix
2132 void *index_file (void *arg)
2133 #else
2134 uint __stdcall index_file (void *arg)
2135 #endif
2136 {
2137 int line = 0, found = 0, cnt = 0;
2138 uid next, page_no = LEAF_page;  // start on first page of leaves
2139 unsigned char key[256];
2140 ThreadArg *args = arg;
2141 int ch, len = 0, slot;
2142 time_t tod[1];
2143 BtPool *pool;
2144 BtPage page;
2145 BtKey ptr;
2146 BtDb *bt;
2147 FILE *in;
2148
2149         bt = bt_open (args->mgr);
2150         time (tod);
2151
2152         switch(args->type | 0x20)
2153         {
2154         case 'a':
2155                 fprintf(stderr, "started latch mgr audit\n");
2156                 bt_latchaudit (bt);
2157                 fprintf(stderr, "finished latch mgr audit\n");
2158                 break;
2159
2160         case 'w':
2161                 fprintf(stderr, "started indexing for %s\n", args->infile);
2162                 if( in = fopen (args->infile, "rb") )
2163                   while( ch = getc(in), ch != EOF )
2164                         if( ch == '\n' )
2165                         {
2166                           line++;
2167
2168                           if( args->num == 1 )
2169                                 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2170
2171                           else if( args->num )
2172                                 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2173
2174                           if( bt_insertkey (bt, key, len, 0, line, *tod) )
2175                                 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2176                           len = 0;
2177                         }
2178                         else if( len < 255 )
2179                                 key[len++] = ch;
2180                 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
2181                 break;
2182
2183         case 'd':
2184                 fprintf(stderr, "started deleting keys for %s\n", args->infile);
2185                 if( in = fopen (args->infile, "rb") )
2186                   while( ch = getc(in), ch != EOF )
2187                         if( ch == '\n' )
2188                         {
2189                           line++;
2190                           if( args->num == 1 )
2191                                 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2192
2193                           else if( args->num )
2194                                 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2195
2196                           if( bt_deletekey (bt, key, len, 0) )
2197                                 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2198                           len = 0;
2199                         }
2200                         else if( len < 255 )
2201                                 key[len++] = ch;
2202                 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2203                 break;
2204
2205         case 'f':
2206                 fprintf(stderr, "started finding keys for %s\n", args->infile);
2207                 if( in = fopen (args->infile, "rb") )
2208                   while( ch = getc(in), ch != EOF )
2209                         if( ch == '\n' )
2210                         {
2211                           line++;
2212                           if( args->num == 1 )
2213                                 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2214
2215                           else if( args->num )
2216                                 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2217
2218                           if( bt_findkey (bt, key, len) )
2219                                 found++;
2220                           else if( bt->err )
2221                                 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2222                           len = 0;
2223                         }
2224                         else if( len < 255 )
2225                                 key[len++] = ch;
2226                 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2227                 break;
2228
2229         case 's':
2230                 len = key[0] = 0;
2231
2232                 fprintf(stderr, "started reading\n");
2233
2234                 if( slot = bt_startkey (bt, key, len) )
2235                   slot--;
2236                 else
2237                   fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
2238
2239                 while( slot = bt_nextkey (bt, slot) ) {
2240                         ptr = bt_key(bt, slot);
2241                         fwrite (ptr->key, ptr->len, 1, stdout);
2242                         fputc ('\n', stdout);
2243                 }
2244
2245                 break;
2246
2247         case 'c':
2248                 fprintf(stderr, "started reading\n");
2249
2250                 do {
2251                         if( bt->pool = bt_pinpool (bt, page_no) )
2252                                 page = bt_page (bt, bt->pool, page_no);
2253                         else
2254                                 break;
2255                         bt->set = bt_pinlatch (bt, page_no);
2256                         bt_lockpage (BtLockRead, bt->set);
2257                         cnt += page->act;
2258                         next = bt_getid (page->right);
2259                         bt_unlockpage (BtLockRead, bt->set);
2260                         bt_unpinlatch (bt->set);
2261                         bt_unpinpool (bt->pool);
2262                 } while( page_no = next );
2263
2264                 cnt--;  // remove stopper key
2265                 fprintf(stderr, " Total keys read %d\n", cnt);
2266                 break;
2267         }
2268
2269         bt_close (bt);
2270 #ifdef unix
2271         return NULL;
2272 #else
2273         return 0;
2274 #endif
2275 }
2276
2277 typedef struct timeval timer;
2278
2279 int main (int argc, char **argv)
2280 {
2281 int idx, cnt, len, slot, err;
2282 int segsize, bits = 16;
2283 #ifdef unix
2284 pthread_t *threads;
2285 timer start, stop;
2286 #else
2287 time_t start[1], stop[1];
2288 HANDLE *threads;
2289 #endif
2290 double real_time;
2291 ThreadArg *args;
2292 uint poolsize = 0;
2293 int num = 0;
2294 char key[1];
2295 BtMgr *mgr;
2296 BtKey ptr;
2297 BtDb *bt;
2298
2299         if( argc < 3 ) {
2300                 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]);
2301                 fprintf (stderr, "  where page_bits is the page size in bits\n");
2302                 fprintf (stderr, "  mapped_segments is the number of mmap segments in buffer pool\n");
2303                 fprintf (stderr, "  seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2304                 fprintf (stderr, "  line_numbers = 1 to append line numbers to keys\n");
2305                 fprintf (stderr, "  src_file1 thru src_filen are files of keys separated by newline\n");
2306                 exit(0);
2307         }
2308
2309 #ifdef unix
2310         gettimeofday(&start, NULL);
2311 #else
2312         time(start);
2313 #endif
2314
2315         if( argc > 3 )
2316                 bits = atoi(argv[3]);
2317
2318         if( argc > 4 )
2319                 poolsize = atoi(argv[4]);
2320
2321         if( !poolsize )
2322                 fprintf (stderr, "Warning: no mapped_pool\n");
2323
2324         if( poolsize > 65535 )
2325                 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2326
2327         if( argc > 5 )
2328                 segsize = atoi(argv[5]);
2329         else
2330                 segsize = 4;    // 16 pages per mmap segment
2331
2332         if( argc > 6 )
2333                 num = atoi(argv[6]);
2334
2335         cnt = argc - 7;
2336 #ifdef unix
2337         threads = malloc (cnt * sizeof(pthread_t));
2338 #else
2339         threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2340 #endif
2341         args = malloc (cnt * sizeof(ThreadArg));
2342
2343         mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2344
2345         if( !mgr ) {
2346                 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2347                 exit (1);
2348         }
2349
2350         //      fire off threads
2351
2352         for( idx = 0; idx < cnt; idx++ ) {
2353                 args[idx].infile = argv[idx + 7];
2354                 args[idx].type = argv[2][0];
2355                 args[idx].mgr = mgr;
2356                 args[idx].num = num;
2357                 args[idx].idx = idx;
2358 #ifdef unix
2359                 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2360                         fprintf(stderr, "Error creating thread %d\n", err);
2361 #else
2362                 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2363 #endif
2364         }
2365
2366         //      wait for termination
2367
2368 #ifdef unix
2369         for( idx = 0; idx < cnt; idx++ )
2370                 pthread_join (threads[idx], NULL);
2371         gettimeofday(&stop, NULL);
2372         real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2373 #else
2374         WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2375
2376         for( idx = 0; idx < cnt; idx++ )
2377                 CloseHandle(threads[idx]);
2378
2379         time (stop);
2380         real_time = 1000 * (*stop - *start);
2381 #endif
2382         fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);
2383         bt_mgrclose (mgr);
2384 }
2385
2386 #endif  //STANDALONE