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