1 // btree version threads2j linux futex concurrency version
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) ParentModification: Exclusive. Change the node's parent keys. Incompatible with another ParentModification.
91 // mode & definition for latch implementation
94 Mutex = 1 << 0, // the mutex bit
95 Write = 1 << 1, // the writers bit
96 Share = 1 << 2, // reader count
97 PendRd = 1 << 12, // reader contended count
98 PendWr = 1 << 22 // writer contended count
102 QueRd = 1, // reader queue
103 QueWr = 2 // writer queue
106 // share is count of read accessors
107 // grant write lock when share == 0
110 volatile uint mutex:1; // 1 = busy
111 volatile uint write:1; // 1 = exclusive
112 volatile uint share:10; // count of readers holding locks
113 volatile uint readwait:10; // count of readers waiting
114 volatile uint writewait:10; // count of writers waiting
117 // Define the length of the page and key pointers
121 // Page key slot definition.
123 // If BT_maxbits is 15 or less, you can save 4 bytes
124 // for each key stored by making the first two uints
125 // into ushorts. You can also save 4 bytes by removing
126 // the tod field from the key.
128 // Keys are marked dead, but remain on the page until
129 // it cleanup is called. The fence key (highest key) for
130 // the page is always present, even after cleanup.
133 uint off:BT_maxbits; // page offset for key start
134 uint dead:1; // set for deleted key
135 uint tod; // time-stamp for key
136 unsigned char id[BtId]; // id associated with key
139 // The key structure occupies space at the upper end of
140 // each page. It's a length byte followed by the value
145 unsigned char key[1];
148 // The first part of an index page.
149 // It is immediately followed
150 // by the BtSlot array of keys.
152 typedef struct Page {
153 uint cnt; // count of keys in page
154 uint act; // count of active keys
155 uint min; // next key offset
156 unsigned char bits; // page size in bits
157 unsigned char lvl:7; // level of page
158 unsigned char dirty:1; // page has deleted keys
159 unsigned char right[BtId]; // page number to right
162 // hash table entries
166 volatile ushort slot; // Latch table entry at head of chain
169 // latch manager table structure
172 BtLatch readwr[1]; // read/write page lock
173 BtLatch access[1]; // Access Intent/Page delete
174 BtLatch parent[1]; // adoption of foster children
175 BtLatch busy[1]; // slot is being moved between chains
176 volatile ushort next; // next entry in hash table chain
177 volatile ushort prev; // prev entry in hash table chain
178 volatile ushort pin; // number of outstanding locks
179 volatile ushort hash; // hash slot entry is under
180 volatile uid page_no; // latch set page number
183 // The memory mapping pool table buffer manager entry
186 unsigned long long int lru; // number of times accessed
187 uid basepage; // mapped base page number
188 char *map; // mapped memory pointer
189 ushort slot; // slot index in this array
190 ushort pin; // mapped page pin counter
191 void *hashprev; // previous pool entry for the same hash idx
192 void *hashnext; // next pool entry for the same hash idx
194 HANDLE hmap; // Windows memory mapping handle
198 // structure for latch manager on ALLOC_page
201 struct Page alloc[2]; // next & free page_nos in right ptr
202 BtLatch lock[1]; // allocation area lite latch
203 ushort latchdeployed; // highest number of latch entries deployed
204 ushort nlatchpage; // number of latch pages at BT_latch
205 ushort latchtotal; // number of page latch entries
206 ushort latchhash; // number of latch hash table slots
207 ushort latchvictim; // next latch entry to examine
208 BtHashEntry table[0]; // the hash table
211 // The object structure for Btree access
214 uint page_size; // page size
215 uint page_bits; // page size in bits
216 uint seg_bits; // seg size in pages in bits
217 uint mode; // read-write mode
223 ushort poolcnt; // highest page pool node in use
224 ushort poolmax; // highest page pool node allocated
225 ushort poolmask; // total number of pages in mmap segment - 1
226 ushort evicted; // last evicted hash table slot
227 ushort hashsize; // size of Hash Table for pool entries
228 ushort *hash; // pool index for hash entries
229 BtLatch *latch; // latches for pool hash slots
230 BtLatchMgr *latchmgr; // mapped latch page from allocation page
231 BtLatchSet *latchsets; // mapped latch set from latch pages
232 BtPool *pool; // memory pool page segments
234 HANDLE halloc; // allocation and latch table handle
239 BtMgr *mgr; // buffer manager for thread
240 BtPage cursor; // cached frame for start/next (never mapped)
241 BtPage frame; // spare frame for the page split (never mapped)
242 BtPage zero; // page of zeroes to extend the file (never mapped)
243 BtPage page; // current page mapped from file
244 uid page_no; // current page number
245 uid cursor_page; // current cursor page number
246 BtLatchSet *set; // current page latchset
247 BtPool *pool; // current page pool
248 unsigned char *mem; // frame, cursor, page memory buffer
249 int parent; // last loadpage was from a parent level
250 int found; // last delete or insert was found
251 int err; // last error
265 extern void bt_close (BtDb *bt);
266 extern BtDb *bt_open (BtMgr *mgr);
267 extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod, uint lvl);
268 extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len);
269 extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
270 extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
271 extern uint bt_nextkey (BtDb *bt, uint slot);
273 // internal functions
274 BTERR bt_splitpage (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no);
275 uint bt_cleanpage(BtDb *bt, BtPage page, uint amt, uint slot);
276 BTERR bt_mergeleft (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no, uint lvl);
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
284 extern BtKey bt_key (BtDb *bt, uint slot);
285 extern uid bt_uid (BtDb *bt, uint slot);
286 extern uint bt_tod (BtDb *bt, uint slot);
288 // BTree page number constants
289 #define ALLOC_page 0 // allocation & lock manager hash table
290 #define ROOT_page 1 // root of the btree
291 #define LEAF_page 2 // first page of leaves
292 #define LATCH_page 3 // pages for lock manager
294 // Number of levels to create in a new BTree
298 // The page is allocated from low and hi ends.
299 // The key offsets and row-id's are allocated
300 // from the bottom, while the text of the key
301 // is allocated from the top. When the two
302 // areas meet, the page is split into two.
304 // A key consists of a length byte, two bytes of
305 // index number (0 - 65534), and up to 253 bytes
306 // of key value. Duplicate keys are discarded.
307 // Associated with each key is a 48 bit row-id.
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 always
323 // present, even after deletion and cleanup.
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 prevent resplitting
339 // or deleting a node before its fence is posted into its upper level.
341 // Empty pages are chained together through the ALLOC page and reused.
343 // Access macros to address slot and key values from the page
345 #define slotptr(page, slot) (((BtSlot *)(page+1)) + (slot-1))
346 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
348 void bt_putid(unsigned char *dest, uid id)
353 dest[i] = (unsigned char)id, id >>= 8;
356 uid bt_getid(unsigned char *src)
361 for( i = 0; i < BtId; i++ )
362 id <<= 8, id |= *src++;
369 int sys_futex(void *addr1, int op, int val1, struct timespec *timeout, void *addr2, int val3)
371 return syscall(SYS_futex, addr1, op, val1, timeout, addr2, val3);
374 // wait until write lock mode is clear
375 // and add 1 to the share count
377 void bt_spinreadlock(BtLatch *latch, int private)
382 private = FUTEX_PRIVATE_FLAG;
385 // obtain latch mutex
386 if( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex ) {
391 // wait for writers to clear
392 // increment read waiters and wait
394 if( latch->write || latch->writewait ) {
395 __sync_fetch_and_add ((uint *)latch, PendRd);
396 prev = __sync_fetch_and_and ((uint *)latch, ~Mutex) & ~Mutex;
397 sys_futex( (uint *)latch, FUTEX_WAIT_BITSET | private, prev, NULL, NULL, QueRd );
398 __sync_fetch_and_sub ((uint *)latch, PendRd);
402 // increment reader lock count
403 // and release latch mutex
405 __sync_fetch_and_add ((uint *)latch, Share);
406 __sync_fetch_and_and ((uint *)latch, ~Mutex);
411 // wait for other read and write latches to relinquish
413 void bt_spinwritelock(BtLatch *latch, int private)
418 private = FUTEX_PRIVATE_FLAG;
421 // obtain latch mutex
422 if( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex ) {
427 // wait for write and reader count to clear
429 if( latch->write || latch->share ) {
430 __sync_fetch_and_add ((uint *)latch, PendWr);
431 prev = __sync_fetch_and_and ((uint *)latch, ~Mutex) & ~Mutex;
432 sys_futex( (uint *)latch, FUTEX_WAIT_BITSET | private, prev, NULL, NULL, QueWr );
433 __sync_fetch_and_sub ((uint *)latch, PendWr);
438 // release latch mutex
440 __sync_fetch_and_or ((uint *)latch, Write);
441 __sync_fetch_and_and ((uint *)latch, ~Mutex);
446 // try to obtain write lock
448 // return 1 if obtained,
451 int bt_spinwritetry(BtLatch *latch)
456 // abandon request if not taken
458 if( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex )
461 // see if write mode is available
463 if( !latch->write && !latch->share ) {
464 __sync_fetch_and_or ((uint *)latch, Write);
469 // release latch mutex
471 __sync_fetch_and_and ((uint *)latch, ~Mutex);
477 void bt_spinreleasewrite(BtLatch *latch, int private)
480 private = FUTEX_PRIVATE_FLAG;
482 // obtain latch mutex
484 while( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex )
487 __sync_fetch_and_and ((uint *)latch, ~Write);
491 if( latch->writewait )
492 if( sys_futex( (uint *)latch, FUTEX_WAKE_BITSET | private, 1, NULL, NULL, QueWr ) )
495 if( latch->readwait )
496 sys_futex( (uint *)latch, FUTEX_WAKE_BITSET | private, INT_MAX, NULL, NULL, QueRd );
498 // release latch mutex
501 __sync_fetch_and_and ((uint *)latch, ~Mutex);
504 // decrement reader count
506 void bt_spinreleaseread(BtLatch *latch, int private)
509 private = FUTEX_PRIVATE_FLAG;
511 // obtain latch mutex
513 while( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex )
516 __sync_fetch_and_sub ((uint *)latch, Share);
518 // wake waiting writers
520 if( !latch->share && latch->writewait )
521 sys_futex( (uint *)latch, FUTEX_WAKE_BITSET | private, 1, NULL, NULL, QueWr );
523 // release latch mutex
525 __sync_fetch_and_and ((uint *)latch, ~Mutex);
528 // link latch table entry into latch hash table
530 void bt_latchlink (BtDb *bt, ushort hashidx, ushort victim, uid page_no)
532 BtLatchSet *set = bt->mgr->latchsets + victim;
534 if( set->next = bt->mgr->latchmgr->table[hashidx].slot )
535 bt->mgr->latchsets[set->next].prev = victim;
537 bt->mgr->latchmgr->table[hashidx].slot = victim;
538 set->page_no = page_no;
545 void bt_unpinlatch (BtLatchSet *set)
548 __sync_fetch_and_add(&set->pin, -1);
550 _InterlockedDecrement16 (&set->pin);
554 // find existing latchset or inspire new one
555 // return with latchset pinned
557 BtLatchSet *bt_pinlatch (BtDb *bt, uid page_no)
559 ushort hashidx = page_no % bt->mgr->latchmgr->latchhash;
560 ushort slot, avail = 0, victim, idx;
563 // obtain read lock on hash table entry
565 bt_spinreadlock(bt->mgr->latchmgr->table[hashidx].latch, 0);
567 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
569 set = bt->mgr->latchsets + slot;
570 if( page_no == set->page_no )
572 } while( slot = set->next );
576 __sync_fetch_and_add(&set->pin, 1);
578 _InterlockedIncrement16 (&set->pin);
582 bt_spinreleaseread (bt->mgr->latchmgr->table[hashidx].latch, 0);
587 // try again, this time with write lock
589 bt_spinwritelock(bt->mgr->latchmgr->table[hashidx].latch, 0);
591 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
593 set = bt->mgr->latchsets + slot;
594 if( page_no == set->page_no )
596 if( !set->pin && !avail )
598 } while( slot = set->next );
600 // found our entry, or take over an unpinned one
602 if( slot || (slot = avail) ) {
603 set = bt->mgr->latchsets + slot;
605 __sync_fetch_and_add(&set->pin, 1);
607 _InterlockedIncrement16 (&set->pin);
609 set->page_no = page_no;
610 bt_spinreleasewrite(bt->mgr->latchmgr->table[hashidx].latch, 0);
614 // see if there are any unused entries
616 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, 1) + 1;
618 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchdeployed);
621 if( victim < bt->mgr->latchmgr->latchtotal ) {
622 set = bt->mgr->latchsets + victim;
624 __sync_fetch_and_add(&set->pin, 1);
626 _InterlockedIncrement16 (&set->pin);
628 bt_latchlink (bt, hashidx, victim, page_no);
629 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch, 0);
634 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, -1);
636 victim = _InterlockedDecrement16 (&bt->mgr->latchmgr->latchdeployed);
638 // find and reuse previous lock entry
642 victim = __sync_fetch_and_add(&bt->mgr->latchmgr->latchvictim, 1);
644 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchvictim) - 1;
646 // we don't use slot zero
648 if( victim %= bt->mgr->latchmgr->latchtotal )
649 set = bt->mgr->latchsets + victim;
653 // take control of our slot
654 // from other threads
656 if( set->pin || !bt_spinwritetry (set->busy) )
661 // try to get write lock on hash chain
662 // skip entry if not obtained
663 // or has outstanding locks
665 if( !bt_spinwritetry (bt->mgr->latchmgr->table[idx].latch) ) {
666 bt_spinreleasewrite (set->busy, 0);
671 bt_spinreleasewrite (set->busy, 0);
672 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch, 0);
676 // unlink our available victim from its hash chain
679 bt->mgr->latchsets[set->prev].next = set->next;
681 bt->mgr->latchmgr->table[idx].slot = set->next;
684 bt->mgr->latchsets[set->next].prev = set->prev;
686 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch, 0);
688 __sync_fetch_and_add(&set->pin, 1);
690 _InterlockedIncrement16 (&set->pin);
692 bt_latchlink (bt, hashidx, victim, page_no);
693 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch, 0);
694 bt_spinreleasewrite (set->busy, 0);
699 void bt_mgrclose (BtMgr *mgr)
704 // release mapped pages
705 // note that slot zero is never used
707 for( slot = 1; slot < mgr->poolmax; slot++ ) {
708 pool = mgr->pool + slot;
711 munmap (pool->map, (mgr->poolmask+1) << mgr->page_bits);
714 FlushViewOfFile(pool->map, 0);
715 UnmapViewOfFile(pool->map);
716 CloseHandle(pool->hmap);
722 munmap (mgr->latchsets, mgr->latchmgr->nlatchpage * mgr->page_size);
723 munmap (mgr->latchmgr, mgr->page_size);
725 FlushViewOfFile(mgr->latchmgr, 0);
726 UnmapViewOfFile(mgr->latchmgr);
727 CloseHandle(mgr->halloc);
736 FlushFileBuffers(mgr->idx);
737 CloseHandle(mgr->idx);
738 GlobalFree (mgr->pool);
739 GlobalFree (mgr->hash);
740 GlobalFree (mgr->latch);
745 // close and release memory
747 void bt_close (BtDb *bt)
754 VirtualFree (bt->mem, 0, MEM_RELEASE);
759 // open/create new btree buffer manager
761 // call with file_name, BT_openmode, bits in page size (e.g. 16),
762 // size of mapped page pool (e.g. 8192)
764 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
766 uint lvl, attr, cacheblk, last, slot, idx;
767 uint nlatchpage, latchhash;
768 BtLatchMgr *latchmgr;
775 SYSTEM_INFO sysinfo[1];
778 // determine sanity of page size and buffer pool
780 if( bits > BT_maxbits )
782 else if( bits < BT_minbits )
786 return NULL; // must have buffer pool
789 mgr = calloc (1, sizeof(BtMgr));
790 mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
793 return free(mgr), NULL;
795 cacheblk = 4096; // minimum mmap segment size for unix
798 mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
799 attr = FILE_ATTRIBUTE_NORMAL;
800 mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
802 if( mgr->idx == INVALID_HANDLE_VALUE )
803 return GlobalFree(mgr), NULL;
805 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
806 GetSystemInfo(sysinfo);
807 cacheblk = sysinfo->dwAllocationGranularity;
811 latchmgr = malloc (BT_maxpage);
814 // read minimum page size to get root info
816 if( size = lseek (mgr->idx, 0L, 2) ) {
817 if( pread(mgr->idx, latchmgr, BT_minpage, 0) == BT_minpage )
818 bits = latchmgr->alloc->bits;
820 return free(mgr), free(latchmgr), NULL;
821 } else if( mode == BT_ro )
822 return free(latchmgr), free (mgr), NULL;
824 latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
825 size = GetFileSize(mgr->idx, amt);
828 if( !ReadFile(mgr->idx, (char *)latchmgr, BT_minpage, amt, NULL) )
829 return bt_mgrclose (mgr), NULL;
830 bits = latchmgr->alloc->bits;
831 } else if( mode == BT_ro )
832 return bt_mgrclose (mgr), NULL;
835 mgr->page_size = 1 << bits;
836 mgr->page_bits = bits;
838 mgr->poolmax = poolmax;
841 if( cacheblk < mgr->page_size )
842 cacheblk = mgr->page_size;
844 // mask for partial memmaps
846 mgr->poolmask = (cacheblk >> bits) - 1;
848 // see if requested size of pages per memmap is greater
850 if( (1 << segsize) > mgr->poolmask )
851 mgr->poolmask = (1 << segsize) - 1;
855 while( (1 << mgr->seg_bits) <= mgr->poolmask )
858 mgr->hashsize = hashsize;
861 mgr->pool = calloc (poolmax, sizeof(BtPool));
862 mgr->hash = calloc (hashsize, sizeof(ushort));
863 mgr->latch = calloc (hashsize, sizeof(BtLatch));
865 mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * sizeof(BtPool));
866 mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
867 mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtLatch));
873 // initialize an empty b-tree with latch page, root page, page of leaves
874 // and page(s) of latches
876 memset (latchmgr, 0, 1 << bits);
877 nlatchpage = BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1;
878 bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
879 latchmgr->alloc->bits = mgr->page_bits;
881 latchmgr->nlatchpage = nlatchpage;
882 latchmgr->latchtotal = nlatchpage * (mgr->page_size / sizeof(BtLatchSet));
884 // initialize latch manager
886 latchhash = (mgr->page_size - sizeof(BtLatchMgr)) / sizeof(BtHashEntry);
888 // size of hash table = total number of latchsets
890 if( latchhash > latchmgr->latchtotal )
891 latchhash = latchmgr->latchtotal;
893 latchmgr->latchhash = latchhash;
896 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
897 return bt_mgrclose (mgr), NULL;
899 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
900 return bt_mgrclose (mgr), NULL;
902 if( *amt < mgr->page_size )
903 return bt_mgrclose (mgr), NULL;
906 memset (latchmgr, 0, 1 << bits);
907 latchmgr->alloc->bits = mgr->page_bits;
909 for( lvl=MIN_lvl; lvl--; ) {
910 slotptr(latchmgr->alloc, 1)->off = mgr->page_size - 3;
911 bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
912 key = keyptr(latchmgr->alloc, 1);
913 key->len = 2; // create stopper key
916 latchmgr->alloc->min = mgr->page_size - 3;
917 latchmgr->alloc->lvl = lvl;
918 latchmgr->alloc->cnt = 1;
919 latchmgr->alloc->act = 1;
921 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
922 return bt_mgrclose (mgr), NULL;
924 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
925 return bt_mgrclose (mgr), NULL;
927 if( *amt < mgr->page_size )
928 return bt_mgrclose (mgr), NULL;
932 // clear out latch manager locks
933 // and rest of pages to round out segment
935 memset(latchmgr, 0, mgr->page_size);
938 while( last <= ((MIN_lvl + 1 + nlatchpage) | mgr->poolmask) ) {
940 pwrite(mgr->idx, latchmgr, mgr->page_size, last << mgr->page_bits);
942 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
943 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
944 return bt_mgrclose (mgr), NULL;
945 if( *amt < mgr->page_size )
946 return bt_mgrclose (mgr), NULL;
953 flag = PROT_READ | PROT_WRITE;
954 mgr->latchmgr = mmap (0, mgr->page_size, flag, MAP_SHARED, mgr->idx, ALLOC_page * mgr->page_size);
955 if( mgr->latchmgr == MAP_FAILED )
956 return bt_mgrclose (mgr), NULL;
957 mgr->latchsets = (BtLatchSet *)mmap (0, mgr->latchmgr->nlatchpage * mgr->page_size, flag, MAP_SHARED, mgr->idx, LATCH_page * mgr->page_size);
958 if( mgr->latchsets == MAP_FAILED )
959 return bt_mgrclose (mgr), NULL;
961 flag = PAGE_READWRITE;
962 mgr->halloc = CreateFileMapping(mgr->idx, NULL, flag, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size, NULL);
964 return bt_mgrclose (mgr), NULL;
966 flag = FILE_MAP_WRITE;
967 mgr->latchmgr = MapViewOfFile(mgr->halloc, flag, 0, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size);
969 return GetLastError(), bt_mgrclose (mgr), NULL;
971 mgr->latchsets = (void *)((char *)mgr->latchmgr + LATCH_page * mgr->page_size);
977 VirtualFree (latchmgr, 0, MEM_RELEASE);
982 // open BTree access method
983 // based on buffer manager
985 BtDb *bt_open (BtMgr *mgr)
987 BtDb *bt = malloc (sizeof(*bt));
989 memset (bt, 0, sizeof(*bt));
992 bt->mem = malloc (3 *mgr->page_size);
994 bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
996 bt->frame = (BtPage)bt->mem;
997 bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
998 bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
1000 memset (bt->zero, 0, mgr->page_size);
1004 // compare two keys, returning > 0, = 0, or < 0
1005 // as the comparison value
1007 int keycmp (BtKey key1, unsigned char *key2, uint len2)
1009 uint len1 = key1->len;
1012 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
1025 // find segment in pool
1026 // must be called with hashslot idx locked
1027 // return NULL if not there
1028 // otherwise return node
1030 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
1035 // compute start of hash chain in pool
1037 if( slot = bt->mgr->hash[idx] )
1038 pool = bt->mgr->pool + slot;
1042 page_no &= ~bt->mgr->poolmask;
1044 while( pool->basepage != page_no )
1045 if( pool = pool->hashnext )
1053 // add segment to hash table
1055 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
1060 pool->hashprev = pool->hashnext = NULL;
1061 pool->basepage = page_no & ~bt->mgr->poolmask;
1064 if( slot = bt->mgr->hash[idx] ) {
1065 node = bt->mgr->pool + slot;
1066 pool->hashnext = node;
1067 node->hashprev = pool;
1070 bt->mgr->hash[idx] = pool->slot;
1073 // find best segment to evict from buffer pool
1075 BtPool *bt_findlru (BtDb *bt, uint hashslot)
1077 unsigned long long int target = ~0LL;
1078 BtPool *pool = NULL, *node;
1083 node = bt->mgr->pool + hashslot;
1085 // scan pool entries under hash table slot
1090 if( node->lru > target )
1094 } while( node = node->hashnext );
1099 // map new buffer pool segment to virtual memory
1101 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
1103 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
1104 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
1108 flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
1109 pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED, bt->mgr->idx, off);
1110 if( pool->map == MAP_FAILED )
1111 return bt->err = BTERR_map;
1114 flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
1115 pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
1117 return bt->err = BTERR_map;
1119 flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
1120 pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1122 return bt->err = BTERR_map;
1127 // calculate page within pool
1129 BtPage bt_page (BtDb *bt, BtPool *pool, uid page_no)
1131 uint subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1134 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1140 void bt_unpinpool (BtPool *pool)
1143 __sync_fetch_and_add(&pool->pin, -1);
1145 _InterlockedDecrement16 (&pool->pin);
1149 // find or place requested page in segment-pool
1150 // return pool table entry, incrementing pin
1152 BtPool *bt_pinpool(BtDb *bt, uid page_no)
1154 BtPool *pool, *node, *next;
1155 uint slot, idx, victim;
1157 // lock hash table chain
1159 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1160 bt_spinreadlock (&bt->mgr->latch[idx], 1);
1162 // look up in hash table
1164 if( pool = bt_findpool(bt, page_no, idx) ) {
1166 __sync_fetch_and_add(&pool->pin, 1);
1168 _InterlockedIncrement16 (&pool->pin);
1170 bt_spinreleaseread (&bt->mgr->latch[idx], 1);
1175 // upgrade to write lock
1177 bt_spinreleaseread (&bt->mgr->latch[idx], 1);
1178 bt_spinwritelock (&bt->mgr->latch[idx], 1);
1180 // try to find page in pool with write lock
1182 if( pool = bt_findpool(bt, page_no, idx) ) {
1184 __sync_fetch_and_add(&pool->pin, 1);
1186 _InterlockedIncrement16 (&pool->pin);
1188 bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
1193 // allocate a new pool node
1194 // and add to hash table
1197 slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
1199 slot = _InterlockedIncrement16 (&bt->mgr->poolcnt) - 1;
1202 if( ++slot < bt->mgr->poolmax ) {
1203 pool = bt->mgr->pool + slot;
1206 if( bt_mapsegment(bt, pool, page_no) )
1209 bt_linkhash(bt, pool, page_no, idx);
1211 __sync_fetch_and_add(&pool->pin, 1);
1213 _InterlockedIncrement16 (&pool->pin);
1215 bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
1219 // pool table is full
1220 // find best pool entry to evict
1223 __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
1225 _InterlockedDecrement16 (&bt->mgr->poolcnt);
1230 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
1232 victim = _InterlockedIncrement16 (&bt->mgr->evicted) - 1;
1234 victim %= bt->mgr->hashsize;
1236 // try to get write lock
1237 // skip entry if not obtained
1239 if( !bt_spinwritetry (&bt->mgr->latch[victim]) )
1242 // if pool entry is empty
1243 // or any pages are pinned
1246 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
1247 bt_spinreleasewrite (&bt->mgr->latch[victim], 1);
1251 // unlink victim pool node from hash table
1253 if( node = pool->hashprev )
1254 node->hashnext = pool->hashnext;
1255 else if( node = pool->hashnext )
1256 bt->mgr->hash[victim] = node->slot;
1258 bt->mgr->hash[victim] = 0;
1260 if( node = pool->hashnext )
1261 node->hashprev = pool->hashprev;
1263 bt_spinreleasewrite (&bt->mgr->latch[victim], 1);
1265 // remove old file mapping
1267 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1269 FlushViewOfFile(pool->map, 0);
1270 UnmapViewOfFile(pool->map);
1271 CloseHandle(pool->hmap);
1275 // create new pool mapping
1276 // and link into hash table
1278 if( bt_mapsegment(bt, pool, page_no) )
1281 bt_linkhash(bt, pool, page_no, idx);
1283 __sync_fetch_and_add(&pool->pin, 1);
1285 _InterlockedIncrement16 (&pool->pin);
1287 bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
1292 // place write, read, or parent lock on requested page_no.
1294 void bt_lockpage(BtLock mode, BtLatchSet *set)
1298 bt_spinreadlock (set->readwr, 0);
1301 bt_spinwritelock (set->readwr, 0);
1304 bt_spinreadlock (set->access, 0);
1307 bt_spinwritelock (set->access, 0);
1310 bt_spinwritelock (set->parent, 0);
1315 // remove write, read, or parent lock on requested page
1317 void bt_unlockpage(BtLock mode, BtLatchSet *set)
1321 bt_spinreleaseread (set->readwr, 0);
1324 bt_spinreleasewrite (set->readwr, 0);
1327 bt_spinreleaseread (set->access, 0);
1330 bt_spinreleasewrite (set->access, 0);
1333 bt_spinreleasewrite (set->parent, 0);
1338 // allocate a new page and write page into it
1340 uid bt_newpage(BtDb *bt, BtPage page)
1348 // lock allocation page
1350 bt_spinwritelock(bt->mgr->latchmgr->lock, 0);
1352 // use empty chain first
1353 // else allocate empty page
1355 if( new_page = bt_getid(bt->mgr->latchmgr->alloc[1].right) ) {
1356 if( pool = bt_pinpool (bt, new_page) )
1357 pmap = bt_page (bt, pool, new_page);
1360 bt_putid(bt->mgr->latchmgr->alloc[1].right, bt_getid(pmap->right));
1361 bt_unpinpool (pool);
1364 new_page = bt_getid(bt->mgr->latchmgr->alloc->right);
1365 bt_putid(bt->mgr->latchmgr->alloc->right, new_page+1);
1369 if ( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1370 return bt->err = BTERR_wrt, 0;
1372 // if writing first page of pool block, zero last page in the block
1374 if ( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1376 // use zero buffer to write zeros
1377 memset(bt->zero, 0, bt->mgr->page_size);
1378 if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1379 return bt->err = BTERR_wrt, 0;
1382 // bring new page into pool and copy page.
1383 // this will extend the file into the new pages.
1385 if( pool = bt_pinpool (bt, new_page) )
1386 pmap = bt_page (bt, pool, new_page);
1390 memcpy(pmap, page, bt->mgr->page_size);
1391 bt_unpinpool (pool);
1393 // unlock allocation latch and return new page no
1395 bt_spinreleasewrite(bt->mgr->latchmgr->lock, 0);
1399 // find slot in page for given key at a given level
1401 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1403 uint diff, higher = bt->page->cnt, low = 1, slot;
1407 // make stopper key an infinite fence value
1408 // by setting the good flag
1410 if( bt_getid (bt->page->right) )
1415 // low is the next candidate.
1416 // loop ends when they meet
1418 // if good, higher is already
1419 // tested as .ge. the given key.
1421 while( diff = higher - low ) {
1422 slot = low + ( diff >> 1 );
1423 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1426 higher = slot, good++;
1429 // return zero if key is on right link page
1431 return good ? higher : 0;
1434 // find and load page at given level for given key
1435 // leave page rd or wr locked as requested
1437 int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, uint lock)
1439 uid page_no = ROOT_page, prevpage = 0;
1440 BtLatchSet *set, *prevset;
1441 uint drill = 0xff, slot;
1442 uint mode, prevmode;
1446 // start at root of btree and drill down
1451 // determine lock mode of drill level
1452 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1454 bt->set = bt_pinlatch (bt, page_no);
1455 bt->page_no = page_no;
1457 // pin page contents
1459 if( bt->pool = bt_pinpool (bt, page_no) )
1460 bt->page = bt_page (bt, bt->pool, page_no);
1464 // obtain access lock using lock chaining with Access mode
1466 if( page_no > ROOT_page )
1467 bt_lockpage(BtLockAccess, bt->set);
1469 // release & unpin parent page
1472 bt_unlockpage(prevmode, prevset);
1473 bt_unpinlatch (prevset);
1474 bt_unpinpool (prevpool);
1478 // obtain read lock using lock chaining
1480 bt_lockpage(mode, bt->set);
1482 if( page_no > ROOT_page )
1483 bt_unlockpage(BtLockAccess, bt->set);
1485 // re-read and re-lock root after determining actual level of root
1487 if( bt->page->lvl != drill) {
1488 if ( bt->page_no != ROOT_page )
1489 return bt->err = BTERR_struct, 0;
1491 drill = bt->page->lvl;
1493 if( lock == BtLockWrite && drill == lvl ) {
1494 bt_unlockpage(mode, bt->set);
1495 bt_unpinlatch (bt->set);
1496 bt_unpinpool (bt->pool);
1501 // find key on page at this level
1502 // and descend to requested level
1504 if( slot = bt_findslot (bt, key, len) ) {
1506 return bt->parent = parent, slot;
1508 while( slotptr(bt->page, slot)->dead )
1509 if( slot++ < bt->page->cnt )
1512 page_no = bt_getid(bt->page->right);
1517 page_no = bt_getid(slotptr(bt->page, slot)->id);
1522 // or slide right into next page
1525 page_no = bt_getid(bt->page->right);
1529 // continue down / right using overlapping locks
1530 // to protect pages being split.
1533 prevpage = bt->page_no;
1534 prevpool = bt->pool;
1539 // return error on end of right chain
1541 bt->err = BTERR_struct;
1542 return 0; // return error
1545 // remove empty page from the B-tree
1546 // by pulling our right node left over ourselves
1548 // call with bt->page, etc, set to page's locked parent
1549 // returns with page locked.
1551 BTERR bt_mergeright (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no, uint lvl, uint slot)
1553 BtLatchSet *rset, *pset, *rpset;
1554 BtPool *rpool, *ppool, *rppool;
1555 BtPage rpage, ppage, rppage;
1556 uid right, parent, rparent;
1560 // cache node's parent page
1562 parent = bt->page_no;
1567 // lock and map our right page
1568 // it cannot be NULL because of the stopper
1569 // in the last right page
1571 bt_lockpage (BtLockWrite, set);
1573 // if we aren't dead yet
1578 if( right = bt_getid (page->right) )
1579 if( rpool = bt_pinpool (bt, right) )
1580 rpage = bt_page (bt, rpool, right);
1584 return bt->err = BTERR_struct;
1586 rset = bt_pinlatch (bt, right);
1588 // find our right neighbor
1590 if( ppage->act > 1 ) {
1591 for( idx = slot; idx++ < ppage->cnt; )
1592 if( !slotptr(ppage, idx)->dead )
1595 if( idx > ppage->cnt )
1596 return bt->err = BTERR_struct;
1598 // redirect right neighbor in parent to left node
1600 bt_putid(slotptr(ppage,idx)->id, page_no);
1603 // if parent has only our deleted page, e.g. no right neighbor
1604 // prepare to merge parent itself
1606 if( ppage->act == 1 ) {
1607 if( rparent = bt_getid (ppage->right) )
1608 if( rppool = bt_pinpool (bt, rparent) )
1609 rppage = bt_page (bt, rppool, rparent);
1613 return bt->err = BTERR_struct;
1615 rpset = bt_pinlatch (bt, rparent);
1616 bt_lockpage (BtLockWrite, rpset);
1618 // find our right neighbor on right parent page
1620 for( idx = 0; idx++ < rppage->cnt; )
1621 if( !slotptr(rppage, idx)->dead ) {
1622 bt_putid (slotptr(rppage, idx)->id, page_no);
1626 if( idx > rppage->cnt )
1627 return bt->err = BTERR_struct;
1630 // now that there are no more pointers to our right node
1631 // we can wait for delete lock on it
1633 bt_lockpage(BtLockDelete, rset);
1634 bt_lockpage(BtLockWrite, rset);
1636 // pull contents of right page into our empty page
1638 memcpy (page, rpage, bt->mgr->page_size);
1640 // ready to release right parent lock
1641 // now that we have a new page in place
1643 if( ppage->act == 1 ) {
1644 bt_unlockpage (BtLockWrite, rpset);
1645 bt_unpinlatch (rpset);
1646 bt_unpinpool (rppool);
1649 // add killed right block to free chain
1652 bt_spinwritelock(bt->mgr->latchmgr->lock, 0);
1654 // store free chain in allocation page second right
1656 bt_putid(rpage->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1657 bt_putid(bt->mgr->latchmgr->alloc[1].right, right);
1659 // unlock latch mgr and right page
1661 bt_unlockpage(BtLockDelete, rset);
1662 bt_unlockpage(BtLockWrite, rset);
1663 bt_unpinlatch (rset);
1664 bt_unpinpool (rpool);
1666 bt_spinreleasewrite(bt->mgr->latchmgr->lock, 0);
1668 // delete our obsolete fence key from our parent
1670 slotptr(ppage, slot)->dead = 1;
1673 // if our parent now empty
1674 // remove it from the tree
1676 if( ppage->act-- == 1 )
1677 if( bt_mergeleft (bt, ppage, ppool, pset, parent, lvl+1) )
1681 bt_unlockpage (BtLockWrite, pset);
1682 bt_unpinlatch (pset);
1683 bt_unpinpool (ppool);
1689 // remove empty page from the B-tree
1690 // try merging left first. If no left
1691 // sibling, then merge right.
1693 // call with page loaded and locked,
1694 // return with page locked.
1696 BTERR bt_mergeleft (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no, uint lvl)
1698 unsigned char fencekey[256], postkey[256];
1699 uint slot, idx, postfence = 0;
1700 BtLatchSet *lset, *pset;
1701 BtPool *lpool, *ppool;
1702 BtPage lpage, ppage;
1706 ptr = keyptr(page, page->cnt);
1707 memcpy(fencekey, ptr, ptr->len + 1);
1708 bt_unlockpage (BtLockWrite, set);
1710 // load and lock our parent
1713 if( !(slot = bt_loadpage (bt, fencekey+1, *fencekey, lvl+1, BtLockWrite)) )
1716 parent = bt->page_no;
1721 // wait until we are posted in our parent
1724 bt_unlockpage (BtLockWrite, pset);
1725 bt_unpinlatch (pset);
1726 bt_unpinpool (ppool);
1735 // find our left neighbor in our parent page
1737 for( idx = slot; --idx; )
1738 if( !slotptr(ppage, idx)->dead )
1741 // if no left neighbor, do right merge
1744 return bt_mergeright (bt, page, pool, set, page_no, lvl, slot);
1746 // lock and map our left neighbor's page
1748 left = bt_getid (slotptr(ppage, idx)->id);
1750 if( lpool = bt_pinpool (bt, left) )
1751 lpage = bt_page (bt, lpool, left);
1755 lset = bt_pinlatch (bt, left);
1756 bt_lockpage(BtLockWrite, lset);
1758 // wait until sibling is in our parent
1760 if( bt_getid (lpage->right) != page_no ) {
1761 bt_unlockpage (BtLockWrite, pset);
1762 bt_unpinlatch (pset);
1763 bt_unpinpool (ppool);
1764 bt_unlockpage (BtLockWrite, lset);
1765 bt_unpinlatch (lset);
1766 bt_unpinpool (lpool);
1775 // since our page will have no more pointers to it,
1776 // obtain Delete lock and wait for write locks to clear
1778 bt_lockpage(BtLockDelete, set);
1779 bt_lockpage(BtLockWrite, set);
1781 // if we aren't dead yet,
1782 // get ready for exit
1785 bt_unlockpage(BtLockDelete, set);
1786 bt_unlockpage(BtLockWrite, lset);
1787 bt_unpinlatch (lset);
1788 bt_unpinpool (lpool);
1792 // are we are the fence key for our parent?
1793 // if so, grab our old fence key
1795 if( postfence = slot == ppage->cnt ) {
1796 ptr = keyptr (ppage, ppage->cnt);
1797 memcpy(fencekey, ptr, ptr->len + 1);
1798 memset(slotptr(ppage, ppage->cnt), 0, sizeof(BtSlot));
1800 // clear out other dead slots
1802 while( --ppage->cnt )
1803 if( slotptr(ppage, ppage->cnt)->dead )
1804 memset(slotptr(ppage, ppage->cnt), 0, sizeof(BtSlot));
1808 ptr = keyptr (ppage, ppage->cnt);
1809 memcpy(postkey, ptr, ptr->len + 1);
1811 slotptr(ppage,slot)->dead = 1;
1816 // push our right neighbor pointer to our left
1818 memcpy (lpage->right, page->right, BtId);
1820 // add ourselves to free chain
1823 bt_spinwritelock(bt->mgr->latchmgr->lock, 0);
1825 // store free chain in allocation page second right
1826 bt_putid(page->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1827 bt_putid(bt->mgr->latchmgr->alloc[1].right, page_no);
1829 // unlock latch mgr and pages
1831 bt_spinreleasewrite(bt->mgr->latchmgr->lock, 0);
1832 bt_unlockpage(BtLockWrite, lset);
1833 bt_unpinlatch (lset);
1834 bt_unpinpool (lpool);
1836 // release our node's delete lock
1838 bt_unlockpage(BtLockDelete, set);
1841 bt_unlockpage (BtLockWrite, pset);
1842 bt_unpinpool (ppool);
1844 // do we need to post parent's fence key in its parent?
1846 if( !postfence || parent == ROOT_page ) {
1847 bt_unpinlatch (pset);
1852 // interlock parent fence post
1854 bt_lockpage (BtLockParent, pset);
1856 // load parent's parent page
1858 if( !(slot = bt_loadpage (bt, fencekey+1, *fencekey, lvl+2, BtLockWrite)) )
1861 if( !(slot = bt_cleanpage (bt, bt->page, *fencekey, slot)) )
1862 if( bt_splitpage (bt, bt->page, bt->pool, bt->set, bt->page_no) )
1869 page->min -= *postkey + 1;
1870 ((unsigned char *)page)[page->min] = *postkey;
1871 memcpy ((unsigned char *)page + page->min +1, postkey + 1, *postkey );
1872 slotptr(page, slot)->off = page->min;
1874 bt_unlockpage (BtLockParent, pset);
1875 bt_unpinlatch (pset);
1877 bt_unlockpage (BtLockWrite, bt->set);
1878 bt_unpinlatch (bt->set);
1879 bt_unpinpool (bt->pool);
1885 // find and delete key on page by marking delete flag bit
1886 // if page becomes empty, delete it from the btree
1888 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len)
1897 if( !(slot = bt_loadpage (bt, key, len, 0, BtLockWrite)) )
1900 page_no = bt->page_no;
1905 // if key is found delete it, otherwise ignore request
1907 ptr = keyptr(page, slot);
1909 if( bt->found = !keycmp (ptr, key, len) )
1910 if( bt->found = slotptr(page, slot)->dead == 0 ) {
1911 slotptr(page,slot)->dead = 1;
1912 if( slot < page->cnt )
1915 if( bt_mergeleft (bt, page, pool, set, page_no, 0) )
1919 bt_unlockpage(BtLockWrite, set);
1920 bt_unpinlatch (set);
1921 bt_unpinpool (pool);
1925 // find key in leaf level and return row-id
1927 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1933 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1934 ptr = keyptr(bt->page, slot);
1938 // if key exists, return row-id
1939 // otherwise return 0
1941 if( slot <= bt->page->cnt && !keycmp (ptr, key, len) )
1942 id = bt_getid(slotptr(bt->page,slot)->id);
1946 bt_unlockpage (BtLockRead, bt->set);
1947 bt_unpinlatch (bt->set);
1948 bt_unpinpool (bt->pool);
1952 // check page for space available,
1953 // clean if necessary and return
1954 // 0 - page needs splitting
1955 // >0 new slot value
1957 uint bt_cleanpage(BtDb *bt, BtPage page, uint amt, uint slot)
1959 uint nxt = bt->mgr->page_size;
1960 uint cnt = 0, idx = 0;
1961 uint max = page->cnt;
1965 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1968 // skip cleanup if nothing to reclaim
1973 memcpy (bt->frame, page, bt->mgr->page_size);
1975 // skip page info and set rest of page to zero
1977 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1981 // try cleaning up page first
1983 // always leave fence key in the array
1984 // otherwise, remove deleted key
1986 while( cnt++ < max ) {
1989 if( cnt < max && slotptr(bt->frame,cnt)->dead )
1994 key = keyptr(bt->frame, cnt);
1995 nxt -= key->len + 1;
1996 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1999 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
2000 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
2002 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2003 slotptr(page, idx)->off = nxt;
2009 // see if page has enough space now, or does it need splitting?
2011 if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
2017 // add key to current page
2018 // page must already be writelocked
2020 void bt_addkeytopage (BtDb *bt, BtPage page, uint slot, unsigned char *key, uint len, uid id, uint tod)
2024 // find next available dead slot and copy key onto page
2026 for( idx = slot; idx < page->cnt; idx++ )
2027 if( slotptr(page, idx)->dead )
2030 if( idx == page->cnt )
2035 // now insert key into array before slot
2038 *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
2040 page->min -= len + 1;
2041 ((unsigned char *)page)[page->min] = len;
2042 memcpy ((unsigned char *)page + page->min +1, key, len );
2044 bt_putid(slotptr(page,slot)->id, id);
2045 slotptr(page, slot)->off = page->min;
2046 slotptr(page, slot)->tod = tod;
2047 slotptr(page, slot)->dead = 0;
2050 BTERR bt_splitroot(BtDb *bt, unsigned char *leftkey, uid page_no2)
2052 uint nxt = bt->mgr->page_size;
2053 BtPage root = bt->page;
2056 // Obtain an empty page to use, and copy the current
2057 // root contents into it
2059 if( !(new_page = bt_newpage(bt, root)) )
2062 // preserve the page info at the bottom
2063 // and set rest to zero
2065 memset(root+1, 0, bt->mgr->page_size - sizeof(*root));
2067 // insert first key on newroot page
2069 nxt -= *leftkey + 1;
2070 memcpy ((unsigned char *)root + nxt, leftkey, *leftkey + 1);
2071 bt_putid(slotptr(root, 1)->id, new_page);
2072 slotptr(root, 1)->off = nxt;
2074 // insert second key (stopper key) on newroot page
2075 // and increase the root height
2078 *((unsigned char *)root + nxt) = 2;
2079 memset ((unsigned char *)root + nxt + 1, 0xff, 2);
2080 bt_putid(slotptr(root, 2)->id, page_no2);
2081 slotptr(root, 2)->off = nxt;
2083 bt_putid(root->right, 0);
2084 root->min = nxt; // reset lowest used offset and key count
2089 // release and unpin root (bt->page)
2091 bt_unlockpage(BtLockWrite, bt->set);
2092 bt_unpinlatch (bt->set);
2093 bt_unpinpool (bt->pool);
2097 // split already locked full node
2098 // return unlocked and unpinned.
2100 BTERR bt_splitpage (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no)
2102 uint slot, cnt, idx, max, nxt = bt->mgr->page_size;
2103 unsigned char rightkey[256], leftkey[256];
2104 uint tod = time(NULL);
2105 uint lvl = page->lvl;
2109 // initialize frame buffer for right node
2111 memset (bt->frame, 0, bt->mgr->page_size);
2116 // split higher half of keys to bt->frame
2118 while( cnt++ < max ) {
2119 key = keyptr(page, cnt);
2120 nxt -= key->len + 1;
2121 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
2122 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
2123 if( !(slotptr(bt->frame, idx)->dead = slotptr(page, cnt)->dead) )
2125 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
2126 slotptr(bt->frame, idx)->off = nxt;
2129 // transfer right link node to new right node
2131 if( page_no > ROOT_page )
2132 memcpy (bt->frame->right, page->right, BtId);
2134 bt->frame->bits = bt->mgr->page_bits;
2135 bt->frame->min = nxt;
2136 bt->frame->cnt = idx;
2137 bt->frame->lvl = lvl;
2139 // get new free page and write right frame to it.
2141 if( !(new_page = bt_newpage(bt, bt->frame)) )
2144 // remember fence key for new right page to add
2145 // as right sibling to the left node
2147 key = keyptr(bt->frame, idx);
2148 memcpy (rightkey, key, key->len + 1);
2150 // update lower keys to continue in old page
2152 memcpy (bt->frame, page, bt->mgr->page_size);
2153 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
2154 nxt = bt->mgr->page_size;
2160 // assemble page of smaller keys
2161 // to remain in the old page
2163 while( cnt++ < max / 2 ) {
2164 key = keyptr(bt->frame, cnt);
2165 nxt -= key->len + 1;
2166 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2167 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
2168 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
2170 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2171 slotptr(page, idx)->off = nxt;
2174 // finalize left page and save fence key
2176 memcpy(leftkey, key, key->len + 1);
2180 // link new right page
2182 bt_putid (page->right, new_page);
2184 // if current page is the root page, split it
2186 if( page_no == ROOT_page )
2187 return bt_splitroot (bt, leftkey, new_page);
2189 // obtain ParentModification lock for current page
2191 bt_lockpage (BtLockParent, set);
2193 // release wr lock on our page.
2194 // this will keep out another SMO
2196 bt_unlockpage (BtLockWrite, set);
2198 // insert key for old page (lower keys)
2200 if( bt_insertkey (bt, leftkey + 1, *leftkey, page_no, tod, lvl + 1) )
2203 // switch old parent key from us to our right page
2205 if( bt_insertkey (bt, rightkey + 1, *rightkey, new_page, tod, lvl + 1) )
2210 bt_unlockpage (BtLockParent, set);
2211 bt_unpinlatch (set);
2212 bt_unpinpool (pool);
2216 // Insert new key into the btree at given level.
2218 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod, uint lvl)
2225 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
2226 ptr = keyptr(bt->page, slot);
2230 bt->err = BTERR_ovflw;
2234 // if key already exists, update id and return
2238 if( !keycmp (ptr, key, len) ) {
2239 if( slotptr(page, slot)->dead )
2241 slotptr(page, slot)->dead = 0;
2242 slotptr(page, slot)->tod = tod;
2243 bt_putid(slotptr(page,slot)->id, id);
2244 bt_unlockpage(BtLockWrite, bt->set);
2245 bt_unpinlatch (bt->set);
2246 bt_unpinpool (bt->pool);
2250 // check if page has enough space
2252 if( slot = bt_cleanpage (bt, bt->page, len, slot) )
2255 if( bt_splitpage (bt, bt->page, bt->pool, bt->set, bt->page_no) )
2259 bt_addkeytopage (bt, bt->page, slot, key, len, id, tod);
2261 bt_unlockpage (BtLockWrite, bt->set);
2262 bt_unpinlatch (bt->set);
2263 bt_unpinpool (bt->pool);
2267 // cache page of keys into cursor and return starting slot for given key
2269 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2273 // cache page for retrieval
2274 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
2275 memcpy (bt->cursor, bt->page, bt->mgr->page_size);
2277 bt->cursor_page = bt->page_no;
2279 bt_unlockpage(BtLockRead, bt->set);
2280 bt_unpinlatch (bt->set);
2281 bt_unpinpool (bt->pool);
2285 // return next slot for cursor page
2286 // or slide cursor right into next page
2288 uint bt_nextkey (BtDb *bt, uint slot)
2296 right = bt_getid(bt->cursor->right);
2297 while( slot++ < bt->cursor->cnt )
2298 if( slotptr(bt->cursor,slot)->dead )
2300 else if( right || (slot < bt->cursor->cnt) )
2308 bt->cursor_page = right;
2309 if( pool = bt_pinpool (bt, right) )
2310 page = bt_page (bt, pool, right);
2314 set = bt_pinlatch (bt, right);
2315 bt_lockpage(BtLockRead, set);
2317 memcpy (bt->cursor, page, bt->mgr->page_size);
2319 bt_unlockpage(BtLockRead, set);
2320 bt_unpinlatch (set);
2321 bt_unpinpool (pool);
2328 BtKey bt_key(BtDb *bt, uint slot)
2330 return keyptr(bt->cursor, slot);
2333 uid bt_uid(BtDb *bt, uint slot)
2335 return bt_getid(slotptr(bt->cursor,slot)->id);
2338 uint bt_tod(BtDb *bt, uint slot)
2340 return slotptr(bt->cursor,slot)->tod;
2346 void bt_latchaudit (BtDb *bt)
2348 ushort idx, hashidx;
2355 for( idx = 1; idx < bt->mgr->latchmgr->latchdeployed; idx++ ) {
2356 set = bt->mgr->latchsets + idx;
2357 if( *(ushort *)set->readwr || *(ushort *)set->access || *(ushort *)set->parent ) {
2358 fprintf(stderr, "latchset %d locked for page %6x\n", idx, set->page_no);
2359 *(ushort *)set->readwr = 0;
2360 *(ushort *)set->access = 0;
2361 *(ushort *)set->parent = 0;
2364 fprintf(stderr, "latchset %d pinned\n", idx);
2369 for( hashidx = 0; hashidx < bt->mgr->latchmgr->latchhash; hashidx++ ) {
2370 if( *(uint *)bt->mgr->latchmgr->table[hashidx].latch )
2371 fprintf(stderr, "latchmgr locked\n");
2372 if( idx = bt->mgr->latchmgr->table[hashidx].slot ) do {
2373 set = bt->mgr->latchsets + idx;
2374 if( *(uint *)set->readwr || *(ushort *)set->access || *(ushort *)set->parent )
2375 fprintf(stderr, "latchset %d locked\n", idx);
2376 if( set->hash != hashidx )
2377 fprintf(stderr, "latchset %d wrong hashidx\n", idx);
2379 fprintf(stderr, "latchset %d pinned\n", idx);
2380 } while( idx = set->next );
2382 page_no = bt_getid(bt->mgr->latchmgr->alloc[1].right);
2385 fprintf(stderr, "free: %.6x\n", (uint)page_no);
2386 pool = bt_pinpool (bt, page_no);
2387 page = bt_page (bt, pool, page_no);
2388 page_no = bt_getid(page->right);
2389 bt_unpinpool (pool);
2401 // standalone program to index file of keys
2402 // then list them onto std-out
2405 void *index_file (void *arg)
2407 uint __stdcall index_file (void *arg)
2410 int line = 0, found = 0, cnt = 0;
2411 uid next, page_no = LEAF_page; // start on first page of leaves
2412 unsigned char key[256];
2413 ThreadArg *args = arg;
2414 int ch, len = 0, slot;
2423 bt = bt_open (args->mgr);
2426 switch(args->type | 0x20)
2429 fprintf(stderr, "started latch mgr audit\n");
2431 fprintf(stderr, "finished latch mgr audit\n");
2435 fprintf(stderr, "started indexing for %s\n", args->infile);
2436 if( in = fopen (args->infile, "rb") )
2437 while( ch = getc(in), ch != EOF )
2442 if( args->num == 1 )
2443 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2445 else if( args->num )
2446 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2448 if( bt_insertkey (bt, key, len, line, *tod, 0) )
2449 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2452 else if( len < 255 )
2454 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
2458 fprintf(stderr, "started deleting keys for %s\n", args->infile);
2459 if( in = fopen (args->infile, "rb") )
2460 while( ch = getc(in), ch != EOF )
2464 if( args->num == 1 )
2465 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2467 else if( args->num )
2468 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2470 if( bt_deletekey (bt, key, len) )
2471 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2474 else if( len < 255 )
2476 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2480 fprintf(stderr, "started finding keys for %s\n", args->infile);
2481 if( in = fopen (args->infile, "rb") )
2482 while( ch = getc(in), ch != EOF )
2486 if( args->num == 1 )
2487 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2489 else if( args->num )
2490 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2492 if( bt_findkey (bt, key, len) )
2495 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2498 else if( len < 255 )
2500 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2506 fprintf(stderr, "started reading\n");
2508 if( slot = bt_startkey (bt, key, len) )
2511 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
2513 while( slot = bt_nextkey (bt, slot) ) {
2514 ptr = bt_key(bt, slot);
2515 fwrite (ptr->key, ptr->len, 1, stdout);
2516 fputc ('\n', stdout);
2522 fprintf(stderr, "started reading\n");
2525 if( pool = bt_pinpool (bt, page_no) )
2526 page = bt_page (bt, pool, page_no);
2529 set = bt_pinlatch (bt, page_no);
2530 bt_lockpage (BtLockRead, set);
2532 next = bt_getid (page->right);
2533 bt_unlockpage (BtLockRead, set);
2534 bt_unpinlatch (set);
2535 bt_unpinpool (pool);
2536 } while( page_no = next );
2538 cnt--; // remove stopper key
2539 fprintf(stderr, " Total keys read %d\n", cnt);
2551 typedef struct timeval timer;
2553 int main (int argc, char **argv)
2555 int idx, cnt, len, slot, err;
2556 int segsize, bits = 16;
2561 time_t start[1], stop[1];
2574 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]);
2575 fprintf (stderr, " where page_bits is the page size in bits\n");
2576 fprintf (stderr, " mapped_segments is the number of mmap segments in buffer pool\n");
2577 fprintf (stderr, " seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2578 fprintf (stderr, " line_numbers = 1 to append line numbers to keys\n");
2579 fprintf (stderr, " src_file1 thru src_filen are files of keys separated by newline\n");
2584 gettimeofday(&start, NULL);
2590 bits = atoi(argv[3]);
2593 poolsize = atoi(argv[4]);
2596 fprintf (stderr, "Warning: no mapped_pool\n");
2598 if( poolsize > 65535 )
2599 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2602 segsize = atoi(argv[5]);
2604 segsize = 4; // 16 pages per mmap segment
2607 num = atoi(argv[6]);
2611 threads = malloc (cnt * sizeof(pthread_t));
2613 threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2615 args = malloc (cnt * sizeof(ThreadArg));
2617 mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2620 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2626 for( idx = 0; idx < cnt; idx++ ) {
2627 args[idx].infile = argv[idx + 7];
2628 args[idx].type = argv[2][0];
2629 args[idx].mgr = mgr;
2630 args[idx].num = num;
2631 args[idx].idx = idx;
2633 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2634 fprintf(stderr, "Error creating thread %d\n", err);
2636 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2640 // wait for termination
2643 for( idx = 0; idx < cnt; idx++ )
2644 pthread_join (threads[idx], NULL);
2645 gettimeofday(&stop, NULL);
2646 real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2648 WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2650 for( idx = 0; idx < cnt; idx++ )
2651 CloseHandle(threads[idx]);
2654 real_time = 1000 * (*stop - *start);
2656 fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);