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