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