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