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