1 // foster btree version g
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
28 #include <linux/futex.h>
43 #define WIN32_LEAN_AND_MEAN
56 typedef unsigned long long uid;
59 typedef unsigned long long off64_t;
60 typedef unsigned short ushort;
61 typedef unsigned int uint;
64 #define BT_ro 0x6f72 // ro
65 #define BT_rw 0x7772 // rw
67 #define BT_latchtable 128 // number of latch manager slots
69 #define BT_maxbits 24 // maximum page size in bits
70 #define BT_minbits 9 // minimum page size in bits
71 #define BT_minpage (1 << BT_minbits) // minimum page size
72 #define BT_maxpage (1 << BT_maxbits) // maximum page size
75 There are five lock types for each node in three independent sets:
76 1. (set 1) AccessIntent: Sharable. Going to Read the node. Incompatible with NodeDelete.
77 2. (set 1) NodeDelete: Exclusive. About to release the node. Incompatible with AccessIntent.
78 3. (set 2) ReadLock: Sharable. Read the node. Incompatible with WriteLock.
79 4. (set 2) WriteLock: Exclusive. Modify the node. Incompatible with ReadLock and other WriteLocks.
80 5. (set 3) ParentLock: Exclusive. Have parent adopt/delete maximum foster child from the node.
91 // Define the length of the page and key pointers
95 // Page key slot definition.
97 // If BT_maxbits is 15 or less, you can save 4 bytes
98 // for each key stored by making the first two uints
99 // into ushorts. You can also save 4 bytes by removing
100 // the tod field from the key.
102 // Keys are marked dead, but remain on the page until
103 // cleanup is called. The fence key (highest key) for
104 // the page is always present, even after cleanup.
107 uint off:BT_maxbits; // page offset for key start
108 uint dead:1; // set for deleted key
109 uint tod; // time-stamp for key
110 unsigned char id[BtId]; // id associated with key
113 // The key structure occupies space at the upper end of
114 // each page. It's a length byte followed by the value
119 unsigned char key[1];
122 // The first part of an index page.
123 // It is immediately followed
124 // by the BtSlot array of keys.
126 typedef struct Page {
127 volatile uint cnt; // count of keys in page
128 volatile uint act; // count of active keys
129 volatile uint min; // next key offset
130 volatile uint foster; // count of foster children
131 unsigned char bits; // page size in bits
132 unsigned char lvl:7; // level of page
133 unsigned char dirty:1; // page needs to be cleaned
134 unsigned char right[BtId]; // page number to right
137 // mode & definition for latch implementation
140 Mutex = 1 << 0, // the mutex bit
141 Write = 1 << 1, // the writers bit
142 Share = 1 << 2, // reader count
143 PendRd = 1 << 12, // reader contended count
144 PendWr = 1 << 22 // writer contended count
148 QueRd = 1, // reader queue
149 QueWr = 2 // writer queue
152 // share is count of read accessors
153 // grant write lock when share == 0
156 volatile uint mutex:1; // 1 = busy
157 volatile uint write:1; // 1 = exclusive
158 volatile uint share:10; // count of readers holding locks
159 volatile uint readwait:10; // count of readers waiting
160 volatile uint writewait:10; // count of writers waiting
163 // hash table entries
167 volatile ushort slot; // Latch table entry at head of chain
170 // latch manager table structure
173 BtLatch readwr[1]; // read/write page lock
174 BtLatch access[1]; // Access Intent/Page delete
175 BtLatch parent[1]; // adoption of foster children
176 BtLatch busy[1]; // slot is being moved between chains
177 volatile ushort next; // next entry in hash table chain
178 volatile ushort prev; // prev entry in hash table chain
179 volatile ushort pin; // number of outstanding locks
180 volatile ushort hash; // hash slot entry is under
181 volatile uid page_no; // latch set page number
184 // The memory mapping pool table buffer manager entry
187 unsigned long long int lru; // number of times accessed
188 uid basepage; // mapped base page number
189 char *map; // mapped memory pointer
190 ushort pin; // mapped page pin counter
191 ushort slot; // slot index in this array
192 void *hashprev; // previous pool entry for the same hash idx
193 void *hashnext; // next pool entry for the same hash idx
195 HANDLE hmap; // Windows memory mapping handle
199 // structure for latch manager on ALLOC_page
202 struct Page alloc[2]; // next & free page_nos in right ptr
203 BtLatch lock[1]; // allocation area lite latch
204 ushort latchdeployed; // highest number of latch entries deployed
205 ushort nlatchpage; // number of latch pages at BT_latch
206 ushort latchtotal; // number of page latch entries
207 ushort latchhash; // number of latch hash table slots
208 ushort latchvictim; // next latch entry to examine
209 BtHashEntry table[0]; // the hash table
212 // The object structure for Btree access
215 uint page_size; // page size
216 uint page_bits; // page size in bits
217 uint seg_bits; // seg size in pages in bits
218 uint mode; // read-write mode
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 BtLatch *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);
275 // internal functions
276 BTERR bt_splitpage (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no);
277 uint bt_cleanpage(BtDb *bt, BtPage page, uint amt, uint slot);
278 BTERR bt_mergeleft (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no, uint lvl);
281 extern BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolsize, uint segsize, uint hashsize);
282 void bt_mgrclose (BtMgr *mgr);
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++;
365 int sys_futex(void *addr1, int op, int val1, struct timespec *timeout, void *addr2, int val3)
367 return syscall(SYS_futex, addr1, op, val1, timeout, addr2, val3);
370 // wait until write lock mode is clear
371 // and add 1 to the share count
373 void bt_spinreadlock(BtLatch *latch, int private)
378 private = FUTEX_PRIVATE_FLAG;
381 // obtain latch mutex
382 if( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex ) {
387 // wait for writers to clear
388 // increment read waiters and wait
390 if( latch->write || latch->writewait ) {
391 __sync_fetch_and_add ((uint *)latch, PendRd);
392 prev = __sync_fetch_and_and ((uint *)latch, ~Mutex) & ~Mutex;
393 sys_futex( (uint *)latch, FUTEX_WAIT_BITSET | private, prev, NULL, NULL, QueRd );
394 __sync_fetch_and_sub ((uint *)latch, PendRd);
398 // increment reader lock count
399 // and release latch mutex
401 __sync_fetch_and_add ((uint *)latch, Share);
402 __sync_fetch_and_and ((uint *)latch, ~Mutex);
407 // wait for other read and write latches to relinquish
409 void bt_spinwritelock(BtLatch *latch, int private)
414 private = FUTEX_PRIVATE_FLAG;
417 // obtain latch mutex
418 if( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex ) {
423 // wait for write and reader count to clear
425 if( latch->write || latch->share ) {
426 __sync_fetch_and_add ((uint *)latch, PendWr);
427 prev = __sync_fetch_and_and ((uint *)latch, ~Mutex) & ~Mutex;
428 sys_futex( (uint *)latch, FUTEX_WAIT_BITSET | private, prev, NULL, NULL, QueWr );
429 __sync_fetch_and_sub ((uint *)latch, PendWr);
434 // release latch mutex
436 __sync_fetch_and_or ((uint *)latch, Write);
437 __sync_fetch_and_and ((uint *)latch, ~Mutex);
442 // try to obtain write lock
444 // return 1 if obtained,
447 int bt_spinwritetry(BtLatch *latch)
452 // abandon request if not taken
454 if( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex )
457 // see if write mode is available
459 if( !latch->write && !latch->share ) {
460 __sync_fetch_and_or ((uint *)latch, Write);
465 // release latch mutex
467 __sync_fetch_and_and ((uint *)latch, ~Mutex);
473 void bt_spinreleasewrite(BtLatch *latch, int private)
476 private = FUTEX_PRIVATE_FLAG;
478 // obtain latch mutex
480 while( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex )
483 __sync_fetch_and_and ((uint *)latch, ~Write);
487 if( latch->writewait )
488 if( sys_futex( (uint *)latch, FUTEX_WAKE_BITSET | private, 1, NULL, NULL, QueWr ) )
491 if( latch->readwait )
492 sys_futex( (uint *)latch, FUTEX_WAKE_BITSET | private, INT_MAX, NULL, NULL, QueRd );
494 // release latch mutex
497 __sync_fetch_and_and ((uint *)latch, ~Mutex);
500 // decrement reader count
502 void bt_spinreleaseread(BtLatch *latch, int private)
505 private = FUTEX_PRIVATE_FLAG;
507 // obtain latch mutex
509 while( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex )
512 __sync_fetch_and_sub ((uint *)latch, Share);
514 // wake waiting writers
516 if( !latch->share && latch->writewait )
517 sys_futex( (uint *)latch, FUTEX_WAKE_BITSET | private, 1, NULL, NULL, QueWr );
519 // release latch mutex
521 __sync_fetch_and_and ((uint *)latch, ~Mutex);
524 // link latch table entry into latch hash table
526 void bt_latchlink (BtDb *bt, ushort hashidx, ushort victim, uid page_no)
528 BtLatchSet *set = bt->mgr->latchsets + victim;
530 if( set->next = bt->mgr->latchmgr->table[hashidx].slot )
531 bt->mgr->latchsets[set->next].prev = victim;
533 bt->mgr->latchmgr->table[hashidx].slot = victim;
534 set->page_no = page_no;
541 void bt_unpinlatch (BtLatchSet *set)
544 __sync_fetch_and_add(&set->pin, -1);
546 _InterlockedDecrement16 (&set->pin);
550 // find existing latchset or inspire new one
551 // return with latchset pinned
553 BtLatchSet *bt_pinlatch (BtDb *bt, uid page_no)
555 ushort hashidx = page_no % bt->mgr->latchmgr->latchhash;
556 ushort slot, avail = 0, victim, idx;
559 // obtain read lock on hash table entry
561 bt_spinreadlock(bt->mgr->latchmgr->table[hashidx].latch, 0);
563 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
565 set = bt->mgr->latchsets + slot;
566 if( page_no == set->page_no )
568 } while( slot = set->next );
572 __sync_fetch_and_add(&set->pin, 1);
574 _InterlockedIncrement16 (&set->pin);
578 bt_spinreleaseread (bt->mgr->latchmgr->table[hashidx].latch, 0);
583 // try again, this time with write lock
585 bt_spinwritelock(bt->mgr->latchmgr->table[hashidx].latch, 0);
587 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
589 set = bt->mgr->latchsets + slot;
590 if( page_no == set->page_no )
592 if( !set->pin && !avail )
594 } while( slot = set->next );
596 // found our entry, or take over an unpinned one
598 if( slot || (slot = avail) ) {
599 set = bt->mgr->latchsets + slot;
601 __sync_fetch_and_add(&set->pin, 1);
603 _InterlockedIncrement16 (&set->pin);
605 set->page_no = page_no;
606 bt_spinreleasewrite(bt->mgr->latchmgr->table[hashidx].latch, 0);
610 // see if there are any unused entries
612 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, 1) + 1;
614 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchdeployed);
617 if( victim < bt->mgr->latchmgr->latchtotal ) {
618 set = bt->mgr->latchsets + victim;
620 __sync_fetch_and_add(&set->pin, 1);
622 _InterlockedIncrement16 (&set->pin);
624 bt_latchlink (bt, hashidx, victim, page_no);
625 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch, 0);
630 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, -1);
632 victim = _InterlockedDecrement16 (&bt->mgr->latchmgr->latchdeployed);
634 // find and reuse previous lock entry
638 victim = __sync_fetch_and_add(&bt->mgr->latchmgr->latchvictim, 1);
640 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchvictim) - 1;
642 // we don't use slot zero
644 if( victim %= bt->mgr->latchmgr->latchtotal )
645 set = bt->mgr->latchsets + victim;
649 // take control of our slot
650 // from other threads
652 if( set->pin || !bt_spinwritetry (set->busy) )
657 // try to get write lock on hash chain
658 // skip entry if not obtained
659 // or has outstanding locks
661 if( !bt_spinwritetry (bt->mgr->latchmgr->table[idx].latch) ) {
662 bt_spinreleasewrite (set->busy, 0);
667 bt_spinreleasewrite (set->busy, 0);
668 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch, 0);
672 // unlink our available victim from its hash chain
675 bt->mgr->latchsets[set->prev].next = set->next;
677 bt->mgr->latchmgr->table[idx].slot = set->next;
680 bt->mgr->latchsets[set->next].prev = set->prev;
682 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch, 0);
684 __sync_fetch_and_add(&set->pin, 1);
686 _InterlockedIncrement16 (&set->pin);
688 bt_latchlink (bt, hashidx, victim, page_no);
689 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch, 0);
690 bt_spinreleasewrite (set->busy, 0);
695 void bt_mgrclose (BtMgr *mgr)
700 // release mapped pages
701 // note that slot zero is never used
703 for( slot = 1; slot < mgr->poolmax; slot++ ) {
704 pool = mgr->pool + slot;
707 munmap (pool->map, (mgr->poolmask+1) << mgr->page_bits);
710 FlushViewOfFile(pool->map, 0);
711 UnmapViewOfFile(pool->map);
712 CloseHandle(pool->hmap);
718 munmap (mgr->latchsets, mgr->latchmgr->nlatchpage * mgr->page_size);
719 munmap (mgr->latchmgr, mgr->page_size);
721 FlushViewOfFile(mgr->latchmgr, 0);
722 UnmapViewOfFile(mgr->latchmgr);
723 CloseHandle(mgr->halloc);
732 FlushFileBuffers(mgr->idx);
733 CloseHandle(mgr->idx);
734 GlobalFree (mgr->pool);
735 GlobalFree (mgr->hash);
736 GlobalFree (mgr->latch);
741 // close and release memory
743 void bt_close (BtDb *bt)
750 VirtualFree (bt->mem, 0, MEM_RELEASE);
755 // open/create new btree buffer manager
757 // call with file_name, BT_openmode, bits in page size (e.g. 16),
758 // size of mapped page pool (e.g. 8192)
760 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
762 uint lvl, attr, cacheblk, last, slot, idx;
763 uint nlatchpage, latchhash;
764 BtLatchMgr *latchmgr;
772 SYSTEM_INFO sysinfo[1];
775 // determine sanity of page size and buffer pool
777 if( bits > BT_maxbits )
779 else if( bits < BT_minbits )
783 return NULL; // must have buffer pool
786 mgr = calloc (1, sizeof(BtMgr));
788 mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
791 return free(mgr), NULL;
793 cacheblk = 4096; // minimum mmap segment size for unix
796 mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
797 attr = FILE_ATTRIBUTE_NORMAL;
798 mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
800 if( mgr->idx == INVALID_HANDLE_VALUE )
801 return GlobalFree(mgr), NULL;
803 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
804 GetSystemInfo(sysinfo);
805 cacheblk = sysinfo->dwAllocationGranularity;
809 latchmgr = malloc (BT_maxpage);
812 // read minimum page size to get root info
814 if( size = lseek (mgr->idx, 0L, 2) ) {
815 if( pread(mgr->idx, latchmgr, BT_minpage, 0) == BT_minpage )
816 bits = latchmgr->alloc->bits;
818 return free(mgr), free(latchmgr), NULL;
819 } else if( mode == BT_ro )
820 return free(latchmgr), bt_mgrclose (mgr), NULL;
822 latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
823 size = GetFileSize(mgr->idx, amt);
826 if( !ReadFile(mgr->idx, (char *)latchmgr, BT_minpage, amt, NULL) )
827 return bt_mgrclose (mgr), NULL;
828 bits = latchmgr->alloc->bits;
829 } else if( mode == BT_ro )
830 return bt_mgrclose (mgr), NULL;
833 mgr->page_size = 1 << bits;
834 mgr->page_bits = bits;
836 mgr->poolmax = poolmax;
839 if( cacheblk < mgr->page_size )
840 cacheblk = mgr->page_size;
842 // mask for partial memmaps
844 mgr->poolmask = (cacheblk >> bits) - 1;
846 // see if requested size of pages per memmap is greater
848 if( (1 << segsize) > mgr->poolmask )
849 mgr->poolmask = (1 << segsize) - 1;
853 while( (1 << mgr->seg_bits) <= mgr->poolmask )
856 mgr->hashsize = hashsize;
859 mgr->pool = calloc (poolmax, sizeof(BtPool));
860 mgr->hash = calloc (hashsize, sizeof(ushort));
861 mgr->latch = calloc (hashsize, sizeof(BtLatch));
863 mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * sizeof(BtPool));
864 mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
865 mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtLatch));
871 // initialize an empty b-tree with latch page, root page, page of leaves
872 // and page(s) of latches
874 memset (latchmgr, 0, 1 << bits);
875 nlatchpage = BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1;
876 bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
877 latchmgr->alloc->bits = mgr->page_bits;
879 latchmgr->nlatchpage = nlatchpage;
880 latchmgr->latchtotal = nlatchpage * (mgr->page_size / sizeof(BtLatchSet));
882 // initialize latch manager
884 latchhash = (mgr->page_size - sizeof(BtLatchMgr)) / sizeof(BtHashEntry);
886 // size of hash table = total number of latchsets
888 if( latchhash > latchmgr->latchtotal )
889 latchhash = latchmgr->latchtotal;
891 latchmgr->latchhash = latchhash;
894 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
895 return bt_mgrclose (mgr), NULL;
897 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
898 return bt_mgrclose (mgr), NULL;
900 if( *amt < mgr->page_size )
901 return bt_mgrclose (mgr), NULL;
904 memset (latchmgr, 0, 1 << bits);
905 latchmgr->alloc->bits = mgr->page_bits;
907 for( lvl=MIN_lvl; lvl--; ) {
908 slotptr(latchmgr->alloc, 1)->off = mgr->page_size - 3;
909 bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
910 key = keyptr(latchmgr->alloc, 1);
911 key->len = 2; // create stopper key
914 latchmgr->alloc->min = mgr->page_size - 3;
915 latchmgr->alloc->lvl = lvl;
916 latchmgr->alloc->cnt = 1;
917 latchmgr->alloc->act = 1;
919 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
920 return bt_mgrclose (mgr), NULL;
922 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
923 return bt_mgrclose (mgr), NULL;
925 if( *amt < mgr->page_size )
926 return bt_mgrclose (mgr), NULL;
930 // clear out latch manager locks
931 // and rest of pages to round out segment
933 memset(latchmgr, 0, mgr->page_size);
936 while( last <= ((MIN_lvl + 1 + nlatchpage) | mgr->poolmask) ) {
938 pwrite(mgr->idx, latchmgr, mgr->page_size, last << mgr->page_bits);
940 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
941 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
942 return bt_mgrclose (mgr), NULL;
943 if( *amt < mgr->page_size )
944 return bt_mgrclose (mgr), NULL;
951 flag = PROT_READ | PROT_WRITE;
952 mgr->latchmgr = mmap (0, mgr->page_size, flag, MAP_SHARED, mgr->idx, ALLOC_page * mgr->page_size);
953 if( mgr->latchmgr == MAP_FAILED )
954 return bt_mgrclose (mgr), NULL;
955 mgr->latchsets = (BtLatchSet *)mmap (0, mgr->latchmgr->nlatchpage * mgr->page_size, flag, MAP_SHARED, mgr->idx, LATCH_page * mgr->page_size);
956 if( mgr->latchsets == MAP_FAILED )
957 return bt_mgrclose (mgr), NULL;
959 flag = PAGE_READWRITE;
960 mgr->halloc = CreateFileMapping(mgr->idx, NULL, flag, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size, NULL);
962 return bt_mgrclose (mgr), NULL;
964 flag = FILE_MAP_WRITE;
965 mgr->latchmgr = MapViewOfFile(mgr->halloc, flag, 0, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size);
967 return GetLastError(), bt_mgrclose (mgr), NULL;
969 mgr->latchsets = (void *)((char *)mgr->latchmgr + LATCH_page * mgr->page_size);
975 VirtualFree (latchmgr, 0, MEM_RELEASE);
980 // open BTree access method
981 // based on buffer manager
983 BtDb *bt_open (BtMgr *mgr)
985 BtDb *bt = malloc (sizeof(*bt));
987 memset (bt, 0, sizeof(*bt));
990 bt->mem = malloc (3 *mgr->page_size);
992 bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
994 bt->frame = (BtPage)bt->mem;
995 bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
996 bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
998 memset(bt->zero, 0, mgr->page_size);
1002 // compare two keys, returning > 0, = 0, or < 0
1003 // as the comparison value
1005 int keycmp (BtKey key1, unsigned char *key2, uint len2)
1007 uint len1 = key1->len;
1010 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
1023 // find segment in pool
1024 // must be called with hashslot idx locked
1025 // return NULL if not there
1026 // otherwise return node
1028 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
1033 // compute start of hash chain in pool
1035 if( slot = bt->mgr->hash[idx] )
1036 pool = bt->mgr->pool + slot;
1040 page_no &= ~bt->mgr->poolmask;
1042 while( pool->basepage != page_no )
1043 if( pool = pool->hashnext )
1051 // add segment to hash table
1053 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
1058 pool->hashprev = pool->hashnext = NULL;
1059 pool->basepage = page_no & ~bt->mgr->poolmask;
1062 if( slot = bt->mgr->hash[idx] ) {
1063 node = bt->mgr->pool + slot;
1064 pool->hashnext = node;
1065 node->hashprev = pool;
1068 bt->mgr->hash[idx] = pool->slot;
1071 // find best segment to evict from buffer pool
1073 BtPool *bt_findlru (BtDb *bt, uint hashslot)
1075 unsigned long long int target = ~0LL;
1076 BtPool *pool = NULL, *node;
1081 node = bt->mgr->pool + hashslot;
1083 // scan pool entries under hash table slot
1088 if( node->lru > target )
1092 } while( node = node->hashnext );
1097 // map new buffer pool segment to virtual memory
1099 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
1101 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
1102 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
1106 flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
1107 pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED, bt->mgr->idx, off);
1108 if( pool->map == MAP_FAILED )
1109 return bt->err = BTERR_map;
1111 flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
1112 pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
1114 return bt->err = BTERR_map;
1116 flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
1117 pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1119 return bt->err = BTERR_map;
1124 // calculate page within pool
1126 BtPage bt_page (BtDb *bt, BtPool *pool, uid page_no)
1128 uint subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1131 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1137 void bt_unpinpool (BtPool *pool)
1140 __sync_fetch_and_add(&pool->pin, -1);
1142 _InterlockedDecrement16 (&pool->pin);
1146 // find or place requested page in segment-pool
1147 // return pool table entry, incrementing pin
1149 BtPool *bt_pinpool(BtDb *bt, uid page_no)
1151 BtPool *pool, *node, *next;
1152 uint slot, idx, victim;
1155 // lock hash table chain
1157 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1158 bt_spinreadlock (&bt->mgr->latch[idx], 1);
1160 // look up in hash table
1162 if( pool = bt_findpool(bt, page_no, idx) ) {
1164 __sync_fetch_and_add(&pool->pin, 1);
1166 _InterlockedIncrement16 (&pool->pin);
1168 bt_spinreleaseread (&bt->mgr->latch[idx], 1);
1173 // upgrade to write lock
1175 bt_spinreleaseread (&bt->mgr->latch[idx], 1);
1176 bt_spinwritelock (&bt->mgr->latch[idx], 1);
1178 // try to find page in pool with write lock
1180 if( pool = bt_findpool(bt, page_no, idx) ) {
1182 __sync_fetch_and_add(&pool->pin, 1);
1184 _InterlockedIncrement16 (&pool->pin);
1186 bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
1191 // allocate a new pool node
1192 // and add to hash table
1195 slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
1197 slot = _InterlockedIncrement16 (&bt->mgr->poolcnt) - 1;
1200 if( ++slot < bt->mgr->poolmax ) {
1201 pool = bt->mgr->pool + slot;
1204 if( bt_mapsegment(bt, pool, page_no) )
1207 bt_linkhash(bt, pool, page_no, idx);
1209 __sync_fetch_and_add(&pool->pin, 1);
1211 _InterlockedIncrement16 (&pool->pin);
1213 bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
1217 // pool table is full
1218 // find best pool entry to evict
1221 __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
1223 _InterlockedDecrement16 (&bt->mgr->poolcnt);
1228 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
1230 victim = _InterlockedIncrement16 (&bt->mgr->evicted) - 1;
1232 victim %= bt->mgr->hashsize;
1234 // try to get write lock
1235 // skip entry if not obtained
1237 if( !bt_spinwritetry (&bt->mgr->latch[victim]) )
1240 // if cache entry is empty
1241 // or no slots are unpinned
1244 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
1245 bt_spinreleasewrite (&bt->mgr->latch[victim], 1);
1249 // unlink victim pool node from hash table
1251 if( node = pool->hashprev )
1252 node->hashnext = pool->hashnext;
1253 else if( node = pool->hashnext )
1254 bt->mgr->hash[victim] = node->slot;
1256 bt->mgr->hash[victim] = 0;
1258 if( node = pool->hashnext )
1259 node->hashprev = pool->hashprev;
1261 bt_spinreleasewrite (&bt->mgr->latch[victim], 1);
1263 // remove old file mapping
1265 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1267 FlushViewOfFile(pool->map, 0);
1268 UnmapViewOfFile(pool->map);
1269 CloseHandle(pool->hmap);
1273 // create new pool mapping
1274 // and link into hash table
1276 if( bt_mapsegment(bt, pool, page_no) )
1279 bt_linkhash(bt, pool, page_no, idx);
1281 __sync_fetch_and_add(&pool->pin, 1);
1283 _InterlockedIncrement16 (&pool->pin);
1285 bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
1290 // place write, read, or parent lock on requested page_no.
1291 // pin to buffer pool and return latchset pointer
1293 void bt_lockpage(BtLock mode, BtLatchSet *set)
1297 bt_spinreadlock (set->readwr, 0);
1300 bt_spinwritelock (set->readwr, 0);
1303 bt_spinreadlock (set->access, 0);
1306 bt_spinwritelock (set->access, 0);
1309 bt_spinwritelock (set->parent, 0);
1314 // remove write, read, or parent lock on requested page_no.
1316 void bt_unlockpage(BtLock mode, BtLatchSet *set)
1320 bt_spinreleaseread (set->readwr, 0);
1323 bt_spinreleasewrite (set->readwr, 0);
1326 bt_spinreleaseread (set->access, 0);
1329 bt_spinreleasewrite (set->access, 0);
1332 bt_spinreleasewrite (set->parent, 0);
1337 // allocate a new page and write page into it
1339 uid bt_newpage(BtDb *bt, BtPage page)
1347 // lock allocation page
1349 bt_spinwritelock(bt->mgr->latchmgr->lock, 0);
1351 // use empty chain first
1352 // else allocate empty page
1354 if( new_page = bt_getid(bt->mgr->latchmgr->alloc[1].right) ) {
1355 if( pool = bt_pinpool (bt, new_page) )
1356 pmap = bt_page (bt, pool, new_page);
1359 bt_putid(bt->mgr->latchmgr->alloc[1].right, bt_getid(pmap->right));
1360 bt_unpinpool (pool);
1363 new_page = bt_getid(bt->mgr->latchmgr->alloc->right);
1364 bt_putid(bt->mgr->latchmgr->alloc->right, new_page+1);
1368 // if writing first page of pool block, zero last page in the block
1370 if ( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1372 // use zero buffer to write zeros
1373 if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1374 return bt->err = BTERR_wrt, 0;
1377 // unlock allocation latch
1379 bt_spinreleasewrite(bt->mgr->latchmgr->lock, 0);
1381 if ( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1382 return bt->err = BTERR_wrt, 0;
1385 // unlock allocation latch
1387 bt_spinreleasewrite(bt->mgr->latchmgr->lock, 0);
1389 // bring new page into pool and copy page.
1390 // this will extend the file into the new pages.
1391 // NB -- no latch required
1393 if( pool = bt_pinpool (bt, new_page) )
1394 pmap = bt_page (bt, pool, new_page);
1398 memcpy(pmap, page, bt->mgr->page_size);
1399 bt_unpinpool (pool);
1404 // find slot in page for given key at a given level
1406 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1408 uint diff, higher = bt->page->cnt, low = 1, slot;
1412 // make stopper key an infinite fence value
1413 // by setting the good flag
1415 if( bt_getid (bt->page->right) )
1420 // low is the next candidate.
1421 // loop ends when they meet
1423 // if good, higher is already
1424 // tested as .ge. the given key.
1426 while( diff = higher - low ) {
1427 slot = low + ( diff >> 1 );
1428 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1431 higher = slot, good++;
1434 // return zero if key is on right link page
1436 return good ? higher : 0;
1439 // find and load page at given level for given key
1440 // leave page rd or wr locked as requested
1442 uint bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, BtLock lock)
1444 uid page_no = ROOT_page, prevpage = 0;
1445 BtLatchSet *set, *prevset;
1446 uint drill = 0xff, slot;
1447 uint mode, prevmode;
1451 // start at root of btree and drill down
1454 // determine lock mode of drill level
1455 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1457 // obtain latch set for this page
1459 bt->set = bt_pinlatch (bt, page_no);
1460 bt->page_no = page_no;
1462 // pin page contents
1464 if( bt->pool = bt_pinpool (bt, page_no) )
1465 bt->page = bt_page (bt, bt->pool, page_no);
1469 // obtain access lock using lock chaining with Access mode
1471 if( page_no > ROOT_page )
1472 bt_lockpage(BtLockAccess, bt->set);
1474 // now unlock and unpin our (possibly foster) parent
1477 bt_unlockpage(prevmode, prevset);
1478 bt_unpinlatch (prevset);
1479 bt_unpinpool (prevpool);
1483 // obtain read lock using lock chaining
1485 bt_lockpage(mode, bt->set);
1487 if( page_no > ROOT_page )
1488 bt_unlockpage(BtLockAccess, bt->set);
1490 // re-read and re-lock root after determining actual level of root
1492 if( page_no == ROOT_page )
1493 if( bt->page->lvl != drill) {
1494 drill = bt->page->lvl;
1496 if( lock == BtLockWrite && drill == lvl ) {
1497 bt_unlockpage(mode, bt->set);
1498 bt_unpinlatch (bt->set);
1499 bt_unpinpool (bt->pool);
1504 // find key on page at this level
1505 // and either descend to requested level
1506 // or return key slot
1508 if( slot = bt_findslot (bt, key, len) ) {
1509 // is this slot < foster child area
1510 // on the requested level?
1512 // if so, return actual slot even if dead
1514 if( slot <= bt->page->cnt - bt->page->foster )
1516 return bt->foster = foster, slot;
1518 // find next active slot
1519 // note: foster children are never dead
1521 while( slotptr(bt->page, slot)->dead )
1522 if( slot++ < bt->page->cnt )
1525 // we are waiting for fence key posting
1526 page_no = bt_getid(bt->page->right);
1530 // is this slot < foster child area
1531 // if so, drill to next level
1533 if( slot <= bt->page->cnt - bt->page->foster )
1534 foster = 0, drill--;
1538 // continue right onto foster child
1539 // or down to next level.
1541 page_no = bt_getid(slotptr(bt->page, slot)->id);
1543 // or slide right into next page
1546 page_no = bt_getid(bt->page->right);
1551 prevpage = bt->page_no;
1552 prevpool = bt->pool;
1558 // return error on end of chain
1560 bt->err = BTERR_struct;
1561 return 0; // return error
1564 // remove empty page from the B-tree
1565 // by pulling our right node left over ourselves
1567 // call with bt->page, etc, set to page's locked parent
1568 // returns with page locked.
1570 BTERR bt_mergeright (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no, uint lvl, uint slot)
1572 BtLatchSet *rset, *pset, *rpset;
1573 BtPool *rpool, *ppool, *rppool;
1574 BtPage rpage, ppage, rppage;
1575 uid right, parent, rparent;
1579 // cache node's parent page
1581 parent = bt->page_no;
1586 // lock and map our right page
1587 // note that it cannot be our foster child
1588 // since the our node is empty
1589 // and it cannot be NULL because of the stopper
1590 // in the last right page
1592 bt_lockpage (BtLockWrite, set);
1594 // if we aren't dead yet
1599 if( right = bt_getid (page->right) )
1600 if( rpool = bt_pinpool (bt, right) )
1601 rpage = bt_page (bt, rpool, right);
1605 return bt->err = BTERR_struct;
1607 rset = bt_pinlatch (bt, right);
1609 // find our right neighbor
1611 if( ppage->act > 1 ) {
1612 for( idx = slot; idx++ < ppage->cnt; )
1613 if( !slotptr(ppage, idx)->dead )
1616 if( idx > ppage->cnt )
1617 return bt->err = BTERR_struct;
1619 // redirect right neighbor in parent to left node
1621 bt_putid(slotptr(ppage,idx)->id, page_no);
1624 // if parent has only our deleted page, e.g. no right neighbor
1625 // prepare to merge parent itself
1627 if( ppage->act == 1 ) {
1628 if( rparent = bt_getid (ppage->right) )
1629 if( rppool = bt_pinpool (bt, rparent) )
1630 rppage = bt_page (bt, rppool, rparent);
1634 return bt->err = BTERR_struct;
1636 rpset = bt_pinlatch (bt, rparent);
1637 bt_lockpage (BtLockWrite, rpset);
1639 // find our right neighbor on right parent page
1641 for( idx = 0; idx++ < rppage->cnt; )
1642 if( !slotptr(rppage, idx)->dead ) {
1643 bt_putid (slotptr(rppage, idx)->id, page_no);
1647 if( idx > rppage->cnt )
1648 return bt->err = BTERR_struct;
1651 // now that there are no more pointers to our right node
1652 // we can wait for delete lock on it
1654 bt_lockpage(BtLockDelete, rset);
1655 bt_lockpage(BtLockWrite, rset);
1657 // pull contents of right page into our empty page
1659 memcpy (page, rpage, bt->mgr->page_size);
1661 // ready to release right parent lock
1662 // now that we have a new page in place
1664 if( ppage->act == 1 ) {
1665 bt_unlockpage (BtLockWrite, rpset);
1666 bt_unpinlatch (rpset);
1667 bt_unpinpool (rppool);
1670 // add killed right block to free chain
1673 bt_spinwritelock(bt->mgr->latchmgr->lock, 0);
1675 // store free chain in allocation page second right
1677 bt_putid(rpage->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1678 bt_putid(bt->mgr->latchmgr->alloc[1].right, right);
1680 // unlock latch mgr and right page
1682 bt_unlockpage(BtLockDelete, rset);
1683 bt_unlockpage(BtLockWrite, rset);
1684 bt_unpinlatch (rset);
1685 bt_unpinpool (rpool);
1687 bt_spinreleasewrite(bt->mgr->latchmgr->lock, 0);
1689 // delete our obsolete fence key from our parent
1691 slotptr(ppage, slot)->dead = 1;
1694 // if our parent now empty
1695 // remove it from the tree
1697 if( ppage->act-- == 1 )
1698 if( bt_mergeleft (bt, ppage, ppool, pset, parent, lvl+1) )
1702 bt_unlockpage (BtLockWrite, pset);
1703 bt_unpinlatch (pset);
1704 bt_unpinpool (ppool);
1710 // remove empty page from the B-tree
1711 // try merging left first. If no left
1712 // sibling, then merge right.
1714 // call with page loaded and locked,
1715 // return with page locked.
1717 BTERR bt_mergeleft (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no, uint lvl)
1719 unsigned char fencekey[256], postkey[256];
1720 uint slot, idx, postfence = 0;
1721 BtLatchSet *lset, *pset;
1722 BtPool *lpool, *ppool;
1723 BtPage lpage, ppage;
1727 ptr = keyptr(page, page->cnt);
1728 memcpy(fencekey, ptr, ptr->len + 1);
1729 bt_unlockpage (BtLockWrite, set);
1731 // load and lock our parent
1734 if( !(slot = bt_loadpage (bt, fencekey+1, *fencekey, lvl+1, BtLockWrite)) )
1737 parent = bt->page_no;
1742 // wait until we are not a foster child
1745 bt_unlockpage (BtLockWrite, pset);
1746 bt_unpinlatch (pset);
1747 bt_unpinpool (ppool);
1756 // find our left neighbor in our parent page
1758 for( idx = slot; --idx; )
1759 if( !slotptr(ppage, idx)->dead )
1762 // if no left neighbor, do right merge
1765 return bt_mergeright (bt, page, pool, set, page_no, lvl, slot);
1767 // lock and map our left neighbor's page
1769 left = bt_getid (slotptr(ppage, idx)->id);
1771 if( lpool = bt_pinpool (bt, left) )
1772 lpage = bt_page (bt, lpool, left);
1776 lset = bt_pinlatch (bt, left);
1777 bt_lockpage(BtLockWrite, lset);
1779 // wait until foster sibling is in our parent
1781 if( bt_getid (lpage->right) != page_no ) {
1782 bt_unlockpage (BtLockWrite, pset);
1783 bt_unpinlatch (pset);
1784 bt_unpinpool (ppool);
1785 bt_unlockpage (BtLockWrite, lset);
1786 bt_unpinlatch (lset);
1787 bt_unpinpool (lpool);
1796 // since our page will have no more pointers to it,
1797 // obtain Delete lock and wait for write locks to clear
1799 bt_lockpage(BtLockDelete, set);
1800 bt_lockpage(BtLockWrite, set);
1802 // if we aren't dead yet,
1803 // get ready for exit
1806 bt_unlockpage(BtLockDelete, set);
1807 bt_unlockpage(BtLockWrite, lset);
1808 bt_unpinlatch (lset);
1809 bt_unpinpool (lpool);
1813 // are we are the fence key for our parent?
1814 // if so, grab our old fence key
1816 if( postfence = slot == ppage->cnt ) {
1817 ptr = keyptr (ppage, ppage->cnt);
1818 memcpy(fencekey, ptr, ptr->len + 1);
1819 memset(slotptr(ppage, ppage->cnt), 0, sizeof(BtSlot));
1821 // clear out other dead slots
1823 while( --ppage->cnt )
1824 if( slotptr(ppage, ppage->cnt)->dead )
1825 memset(slotptr(ppage, ppage->cnt), 0, sizeof(BtSlot));
1829 ptr = keyptr (ppage, ppage->cnt);
1830 memcpy(postkey, ptr, ptr->len + 1);
1832 slotptr(ppage,slot)->dead = 1;
1837 // push our right neighbor pointer to our left
1839 memcpy (lpage->right, page->right, BtId);
1841 // add ourselves to free chain
1844 bt_spinwritelock(bt->mgr->latchmgr->lock, 0);
1846 // store free chain in allocation page second right
1847 bt_putid(page->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1848 bt_putid(bt->mgr->latchmgr->alloc[1].right, page_no);
1850 // unlock latch mgr and pages
1852 bt_spinreleasewrite(bt->mgr->latchmgr->lock, 0);
1853 bt_unlockpage(BtLockWrite, lset);
1854 bt_unpinlatch (lset);
1855 bt_unpinpool (lpool);
1857 // release our node's delete lock
1859 bt_unlockpage(BtLockDelete, set);
1862 bt_unlockpage (BtLockWrite, pset);
1863 bt_unpinpool (ppool);
1865 // do we need to post parent's fence key in its parent?
1867 if( !postfence || parent == ROOT_page ) {
1868 bt_unpinlatch (pset);
1873 // interlock parent fence post
1875 bt_lockpage (BtLockParent, pset);
1877 // load parent's parent page
1879 if( !(slot = bt_loadpage (bt, fencekey+1, *fencekey, lvl+2, BtLockWrite)) )
1882 if( !(slot = bt_cleanpage (bt, bt->page, *fencekey, slot)) )
1883 if( bt_splitpage (bt, bt->page, bt->pool, bt->set, bt->page_no) )
1890 page->min -= *postkey + 1;
1891 ((unsigned char *)page)[page->min] = *postkey;
1892 memcpy ((unsigned char *)page + page->min +1, postkey + 1, *postkey );
1893 slotptr(page, slot)->off = page->min;
1895 bt_unlockpage (BtLockParent, pset);
1896 bt_unpinlatch (pset);
1898 bt_unlockpage (BtLockWrite, bt->set);
1899 bt_unpinlatch (bt->set);
1900 bt_unpinpool (bt->pool);
1906 // find and delete key on page by marking delete flag bit
1907 // if page becomes empty, delete it from the btree
1909 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len)
1918 if( !(slot = bt_loadpage (bt, key, len, 0, BtLockWrite)) )
1921 page_no = bt->page_no;
1926 // if key is found delete it, otherwise ignore request
1928 ptr = keyptr(page, slot);
1930 if( bt->found = !keycmp (ptr, key, len) )
1931 if( bt->found = slotptr(page, slot)->dead == 0 ) {
1932 slotptr(page,slot)->dead = 1;
1933 if( slot < page->cnt )
1936 if( bt_mergeleft (bt, page, pool, set, page_no, 0) )
1940 bt_unlockpage(BtLockWrite, set);
1941 bt_unpinlatch (set);
1942 bt_unpinpool (pool);
1946 // find key in leaf level and return row-id
1948 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1954 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1955 ptr = keyptr(bt->page, slot);
1959 // if key exists, return row-id
1960 // otherwise return 0
1962 if( slot <= bt->page->cnt && !keycmp (ptr, key, len) )
1963 id = bt_getid(slotptr(bt->page,slot)->id);
1967 bt_unlockpage (BtLockRead, bt->set);
1968 bt_unpinlatch (bt->set);
1969 bt_unpinpool (bt->pool);
1973 // check page for space available,
1974 // clean if necessary and return
1975 // 0 - page needs splitting
1976 // >0 new slot value
1978 uint bt_cleanpage(BtDb *bt, BtPage page, uint amt, uint slot)
1980 uint nxt = bt->mgr->page_size;
1981 uint cnt = 0, idx = 0;
1982 uint max = page->cnt;
1986 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1989 // skip cleanup if nothing to reclaim
1994 memcpy (bt->frame, page, bt->mgr->page_size);
1996 // skip page info and set rest of page to zero
1998 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
2002 // try cleaning up page first
2004 // always leave fence key in the array
2005 // otherwise, remove deleted key
2007 // note: foster children are never dead
2009 while( cnt++ < max ) {
2012 if( cnt < max && slotptr(bt->frame,cnt)->dead )
2017 key = keyptr(bt->frame, cnt);
2018 nxt -= key->len + 1;
2019 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2022 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
2023 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
2025 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2026 slotptr(page, idx)->off = nxt;
2032 // see if page has enough space now, or does it need splitting?
2034 if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
2040 // add key to current page
2041 // page must already be writelocked
2043 void bt_addkeytopage (BtDb *bt, BtPage page, uint slot, unsigned char *key, uint len, uid id, uint tod)
2047 // find next available dead slot and copy key onto page
2048 // note that foster children on the page are never dead
2050 // look for next hole, but stay back from the fence key
2052 for( idx = slot; idx < page->cnt; idx++ )
2053 if( slotptr(page, idx)->dead )
2056 if( idx == page->cnt )
2061 // now insert key into array before slot
2064 *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
2066 page->min -= len + 1;
2067 ((unsigned char *)page)[page->min] = len;
2068 memcpy ((unsigned char *)page + page->min +1, key, len );
2070 bt_putid(slotptr(page,slot)->id, id);
2071 slotptr(page, slot)->off = page->min;
2072 slotptr(page, slot)->tod = tod;
2073 slotptr(page, slot)->dead = 0;
2076 // split the root and raise the height of the btree
2077 // call with current page locked and page no of foster child
2078 // return with current page (root) unlocked
2080 BTERR bt_splitroot(BtDb *bt, uid right)
2082 uint nxt = bt->mgr->page_size;
2083 unsigned char fencekey[256];
2084 BtPage root = bt->page;
2088 // Obtain an empty page to use, and copy the left page
2089 // contents into it from the root. Strip foster child key.
2090 // (it's the stopper key)
2092 memset (slotptr(root, root->cnt), 0, sizeof(BtSlot));
2098 // Save left fence key.
2100 key = keyptr(root, root->cnt);
2101 memcpy (fencekey, key, key->len + 1);
2103 // copy the lower keys into a new left page
2105 if( !(new_page = bt_newpage(bt, root)) )
2108 // preserve the page info at the bottom
2109 // and set rest of the root to zero
2111 memset (root+1, 0, bt->mgr->page_size - sizeof(*root));
2113 // insert left fence key on empty newroot page
2115 nxt -= *fencekey + 1;
2116 memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
2117 bt_putid(slotptr(root, 1)->id, new_page);
2118 slotptr(root, 1)->off = nxt;
2120 // insert stopper key on newroot page
2121 // and increase the root height
2127 memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
2128 bt_putid(slotptr(root, 2)->id, right);
2129 slotptr(root, 2)->off = nxt;
2131 bt_putid(root->right, 0);
2132 root->min = nxt; // reset lowest used offset and key count
2137 // release and unpin root (bt->page)
2139 bt_unlockpage(BtLockWrite, bt->set);
2140 bt_unpinlatch (bt->set);
2141 bt_unpinpool (bt->pool);
2145 // split already locked full node
2146 // return unlocked and unpinned.
2148 BTERR bt_splitpage (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no)
2150 uint slot, cnt, idx, max, nxt = bt->mgr->page_size;
2151 unsigned char fencekey[256];
2152 uint tod = time(NULL);
2153 uint lvl = page->lvl;
2157 // initialize frame buffer for right node
2159 memset (bt->frame, 0, bt->mgr->page_size);
2160 max = page->cnt - page->foster;
2164 // split higher half of keys to bt->frame
2165 // leaving old foster children in the left node,
2166 // and adding a new foster child there.
2168 while( cnt++ < max ) {
2169 key = keyptr(page, cnt);
2170 nxt -= key->len + 1;
2171 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
2172 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
2173 if( !(slotptr(bt->frame, idx)->dead = slotptr(page, cnt)->dead) )
2175 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
2176 slotptr(bt->frame, idx)->off = nxt;
2179 // transfer right link node to new right node
2181 if( page_no > ROOT_page )
2182 memcpy (bt->frame->right, page->right, BtId);
2184 bt->frame->bits = bt->mgr->page_bits;
2185 bt->frame->min = nxt;
2186 bt->frame->cnt = idx;
2187 bt->frame->lvl = lvl;
2189 // get new free page and write right frame to it.
2191 if( !(new_page = bt_newpage(bt, bt->frame)) )
2194 // remember fence key for new right page to add
2195 // as foster child to the left node
2197 key = keyptr(bt->frame, idx);
2198 memcpy (fencekey, key, key->len + 1);
2200 // update lower keys and foster children to continue in old page
2202 memcpy (bt->frame, page, bt->mgr->page_size);
2203 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
2204 nxt = bt->mgr->page_size;
2210 // assemble page of smaller keys
2211 // to remain in the old page
2213 while( cnt++ < max / 2 ) {
2214 key = keyptr(bt->frame, cnt);
2215 nxt -= key->len + 1;
2216 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2217 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
2218 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
2220 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2221 slotptr(page, idx)->off = nxt;
2224 // insert new foster child for right page in queue
2225 // before any of the current foster children
2227 nxt -= *fencekey + 1;
2228 memcpy ((unsigned char *)page + nxt, fencekey, *fencekey + 1);
2230 bt_putid (slotptr(page,++idx)->id, new_page);
2231 slotptr(page, idx)->tod = tod;
2232 slotptr(page, idx)->off = nxt;
2236 // continue with old foster child keys
2237 // note that none will be dead
2239 cnt = bt->frame->cnt - bt->frame->foster;
2241 while( cnt++ < bt->frame->cnt ) {
2242 key = keyptr(bt->frame, cnt);
2243 nxt -= key->len + 1;
2244 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2245 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
2246 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2247 slotptr(page, idx)->off = nxt;
2254 // link new right page
2256 bt_putid (page->right, new_page);
2258 // if current page is the root page, split it
2260 if( page_no == ROOT_page )
2261 return bt_splitroot (bt, new_page);
2263 // release wr lock on our page
2265 bt_unlockpage (BtLockWrite, set);
2267 // obtain ParentModification lock for current page
2268 // to fix new fence key and oldest foster child on page
2270 bt_lockpage (BtLockParent, set);
2272 // get our new fence key to insert in parent node
2274 bt_lockpage (BtLockRead, set);
2276 key = keyptr(page, page->cnt-1);
2277 memcpy (fencekey, key, key->len+1);
2279 bt_unlockpage (BtLockRead, set);
2281 if( bt_insertkey (bt, fencekey + 1, *fencekey, page_no, tod, lvl + 1) )
2284 // lock our page for writing
2286 bt_lockpage (BtLockRead, set);
2288 // switch old parent key from us to our oldest foster child
2290 key = keyptr(page, page->cnt);
2291 memcpy (fencekey, key, key->len+1);
2293 new_page = bt_getid (slotptr(page, page->cnt)->id);
2294 bt_unlockpage (BtLockRead, set);
2296 if( bt_insertkey (bt, fencekey + 1, *fencekey, new_page, tod, lvl + 1) )
2299 // now that it has its own parent pointer,
2300 // remove oldest foster child from our page
2302 bt_lockpage (BtLockWrite, set);
2303 memset (slotptr(page, page->cnt), 0, sizeof(BtSlot));
2309 bt_unlockpage (BtLockParent, set);
2311 // if this emptied page,
2312 // undo the foster child
2315 if( bt_mergeleft (bt, page, pool, set, page_no, lvl) )
2320 bt_unlockpage (BtLockWrite, set);
2321 bt_unpinlatch (set);
2322 bt_unpinpool (pool);
2326 // Insert new key into the btree at leaf level.
2328 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod, uint lvl)
2335 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
2336 ptr = keyptr(bt->page, slot);
2340 bt->err = BTERR_ovflw;
2344 // if key already exists, update id and return
2348 if( !keycmp (ptr, key, len) ) {
2349 if( slotptr(page, slot)->dead )
2351 slotptr(page, slot)->dead = 0;
2352 slotptr(page, slot)->tod = tod;
2353 bt_putid(slotptr(page,slot)->id, id);
2354 bt_unlockpage(BtLockWrite, bt->set);
2355 bt_unpinlatch (bt->set);
2356 bt_unpinpool (bt->pool);
2360 // check if page has enough space
2362 if( slot = bt_cleanpage (bt, bt->page, len, slot) )
2365 if( bt_splitpage (bt, bt->page, bt->pool, bt->set, bt->page_no) )
2369 bt_addkeytopage (bt, bt->page, slot, key, len, id, tod);
2371 bt_unlockpage (BtLockWrite, bt->set);
2372 bt_unpinlatch (bt->set);
2373 bt_unpinpool (bt->pool);
2377 // cache page of keys into cursor and return starting slot for given key
2379 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2383 // cache page for retrieval
2384 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
2385 memcpy (bt->cursor, bt->page, bt->mgr->page_size);
2387 bt->cursor_page = bt->page_no;
2389 bt_unlockpage(BtLockRead, bt->set);
2390 bt_unpinlatch (bt->set);
2391 bt_unpinpool (bt->pool);
2395 // return next slot for cursor page
2396 // or slide cursor right into next page
2398 uint bt_nextkey (BtDb *bt, uint slot)
2406 right = bt_getid(bt->cursor->right);
2407 while( slot++ < bt->cursor->cnt - bt->cursor->foster )
2408 if( slotptr(bt->cursor,slot)->dead )
2410 else if( right || (slot < bt->cursor->cnt - bt->cursor->foster) )
2418 bt->cursor_page = right;
2419 if( pool = bt_pinpool (bt, right) )
2420 page = bt_page (bt, pool, right);
2424 set = bt_pinlatch (bt, right);
2425 bt_lockpage(BtLockRead, set);
2427 memcpy (bt->cursor, page, bt->mgr->page_size);
2429 bt_unlockpage(BtLockRead, set);
2430 bt_unpinlatch (set);
2431 bt_unpinpool (pool);
2438 BtKey bt_key(BtDb *bt, uint slot)
2440 return keyptr(bt->cursor, slot);
2443 uid bt_uid(BtDb *bt, uint slot)
2445 return bt_getid(slotptr(bt->cursor,slot)->id);
2448 uint bt_tod(BtDb *bt, uint slot)
2450 return slotptr(bt->cursor,slot)->tod;
2456 void bt_latchaudit (BtDb *bt)
2458 ushort idx, hashidx;
2465 for( idx = 1; idx < bt->mgr->latchmgr->latchdeployed; idx++ ) {
2466 set = bt->mgr->latchsets + idx;
2467 if( *(ushort *)set->readwr || *(ushort *)set->access || *(ushort *)set->parent ) {
2468 fprintf(stderr, "latchset %d locked for page %6x\n", idx, set->page_no);
2469 *(ushort *)set->readwr = 0;
2470 *(ushort *)set->access = 0;
2471 *(ushort *)set->parent = 0;
2474 fprintf(stderr, "latchset %d pinned\n", idx);
2479 for( hashidx = 0; hashidx < bt->mgr->latchmgr->latchhash; hashidx++ ) {
2480 if( *(uint *)bt->mgr->latchmgr->table[hashidx].latch )
2481 fprintf(stderr, "latchmgr locked\n");
2482 if( idx = bt->mgr->latchmgr->table[hashidx].slot ) do {
2483 set = bt->mgr->latchsets + idx;
2484 if( *(uint *)set->readwr || *(ushort *)set->access || *(ushort *)set->parent )
2485 fprintf(stderr, "latchset %d locked\n", idx);
2486 if( set->hash != hashidx )
2487 fprintf(stderr, "latchset %d wrong hashidx\n", idx);
2489 fprintf(stderr, "latchset %d pinned\n", idx);
2490 } while( idx = set->next );
2492 page_no = bt_getid(bt->mgr->latchmgr->alloc[1].right);
2495 fprintf(stderr, "free: %.6x\n", (uint)page_no);
2496 pool = bt_pinpool (bt, page_no);
2497 page = bt_page (bt, pool, page_no);
2498 page_no = bt_getid(page->right);
2499 bt_unpinpool (pool);
2511 // standalone program to index file of keys
2512 // then list them onto std-out
2515 void *index_file (void *arg)
2517 uint __stdcall index_file (void *arg)
2520 int line = 0, found = 0, cnt = 0;
2521 uid next, page_no = LEAF_page; // start on first page of leaves
2522 unsigned char key[256];
2523 ThreadArg *args = arg;
2524 int ch, len = 0, slot;
2533 bt = bt_open (args->mgr);
2536 switch(args->type | 0x20)
2539 fprintf(stderr, "started latch mgr audit\n");
2541 fprintf(stderr, "finished latch mgr audit\n");
2545 fprintf(stderr, "started indexing for %s\n", args->infile);
2546 if( in = fopen (args->infile, "rb") )
2547 while( ch = getc(in), ch != EOF )
2552 if( args->num == 1 )
2553 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2555 else if( args->num )
2556 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2558 if( bt_insertkey (bt, key, len, line, *tod, 0) )
2559 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2562 else if( len < 255 )
2564 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
2568 fprintf(stderr, "started deleting keys for %s\n", args->infile);
2569 if( in = fopen (args->infile, "rb") )
2570 while( ch = getc(in), ch != EOF )
2574 if( args->num == 1 )
2575 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2577 else if( args->num )
2578 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2580 if( bt_deletekey (bt, key, len) )
2581 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2584 else if( len < 255 )
2586 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2590 fprintf(stderr, "started finding keys for %s\n", args->infile);
2591 if( in = fopen (args->infile, "rb") )
2592 while( ch = getc(in), ch != EOF )
2596 if( args->num == 1 )
2597 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2599 else if( args->num )
2600 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2602 if( bt_findkey (bt, key, len) )
2605 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2608 else if( len < 255 )
2610 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2616 fprintf(stderr, "started reading\n");
2618 if( slot = bt_startkey (bt, key, len) )
2621 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
2623 while( slot = bt_nextkey (bt, slot) ) {
2624 ptr = bt_key(bt, slot);
2625 fwrite (ptr->key, ptr->len, 1, stdout);
2626 fputc ('\n', stdout);
2632 fprintf(stderr, "started reading\n");
2635 if( pool = bt_pinpool (bt, page_no) )
2636 page = bt_page (bt, pool, page_no);
2639 set = bt_pinlatch (bt, page_no);
2640 bt_lockpage (BtLockRead, set);
2642 next = bt_getid (page->right);
2643 bt_unlockpage (BtLockRead, set);
2644 bt_unpinlatch (set);
2645 bt_unpinpool (pool);
2646 } while( page_no = next );
2648 cnt--; // remove stopper key
2649 fprintf(stderr, " Total keys read %d\n", cnt);
2661 typedef struct timeval timer;
2663 int main (int argc, char **argv)
2665 int idx, cnt, len, slot, err;
2666 int segsize, bits = 16;
2671 time_t start[1], stop[1];
2684 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]);
2685 fprintf (stderr, " where page_bits is the page size in bits\n");
2686 fprintf (stderr, " mapped_segments is the number of mmap segments in buffer pool\n");
2687 fprintf (stderr, " seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2688 fprintf (stderr, " line_numbers = 1 to append line numbers to keys\n");
2689 fprintf (stderr, " src_file1 thru src_filen are files of keys separated by newline\n");
2694 gettimeofday(&start, NULL);
2700 bits = atoi(argv[3]);
2703 poolsize = atoi(argv[4]);
2706 fprintf (stderr, "Warning: no mapped_pool\n");
2708 if( poolsize > 65535 )
2709 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2712 segsize = atoi(argv[5]);
2714 segsize = 4; // 16 pages per mmap segment
2717 num = atoi(argv[6]);
2721 threads = malloc (cnt * sizeof(pthread_t));
2723 threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2725 args = malloc (cnt * sizeof(ThreadArg));
2727 mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2730 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2736 for( idx = 0; idx < cnt; idx++ ) {
2737 args[idx].infile = argv[idx + 7];
2738 args[idx].type = argv[2][0];
2739 args[idx].mgr = mgr;
2740 args[idx].num = num;
2741 args[idx].idx = idx;
2743 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2744 fprintf(stderr, "Error creating thread %d\n", err);
2746 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2750 // wait for termination
2753 for( idx = 0; idx < cnt; idx++ )
2754 pthread_join (threads[idx], NULL);
2755 gettimeofday(&stop, NULL);
2756 real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2758 WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2760 for( idx = 0; idx < cnt; idx++ )
2761 CloseHandle(threads[idx]);
2764 real_time = 1000 * (*stop - *start);
2766 fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);