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