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