1 // foster btree version e
4 // author: karl malbrain, malbrain@cal.berkeley.edu
7 This work, including the source code, documentation
8 and related data, is placed into the public domain.
10 The orginal author is Karl Malbrain.
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.
20 // Please see the project home page for documentation
21 // code.google.com/p/high-concurrency-btree
23 #define _FILE_OFFSET_BITS 64
24 #define _LARGEFILE64_SOURCE
40 #define WIN32_LEAN_AND_MEAN
53 typedef unsigned long long uid;
56 typedef unsigned long long off64_t;
57 typedef unsigned short ushort;
58 typedef unsigned int uint;
61 #define BT_ro 0x6f72 // ro
62 #define BT_rw 0x7772 // rw
64 #define BT_latchtable 128 // number of latch manager slots
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
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.
88 // Define the length of the page and key pointers
92 // Page key slot definition.
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.
99 // Keys are marked dead, but remain on the page until
100 // cleanup is called. The fence key (highest key) for
101 // the page is always present, even after cleanup.
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
110 // The key structure occupies space at the upper end of
111 // each page. It's a length byte followed by the value
116 unsigned char key[1];
119 // The first part of an index page.
120 // It is immediately followed
121 // by the BtSlot array of keys.
123 typedef struct Page {
124 volatile uint cnt; // count of keys in page
125 volatile uint act; // count of active keys
126 volatile uint min; // next key offset
127 volatile uint foster; // count of foster children
128 unsigned char bits; // page size in bits
129 unsigned char lvl:7; // level of page
130 unsigned char dirty:1; // page needs to be cleaned
131 unsigned char right[BtId]; // page number to right
134 // mode & definition for hash latch implementation
143 // mutex locks the other fields
144 // exclusive is set for write access
145 // share is count of read accessors
148 volatile ushort mutex:1;
149 volatile ushort exclusive:1;
150 volatile ushort pending:1;
151 volatile ushort share:13;
154 // hash table entries
157 BtSpinLatch latch[1];
158 volatile ushort slot; // Latch table entry at head of chain
161 // latch manager table structure
165 pthread_rwlock_t lock[1];
172 BtLatch readwr[1]; // read/write page lock
173 BtLatch access[1]; // Access Intent/Page delete
174 BtLatch parent[1]; // adoption of foster children
175 BtSpinLatch busy[1]; // slot is being moved between chains
176 volatile ushort next; // next entry in hash table chain
177 volatile ushort prev; // prev entry in hash table chain
178 volatile ushort pin; // number of outstanding locks
179 volatile ushort hash; // hash slot entry is under
180 volatile uid page_no; // latch set page number
183 // The memory mapping pool table buffer manager entry
186 unsigned long long int lru; // number of times accessed
187 uid basepage; // mapped base page number
188 char *map; // mapped memory pointer
189 ushort pin; // mapped page pin counter
190 ushort slot; // slot index in this array
191 void *hashprev; // previous pool entry for the same hash idx
192 void *hashnext; // next pool entry for the same hash idx
194 HANDLE hmap; // Windows memory mapping handle
198 // structure for latch manager on ALLOC_page
201 struct Page alloc[2]; // next & free page_nos in right ptr
202 BtSpinLatch lock[1]; // allocation area lite latch
203 ushort latchdeployed; // highest number of latch entries deployed
204 ushort nlatchpage; // number of latch pages at BT_latch
205 ushort latchtotal; // number of page latch entries
206 ushort latchhash; // number of latch hash table slots
207 ushort latchvictim; // next latch entry to examine
208 BtHashEntry table[0]; // the hash table
211 // The object structure for Btree access
214 uint page_size; // page size
215 uint page_bits; // page size in bits
216 uint seg_bits; // seg size in pages in bits
217 uint mode; // read-write mode
220 char *pooladvise; // bit maps for pool page advisements
224 ushort poolcnt; // highest page pool node in use
225 ushort poolmax; // highest page pool node allocated
226 ushort poolmask; // total number of pages in mmap segment - 1
227 ushort hashsize; // size of Hash Table for pool entries
228 ushort evicted; // last evicted hash table slot
229 ushort *hash; // hash table of pool entries
230 BtPool *pool; // memory pool page segments
231 BtSpinLatch *latch; // latches for pool hash slots
232 BtLatchMgr *latchmgr; // mapped latch page from allocation page
233 BtLatchSet *latchsets; // mapped latch set from latch pages
235 HANDLE halloc; // allocation and latch table handle
240 BtMgr *mgr; // buffer manager for thread
241 BtPage cursor; // cached frame for start/next (never mapped)
242 BtPage frame; // spare frame for the page split (never mapped)
243 BtPage zero; // page frame for zeroes at end of file
244 BtPage page; // current page
245 uid page_no; // current page number
246 uid cursor_page; // current cursor page number
247 BtLatchSet *set; // current page latch set
248 BtPool *pool; // current page pool
249 unsigned char *mem; // frame, cursor, page memory buffer
250 int foster; // last search was to foster child
251 int found; // last delete was found
252 int err; // last error
267 extern void bt_close (BtDb *bt);
268 extern BtDb *bt_open (BtMgr *mgr);
269 extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod, uint lvl);
270 extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len);
271 extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
272 extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
273 extern uint bt_nextkey (BtDb *bt, uint slot);
276 extern BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolsize, uint segsize, uint hashsize);
277 void bt_mgrclose (BtMgr *mgr);
279 // internal functions
280 BTERR bt_splitpage (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no);
281 uint bt_cleanpage(BtDb *bt, BtPage page, uint amt, uint slot);
282 BTERR bt_mergeleft (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no, uint lvl);
284 // Helper functions to return cursor slot values
286 extern BtKey bt_key (BtDb *bt, uint slot);
287 extern uid bt_uid (BtDb *bt, uint slot);
288 extern uint bt_tod (BtDb *bt, uint slot);
290 // BTree page number constants
291 #define ALLOC_page 0 // allocation & lock manager hash table
292 #define ROOT_page 1 // root of the btree
293 #define LEAF_page 2 // first page of leaves
294 #define LATCH_page 3 // pages for lock manager
296 // Number of levels to create in a new BTree
300 // The page is allocated from low and hi ends.
301 // The key offsets and row-id's are allocated
302 // from the bottom, while the text of the key
303 // is allocated from the top. When the two
304 // areas meet, the page is split into two.
306 // A key consists of a length byte, two bytes of
307 // index number (0 - 65534), and up to 253 bytes
308 // of key value. Duplicate keys are discarded.
309 // Associated with each key is a 48 bit row-id.
311 // The b-tree root is always located at page 1.
312 // The first leaf page of level zero is always
313 // located on page 2.
315 // When to root page fills, it is split in two and
316 // the tree height is raised by a new root at page
317 // one with two keys.
319 // Deleted keys are marked with a dead bit until
320 // page cleanup The fence key for a node is always
321 // present, even after deletion and cleanup.
323 // Groups of pages called segments from the btree are
324 // cached with memory mapping. A hash table is used to keep
325 // track of the cached segments. This behaviour is controlled
326 // by the cache block size parameter to bt_open.
328 // To achieve maximum concurrency one page is locked at a time
329 // as the tree is traversed to find leaf key in question.
331 // An adoption traversal leaves the parent node locked as the
332 // tree is traversed to the level in quesiton.
334 // Page 0 is dedicated to lock for new page extensions,
335 // and chains empty pages together for reuse.
337 // Empty pages are chained together through the ALLOC page and reused.
339 // Access macros to address slot and key values from the page
341 #define slotptr(page, slot) (((BtSlot *)(page+1)) + (slot-1))
342 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
344 void bt_putid(unsigned char *dest, uid id)
349 dest[i] = (unsigned char)id, id >>= 8;
352 uid bt_getid(unsigned char *src)
357 for( i = 0; i < BtId; i++ )
358 id <<= 8, id |= *src++;
363 // wait until write lock mode is clear
364 // and add 1 to the share count
366 void bt_spinreadlock(BtSpinLatch *latch)
372 while( __sync_fetch_and_or((ushort *)latch, Mutex) & Mutex )
375 while( _InterlockedOr16((ushort *)latch, Mutex) & Mutex )
379 // see if exclusive request is granted or pending
381 if( prev = !(latch->exclusive | latch->pending) )
383 __sync_fetch_and_add((ushort *)latch, Share);
385 _InterlockedExchangeAdd16 ((ushort *)latch, Share);
389 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
391 _InterlockedAnd16((ushort *)latch, ~Mutex);
396 } while( sched_yield(), 1 );
398 } while( SwitchToThread(), 1 );
402 // wait for other read and write latches to relinquish
404 void bt_spinwritelock(BtSpinLatch *latch)
408 while( __sync_fetch_and_or((ushort *)latch, Mutex | Pending) & Mutex )
411 while( _InterlockedOr16((ushort *)latch, Mutex | Pending) & Mutex )
414 if( !(latch->share | latch->exclusive) ) {
416 __sync_fetch_and_or((ushort *)latch, Write);
417 __sync_fetch_and_and ((ushort *)latch, ~(Mutex | Pending));
419 _InterlockedOr16((ushort *)latch, Write);
420 _InterlockedAnd16((ushort *)latch, ~(Mutex | Pending));
426 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
428 _InterlockedAnd16((ushort *)latch, ~Mutex);
438 // try to obtain write lock
440 // return 1 if obtained,
443 int bt_spinwritetry(BtSpinLatch *latch)
448 if( prev = __sync_fetch_and_or((ushort *)latch, Mutex), prev & Mutex )
451 if( prev = _InterlockedOr16((ushort *)latch, Mutex), prev & Mutex )
454 // take write access if all bits are clear
458 __sync_fetch_and_or ((ushort *)latch, Write);
460 _InterlockedOr16((ushort *)latch, Write);
464 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
466 _InterlockedAnd16((ushort *)latch, ~Mutex);
473 void bt_spinreleasewrite(BtSpinLatch *latch)
476 __sync_fetch_and_and ((ushort *)latch, ~Write);
478 _InterlockedAnd16((ushort *)latch, ~Write);
482 // decrement reader count
484 void bt_spinreleaseread(BtSpinLatch *latch)
487 __sync_fetch_and_add((ushort *)latch, -Share);
489 _InterlockedExchangeAdd16 ((ushort *)latch, -Share);
493 void bt_initlockset (BtLatchSet *set, int reuse)
496 pthread_rwlockattr_t rwattr[1];
499 pthread_rwlock_destroy (set->readwr->lock);
500 pthread_rwlock_destroy (set->access->lock);
501 pthread_rwlock_destroy (set->parent->lock);
504 pthread_rwlockattr_init (rwattr);
505 pthread_rwlockattr_setkind_np (rwattr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
506 pthread_rwlockattr_setpshared (rwattr, PTHREAD_PROCESS_SHARED);
508 pthread_rwlock_init (set->readwr->lock, rwattr);
509 pthread_rwlock_init (set->access->lock, rwattr);
510 pthread_rwlock_init (set->parent->lock, rwattr);
511 pthread_rwlockattr_destroy (rwattr);
513 InitializeSRWLock (set->readwr->srw);
514 InitializeSRWLock (set->access->srw);
515 InitializeSRWLock (set->parent->srw);
519 // link latch table entry into latch hash table
521 void bt_latchlink (BtDb *bt, ushort hashidx, ushort victim, uid page_no)
523 BtLatchSet *set = bt->mgr->latchsets + victim;
525 if( set->next = bt->mgr->latchmgr->table[hashidx].slot )
526 bt->mgr->latchsets[set->next].prev = victim;
528 bt->mgr->latchmgr->table[hashidx].slot = victim;
529 set->page_no = page_no;
534 void bt_unpinlatch (BtLatchSet *set)
537 __sync_fetch_and_add(&set->pin, -1);
539 _InterlockedDecrement16 (&set->pin);
543 // find existing latchset or inspire new one
544 // return with latchset pinned
546 BtLatchSet *bt_pinlatch (BtDb *bt, uid page_no)
548 ushort hashidx = page_no % bt->mgr->latchmgr->latchhash;
549 ushort slot, avail = 0, victim, idx;
552 // obtain read lock on hash table entry
554 bt_spinreadlock(bt->mgr->latchmgr->table[hashidx].latch);
556 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
558 set = bt->mgr->latchsets + slot;
559 if( page_no == set->page_no )
561 } while( slot = set->next );
565 __sync_fetch_and_add(&set->pin, 1);
567 _InterlockedIncrement16 (&set->pin);
571 bt_spinreleaseread (bt->mgr->latchmgr->table[hashidx].latch);
576 // try again, this time with write lock
578 bt_spinwritelock(bt->mgr->latchmgr->table[hashidx].latch);
580 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
582 set = bt->mgr->latchsets + slot;
583 if( page_no == set->page_no )
585 if( !set->pin && !avail )
587 } while( slot = set->next );
589 // found our entry, or take over an unpinned one
591 if( slot || (slot = avail) ) {
592 set = bt->mgr->latchsets + slot;
594 __sync_fetch_and_add(&set->pin, 1);
596 _InterlockedIncrement16 (&set->pin);
598 set->page_no = page_no;
599 bt_spinreleasewrite(bt->mgr->latchmgr->table[hashidx].latch);
603 // see if there are any unused entries
605 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, 1) + 1;
607 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchdeployed);
610 if( victim < bt->mgr->latchmgr->latchtotal ) {
611 set = bt->mgr->latchsets + victim;
613 __sync_fetch_and_add(&set->pin, 1);
615 _InterlockedIncrement16 (&set->pin);
617 bt_initlockset (set, 0);
618 bt_latchlink (bt, hashidx, victim, page_no);
619 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
624 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, -1);
626 victim = _InterlockedDecrement16 (&bt->mgr->latchmgr->latchdeployed);
628 // find and reuse previous lock entry
632 victim = __sync_fetch_and_add(&bt->mgr->latchmgr->latchvictim, 1);
634 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchvictim) - 1;
636 // we don't use slot zero
638 if( victim %= bt->mgr->latchmgr->latchtotal )
639 set = bt->mgr->latchsets + victim;
643 // take control of our slot
644 // from other threads
646 if( set->pin || !bt_spinwritetry (set->busy) )
651 // try to get write lock on hash chain
652 // skip entry if not obtained
653 // or has outstanding locks
655 if( !bt_spinwritetry (bt->mgr->latchmgr->table[idx].latch) ) {
656 bt_spinreleasewrite (set->busy);
661 bt_spinreleasewrite (set->busy);
662 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
666 // unlink our available victim from its hash chain
669 bt->mgr->latchsets[set->prev].next = set->next;
671 bt->mgr->latchmgr->table[idx].slot = set->next;
674 bt->mgr->latchsets[set->next].prev = set->prev;
676 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
678 __sync_fetch_and_add(&set->pin, 1);
680 _InterlockedIncrement16 (&set->pin);
682 bt_initlockset (set, 1);
683 bt_latchlink (bt, hashidx, victim, page_no);
684 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
685 bt_spinreleasewrite (set->busy);
690 void bt_mgrclose (BtMgr *mgr)
695 // release mapped pages
696 // note that slot zero is never used
698 for( slot = 1; slot < mgr->poolmax; slot++ ) {
699 pool = mgr->pool + slot;
702 munmap (pool->map, (mgr->poolmask+1) << mgr->page_bits);
705 FlushViewOfFile(pool->map, 0);
706 UnmapViewOfFile(pool->map);
707 CloseHandle(pool->hmap);
713 munmap (mgr->latchsets, mgr->latchmgr->nlatchpage * mgr->page_size);
714 munmap (mgr->latchmgr, mgr->page_size);
716 FlushViewOfFile(mgr->latchmgr, 0);
717 UnmapViewOfFile(mgr->latchmgr);
718 CloseHandle(mgr->halloc);
725 free (mgr->pooladvise);
728 FlushFileBuffers(mgr->idx);
729 CloseHandle(mgr->idx);
730 GlobalFree (mgr->pool);
731 GlobalFree (mgr->hash);
732 GlobalFree (mgr->latch);
737 // close and release memory
739 void bt_close (BtDb *bt)
746 VirtualFree (bt->mem, 0, MEM_RELEASE);
751 // open/create new btree buffer manager
753 // call with file_name, BT_openmode, bits in page size (e.g. 16),
754 // size of mapped page pool (e.g. 8192)
756 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
758 uint lvl, attr, cacheblk, last, slot, idx;
759 uint nlatchpage, latchhash;
760 BtLatchMgr *latchmgr;
768 SYSTEM_INFO sysinfo[1];
771 // determine sanity of page size and buffer pool
773 if( bits > BT_maxbits )
775 else if( bits < BT_minbits )
779 return NULL; // must have buffer pool
782 mgr = calloc (1, sizeof(BtMgr));
784 mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
787 return free(mgr), NULL;
789 cacheblk = 4096; // minimum mmap segment size for unix
792 mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
793 attr = FILE_ATTRIBUTE_NORMAL;
794 mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
796 if( mgr->idx == INVALID_HANDLE_VALUE )
797 return GlobalFree(mgr), NULL;
799 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
800 GetSystemInfo(sysinfo);
801 cacheblk = sysinfo->dwAllocationGranularity;
805 latchmgr = malloc (BT_maxpage);
808 // read minimum page size to get root info
810 if( size = lseek (mgr->idx, 0L, 2) ) {
811 if( pread(mgr->idx, latchmgr, BT_minpage, 0) == BT_minpage )
812 bits = latchmgr->alloc->bits;
814 return free(mgr), free(latchmgr), NULL;
815 } else if( mode == BT_ro )
816 return free(latchmgr), free (mgr), NULL;
818 latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
819 size = GetFileSize(mgr->idx, amt);
822 if( !ReadFile(mgr->idx, (char *)latchmgr, BT_minpage, amt, NULL) )
823 return bt_mgrclose (mgr), NULL;
824 bits = latchmgr->alloc->bits;
825 } else if( mode == BT_ro )
826 return bt_mgrclose (mgr), NULL;
829 mgr->page_size = 1 << bits;
830 mgr->page_bits = bits;
832 mgr->poolmax = poolmax;
835 if( cacheblk < mgr->page_size )
836 cacheblk = mgr->page_size;
838 // mask for partial memmaps
840 mgr->poolmask = (cacheblk >> bits) - 1;
842 // see if requested size of pages per memmap is greater
844 if( (1 << segsize) > mgr->poolmask )
845 mgr->poolmask = (1 << segsize) - 1;
849 while( (1 << mgr->seg_bits) <= mgr->poolmask )
852 mgr->hashsize = hashsize;
855 mgr->pool = calloc (poolmax, sizeof(BtPool));
856 mgr->hash = calloc (hashsize, sizeof(ushort));
857 mgr->latch = calloc (hashsize, sizeof(BtSpinLatch));
858 mgr->pooladvise = calloc (poolmax, (mgr->poolmask + 8) / 8);
860 mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * sizeof(BtPool));
861 mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
862 mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtSpinLatch));
868 // initialize an empty b-tree with latch page, root page, page of leaves
869 // and page(s) of latches
871 memset (latchmgr, 0, 1 << bits);
872 nlatchpage = BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1;
873 bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
874 latchmgr->alloc->bits = mgr->page_bits;
876 latchmgr->nlatchpage = nlatchpage;
877 latchmgr->latchtotal = nlatchpage * (mgr->page_size / sizeof(BtLatchSet));
879 // initialize latch manager
881 latchhash = (mgr->page_size - sizeof(BtLatchMgr)) / sizeof(BtHashEntry);
883 // size of hash table = total number of latchsets
885 if( latchhash > latchmgr->latchtotal )
886 latchhash = latchmgr->latchtotal;
888 latchmgr->latchhash = latchhash;
891 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
892 return free(latchmgr), bt_mgrclose (mgr), NULL;
894 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
895 return bt_mgrclose (mgr), NULL;
897 if( *amt < mgr->page_size )
898 return bt_mgrclose (mgr), NULL;
901 memset (latchmgr, 0, 1 << bits);
902 latchmgr->alloc->bits = mgr->page_bits;
904 for( lvl=MIN_lvl; lvl--; ) {
905 slotptr(latchmgr->alloc, 1)->off = mgr->page_size - 3;
906 bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
907 key = keyptr(latchmgr->alloc, 1);
908 key->len = 2; // create stopper key
911 latchmgr->alloc->min = mgr->page_size - 3;
912 latchmgr->alloc->lvl = lvl;
913 latchmgr->alloc->cnt = 1;
914 latchmgr->alloc->act = 1;
916 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
917 return bt_mgrclose (mgr), NULL;
919 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
920 return bt_mgrclose (mgr), NULL;
922 if( *amt < mgr->page_size )
923 return bt_mgrclose (mgr), NULL;
927 // clear out latch manager locks
928 // and rest of pages to round out segment
930 memset(latchmgr, 0, mgr->page_size);
933 while( last <= ((MIN_lvl + 1 + nlatchpage) | mgr->poolmask) ) {
935 pwrite(mgr->idx, latchmgr, mgr->page_size, last << mgr->page_bits);
937 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
938 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
939 return bt_mgrclose (mgr), NULL;
940 if( *amt < mgr->page_size )
941 return bt_mgrclose (mgr), NULL;
948 flag = PROT_READ | PROT_WRITE;
949 mgr->latchmgr = mmap (0, mgr->page_size, flag, MAP_SHARED, mgr->idx, ALLOC_page * mgr->page_size);
950 if( mgr->latchmgr == MAP_FAILED )
951 return bt_mgrclose (mgr), NULL;
952 mgr->latchsets = (BtLatchSet *)mmap (0, mgr->latchmgr->nlatchpage * mgr->page_size, flag, MAP_SHARED, mgr->idx, LATCH_page * mgr->page_size);
953 if( mgr->latchsets == MAP_FAILED )
954 return bt_mgrclose (mgr), NULL;
956 flag = PAGE_READWRITE;
957 mgr->halloc = CreateFileMapping(mgr->idx, NULL, flag, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size, NULL);
959 return bt_mgrclose (mgr), NULL;
961 flag = FILE_MAP_WRITE;
962 mgr->latchmgr = MapViewOfFile(mgr->halloc, flag, 0, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size);
964 return GetLastError(), bt_mgrclose (mgr), NULL;
966 mgr->latchsets = (void *)((char *)mgr->latchmgr + LATCH_page * mgr->page_size);
972 VirtualFree (latchmgr, 0, MEM_RELEASE);
977 // open BTree access method
978 // based on buffer manager
980 BtDb *bt_open (BtMgr *mgr)
982 BtDb *bt = malloc (sizeof(*bt));
984 memset (bt, 0, sizeof(*bt));
987 bt->mem = malloc (3 *mgr->page_size);
989 bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
991 bt->frame = (BtPage)bt->mem;
992 bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
993 bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
995 memset(bt->zero, 0, mgr->page_size);
999 // compare two keys, returning > 0, = 0, or < 0
1000 // as the comparison value
1002 int keycmp (BtKey key1, unsigned char *key2, uint len2)
1004 uint len1 = key1->len;
1007 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
1020 void bt_readlock(BtLatch *latch)
1023 pthread_rwlock_rdlock (latch->lock);
1025 AcquireSRWLockShared (latch->srw);
1029 // wait for other read and write latches to relinquish
1031 void bt_writelock(BtLatch *latch)
1034 pthread_rwlock_wrlock (latch->lock);
1036 AcquireSRWLockExclusive (latch->srw);
1040 // try to obtain write lock
1042 // return 1 if obtained,
1043 // 0 if already write or read locked
1045 int bt_writetry(BtLatch *latch)
1050 result = !pthread_rwlock_trywrlock (latch->lock);
1052 result = TryAcquireSRWLockExclusive (latch->srw);
1059 void bt_releasewrite(BtLatch *latch)
1062 pthread_rwlock_unlock (latch->lock);
1064 ReleaseSRWLockExclusive (latch->srw);
1068 // decrement reader count
1070 void bt_releaseread(BtLatch *latch)
1073 pthread_rwlock_unlock (latch->lock);
1075 ReleaseSRWLockShared (latch->srw);
1081 // find segment in pool
1082 // must be called with hashslot idx locked
1083 // return NULL if not there
1084 // otherwise return node
1086 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
1091 // compute start of hash chain in pool
1093 if( slot = bt->mgr->hash[idx] )
1094 pool = bt->mgr->pool + slot;
1098 page_no &= ~bt->mgr->poolmask;
1100 while( pool->basepage != page_no )
1101 if( pool = pool->hashnext )
1109 // add segment to hash table
1111 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
1116 pool->hashprev = pool->hashnext = NULL;
1117 pool->basepage = page_no & ~bt->mgr->poolmask;
1120 if( slot = bt->mgr->hash[idx] ) {
1121 node = bt->mgr->pool + slot;
1122 pool->hashnext = node;
1123 node->hashprev = pool;
1126 bt->mgr->hash[idx] = pool->slot;
1129 // find best segment to evict from buffer pool
1131 BtPool *bt_findlru (BtDb *bt, uint hashslot)
1133 unsigned long long int target = ~0LL;
1134 BtPool *pool = NULL, *node;
1139 node = bt->mgr->pool + hashslot;
1141 // scan pool entries under hash table slot
1146 if( node->lru > target )
1150 } while( node = node->hashnext );
1155 // map new buffer pool segment to virtual memory
1157 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
1159 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
1160 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
1164 flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
1165 pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED, bt->mgr->idx, off);
1166 if( pool->map == MAP_FAILED )
1167 return bt->err = BTERR_map;
1168 // clear out madvise issued bits
1169 memset (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8) / 8), 0, (bt->mgr->poolmask + 8)/8);
1171 flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
1172 pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
1174 return bt->err = BTERR_map;
1176 flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
1177 pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1179 return bt->err = BTERR_map;
1184 // calculate page within pool
1186 BtPage bt_page (BtDb *bt, BtPool *pool, uid page_no)
1188 uint subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1191 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1194 uint idx = subpage / 8;
1195 uint bit = subpage % 8;
1197 if( ~((bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] >> bit) & 1 ) {
1198 madvise (page, bt->mgr->page_size, MADV_WILLNEED);
1199 (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] |= 1 << bit;
1208 void bt_unpinpool (BtPool *pool)
1211 __sync_fetch_and_add(&pool->pin, -1);
1213 _InterlockedDecrement16 (&pool->pin);
1217 // find or place requested page in segment-pool
1218 // return pool table entry, incrementing pin
1220 BtPool *bt_pinpool(BtDb *bt, uid page_no)
1222 BtPool *pool, *node, *next;
1223 uint slot, idx, victim;
1226 // lock hash table chain
1228 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1229 bt_spinreadlock (&bt->mgr->latch[idx]);
1231 // look up in hash table
1233 if( pool = bt_findpool(bt, page_no, idx) ) {
1235 __sync_fetch_and_add(&pool->pin, 1);
1237 _InterlockedIncrement16 (&pool->pin);
1239 bt_spinreleaseread (&bt->mgr->latch[idx]);
1244 // upgrade to write lock
1246 bt_spinreleaseread (&bt->mgr->latch[idx]);
1247 bt_spinwritelock (&bt->mgr->latch[idx]);
1249 // try to find page in pool with write lock
1251 if( pool = bt_findpool(bt, page_no, idx) ) {
1253 __sync_fetch_and_add(&pool->pin, 1);
1255 _InterlockedIncrement16 (&pool->pin);
1257 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1262 // allocate a new pool node
1263 // and add to hash table
1266 slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
1268 slot = _InterlockedIncrement16 (&bt->mgr->poolcnt) - 1;
1271 if( ++slot < bt->mgr->poolmax ) {
1272 pool = bt->mgr->pool + slot;
1275 if( bt_mapsegment(bt, pool, page_no) )
1278 bt_linkhash(bt, pool, page_no, idx);
1280 __sync_fetch_and_add(&pool->pin, 1);
1282 _InterlockedIncrement16 (&pool->pin);
1284 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1288 // pool table is full
1289 // find best pool entry to evict
1292 __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
1294 _InterlockedDecrement16 (&bt->mgr->poolcnt);
1299 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
1301 victim = _InterlockedIncrement16 (&bt->mgr->evicted) - 1;
1303 victim %= bt->mgr->hashsize;
1305 // try to get write lock
1306 // skip entry if not obtained
1308 if( !bt_spinwritetry (&bt->mgr->latch[victim]) )
1311 // if cache entry is empty
1312 // or no slots are unpinned
1315 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
1316 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1320 // unlink victim pool node from hash table
1322 if( node = pool->hashprev )
1323 node->hashnext = pool->hashnext;
1324 else if( node = pool->hashnext )
1325 bt->mgr->hash[victim] = node->slot;
1327 bt->mgr->hash[victim] = 0;
1329 if( node = pool->hashnext )
1330 node->hashprev = pool->hashprev;
1332 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1334 // remove old file mapping
1336 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1338 FlushViewOfFile(pool->map, 0);
1339 UnmapViewOfFile(pool->map);
1340 CloseHandle(pool->hmap);
1344 // create new pool mapping
1345 // and link into hash table
1347 if( bt_mapsegment(bt, pool, page_no) )
1350 bt_linkhash(bt, pool, page_no, idx);
1352 __sync_fetch_and_add(&pool->pin, 1);
1354 _InterlockedIncrement16 (&pool->pin);
1356 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1361 // place write, read, or parent lock on requested page_no.
1362 // pin to buffer pool and return latchset pointer
1364 void bt_lockpage(BtLock mode, BtLatchSet *set)
1368 bt_readlock (set->readwr);
1371 bt_writelock (set->readwr);
1374 bt_readlock (set->access);
1377 bt_writelock (set->access);
1380 bt_writelock (set->parent);
1385 // remove write, read, or parent lock on requested page_no.
1387 void bt_unlockpage(BtLock mode, BtLatchSet *set)
1391 bt_releaseread (set->readwr);
1394 bt_releasewrite (set->readwr);
1397 bt_releaseread (set->access);
1400 bt_releasewrite (set->access);
1403 bt_releasewrite (set->parent);
1408 // allocate a new page and write page into it
1410 uid bt_newpage(BtDb *bt, BtPage page)
1418 // lock allocation page
1420 bt_spinwritelock(bt->mgr->latchmgr->lock);
1422 // use empty chain first
1423 // else allocate empty page
1425 if( new_page = bt_getid(bt->mgr->latchmgr->alloc[1].right) ) {
1426 if( pool = bt_pinpool (bt, new_page) )
1427 pmap = bt_page (bt, pool, new_page);
1430 bt_putid(bt->mgr->latchmgr->alloc[1].right, bt_getid(pmap->right));
1431 bt_unpinpool (pool);
1434 new_page = bt_getid(bt->mgr->latchmgr->alloc->right);
1435 bt_putid(bt->mgr->latchmgr->alloc->right, new_page+1);
1439 // if writing first page of pool block, zero last page in the block
1441 if ( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1443 // use zero buffer to write zeros
1444 if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1445 return bt->err = BTERR_wrt, 0;
1448 // unlock allocation latch
1450 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1452 if ( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1453 return bt->err = BTERR_wrt, 0;
1456 // unlock allocation latch
1458 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1460 // bring new page into pool and copy page.
1461 // this will extend the file into the new pages.
1462 // NB -- no latch required
1464 if( pool = bt_pinpool (bt, new_page) )
1465 pmap = bt_page (bt, pool, new_page);
1469 memcpy(pmap, page, bt->mgr->page_size);
1470 bt_unpinpool (pool);
1475 // find slot in page for given key at a given level
1477 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1479 uint diff, higher = bt->page->cnt, low = 1, slot;
1481 // low is the lowest candidate, higher is already
1482 // tested as .ge. the given key, loop ends when they meet
1484 while( diff = higher - low ) {
1485 slot = low + ( diff >> 1 );
1486 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1495 // find and load page at given level for given key
1496 // leave page rd or wr locked as requested
1498 uint bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, BtLock lock)
1500 uid page_no = ROOT_page, prevpage = 0;
1501 BtLatchSet *set, *prevset;
1502 uint drill = 0xff, slot;
1503 uint mode, prevmode;
1507 // start at root of btree and drill down
1510 // determine lock mode of drill level
1511 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1513 // obtain latch set for this page
1515 bt->set = bt_pinlatch (bt, page_no);
1516 bt->page_no = page_no;
1518 // pin page contents
1520 if( bt->pool = bt_pinpool (bt, page_no) )
1521 bt->page = bt_page (bt, bt->pool, page_no);
1525 // obtain access lock using lock chaining with Access mode
1527 if( page_no > ROOT_page )
1528 bt_lockpage(BtLockAccess, bt->set);
1530 // now unlock and unpin our (possibly foster) parent
1533 bt_unlockpage(prevmode, prevset);
1534 bt_unpinlatch (prevset);
1535 bt_unpinpool (prevpool);
1539 // obtain read lock using lock chaining
1541 bt_lockpage(mode, bt->set);
1543 if( page_no > ROOT_page )
1544 bt_unlockpage(BtLockAccess, bt->set);
1546 // re-read and re-lock root after determining actual level of root
1548 if( page_no == ROOT_page )
1549 if( bt->page->lvl != drill) {
1550 drill = bt->page->lvl;
1552 if( lock == BtLockWrite && drill == lvl ) {
1553 bt_unlockpage(mode, bt->set);
1554 bt_unpinlatch (bt->set);
1555 bt_unpinpool (bt->pool);
1560 prevpage = bt->page_no;
1561 prevpool = bt->pool;
1565 // were we supposed to find a foster child?
1566 // if so, slide right onto it
1568 if( keycmp (keyptr(bt->page,bt->page->cnt), key, len) < 0 ) {
1569 page_no = bt_getid(bt->page->right);
1574 // find key on page at this level
1575 // and either descend to requested level
1576 // or return key slot
1578 slot = bt_findslot (bt, key, len);
1580 // is this slot < foster child area
1581 // on the requested level?
1583 // if so, return actual slot even if dead
1585 if( slot <= bt->page->cnt - bt->page->foster )
1587 return bt->foster = foster, slot;
1589 // find next active slot
1591 // note: foster children are never dead
1593 while( slotptr(bt->page, slot)->dead )
1594 if( slot++ < bt->page->cnt )
1597 // we are waiting for fence key posting
1598 page_no = bt_getid(bt->page->right);
1602 // is this slot < foster child area
1603 // if so, drill to next level
1605 if( slot <= bt->page->cnt - bt->page->foster )
1606 foster = 0, drill--;
1610 // continue right onto foster child
1611 // or down to next level.
1613 page_no = bt_getid(slotptr(bt->page, slot)->id);
1617 // return error on end of chain
1619 bt->err = BTERR_struct;
1620 return 0; // return error
1623 // remove empty page from the B-tree
1624 // by pulling our right node left over ourselves
1626 // call with bt->page, etc, set to page's locked parent
1627 // returns with page locked.
1629 BTERR bt_mergeright (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no, uint lvl, uint slot)
1631 BtLatchSet *rset, *pset, *rpset;
1632 BtPool *rpool, *ppool, *rppool;
1633 BtPage rpage, ppage, rppage;
1634 uid right, parent, rparent;
1638 // cache node's parent page
1640 parent = bt->page_no;
1645 // lock and map our right page
1646 // note that it cannot be our foster child
1647 // since the our node is empty
1648 // and it cannot be NULL because of the stopper
1649 // in the last right page
1651 bt_lockpage (BtLockWrite, set);
1653 // if we aren't dead yet
1658 if( right = bt_getid (page->right) )
1659 if( rpool = bt_pinpool (bt, right) )
1660 rpage = bt_page (bt, rpool, right);
1664 return bt->err = BTERR_struct;
1666 rset = bt_pinlatch (bt, right);
1668 // find our right neighbor
1670 if( ppage->act > 1 ) {
1671 for( idx = slot; idx++ < ppage->cnt; )
1672 if( !slotptr(ppage, idx)->dead )
1675 if( idx > ppage->cnt )
1676 return bt->err = BTERR_struct;
1678 // redirect right neighbor in parent to left node
1680 bt_putid(slotptr(ppage,idx)->id, page_no);
1683 // if parent has only our deleted page, e.g. no right neighbor
1684 // prepare to merge parent itself
1686 if( ppage->act == 1 ) {
1687 if( rparent = bt_getid (ppage->right) )
1688 if( rppool = bt_pinpool (bt, rparent) )
1689 rppage = bt_page (bt, rppool, rparent);
1693 return bt->err = BTERR_struct;
1695 rpset = bt_pinlatch (bt, rparent);
1696 bt_lockpage (BtLockWrite, rpset);
1698 // find our right neighbor on right parent page
1700 for( idx = 0; idx++ < rppage->cnt; )
1701 if( !slotptr(rppage, idx)->dead ) {
1702 bt_putid (slotptr(rppage, idx)->id, page_no);
1706 if( idx > rppage->cnt )
1707 return bt->err = BTERR_struct;
1710 // now that there are no more pointers to our right node
1711 // we can wait for delete lock on it
1713 bt_lockpage(BtLockDelete, rset);
1714 bt_lockpage(BtLockWrite, rset);
1716 // pull contents of right page into our empty page
1718 memcpy (page, rpage, bt->mgr->page_size);
1720 // ready to release right parent lock
1721 // now that we have a new page in place
1723 if( ppage->act == 1 ) {
1724 bt_unlockpage (BtLockWrite, rpset);
1725 bt_unpinlatch (rpset);
1726 bt_unpinpool (rppool);
1729 // add killed right block to free chain
1732 bt_spinwritelock(bt->mgr->latchmgr->lock);
1734 // store free chain in allocation page second right
1736 bt_putid(rpage->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1737 bt_putid(bt->mgr->latchmgr->alloc[1].right, right);
1739 // unlock latch mgr and right page
1741 bt_unlockpage(BtLockDelete, rset);
1742 bt_unlockpage(BtLockWrite, rset);
1743 bt_unpinlatch (rset);
1744 bt_unpinpool (rpool);
1746 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1748 // delete our obsolete fence key from our parent
1750 slotptr(ppage, slot)->dead = 1;
1753 // if our parent now empty
1754 // remove it from the tree
1756 if( ppage->act-- == 1 )
1757 if( bt_mergeleft (bt, ppage, ppool, pset, parent, lvl+1) )
1761 bt_unlockpage (BtLockWrite, pset);
1762 bt_unpinlatch (pset);
1763 bt_unpinpool (ppool);
1769 // remove empty page from the B-tree
1770 // try merging left first. If no left
1771 // sibling, then merge right.
1773 // call with page loaded and locked,
1774 // return with page locked.
1776 BTERR bt_mergeleft (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no, uint lvl)
1778 unsigned char fencekey[256], postkey[256];
1779 uint slot, idx, postfence = 0;
1780 BtLatchSet *lset, *pset;
1781 BtPool *lpool, *ppool;
1782 BtPage lpage, ppage;
1786 ptr = keyptr(page, page->cnt);
1787 memcpy(fencekey, ptr, ptr->len + 1);
1788 bt_unlockpage (BtLockWrite, set);
1790 // load and lock our parent
1793 if( !(slot = bt_loadpage (bt, fencekey+1, *fencekey, lvl+1, BtLockWrite)) )
1796 parent = bt->page_no;
1801 // wait until we are not a foster child
1804 bt_unlockpage (BtLockWrite, pset);
1805 bt_unpinlatch (pset);
1806 bt_unpinpool (ppool);
1815 // find our left neighbor in our parent page
1817 for( idx = slot; --idx; )
1818 if( !slotptr(ppage, idx)->dead )
1821 // if no left neighbor, do right merge
1824 return bt_mergeright (bt, page, pool, set, page_no, lvl, slot);
1826 // lock and map our left neighbor's page
1828 left = bt_getid (slotptr(ppage, idx)->id);
1830 if( lpool = bt_pinpool (bt, left) )
1831 lpage = bt_page (bt, lpool, left);
1835 lset = bt_pinlatch (bt, left);
1836 bt_lockpage(BtLockWrite, lset);
1838 // wait until foster sibling is in our parent
1840 if( bt_getid (lpage->right) != page_no ) {
1841 bt_unlockpage (BtLockWrite, pset);
1842 bt_unpinlatch (pset);
1843 bt_unpinpool (ppool);
1844 bt_unlockpage (BtLockWrite, lset);
1845 bt_unpinlatch (lset);
1846 bt_unpinpool (lpool);
1855 // since our page will have no more pointers to it,
1856 // obtain Delete lock and wait for write locks to clear
1858 bt_lockpage(BtLockDelete, set);
1859 bt_lockpage(BtLockWrite, set);
1861 // if we aren't dead yet,
1862 // get ready for exit
1865 bt_unlockpage(BtLockDelete, set);
1866 bt_unlockpage(BtLockWrite, lset);
1867 bt_unpinlatch (lset);
1868 bt_unpinpool (lpool);
1872 // are we are the fence key for our parent?
1873 // if so, grab our old fence key
1875 if( postfence = slot == ppage->cnt ) {
1876 ptr = keyptr (ppage, ppage->cnt);
1877 memcpy(fencekey, ptr, ptr->len + 1);
1878 memset(slotptr(ppage, ppage->cnt), 0, sizeof(BtSlot));
1880 // clear out other dead slots
1882 while( --ppage->cnt )
1883 if( slotptr(ppage, ppage->cnt)->dead )
1884 memset(slotptr(ppage, ppage->cnt), 0, sizeof(BtSlot));
1888 ptr = keyptr (ppage, ppage->cnt);
1889 memcpy(postkey, ptr, ptr->len + 1);
1891 slotptr(ppage,slot)->dead = 1;
1896 // push our right neighbor pointer to our left
1898 memcpy (lpage->right, page->right, BtId);
1900 // add ourselves to free chain
1903 bt_spinwritelock(bt->mgr->latchmgr->lock);
1905 // store free chain in allocation page second right
1906 bt_putid(page->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1907 bt_putid(bt->mgr->latchmgr->alloc[1].right, page_no);
1909 // unlock latch mgr and pages
1911 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1912 bt_unlockpage(BtLockWrite, lset);
1913 bt_unpinlatch (lset);
1914 bt_unpinpool (lpool);
1916 // release our node's delete lock
1918 bt_unlockpage(BtLockDelete, set);
1921 bt_unlockpage (BtLockWrite, pset);
1922 bt_unpinpool (ppool);
1924 // do we need to post parent's fence key in its parent?
1926 if( !postfence || parent == ROOT_page ) {
1927 bt_unpinlatch (pset);
1932 // interlock parent fence post
1934 bt_lockpage (BtLockParent, pset);
1936 // load parent's parent page
1938 if( !(slot = bt_loadpage (bt, fencekey+1, *fencekey, lvl+2, BtLockWrite)) )
1941 if( !(slot = bt_cleanpage (bt, bt->page, *fencekey, slot)) )
1942 if( bt_splitpage (bt, bt->page, bt->pool, bt->set, bt->page_no) )
1949 page->min -= *postkey + 1;
1950 ((unsigned char *)page)[page->min] = *postkey;
1951 memcpy ((unsigned char *)page + page->min +1, postkey + 1, *postkey );
1952 slotptr(page, slot)->off = page->min;
1954 bt_unlockpage (BtLockParent, pset);
1955 bt_unpinlatch (pset);
1957 bt_unlockpage (BtLockWrite, bt->set);
1958 bt_unpinlatch (bt->set);
1959 bt_unpinpool (bt->pool);
1965 // find and delete key on page by marking delete flag bit
1966 // if page becomes empty, delete it from the btree
1968 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len)
1977 if( !(slot = bt_loadpage (bt, key, len, 0, BtLockWrite)) )
1980 page_no = bt->page_no;
1985 // if key is found delete it, otherwise ignore request
1987 ptr = keyptr(page, slot);
1989 if( bt->found = !keycmp (ptr, key, len) )
1990 if( bt->found = slotptr(page, slot)->dead == 0 ) {
1991 slotptr(page,slot)->dead = 1;
1992 if( slot < page->cnt )
1995 if( bt_mergeleft (bt, page, pool, set, page_no, 0) )
1999 bt_unlockpage(BtLockWrite, set);
2000 bt_unpinlatch (set);
2001 bt_unpinpool (pool);
2005 // find key in leaf level and return row-id
2007 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
2013 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
2014 ptr = keyptr(bt->page, slot);
2018 // if key exists, return row-id
2019 // otherwise return 0
2021 if( slot <= bt->page->cnt && !keycmp (ptr, key, len) )
2022 id = bt_getid(slotptr(bt->page,slot)->id);
2026 bt_unlockpage (BtLockRead, bt->set);
2027 bt_unpinlatch (bt->set);
2028 bt_unpinpool (bt->pool);
2032 // check page for space available,
2033 // clean if necessary and return
2034 // 0 - page needs splitting
2035 // >0 new slot value
2037 uint bt_cleanpage(BtDb *bt, BtPage page, uint amt, uint slot)
2039 uint nxt = bt->mgr->page_size;
2040 uint cnt = 0, idx = 0;
2041 uint max = page->cnt;
2045 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
2048 // skip cleanup if nothing to reclaim
2053 memcpy (bt->frame, page, bt->mgr->page_size);
2055 // skip page info and set rest of page to zero
2057 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
2061 // try cleaning up page first
2063 // always leave fence key in the array
2064 // otherwise, remove deleted key
2066 // note: foster children are never dead
2068 while( cnt++ < max ) {
2071 if( cnt < max && slotptr(bt->frame,cnt)->dead )
2076 key = keyptr(bt->frame, cnt);
2077 nxt -= key->len + 1;
2078 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2081 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
2082 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
2084 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2085 slotptr(page, idx)->off = nxt;
2091 // see if page has enough space now, or does it need splitting?
2093 if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
2099 // add key to current page
2100 // page must already be writelocked
2102 void bt_addkeytopage (BtDb *bt, BtPage page, uint slot, unsigned char *key, uint len, uid id, uint tod)
2106 // find next available dead slot and copy key onto page
2107 // note that foster children on the page are never dead
2109 // look for next hole, but stay back from the fence key
2111 for( idx = slot; idx < page->cnt; idx++ )
2112 if( slotptr(page, idx)->dead )
2115 if( idx == page->cnt )
2120 // now insert key into array before slot
2123 *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
2125 page->min -= len + 1;
2126 ((unsigned char *)page)[page->min] = len;
2127 memcpy ((unsigned char *)page + page->min +1, key, len );
2129 bt_putid(slotptr(page,slot)->id, id);
2130 slotptr(page, slot)->off = page->min;
2131 slotptr(page, slot)->tod = tod;
2132 slotptr(page, slot)->dead = 0;
2135 // split the root and raise the height of the btree
2136 // call with current page locked and page no of foster child
2137 // return with current page (root) unlocked
2139 BTERR bt_splitroot(BtDb *bt, uid right)
2141 uint nxt = bt->mgr->page_size;
2142 unsigned char fencekey[256];
2143 BtPage root = bt->page;
2147 // Obtain an empty page to use, and copy the left page
2148 // contents into it from the root. Strip foster child key.
2149 // (it's the stopper key)
2151 memset (slotptr(root, root->cnt), 0, sizeof(BtSlot));
2157 // Save left fence key.
2159 key = keyptr(root, root->cnt);
2160 memcpy (fencekey, key, key->len + 1);
2162 // copy the lower keys into a new left page
2164 if( !(new_page = bt_newpage(bt, root)) )
2167 // preserve the page info at the bottom
2168 // and set rest of the root to zero
2170 memset (root+1, 0, bt->mgr->page_size - sizeof(*root));
2172 // insert left fence key on empty newroot page
2174 nxt -= *fencekey + 1;
2175 memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
2176 bt_putid(slotptr(root, 1)->id, new_page);
2177 slotptr(root, 1)->off = nxt;
2179 // insert stopper key on newroot page
2180 // and increase the root height
2186 memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
2187 bt_putid(slotptr(root, 2)->id, right);
2188 slotptr(root, 2)->off = nxt;
2190 bt_putid(root->right, 0);
2191 root->min = nxt; // reset lowest used offset and key count
2196 // release and unpin root (bt->page)
2198 bt_unlockpage(BtLockWrite, bt->set);
2199 bt_unpinlatch (bt->set);
2200 bt_unpinpool (bt->pool);
2204 // split already locked full node
2205 // return unlocked and unpinned.
2207 BTERR bt_splitpage (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no)
2209 uint slot, cnt, idx, max, nxt = bt->mgr->page_size;
2210 unsigned char fencekey[256];
2211 uint tod = time(NULL);
2212 uint lvl = page->lvl;
2216 // initialize frame buffer for right node
2218 memset (bt->frame, 0, bt->mgr->page_size);
2219 max = page->cnt - page->foster;
2223 // split higher half of keys to bt->frame
2224 // leaving old foster children in the left node,
2225 // and adding a new foster child there.
2227 while( cnt++ < max ) {
2228 key = keyptr(page, cnt);
2229 nxt -= key->len + 1;
2230 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
2231 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
2232 if( !(slotptr(bt->frame, idx)->dead = slotptr(page, cnt)->dead) )
2234 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
2235 slotptr(bt->frame, idx)->off = nxt;
2238 // transfer right link node to new right node
2240 if( page_no > ROOT_page )
2241 memcpy (bt->frame->right, page->right, BtId);
2243 bt->frame->bits = bt->mgr->page_bits;
2244 bt->frame->min = nxt;
2245 bt->frame->cnt = idx;
2246 bt->frame->lvl = lvl;
2248 // get new free page and write right frame to it.
2250 if( !(new_page = bt_newpage(bt, bt->frame)) )
2253 // remember fence key for new right page to add
2254 // as foster child to the left node
2256 key = keyptr(bt->frame, idx);
2257 memcpy (fencekey, key, key->len + 1);
2259 // update lower keys and foster children to continue in old page
2261 memcpy (bt->frame, page, bt->mgr->page_size);
2262 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
2263 nxt = bt->mgr->page_size;
2269 // assemble page of smaller keys
2270 // to remain in the old page
2272 while( cnt++ < max / 2 ) {
2273 key = keyptr(bt->frame, cnt);
2274 nxt -= key->len + 1;
2275 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2276 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
2277 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
2279 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2280 slotptr(page, idx)->off = nxt;
2283 // insert new foster child for right page in queue
2284 // before any of the current foster children
2286 nxt -= *fencekey + 1;
2287 memcpy ((unsigned char *)page + nxt, fencekey, *fencekey + 1);
2289 bt_putid (slotptr(page,++idx)->id, new_page);
2290 slotptr(page, idx)->tod = tod;
2291 slotptr(page, idx)->off = nxt;
2295 // continue with old foster child keys
2296 // note that none will be dead
2298 cnt = bt->frame->cnt - bt->frame->foster;
2300 while( cnt++ < bt->frame->cnt ) {
2301 key = keyptr(bt->frame, cnt);
2302 nxt -= key->len + 1;
2303 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2304 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
2305 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2306 slotptr(page, idx)->off = nxt;
2313 // link new right page
2315 bt_putid (page->right, new_page);
2317 // if current page is the root page, split it
2319 if( page_no == ROOT_page )
2320 return bt_splitroot (bt, new_page);
2322 // release wr lock on our page
2324 bt_unlockpage (BtLockWrite, set);
2326 // obtain ParentModification lock for current page
2327 // to fix new fence key and oldest foster child on page
2329 bt_lockpage (BtLockParent, set);
2331 // get our new fence key to insert in parent node
2333 bt_lockpage (BtLockRead, set);
2335 key = keyptr(page, page->cnt-1);
2336 memcpy (fencekey, key, key->len+1);
2338 bt_unlockpage (BtLockRead, set);
2340 if( bt_insertkey (bt, fencekey + 1, *fencekey, page_no, tod, lvl + 1) )
2343 // lock our page for writing
2345 bt_lockpage (BtLockRead, set);
2347 // switch old parent key from us to our oldest foster child
2349 key = keyptr(page, page->cnt);
2350 memcpy (fencekey, key, key->len+1);
2352 new_page = bt_getid (slotptr(page, page->cnt)->id);
2353 bt_unlockpage (BtLockRead, set);
2355 if( bt_insertkey (bt, fencekey + 1, *fencekey, new_page, tod, lvl + 1) )
2358 // now that it has its own parent pointer,
2359 // remove oldest foster child from our page
2361 bt_lockpage (BtLockWrite, set);
2362 memset (slotptr(page, page->cnt), 0, sizeof(BtSlot));
2368 bt_unlockpage (BtLockParent, set);
2370 // if this emptied page,
2371 // undo the foster child
2374 if( bt_mergeleft (bt, page, pool, set, page_no, lvl) )
2379 bt_unlockpage (BtLockWrite, set);
2380 bt_unpinlatch (set);
2381 bt_unpinpool (pool);
2385 // Insert new key into the btree at leaf level.
2387 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod, uint lvl)
2394 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
2395 ptr = keyptr(bt->page, slot);
2399 bt->err = BTERR_ovflw;
2403 // if key already exists, update id and return
2407 if( !keycmp (ptr, key, len) ) {
2408 if( slotptr(page, slot)->dead )
2410 slotptr(page, slot)->dead = 0;
2411 slotptr(page, slot)->tod = tod;
2412 bt_putid(slotptr(page,slot)->id, id);
2413 bt_unlockpage(BtLockWrite, bt->set);
2414 bt_unpinlatch (bt->set);
2415 bt_unpinpool (bt->pool);
2419 // check if page has enough space
2421 if( slot = bt_cleanpage (bt, bt->page, len, slot) )
2424 if( bt_splitpage (bt, bt->page, bt->pool, bt->set, bt->page_no) )
2428 bt_addkeytopage (bt, bt->page, slot, key, len, id, tod);
2430 bt_unlockpage (BtLockWrite, bt->set);
2431 bt_unpinlatch (bt->set);
2432 bt_unpinpool (bt->pool);
2436 // cache page of keys into cursor and return starting slot for given key
2438 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2442 // cache page for retrieval
2443 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
2444 memcpy (bt->cursor, bt->page, bt->mgr->page_size);
2446 bt->cursor_page = bt->page_no;
2448 bt_unlockpage(BtLockRead, bt->set);
2449 bt_unpinlatch (bt->set);
2450 bt_unpinpool (bt->pool);
2454 // return next slot for cursor page
2455 // or slide cursor right into next page
2457 uint bt_nextkey (BtDb *bt, uint slot)
2465 right = bt_getid(bt->cursor->right);
2466 while( slot++ < bt->cursor->cnt - bt->cursor->foster )
2467 if( slotptr(bt->cursor,slot)->dead )
2469 else if( right || (slot < bt->cursor->cnt - bt->cursor->foster) )
2477 bt->cursor_page = right;
2478 if( pool = bt_pinpool (bt, right) )
2479 page = bt_page (bt, pool, right);
2483 set = bt_pinlatch (bt, right);
2484 bt_lockpage(BtLockRead, set);
2486 memcpy (bt->cursor, page, bt->mgr->page_size);
2488 bt_unlockpage(BtLockRead, set);
2489 bt_unpinlatch (set);
2490 bt_unpinpool (pool);
2497 BtKey bt_key(BtDb *bt, uint slot)
2499 return keyptr(bt->cursor, slot);
2502 uid bt_uid(BtDb *bt, uint slot)
2504 return bt_getid(slotptr(bt->cursor,slot)->id);
2507 uint bt_tod(BtDb *bt, uint slot)
2509 return slotptr(bt->cursor,slot)->tod;
2522 // standalone program to index file of keys
2523 // then list them onto std-out
2526 void *index_file (void *arg)
2528 uint __stdcall index_file (void *arg)
2531 int line = 0, found = 0, cnt = 0;
2532 uid next, page_no = LEAF_page; // start on first page of leaves
2533 unsigned char key[256];
2534 ThreadArg *args = arg;
2535 int ch, len = 0, slot;
2544 bt = bt_open (args->mgr);
2547 switch(args->type | 0x20)
2550 fprintf(stderr, "started indexing for %s\n", args->infile);
2551 if( in = fopen (args->infile, "rb") )
2552 while( ch = getc(in), ch != EOF )
2557 if( args->num == 1 )
2558 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2560 else if( args->num )
2561 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2563 if( bt_insertkey (bt, key, len, line, *tod, 0) )
2564 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2567 else if( len < 255 )
2569 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
2573 fprintf(stderr, "started deleting keys for %s\n", args->infile);
2574 if( in = fopen (args->infile, "rb") )
2575 while( ch = getc(in), ch != EOF )
2579 if( args->num == 1 )
2580 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2582 else if( args->num )
2583 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2585 if( bt_deletekey (bt, key, len) )
2586 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2589 else if( len < 255 )
2591 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2595 fprintf(stderr, "started finding keys for %s\n", args->infile);
2596 if( in = fopen (args->infile, "rb") )
2597 while( ch = getc(in), ch != EOF )
2601 if( args->num == 1 )
2602 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2604 else if( args->num )
2605 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2607 if( bt_findkey (bt, key, len) )
2610 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2613 else if( len < 255 )
2615 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2621 fprintf(stderr, "started reading\n");
2623 if( slot = bt_startkey (bt, key, len) )
2626 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
2628 while( slot = bt_nextkey (bt, slot) ) {
2629 ptr = bt_key(bt, slot);
2630 fwrite (ptr->key, ptr->len, 1, stdout);
2631 fputc ('\n', stdout);
2637 fprintf(stderr, "started reading\n");
2640 if( pool = bt_pinpool (bt, page_no) )
2641 page = bt_page (bt, pool, page_no);
2644 set = bt_pinlatch (bt, page_no);
2645 bt_lockpage (BtLockRead, set);
2647 next = bt_getid (page->right);
2648 bt_unlockpage (BtLockRead, set);
2649 bt_unpinlatch (set);
2650 bt_unpinpool (pool);
2651 } while( page_no = next );
2653 cnt--; // remove stopper key
2654 fprintf(stderr, " Total keys read %d\n", cnt);
2666 typedef struct timeval timer;
2668 int main (int argc, char **argv)
2670 int idx, cnt, len, slot, err;
2671 int segsize, bits = 16;
2676 time_t start[1], stop[1];
2689 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]);
2690 fprintf (stderr, " where page_bits is the page size in bits\n");
2691 fprintf (stderr, " mapped_segments is the number of mmap segments in buffer pool\n");
2692 fprintf (stderr, " seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2693 fprintf (stderr, " line_numbers = 1 to append line numbers to keys\n");
2694 fprintf (stderr, " src_file1 thru src_filen are files of keys separated by newline\n");
2699 gettimeofday(&start, NULL);
2705 bits = atoi(argv[3]);
2708 poolsize = atoi(argv[4]);
2711 fprintf (stderr, "Warning: no mapped_pool\n");
2713 if( poolsize > 65535 )
2714 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2717 segsize = atoi(argv[5]);
2719 segsize = 4; // 16 pages per mmap segment
2722 num = atoi(argv[6]);
2726 threads = malloc (cnt * sizeof(pthread_t));
2728 threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2730 args = malloc (cnt * sizeof(ThreadArg));
2732 mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2735 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2741 for( idx = 0; idx < cnt; idx++ ) {
2742 args[idx].infile = argv[idx + 7];
2743 args[idx].type = argv[2][0];
2744 args[idx].mgr = mgr;
2745 args[idx].num = num;
2746 args[idx].idx = idx;
2748 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2749 fprintf(stderr, "Error creating thread %d\n", err);
2751 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2755 // wait for termination
2758 for( idx = 0; idx < cnt; idx++ )
2759 pthread_join (threads[idx], NULL);
2760 gettimeofday(&stop, NULL);
2761 real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2763 WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2765 for( idx = 0; idx < cnt; idx++ )
2766 CloseHandle(threads[idx]);
2769 real_time = 1000 * (*stop - *start);
2771 fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);