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