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