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