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