]> pd.if.org Git - btree/blob - btree2u.c
fix for buffer pools > 4GB. Recommend btree2u for linux
[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                 fprintf (stderr, "Unable to read page %.8x errno = %d\n", page_no, errno);
478                 return bt->err = BTERR_read;
479         }
480 #else
481 OVERLAPPED ovl[1];
482 uint amt[1];
483
484         memset (ovl, 0, sizeof(OVERLAPPED));
485         ovl->Offset = off;
486         ovl->OffsetHigh = off >> 32;
487
488         if( !ReadFile(bt->idx, page, bt->page_size, amt, ovl)) {
489                 fprintf (stderr, "Unable to read page %.8x GetLastError = %d\n", page_no, GetLastError());
490                 return bt->err = BTERR_read;
491         }
492         if( *amt <  bt->page_size ) {
493                 fprintf (stderr, "Unable to read page %.8x GetLastError = %d\n", page_no, GetLastError());
494                 return bt->err = BTERR_read;
495         }
496 #endif
497         return 0;
498 }
499
500 //      write page to permanent location in Btree file
501 //      clear the dirty bit
502
503 BTERR bt_writepage (BtDb *bt, BtPage page, uid page_no)
504 {
505 off64_t off = page_no << bt->page_bits;
506
507 #ifdef unix
508         page->dirty = 0;
509
510         if( pwrite(bt->idx, page, bt->page_size, off) < bt->page_size )
511                 return bt->err = BTERR_wrt;
512 #else
513 OVERLAPPED ovl[1];
514 uint amt[1];
515
516         memset (ovl, 0, sizeof(OVERLAPPED));
517         ovl->Offset = off;
518         ovl->OffsetHigh = off >> 32;
519         page->dirty = 0;
520
521         if( !WriteFile(bt->idx, page, bt->page_size, amt, ovl) )
522                 return bt->err = BTERR_wrt;
523
524         if( *amt <  bt->page_size )
525                 return bt->err = BTERR_wrt;
526 #endif
527         return 0;
528 }
529
530 //      link latch table entry into head of latch hash table
531
532 BTERR bt_latchlink (BtDb *bt, uint hashidx, uint slot, uid page_no)
533 {
534 BtPage page = (BtPage)((uid)slot * bt->page_size + bt->pagepool);
535 BtLatchSet *latch = bt->latchsets + slot;
536
537         if( latch->next = bt->table[hashidx].slot )
538                 bt->latchsets[latch->next].prev = slot;
539
540         bt->table[hashidx].slot = slot;
541         latch->page_no = page_no;
542         latch->prev = 0;
543         latch->pin = 1;
544
545         return bt_readpage (bt, page, page_no);
546 }
547
548 //      release latch pin
549
550 void bt_unpinlatch (BtLatchSet *latch)
551 {
552 #ifdef unix
553         __sync_fetch_and_add(&latch->pin, -1);
554 #else
555         _InterlockedDecrement (&latch->pin);
556 #endif
557 }
558
559 //      find existing latchset or inspire new one
560 //      return with latchset pinned
561
562 BtLatchSet *bt_pinlatch (BtDb *bt, uid page_no)
563 {
564 uint hashidx = page_no % bt->latchmgr->latchhash;
565 BtLatchSet *latch;
566 uint slot, idx;
567 off64_t off;
568 uint amt[1];
569 BtPage page;
570
571   //  try to find unpinned entry
572
573   bt_spinwritelock(bt->table[hashidx].latch);
574
575   if( slot = bt->table[hashidx].slot ) do
576   {
577         latch = bt->latchsets + slot;
578         if( page_no == latch->page_no )
579                 break;
580   } while( slot = latch->next );
581
582   //  found our entry, bring to front of hash chain
583
584   if( slot ) {
585         latch = bt->latchsets + slot;
586 #ifdef unix
587         __sync_fetch_and_add(&latch->pin, 1);
588 #else
589         _InterlockedIncrement (&latch->pin);
590 #endif
591         //  unlink our entry from its hash chain position
592
593         if( latch->prev )
594                 bt->latchsets[latch->prev].next = latch->next;
595         else
596                 bt->table[hashidx].slot = latch->next;
597
598         if( latch->next )
599                 bt->latchsets[latch->next].prev = latch->prev;
600
601         //  now link into head of the hash chain
602
603         if( latch->next = bt->table[hashidx].slot )
604                 bt->latchsets[latch->next].prev = slot;
605
606         bt->table[hashidx].slot = slot;
607         latch->prev = 0;
608
609         bt_spinreleasewrite(bt->table[hashidx].latch);
610         return latch;
611   }
612
613         //  see if there are any unused pool entries
614 #ifdef unix
615         slot = __sync_fetch_and_add (&bt->latchmgr->latchdeployed, 1) + 1;
616 #else
617         slot = _InterlockedIncrement (&bt->latchmgr->latchdeployed);
618 #endif
619
620         if( slot < bt->latchmgr->latchtotal ) {
621                 latch = bt->latchsets + slot;
622                 if( bt_latchlink (bt, hashidx, slot, page_no) )
623                         return NULL;
624                 bt_spinreleasewrite (bt->table[hashidx].latch);
625                 return latch;
626         }
627
628 #ifdef unix
629         __sync_fetch_and_add (&bt->latchmgr->latchdeployed, -1);
630 #else
631         _InterlockedDecrement (&bt->latchmgr->latchdeployed);
632 #endif
633   //  find and reuse previous lru lock entry on victim hash chain
634
635   while( 1 ) {
636 #ifdef unix
637         idx = __sync_fetch_and_add(&bt->latchmgr->latchvictim, 1);
638 #else
639         idx = _InterlockedIncrement (&bt->latchmgr->latchvictim) - 1;
640 #endif
641         // try to get write lock on hash chain
642         //      skip entry if not obtained
643         //      or has outstanding locks
644
645         idx %= bt->latchmgr->latchhash;
646
647         if( !bt_spinwritetry (bt->table[idx].latch) )
648                 continue;
649
650         if( slot = bt->table[idx].slot )
651           while( 1 ) {
652                 latch = bt->latchsets + slot;
653                 if( !latch->next )
654                         break;
655                 slot = latch->next;
656           }
657
658         if( !slot || latch->pin ) {
659                 bt_spinreleasewrite (bt->table[idx].latch);
660                 continue;
661         }
662
663         //  update permanent page area in btree
664
665         page = (BtPage)((uid)slot * bt->page_size + bt->pagepool);
666
667         if( page->dirty )
668           if( bt_writepage (bt, page, latch->page_no) )
669                 return NULL;
670
671         //  unlink our available slot from its hash chain
672
673         if( latch->prev )
674                 bt->latchsets[latch->prev].next = latch->next;
675         else
676                 bt->table[idx].slot = latch->next;
677
678         if( latch->next )
679                 bt->latchsets[latch->next].prev = latch->prev;
680
681         bt_spinreleasewrite (bt->table[idx].latch);
682
683         if( bt_latchlink (bt, hashidx, slot, page_no) )
684                 return NULL;
685
686         bt_spinreleasewrite (bt->table[hashidx].latch);
687         return latch;
688   }
689 }
690
691 //      close and release memory
692
693 void bt_close (BtDb *bt)
694 {
695 #ifdef unix
696         munmap (bt->table, bt->latchmgr->nlatchpage * bt->page_size);
697         munmap (bt->latchmgr, bt->page_size);
698 #else
699         FlushViewOfFile(bt->latchmgr, 0);
700         UnmapViewOfFile(bt->latchmgr);
701         CloseHandle(bt->halloc);
702 #endif
703 #ifdef unix
704         if( bt->mem )
705                 free (bt->mem);
706         close (bt->idx);
707         free (bt);
708 #else
709         if( bt->mem)
710                 VirtualFree (bt->mem, 0, MEM_RELEASE);
711         FlushFileBuffers(bt->idx);
712         CloseHandle(bt->idx);
713         GlobalFree (bt);
714 #endif
715 }
716 //  open/create new btree
717
718 //      call with file_name, BT_openmode, bits in page size (e.g. 16),
719 //              size of mapped page pool (e.g. 8192)
720
721 BtDb *bt_open (char *name, uint mode, uint bits, uint nodemax)
722 {
723 uint lvl, attr, last, slot, idx;
724 uint nlatchpage, latchhash;
725 BtLatchMgr *latchmgr;
726 off64_t size, off;
727 uint amt[1];
728 BtKey key;
729 BtDb* bt;
730 int flag;
731
732 #ifndef unix
733 OVERLAPPED ovl[1];
734 #else
735 struct flock lock[1];
736 #endif
737
738         // determine sanity of page size and buffer pool
739
740         if( bits > BT_maxbits )
741                 bits = BT_maxbits;
742         else if( bits < BT_minbits )
743                 bits = BT_minbits;
744
745         if( mode == BT_ro ) {
746                 fprintf(stderr, "ReadOnly mode not supported: %s\n", name);
747                 return NULL;
748         }
749 #ifdef unix
750         bt = calloc (1, sizeof(BtDb));
751
752         bt->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
753
754         if( bt->idx == -1 ) {
755                 fprintf(stderr, "unable to open %s\n", name);
756                 return free(bt), NULL;
757         }
758 #else
759         bt = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtDb));
760         attr = FILE_ATTRIBUTE_NORMAL;
761         bt->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
762
763         if( bt->idx == INVALID_HANDLE_VALUE ) {
764                 fprintf(stderr, "unable to open %s\n", name);
765                 return GlobalFree(bt), NULL;
766         }
767 #endif
768 #ifdef unix
769         memset (lock, 0, sizeof(lock));
770         lock->l_len = sizeof(struct BtPage_);
771         lock->l_type = F_WRLCK;
772
773         if( fcntl (bt->idx, F_SETLKW, lock) < 0 ) {
774                 fprintf(stderr, "unable to lock record zero %s\n", name);
775                 return bt_close (bt), NULL;
776         }
777 #else
778         memset (ovl, 0, sizeof(ovl));
779
780         //      use large offsets to
781         //      simulate advisory locking
782
783         ovl->OffsetHigh |= 0x80000000;
784
785         if( !LockFileEx (bt->idx, LOCKFILE_EXCLUSIVE_LOCK, 0, sizeof(struct BtPage_), 0L, ovl) ) {
786                 fprintf(stderr, "unable to lock record zero %s, GetLastError = %d\n", name, GetLastError());
787                 return bt_close (bt), NULL;
788         }
789 #endif 
790
791 #ifdef unix
792         latchmgr = malloc (BT_maxpage);
793         *amt = 0;
794
795         // read minimum page size to get root info
796
797         if( size = lseek (bt->idx, 0L, 2) ) {
798                 if( pread(bt->idx, latchmgr, BT_minpage, 0) == BT_minpage )
799                         bits = latchmgr->alloc->bits;
800                 else {
801                         fprintf(stderr, "Unable to read page zero\n");
802                         return free(bt), free(latchmgr), NULL;
803                 }
804         }
805 #else
806         latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
807         size = GetFileSize(bt->idx, amt);
808
809         if( size || *amt ) {
810                 if( !ReadFile(bt->idx, (char *)latchmgr, BT_minpage, amt, NULL) ) {
811                         fprintf(stderr, "Unable to read page zero\n");
812                         return bt_close (bt), NULL;
813                 } else
814                         bits = latchmgr->alloc->bits;
815         }
816 #endif
817
818         bt->page_size = 1 << bits;
819         bt->page_bits = bits;
820
821         bt->mode = mode;
822
823         if( size || *amt ) {
824                 nlatchpage = latchmgr->nlatchpage;
825                 goto btlatch;
826         }
827
828         if( nodemax < 16 ) {
829                 fprintf(stderr, "Buffer pool too small: %d\n", nodemax);
830                 return bt_close(bt), NULL;
831         }
832
833         // initialize an empty b-tree with latch page, root page, page of leaves
834         // and page(s) of latches and page pool cache
835
836         memset (latchmgr, 0, 1 << bits);
837         latchmgr->alloc->bits = bt->page_bits;
838
839         //  calculate number of latch hash table entries
840
841         nlatchpage = (nodemax/16 * sizeof(BtHashEntry) + bt->page_size - 1) / bt->page_size;
842         latchhash = nlatchpage * bt->page_size / sizeof(BtHashEntry);
843
844         nlatchpage += nodemax;          // size of the buffer pool in pages
845         nlatchpage += (sizeof(BtLatchSet) * nodemax + bt->page_size - 1)/bt->page_size;
846
847         bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
848         latchmgr->nlatchpage = nlatchpage;
849         latchmgr->latchtotal = nodemax;
850         latchmgr->latchhash = latchhash;
851
852         if( bt_writepage (bt, latchmgr->alloc, 0) ) {
853                 fprintf (stderr, "Unable to create btree page zero\n");
854                 return bt_close (bt), NULL;
855         }
856
857         memset (latchmgr, 0, 1 << bits);
858         latchmgr->alloc->bits = bt->page_bits;
859
860         for( lvl=MIN_lvl; lvl--; ) {
861                 last = MIN_lvl - lvl;   // page number
862                 slotptr(latchmgr->alloc, 1)->off = bt->page_size - 3;
863                 bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? last + 1 : 0);
864                 key = keyptr(latchmgr->alloc, 1);
865                 key->len = 2;           // create stopper key
866                 key->key[0] = 0xff;
867                 key->key[1] = 0xff;
868
869                 latchmgr->alloc->min = bt->page_size - 3;
870                 latchmgr->alloc->lvl = lvl;
871                 latchmgr->alloc->cnt = 1;
872                 latchmgr->alloc->act = 1;
873
874                 if( bt_writepage (bt, latchmgr->alloc, last) ) {
875                         fprintf (stderr, "Unable to create btree page %.8x\n", last);
876                         return bt_close (bt), NULL;
877                 }
878         }
879
880         // clear out buffer pool pages
881
882         memset(latchmgr, 0, bt->page_size);
883         last = MIN_lvl;
884
885         while( ++last < ((MIN_lvl + 1 + nlatchpage) ) )
886           if( bt_writepage (bt, latchmgr->alloc, last) ) {
887                 fprintf (stderr, "Unable to write buffer pool page %.8x\n", last);
888                 return bt_close (bt), NULL;
889           }
890                 
891 #ifdef unix
892         free (latchmgr);
893 #else
894         VirtualFree (latchmgr, 0, MEM_RELEASE);
895 #endif
896
897 btlatch:
898 #ifdef unix
899         lock->l_type = F_UNLCK;
900         if( fcntl (bt->idx, F_SETLK, lock) < 0 ) {
901                 fprintf (stderr, "Unable to unlock page zero\n");
902                 return bt_close (bt), NULL;
903         }
904 #else
905         if( !UnlockFileEx (bt->idx, 0, sizeof(struct BtPage_), 0, ovl) ) {
906                 fprintf (stderr, "Unable to unlock page zero, GetLastError = %d\n", GetLastError());
907                 return bt_close (bt), NULL;
908         }
909 #endif
910 #ifdef unix
911         flag = PROT_READ | PROT_WRITE;
912         bt->latchmgr = mmap (0, bt->page_size, flag, MAP_SHARED, bt->idx, ALLOC_page * bt->page_size);
913         if( bt->latchmgr == MAP_FAILED ) {
914                 fprintf (stderr, "Unable to mmap page zero, errno = %d", errno);
915                 return bt_close (bt), NULL;
916         }
917         bt->table = (void *)mmap (0, (uid)nlatchpage * bt->page_size, flag, MAP_SHARED, bt->idx, LATCH_page * bt->page_size);
918         if( bt->table == MAP_FAILED ) {
919                 fprintf (stderr, "Unable to mmap buffer pool, errno = %d", errno);
920                 return bt_close (bt), NULL;
921         }
922 #else
923         flag = PAGE_READWRITE;
924         bt->halloc = CreateFileMapping(bt->idx, NULL, flag, 0, ((uid)nlatchpage + LATCH_page) * bt->page_size, NULL);
925         if( !bt->halloc ) {
926                 fprintf (stderr, "Unable to create file mapping for buffer pool mgr, GetLastError = %d\n", GetLastError());
927                 return bt_close (bt), NULL;
928         }
929
930         flag = FILE_MAP_WRITE;
931         bt->latchmgr = MapViewOfFile(bt->halloc, flag, 0, 0, ((uid)nlatchpage + LATCH_page) * bt->page_size);
932         if( !bt->latchmgr ) {
933                 fprintf (stderr, "Unable to map buffer pool, GetLastError = %d\n", GetLastError());
934                 return bt_close (bt), NULL;
935         }
936
937         bt->table = (void *)((char *)bt->latchmgr + LATCH_page * bt->page_size);
938 #endif
939         bt->pagepool = (unsigned char *)bt->table + (uid)(nlatchpage - bt->latchmgr->latchtotal) * bt->page_size;
940         bt->latchsets = (BtLatchSet *)(bt->pagepool - (uid)bt->latchmgr->latchtotal * sizeof(BtLatchSet));
941
942 #ifdef unix
943         bt->mem = malloc (2 * bt->page_size);
944 #else
945         bt->mem = VirtualAlloc(NULL, 2 * bt->page_size, MEM_COMMIT, PAGE_READWRITE);
946 #endif
947         bt->frame = (BtPage)bt->mem;
948         bt->cursor = (BtPage)(bt->mem + bt->page_size);
949         return bt;
950 }
951
952 // place write, read, or parent lock on requested page_no.
953
954 void bt_lockpage(BtLock mode, BtLatchSet *latch)
955 {
956         switch( mode ) {
957         case BtLockRead:
958                 bt_spinreadlock (latch->readwr);
959                 break;
960         case BtLockWrite:
961                 bt_spinwritelock (latch->readwr);
962                 break;
963         case BtLockAccess:
964                 bt_spinreadlock (latch->access);
965                 break;
966         case BtLockDelete:
967                 bt_spinwritelock (latch->access);
968                 break;
969         case BtLockParent:
970                 bt_spinwritelock (latch->parent);
971                 break;
972         }
973 }
974
975 // remove write, read, or parent lock on requested page
976
977 void bt_unlockpage(BtLock mode, BtLatchSet *latch)
978 {
979         switch( mode ) {
980         case BtLockRead:
981                 bt_spinreleaseread (latch->readwr);
982                 break;
983         case BtLockWrite:
984                 bt_spinreleasewrite (latch->readwr);
985                 break;
986         case BtLockAccess:
987                 bt_spinreleaseread (latch->access);
988                 break;
989         case BtLockDelete:
990                 bt_spinreleasewrite (latch->access);
991                 break;
992         case BtLockParent:
993                 bt_spinreleasewrite (latch->parent);
994                 break;
995         }
996 }
997
998 //      allocate a new page and write page into it
999
1000 uid bt_newpage(BtDb *bt, BtPage page)
1001 {
1002 BtLatchSet *latch;
1003 uid new_page;
1004 BtPage temp;
1005
1006         //      lock allocation page
1007
1008         bt_spinwritelock(bt->latchmgr->lock);
1009
1010         // use empty chain first
1011         // else allocate empty page
1012
1013         if( new_page = bt_getid(bt->latchmgr->alloc[1].right) ) {
1014           if( latch = bt_pinlatch (bt, new_page) )
1015                 temp = bt_mappage (bt, latch);
1016           else
1017                 return 0;
1018
1019           bt_putid(bt->latchmgr->alloc[1].right, bt_getid(temp->right));
1020           bt_spinreleasewrite(bt->latchmgr->lock);
1021           memcpy (temp, page, bt->page_size);
1022
1023           bt_update (bt, temp);
1024           bt_unpinlatch (latch);
1025           return new_page;
1026         } else {
1027           new_page = bt_getid(bt->latchmgr->alloc->right);
1028           bt_putid(bt->latchmgr->alloc->right, new_page+1);
1029           bt_spinreleasewrite(bt->latchmgr->lock);
1030
1031           if( bt_writepage (bt, page, new_page) )
1032                 return 0;
1033         }
1034
1035         bt_update (bt, bt->latchmgr->alloc);
1036         return new_page;
1037 }
1038
1039 //  compare two keys, returning > 0, = 0, or < 0
1040 //  as the comparison value
1041
1042 int keycmp (BtKey key1, unsigned char *key2, uint len2)
1043 {
1044 uint len1 = key1->len;
1045 int ans;
1046
1047         if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
1048                 return ans;
1049
1050         if( len1 > len2 )
1051                 return 1;
1052         if( len1 < len2 )
1053                 return -1;
1054
1055         return 0;
1056 }
1057
1058 //  Update current page of btree by
1059 //      flushing mapped area to disk backing of cache pool.
1060 //      mark page as dirty for rewrite to permanent location
1061
1062 void bt_update (BtDb *bt, BtPage page)
1063 {
1064 #ifdef unix
1065         msync (page, bt->page_size, MS_ASYNC);
1066 #else
1067 //      FlushViewOfFile (page, bt->page_size);
1068 #endif
1069         page->dirty = 1;
1070 }
1071
1072 //  map the btree cached page onto current page
1073
1074 BtPage bt_mappage (BtDb *bt, BtLatchSet *latch)
1075 {
1076         return (BtPage)((uid)(latch - bt->latchsets) * bt->page_size + bt->pagepool);
1077 }
1078
1079 //      deallocate a deleted page 
1080 //      place on free chain out of allocator page
1081 //      call with page latched for Writing and Deleting
1082
1083 BTERR bt_freepage(BtDb *bt, uid page_no, BtLatchSet *latch)
1084 {
1085 BtPage page = bt_mappage (bt, latch);
1086
1087         //      lock allocation page
1088
1089         bt_spinwritelock (bt->latchmgr->lock);
1090
1091         //      store chain in second right
1092         bt_putid(page->right, bt_getid(bt->latchmgr->alloc[1].right));
1093         bt_putid(bt->latchmgr->alloc[1].right, page_no);
1094
1095         page->free = 1;
1096         bt_update(bt, page);
1097
1098         // unlock released page
1099
1100         bt_unlockpage (BtLockDelete, latch);
1101         bt_unlockpage (BtLockWrite, latch);
1102         bt_unpinlatch (latch);
1103
1104         // unlock allocation page
1105
1106         bt_spinreleasewrite (bt->latchmgr->lock);
1107         bt_update (bt, bt->latchmgr->alloc);
1108         return 0;
1109 }
1110
1111 //  find slot in page for given key at a given level
1112
1113 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1114 {
1115 uint diff, higher = bt->page->cnt, low = 1, slot;
1116 uint good = 0;
1117
1118         //      make stopper key an infinite fence value
1119
1120         if( bt_getid (bt->page->right) )
1121                 higher++;
1122         else
1123                 good++;
1124
1125         //      low is the lowest candidate, higher is already
1126         //      tested as .ge. the given key, loop ends when they meet
1127
1128         while( diff = higher - low ) {
1129                 slot = low + ( diff >> 1 );
1130                 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1131                         low = slot + 1;
1132                 else
1133                         higher = slot, good++;
1134         }
1135
1136         //      return zero if key is on right link page
1137
1138         return good ? higher : 0;
1139 }
1140
1141 //  find and load page at given level for given key
1142 //      leave page rd or wr locked as requested
1143
1144 int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, uint lock)
1145 {
1146 uid page_no = ROOT_page, prevpage = 0;
1147 uint drill = 0xff, slot;
1148 BtLatchSet *prevlatch;
1149 uint mode, prevmode;
1150
1151   //  start at root of btree and drill down
1152
1153   do {
1154         // determine lock mode of drill level
1155         mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead; 
1156
1157         if( bt->latch = bt_pinlatch(bt, page_no) )
1158                 bt->page_no = page_no;
1159         else
1160                 return 0;
1161
1162         // obtain access lock using lock chaining
1163
1164         if( page_no > ROOT_page )
1165                 bt_lockpage(BtLockAccess, bt->latch);
1166
1167         if( prevpage ) {
1168                 bt_unlockpage(prevmode, prevlatch);
1169                 bt_unpinlatch(prevlatch);
1170                 prevpage = 0;
1171         }
1172
1173         // obtain read lock using lock chaining
1174
1175         bt_lockpage(mode, bt->latch);
1176
1177         if( page_no > ROOT_page )
1178                 bt_unlockpage(BtLockAccess, bt->latch);
1179
1180         //      map/obtain page contents
1181
1182         bt->page = bt_mappage (bt, bt->latch);
1183
1184         // re-read and re-lock root after determining actual level of root
1185
1186         if( bt->page->lvl != drill) {
1187                 if( bt->page_no != ROOT_page )
1188                         return bt->err = BTERR_struct, 0;
1189                         
1190                 drill = bt->page->lvl;
1191
1192                 if( lock != BtLockRead && drill == lvl ) {
1193                         bt_unlockpage(mode, bt->latch);
1194                         bt_unpinlatch(bt->latch);
1195                         continue;
1196                 }
1197         }
1198
1199         prevpage = bt->page_no;
1200         prevlatch = bt->latch;
1201         prevmode = mode;
1202
1203         //  find key on page at this level
1204         //  and descend to requested level
1205
1206         if( !bt->page->kill )
1207          if( slot = bt_findslot (bt, key, len) ) {
1208           if( drill == lvl )
1209                 return slot;
1210
1211           while( slotptr(bt->page, slot)->dead )
1212                 if( slot++ < bt->page->cnt )
1213                         continue;
1214                 else
1215                         goto slideright;
1216
1217           page_no = bt_getid(slotptr(bt->page, slot)->id);
1218           drill--;
1219           continue;
1220          }
1221
1222         //  or slide right into next page
1223
1224 slideright:
1225         page_no = bt_getid(bt->page->right);
1226
1227   } while( page_no );
1228
1229   // return error on end of right chain
1230
1231   bt->err = BTERR_eof;
1232   return 0;     // return error
1233 }
1234
1235 //      a fence key was deleted from a page
1236 //      push new fence value upwards
1237
1238 BTERR bt_fixfence (BtDb *bt, uid page_no, uint lvl)
1239 {
1240 unsigned char leftkey[256], rightkey[256];
1241 BtLatchSet *latch = bt->latch;
1242 BtKey ptr;
1243
1244         // remove deleted key, the old fence value
1245
1246         ptr = keyptr(bt->page, bt->page->cnt);
1247         memcpy(rightkey, ptr, ptr->len + 1);
1248
1249         memset (slotptr(bt->page, bt->page->cnt--), 0, sizeof(BtSlot));
1250         bt->page->clean = 1;
1251
1252         ptr = keyptr(bt->page, bt->page->cnt);
1253         memcpy(leftkey, ptr, ptr->len + 1);
1254
1255         bt_update (bt, bt->page);
1256         bt_lockpage (BtLockParent, latch);
1257         bt_unlockpage (BtLockWrite, latch);
1258
1259         //  insert new (now smaller) fence key
1260
1261         if( bt_insertkey (bt, leftkey+1, *leftkey, lvl + 1, page_no, time(NULL)) )
1262                 return bt->err;
1263
1264         //  remove old (larger) fence key
1265
1266         if( bt_deletekey (bt, rightkey+1, *rightkey, lvl + 1) )
1267                 return bt->err;
1268
1269         bt_unlockpage (BtLockParent, latch);
1270         bt_unpinlatch (latch);
1271         return 0;
1272 }
1273
1274 //      root has a single child
1275 //      collapse a level from the btree
1276 //      call with root locked in bt->page
1277
1278 BTERR bt_collapseroot (BtDb *bt, BtPage root)
1279 {
1280 BtLatchSet *latch;
1281 BtPage temp;
1282 uid child;
1283 uint idx;
1284
1285         // find the child entry
1286         //      and promote to new root
1287
1288   do {
1289         for( idx = 0; idx++ < root->cnt; )
1290           if( !slotptr(root, idx)->dead )
1291                 break;
1292
1293         child = bt_getid (slotptr(root, idx)->id);
1294         if( latch = bt_pinlatch (bt, child) )
1295                 temp = bt_mappage (bt, latch);
1296         else
1297                 return bt->err;
1298
1299         bt_lockpage (BtLockDelete, latch);
1300         bt_lockpage (BtLockWrite, latch);
1301         memcpy (root, temp, bt->page_size);
1302
1303         bt_update (bt, root);
1304
1305         if( bt_freepage (bt, child, latch) )
1306                 return bt->err;
1307
1308   } while( root->lvl > 1 && root->act == 1 );
1309
1310   bt_unlockpage (BtLockWrite, bt->latch);
1311   bt_unpinlatch (bt->latch);
1312   return 0;
1313 }
1314
1315 //  find and delete key on page by marking delete flag bit
1316 //  when page becomes empty, delete it
1317
1318 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl)
1319 {
1320 unsigned char lowerkey[256], higherkey[256];
1321 uint slot, dirty = 0, idx, fence, found;
1322 BtLatchSet *latch, *rlatch;
1323 uid page_no, right;
1324 BtPage temp;
1325 BtKey ptr;
1326
1327         if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1328                 ptr = keyptr(bt->page, slot);
1329         else
1330                 return bt->err;
1331
1332         // are we deleting a fence slot?
1333
1334         fence = slot == bt->page->cnt;
1335
1336         // if key is found delete it, otherwise ignore request
1337
1338         if( found = !keycmp (ptr, key, len) )
1339           if( found = slotptr(bt->page, slot)->dead == 0 ) {
1340                 dirty = slotptr(bt->page,slot)->dead = 1;
1341                 bt->page->clean = 1;
1342                 bt->page->act--;
1343
1344                 // collapse empty slots
1345
1346                 while( idx = bt->page->cnt - 1 )
1347                   if( slotptr(bt->page, idx)->dead ) {
1348                         *slotptr(bt->page, idx) = *slotptr(bt->page, idx + 1);
1349                         memset (slotptr(bt->page, bt->page->cnt--), 0, sizeof(BtSlot));
1350                   } else
1351                         break;
1352           }
1353
1354         right = bt_getid(bt->page->right);
1355         page_no = bt->page_no;
1356         latch = bt->latch;
1357
1358         if( !dirty ) {
1359           if( lvl )
1360                 return bt_abort (bt, bt->page, page_no, BTERR_notfound);
1361           bt_unlockpage(BtLockWrite, latch);
1362           bt_unpinlatch (latch);
1363           return bt->found = found, 0;
1364         }
1365
1366         //      did we delete a fence key in an upper level?
1367
1368         if( lvl && bt->page->act && fence )
1369           if( bt_fixfence (bt, page_no, lvl) )
1370                 return bt->err;
1371           else
1372                 return bt->found = found, 0;
1373
1374         //      is this a collapsed root?
1375
1376         if( lvl > 1 && page_no == ROOT_page && bt->page->act == 1 )
1377           if( bt_collapseroot (bt, bt->page) )
1378                 return bt->err;
1379           else
1380                 return bt->found = found, 0;
1381
1382         // return if page is not empty
1383
1384         if( bt->page->act ) {
1385           bt_update(bt, bt->page);
1386           bt_unlockpage(BtLockWrite, latch);
1387           bt_unpinlatch (latch);
1388           return bt->found = found, 0;
1389         }
1390
1391         // cache copy of fence key
1392         //      in order to find parent
1393
1394         ptr = keyptr(bt->page, bt->page->cnt);
1395         memcpy(lowerkey, ptr, ptr->len + 1);
1396
1397         // obtain lock on right page
1398
1399         if( rlatch = bt_pinlatch (bt, right) )
1400                 temp = bt_mappage (bt, rlatch);
1401         else
1402                 return bt->err;
1403
1404         bt_lockpage(BtLockWrite, rlatch);
1405
1406         if( temp->kill ) {
1407                 bt_abort(bt, temp, right, 0);
1408                 return bt_abort(bt, bt->page, bt->page_no, BTERR_kill);
1409         }
1410
1411         // pull contents of next page into current empty page 
1412
1413         memcpy (bt->page, temp, bt->page_size);
1414
1415         //      cache copy of key to update
1416
1417         ptr = keyptr(temp, temp->cnt);
1418         memcpy(higherkey, ptr, ptr->len + 1);
1419
1420         //  Mark right page as deleted and point it to left page
1421         //      until we can post updates at higher level.
1422
1423         bt_putid(temp->right, page_no);
1424         temp->kill = 1;
1425
1426         bt_update(bt, bt->page);
1427         bt_update(bt, temp);
1428
1429         bt_lockpage(BtLockParent, latch);
1430         bt_unlockpage(BtLockWrite, latch);
1431
1432         bt_lockpage(BtLockParent, rlatch);
1433         bt_unlockpage(BtLockWrite, rlatch);
1434
1435         //  redirect higher key directly to consolidated node
1436
1437         if( bt_insertkey (bt, higherkey+1, *higherkey, lvl+1, page_no, time(NULL)) )
1438                 return bt->err;
1439
1440         //  delete old lower key to consolidated node
1441
1442         if( bt_deletekey (bt, lowerkey + 1, *lowerkey, lvl + 1) )
1443                 return bt->err;
1444
1445         //  obtain write & delete lock on deleted node
1446         //      add right block to free chain
1447
1448         bt_lockpage(BtLockDelete, rlatch);
1449         bt_lockpage(BtLockWrite, rlatch);
1450         bt_unlockpage(BtLockParent, rlatch);
1451
1452         if( bt_freepage (bt, right, rlatch) )
1453                 return bt->err;
1454
1455         bt_unlockpage(BtLockParent, latch);
1456         bt_unpinlatch(latch);
1457         return 0;
1458 }
1459
1460 //      find key in leaf level and return row-id
1461
1462 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1463 {
1464 uint  slot;
1465 BtKey ptr;
1466 uid id;
1467
1468         if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1469                 ptr = keyptr(bt->page, slot);
1470         else
1471                 return 0;
1472
1473         // if key exists, return row-id
1474         //      otherwise return 0
1475
1476         if( ptr->len == len && !memcmp (ptr->key, key, len) )
1477                 id = bt_getid(slotptr(bt->page,slot)->id);
1478         else
1479                 id = 0;
1480
1481         bt_unlockpage (BtLockRead, bt->latch);
1482         bt_unpinlatch (bt->latch);
1483         return id;
1484 }
1485
1486 //      check page for space available,
1487 //      clean if necessary and return
1488 //      0 - page needs splitting
1489 //      >0 - go ahead with new slot
1490  
1491 uint bt_cleanpage(BtDb *bt, uint amt, uint slot)
1492 {
1493 uint nxt = bt->page_size;
1494 BtPage page = bt->page;
1495 uint cnt = 0, idx = 0;
1496 uint max = page->cnt;
1497 uint newslot = slot;
1498 BtKey key;
1499 int ret;
1500
1501         if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1502                 return slot;
1503
1504         //      skip cleanup if nothing to reclaim
1505
1506         if( !page->clean )
1507                 return 0;
1508
1509         memcpy (bt->frame, page, bt->page_size);
1510
1511         // skip page info and set rest of page to zero
1512
1513         memset (page+1, 0, bt->page_size - sizeof(*page));
1514         page->act = 0;
1515
1516         while( cnt++ < max ) {
1517                 if( cnt == slot )
1518                         newslot = idx + 1;
1519                 // always leave fence key in list
1520                 if( cnt < max && slotptr(bt->frame,cnt)->dead )
1521                         continue;
1522
1523                 // copy key
1524                 key = keyptr(bt->frame, cnt);
1525                 nxt -= key->len + 1;
1526                 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1527
1528                 // copy slot
1529                 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1530                 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1531                         page->act++;
1532 #ifdef USETOD
1533                 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1534 #endif
1535                 slotptr(page, idx)->off = nxt;
1536         }
1537
1538         page->min = nxt;
1539         page->cnt = idx;
1540
1541         if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1542                 return newslot;
1543
1544         return 0;
1545 }
1546
1547 // split the root and raise the height of the btree
1548
1549 BTERR bt_splitroot(BtDb *bt, unsigned char *leftkey, uid page_no2)
1550 {
1551 uint nxt = bt->page_size;
1552 BtPage root = bt->page;
1553 uid right;
1554
1555         //  Obtain an empty page to use, and copy the current
1556         //  root contents into it
1557
1558         if( !(right = bt_newpage(bt, root)) )
1559                 return bt->err;
1560
1561         // preserve the page info at the bottom
1562         // and set rest to zero
1563
1564         memset(root+1, 0, bt->page_size - sizeof(*root));
1565
1566         // insert first key on newroot page
1567
1568         nxt -= *leftkey + 1;
1569         memcpy ((unsigned char *)root + nxt, leftkey, *leftkey + 1);
1570         bt_putid(slotptr(root, 1)->id, right);
1571         slotptr(root, 1)->off = nxt;
1572         
1573         // insert second key on newroot page
1574         // and increase the root height
1575
1576         nxt -= 3;
1577         ((unsigned char *)root)[nxt] = 2;
1578         ((unsigned char *)root)[nxt+1] = 0xff;
1579         ((unsigned char *)root)[nxt+2] = 0xff;
1580         bt_putid(slotptr(root, 2)->id, page_no2);
1581         slotptr(root, 2)->off = nxt;
1582
1583         bt_putid(root->right, 0);
1584         root->min = nxt;                // reset lowest used offset and key count
1585         root->cnt = 2;
1586         root->act = 2;
1587         root->lvl++;
1588
1589         // update and release root (bt->page)
1590
1591         bt_update(bt, root);
1592
1593         bt_unlockpage(BtLockWrite, bt->latch);
1594         bt_unpinlatch(bt->latch);
1595         return 0;
1596 }
1597
1598 //  split already locked full node
1599 //      return unlocked.
1600
1601 BTERR bt_splitpage (BtDb *bt)
1602 {
1603 uint cnt = 0, idx = 0, max, nxt = bt->page_size;
1604 unsigned char fencekey[256], rightkey[256];
1605 uid page_no = bt->page_no, right;
1606 BtLatchSet *latch, *rlatch;
1607 BtPage page = bt->page;
1608 uint lvl = page->lvl;
1609 BtKey key;
1610
1611         latch = bt->latch;
1612
1613         //  split higher half of keys to bt->frame
1614         //      the last key (fence key) might be dead
1615
1616         memset (bt->frame, 0, bt->page_size);
1617         max = page->cnt;
1618         cnt = max / 2;
1619         idx = 0;
1620
1621         while( cnt++ < max ) {
1622                 key = keyptr(page, cnt);
1623                 nxt -= key->len + 1;
1624                 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
1625                 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
1626                 if( !(slotptr(bt->frame, idx)->dead = slotptr(page, cnt)->dead) )
1627                         bt->frame->act++;
1628 #ifdef USETOD
1629                 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
1630 #endif
1631                 slotptr(bt->frame, idx)->off = nxt;
1632         }
1633
1634         //      remember fence key for new right page
1635
1636         memcpy (rightkey, key, key->len + 1);
1637
1638         bt->frame->bits = bt->page_bits;
1639         bt->frame->min = nxt;
1640         bt->frame->cnt = idx;
1641         bt->frame->lvl = lvl;
1642
1643         // link right node
1644
1645         if( page_no > ROOT_page )
1646                 memcpy (bt->frame->right, page->right, BtId);
1647
1648         //      get new free page and write frame to it.
1649
1650         if( !(right = bt_newpage(bt, bt->frame)) )
1651                 return bt->err;
1652
1653         //      update lower keys to continue in old page
1654
1655         memcpy (bt->frame, page, bt->page_size);
1656         memset (page+1, 0, bt->page_size - sizeof(*page));
1657         nxt = bt->page_size;
1658         page->clean = 0;
1659         page->act = 0;
1660         cnt = 0;
1661         idx = 0;
1662
1663         //  assemble page of smaller keys
1664         //      (they're all active keys)
1665
1666         while( cnt++ < max / 2 ) {
1667                 key = keyptr(bt->frame, cnt);
1668                 nxt -= key->len + 1;
1669                 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1670                 memcpy(slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1671 #ifdef USETOD
1672                 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1673 #endif
1674                 slotptr(page, idx)->off = nxt;
1675                 page->act++;
1676         }
1677
1678         // remember fence key for smaller page
1679
1680         memcpy (fencekey, key, key->len + 1);
1681
1682         bt_putid(page->right, right);
1683         page->min = nxt;
1684         page->cnt = idx;
1685
1686         // if current page is the root page, split it
1687
1688         if( page_no == ROOT_page )
1689                 return bt_splitroot (bt, fencekey, right);
1690
1691         //      lock right page
1692
1693         if( rlatch = bt_pinlatch (bt, right) )
1694                 bt_lockpage (BtLockParent, rlatch);
1695         else
1696                 return bt->err;
1697
1698         // update left (containing) node
1699
1700         bt_update(bt, page);
1701
1702         bt_lockpage (BtLockParent, latch);
1703         bt_unlockpage (BtLockWrite, latch);
1704
1705         // insert new fence for reformulated left block
1706
1707         if( bt_insertkey (bt, fencekey+1, *fencekey, lvl+1, page_no, time(NULL)) )
1708                 return bt->err;
1709
1710         //      switch fence for right block of larger keys to new right page
1711
1712         if( bt_insertkey (bt, rightkey+1, *rightkey, lvl+1, right, time(NULL)) )
1713                 return bt->err;
1714
1715         bt_unlockpage (BtLockParent, latch);
1716         bt_unlockpage (BtLockParent, rlatch);
1717
1718         bt_unpinlatch (rlatch);
1719         bt_unpinlatch (latch);
1720         return 0;
1721 }
1722
1723 //  Insert new key into the btree at requested level.
1724 //  Pages are unlocked at exit.
1725
1726 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod)
1727 {
1728 uint slot, idx;
1729 BtPage page;
1730 BtKey ptr;
1731
1732   while( 1 ) {
1733         if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1734                 ptr = keyptr(bt->page, slot);
1735         else
1736         {
1737                 if( !bt->err )
1738                         bt->err = BTERR_ovflw;
1739                 return bt->err;
1740         }
1741
1742         // if key already exists, update id and return
1743
1744         page = bt->page;
1745
1746         if( !keycmp (ptr, key, len) ) {
1747           if( slotptr(page, slot)->dead )
1748                 page->act++;
1749           slotptr(page, slot)->dead = 0;
1750 #ifdef USETOD
1751           slotptr(page, slot)->tod = tod;
1752 #endif
1753           bt_putid(slotptr(page,slot)->id, id);
1754           bt_update(bt, bt->page);
1755           bt_unlockpage(BtLockWrite, bt->latch);
1756           bt_unpinlatch (bt->latch);
1757           return 0;
1758         }
1759
1760         // check if page has enough space
1761
1762         if( slot = bt_cleanpage (bt, len, slot) )
1763                 break;
1764
1765         if( bt_splitpage (bt) )
1766                 return bt->err;
1767   }
1768
1769   // calculate next available slot and copy key into page
1770
1771   page->min -= len + 1; // reset lowest used offset
1772   ((unsigned char *)page)[page->min] = len;
1773   memcpy ((unsigned char *)page + page->min +1, key, len );
1774
1775   for( idx = slot; idx < page->cnt; idx++ )
1776         if( slotptr(page, idx)->dead )
1777                 break;
1778
1779   // now insert key into array before slot
1780   // preserving the fence slot
1781
1782   if( idx == page->cnt )
1783         idx++, page->cnt++;
1784
1785   page->act++;
1786
1787   while( idx > slot )
1788         *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
1789
1790   bt_putid(slotptr(page,slot)->id, id);
1791   slotptr(page, slot)->off = page->min;
1792 #ifdef USETOD
1793   slotptr(page, slot)->tod = tod;
1794 #endif
1795   slotptr(page, slot)->dead = 0;
1796
1797   bt_update(bt, bt->page);
1798
1799   bt_unlockpage(BtLockWrite, bt->latch);
1800   bt_unpinlatch(bt->latch);
1801   return 0;
1802 }
1803
1804 //  cache page of keys into cursor and return starting slot for given key
1805
1806 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
1807 {
1808 uint slot;
1809
1810         // cache page for retrieval
1811
1812         if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1813           memcpy (bt->cursor, bt->page, bt->page_size);
1814         else
1815           return 0;
1816
1817         bt_unlockpage(BtLockRead, bt->latch);
1818         bt->cursor_page = bt->page_no;
1819         bt_unpinlatch (bt->latch);
1820         return slot;
1821 }
1822
1823 //  return next slot for cursor page
1824 //  or slide cursor right into next page
1825
1826 uint bt_nextkey (BtDb *bt, uint slot)
1827 {
1828 BtLatchSet *latch;
1829 off64_t right;
1830
1831   do {
1832         right = bt_getid(bt->cursor->right);
1833
1834         while( slot++ < bt->cursor->cnt )
1835           if( slotptr(bt->cursor,slot)->dead )
1836                 continue;
1837           else if( right || (slot < bt->cursor->cnt))
1838                 return slot;
1839           else
1840                 break;
1841
1842         if( !right )
1843                 break;
1844
1845         bt->cursor_page = right;
1846
1847         if( latch = bt_pinlatch (bt, right) )
1848         bt_lockpage(BtLockRead, latch);
1849         else
1850                 return 0;
1851
1852         bt->page = bt_mappage (bt, latch);
1853         memcpy (bt->cursor, bt->page, bt->page_size);
1854         bt_unlockpage(BtLockRead, latch);
1855         bt_unpinlatch (latch);
1856         slot = 0;
1857   } while( 1 );
1858
1859   return bt->err = 0;
1860 }
1861
1862 BtKey bt_key(BtDb *bt, uint slot)
1863 {
1864         return keyptr(bt->cursor, slot);
1865 }
1866
1867 uid bt_uid(BtDb *bt, uint slot)
1868 {
1869         return bt_getid(slotptr(bt->cursor,slot)->id);
1870 }
1871
1872 #ifdef USETOD
1873 uint bt_tod(BtDb *bt, uint slot)
1874 {
1875         return slotptr(bt->cursor,slot)->tod;
1876 }
1877 #endif
1878
1879 #ifdef STANDALONE
1880
1881 uint bt_audit (BtDb *bt)
1882 {
1883 uint idx, hashidx;
1884 uid next, page_no;
1885 BtLatchSet *latch;
1886 uint cnt = 0;
1887 BtPage page;
1888 uint amt[1];
1889 BtKey ptr;
1890
1891         if( *(ushort *)(bt->latchmgr->lock) )
1892                 fprintf(stderr, "Alloc page locked\n");
1893         *(ushort *)(bt->latchmgr->lock) = 0;
1894
1895         for( idx = 1; idx <= bt->latchmgr->latchdeployed; idx++ ) {
1896                 latch = bt->latchsets + idx;
1897                 if( *(ushort *)latch->readwr )
1898                         fprintf(stderr, "latchset %d rwlocked for page %.8x\n", idx, latch->page_no);
1899                 *(ushort *)latch->readwr = 0;
1900
1901                 if( *(ushort *)latch->access )
1902                         fprintf(stderr, "latchset %d accesslocked for page %.8x\n", idx, latch->page_no);
1903                 *(ushort *)latch->access = 0;
1904
1905                 if( *(ushort *)latch->parent )
1906                         fprintf(stderr, "latchset %d parentlocked for page %.8x\n", idx, latch->page_no);
1907                 *(ushort *)latch->parent = 0;
1908
1909                 if( latch->pin ) {
1910                         fprintf(stderr, "latchset %d pinned for page %.8x\n", idx, latch->page_no);
1911                         latch->pin = 0;
1912                 }
1913                 page = (BtPage)((uid)idx * bt->page_size + bt->pagepool);
1914
1915             if( page->dirty )
1916                  if( bt_writepage (bt, page, latch->page_no) )
1917                         fprintf(stderr, "Page %.8x Write Error\n", latch->page_no);
1918         }
1919
1920         for( hashidx = 0; hashidx < bt->latchmgr->latchhash; hashidx++ ) {
1921           if( *(ushort *)(bt->table[hashidx].latch) )
1922                         fprintf(stderr, "hash entry %d locked\n", hashidx);
1923
1924           *(ushort *)(bt->table[hashidx].latch) = 0;
1925
1926           if( idx = bt->table[hashidx].slot ) do {
1927                 latch = bt->latchsets + idx;
1928                 if( latch->pin )
1929                         fprintf(stderr, "latchset %d pinned for page %.8x\n", idx, latch->page_no);
1930           } while( idx = latch->next );
1931         }
1932
1933         next = bt->latchmgr->nlatchpage + LATCH_page;
1934         page_no = LEAF_page;
1935
1936         while( page_no < bt_getid(bt->latchmgr->alloc->right) ) {
1937                 if( bt_readpage (bt, bt->frame, page_no) )
1938                   fprintf(stderr, "page %.8x unreadable\n", page_no);
1939                 if( !bt->frame->free ) {
1940                  for( idx = 0; idx++ < bt->frame->cnt - 1; ) {
1941                   ptr = keyptr(bt->frame, idx+1);
1942                   if( keycmp (keyptr(bt->frame, idx), ptr->key, ptr->len) >= 0 )
1943                         fprintf(stderr, "page %.8x idx %.2x out of order\n", page_no, idx);
1944                  }
1945                  if( !bt->frame->lvl )
1946                         cnt += bt->frame->act;
1947                 }
1948
1949                 if( page_no > LEAF_page )
1950                         next = page_no + 1;
1951                 page_no = next;
1952         }
1953         return cnt - 1;
1954 }
1955
1956 #ifndef unix
1957 double getCpuTime(int type)
1958 {
1959 FILETIME crtime[1];
1960 FILETIME xittime[1];
1961 FILETIME systime[1];
1962 FILETIME usrtime[1];
1963 SYSTEMTIME timeconv[1];
1964 double ans = 0;
1965
1966         memset (timeconv, 0, sizeof(SYSTEMTIME));
1967
1968         switch( type ) {
1969         case 0:
1970                 GetSystemTimeAsFileTime (xittime);
1971                 FileTimeToSystemTime (xittime, timeconv);
1972                 ans = (double)timeconv->wDayOfWeek * 3600 * 24;
1973                 break;
1974         case 1:
1975                 GetProcessTimes (GetCurrentProcess(), crtime, xittime, systime, usrtime);
1976                 FileTimeToSystemTime (usrtime, timeconv);
1977                 break;
1978         case 2:
1979                 GetProcessTimes (GetCurrentProcess(), crtime, xittime, systime, usrtime);
1980                 FileTimeToSystemTime (systime, timeconv);
1981                 break;
1982         }
1983
1984         ans += (double)timeconv->wHour * 3600;
1985         ans += (double)timeconv->wMinute * 60;
1986         ans += (double)timeconv->wSecond;
1987         ans += (double)timeconv->wMilliseconds / 1000;
1988         return ans;
1989 }
1990 #else
1991 #include <time.h>
1992 #include <sys/resource.h>
1993
1994 double getCpuTime(int type)
1995 {
1996 struct rusage used[1];
1997 struct timeval tv[1];
1998
1999         switch( type ) {
2000         case 0:
2001                 gettimeofday(tv, NULL);
2002                 return (double)tv->tv_sec + (double)tv->tv_usec / 1000000;
2003
2004         case 1:
2005                 getrusage(RUSAGE_SELF, used);
2006                 return (double)used->ru_utime.tv_sec + (double)used->ru_utime.tv_usec / 1000000;
2007
2008         case 2:
2009                 getrusage(RUSAGE_SELF, used);
2010                 return (double)used->ru_stime.tv_sec + (double)used->ru_stime.tv_usec / 1000000;
2011         }
2012
2013         return 0;
2014 }
2015 #endif
2016
2017 //  standalone program to index file of keys
2018 //  then list them onto std-out
2019
2020 int main (int argc, char **argv)
2021 {
2022 uint slot, line = 0, off = 0, found = 0;
2023 int ch, cnt = 0, bits = 12, idx;
2024 unsigned char key[256];
2025 double done, start;
2026 uid next, page_no;
2027 float elapsed;
2028 time_t tod[1];
2029 uint scan = 0;
2030 uint len = 0;
2031 uint map = 0;
2032 BtKey ptr;
2033 BtDb *bt;
2034 FILE *in;
2035
2036         if( argc < 4 ) {
2037                 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]);
2038                 fprintf (stderr, "  page_bits: size of btree page in bits\n");
2039                 fprintf (stderr, "  mapped_pool_pages: number of pages in buffer pool\n");
2040                 exit(0);
2041         }
2042
2043         start = getCpuTime(0);
2044         time(tod);
2045
2046         if( argc > 4 )
2047                 bits = atoi(argv[4]);
2048
2049         if( argc > 5 )
2050                 map = atoi(argv[5]);
2051
2052         if( argc > 6 )
2053                 off = atoi(argv[6]);
2054
2055         bt = bt_open ((argv[1]), BT_rw, bits, map);
2056
2057         if( !bt ) {
2058                 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2059                 exit (1);
2060         }
2061
2062         switch(argv[3][0]| 0x20)
2063         {
2064         case 'a':
2065                 fprintf(stderr, "started audit for %s\n", argv[2]);
2066                 cnt = bt_audit (bt);
2067                 fprintf(stderr, "finished audit for %s, %d keys\n", argv[2], cnt);
2068                 break;
2069
2070         case 'w':
2071                 fprintf(stderr, "started indexing for %s\n", argv[2]);
2072                 if( argc > 2 && (in = fopen (argv[2], "rb")) )
2073                   while( ch = getc(in), ch != EOF )
2074                         if( ch == '\n' )
2075                         {
2076                           if( off )
2077                                 sprintf((char *)key+len, "%.9d", line + off), len += 9;
2078
2079                           if( bt_insertkey (bt, key, len, 0, ++line, *tod) )
2080                                 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2081                           len = 0;
2082                         }
2083                         else if( len < 245 )
2084                                 key[len++] = ch;
2085                 fprintf(stderr, "finished adding keys for %s, %d \n", argv[2], line);
2086                 break;
2087
2088         case 'd':
2089                 fprintf(stderr, "started deleting keys for %s\n", argv[2]);
2090                 if( argc > 2 && (in = fopen (argv[2], "rb")) )
2091                   while( ch = getc(in), ch != EOF )
2092                         if( ch == '\n' )
2093                         {
2094                           if( off )
2095                                 sprintf((char *)key+len, "%.9d", line + off), len += 9;
2096                           line++;
2097                           if( bt_deletekey (bt, key, len, 0) )
2098                                 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2099                           len = 0;
2100                         }
2101                         else if( len < 245 )
2102                                 key[len++] = ch;
2103                 fprintf(stderr, "finished deleting keys for %s, %d \n", argv[2], line);
2104                 break;
2105
2106         case 'f':
2107                 fprintf(stderr, "started finding keys for %s\n", argv[2]);
2108                 if( argc > 2 && (in = fopen (argv[2], "rb")) )
2109                   while( ch = getc(in), ch != EOF )
2110                         if( ch == '\n' )
2111                         {
2112                           if( off )
2113                                 sprintf((char *)key+len, "%.9d", line + off), len += 9;
2114                           line++;
2115                           if( bt_findkey (bt, key, len) )
2116                                 found++;
2117                           else if( bt->err )
2118                                 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2119                           len = 0;
2120                         }
2121                         else if( len < 245 )
2122                                 key[len++] = ch;
2123                 fprintf(stderr, "finished search of %d keys for %s, found %d\n", line, argv[2], found);
2124                 break;
2125
2126         case 's':
2127                 fprintf(stderr, "started scaning\n");
2128                 cnt = len = key[0] = 0;
2129
2130                 if( slot = bt_startkey (bt, key, len) )
2131                   slot--;
2132                 else
2133                   fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
2134
2135                 while( slot = bt_nextkey (bt, slot) ) {
2136                         ptr = bt_key(bt, slot);
2137                         fwrite (ptr->key, ptr->len, 1, stdout);
2138                         fputc ('\n', stdout);
2139                         cnt++;
2140                 }
2141
2142                 fprintf(stderr, " Total keys read %d\n", cnt - 1);
2143                 break;
2144
2145         case 'c':
2146           fprintf(stderr, "started counting\n");
2147           cnt = 0;
2148
2149           next = bt->latchmgr->nlatchpage + LATCH_page;
2150           page_no = LEAF_page;
2151
2152           while( page_no < bt_getid(bt->latchmgr->alloc->right) ) {
2153           BtLatchSet *latch;
2154           BtPage page;
2155                 if( latch = bt_pinlatch (bt, page_no) )
2156                         page = bt_mappage (bt, latch);
2157                 if( !page->free && !page->lvl )
2158                         cnt += page->act;
2159                 if( page_no > LEAF_page )
2160                         next = page_no + 1;
2161                 if( scan )
2162                  for( idx = 0; idx++ < page->cnt; ) {
2163                   if( slotptr(page, idx)->dead )
2164                         continue;
2165                   ptr = keyptr(page, idx);
2166                   if( idx != page->cnt && bt_getid (page->right) ) {
2167                         fwrite (ptr->key, ptr->len, 1, stdout);
2168                         fputc ('\n', stdout);
2169                   }
2170                  }
2171                 bt_unpinlatch (latch);
2172                 page_no = next;
2173           }
2174                 
2175           cnt--;        // remove stopper key
2176           fprintf(stderr, " Total keys read %d\n", cnt);
2177           break;
2178         }
2179
2180         done = getCpuTime(0);
2181         elapsed = (float)(done - start);
2182         fprintf(stderr, " real %dm%.3fs\n", (int)(elapsed/60), elapsed - (int)(elapsed/60)*60);
2183         elapsed = getCpuTime(1);
2184         fprintf(stderr, " user %dm%.3fs\n", (int)(elapsed/60), elapsed - (int)(elapsed/60)*60);
2185         elapsed = getCpuTime(2);
2186         fprintf(stderr, " sys  %dm%.3fs\n", (int)(elapsed/60), elapsed - (int)(elapsed/60)*60);
2187         return 0;
2188 }
2189
2190 #endif  //STANDALONE