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