1 // btree version threads2j linux futex concurrency version
2 // with reworked bt_deletekey
5 // author: karl malbrain, malbrain@cal.berkeley.edu
8 This work, including the source code, documentation
9 and related data, is placed into the public domain.
11 The orginal author is Karl Malbrain.
13 THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY
14 OF ANY KIND, NOT EVEN THE IMPLIED WARRANTY OF
15 MERCHANTABILITY. THE AUTHOR OF THIS SOFTWARE,
16 ASSUMES _NO_ RESPONSIBILITY FOR ANY CONSEQUENCE
17 RESULTING FROM THE USE, MODIFICATION, OR
18 REDISTRIBUTION OF THIS SOFTWARE.
21 // Please see the project home page for documentation
22 // code.google.com/p/high-concurrency-btree
24 #define _FILE_OFFSET_BITS 64
25 #define _LARGEFILE64_SOURCE
29 #include <linux/futex.h>
44 #define WIN32_LEAN_AND_MEAN
58 typedef unsigned long long uid;
61 typedef unsigned long long off64_t;
62 typedef unsigned short ushort;
63 typedef unsigned int uint;
66 #define BT_ro 0x6f72 // ro
67 #define BT_rw 0x7772 // rw
69 #define BT_latchtable 128 // number of latch manager slots
71 #define BT_maxbits 24 // maximum page size in bits
72 #define BT_minbits 9 // minimum page size in bits
73 #define BT_minpage (1 << BT_minbits) // minimum page size
74 #define BT_maxpage (1 << BT_maxbits) // maximum page size
77 There are five lock types for each node in three independent sets:
78 1. (set 1) AccessIntent: Sharable. Going to Read the node. Incompatible with NodeDelete.
79 2. (set 1) NodeDelete: Exclusive. About to release the node. Incompatible with AccessIntent.
80 3. (set 2) ReadLock: Sharable. Read the node. Incompatible with WriteLock.
81 4. (set 2) WriteLock: Exclusive. Modify the node. Incompatible with ReadLock and other WriteLocks.
82 5. (set 3) ParentModification: Exclusive. Change the node's parent keys. Incompatible with another ParentModification.
94 // mode & definition for latch implementation
97 QueRd = 1, // reader queue
98 QueWr = 2 // writer queue
101 // share is count of read accessors
102 // grant write lock when share == 0
105 volatile unsigned char mutex; // 1 = busy
106 volatile unsigned char write:1; // 1 = exclusive
107 volatile unsigned char readwait:1; // readers are waiting
108 volatile unsigned char writewait:1; // writers are waiting
109 volatile unsigned char filler:5;
110 volatile ushort share; // count of readers holding locks
111 volatile ushort rcnt; // count of waiting readers
112 volatile ushort wcnt; // count of waiting writers
115 // Define the length of the page and key pointers
119 // Page key slot definition.
121 // If BT_maxbits is 15 or less, you can save 4 bytes
122 // for each key stored by making the first two uints
123 // into ushorts. You can also save 4 bytes by removing
124 // the tod field from the key.
126 // Keys are marked dead, but remain on the page until
127 // it cleanup is called. The fence key (highest key) for
128 // the page is always present, even after cleanup.
131 uint off:BT_maxbits; // page offset for key start
132 uint dead:1; // set for deleted key
133 uint tod; // time-stamp for key
134 unsigned char id[BtId]; // id associated with key
137 // The key structure occupies space at the upper end of
138 // each page. It's a length byte followed by the key
143 unsigned char key[1];
146 // The first part of an index page.
147 // It is immediately followed
148 // by the BtSlot array of keys.
150 typedef struct BtPage_ {
151 uint cnt; // count of keys in page
152 uint act; // count of active keys
153 uint min; // next key offset
154 unsigned char bits:7; // page size in bits
155 unsigned char free:1; // page is on free list
156 unsigned char lvl:5; // level of page
157 unsigned char kill:1; // page is being deleted
158 unsigned char dirty:1; // page has deleted keys
159 unsigned char posted:1; // page fence has posted
160 unsigned char right[BtId]; // page number to right
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 slot; // slot index in this array
191 ushort pin; // mapped page pin counter
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 // The loadpage interface object
202 uid page_no; // current page number
203 BtPage page; // current page pointer
204 BtPool *pool; // current page pool
205 BtLatchSet *latch; // current page latch set
208 // structure for latch manager on ALLOC_page
211 struct BtPage_ alloc[2]; // next & free page_nos in right ptr
212 BtLatch lock[1]; // allocation area lite latch
213 ushort latchdeployed; // highest number of latch entries deployed
214 ushort nlatchpage; // number of latch pages at BT_latch
215 ushort latchtotal; // number of page latch entries
216 ushort latchhash; // number of latch hash table slots
217 ushort latchvictim; // next latch entry to examine
218 BtHashEntry table[0]; // the hash table
221 // The object structure for Btree access
224 uint page_size; // page size
225 uint page_bits; // page size in bits
226 uint seg_bits; // seg size in pages in bits
227 uint mode; // read-write mode
233 ushort poolcnt; // highest page pool node in use
234 ushort poolmax; // highest page pool node allocated
235 ushort poolmask; // total number of pages in mmap segment - 1
236 ushort evicted; // last evicted hash table slot
237 ushort hashsize; // size of Hash Table for pool entries
238 ushort *hash; // pool index for hash entries
239 BtLatch *latch; // latches for pool hash slots
240 BtLatchMgr *latchmgr; // mapped latch page from allocation page
241 BtLatchSet *latchsets; // mapped latch set from latch pages
242 BtPool *pool; // memory pool page segments
244 HANDLE halloc; // allocation and latch table handle
249 BtMgr *mgr; // buffer manager for thread
250 BtPage cursor; // cached frame for start/next (never mapped)
251 BtPage frame; // spare frame for the page split (never mapped)
252 BtPage zero; // page of zeroes to extend the file (never mapped)
253 uid cursor_page; // current cursor page number
254 unsigned char *mem; // frame, cursor, page memory buffer
255 int found; // last delete or insert was found
256 int err; // last error
270 extern void bt_close (BtDb *bt);
271 extern BtDb *bt_open (BtMgr *mgr);
272 extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod);
273 extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl);
274 extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
275 extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
276 extern uint bt_nextkey (BtDb *bt, uint slot);
279 extern BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolsize, uint segsize, uint hashsize);
280 void bt_mgrclose (BtMgr *mgr);
282 // Helper functions to return slot values
283 extern BtKey bt_key (BtDb *bt, uint slot);
284 extern uid bt_uid (BtDb *bt, uint slot);
285 extern uint bt_tod (BtDb *bt, uint slot);
287 // BTree page number constants
288 #define ALLOC_page 0 // allocation & lock manager hash table
289 #define ROOT_page 1 // root of the btree
290 #define LEAF_page 2 // first page of leaves
291 #define LATCH_page 3 // pages for lock manager
293 // Number of levels to create in a new BTree
297 // The page is allocated from low and hi ends.
298 // The key offsets and row-id's are allocated
299 // from the bottom, while the text of the key
300 // is allocated from the top. When the two
301 // areas meet, the page is split into two.
303 // A key consists of a length byte, two bytes of
304 // index number (0 - 65534), and up to 253 bytes
305 // of key value. Duplicate keys are discarded.
306 // Associated with each key is a 48 bit row-id,
307 // or any other value desired.
309 // The b-tree root is always located at page 1.
310 // The first leaf page of level zero is always
311 // located on page 2.
313 // The b-tree pages are linked with next
314 // pointers to facilitate enumerators,
315 // and provide for concurrency.
317 // When to root page fills, it is split in two and
318 // the tree height is raised by a new root at page
319 // one with two keys.
321 // Deleted keys are marked with a dead bit until
322 // page cleanup. The fence key for a node is
325 // Groups of pages called segments from the btree are optionally
326 // cached with a memory mapped pool. A hash table is used to keep
327 // track of the cached segments. This behaviour is controlled
328 // by the cache block size parameter to bt_open.
330 // To achieve maximum concurrency one page is locked at a time
331 // as the tree is traversed to find leaf key in question. The right
332 // page numbers are used in cases where the page is being split,
335 // Page 0 is dedicated to lock for new page extensions,
336 // and chains empty pages together for reuse.
338 // The ParentModification lock on a node is obtained to serialize posting
339 // or changing the fence key for a node.
341 // Empty pages are chained together through the ALLOC page and reused.
343 // Access macros to address slot and key values from the page
344 // Page slots use 1 based indexing.
346 #define slotptr(page, slot) (((BtSlot *)(page+1)) + (slot-1))
347 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
349 void bt_putid(unsigned char *dest, uid id)
354 dest[i] = (unsigned char)id, id >>= 8;
357 uid bt_getid(unsigned char *src)
362 for( i = 0; i < BtId; i++ )
363 id <<= 8, id |= *src++;
370 int sys_futex(void *addr1, int op, int val1, struct timespec *timeout, void *addr2, int val3)
372 return syscall(SYS_futex, addr1, op, val1, timeout, addr2, val3);
375 // wait until write lock mode is clear
376 // and add 1 to the share count
378 void bt_spinreadlock(BtLatch *latch, int private)
384 private = FUTEX_PRIVATE_FLAG;
387 // obtain latch mutex
388 while( __sync_lock_test_and_set(&latch->mutex, 1) )
392 latch->rcnt--, decr = 0;
394 // wait for writers to clear
395 // increment read waiters and wait
397 if( latch->write || latch->writewait ) {
400 prev = *(uint *)latch & ~1;
401 __sync_lock_release (&latch->mutex);
402 sys_futex( (uint *)latch, FUTEX_WAIT_BITSET | private, prev, NULL, NULL, QueRd );
407 // increment reader lock count
408 // and release latch mutex
412 __sync_lock_release (&latch->mutex);
417 // wait for other read and write latches to relinquish
419 void bt_spinwritelock(BtLatch *latch, int private)
425 private = FUTEX_PRIVATE_FLAG;
428 // obtain latch mutex
429 while( __sync_lock_test_and_set(&latch->mutex, 1) )
433 latch->wcnt--, decr = 0;
435 // wait for write and reader count to clear
437 if( latch->write || latch->share ) {
438 latch->writewait = 1;
440 prev = *(uint *)latch & ~1;
441 __sync_lock_release (&latch->mutex);
442 sys_futex( (uint *)latch, FUTEX_WAIT_BITSET | private, prev, NULL, NULL, QueWr );
448 // release latch mutex
451 latch->writewait = 0;
454 __sync_lock_release (&latch->mutex);
459 // try to obtain write lock
461 // return 1 if obtained,
464 int bt_spinwritetry(BtLatch *latch)
469 // abandon request if not taken
471 if( __sync_lock_test_and_set(&latch->mutex, 1) )
474 // see if write mode is available
476 if( !latch->write && !latch->share )
477 ans = latch->write = 1;
481 // release latch mutex
483 __sync_lock_release (&latch->mutex);
489 void bt_spinreleasewrite(BtLatch *latch, int private)
492 private = FUTEX_PRIVATE_FLAG;
494 // obtain latch mutex
496 while( __sync_lock_test_and_set(&latch->mutex, 1) )
504 if( sys_futex( (uint *)latch, FUTEX_WAKE_BITSET | private, 1, NULL, NULL, QueWr ) )
508 sys_futex( (uint *)latch, FUTEX_WAKE_BITSET | private, INT_MAX, NULL, NULL, QueRd );
510 // release latch mutex
513 __sync_lock_release (&latch->mutex);
516 // decrement reader count
518 void bt_spinreleaseread(BtLatch *latch, int private)
521 private = FUTEX_PRIVATE_FLAG;
523 // obtain latch mutex
525 while( __sync_lock_test_and_set(&latch->mutex, 1) )
530 // wake waiting writers
532 if( !latch->share && latch->wcnt )
533 sys_futex( (uint *)latch, FUTEX_WAKE_BITSET | private, 1, NULL, NULL, QueWr );
535 // release latch mutex
537 __sync_lock_release (&latch->mutex);
540 // link latch table entry into latch hash table
542 void bt_latchlink (BtDb *bt, ushort hashidx, ushort victim, uid page_no)
544 BtLatchSet *set = bt->mgr->latchsets + victim;
546 if( set->next = bt->mgr->latchmgr->table[hashidx].slot )
547 bt->mgr->latchsets[set->next].prev = victim;
549 bt->mgr->latchmgr->table[hashidx].slot = victim;
550 set->page_no = page_no;
557 void bt_unpinlatch (BtLatchSet *set)
560 __sync_fetch_and_add(&set->pin, -1);
562 _InterlockedDecrement16 (&set->pin);
566 // find existing latchset or inspire new one
567 // return with latchset pinned
569 BtLatchSet *bt_pinlatch (BtDb *bt, uid page_no)
571 ushort hashidx = page_no % bt->mgr->latchmgr->latchhash;
572 ushort slot, avail = 0, victim, idx;
575 // obtain read lock on hash table entry
577 bt_spinreadlock(bt->mgr->latchmgr->table[hashidx].latch, 0);
579 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
581 set = bt->mgr->latchsets + slot;
582 if( page_no == set->page_no )
584 } while( slot = set->next );
588 __sync_fetch_and_add(&set->pin, 1);
590 _InterlockedIncrement16 (&set->pin);
594 bt_spinreleaseread (bt->mgr->latchmgr->table[hashidx].latch, 0);
599 // try again, this time with write lock
601 bt_spinwritelock(bt->mgr->latchmgr->table[hashidx].latch, 0);
603 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
605 set = bt->mgr->latchsets + slot;
606 if( page_no == set->page_no )
608 if( !set->pin && !avail )
610 } while( slot = set->next );
612 // found our entry, or take over an unpinned one
614 if( slot || (slot = avail) ) {
615 set = bt->mgr->latchsets + slot;
617 __sync_fetch_and_add(&set->pin, 1);
619 _InterlockedIncrement16 (&set->pin);
621 set->page_no = page_no;
622 bt_spinreleasewrite(bt->mgr->latchmgr->table[hashidx].latch, 0);
626 // see if there are any unused entries
628 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, 1) + 1;
630 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchdeployed);
633 if( victim < bt->mgr->latchmgr->latchtotal ) {
634 set = bt->mgr->latchsets + victim;
636 __sync_fetch_and_add(&set->pin, 1);
638 _InterlockedIncrement16 (&set->pin);
640 bt_latchlink (bt, hashidx, victim, page_no);
641 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch, 0);
646 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, -1);
648 victim = _InterlockedDecrement16 (&bt->mgr->latchmgr->latchdeployed);
650 // find and reuse previous lock entry
654 victim = __sync_fetch_and_add(&bt->mgr->latchmgr->latchvictim, 1);
656 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchvictim) - 1;
658 // we don't use slot zero
660 if( victim %= bt->mgr->latchmgr->latchtotal )
661 set = bt->mgr->latchsets + victim;
665 // take control of our slot
666 // from other threads
668 if( set->pin || !bt_spinwritetry (set->busy) )
673 // try to get write lock on hash chain
674 // skip entry if not obtained
675 // or has outstanding locks
677 if( !bt_spinwritetry (bt->mgr->latchmgr->table[idx].latch) ) {
678 bt_spinreleasewrite (set->busy, 0);
683 bt_spinreleasewrite (set->busy, 0);
684 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch, 0);
688 // unlink our available victim from its hash chain
691 bt->mgr->latchsets[set->prev].next = set->next;
693 bt->mgr->latchmgr->table[idx].slot = set->next;
696 bt->mgr->latchsets[set->next].prev = set->prev;
698 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch, 0);
700 __sync_fetch_and_add(&set->pin, 1);
702 _InterlockedIncrement16 (&set->pin);
704 bt_latchlink (bt, hashidx, victim, page_no);
705 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch, 0);
706 bt_spinreleasewrite (set->busy, 0);
711 void bt_mgrclose (BtMgr *mgr)
716 // release mapped pages
717 // note that slot zero is never used
719 for( slot = 1; slot < mgr->poolmax; slot++ ) {
720 pool = mgr->pool + slot;
723 munmap (pool->map, (mgr->poolmask+1) << mgr->page_bits);
726 FlushViewOfFile(pool->map, 0);
727 UnmapViewOfFile(pool->map);
728 CloseHandle(pool->hmap);
734 munmap (mgr->latchsets, mgr->latchmgr->nlatchpage * mgr->page_size);
735 munmap (mgr->latchmgr, mgr->page_size);
737 FlushViewOfFile(mgr->latchmgr, 0);
738 UnmapViewOfFile(mgr->latchmgr);
739 CloseHandle(mgr->halloc);
748 FlushFileBuffers(mgr->idx);
749 CloseHandle(mgr->idx);
750 GlobalFree (mgr->pool);
751 GlobalFree (mgr->hash);
752 GlobalFree (mgr->latch);
757 // close and release memory
759 void bt_close (BtDb *bt)
766 VirtualFree (bt->mem, 0, MEM_RELEASE);
771 // open/create new btree buffer manager
773 // call with file_name, BT_openmode, bits in page size (e.g. 16),
774 // size of mapped page pool (e.g. 8192)
776 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
778 uint lvl, attr, cacheblk, last, slot, idx;
779 uint nlatchpage, latchhash;
780 BtLatchMgr *latchmgr;
787 SYSTEM_INFO sysinfo[1];
790 // determine sanity of page size and buffer pool
792 if( bits > BT_maxbits )
794 else if( bits < BT_minbits )
798 return NULL; // must have buffer pool
801 mgr = calloc (1, sizeof(BtMgr));
802 mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
805 return free(mgr), NULL;
807 cacheblk = 4096; // minimum mmap segment size for unix
810 mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
811 attr = FILE_ATTRIBUTE_NORMAL;
812 mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
814 if( mgr->idx == INVALID_HANDLE_VALUE )
815 return GlobalFree(mgr), NULL;
817 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
818 GetSystemInfo(sysinfo);
819 cacheblk = sysinfo->dwAllocationGranularity;
823 latchmgr = malloc (BT_maxpage);
826 // read minimum page size to get root info
828 if( size = lseek (mgr->idx, 0L, 2) ) {
829 if( pread(mgr->idx, latchmgr, BT_minpage, 0) == BT_minpage )
830 bits = latchmgr->alloc->bits;
832 return free(mgr), free(latchmgr), NULL;
833 } else if( mode == BT_ro )
834 return free(latchmgr), free (mgr), NULL;
836 latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
837 size = GetFileSize(mgr->idx, amt);
840 if( !ReadFile(mgr->idx, (char *)latchmgr, BT_minpage, amt, NULL) )
841 return bt_mgrclose (mgr), NULL;
842 bits = latchmgr->alloc->bits;
843 } else if( mode == BT_ro )
844 return bt_mgrclose (mgr), NULL;
847 mgr->page_size = 1 << bits;
848 mgr->page_bits = bits;
850 mgr->poolmax = poolmax;
853 if( cacheblk < mgr->page_size )
854 cacheblk = mgr->page_size;
856 // mask for partial memmaps
858 mgr->poolmask = (cacheblk >> bits) - 1;
860 // see if requested size of pages per memmap is greater
862 if( (1 << segsize) > mgr->poolmask )
863 mgr->poolmask = (1 << segsize) - 1;
867 while( (1 << mgr->seg_bits) <= mgr->poolmask )
870 mgr->hashsize = hashsize;
873 mgr->pool = calloc (poolmax, sizeof(BtPool));
874 mgr->hash = calloc (hashsize, sizeof(ushort));
875 mgr->latch = calloc (hashsize, sizeof(BtLatch));
877 mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * sizeof(BtPool));
878 mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
879 mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtLatch));
885 // initialize an empty b-tree with latch page, root page, page of leaves
886 // and page(s) of latches
888 memset (latchmgr, 0, 1 << bits);
889 nlatchpage = BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1;
890 bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
891 latchmgr->alloc->bits = mgr->page_bits;
893 latchmgr->nlatchpage = nlatchpage;
894 latchmgr->latchtotal = nlatchpage * (mgr->page_size / sizeof(BtLatchSet));
896 // initialize latch manager
898 latchhash = (mgr->page_size - sizeof(BtLatchMgr)) / sizeof(BtHashEntry);
900 // size of hash table = total number of latchsets
902 if( latchhash > latchmgr->latchtotal )
903 latchhash = latchmgr->latchtotal;
905 latchmgr->latchhash = latchhash;
908 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
909 return bt_mgrclose (mgr), NULL;
911 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
912 return bt_mgrclose (mgr), NULL;
914 if( *amt < mgr->page_size )
915 return bt_mgrclose (mgr), NULL;
918 memset (latchmgr, 0, 1 << bits);
919 latchmgr->alloc->bits = mgr->page_bits;
921 for( lvl=MIN_lvl; lvl--; ) {
922 slotptr(latchmgr->alloc, 1)->off = mgr->page_size - 3;
923 bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
924 key = keyptr(latchmgr->alloc, 1);
925 key->len = 2; // create stopper key
928 latchmgr->alloc->min = mgr->page_size - 3;
929 latchmgr->alloc->lvl = lvl;
930 latchmgr->alloc->cnt = 1;
931 latchmgr->alloc->act = 1;
933 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
934 return bt_mgrclose (mgr), NULL;
936 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
937 return bt_mgrclose (mgr), NULL;
939 if( *amt < mgr->page_size )
940 return bt_mgrclose (mgr), NULL;
944 // clear out latch manager locks
945 // and rest of pages to round out segment
947 memset(latchmgr, 0, mgr->page_size);
950 while( last <= ((MIN_lvl + 1 + nlatchpage) | mgr->poolmask) ) {
952 pwrite(mgr->idx, latchmgr, mgr->page_size, last << mgr->page_bits);
954 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
955 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
956 return bt_mgrclose (mgr), NULL;
957 if( *amt < mgr->page_size )
958 return bt_mgrclose (mgr), NULL;
965 flag = PROT_READ | PROT_WRITE;
966 mgr->latchmgr = mmap (0, mgr->page_size, flag, MAP_SHARED, mgr->idx, ALLOC_page * mgr->page_size);
967 if( mgr->latchmgr == MAP_FAILED )
968 return bt_mgrclose (mgr), NULL;
969 mgr->latchsets = (BtLatchSet *)mmap (0, mgr->latchmgr->nlatchpage * mgr->page_size, flag, MAP_SHARED, mgr->idx, LATCH_page * mgr->page_size);
970 if( mgr->latchsets == MAP_FAILED )
971 return bt_mgrclose (mgr), NULL;
973 flag = PAGE_READWRITE;
974 mgr->halloc = CreateFileMapping(mgr->idx, NULL, flag, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size, NULL);
976 return bt_mgrclose (mgr), NULL;
978 flag = FILE_MAP_WRITE;
979 mgr->latchmgr = MapViewOfFile(mgr->halloc, flag, 0, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size);
981 return GetLastError(), bt_mgrclose (mgr), NULL;
983 mgr->latchsets = (void *)((char *)mgr->latchmgr + LATCH_page * mgr->page_size);
989 VirtualFree (latchmgr, 0, MEM_RELEASE);
994 // open BTree access method
995 // based on buffer manager
997 BtDb *bt_open (BtMgr *mgr)
999 BtDb *bt = malloc (sizeof(*bt));
1001 memset (bt, 0, sizeof(*bt));
1004 bt->mem = malloc (3 *mgr->page_size);
1006 bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
1008 bt->frame = (BtPage)bt->mem;
1009 bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
1010 bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
1012 memset (bt->zero, 0, mgr->page_size);
1016 // compare two keys, returning > 0, = 0, or < 0
1017 // as the comparison value
1019 int keycmp (BtKey key1, unsigned char *key2, uint len2)
1021 uint len1 = key1->len;
1024 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
1037 // find segment in pool
1038 // must be called with hashslot idx locked
1039 // return NULL if not there
1040 // otherwise return node
1042 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
1047 // compute start of hash chain in pool
1049 if( slot = bt->mgr->hash[idx] )
1050 pool = bt->mgr->pool + slot;
1054 page_no &= ~bt->mgr->poolmask;
1056 while( pool->basepage != page_no )
1057 if( pool = pool->hashnext )
1065 // add segment to hash table
1067 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
1072 pool->hashprev = pool->hashnext = NULL;
1073 pool->basepage = page_no & ~bt->mgr->poolmask;
1076 if( slot = bt->mgr->hash[idx] ) {
1077 node = bt->mgr->pool + slot;
1078 pool->hashnext = node;
1079 node->hashprev = pool;
1082 bt->mgr->hash[idx] = pool->slot;
1085 // find best segment to evict from buffer pool
1087 BtPool *bt_findlru (BtDb *bt, uint hashslot)
1089 unsigned long long int target = ~0LL;
1090 BtPool *pool = NULL, *node;
1095 node = bt->mgr->pool + hashslot;
1097 // scan pool entries under hash table slot
1102 if( node->lru > target )
1106 } while( node = node->hashnext );
1111 // map new buffer pool segment to virtual memory
1113 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
1115 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
1116 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
1120 flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
1121 pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED, bt->mgr->idx, off);
1122 if( pool->map == MAP_FAILED )
1123 return bt->err = BTERR_map;
1126 flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
1127 pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
1129 return bt->err = BTERR_map;
1131 flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
1132 pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1134 return bt->err = BTERR_map;
1139 // calculate page within pool
1141 BtPage bt_page (BtDb *bt, BtPool *pool, uid page_no)
1143 uint subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1146 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1152 void bt_unpinpool (BtPool *pool)
1155 __sync_fetch_and_add(&pool->pin, -1);
1157 _InterlockedDecrement16 (&pool->pin);
1161 // find or place requested page in segment-pool
1162 // return pool table entry, incrementing pin
1164 BtPool *bt_pinpool(BtDb *bt, uid page_no)
1166 BtPool *pool, *node, *next;
1167 uint slot, idx, victim;
1169 // lock hash table chain
1171 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1172 bt_spinreadlock (&bt->mgr->latch[idx], 1);
1174 // look up in hash table
1176 if( pool = bt_findpool(bt, page_no, idx) ) {
1178 __sync_fetch_and_add(&pool->pin, 1);
1180 _InterlockedIncrement16 (&pool->pin);
1182 bt_spinreleaseread (&bt->mgr->latch[idx], 1);
1187 // upgrade to write lock
1189 bt_spinreleaseread (&bt->mgr->latch[idx], 1);
1190 bt_spinwritelock (&bt->mgr->latch[idx], 1);
1192 // try to find page in pool with write lock
1194 if( pool = bt_findpool(bt, page_no, idx) ) {
1196 __sync_fetch_and_add(&pool->pin, 1);
1198 _InterlockedIncrement16 (&pool->pin);
1200 bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
1205 // allocate a new pool node
1206 // and add to hash table
1209 slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
1211 slot = _InterlockedIncrement16 (&bt->mgr->poolcnt) - 1;
1214 if( ++slot < bt->mgr->poolmax ) {
1215 pool = bt->mgr->pool + slot;
1218 if( bt_mapsegment(bt, pool, page_no) )
1221 bt_linkhash(bt, pool, page_no, idx);
1223 __sync_fetch_and_add(&pool->pin, 1);
1225 _InterlockedIncrement16 (&pool->pin);
1227 bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
1231 // pool table is full
1232 // find best pool entry to evict
1235 __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
1237 _InterlockedDecrement16 (&bt->mgr->poolcnt);
1242 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
1244 victim = _InterlockedIncrement16 (&bt->mgr->evicted) - 1;
1246 victim %= bt->mgr->hashsize;
1248 // try to get write lock
1249 // skip entry if not obtained
1251 if( !bt_spinwritetry (&bt->mgr->latch[victim]) )
1254 // if pool entry is empty
1255 // or any pages are pinned
1258 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
1259 bt_spinreleasewrite (&bt->mgr->latch[victim], 1);
1263 // unlink victim pool node from hash table
1265 if( node = pool->hashprev )
1266 node->hashnext = pool->hashnext;
1267 else if( node = pool->hashnext )
1268 bt->mgr->hash[victim] = node->slot;
1270 bt->mgr->hash[victim] = 0;
1272 if( node = pool->hashnext )
1273 node->hashprev = pool->hashprev;
1275 bt_spinreleasewrite (&bt->mgr->latch[victim], 1);
1277 // remove old file mapping
1279 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1281 FlushViewOfFile(pool->map, 0);
1282 UnmapViewOfFile(pool->map);
1283 CloseHandle(pool->hmap);
1287 // create new pool mapping
1288 // and link into hash table
1290 if( bt_mapsegment(bt, pool, page_no) )
1293 bt_linkhash(bt, pool, page_no, idx);
1295 __sync_fetch_and_add(&pool->pin, 1);
1297 _InterlockedIncrement16 (&pool->pin);
1299 bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
1304 // place write, read, or parent lock on requested page_no.
1306 void bt_lockpage(BtLock mode, BtLatchSet *set)
1310 bt_spinreadlock (set->readwr, 0);
1313 bt_spinwritelock (set->readwr, 0);
1316 bt_spinreadlock (set->access, 0);
1319 bt_spinwritelock (set->access, 0);
1322 bt_spinwritelock (set->parent, 0);
1324 case BtLockParentWrt:
1325 bt_spinwritelock (set->parent, 0);
1326 bt_spinwritelock (set->readwr, 0);
1331 // remove write, read, or parent lock on requested page
1333 void bt_unlockpage(BtLock mode, BtLatchSet *set)
1337 bt_spinreleaseread (set->readwr, 0);
1340 bt_spinreleasewrite (set->readwr, 0);
1343 bt_spinreleaseread (set->access, 0);
1346 bt_spinreleasewrite (set->access, 0);
1349 bt_spinreleasewrite (set->parent, 0);
1351 case BtLockParentWrt:
1352 bt_spinreleasewrite (set->parent, 0);
1353 bt_spinreleasewrite (set->readwr, 0);
1358 // allocate a new page and write page into it
1360 uid bt_newpage(BtDb *bt, BtPage page)
1366 // lock allocation page
1368 bt_spinwritelock(bt->mgr->latchmgr->lock, 0);
1370 // use empty chain first
1371 // else allocate empty page
1373 if( new_page = bt_getid(bt->mgr->latchmgr->alloc[1].right) ) {
1374 if( set->pool = bt_pinpool (bt, new_page) )
1375 set->page = bt_page (bt, set->pool, new_page);
1379 bt_putid(bt->mgr->latchmgr->alloc[1].right, bt_getid(set->page->right));
1380 bt_unpinpool (set->pool);
1383 new_page = bt_getid(bt->mgr->latchmgr->alloc->right);
1384 bt_putid(bt->mgr->latchmgr->alloc->right, new_page+1);
1388 if ( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1389 return bt->err = BTERR_wrt, 0;
1391 // if writing first page of pool block, zero last page in the block
1393 if ( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1395 // use zero buffer to write zeros
1396 if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1397 return bt->err = BTERR_wrt, 0;
1400 // bring new page into pool and copy page.
1401 // this will extend the file into the new pages.
1403 if( set->pool = bt_pinpool (bt, new_page) )
1404 set->page = bt_page (bt, set->pool, new_page);
1408 memcpy(set->page, page, bt->mgr->page_size);
1409 bt_unpinpool (set->pool);
1411 // unlock allocation latch and return new page no
1413 bt_spinreleasewrite(bt->mgr->latchmgr->lock, 0);
1417 // find slot in page for given key at a given level
1419 int bt_findslot (BtPageSet *set, unsigned char *key, uint len)
1421 uint diff, higher = set->page->cnt, low = 1, slot;
1424 // make stopper key an infinite fence value
1426 if( bt_getid (set->page->right) )
1431 // low is the lowest candidate.
1432 // loop ends when they meet
1434 // higher is already
1435 // tested as .ge. the passed key.
1437 while( diff = higher - low ) {
1438 slot = low + ( diff >> 1 );
1439 if( keycmp (keyptr(set->page, slot), key, len) < 0 )
1442 higher = slot, good++;
1445 // return zero if key is on right link page
1447 return good ? higher : 0;
1450 // find and load page at given level for given key
1451 // leave page rd or wr locked as requested
1453 int bt_loadpage (BtDb *bt, BtPageSet *set, unsigned char *key, uint len, uint lvl, BtLock lock)
1455 uid page_no = ROOT_page, prevpage = 0;
1456 uint drill = 0xff, slot;
1457 BtLatchSet *prevlatch;
1458 uint mode, prevmode;
1461 // start at root of btree and drill down
1464 // determine lock mode of drill level
1465 mode = (drill == lvl) ? lock : BtLockRead;
1467 set->latch = bt_pinlatch (bt, page_no);
1468 set->page_no = page_no;
1470 // pin page contents
1472 if( set->pool = bt_pinpool (bt, page_no) )
1473 set->page = bt_page (bt, set->pool, page_no);
1477 // obtain access lock using lock chaining with Access mode
1479 if( page_no > ROOT_page )
1480 bt_lockpage(BtLockAccess, set->latch);
1482 // release & unpin parent page
1485 bt_unlockpage(prevmode, prevlatch);
1486 bt_unpinlatch (prevlatch);
1487 bt_unpinpool (prevpool);
1491 // obtain read lock using lock chaining
1493 bt_lockpage(mode, set->latch);
1495 if( set->page->free )
1496 return bt->err = BTERR_struct, 0;
1498 if( page_no > ROOT_page )
1499 bt_unlockpage(BtLockAccess, set->latch);
1501 // re-read and re-lock root after determining actual level of root
1503 if( set->page->lvl != drill) {
1504 if ( set->page_no != ROOT_page )
1505 return bt->err = BTERR_struct, 0;
1507 drill = set->page->lvl;
1509 if( lock != BtLockRead && drill == lvl ) {
1510 bt_unlockpage(mode, set->latch);
1511 bt_unpinlatch (set->latch);
1512 bt_unpinpool (set->pool);
1517 prevpage = set->page_no;
1518 prevlatch = set->latch;
1519 prevpool = set->pool;
1522 // find key on page at this level
1523 // and descend to requested level
1525 if( !set->page->kill )
1526 if( slot = bt_findslot (set, key, len) ) {
1530 while( slotptr(set->page, slot)->dead )
1531 if( slot++ < set->page->cnt )
1536 page_no = bt_getid(slotptr(set->page, slot)->id);
1541 // or slide right into next page
1544 page_no = bt_getid(set->page->right);
1548 // return error on end of right chain
1550 bt->err = BTERR_struct;
1551 return 0; // return error
1554 // return page to free list
1555 // page must be delete & write locked
1557 void bt_freepage (BtDb *bt, BtPageSet *set)
1559 // lock allocation page
1561 bt_spinwritelock (bt->mgr->latchmgr->lock, 0);
1563 // store chain in second right
1564 bt_putid(set->page->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1565 bt_putid(bt->mgr->latchmgr->alloc[1].right, set->page_no);
1566 set->page->free = 1;
1568 // unlock released page
1570 bt_unlockpage (BtLockDelete, set->latch);
1571 bt_unlockpage (BtLockWrite, set->latch);
1572 bt_unpinlatch (set->latch);
1573 bt_unpinpool (set->pool);
1575 // unlock allocation page
1577 bt_spinreleasewrite (bt->mgr->latchmgr->lock, 0);
1580 // a fence key was deleted from a page
1581 // push new fence value upwards
1583 BTERR bt_fixfence (BtDb *bt, BtPageSet *set, uint lvl)
1585 unsigned char leftkey[256], rightkey[256];
1590 // remove the old fence value
1592 ptr = keyptr(set->page, set->page->cnt);
1593 memcpy (rightkey, ptr, ptr->len + 1);
1595 memset (slotptr(set->page, set->page->cnt--), 0, sizeof(BtSlot));
1596 set->page->dirty = 1;
1598 ptr = keyptr(set->page, set->page->cnt);
1599 memcpy (leftkey, ptr, ptr->len + 1);
1600 page_no = set->page_no;
1602 bt_unlockpage (BtLockWrite, set->latch);
1604 // insert new (now smaller) fence key
1606 if( bt_insertkey (bt, leftkey+1, *leftkey, lvl+1, page_no, time(NULL)) )
1609 // now delete old fence key
1611 if( bt_deletekey (bt, rightkey+1, *rightkey, lvl+1) )
1614 bt_unlockpage (BtLockParent, set->latch);
1615 bt_unpinlatch(set->latch);
1616 bt_unpinpool (set->pool);
1620 // root has a single child
1621 // collapse a level from the tree
1623 BTERR bt_collapseroot (BtDb *bt, BtPageSet *root)
1628 // find the child entry and promote as new root contents
1631 for( idx = 0; idx++ < root->page->cnt; )
1632 if( !slotptr(root->page, idx)->dead )
1635 child->page_no = bt_getid (slotptr(root->page, idx)->id);
1637 child->latch = bt_pinlatch (bt, child->page_no);
1638 bt_lockpage (BtLockDelete, child->latch);
1639 bt_lockpage (BtLockWrite, child->latch);
1641 if( child->pool = bt_pinpool (bt, child->page_no) )
1642 child->page = bt_page (bt, child->pool, child->page_no);
1646 memcpy (root->page, child->page, bt->mgr->page_size);
1647 bt_freepage (bt, child);
1649 } while( root->page->lvl > 1 && root->page->act == 1 );
1651 bt_unlockpage (BtLockParentWrt, root->latch);
1652 bt_unpinlatch (root->latch);
1653 bt_unpinpool (root->pool);
1657 // find and delete key on page by marking delete flag bit
1658 // if page becomes empty, delete it from the btree
1660 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl)
1662 unsigned char lowerfence[256], higherfence[256];
1663 uint slot, idx, dirty = 0, fence, found;
1664 BtPageSet set[1], right[1];
1667 if( slot = bt_loadpage (bt, set, key, len, lvl, BtLockParentWrt) )
1668 ptr = keyptr(set->page, slot);
1672 // are we deleting a fence slot?
1674 fence = slot == set->page->cnt;
1676 // if key is found delete it, otherwise ignore request
1678 if( found = !keycmp (ptr, key, len) )
1679 if( found = slotptr(set->page, slot)->dead == 0 ) {
1680 dirty = slotptr(set->page, slot)->dead = 1;
1681 set->page->dirty = 1;
1684 // collapse empty slots
1686 while( idx = set->page->cnt - 1 )
1687 if( slotptr(set->page, idx)->dead ) {
1688 *slotptr(set->page, idx) = *slotptr(set->page, idx + 1);
1689 memset (slotptr(set->page, set->page->cnt--), 0, sizeof(BtSlot));
1694 // did we delete a fence key in an upper level?
1696 if( dirty && lvl && set->page->act && fence )
1697 if( bt_fixfence (bt, set, lvl) )
1700 return bt->found = found, 0;
1702 // is this a collapsed root?
1704 if( lvl > 1 && set->page_no == ROOT_page && set->page->act == 1 )
1705 if( bt_collapseroot (bt, set) )
1708 return bt->found = found, 0;
1710 // return if page is not empty
1712 if( set->page->act ) {
1713 bt_unlockpage(BtLockParentWrt, set->latch);
1714 bt_unpinlatch (set->latch);
1715 bt_unpinpool (set->pool);
1716 return bt->found = found, 0;
1719 // cache copy of fence key
1720 // to post in parent
1722 ptr = keyptr(set->page, set->page->cnt);
1723 memcpy (lowerfence, ptr, ptr->len + 1);
1725 // obtain lock on right page
1727 right->page_no = bt_getid(set->page->right);
1728 right->latch = bt_pinlatch (bt, right->page_no);
1729 bt_lockpage (BtLockParentWrt, right->latch);
1731 // pin page contents
1733 if( right->pool = bt_pinpool (bt, right->page_no) )
1734 right->page = bt_page (bt, right->pool, right->page_no);
1738 if( right->page->kill )
1739 return bt->err = BTERR_struct;
1741 // pull contents of right peer into our empty page
1743 memcpy (set->page, right->page, bt->mgr->page_size);
1745 // cache copy of key to update
1747 ptr = keyptr(right->page, right->page->cnt);
1748 memcpy (higherfence, ptr, ptr->len + 1);
1750 // mark right page deleted and point it to left page
1751 // until we can post parent updates
1753 bt_putid (right->page->right, set->page_no);
1754 right->page->kill = 1;
1756 bt_unlockpage (BtLockWrite, right->latch);
1757 bt_unlockpage (BtLockWrite, set->latch);
1759 // redirect higher key directly to our new node contents
1761 if( bt_insertkey (bt, higherfence+1, *higherfence, lvl+1, set->page_no, time(NULL)) )
1764 // delete old lower key to our node
1766 if( bt_deletekey (bt, lowerfence+1, *lowerfence, lvl+1) )
1769 // obtain delete and write locks to right node
1771 bt_unlockpage (BtLockParent, right->latch);
1772 bt_lockpage (BtLockDelete, right->latch);
1773 bt_lockpage (BtLockWrite, right->latch);
1774 bt_freepage (bt, right);
1776 bt_unlockpage (BtLockParent, set->latch);
1777 bt_unpinlatch (set->latch);
1778 bt_unpinpool (set->pool);
1783 // find key in leaf level and return row-id
1785 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1792 if( slot = bt_loadpage (bt, set, key, len, 0, BtLockRead) )
1793 ptr = keyptr(set->page, slot);
1797 // if key exists, return row-id
1798 // otherwise return 0
1800 if( slot <= set->page->cnt )
1801 if( !keycmp (ptr, key, len) )
1802 id = bt_getid(slotptr(set->page,slot)->id);
1804 bt_unlockpage (BtLockRead, set->latch);
1805 bt_unpinlatch (set->latch);
1806 bt_unpinpool (set->pool);
1810 // check page for space available,
1811 // clean if necessary and return
1812 // 0 - page needs splitting
1813 // >0 new slot value
1815 uint bt_cleanpage(BtDb *bt, BtPage page, uint amt, uint slot)
1817 uint nxt = bt->mgr->page_size;
1818 uint cnt = 0, idx = 0;
1819 uint max = page->cnt;
1823 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1826 // skip cleanup if nothing to reclaim
1831 memcpy (bt->frame, page, bt->mgr->page_size);
1833 // skip page info and set rest of page to zero
1835 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1839 // try cleaning up page first
1840 // by removing deleted keys
1842 while( cnt++ < max ) {
1845 if( cnt < max && slotptr(bt->frame,cnt)->dead )
1848 // copy the key across
1850 key = keyptr(bt->frame, cnt);
1851 nxt -= key->len + 1;
1852 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1856 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1857 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1859 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1860 slotptr(page, idx)->off = nxt;
1866 // see if page has enough space now, or does it need splitting?
1868 if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1874 // split the root and raise the height of the btree
1876 BTERR bt_splitroot(BtDb *bt, BtPageSet *root, unsigned char *leftkey, uid page_no2)
1878 uint nxt = bt->mgr->page_size;
1881 // Obtain an empty page to use, and copy the current
1882 // root contents into it, e.g. lower keys
1884 if( !(left = bt_newpage(bt, root->page)) )
1887 // preserve the page info at the bottom
1888 // of higher keys and set rest to zero
1890 memset(root->page+1, 0, bt->mgr->page_size - sizeof(*root->page));
1892 // insert lower keys page fence key on newroot page as first key
1894 nxt -= *leftkey + 1;
1895 memcpy ((unsigned char *)root->page + nxt, leftkey, *leftkey + 1);
1896 bt_putid(slotptr(root->page, 1)->id, left);
1897 slotptr(root->page, 1)->off = nxt;
1899 // insert stopper key on newroot page
1900 // and increase the root height
1903 ((unsigned char *)root->page)[nxt] = 2;
1904 ((unsigned char *)root->page)[nxt+1] = 0xff;
1905 ((unsigned char *)root->page)[nxt+2] = 0xff;
1906 bt_putid(slotptr(root->page, 2)->id, page_no2);
1907 slotptr(root->page, 2)->off = nxt;
1909 bt_putid(root->page->right, 0);
1910 root->page->min = nxt; // reset lowest used offset and key count
1911 root->page->cnt = 2;
1912 root->page->act = 2;
1915 // release and unpin root
1917 bt_unlockpage(BtLockWrite, root->latch);
1918 bt_unpinlatch (root->latch);
1919 bt_unpinpool (root->pool);
1923 // split already locked full node
1926 BTERR bt_splitpage (BtDb *bt, BtPageSet *set)
1928 uint cnt = 0, idx = 0, max, nxt = bt->mgr->page_size;
1929 unsigned char fencekey[256];
1930 uint lvl = set->page->lvl;
1935 // split higher half of keys to bt->frame
1937 memset (bt->frame, 0, bt->mgr->page_size);
1938 max = set->page->cnt;
1942 while( cnt++ < max ) {
1943 key = keyptr(set->page, cnt);
1944 nxt -= key->len + 1;
1945 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
1947 memcpy(slotptr(bt->frame,++idx)->id, slotptr(set->page,cnt)->id, BtId);
1948 if( !(slotptr(bt->frame, idx)->dead = slotptr(set->page, cnt)->dead) )
1950 slotptr(bt->frame, idx)->tod = slotptr(set->page, cnt)->tod;
1951 slotptr(bt->frame, idx)->off = nxt;
1954 bt->frame->bits = bt->mgr->page_bits;
1955 bt->frame->min = nxt;
1956 bt->frame->cnt = idx;
1957 bt->frame->lvl = lvl;
1961 if( set->page_no > ROOT_page )
1962 memcpy (bt->frame->right, set->page->right, BtId);
1964 // get new free page and write higher keys to it.
1966 if( !(right = bt_newpage(bt, bt->frame)) )
1969 // update lower keys to continue in old page
1971 memcpy (bt->frame, set->page, bt->mgr->page_size);
1972 memset (set->page+1, 0, bt->mgr->page_size - sizeof(*set->page));
1973 nxt = bt->mgr->page_size;
1974 set->page->posted = 0;
1975 set->page->dirty = 0;
1980 // assemble page of smaller keys
1982 while( cnt++ < max / 2 ) {
1983 key = keyptr(bt->frame, cnt);
1984 nxt -= key->len + 1;
1985 memcpy ((unsigned char *)set->page + nxt, key, key->len + 1);
1986 memcpy(slotptr(set->page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1987 slotptr(set->page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1988 slotptr(set->page, idx)->off = nxt;
1992 // remember fence key for smaller page
1994 memcpy(fencekey, key, key->len + 1);
1995 bt_putid(set->page->right, right);
1996 set->page->min = nxt;
1997 set->page->cnt = idx;
1999 // if current page is the root page, split it
2001 if( set->page_no == ROOT_page )
2002 return bt_splitroot (bt, set, fencekey, right);
2004 bt_unlockpage (BtLockWrite, set->latch);
2007 // insert new fences in their parent pages
2010 bt_lockpage (BtLockParent, set->latch);
2011 bt_lockpage (BtLockWrite, set->latch);
2013 key = keyptr (set->page, set->page->cnt);
2014 memcpy (fencekey, key, key->len + 1);
2015 prev = set->page->posted;
2017 if( right && prev ) {
2018 bt_unlockpage (BtLockParent, set->latch);
2019 bt_unlockpage (BtLockWrite, set->latch);
2020 bt_unpinlatch (set->latch);
2021 bt_unpinpool (set->pool);
2025 right = bt_getid (set->page->right);
2026 set->page->posted = 1;
2028 bt_unlockpage (BtLockWrite, set->latch);
2030 // insert new fence for reformulated left block of smaller keys
2033 if( bt_insertkey (bt, fencekey+1, *fencekey, lvl+1, set->page_no, time(NULL)) )
2036 bt_unlockpage (BtLockParent, set->latch);
2037 bt_unpinlatch (set->latch);
2038 bt_unpinpool (set->pool);
2040 if( !(set->page_no = right) )
2043 set->latch = bt_pinlatch (bt, right);
2045 if( set->pool = bt_pinpool (bt, right) )
2046 set->page = bt_page (bt, set->pool, right);
2054 // Insert new key into the btree at given level.
2056 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod)
2063 if( slot = bt_loadpage (bt, set, key, len, lvl, BtLockWrite) )
2064 ptr = keyptr(set->page, slot);
2068 bt->err = BTERR_ovflw;
2072 // if key already exists, update id and return
2074 if( !keycmp (ptr, key, len) ) {
2075 if( slotptr(set->page, slot)->dead )
2077 slotptr(set->page, slot)->dead = 0;
2078 slotptr(set->page, slot)->tod = tod;
2079 bt_putid(slotptr(set->page,slot)->id, id);
2080 bt_unlockpage(BtLockWrite, set->latch);
2081 bt_unpinlatch (set->latch);
2082 bt_unpinpool (set->pool);
2086 // check if page has enough space
2088 if( slot = bt_cleanpage (bt, set->page, len, slot) )
2091 if( bt_splitpage (bt, set) )
2095 // calculate next available slot and copy key into page
2097 set->page->min -= len + 1; // reset lowest used offset
2098 ((unsigned char *)set->page)[set->page->min] = len;
2099 memcpy ((unsigned char *)set->page + set->page->min +1, key, len );
2101 for( idx = slot; idx < set->page->cnt; idx++ )
2102 if( slotptr(set->page, idx)->dead )
2105 // now insert key into array before slot
2107 if( idx == set->page->cnt )
2108 idx++, set->page->cnt++;
2113 *slotptr(set->page, idx) = *slotptr(set->page, idx -1), idx--;
2115 bt_putid(slotptr(set->page,slot)->id, id);
2116 slotptr(set->page, slot)->off = set->page->min;
2117 slotptr(set->page, slot)->tod = tod;
2118 slotptr(set->page, slot)->dead = 0;
2120 bt_unlockpage (BtLockWrite, set->latch);
2121 bt_unpinlatch (set->latch);
2122 bt_unpinpool (set->pool);
2126 // cache page of keys into cursor and return starting slot for given key
2128 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2133 // cache page for retrieval
2135 if( slot = bt_loadpage (bt, set, key, len, 0, BtLockRead) )
2136 memcpy (bt->cursor, set->page, bt->mgr->page_size);
2140 bt->cursor_page = set->page_no;
2142 bt_unlockpage(BtLockRead, set->latch);
2143 bt_unpinlatch (set->latch);
2144 bt_unpinpool (set->pool);
2148 // return next slot for cursor page
2149 // or slide cursor right into next page
2151 uint bt_nextkey (BtDb *bt, uint slot)
2157 right = bt_getid(bt->cursor->right);
2159 while( slot++ < bt->cursor->cnt )
2160 if( slotptr(bt->cursor,slot)->dead )
2162 else if( right || (slot < bt->cursor->cnt) ) // skip infinite stopper
2170 bt->cursor_page = right;
2172 if( set->pool = bt_pinpool (bt, right) )
2173 set->page = bt_page (bt, set->pool, right);
2177 set->latch = bt_pinlatch (bt, right);
2178 bt_lockpage(BtLockRead, set->latch);
2180 memcpy (bt->cursor, set->page, bt->mgr->page_size);
2182 bt_unlockpage(BtLockRead, set->latch);
2183 bt_unpinlatch (set->latch);
2184 bt_unpinpool (set->pool);
2192 BtKey bt_key(BtDb *bt, uint slot)
2194 return keyptr(bt->cursor, slot);
2197 uid bt_uid(BtDb *bt, uint slot)
2199 return bt_getid(slotptr(bt->cursor,slot)->id);
2202 uint bt_tod(BtDb *bt, uint slot)
2204 return slotptr(bt->cursor,slot)->tod;
2210 void bt_latchaudit (BtDb *bt)
2212 ushort idx, hashidx;
2220 for( idx = 1; idx < bt->mgr->latchmgr->latchdeployed; idx++ ) {
2221 latch = bt->mgr->latchsets + idx;
2222 if( *(uint *)latch->readwr ) {
2223 fprintf(stderr, "latchset %d r/w locked for page %.8x\n", idx, latch->page_no);
2224 *(uint *)latch->readwr = 0;
2226 if( *(uint *)latch->access ) {
2227 fprintf(stderr, "latchset %d access locked for page %.8x\n", idx, latch->page_no);
2228 *(uint *)latch->access = 0;
2230 if( *(uint *)latch->parent ) {
2231 fprintf(stderr, "latchset %d parent locked for page %.8x\n", idx, latch->page_no);
2232 *(uint *)latch->parent = 0;
2234 if( *(uint *)latch->busy ) {
2235 fprintf(stderr, "latchset %d busy locked for page %.8x\n", idx, latch->page_no);
2236 *(uint *)latch->parent = 0;
2239 fprintf(stderr, "latchset %d pinned for page %.8x\n", idx, latch->page_no);
2244 for( hashidx = 0; hashidx < bt->mgr->latchmgr->latchhash; hashidx++ ) {
2245 if( idx = bt->mgr->latchmgr->table[hashidx].slot ) do {
2246 latch = bt->mgr->latchsets + idx;
2247 if( latch->hash != hashidx ) {
2248 fprintf(stderr, "latchset %d wrong hashidx\n", idx);
2249 latch->hash = hashidx;
2251 } while( idx = latch->next );
2254 next = bt->mgr->latchmgr->nlatchpage + LATCH_page;
2255 page_no = LEAF_page;
2257 while( page_no < bt_getid(bt->mgr->latchmgr->alloc->right) ) {
2258 pread (bt->mgr->idx, bt->frame, bt->mgr->page_size, page_no << bt->mgr->page_bits);
2259 if( !bt->frame->free )
2260 for( idx = 0; idx++ < bt->frame->cnt - 1; ) {
2261 ptr = keyptr(bt->frame, idx+1);
2262 if( keycmp (keyptr(bt->frame, idx), ptr->key, ptr->len) >= 0 )
2263 fprintf(stderr, "page %.8x idx %.2x out of order\n", page_no, idx);
2266 if( page_no > LEAF_page )
2280 // standalone program to index file of keys
2281 // then list them onto std-out
2284 void *index_file (void *arg)
2286 uint __stdcall index_file (void *arg)
2289 int line = 0, found = 0, cnt = 0;
2290 uid next, page_no = LEAF_page; // start on first page of leaves
2291 unsigned char key[256];
2292 ThreadArg *args = arg;
2293 int ch, len = 0, slot;
2300 bt = bt_open (args->mgr);
2303 switch(args->type | 0x20)
2306 fprintf(stderr, "started latch mgr audit\n");
2308 fprintf(stderr, "finished latch mgr audit\n");
2312 fprintf(stderr, "started indexing for %s\n", args->infile);
2313 if( in = fopen (args->infile, "rb") )
2314 while( ch = getc(in), ch != EOF )
2319 if( args->num == 1 )
2320 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2322 else if( args->num )
2323 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2325 if( bt_insertkey (bt, key, len, 0, line, *tod) )
2326 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2329 else if( len < 255 )
2331 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
2335 fprintf(stderr, "started deleting keys for %s\n", args->infile);
2336 if( in = fopen (args->infile, "rb") )
2337 while( ch = getc(in), ch != EOF )
2341 if( args->num == 1 )
2342 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2344 else if( args->num )
2345 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2347 if( bt_deletekey (bt, key, len, 0) )
2348 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2351 else if( len < 255 )
2353 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2357 fprintf(stderr, "started finding keys for %s\n", args->infile);
2358 if( in = fopen (args->infile, "rb") )
2359 while( ch = getc(in), ch != EOF )
2363 if( args->num == 1 )
2364 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2366 else if( args->num )
2367 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2369 if( bt_findkey (bt, key, len) )
2372 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2374 fprintf(stderr, "Unable to find key %.*s line %d\n", len, key, line);
2377 else if( len < 255 )
2379 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2383 fprintf(stderr, "started scanning\n");
2385 if( set->pool = bt_pinpool (bt, page_no) )
2386 set->page = bt_page (bt, set->pool, page_no);
2389 set->latch = bt_pinlatch (bt, page_no);
2390 bt_lockpage (BtLockRead, set->latch);
2391 next = bt_getid (set->page->right);
2392 cnt += set->page->act;
2394 for( slot = 0; slot++ < set->page->cnt; )
2395 if( next || slot < set->page->cnt )
2396 if( !slotptr(set->page, slot)->dead ) {
2397 ptr = keyptr(set->page, slot);
2398 fwrite (ptr->key, ptr->len, 1, stdout);
2399 fputc ('\n', stdout);
2402 bt_unlockpage (BtLockRead, set->latch);
2403 bt_unpinlatch (set->latch);
2404 bt_unpinpool (set->pool);
2405 } while( page_no = next );
2407 cnt--; // remove stopper key
2408 fprintf(stderr, " Total keys read %d\n", cnt);
2412 fprintf(stderr, "started counting\n");
2413 next = bt->mgr->latchmgr->nlatchpage + LATCH_page;
2414 page_no = LEAF_page;
2416 while( page_no < bt_getid(bt->mgr->latchmgr->alloc->right) ) {
2417 pread (bt->mgr->idx, bt->frame, bt->mgr->page_size, page_no << bt->mgr->page_bits);
2418 if( !bt->frame->free && !bt->frame->lvl )
2419 cnt += bt->frame->act;
2420 if( page_no > LEAF_page )
2425 cnt--; // remove stopper key
2426 fprintf(stderr, " Total keys read %d\n", cnt);
2438 typedef struct timeval timer;
2440 int main (int argc, char **argv)
2442 int idx, cnt, len, slot, err;
2443 int segsize, bits = 16;
2448 time_t start[1], stop[1];
2461 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]);
2462 fprintf (stderr, " where page_bits is the page size in bits\n");
2463 fprintf (stderr, " mapped_segments is the number of mmap segments in buffer pool\n");
2464 fprintf (stderr, " seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2465 fprintf (stderr, " line_numbers = 1 to append line numbers to keys\n");
2466 fprintf (stderr, " src_file1 thru src_filen are files of keys separated by newline\n");
2471 gettimeofday(&start, NULL);
2477 bits = atoi(argv[3]);
2480 poolsize = atoi(argv[4]);
2483 fprintf (stderr, "Warning: no mapped_pool\n");
2485 if( poolsize > 65535 )
2486 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2489 segsize = atoi(argv[5]);
2491 segsize = 4; // 16 pages per mmap segment
2494 num = atoi(argv[6]);
2498 threads = malloc (cnt * sizeof(pthread_t));
2500 threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2502 args = malloc (cnt * sizeof(ThreadArg));
2504 mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2507 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2513 for( idx = 0; idx < cnt; idx++ ) {
2514 args[idx].infile = argv[idx + 7];
2515 args[idx].type = argv[2][0];
2516 args[idx].mgr = mgr;
2517 args[idx].num = num;
2518 args[idx].idx = idx;
2520 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2521 fprintf(stderr, "Error creating thread %d\n", err);
2523 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2527 // wait for termination
2530 for( idx = 0; idx < cnt; idx++ )
2531 pthread_join (threads[idx], NULL);
2532 gettimeofday(&stop, NULL);
2533 real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2535 WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2537 for( idx = 0; idx < cnt; idx++ )
2538 CloseHandle(threads[idx]);
2541 real_time = 1000 * (*stop - *start);
2543 fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);