]> pd.if.org Git - btree/blob - threads2i.c
0c7c41d43896023485e29cab0f96a3ad30b640c9
[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];
1882 uint lvl = set->page->lvl;
1883 uint prev;
1884 uid right;
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         bt->frame->bits = bt->mgr->page_bits;
1907         bt->frame->min = nxt;
1908         bt->frame->cnt = idx;
1909         bt->frame->lvl = lvl;
1910
1911         // link right node
1912
1913         if( set->page_no > ROOT_page )
1914                 memcpy (bt->frame->right, set->page->right, BtId);
1915
1916         //      get new free page and write higher keys to it.
1917
1918         if( !(right = bt_newpage(bt, bt->frame)) )
1919                 return bt->err;
1920
1921         //      update lower keys to continue in old page
1922
1923         memcpy (bt->frame, set->page, bt->mgr->page_size);
1924         memset (set->page+1, 0, bt->mgr->page_size - sizeof(*set->page));
1925         nxt = bt->mgr->page_size;
1926         set->page->posted = 0;
1927         set->page->dirty = 0;
1928         set->page->act = 0;
1929         cnt = 0;
1930         idx = 0;
1931
1932         //  assemble page of smaller keys
1933
1934         while( cnt++ < max / 2 ) {
1935                 key = keyptr(bt->frame, cnt);
1936                 nxt -= key->len + 1;
1937                 memcpy ((unsigned char *)set->page + nxt, key, key->len + 1);
1938                 memcpy(slotptr(set->page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1939                 slotptr(set->page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1940                 slotptr(set->page, idx)->off = nxt;
1941                 set->page->act++;
1942         }
1943
1944         // remember fence key for smaller page
1945
1946         memcpy(fencekey, key, key->len + 1);
1947         bt_putid(set->page->right, right);
1948         set->page->min = nxt;
1949         set->page->cnt = idx;
1950
1951         // if current page is the root page, split it
1952
1953         if( set->page_no == ROOT_page )
1954                 return bt_splitroot (bt, set, fencekey, right);
1955
1956         right = 0;
1957
1958         // insert new fences in their parent pages
1959
1960         while( 1 ) {
1961                 bt_lockpage (BtLockParent, set->latch);
1962
1963                 key = keyptr (set->page, set->page->cnt);
1964                 memcpy (fencekey, key, key->len + 1);
1965                 prev = set->page->posted;
1966
1967                 if( right && prev ) {
1968                         bt_unlockpage (BtLockParent, set->latch);
1969                         bt_unlockpage (BtLockWrite, set->latch);
1970                         bt_unpinlatch (set->latch);
1971                         bt_unpinpool (set->pool);
1972                         return 0;
1973                 }
1974
1975                 right = bt_getid (set->page->right);
1976                 set->page->posted = 1;
1977
1978                 bt_unlockpage (BtLockWrite, set->latch);
1979
1980                 // insert new fence for reformulated left block of smaller keys
1981
1982                 if( !prev )
1983                   if( bt_insertkey (bt, fencekey+1, *fencekey, lvl+1, set->page_no, time(NULL)) )
1984                         return bt->err;
1985
1986                 bt_unlockpage (BtLockParent, set->latch);
1987                 bt_unpinlatch (set->latch);
1988                 bt_unpinpool (set->pool);
1989
1990                 if( !(set->page_no = right) )
1991                         break;
1992
1993                 set->latch = bt_pinlatch (bt, right);
1994
1995                 if( set->pool = bt_pinpool (bt, right) )
1996                         set->page = bt_page (bt, set->pool, right);
1997                 else
1998                         return bt->err;
1999
2000                 bt_lockpage (BtLockWrite, set->latch);
2001         }
2002
2003         return 0;
2004 }
2005
2006 //  Insert new key into the btree at given level.
2007
2008 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod)
2009 {
2010 BtPageSet set[1];
2011 uint slot, idx;
2012 BtKey ptr;
2013
2014         while( 1 ) {
2015                 if( slot = bt_loadpage (bt, set, key, len, lvl, BtLockWrite) )
2016                         ptr = keyptr(set->page, slot);
2017                 else
2018                 {
2019                         if ( !bt->err )
2020                                 bt->err = BTERR_ovflw;
2021                         return bt->err;
2022                 }
2023
2024                 // if key already exists, update id and return
2025
2026                 if( !keycmp (ptr, key, len) ) {
2027                         if( slotptr(set->page, slot)->dead )
2028                                 set->page->act++;
2029                         slotptr(set->page, slot)->dead = 0;
2030                         slotptr(set->page, slot)->tod = tod;
2031                         bt_putid(slotptr(set->page,slot)->id, id);
2032                         bt_unlockpage(BtLockWrite, set->latch);
2033                         bt_unpinlatch (set->latch);
2034                         bt_unpinpool (set->pool);
2035                         return 0;
2036                 }
2037
2038                 // check if page has enough space
2039
2040                 if( slot = bt_cleanpage (bt, set->page, len, slot) )
2041                         break;
2042
2043                 if( bt_splitpage (bt, set) )
2044                         return bt->err;
2045         }
2046
2047         // calculate next available slot and copy key into page
2048
2049         set->page->min -= len + 1; // reset lowest used offset
2050         ((unsigned char *)set->page)[set->page->min] = len;
2051         memcpy ((unsigned char *)set->page + set->page->min +1, key, len );
2052
2053         for( idx = slot; idx < set->page->cnt; idx++ )
2054           if( slotptr(set->page, idx)->dead )
2055                 break;
2056
2057         // now insert key into array before slot
2058
2059         if( idx == set->page->cnt )
2060                 idx++, set->page->cnt++;
2061
2062         set->page->act++;
2063
2064         while( idx > slot )
2065                 *slotptr(set->page, idx) = *slotptr(set->page, idx -1), idx--;
2066
2067         bt_putid(slotptr(set->page,slot)->id, id);
2068         slotptr(set->page, slot)->off = set->page->min;
2069         slotptr(set->page, slot)->tod = tod;
2070         slotptr(set->page, slot)->dead = 0;
2071
2072         bt_unlockpage (BtLockWrite, set->latch);
2073         bt_unpinlatch (set->latch);
2074         bt_unpinpool (set->pool);
2075         return 0;
2076 }
2077
2078 //  cache page of keys into cursor and return starting slot for given key
2079
2080 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2081 {
2082 BtPageSet set[1];
2083 uint slot;
2084
2085         // cache page for retrieval
2086
2087         if( slot = bt_loadpage (bt, set, key, len, 0, BtLockRead) )
2088           memcpy (bt->cursor, set->page, bt->mgr->page_size);
2089         else
2090           return 0;
2091
2092         bt->cursor_page = set->page_no;
2093
2094         bt_unlockpage(BtLockRead, set->latch);
2095         bt_unpinlatch (set->latch);
2096         bt_unpinpool (set->pool);
2097         return slot;
2098 }
2099
2100 //  return next slot for cursor page
2101 //  or slide cursor right into next page
2102
2103 uint bt_nextkey (BtDb *bt, uint slot)
2104 {
2105 BtPageSet set[1];
2106 uid right;
2107
2108   do {
2109         right = bt_getid(bt->cursor->right);
2110
2111         while( slot++ < bt->cursor->cnt )
2112           if( slotptr(bt->cursor,slot)->dead )
2113                 continue;
2114           else if( right || (slot < bt->cursor->cnt) ) // skip infinite stopper
2115                 return slot;
2116           else
2117                 break;
2118
2119         if( !right )
2120                 break;
2121
2122         bt->cursor_page = right;
2123
2124         if( set->pool = bt_pinpool (bt, right) )
2125                 set->page = bt_page (bt, set->pool, right);
2126         else
2127                 return 0;
2128
2129         set->latch = bt_pinlatch (bt, right);
2130     bt_lockpage(BtLockRead, set->latch);
2131
2132         memcpy (bt->cursor, set->page, bt->mgr->page_size);
2133
2134         bt_unlockpage(BtLockRead, set->latch);
2135         bt_unpinlatch (set->latch);
2136         bt_unpinpool (set->pool);
2137         slot = 0;
2138
2139   } while( 1 );
2140
2141   return bt->err = 0;
2142 }
2143
2144 BtKey bt_key(BtDb *bt, uint slot)
2145 {
2146         return keyptr(bt->cursor, slot);
2147 }
2148
2149 uid bt_uid(BtDb *bt, uint slot)
2150 {
2151         return bt_getid(slotptr(bt->cursor,slot)->id);
2152 }
2153
2154 uint bt_tod(BtDb *bt, uint slot)
2155 {
2156         return slotptr(bt->cursor,slot)->tod;
2157 }
2158
2159
2160 #ifdef STANDALONE
2161
2162 void bt_latchaudit (BtDb *bt)
2163 {
2164 ushort idx, hashidx;
2165 uid next, page_no;
2166 BtLatchSet *latch;
2167 BtPool *pool;
2168 BtPage page;
2169 BtKey ptr;
2170
2171 #ifdef unix
2172         for( idx = 1; idx < bt->mgr->latchmgr->latchdeployed; idx++ ) {
2173                 latch = bt->mgr->latchsets + idx;
2174                 if( *(ushort *)latch->readwr ) {
2175                         fprintf(stderr, "latchset %d r/w locked for page %.8x\n", idx, latch->page_no);
2176                         *(ushort *)latch->readwr = 0;
2177                 }
2178                 if( *(ushort *)latch->access ) {
2179                         fprintf(stderr, "latchset %d access locked for page %.8x\n", idx, latch->page_no);
2180                         *(ushort *)latch->access = 0;
2181                 }
2182                 if( *(ushort *)latch->parent ) {
2183                         fprintf(stderr, "latchset %d parent locked for page %.8x\n", idx, latch->page_no);
2184                         *(ushort *)latch->parent = 0;
2185                 }
2186                 if( *(ushort *)latch->busy ) {
2187                         fprintf(stderr, "latchset %d busy locked for page %.8x\n", idx, latch->page_no);
2188                         *(ushort *)latch->parent = 0;
2189                 }
2190                 if( latch->pin ) {
2191                         fprintf(stderr, "latchset %d pinned for page %.8x\n", idx, latch->page_no);
2192                         latch->pin = 0;
2193                 }
2194         }
2195
2196         for( hashidx = 0; hashidx < bt->mgr->latchmgr->latchhash; hashidx++ ) {
2197           if( idx = bt->mgr->latchmgr->table[hashidx].slot ) do {
2198                 latch = bt->mgr->latchsets + idx;
2199                 if( latch->hash != hashidx ) {
2200                         fprintf(stderr, "latchset %d wrong hashidx\n", idx);
2201                         latch->hash = hashidx;
2202                 }
2203           } while( idx = latch->next );
2204         }
2205
2206         next = bt->mgr->latchmgr->nlatchpage + LATCH_page;
2207         page_no = LEAF_page;
2208
2209         while( page_no < bt_getid(bt->mgr->latchmgr->alloc->right) ) {
2210                 pread (bt->mgr->idx, bt->frame, bt->mgr->page_size, page_no << bt->mgr->page_bits);
2211                 if( !bt->frame->free )
2212                  for( idx = 0; idx++ < bt->frame->cnt - 1; ) {
2213                   ptr = keyptr(bt->frame, idx+1);
2214                   if( keycmp (keyptr(bt->frame, idx), ptr->key, ptr->len) >= 0 )
2215                         fprintf(stderr, "page %.8x idx %.2x out of order\n", page_no, idx);
2216                  }
2217
2218                 if( page_no > LEAF_page )
2219                         next = page_no + 1;
2220                 page_no = next;
2221         }
2222 #endif
2223 }
2224
2225 typedef struct {
2226         char type, idx;
2227         char *infile;
2228         BtMgr *mgr;
2229         int num;
2230 } ThreadArg;
2231
2232 //  standalone program to index file of keys
2233 //  then list them onto std-out
2234
2235 #ifdef unix
2236 void *index_file (void *arg)
2237 #else
2238 uint __stdcall index_file (void *arg)
2239 #endif
2240 {
2241 int line = 0, found = 0, cnt = 0;
2242 uid next, page_no = LEAF_page;  // start on first page of leaves
2243 unsigned char key[256];
2244 ThreadArg *args = arg;
2245 int ch, len = 0, slot;
2246 BtPageSet set[1];
2247 time_t tod[1];
2248 BtKey ptr;
2249 BtDb *bt;
2250 FILE *in;
2251
2252         bt = bt_open (args->mgr);
2253         time (tod);
2254
2255         switch(args->type | 0x20)
2256         {
2257         case 'a':
2258                 fprintf(stderr, "started latch mgr audit\n");
2259                 bt_latchaudit (bt);
2260                 fprintf(stderr, "finished latch mgr audit\n");
2261                 break;
2262
2263         case 'w':
2264                 fprintf(stderr, "started indexing for %s\n", args->infile);
2265                 if( in = fopen (args->infile, "rb") )
2266                   while( ch = getc(in), ch != EOF )
2267                         if( ch == '\n' )
2268                         {
2269                           line++;
2270
2271                           if( args->num == 1 )
2272                                 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2273
2274                           else if( args->num )
2275                                 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2276
2277                           if( bt_insertkey (bt, key, len, 0, line, *tod) )
2278                                 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2279                           len = 0;
2280                         }
2281                         else if( len < 255 )
2282                                 key[len++] = ch;
2283                 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
2284                 break;
2285
2286         case 'd':
2287                 fprintf(stderr, "started deleting keys for %s\n", args->infile);
2288                 if( in = fopen (args->infile, "rb") )
2289                   while( ch = getc(in), ch != EOF )
2290                         if( ch == '\n' )
2291                         {
2292                           line++;
2293                           if( args->num == 1 )
2294                                 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2295
2296                           else if( args->num )
2297                                 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2298
2299                           if( bt_deletekey (bt, key, len, 0) )
2300                                 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2301                           len = 0;
2302                         }
2303                         else if( len < 255 )
2304                                 key[len++] = ch;
2305                 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2306                 break;
2307
2308         case 'f':
2309                 fprintf(stderr, "started finding keys for %s\n", args->infile);
2310                 if( in = fopen (args->infile, "rb") )
2311                   while( ch = getc(in), ch != EOF )
2312                         if( ch == '\n' )
2313                         {
2314                           line++;
2315                           if( args->num == 1 )
2316                                 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2317
2318                           else if( args->num )
2319                                 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2320
2321                           if( bt_findkey (bt, key, len) )
2322                                 found++;
2323                           else if( bt->err )
2324                                 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2325                           else
2326                                 fprintf(stderr, "Unable to find key %.*s line %d\n", len, key, line);
2327                           len = 0;
2328                         }
2329                         else if( len < 255 )
2330                                 key[len++] = ch;
2331                 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2332                 break;
2333
2334         case 's':
2335                 fprintf(stderr, "started scanning\n");
2336                 do {
2337                         if( set->pool = bt_pinpool (bt, page_no) )
2338                                 set->page = bt_page (bt, set->pool, page_no);
2339                         else
2340                                 break;
2341                         set->latch = bt_pinlatch (bt, page_no);
2342                         bt_lockpage (BtLockRead, set->latch);
2343                         next = bt_getid (set->page->right);
2344                         cnt += set->page->act;
2345
2346                         for( slot = 0; slot++ < set->page->cnt; )
2347                          if( next || slot < set->page->cnt )
2348                           if( !slotptr(set->page, slot)->dead ) {
2349                                 ptr = keyptr(set->page, slot);
2350                                 fwrite (ptr->key, ptr->len, 1, stdout);
2351                                 fputc ('\n', stdout);
2352                           }
2353
2354                         bt_unlockpage (BtLockRead, set->latch);
2355                         bt_unpinlatch (set->latch);
2356                         bt_unpinpool (set->pool);
2357                 } while( page_no = next );
2358
2359                 cnt--;  // remove stopper key
2360                 fprintf(stderr, " Total keys read %d\n", cnt);
2361                 break;
2362
2363         case 'c':
2364                 fprintf(stderr, "started counting\n");
2365                 next = bt->mgr->latchmgr->nlatchpage + LATCH_page;
2366                 page_no = LEAF_page;
2367
2368                 while( page_no < bt_getid(bt->mgr->latchmgr->alloc->right) ) {
2369                 uid off = page_no << bt->mgr->page_bits;
2370 #ifdef unix
2371                   pread (bt->mgr->idx, bt->frame, bt->mgr->page_size, off);
2372 #else
2373                 DWORD amt[1];
2374
2375                   SetFilePointer (bt->mgr->idx, (long)off, (long*)(&off)+1, FILE_BEGIN);
2376
2377                   if( !ReadFile(bt->mgr->idx, bt->frame, bt->mgr->page_size, amt, NULL))
2378                         return bt->err = BTERR_map;
2379
2380                   if( *amt <  bt->mgr->page_size )
2381                         return bt->err = BTERR_map;
2382 #endif
2383                         if( !bt->frame->free && !bt->frame->lvl )
2384                                 cnt += bt->frame->act;
2385                         if( page_no > LEAF_page )
2386                                 next = page_no + 1;
2387                         page_no = next;
2388                 }
2389                 
2390                 cnt--;  // remove stopper key
2391                 fprintf(stderr, " Total keys read %d\n", cnt);
2392                 break;
2393         }
2394
2395         bt_close (bt);
2396 #ifdef unix
2397         return NULL;
2398 #else
2399         return 0;
2400 #endif
2401 }
2402
2403 typedef struct timeval timer;
2404
2405 int main (int argc, char **argv)
2406 {
2407 int idx, cnt, len, slot, err;
2408 int segsize, bits = 16;
2409 #ifdef unix
2410 pthread_t *threads;
2411 timer start, stop;
2412 #else
2413 time_t start[1], stop[1];
2414 HANDLE *threads;
2415 #endif
2416 double real_time;
2417 ThreadArg *args;
2418 uint poolsize = 0;
2419 int num = 0;
2420 char key[1];
2421 BtMgr *mgr;
2422 BtKey ptr;
2423 BtDb *bt;
2424
2425         if( argc < 3 ) {
2426                 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]);
2427                 fprintf (stderr, "  where page_bits is the page size in bits\n");
2428                 fprintf (stderr, "  mapped_segments is the number of mmap segments in buffer pool\n");
2429                 fprintf (stderr, "  seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2430                 fprintf (stderr, "  line_numbers = 1 to append line numbers to keys\n");
2431                 fprintf (stderr, "  src_file1 thru src_filen are files of keys separated by newline\n");
2432                 exit(0);
2433         }
2434
2435 #ifdef unix
2436         gettimeofday(&start, NULL);
2437 #else
2438         time(start);
2439 #endif
2440
2441         if( argc > 3 )
2442                 bits = atoi(argv[3]);
2443
2444         if( argc > 4 )
2445                 poolsize = atoi(argv[4]);
2446
2447         if( !poolsize )
2448                 fprintf (stderr, "Warning: no mapped_pool\n");
2449
2450         if( poolsize > 65535 )
2451                 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2452
2453         if( argc > 5 )
2454                 segsize = atoi(argv[5]);
2455         else
2456                 segsize = 4;    // 16 pages per mmap segment
2457
2458         if( argc > 6 )
2459                 num = atoi(argv[6]);
2460
2461         cnt = argc - 7;
2462 #ifdef unix
2463         threads = malloc (cnt * sizeof(pthread_t));
2464 #else
2465         threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2466 #endif
2467         args = malloc (cnt * sizeof(ThreadArg));
2468
2469         mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2470
2471         if( !mgr ) {
2472                 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2473                 exit (1);
2474         }
2475
2476         //      fire off threads
2477
2478         for( idx = 0; idx < cnt; idx++ ) {
2479                 args[idx].infile = argv[idx + 7];
2480                 args[idx].type = argv[2][0];
2481                 args[idx].mgr = mgr;
2482                 args[idx].num = num;
2483                 args[idx].idx = idx;
2484 #ifdef unix
2485                 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2486                         fprintf(stderr, "Error creating thread %d\n", err);
2487 #else
2488                 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2489 #endif
2490         }
2491
2492         //      wait for termination
2493
2494 #ifdef unix
2495         for( idx = 0; idx < cnt; idx++ )
2496                 pthread_join (threads[idx], NULL);
2497         gettimeofday(&stop, NULL);
2498         real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2499 #else
2500         WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2501
2502         for( idx = 0; idx < cnt; idx++ )
2503                 CloseHandle(threads[idx]);
2504
2505         time (stop);
2506         real_time = 1000 * (*stop - *start);
2507 #endif
2508         fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);
2509         bt_mgrclose (mgr);
2510 }
2511
2512 #endif  //STANDALONE