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