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
219 char *pooladvise; // bit maps for pool page advisements
224 ushort poolcnt; // highest page pool node in use
225 ushort poolmax; // highest page pool node allocated
226 ushort poolmask; // total number of pages in mmap segment - 1
227 ushort evicted; // last evicted hash table slot
228 ushort hashsize; // size of Hash Table for pool entries
229 ushort *hash; // pool index for hash entries
230 BtLatch *latch; // latches for pool hash slots
231 BtLatchMgr *latchmgr; // mapped latch page from allocation page
232 BtLatchSet *latchsets; // mapped latch set from latch pages
233 BtPool *pool; // memory pool page segments
235 HANDLE halloc; // allocation and latch table handle
240 BtMgr *mgr; // buffer manager for thread
241 BtPage cursor; // cached frame for start/next (never mapped)
242 BtPage frame; // spare frame for the page split (never mapped)
243 BtPage zero; // page of zeroes to extend the file (never mapped)
244 BtPage page; // current page mapped from file
245 uid page_no; // current page number
246 uid cursor_page; // current cursor page number
247 BtLatchSet *set; // current page latchset
248 BtPool *pool; // current page pool
249 unsigned char *mem; // frame, cursor, page memory buffer
250 int parent; // last loadpage was from a parent level
251 int found; // last delete or insert was found
252 int err; // last error
266 extern void bt_close (BtDb *bt);
267 extern BtDb *bt_open (BtMgr *mgr);
268 extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod, uint lvl);
269 extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len);
270 extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
271 extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
272 extern uint bt_nextkey (BtDb *bt, uint slot);
274 // internal functions
275 BTERR bt_splitpage (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no);
276 uint bt_cleanpage(BtDb *bt, BtPage page, uint amt, uint slot);
277 BTERR bt_mergeleft (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no, uint lvl);
280 extern BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolsize, uint segsize, uint hashsize);
281 void bt_mgrclose (BtMgr *mgr);
283 // Helper functions to return slot values
285 extern BtKey bt_key (BtDb *bt, uint slot);
286 extern uid bt_uid (BtDb *bt, uint slot);
287 extern uint bt_tod (BtDb *bt, uint slot);
289 // BTree page number constants
290 #define ALLOC_page 0 // allocation & lock manager hash table
291 #define ROOT_page 1 // root of the btree
292 #define LEAF_page 2 // first page of leaves
293 #define LATCH_page 3 // pages for lock manager
295 // Number of levels to create in a new BTree
299 // The page is allocated from low and hi ends.
300 // The key offsets and row-id's are allocated
301 // from the bottom, while the text of the key
302 // is allocated from the top. When the two
303 // areas meet, the page is split into two.
305 // A key consists of a length byte, two bytes of
306 // index number (0 - 65534), and up to 253 bytes
307 // of key value. Duplicate keys are discarded.
308 // Associated with each key is a 48 bit row-id.
310 // The b-tree root is always located at page 1.
311 // The first leaf page of level zero is always
312 // located on page 2.
314 // The b-tree pages are linked with next
315 // pointers to facilitate enumerators,
316 // and provide for concurrency.
318 // When to root page fills, it is split in two and
319 // the tree height is raised by a new root at page
320 // one with two keys.
322 // Deleted keys are marked with a dead bit until
323 // page cleanup The fence key for a node is always
324 // present, even after deletion and cleanup.
326 // Groups of pages called segments from the btree are optionally
327 // cached with a memory mapped pool. A hash table is used to keep
328 // track of the cached segments. This behaviour is controlled
329 // by the cache block size parameter to bt_open.
331 // To achieve maximum concurrency one page is locked at a time
332 // as the tree is traversed to find leaf key in question. The right
333 // page numbers are used in cases where the page is being split,
336 // Page 0 is dedicated to lock for new page extensions,
337 // and chains empty pages together for reuse.
339 // The ParentModification lock on a node is obtained to prevent resplitting
340 // or deleting a node before its fence is posted into its upper level.
342 // Empty pages are chained together through the ALLOC page and reused.
344 // Access macros to address slot and key values from the page
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)
383 private = FUTEX_PRIVATE_FLAG;
386 // obtain latch mutex
387 if( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex ) {
392 // wait for writers to clear
393 // increment read waiters and wait
395 if( latch->write || latch->writewait ) {
396 __sync_fetch_and_add ((uint *)latch, PendRd);
397 prev = __sync_fetch_and_and ((uint *)latch, ~Mutex) & ~Mutex;
398 sys_futex( (uint *)latch, FUTEX_WAIT_BITSET | private, prev, NULL, NULL, QueRd );
399 __sync_fetch_and_sub ((uint *)latch, PendRd);
403 // increment reader lock count
404 // and release latch mutex
406 __sync_fetch_and_add ((uint *)latch, Share);
407 __sync_fetch_and_and ((uint *)latch, ~Mutex);
412 // wait for other read and write latches to relinquish
414 void bt_spinwritelock(BtLatch *latch, int private)
419 private = FUTEX_PRIVATE_FLAG;
422 // obtain latch mutex
423 if( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex ) {
428 // wait for write and reader count to clear
430 if( latch->write || latch->share ) {
431 __sync_fetch_and_add ((uint *)latch, PendWr);
432 prev = __sync_fetch_and_and ((uint *)latch, ~Mutex) & ~Mutex;
433 sys_futex( (uint *)latch, FUTEX_WAIT_BITSET | private, prev, NULL, NULL, QueWr );
434 __sync_fetch_and_sub ((uint *)latch, PendWr);
439 // release latch mutex
441 __sync_fetch_and_or ((uint *)latch, Write);
442 __sync_fetch_and_and ((uint *)latch, ~Mutex);
447 // try to obtain write lock
449 // return 1 if obtained,
452 int bt_spinwritetry(BtLatch *latch)
457 // abandon request if not taken
459 if( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex )
462 // see if write mode is available
464 if( !latch->write && !latch->share ) {
465 __sync_fetch_and_or ((uint *)latch, Write);
470 // release latch mutex
472 __sync_fetch_and_and ((uint *)latch, ~Mutex);
478 void bt_spinreleasewrite(BtLatch *latch, int private)
481 private = FUTEX_PRIVATE_FLAG;
483 // obtain latch mutex
485 while( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex )
488 __sync_fetch_and_and ((uint *)latch, ~Write);
492 if( latch->writewait )
493 if( sys_futex( (uint *)latch, FUTEX_WAKE_BITSET | private, 1, NULL, NULL, QueWr ) )
496 if( latch->readwait )
497 sys_futex( (uint *)latch, FUTEX_WAKE_BITSET | private, INT_MAX, NULL, NULL, QueRd );
499 // release latch mutex
502 __sync_fetch_and_and ((uint *)latch, ~Mutex);
505 // decrement reader count
507 void bt_spinreleaseread(BtLatch *latch, int private)
510 private = FUTEX_PRIVATE_FLAG;
512 // obtain latch mutex
514 while( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex )
517 __sync_fetch_and_sub ((uint *)latch, Share);
519 // wake waiting writers
521 if( !latch->share && latch->writewait )
522 sys_futex( (uint *)latch, FUTEX_WAKE_BITSET | private, 1, NULL, NULL, QueWr );
524 // release latch mutex
526 __sync_fetch_and_and ((uint *)latch, ~Mutex);
529 // link latch table entry into latch hash table
531 void bt_latchlink (BtDb *bt, ushort hashidx, ushort victim, uid page_no)
533 BtLatchSet *set = bt->mgr->latchsets + victim;
535 if( set->next = bt->mgr->latchmgr->table[hashidx].slot )
536 bt->mgr->latchsets[set->next].prev = victim;
538 bt->mgr->latchmgr->table[hashidx].slot = victim;
539 set->page_no = page_no;
546 void bt_unpinlatch (BtLatchSet *set)
549 __sync_fetch_and_add(&set->pin, -1);
551 _InterlockedDecrement16 (&set->pin);
555 // find existing latchset or inspire new one
556 // return with latchset pinned
558 BtLatchSet *bt_pinlatch (BtDb *bt, uid page_no)
560 ushort hashidx = page_no % bt->mgr->latchmgr->latchhash;
561 ushort slot, avail = 0, victim, idx;
564 // obtain read lock on hash table entry
566 bt_spinreadlock(bt->mgr->latchmgr->table[hashidx].latch, 0);
568 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
570 set = bt->mgr->latchsets + slot;
571 if( page_no == set->page_no )
573 } while( slot = set->next );
577 __sync_fetch_and_add(&set->pin, 1);
579 _InterlockedIncrement16 (&set->pin);
583 bt_spinreleaseread (bt->mgr->latchmgr->table[hashidx].latch, 0);
588 // try again, this time with write lock
590 bt_spinwritelock(bt->mgr->latchmgr->table[hashidx].latch, 0);
592 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
594 set = bt->mgr->latchsets + slot;
595 if( page_no == set->page_no )
597 if( !set->pin && !avail )
599 } while( slot = set->next );
601 // found our entry, or take over an unpinned one
603 if( slot || (slot = avail) ) {
604 set = bt->mgr->latchsets + slot;
606 __sync_fetch_and_add(&set->pin, 1);
608 _InterlockedIncrement16 (&set->pin);
610 set->page_no = page_no;
611 bt_spinreleasewrite(bt->mgr->latchmgr->table[hashidx].latch, 0);
615 // see if there are any unused entries
617 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, 1) + 1;
619 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchdeployed);
622 if( victim < bt->mgr->latchmgr->latchtotal ) {
623 set = bt->mgr->latchsets + victim;
625 __sync_fetch_and_add(&set->pin, 1);
627 _InterlockedIncrement16 (&set->pin);
629 bt_latchlink (bt, hashidx, victim, page_no);
630 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch, 0);
635 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, -1);
637 victim = _InterlockedDecrement16 (&bt->mgr->latchmgr->latchdeployed);
639 // find and reuse previous lock entry
643 victim = __sync_fetch_and_add(&bt->mgr->latchmgr->latchvictim, 1);
645 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchvictim) - 1;
647 // we don't use slot zero
649 if( victim %= bt->mgr->latchmgr->latchtotal )
650 set = bt->mgr->latchsets + victim;
654 // take control of our slot
655 // from other threads
657 if( set->pin || !bt_spinwritetry (set->busy) )
662 // try to get write lock on hash chain
663 // skip entry if not obtained
664 // or has outstanding locks
666 if( !bt_spinwritetry (bt->mgr->latchmgr->table[idx].latch) ) {
667 bt_spinreleasewrite (set->busy, 0);
672 bt_spinreleasewrite (set->busy, 0);
673 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch, 0);
677 // unlink our available victim from its hash chain
680 bt->mgr->latchsets[set->prev].next = set->next;
682 bt->mgr->latchmgr->table[idx].slot = set->next;
685 bt->mgr->latchsets[set->next].prev = set->prev;
687 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch, 0);
689 __sync_fetch_and_add(&set->pin, 1);
691 _InterlockedIncrement16 (&set->pin);
693 bt_latchlink (bt, hashidx, victim, page_no);
694 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch, 0);
695 bt_spinreleasewrite (set->busy, 0);
700 void bt_mgrclose (BtMgr *mgr)
705 // release mapped pages
706 // note that slot zero is never used
708 for( slot = 1; slot < mgr->poolmax; slot++ ) {
709 pool = mgr->pool + slot;
712 munmap (pool->map, (mgr->poolmask+1) << mgr->page_bits);
715 FlushViewOfFile(pool->map, 0);
716 UnmapViewOfFile(pool->map);
717 CloseHandle(pool->hmap);
723 munmap (mgr->latchsets, mgr->latchmgr->nlatchpage * mgr->page_size);
724 munmap (mgr->latchmgr, mgr->page_size);
726 FlushViewOfFile(mgr->latchmgr, 0);
727 UnmapViewOfFile(mgr->latchmgr);
728 CloseHandle(mgr->halloc);
735 free (mgr->pooladvise);
738 FlushFileBuffers(mgr->idx);
739 CloseHandle(mgr->idx);
740 GlobalFree (mgr->pool);
741 GlobalFree (mgr->hash);
742 GlobalFree (mgr->latch);
747 // close and release memory
749 void bt_close (BtDb *bt)
756 VirtualFree (bt->mem, 0, MEM_RELEASE);
761 // open/create new btree buffer manager
763 // call with file_name, BT_openmode, bits in page size (e.g. 16),
764 // size of mapped page pool (e.g. 8192)
766 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
768 uint lvl, attr, cacheblk, last, slot, idx;
769 uint nlatchpage, latchhash;
770 BtLatchMgr *latchmgr;
777 SYSTEM_INFO sysinfo[1];
780 // determine sanity of page size and buffer pool
782 if( bits > BT_maxbits )
784 else if( bits < BT_minbits )
788 return NULL; // must have buffer pool
791 mgr = calloc (1, sizeof(BtMgr));
792 mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
795 return free(mgr), NULL;
797 cacheblk = 4096; // minimum mmap segment size for unix
800 mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
801 attr = FILE_ATTRIBUTE_NORMAL;
802 mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
804 if( mgr->idx == INVALID_HANDLE_VALUE )
805 return GlobalFree(mgr), NULL;
807 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
808 GetSystemInfo(sysinfo);
809 cacheblk = sysinfo->dwAllocationGranularity;
813 latchmgr = malloc (BT_maxpage);
816 // read minimum page size to get root info
818 if( size = lseek (mgr->idx, 0L, 2) ) {
819 if( pread(mgr->idx, latchmgr, BT_minpage, 0) == BT_minpage )
820 bits = latchmgr->alloc->bits;
822 return free(mgr), free(latchmgr), NULL;
823 } else if( mode == BT_ro )
824 return free(latchmgr), free (mgr), NULL;
826 latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
827 size = GetFileSize(mgr->idx, amt);
830 if( !ReadFile(mgr->idx, (char *)latchmgr, BT_minpage, amt, NULL) )
831 return bt_mgrclose (mgr), NULL;
832 bits = latchmgr->alloc->bits;
833 } else if( mode == BT_ro )
834 return bt_mgrclose (mgr), NULL;
837 mgr->page_size = 1 << bits;
838 mgr->page_bits = bits;
840 mgr->poolmax = poolmax;
843 if( cacheblk < mgr->page_size )
844 cacheblk = mgr->page_size;
846 // mask for partial memmaps
848 mgr->poolmask = (cacheblk >> bits) - 1;
850 // see if requested size of pages per memmap is greater
852 if( (1 << segsize) > mgr->poolmask )
853 mgr->poolmask = (1 << segsize) - 1;
857 while( (1 << mgr->seg_bits) <= mgr->poolmask )
860 mgr->hashsize = hashsize;
863 mgr->pool = calloc (poolmax, sizeof(BtPool));
864 mgr->hash = calloc (hashsize, sizeof(ushort));
865 mgr->latch = calloc (hashsize, sizeof(BtLatch));
866 mgr->pooladvise = calloc (poolmax, (mgr->poolmask + 8) / 8);
868 mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * sizeof(BtPool));
869 mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
870 mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtLatch));
876 // initialize an empty b-tree with latch page, root page, page of leaves
877 // and page(s) of latches
879 memset (latchmgr, 0, 1 << bits);
880 nlatchpage = BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1;
881 bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
882 latchmgr->alloc->bits = mgr->page_bits;
884 latchmgr->nlatchpage = nlatchpage;
885 latchmgr->latchtotal = nlatchpage * (mgr->page_size / sizeof(BtLatchSet));
887 // initialize latch manager
889 latchhash = (mgr->page_size - sizeof(BtLatchMgr)) / sizeof(BtHashEntry);
891 // size of hash table = total number of latchsets
893 if( latchhash > latchmgr->latchtotal )
894 latchhash = latchmgr->latchtotal;
896 latchmgr->latchhash = latchhash;
899 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
900 return bt_mgrclose (mgr), NULL;
902 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
903 return bt_mgrclose (mgr), NULL;
905 if( *amt < mgr->page_size )
906 return bt_mgrclose (mgr), NULL;
909 memset (latchmgr, 0, 1 << bits);
910 latchmgr->alloc->bits = mgr->page_bits;
912 for( lvl=MIN_lvl; lvl--; ) {
913 slotptr(latchmgr->alloc, 1)->off = mgr->page_size - 3;
914 bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
915 key = keyptr(latchmgr->alloc, 1);
916 key->len = 2; // create stopper key
919 latchmgr->alloc->min = mgr->page_size - 3;
920 latchmgr->alloc->lvl = lvl;
921 latchmgr->alloc->cnt = 1;
922 latchmgr->alloc->act = 1;
924 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
925 return bt_mgrclose (mgr), NULL;
927 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
928 return bt_mgrclose (mgr), NULL;
930 if( *amt < mgr->page_size )
931 return bt_mgrclose (mgr), NULL;
935 // clear out latch manager locks
936 // and rest of pages to round out segment
938 memset(latchmgr, 0, mgr->page_size);
941 while( last <= ((MIN_lvl + 1 + nlatchpage) | mgr->poolmask) ) {
943 pwrite(mgr->idx, latchmgr, mgr->page_size, last << mgr->page_bits);
945 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
946 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
947 return bt_mgrclose (mgr), NULL;
948 if( *amt < mgr->page_size )
949 return bt_mgrclose (mgr), NULL;
956 flag = PROT_READ | PROT_WRITE;
957 mgr->latchmgr = mmap (0, mgr->page_size, flag, MAP_SHARED, mgr->idx, ALLOC_page * mgr->page_size);
958 if( mgr->latchmgr == MAP_FAILED )
959 return bt_mgrclose (mgr), NULL;
960 mgr->latchsets = (BtLatchSet *)mmap (0, mgr->latchmgr->nlatchpage * mgr->page_size, flag, MAP_SHARED, mgr->idx, LATCH_page * mgr->page_size);
961 if( mgr->latchsets == MAP_FAILED )
962 return bt_mgrclose (mgr), NULL;
964 flag = PAGE_READWRITE;
965 mgr->halloc = CreateFileMapping(mgr->idx, NULL, flag, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size, NULL);
967 return bt_mgrclose (mgr), NULL;
969 flag = FILE_MAP_WRITE;
970 mgr->latchmgr = MapViewOfFile(mgr->halloc, flag, 0, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size);
972 return GetLastError(), bt_mgrclose (mgr), NULL;
974 mgr->latchsets = (void *)((char *)mgr->latchmgr + LATCH_page * mgr->page_size);
980 VirtualFree (latchmgr, 0, MEM_RELEASE);
985 // open BTree access method
986 // based on buffer manager
988 BtDb *bt_open (BtMgr *mgr)
990 BtDb *bt = malloc (sizeof(*bt));
992 memset (bt, 0, sizeof(*bt));
995 bt->mem = malloc (3 *mgr->page_size);
997 bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
999 bt->frame = (BtPage)bt->mem;
1000 bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
1001 bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
1003 memset (bt->zero, 0, mgr->page_size);
1007 // compare two keys, returning > 0, = 0, or < 0
1008 // as the comparison value
1010 int keycmp (BtKey key1, unsigned char *key2, uint len2)
1012 uint len1 = key1->len;
1015 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
1028 // find segment in pool
1029 // must be called with hashslot idx locked
1030 // return NULL if not there
1031 // otherwise return node
1033 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
1038 // compute start of hash chain in pool
1040 if( slot = bt->mgr->hash[idx] )
1041 pool = bt->mgr->pool + slot;
1045 page_no &= ~bt->mgr->poolmask;
1047 while( pool->basepage != page_no )
1048 if( pool = pool->hashnext )
1056 // add segment to hash table
1058 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
1063 pool->hashprev = pool->hashnext = NULL;
1064 pool->basepage = page_no & ~bt->mgr->poolmask;
1067 if( slot = bt->mgr->hash[idx] ) {
1068 node = bt->mgr->pool + slot;
1069 pool->hashnext = node;
1070 node->hashprev = pool;
1073 bt->mgr->hash[idx] = pool->slot;
1076 // find best segment to evict from buffer pool
1078 BtPool *bt_findlru (BtDb *bt, uint hashslot)
1080 unsigned long long int target = ~0LL;
1081 BtPool *pool = NULL, *node;
1086 node = bt->mgr->pool + hashslot;
1088 // scan pool entries under hash table slot
1093 if( node->lru > target )
1097 } while( node = node->hashnext );
1102 // map new buffer pool segment to virtual memory
1104 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
1106 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
1107 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
1111 flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
1112 pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED, bt->mgr->idx, off);
1113 if( pool->map == MAP_FAILED )
1114 return bt->err = BTERR_map;
1116 // clear out madvise issued bits
1117 memset (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8) / 8), 0, (bt->mgr->poolmask + 8)/8);
1119 flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
1120 pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
1122 return bt->err = BTERR_map;
1124 flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
1125 pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1127 return bt->err = BTERR_map;
1132 // calculate page within pool
1134 BtPage bt_page (BtDb *bt, BtPool *pool, uid page_no)
1136 uint subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1139 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1142 uint idx = subpage / 8;
1143 uint bit = subpage % 8;
1145 if( ~((bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] >> bit) & 1 ) {
1146 madvise (page, bt->mgr->page_size, MADV_WILLNEED);
1147 (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] |= 1 << bit;
1156 void bt_unpinpool (BtPool *pool)
1159 __sync_fetch_and_add(&pool->pin, -1);
1161 _InterlockedDecrement16 (&pool->pin);
1165 // find or place requested page in segment-pool
1166 // return pool table entry, incrementing pin
1168 BtPool *bt_pinpool(BtDb *bt, uid page_no)
1170 BtPool *pool, *node, *next;
1171 uint slot, idx, victim;
1173 // lock hash table chain
1175 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1176 bt_spinreadlock (&bt->mgr->latch[idx], 1);
1178 // look up in hash table
1180 if( pool = bt_findpool(bt, page_no, idx) ) {
1182 __sync_fetch_and_add(&pool->pin, 1);
1184 _InterlockedIncrement16 (&pool->pin);
1186 bt_spinreleaseread (&bt->mgr->latch[idx], 1);
1191 // upgrade to write lock
1193 bt_spinreleaseread (&bt->mgr->latch[idx], 1);
1194 bt_spinwritelock (&bt->mgr->latch[idx], 1);
1196 // try to find page in pool with write lock
1198 if( pool = bt_findpool(bt, page_no, idx) ) {
1200 __sync_fetch_and_add(&pool->pin, 1);
1202 _InterlockedIncrement16 (&pool->pin);
1204 bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
1209 // allocate a new pool node
1210 // and add to hash table
1213 slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
1215 slot = _InterlockedIncrement16 (&bt->mgr->poolcnt) - 1;
1218 if( ++slot < bt->mgr->poolmax ) {
1219 pool = bt->mgr->pool + slot;
1222 if( bt_mapsegment(bt, pool, page_no) )
1225 bt_linkhash(bt, pool, page_no, idx);
1227 __sync_fetch_and_add(&pool->pin, 1);
1229 _InterlockedIncrement16 (&pool->pin);
1231 bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
1235 // pool table is full
1236 // find best pool entry to evict
1239 __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
1241 _InterlockedDecrement16 (&bt->mgr->poolcnt);
1246 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
1248 victim = _InterlockedIncrement16 (&bt->mgr->evicted) - 1;
1250 victim %= bt->mgr->hashsize;
1252 // try to get write lock
1253 // skip entry if not obtained
1255 if( !bt_spinwritetry (&bt->mgr->latch[victim]) )
1258 // if pool entry is empty
1259 // or any pages are pinned
1262 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
1263 bt_spinreleasewrite (&bt->mgr->latch[victim], 1);
1267 // unlink victim pool node from hash table
1269 if( node = pool->hashprev )
1270 node->hashnext = pool->hashnext;
1271 else if( node = pool->hashnext )
1272 bt->mgr->hash[victim] = node->slot;
1274 bt->mgr->hash[victim] = 0;
1276 if( node = pool->hashnext )
1277 node->hashprev = pool->hashprev;
1279 bt_spinreleasewrite (&bt->mgr->latch[victim], 1);
1281 // remove old file mapping
1283 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1285 FlushViewOfFile(pool->map, 0);
1286 UnmapViewOfFile(pool->map);
1287 CloseHandle(pool->hmap);
1291 // create new pool mapping
1292 // and link into hash table
1294 if( bt_mapsegment(bt, pool, page_no) )
1297 bt_linkhash(bt, pool, page_no, idx);
1299 __sync_fetch_and_add(&pool->pin, 1);
1301 _InterlockedIncrement16 (&pool->pin);
1303 bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
1308 // place write, read, or parent lock on requested page_no.
1310 void bt_lockpage(BtLock mode, BtLatchSet *set)
1314 bt_spinreadlock (set->readwr, 0);
1317 bt_spinwritelock (set->readwr, 0);
1320 bt_spinreadlock (set->access, 0);
1323 bt_spinwritelock (set->access, 0);
1326 bt_spinwritelock (set->parent, 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);
1354 // allocate a new page and write page into it
1356 uid bt_newpage(BtDb *bt, BtPage page)
1364 // lock allocation page
1366 bt_spinwritelock(bt->mgr->latchmgr->lock, 0);
1368 // use empty chain first
1369 // else allocate empty page
1371 if( new_page = bt_getid(bt->mgr->latchmgr->alloc[1].right) ) {
1372 if( pool = bt_pinpool (bt, new_page) )
1373 pmap = bt_page (bt, pool, new_page);
1376 bt_putid(bt->mgr->latchmgr->alloc[1].right, bt_getid(pmap->right));
1377 bt_unpinpool (pool);
1380 new_page = bt_getid(bt->mgr->latchmgr->alloc->right);
1381 bt_putid(bt->mgr->latchmgr->alloc->right, new_page+1);
1385 if ( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1386 return bt->err = BTERR_wrt, 0;
1388 // if writing first page of pool block, zero last page in the block
1390 if ( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1392 // use zero buffer to write zeros
1393 memset(bt->zero, 0, bt->mgr->page_size);
1394 if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1395 return bt->err = BTERR_wrt, 0;
1398 // bring new page into pool and copy page.
1399 // this will extend the file into the new pages.
1401 if( pool = bt_pinpool (bt, new_page) )
1402 pmap = bt_page (bt, pool, new_page);
1406 memcpy(pmap, page, bt->mgr->page_size);
1407 bt_unpinpool (pool);
1409 // unlock allocation latch and return new page no
1411 bt_spinreleasewrite(bt->mgr->latchmgr->lock, 0);
1415 // find slot in page for given key at a given level
1417 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1419 uint diff, higher = bt->page->cnt, low = 1, slot;
1422 // make stopper key an infinite fence value
1424 if( bt_getid (bt->page->right) )
1429 // low is the next candidate, higher is already
1430 // tested as .ge. the given key, loop ends when they meet
1432 while( diff = higher - low ) {
1433 slot = low + ( diff >> 1 );
1434 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1437 higher = slot, good++;
1440 // return zero if key is on right link page
1442 return good ? higher : 0;
1445 // find and load page at given level for given key
1446 // leave page rd or wr locked as requested
1448 int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, uint lock)
1450 uid page_no = ROOT_page, prevpage = 0;
1451 BtLatchSet *set, *prevset;
1452 uint drill = 0xff, slot;
1453 uint mode, prevmode;
1457 // start at root of btree and drill down
1462 // determine lock mode of drill level
1463 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1465 bt->set = bt_pinlatch (bt, page_no);
1466 bt->page_no = page_no;
1468 // pin page contents
1470 if( bt->pool = bt_pinpool (bt, page_no) )
1471 bt->page = bt_page (bt, bt->pool, page_no);
1475 // obtain access lock using lock chaining with Access mode
1477 if( page_no > ROOT_page )
1478 bt_lockpage(BtLockAccess, bt->set);
1480 // release & unpin parent page
1483 bt_unlockpage(prevmode, prevset);
1484 bt_unpinlatch (prevset);
1485 bt_unpinpool (prevpool);
1489 // obtain read lock using lock chaining
1491 bt_lockpage(mode, bt->set);
1493 if( page_no > ROOT_page )
1494 bt_unlockpage(BtLockAccess, bt->set);
1496 // re-read and re-lock root after determining actual level of root
1498 if( bt->page->lvl != drill) {
1499 if ( bt->page_no != ROOT_page )
1500 return bt->err = BTERR_struct, 0;
1502 drill = bt->page->lvl;
1504 if( lock == BtLockWrite && drill == lvl ) {
1505 bt_unlockpage(mode, bt->set);
1506 bt_unpinlatch (bt->set);
1507 bt_unpinpool (bt->pool);
1512 // find key on page at this level
1513 // and descend to requested level
1515 if( slot = bt_findslot (bt, key, len) ) {
1517 return bt->parent = parent, slot;
1519 while( slotptr(bt->page, slot)->dead )
1520 if( slot++ < bt->page->cnt )
1523 page_no = bt_getid(bt->page->right);
1528 page_no = bt_getid(slotptr(bt->page, slot)->id);
1533 // or slide right into next page
1536 page_no = bt_getid(bt->page->right);
1540 // continue down / right using overlapping locks
1541 // to protect pages being split.
1544 prevpage = bt->page_no;
1545 prevpool = bt->pool;
1550 // return error on end of right chain
1552 bt->err = BTERR_struct;
1553 return 0; // return error
1556 // remove empty page from the B-tree
1557 // by pulling our right node left over ourselves
1559 // call with bt->page, etc, set to page's locked parent
1560 // returns with page locked.
1562 BTERR bt_mergeright (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no, uint lvl, uint slot)
1564 BtLatchSet *rset, *pset, *rpset;
1565 BtPool *rpool, *ppool, *rppool;
1566 BtPage rpage, ppage, rppage;
1567 uid right, parent, rparent;
1571 // cache node's parent page
1573 parent = bt->page_no;
1578 // lock and map our right page
1579 // it cannot be NULL because of the stopper
1580 // in the last right page
1582 bt_lockpage (BtLockWrite, set);
1584 // if we aren't dead yet
1589 if( right = bt_getid (page->right) )
1590 if( rpool = bt_pinpool (bt, right) )
1591 rpage = bt_page (bt, rpool, right);
1595 return bt->err = BTERR_struct;
1597 rset = bt_pinlatch (bt, right);
1599 // find our right neighbor
1601 if( ppage->act > 1 ) {
1602 for( idx = slot; idx++ < ppage->cnt; )
1603 if( !slotptr(ppage, idx)->dead )
1606 if( idx > ppage->cnt )
1607 return bt->err = BTERR_struct;
1609 // redirect right neighbor in parent to left node
1611 bt_putid(slotptr(ppage,idx)->id, page_no);
1614 // if parent has only our deleted page, e.g. no right neighbor
1615 // prepare to merge parent itself
1617 if( ppage->act == 1 ) {
1618 if( rparent = bt_getid (ppage->right) )
1619 if( rppool = bt_pinpool (bt, rparent) )
1620 rppage = bt_page (bt, rppool, rparent);
1624 return bt->err = BTERR_struct;
1626 rpset = bt_pinlatch (bt, rparent);
1627 bt_lockpage (BtLockWrite, rpset);
1629 // find our right neighbor on right parent page
1631 for( idx = 0; idx++ < rppage->cnt; )
1632 if( !slotptr(rppage, idx)->dead ) {
1633 bt_putid (slotptr(rppage, idx)->id, page_no);
1637 if( idx > rppage->cnt )
1638 return bt->err = BTERR_struct;
1641 // now that there are no more pointers to our right node
1642 // we can wait for delete lock on it
1644 bt_lockpage(BtLockDelete, rset);
1645 bt_lockpage(BtLockWrite, rset);
1647 // pull contents of right page into our empty page
1649 memcpy (page, rpage, bt->mgr->page_size);
1651 // ready to release right parent lock
1652 // now that we have a new page in place
1654 if( ppage->act == 1 ) {
1655 bt_unlockpage (BtLockWrite, rpset);
1656 bt_unpinlatch (rpset);
1657 bt_unpinpool (rppool);
1660 // add killed right block to free chain
1663 bt_spinwritelock(bt->mgr->latchmgr->lock, 0);
1665 // store free chain in allocation page second right
1667 bt_putid(rpage->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1668 bt_putid(bt->mgr->latchmgr->alloc[1].right, right);
1670 // unlock latch mgr and right page
1672 bt_unlockpage(BtLockDelete, rset);
1673 bt_unlockpage(BtLockWrite, rset);
1674 bt_unpinlatch (rset);
1675 bt_unpinpool (rpool);
1677 bt_spinreleasewrite(bt->mgr->latchmgr->lock, 0);
1679 // delete our obsolete fence key from our parent
1681 slotptr(ppage, slot)->dead = 1;
1684 // if our parent now empty
1685 // remove it from the tree
1687 if( ppage->act-- == 1 )
1688 if( bt_mergeleft (bt, ppage, ppool, pset, parent, lvl+1) )
1692 bt_unlockpage (BtLockWrite, pset);
1693 bt_unpinlatch (pset);
1694 bt_unpinpool (ppool);
1700 // remove empty page from the B-tree
1701 // try merging left first. If no left
1702 // sibling, then merge right.
1704 // call with page loaded and locked,
1705 // return with page locked.
1707 BTERR bt_mergeleft (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no, uint lvl)
1709 unsigned char fencekey[256], postkey[256];
1710 uint slot, idx, postfence = 0;
1711 BtLatchSet *lset, *pset;
1712 BtPool *lpool, *ppool;
1713 BtPage lpage, ppage;
1717 ptr = keyptr(page, page->cnt);
1718 memcpy(fencekey, ptr, ptr->len + 1);
1719 bt_unlockpage (BtLockWrite, set);
1721 // load and lock our parent
1724 if( !(slot = bt_loadpage (bt, fencekey+1, *fencekey, lvl+1, BtLockWrite)) )
1727 parent = bt->page_no;
1732 // wait until we are posted in our parent
1735 bt_unlockpage (BtLockWrite, pset);
1736 bt_unpinlatch (pset);
1737 bt_unpinpool (ppool);
1746 // find our left neighbor in our parent page
1748 for( idx = slot; --idx; )
1749 if( !slotptr(ppage, idx)->dead )
1752 // if no left neighbor, do right merge
1755 return bt_mergeright (bt, page, pool, set, page_no, lvl, slot);
1757 // lock and map our left neighbor's page
1759 left = bt_getid (slotptr(ppage, idx)->id);
1761 if( lpool = bt_pinpool (bt, left) )
1762 lpage = bt_page (bt, lpool, left);
1766 lset = bt_pinlatch (bt, left);
1767 bt_lockpage(BtLockWrite, lset);
1769 // wait until sibling is in our parent
1771 if( bt_getid (lpage->right) != page_no ) {
1772 bt_unlockpage (BtLockWrite, pset);
1773 bt_unpinlatch (pset);
1774 bt_unpinpool (ppool);
1775 bt_unlockpage (BtLockWrite, lset);
1776 bt_unpinlatch (lset);
1777 bt_unpinpool (lpool);
1786 // since our page will have no more pointers to it,
1787 // obtain Delete lock and wait for write locks to clear
1789 bt_lockpage(BtLockDelete, set);
1790 bt_lockpage(BtLockWrite, set);
1792 // if we aren't dead yet,
1793 // get ready for exit
1796 bt_unlockpage(BtLockDelete, set);
1797 bt_unlockpage(BtLockWrite, lset);
1798 bt_unpinlatch (lset);
1799 bt_unpinpool (lpool);
1803 // are we are the fence key for our parent?
1804 // if so, grab our old fence key
1806 if( postfence = slot == ppage->cnt ) {
1807 ptr = keyptr (ppage, ppage->cnt);
1808 memcpy(fencekey, ptr, ptr->len + 1);
1809 memset(slotptr(ppage, ppage->cnt), 0, sizeof(BtSlot));
1811 // clear out other dead slots
1813 while( --ppage->cnt )
1814 if( slotptr(ppage, ppage->cnt)->dead )
1815 memset(slotptr(ppage, ppage->cnt), 0, sizeof(BtSlot));
1819 ptr = keyptr (ppage, ppage->cnt);
1820 memcpy(postkey, ptr, ptr->len + 1);
1822 slotptr(ppage,slot)->dead = 1;
1827 // push our right neighbor pointer to our left
1829 memcpy (lpage->right, page->right, BtId);
1831 // add ourselves to free chain
1834 bt_spinwritelock(bt->mgr->latchmgr->lock, 0);
1836 // store free chain in allocation page second right
1837 bt_putid(page->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1838 bt_putid(bt->mgr->latchmgr->alloc[1].right, page_no);
1840 // unlock latch mgr and pages
1842 bt_spinreleasewrite(bt->mgr->latchmgr->lock, 0);
1843 bt_unlockpage(BtLockWrite, lset);
1844 bt_unpinlatch (lset);
1845 bt_unpinpool (lpool);
1847 // release our node's delete lock
1849 bt_unlockpage(BtLockDelete, set);
1852 bt_unlockpage (BtLockWrite, pset);
1853 bt_unpinpool (ppool);
1855 // do we need to post parent's fence key in its parent?
1857 if( !postfence || parent == ROOT_page ) {
1858 bt_unpinlatch (pset);
1863 // interlock parent fence post
1865 bt_lockpage (BtLockParent, pset);
1867 // load parent's parent page
1869 if( !(slot = bt_loadpage (bt, fencekey+1, *fencekey, lvl+2, BtLockWrite)) )
1872 if( !(slot = bt_cleanpage (bt, bt->page, *fencekey, slot)) )
1873 if( bt_splitpage (bt, bt->page, bt->pool, bt->set, bt->page_no) )
1880 page->min -= *postkey + 1;
1881 ((unsigned char *)page)[page->min] = *postkey;
1882 memcpy ((unsigned char *)page + page->min +1, postkey + 1, *postkey );
1883 slotptr(page, slot)->off = page->min;
1885 bt_unlockpage (BtLockParent, pset);
1886 bt_unpinlatch (pset);
1888 bt_unlockpage (BtLockWrite, bt->set);
1889 bt_unpinlatch (bt->set);
1890 bt_unpinpool (bt->pool);
1896 // find and delete key on page by marking delete flag bit
1897 // if page becomes empty, delete it from the btree
1899 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len)
1908 if( !(slot = bt_loadpage (bt, key, len, 0, BtLockWrite)) )
1911 page_no = bt->page_no;
1916 // if key is found delete it, otherwise ignore request
1918 ptr = keyptr(page, slot);
1920 if( bt->found = !keycmp (ptr, key, len) )
1921 if( bt->found = slotptr(page, slot)->dead == 0 ) {
1922 slotptr(page,slot)->dead = 1;
1923 if( slot < page->cnt )
1926 if( bt_mergeleft (bt, page, pool, set, page_no, 0) )
1930 bt_unlockpage(BtLockWrite, set);
1931 bt_unpinlatch (set);
1932 bt_unpinpool (pool);
1936 // find key in leaf level and return row-id
1938 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1944 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1945 ptr = keyptr(bt->page, slot);
1949 // if key exists, return row-id
1950 // otherwise return 0
1952 if( slot <= bt->page->cnt && !keycmp (ptr, key, len) )
1953 id = bt_getid(slotptr(bt->page,slot)->id);
1957 bt_unlockpage (BtLockRead, bt->set);
1958 bt_unpinlatch (bt->set);
1959 bt_unpinpool (bt->pool);
1963 // check page for space available,
1964 // clean if necessary and return
1965 // 0 - page needs splitting
1966 // >0 new slot value
1968 uint bt_cleanpage(BtDb *bt, BtPage page, uint amt, uint slot)
1970 uint nxt = bt->mgr->page_size;
1971 uint cnt = 0, idx = 0;
1972 uint max = page->cnt;
1976 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1979 // skip cleanup if nothing to reclaim
1984 memcpy (bt->frame, page, bt->mgr->page_size);
1986 // skip page info and set rest of page to zero
1988 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1992 // try cleaning up page first
1994 // always leave fence key in the array
1995 // otherwise, remove deleted key
1997 while( cnt++ < max ) {
2000 if( cnt < max && slotptr(bt->frame,cnt)->dead )
2005 key = keyptr(bt->frame, cnt);
2006 nxt -= key->len + 1;
2007 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2010 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
2011 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
2013 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2014 slotptr(page, idx)->off = nxt;
2020 // see if page has enough space now, or does it need splitting?
2022 if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
2028 // add key to current page
2029 // page must already be writelocked
2031 void bt_addkeytopage (BtDb *bt, BtPage page, uint slot, unsigned char *key, uint len, uid id, uint tod)
2035 // find next available dead slot and copy key onto page
2037 for( idx = slot; idx < page->cnt; idx++ )
2038 if( slotptr(page, idx)->dead )
2041 if( idx == page->cnt )
2046 // now insert key into array before slot
2049 *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
2051 page->min -= len + 1;
2052 ((unsigned char *)page)[page->min] = len;
2053 memcpy ((unsigned char *)page + page->min +1, key, len );
2055 bt_putid(slotptr(page,slot)->id, id);
2056 slotptr(page, slot)->off = page->min;
2057 slotptr(page, slot)->tod = tod;
2058 slotptr(page, slot)->dead = 0;
2061 BTERR bt_splitroot(BtDb *bt, unsigned char *leftkey, uid page_no2)
2063 uint nxt = bt->mgr->page_size;
2064 BtPage root = bt->page;
2067 // Obtain an empty page to use, and copy the current
2068 // root contents into it
2070 if( !(new_page = bt_newpage(bt, root)) )
2073 // preserve the page info at the bottom
2074 // and set rest to zero
2076 memset(root+1, 0, bt->mgr->page_size - sizeof(*root));
2078 // insert first key on newroot page
2080 nxt -= *leftkey + 1;
2081 memcpy ((unsigned char *)root + nxt, leftkey, *leftkey + 1);
2082 bt_putid(slotptr(root, 1)->id, new_page);
2083 slotptr(root, 1)->off = nxt;
2085 // insert second key (stopper key) on newroot page
2086 // and increase the root height
2089 *((unsigned char *)root + nxt) = 2;
2090 memset ((unsigned char *)root + nxt + 1, 0xff, 2);
2091 bt_putid(slotptr(root, 2)->id, page_no2);
2092 slotptr(root, 2)->off = nxt;
2094 bt_putid(root->right, 0);
2095 root->min = nxt; // reset lowest used offset and key count
2100 // release and unpin root (bt->page)
2102 bt_unlockpage(BtLockWrite, bt->set);
2103 bt_unpinlatch (bt->set);
2104 bt_unpinpool (bt->pool);
2108 // split already locked full node
2109 // return unlocked and unpinned.
2111 BTERR bt_splitpage (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no)
2113 uint slot, cnt, idx, max, nxt = bt->mgr->page_size;
2114 unsigned char rightkey[256], leftkey[256];
2115 uint tod = time(NULL);
2116 uint lvl = page->lvl;
2120 // initialize frame buffer for right node
2122 memset (bt->frame, 0, bt->mgr->page_size);
2127 // split higher half of keys to bt->frame
2129 while( cnt++ < max ) {
2130 key = keyptr(page, cnt);
2131 nxt -= key->len + 1;
2132 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
2133 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
2134 if( !(slotptr(bt->frame, idx)->dead = slotptr(page, cnt)->dead) )
2136 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
2137 slotptr(bt->frame, idx)->off = nxt;
2140 // transfer right link node to new right node
2142 if( page_no > ROOT_page )
2143 memcpy (bt->frame->right, page->right, BtId);
2145 bt->frame->bits = bt->mgr->page_bits;
2146 bt->frame->min = nxt;
2147 bt->frame->cnt = idx;
2148 bt->frame->lvl = lvl;
2150 // get new free page and write right frame to it.
2152 if( !(new_page = bt_newpage(bt, bt->frame)) )
2155 // remember fence key for new right page to add
2156 // as right sibling to the left node
2158 key = keyptr(bt->frame, idx);
2159 memcpy (rightkey, key, key->len + 1);
2161 // update lower keys to continue in old page
2163 memcpy (bt->frame, page, bt->mgr->page_size);
2164 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
2165 nxt = bt->mgr->page_size;
2171 // assemble page of smaller keys
2172 // to remain in the old page
2174 while( cnt++ < max / 2 ) {
2175 key = keyptr(bt->frame, cnt);
2176 nxt -= key->len + 1;
2177 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2178 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
2179 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
2181 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2182 slotptr(page, idx)->off = nxt;
2185 // finalize left page and save fence key
2187 memcpy(leftkey, key, key->len + 1);
2191 // link new right page
2193 bt_putid (page->right, new_page);
2195 // if current page is the root page, split it
2197 if( page_no == ROOT_page )
2198 return bt_splitroot (bt, leftkey, new_page);
2200 // obtain ParentModification lock for current page
2202 bt_lockpage (BtLockParent, set);
2204 // release wr lock on our page.
2205 // this will keep out another SMO
2207 bt_unlockpage (BtLockWrite, set);
2209 // insert key for old page (lower keys)
2211 if( bt_insertkey (bt, leftkey + 1, *leftkey, page_no, tod, lvl + 1) )
2214 // switch old parent key from us to our right page
2216 if( bt_insertkey (bt, rightkey + 1, *rightkey, new_page, tod, lvl + 1) )
2221 bt_unlockpage (BtLockParent, set);
2222 bt_unpinlatch (set);
2223 bt_unpinpool (pool);
2227 // Insert new key into the btree at given level.
2229 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod, uint lvl)
2236 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
2237 ptr = keyptr(bt->page, slot);
2241 bt->err = BTERR_ovflw;
2245 // if key already exists, update id and return
2249 if( !keycmp (ptr, key, len) ) {
2250 if( slotptr(page, slot)->dead )
2252 slotptr(page, slot)->dead = 0;
2253 slotptr(page, slot)->tod = tod;
2254 bt_putid(slotptr(page,slot)->id, id);
2255 bt_unlockpage(BtLockWrite, bt->set);
2256 bt_unpinlatch (bt->set);
2257 bt_unpinpool (bt->pool);
2261 // check if page has enough space
2263 if( slot = bt_cleanpage (bt, bt->page, len, slot) )
2266 if( bt_splitpage (bt, bt->page, bt->pool, bt->set, bt->page_no) )
2270 bt_addkeytopage (bt, bt->page, slot, key, len, id, tod);
2272 bt_unlockpage (BtLockWrite, bt->set);
2273 bt_unpinlatch (bt->set);
2274 bt_unpinpool (bt->pool);
2278 // cache page of keys into cursor and return starting slot for given key
2280 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2284 // cache page for retrieval
2285 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
2286 memcpy (bt->cursor, bt->page, bt->mgr->page_size);
2288 bt->cursor_page = bt->page_no;
2290 bt_unlockpage(BtLockRead, bt->set);
2291 bt_unpinlatch (bt->set);
2292 bt_unpinpool (bt->pool);
2296 // return next slot for cursor page
2297 // or slide cursor right into next page
2299 uint bt_nextkey (BtDb *bt, uint slot)
2307 right = bt_getid(bt->cursor->right);
2308 while( slot++ < bt->cursor->cnt )
2309 if( slotptr(bt->cursor,slot)->dead )
2311 else if( right || (slot < bt->cursor->cnt) )
2319 bt->cursor_page = right;
2320 if( pool = bt_pinpool (bt, right) )
2321 page = bt_page (bt, pool, right);
2325 set = bt_pinlatch (bt, right);
2326 bt_lockpage(BtLockRead, set);
2328 memcpy (bt->cursor, page, bt->mgr->page_size);
2330 bt_unlockpage(BtLockRead, set);
2331 bt_unpinlatch (set);
2332 bt_unpinpool (pool);
2339 BtKey bt_key(BtDb *bt, uint slot)
2341 return keyptr(bt->cursor, slot);
2344 uid bt_uid(BtDb *bt, uint slot)
2346 return bt_getid(slotptr(bt->cursor,slot)->id);
2349 uint bt_tod(BtDb *bt, uint slot)
2351 return slotptr(bt->cursor,slot)->tod;
2357 void bt_latchaudit (BtDb *bt)
2359 ushort idx, hashidx;
2366 for( idx = 1; idx < bt->mgr->latchmgr->latchdeployed; idx++ ) {
2367 set = bt->mgr->latchsets + idx;
2368 if( *(ushort *)set->readwr || *(ushort *)set->access || *(ushort *)set->parent ) {
2369 fprintf(stderr, "latchset %d locked for page %6x\n", idx, set->page_no);
2370 *(ushort *)set->readwr = 0;
2371 *(ushort *)set->access = 0;
2372 *(ushort *)set->parent = 0;
2375 fprintf(stderr, "latchset %d pinned\n", idx);
2380 for( hashidx = 0; hashidx < bt->mgr->latchmgr->latchhash; hashidx++ ) {
2381 if( *(uint *)bt->mgr->latchmgr->table[hashidx].latch )
2382 fprintf(stderr, "latchmgr locked\n");
2383 if( idx = bt->mgr->latchmgr->table[hashidx].slot ) do {
2384 set = bt->mgr->latchsets + idx;
2385 if( *(uint *)set->readwr || *(ushort *)set->access || *(ushort *)set->parent )
2386 fprintf(stderr, "latchset %d locked\n", idx);
2387 if( set->hash != hashidx )
2388 fprintf(stderr, "latchset %d wrong hashidx\n", idx);
2390 fprintf(stderr, "latchset %d pinned\n", idx);
2391 } while( idx = set->next );
2393 page_no = bt_getid(bt->mgr->latchmgr->alloc[1].right);
2396 fprintf(stderr, "free: %.6x\n", (uint)page_no);
2397 pool = bt_pinpool (bt, page_no);
2398 page = bt_page (bt, pool, page_no);
2399 page_no = bt_getid(page->right);
2400 bt_unpinpool (pool);
2412 // standalone program to index file of keys
2413 // then list them onto std-out
2416 void *index_file (void *arg)
2418 uint __stdcall index_file (void *arg)
2421 int line = 0, found = 0, cnt = 0;
2422 uid next, page_no = LEAF_page; // start on first page of leaves
2423 unsigned char key[256];
2424 ThreadArg *args = arg;
2425 int ch, len = 0, slot;
2434 bt = bt_open (args->mgr);
2437 switch(args->type | 0x20)
2440 fprintf(stderr, "started latch mgr audit\n");
2442 fprintf(stderr, "finished latch mgr audit\n");
2446 fprintf(stderr, "started indexing for %s\n", args->infile);
2447 if( in = fopen (args->infile, "rb") )
2448 while( ch = getc(in), ch != EOF )
2453 if( args->num == 1 )
2454 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2456 else if( args->num )
2457 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2459 if( bt_insertkey (bt, key, len, line, *tod, 0) )
2460 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2463 else if( len < 255 )
2465 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
2469 fprintf(stderr, "started deleting keys for %s\n", args->infile);
2470 if( in = fopen (args->infile, "rb") )
2471 while( ch = getc(in), ch != EOF )
2475 if( args->num == 1 )
2476 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2478 else if( args->num )
2479 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2481 if( bt_deletekey (bt, key, len) )
2482 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2485 else if( len < 255 )
2487 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2491 fprintf(stderr, "started finding keys for %s\n", args->infile);
2492 if( in = fopen (args->infile, "rb") )
2493 while( ch = getc(in), ch != EOF )
2497 if( args->num == 1 )
2498 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2500 else if( args->num )
2501 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2503 if( bt_findkey (bt, key, len) )
2506 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2509 else if( len < 255 )
2511 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2517 fprintf(stderr, "started reading\n");
2519 if( slot = bt_startkey (bt, key, len) )
2522 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
2524 while( slot = bt_nextkey (bt, slot) ) {
2525 ptr = bt_key(bt, slot);
2526 fwrite (ptr->key, ptr->len, 1, stdout);
2527 fputc ('\n', stdout);
2533 fprintf(stderr, "started reading\n");
2536 if( pool = bt_pinpool (bt, page_no) )
2537 page = bt_page (bt, pool, page_no);
2540 set = bt_pinlatch (bt, page_no);
2541 bt_lockpage (BtLockRead, set);
2543 next = bt_getid (page->right);
2544 bt_unlockpage (BtLockRead, set);
2545 bt_unpinlatch (set);
2546 bt_unpinpool (pool);
2547 } while( page_no = next );
2549 cnt--; // remove stopper key
2550 fprintf(stderr, " Total keys read %d\n", cnt);
2562 typedef struct timeval timer;
2564 int main (int argc, char **argv)
2566 int idx, cnt, len, slot, err;
2567 int segsize, bits = 16;
2572 time_t start[1], stop[1];
2585 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]);
2586 fprintf (stderr, " where page_bits is the page size in bits\n");
2587 fprintf (stderr, " mapped_segments is the number of mmap segments in buffer pool\n");
2588 fprintf (stderr, " seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2589 fprintf (stderr, " line_numbers = 1 to append line numbers to keys\n");
2590 fprintf (stderr, " src_file1 thru src_filen are files of keys separated by newline\n");
2595 gettimeofday(&start, NULL);
2601 bits = atoi(argv[3]);
2604 poolsize = atoi(argv[4]);
2607 fprintf (stderr, "Warning: no mapped_pool\n");
2609 if( poolsize > 65535 )
2610 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2613 segsize = atoi(argv[5]);
2615 segsize = 4; // 16 pages per mmap segment
2618 num = atoi(argv[6]);
2622 threads = malloc (cnt * sizeof(pthread_t));
2624 threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2626 args = malloc (cnt * sizeof(ThreadArg));
2628 mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2631 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2637 for( idx = 0; idx < cnt; idx++ ) {
2638 args[idx].infile = argv[idx + 7];
2639 args[idx].type = argv[2][0];
2640 args[idx].mgr = mgr;
2641 args[idx].num = num;
2642 args[idx].idx = idx;
2644 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2645 fprintf(stderr, "Error creating thread %d\n", err);
2647 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2651 // wait for termination
2654 for( idx = 0; idx < cnt; idx++ )
2655 pthread_join (threads[idx], NULL);
2656 gettimeofday(&stop, NULL);
2657 real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2659 WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2661 for( idx = 0; idx < cnt; idx++ )
2662 CloseHandle(threads[idx]);
2665 real_time = 1000 * (*stop - *start);
2667 fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);