1 // foster btree version g
4 // author: karl malbrain, malbrain@cal.berkeley.edu
7 This work, including the source code, documentation
8 and related data, is placed into the public domain.
10 The orginal author is Karl Malbrain.
12 THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY
13 OF ANY KIND, NOT EVEN THE IMPLIED WARRANTY OF
14 MERCHANTABILITY. THE AUTHOR OF THIS SOFTWARE,
15 ASSUMES _NO_ RESPONSIBILITY FOR ANY CONSEQUENCE
16 RESULTING FROM THE USE, MODIFICATION, OR
17 REDISTRIBUTION OF THIS SOFTWARE.
20 // Please see the project home page for documentation
21 // code.google.com/p/high-concurrency-btree
23 #define _FILE_OFFSET_BITS 64
24 #define _LARGEFILE64_SOURCE
28 #include <linux/futex.h>
43 #define WIN32_LEAN_AND_MEAN
56 typedef unsigned long long uid;
59 typedef unsigned long long off64_t;
60 typedef unsigned short ushort;
61 typedef unsigned int uint;
64 #define BT_ro 0x6f72 // ro
65 #define BT_rw 0x7772 // rw
67 #define BT_latchtable 128 // number of latch manager slots
69 #define BT_maxbits 24 // maximum page size in bits
70 #define BT_minbits 9 // minimum page size in bits
71 #define BT_minpage (1 << BT_minbits) // minimum page size
72 #define BT_maxpage (1 << BT_maxbits) // maximum page size
75 There are five lock types for each node in three independent sets:
76 1. (set 1) AccessIntent: Sharable. Going to Read the node. Incompatible with NodeDelete.
77 2. (set 1) NodeDelete: Exclusive. About to release the node. Incompatible with AccessIntent.
78 3. (set 2) ReadLock: Sharable. Read the node. Incompatible with WriteLock.
79 4. (set 2) WriteLock: Exclusive. Modify the node. Incompatible with ReadLock and other WriteLocks.
80 5. (set 3) ParentLock: Exclusive. Have parent adopt/delete maximum foster child from the node.
91 // Define the length of the page and key pointers
95 // Page key slot definition.
97 // If BT_maxbits is 15 or less, you can save 4 bytes
98 // for each key stored by making the first two uints
99 // into ushorts. You can also save 4 bytes by removing
100 // the tod field from the key.
102 // Keys are marked dead, but remain on the page until
103 // it cleanup is called. The fence key (highest key) for
104 // the page is always present, even after cleanup.
107 uint off:BT_maxbits; // page offset for key start
108 uint dead:1; // set for deleted key
109 uint tod; // time-stamp for key
110 unsigned char id[BtId]; // id associated with key
113 // The key structure occupies space at the upper end of
114 // each page. It's a length byte followed by the value
119 unsigned char key[1];
122 // The first part of an index page.
123 // It is immediately followed
124 // by the BtSlot array of keys.
126 typedef struct Page {
127 volatile uint cnt; // count of keys in page
128 volatile uint act; // count of active keys
129 volatile uint min; // next key offset
130 volatile uint foster; // count of foster children
131 unsigned char bits; // page size in bits
132 unsigned char lvl:7; // level of page
133 unsigned char dirty:1; // page needs to be cleaned
134 unsigned char right[BtId]; // page number to right
137 // mode & definition for latch implementation
140 Mutex = 1 << 0, // the mutex bit
141 Write = 1 << 1, // the writers bit
142 Share = 1 << 2, // reader count
143 PendRd = 1 << 12, // reader contended count
144 PendWr = 1 << 22 // writer contended count
148 QueRd = 1, // reader queue
149 QueWr = 2 // writer queue
152 // share is count of read accessors
153 // grant write lock when share == 0
156 volatile uint mutex:1; // 1 = busy
157 volatile uint write:1; // 1 = exclusive
158 volatile uint share:10; // count of readers holding locks
159 volatile uint readwait:10; // count of readers waiting
160 volatile uint writewait:10; // count of writers waiting
163 // hash table entries
167 volatile ushort slot; // Latch table entry at head of chain
170 // latch manager table structure
173 BtLatch readwr[1]; // read/write page lock
174 BtLatch access[1]; // Access Intent/Page delete
175 BtLatch parent[1]; // adoption of foster children
176 BtLatch busy[1]; // slot is being moved between chains
177 volatile ushort next; // next entry in hash table chain
178 volatile ushort prev; // prev entry in hash table chain
179 volatile ushort pin; // number of outstanding locks
180 volatile ushort hash; // hash slot entry is under
181 volatile uid page_no; // latch set page number
184 // The memory mapping pool table buffer manager entry
187 unsigned long long int lru; // number of times accessed
188 uid basepage; // mapped base page number
189 char *map; // mapped memory pointer
190 ushort pin; // mapped page pin counter
191 ushort slot; // slot index in this array
192 void *hashprev; // previous pool entry for the same hash idx
193 void *hashnext; // next pool entry for the same hash idx
195 HANDLE hmap; // Windows memory mapping handle
199 // structure for latch manager on ALLOC_page
202 struct Page alloc[2]; // next & free page_nos in right ptr
203 BtLatch lock[1]; // allocation area lite latch
204 ushort latchdeployed; // highest number of latch entries deployed
205 ushort nlatchpage; // number of latch pages at BT_latch
206 ushort latchtotal; // number of page latch entries
207 ushort latchhash; // number of latch hash table slots
208 ushort latchvictim; // next latch entry to examine
209 BtHashEntry table[0]; // the hash table
212 // The object structure for Btree access
215 uint page_size; // page size
216 uint page_bits; // page size in bits
217 uint seg_bits; // seg size in pages in bits
218 uint mode; // read-write mode
221 char *pooladvise; // bit maps for pool page advisements
225 ushort poolcnt; // highest page pool node in use
226 ushort poolmax; // highest page pool node allocated
227 ushort poolmask; // total number of pages in mmap segment - 1
228 ushort hashsize; // size of Hash Table for pool entries
229 ushort evicted; // last evicted hash table slot
230 ushort *hash; // hash table of pool entries
231 BtPool *pool; // memory pool page segments
232 BtLatch *latch; // latches for pool hash slots
233 BtLatchMgr *latchmgr; // mapped latch page from allocation page
234 BtLatchSet *latchsets; // mapped latch set from latch pages
236 HANDLE halloc; // allocation and latch table handle
241 BtMgr *mgr; // buffer manager for thread
242 BtPage cursor; // cached frame for start/next (never mapped)
243 BtPage frame; // spare frame for the page split (never mapped)
244 BtPage zero; // page frame for zeroes at end of file
245 BtPage page; // current page
246 uid page_no; // current page number
247 uid cursor_page; // current cursor page number
248 BtLatchSet *set; // current page latch set
249 BtPool *pool; // current page pool
250 unsigned char *mem; // frame, cursor, page memory buffer
251 int found; // last delete was found
252 int err; // last error
267 extern void bt_close (BtDb *bt);
268 extern BtDb *bt_open (BtMgr *mgr);
269 extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod, uint lvl);
270 extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len);
271 extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
272 extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
273 extern uint bt_nextkey (BtDb *bt, uint slot);
276 extern BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolsize, uint segsize, uint hashsize);
277 void bt_mgrclose (BtMgr *mgr);
279 // Helper functions to return cursor slot values
281 extern BtKey bt_key (BtDb *bt, uint slot);
282 extern uid bt_uid (BtDb *bt, uint slot);
283 extern uint bt_tod (BtDb *bt, uint slot);
285 // BTree page number constants
286 #define ALLOC_page 0 // allocation & lock manager hash table
287 #define ROOT_page 1 // root of the btree
288 #define LEAF_page 2 // first page of leaves
289 #define LATCH_page 3 // pages for lock manager
291 // Number of levels to create in a new BTree
295 // The page is allocated from low and hi ends.
296 // The key offsets and row-id's are allocated
297 // from the bottom, while the text of the key
298 // is allocated from the top. When the two
299 // areas meet, the page is split into two.
301 // A key consists of a length byte, two bytes of
302 // index number (0 - 65534), and up to 253 bytes
303 // of key value. Duplicate keys are discarded.
304 // Associated with each key is a 48 bit row-id.
306 // The b-tree root is always located at page 1.
307 // The first leaf page of level zero is always
308 // located on page 2.
310 // When to root page fills, it is split in two and
311 // the tree height is raised by a new root at page
312 // one with two keys.
314 // Deleted keys are marked with a dead bit until
315 // page cleanup The fence key for a node is always
316 // present, even after deletion and cleanup.
318 // Groups of pages called segments from the btree are
319 // cached with memory mapping. A hash table is used to keep
320 // track of the cached segments. This behaviour is controlled
321 // by the cache block size parameter to bt_open.
323 // To achieve maximum concurrency one page is locked at a time
324 // as the tree is traversed to find leaf key in question.
326 // An adoption traversal leaves the parent node locked as the
327 // tree is traversed to the level in quesiton.
329 // Page 0 is dedicated to lock for new page extensions,
330 // and chains empty pages together for reuse.
332 // Empty pages are chained together through the ALLOC page and reused.
334 // Access macros to address slot and key values from the page
336 #define slotptr(page, slot) (((BtSlot *)(page+1)) + (slot-1))
337 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
339 void bt_putid(unsigned char *dest, uid id)
344 dest[i] = (unsigned char)id, id >>= 8;
347 uid bt_getid(unsigned char *src)
352 for( i = 0; i < BtId; i++ )
353 id <<= 8, id |= *src++;
360 int sys_futex(void *addr1, int op, int val1, struct timespec *timeout, void *addr2, int val3)
362 return syscall(SYS_futex, addr1, op, val1, timeout, addr2, val3);
365 // wait until write lock mode is clear
366 // and add 1 to the share count
368 void bt_spinreadlock(BtLatch *latch, int private)
373 private = FUTEX_PRIVATE_FLAG;
376 // obtain latch mutex
377 if( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex ) {
382 // wait for writers to clear
383 // increment read waiters and wait
385 if( latch->write || latch->writewait ) {
386 __sync_fetch_and_add ((uint *)latch, PendRd);
387 prev = __sync_fetch_and_and ((uint *)latch, ~Mutex) & ~Mutex;
388 sys_futex( (uint *)latch, FUTEX_WAIT_BITSET | private, prev, NULL, NULL, QueRd );
389 __sync_fetch_and_sub ((uint *)latch, PendRd);
393 // increment reader lock count
394 // and release latch mutex
396 __sync_fetch_and_add ((uint *)latch, Share);
397 __sync_fetch_and_and ((uint *)latch, ~Mutex);
402 // wait for other read and write latches to relinquish
404 void bt_spinwritelock(BtLatch *latch, int private)
409 private = FUTEX_PRIVATE_FLAG;
412 // obtain latch mutex
413 if( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex ) {
418 // wait for write and reader count to clear
420 if( latch->write || latch->share ) {
421 __sync_fetch_and_add ((uint *)latch, PendWr);
422 prev = __sync_fetch_and_and ((uint *)latch, ~Mutex) & ~Mutex;
423 sys_futex( (uint *)latch, FUTEX_WAIT_BITSET | private, prev, NULL, NULL, QueWr );
424 __sync_fetch_and_sub ((uint *)latch, PendWr);
429 // release latch mutex
431 __sync_fetch_and_or ((uint *)latch, Write);
432 __sync_fetch_and_and ((uint *)latch, ~Mutex);
437 // try to obtain write lock
439 // return 1 if obtained,
442 int bt_spinwritetry(BtLatch *latch)
447 // abandon request if not taken
449 if( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex )
452 // see if write mode is available
454 if( !latch->write && !latch->share ) {
455 __sync_fetch_and_or ((uint *)latch, Write);
460 // release latch mutex
462 __sync_fetch_and_and ((uint *)latch, ~Mutex);
468 void bt_spinreleasewrite(BtLatch *latch, int private)
471 private = FUTEX_PRIVATE_FLAG;
473 // obtain latch mutex
475 while( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex )
478 __sync_fetch_and_and ((uint *)latch, ~Write);
482 if( latch->writewait )
483 if( sys_futex( (uint *)latch, FUTEX_WAKE_BITSET | private, 1, NULL, NULL, QueWr ) )
486 if( latch->readwait )
487 sys_futex( (uint *)latch, FUTEX_WAKE_BITSET | private, INT_MAX, NULL, NULL, QueRd );
489 // release latch mutex
492 __sync_fetch_and_and ((uint *)latch, ~Mutex);
495 // decrement reader count
497 void bt_spinreleaseread(BtLatch *latch, int private)
500 private = FUTEX_PRIVATE_FLAG;
502 // obtain latch mutex
504 while( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex )
507 __sync_fetch_and_sub ((uint *)latch, Share);
509 // wake waiting writers
511 if( !latch->share && latch->writewait )
512 sys_futex( (uint *)latch, FUTEX_WAKE_BITSET | private, 1, NULL, NULL, QueWr );
514 // release latch mutex
516 __sync_fetch_and_and ((uint *)latch, ~Mutex);
519 // link latch table entry into latch hash table
521 void bt_latchlink (BtDb *bt, ushort hashidx, ushort victim, uid page_no)
523 BtLatchSet *set = bt->mgr->latchsets + victim;
525 if( set->next = bt->mgr->latchmgr->table[hashidx].slot )
526 bt->mgr->latchsets[set->next].prev = victim;
528 bt->mgr->latchmgr->table[hashidx].slot = victim;
529 set->page_no = page_no;
536 void bt_unpinlatch (BtLatchSet *set)
539 __sync_fetch_and_add(&set->pin, -1);
541 _InterlockedDecrement16 (&set->pin);
545 // find existing latchset or inspire new one
546 // return with latchset pinned
548 BtLatchSet *bt_pinlatch (BtDb *bt, uid page_no)
550 ushort hashidx = page_no % bt->mgr->latchmgr->latchhash;
551 ushort slot, avail = 0, victim, idx;
554 // obtain read lock on hash table entry
556 bt_spinreadlock(bt->mgr->latchmgr->table[hashidx].latch, 0);
558 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
560 set = bt->mgr->latchsets + slot;
561 if( page_no == set->page_no )
563 } while( slot = set->next );
567 __sync_fetch_and_add(&set->pin, 1);
569 _InterlockedIncrement16 (&set->pin);
573 bt_spinreleaseread (bt->mgr->latchmgr->table[hashidx].latch, 0);
578 // try again, this time with write lock
580 bt_spinwritelock(bt->mgr->latchmgr->table[hashidx].latch, 0);
582 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
584 set = bt->mgr->latchsets + slot;
585 if( page_no == set->page_no )
587 if( !set->pin && !avail )
589 } while( slot = set->next );
591 // found our entry, or take over an unpinned one
593 if( slot || (slot = avail) ) {
594 set = bt->mgr->latchsets + slot;
596 __sync_fetch_and_add(&set->pin, 1);
598 _InterlockedIncrement16 (&set->pin);
600 set->page_no = page_no;
601 bt_spinreleasewrite(bt->mgr->latchmgr->table[hashidx].latch, 0);
605 // see if there are any unused entries
607 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, 1) + 1;
609 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchdeployed);
612 if( victim < bt->mgr->latchmgr->latchtotal ) {
613 set = bt->mgr->latchsets + victim;
615 __sync_fetch_and_add(&set->pin, 1);
617 _InterlockedIncrement16 (&set->pin);
619 bt_latchlink (bt, hashidx, victim, page_no);
620 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch, 0);
625 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, -1);
627 victim = _InterlockedDecrement16 (&bt->mgr->latchmgr->latchdeployed);
629 // find and reuse previous lock entry
633 victim = __sync_fetch_and_add(&bt->mgr->latchmgr->latchvictim, 1);
635 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchvictim) - 1;
637 // we don't use slot zero
639 if( victim %= bt->mgr->latchmgr->latchtotal )
640 set = bt->mgr->latchsets + victim;
644 // take control of our slot
645 // from other threads
647 if( set->pin || !bt_spinwritetry (set->busy) )
652 // try to get write lock on hash chain
653 // skip entry if not obtained
654 // or has outstanding locks
656 if( !bt_spinwritetry (bt->mgr->latchmgr->table[idx].latch) ) {
657 bt_spinreleasewrite (set->busy, 0);
662 bt_spinreleasewrite (set->busy, 0);
663 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch, 0);
667 // unlink our available victim from its hash chain
670 bt->mgr->latchsets[set->prev].next = set->next;
672 bt->mgr->latchmgr->table[idx].slot = set->next;
675 bt->mgr->latchsets[set->next].prev = set->prev;
677 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch, 0);
679 __sync_fetch_and_add(&set->pin, 1);
681 _InterlockedIncrement16 (&set->pin);
683 bt_latchlink (bt, hashidx, victim, page_no);
684 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch, 0);
685 bt_spinreleasewrite (set->busy, 0);
690 void bt_mgrclose (BtMgr *mgr)
695 // release mapped pages
696 // note that slot zero is never used
698 for( slot = 1; slot < mgr->poolmax; slot++ ) {
699 pool = mgr->pool + slot;
702 munmap (pool->map, (mgr->poolmask+1) << mgr->page_bits);
705 FlushViewOfFile(pool->map, 0);
706 UnmapViewOfFile(pool->map);
707 CloseHandle(pool->hmap);
713 munmap (mgr->latchsets, mgr->latchmgr->nlatchpage * mgr->page_size);
714 munmap (mgr->latchmgr, mgr->page_size);
716 FlushViewOfFile(mgr->latchmgr, 0);
717 UnmapViewOfFile(mgr->latchmgr);
718 CloseHandle(mgr->halloc);
725 free (mgr->pooladvise);
728 FlushFileBuffers(mgr->idx);
729 CloseHandle(mgr->idx);
730 GlobalFree (mgr->pool);
731 GlobalFree (mgr->hash);
732 GlobalFree (mgr->latch);
737 // close and release memory
739 void bt_close (BtDb *bt)
746 VirtualFree (bt->mem, 0, MEM_RELEASE);
751 // open/create new btree buffer manager
753 // call with file_name, BT_openmode, bits in page size (e.g. 16),
754 // size of mapped page pool (e.g. 8192)
756 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
758 uint lvl, attr, cacheblk, last, slot, idx;
759 uint nlatchpage, latchhash;
760 BtLatchMgr *latchmgr;
768 SYSTEM_INFO sysinfo[1];
771 // determine sanity of page size and buffer pool
773 if( bits > BT_maxbits )
775 else if( bits < BT_minbits )
779 return NULL; // must have buffer pool
782 mgr = calloc (1, sizeof(BtMgr));
784 mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
787 return free(mgr), NULL;
789 cacheblk = 4096; // minimum mmap segment size for unix
792 mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
793 attr = FILE_ATTRIBUTE_NORMAL;
794 mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
796 if( mgr->idx == INVALID_HANDLE_VALUE )
797 return GlobalFree(mgr), NULL;
799 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
800 GetSystemInfo(sysinfo);
801 cacheblk = sysinfo->dwAllocationGranularity;
805 latchmgr = malloc (BT_maxpage);
808 // read minimum page size to get root info
810 if( size = lseek (mgr->idx, 0L, 2) ) {
811 if( pread(mgr->idx, latchmgr, BT_minpage, 0) == BT_minpage )
812 bits = latchmgr->alloc->bits;
814 return free(mgr), free(latchmgr), NULL;
815 } else if( mode == BT_ro )
816 return free(latchmgr), bt_mgrclose (mgr), NULL;
818 latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
819 size = GetFileSize(mgr->idx, amt);
822 if( !ReadFile(mgr->idx, (char *)latchmgr, BT_minpage, amt, NULL) )
823 return bt_mgrclose (mgr), NULL;
824 bits = latchmgr->alloc->bits;
825 } else if( mode == BT_ro )
826 return bt_mgrclose (mgr), NULL;
829 mgr->page_size = 1 << bits;
830 mgr->page_bits = bits;
832 mgr->poolmax = poolmax;
835 if( cacheblk < mgr->page_size )
836 cacheblk = mgr->page_size;
838 // mask for partial memmaps
840 mgr->poolmask = (cacheblk >> bits) - 1;
842 // see if requested size of pages per memmap is greater
844 if( (1 << segsize) > mgr->poolmask )
845 mgr->poolmask = (1 << segsize) - 1;
849 while( (1 << mgr->seg_bits) <= mgr->poolmask )
852 mgr->hashsize = hashsize;
855 mgr->pool = calloc (poolmax, sizeof(BtPool));
856 mgr->hash = calloc (hashsize, sizeof(ushort));
857 mgr->latch = calloc (hashsize, sizeof(BtLatch));
858 mgr->pooladvise = calloc (poolmax, (mgr->poolmask + 8) / 8);
860 mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * sizeof(BtPool));
861 mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
862 mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtLatch));
868 // initialize an empty b-tree with latch page, root page, page of leaves
869 // and page(s) of latches
871 memset (latchmgr, 0, 1 << bits);
872 nlatchpage = BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1;
873 bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
874 latchmgr->alloc->bits = mgr->page_bits;
876 latchmgr->nlatchpage = nlatchpage;
877 latchmgr->latchtotal = nlatchpage * (mgr->page_size / sizeof(BtLatchSet));
879 // initialize latch manager
881 latchhash = (mgr->page_size - sizeof(BtLatchMgr)) / sizeof(BtHashEntry);
883 // size of hash table = total number of latchsets
885 if( latchhash > latchmgr->latchtotal )
886 latchhash = latchmgr->latchtotal;
888 latchmgr->latchhash = latchhash;
891 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
892 return bt_mgrclose (mgr), NULL;
894 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
895 return bt_mgrclose (mgr), NULL;
897 if( *amt < mgr->page_size )
898 return bt_mgrclose (mgr), NULL;
901 memset (latchmgr, 0, 1 << bits);
902 latchmgr->alloc->bits = mgr->page_bits;
904 for( lvl=MIN_lvl; lvl--; ) {
905 slotptr(latchmgr->alloc, 1)->off = mgr->page_size - 3;
906 bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
907 key = keyptr(latchmgr->alloc, 1);
908 key->len = 2; // create stopper key
911 latchmgr->alloc->min = mgr->page_size - 3;
912 latchmgr->alloc->lvl = lvl;
913 latchmgr->alloc->cnt = 1;
914 latchmgr->alloc->act = 1;
916 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
917 return bt_mgrclose (mgr), NULL;
919 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
920 return bt_mgrclose (mgr), NULL;
922 if( *amt < mgr->page_size )
923 return bt_mgrclose (mgr), NULL;
927 // clear out latch manager locks
928 // and rest of pages to round out segment
930 memset(latchmgr, 0, mgr->page_size);
933 while( last <= ((MIN_lvl + 1 + nlatchpage) | mgr->poolmask) ) {
935 pwrite(mgr->idx, latchmgr, mgr->page_size, last << mgr->page_bits);
937 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
938 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
939 return bt_mgrclose (mgr), NULL;
940 if( *amt < mgr->page_size )
941 return bt_mgrclose (mgr), NULL;
948 flag = PROT_READ | PROT_WRITE;
949 mgr->latchmgr = mmap (0, mgr->page_size, flag, MAP_SHARED, mgr->idx, ALLOC_page * mgr->page_size);
950 if( mgr->latchmgr == MAP_FAILED )
951 return bt_mgrclose (mgr), NULL;
952 mgr->latchsets = (BtLatchSet *)mmap (0, mgr->latchmgr->nlatchpage * mgr->page_size, flag, MAP_SHARED, mgr->idx, LATCH_page * mgr->page_size);
953 if( mgr->latchsets == MAP_FAILED )
954 return bt_mgrclose (mgr), NULL;
956 flag = PAGE_READWRITE;
957 mgr->halloc = CreateFileMapping(mgr->idx, NULL, flag, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size, NULL);
959 return bt_mgrclose (mgr), NULL;
961 flag = FILE_MAP_WRITE;
962 mgr->latchmgr = MapViewOfFile(mgr->halloc, flag, 0, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size);
964 return GetLastError(), bt_mgrclose (mgr), NULL;
966 mgr->latchsets = (void *)((char *)mgr->latchmgr + LATCH_page * mgr->page_size);
972 VirtualFree (latchmgr, 0, MEM_RELEASE);
977 // open BTree access method
978 // based on buffer manager
980 BtDb *bt_open (BtMgr *mgr)
982 BtDb *bt = malloc (sizeof(*bt));
984 memset (bt, 0, sizeof(*bt));
987 bt->mem = malloc (3 *mgr->page_size);
989 bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
991 bt->frame = (BtPage)bt->mem;
992 bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
993 bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
995 memset(bt->zero, 0, mgr->page_size);
999 // compare two keys, returning > 0, = 0, or < 0
1000 // as the comparison value
1002 int keycmp (BtKey key1, unsigned char *key2, uint len2)
1004 uint len1 = key1->len;
1007 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
1020 // find segment in pool
1021 // must be called with hashslot idx locked
1022 // return NULL if not there
1023 // otherwise return node
1025 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
1030 // compute start of hash chain in pool
1032 if( slot = bt->mgr->hash[idx] )
1033 pool = bt->mgr->pool + slot;
1037 page_no &= ~bt->mgr->poolmask;
1039 while( pool->basepage != page_no )
1040 if( pool = pool->hashnext )
1048 // add segment to hash table
1050 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
1055 pool->hashprev = pool->hashnext = NULL;
1056 pool->basepage = page_no & ~bt->mgr->poolmask;
1059 if( slot = bt->mgr->hash[idx] ) {
1060 node = bt->mgr->pool + slot;
1061 pool->hashnext = node;
1062 node->hashprev = pool;
1065 bt->mgr->hash[idx] = pool->slot;
1068 // find best segment to evict from buffer pool
1070 BtPool *bt_findlru (BtDb *bt, uint hashslot)
1072 unsigned long long int target = ~0LL;
1073 BtPool *pool = NULL, *node;
1078 node = bt->mgr->pool + hashslot;
1080 // scan pool entries under hash table slot
1085 if( node->lru > target )
1089 } while( node = node->hashnext );
1094 // map new buffer pool segment to virtual memory
1096 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
1098 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
1099 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
1103 flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
1104 pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED, bt->mgr->idx, off);
1105 if( pool->map == MAP_FAILED )
1106 return bt->err = BTERR_map;
1107 // clear out madvise issued bits
1108 memset (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8) / 8), 0, (bt->mgr->poolmask + 8)/8);
1110 flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
1111 pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
1113 return bt->err = BTERR_map;
1115 flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
1116 pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1118 return bt->err = BTERR_map;
1123 // calculate page within pool
1125 BtPage bt_page (BtDb *bt, BtPool *pool, uid page_no)
1127 uint subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1130 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1133 uint idx = subpage / 8;
1134 uint bit = subpage % 8;
1136 if( ~((bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] >> bit) & 1 ) {
1137 madvise (page, bt->mgr->page_size, MADV_WILLNEED);
1138 (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] |= 1 << bit;
1147 void bt_unpinpool (BtPool *pool)
1150 __sync_fetch_and_add(&pool->pin, -1);
1152 _InterlockedDecrement16 (&pool->pin);
1156 // find or place requested page in segment-pool
1157 // return pool table entry, incrementing pin
1159 BtPool *bt_pinpool(BtDb *bt, uid page_no)
1161 BtPool *pool, *node, *next;
1162 uint slot, idx, victim;
1165 // lock hash table chain
1167 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1168 bt_spinreadlock (&bt->mgr->latch[idx], 1);
1170 // look up in hash table
1172 if( pool = bt_findpool(bt, page_no, idx) ) {
1174 __sync_fetch_and_add(&pool->pin, 1);
1176 _InterlockedIncrement16 (&pool->pin);
1178 bt_spinreleaseread (&bt->mgr->latch[idx], 1);
1183 // upgrade to write lock
1185 bt_spinreleaseread (&bt->mgr->latch[idx], 1);
1186 bt_spinwritelock (&bt->mgr->latch[idx], 1);
1188 // try to find page in pool with write lock
1190 if( pool = bt_findpool(bt, page_no, idx) ) {
1192 __sync_fetch_and_add(&pool->pin, 1);
1194 _InterlockedIncrement16 (&pool->pin);
1196 bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
1201 // allocate a new pool node
1202 // and add to hash table
1205 slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
1207 slot = _InterlockedIncrement16 (&bt->mgr->poolcnt) - 1;
1210 if( ++slot < bt->mgr->poolmax ) {
1211 pool = bt->mgr->pool + slot;
1214 if( bt_mapsegment(bt, pool, page_no) )
1217 bt_linkhash(bt, pool, page_no, idx);
1219 __sync_fetch_and_add(&pool->pin, 1);
1221 _InterlockedIncrement16 (&pool->pin);
1223 bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
1227 // pool table is full
1228 // find best pool entry to evict
1231 __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
1233 _InterlockedDecrement16 (&bt->mgr->poolcnt);
1238 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
1240 victim = _InterlockedIncrement16 (&bt->mgr->evicted) - 1;
1242 victim %= bt->mgr->hashsize;
1244 // try to get write lock
1245 // skip entry if not obtained
1247 if( !bt_spinwritetry (&bt->mgr->latch[victim]) )
1250 // if cache entry is empty
1251 // or no slots are unpinned
1254 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
1255 bt_spinreleasewrite (&bt->mgr->latch[victim], 1);
1259 // unlink victim pool node from hash table
1261 if( node = pool->hashprev )
1262 node->hashnext = pool->hashnext;
1263 else if( node = pool->hashnext )
1264 bt->mgr->hash[victim] = node->slot;
1266 bt->mgr->hash[victim] = 0;
1268 if( node = pool->hashnext )
1269 node->hashprev = pool->hashprev;
1271 bt_spinreleasewrite (&bt->mgr->latch[victim], 1);
1273 // remove old file mapping
1275 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1277 FlushViewOfFile(pool->map, 0);
1278 UnmapViewOfFile(pool->map);
1279 CloseHandle(pool->hmap);
1283 // create new pool mapping
1284 // and link into hash table
1286 if( bt_mapsegment(bt, pool, page_no) )
1289 bt_linkhash(bt, pool, page_no, idx);
1291 __sync_fetch_and_add(&pool->pin, 1);
1293 _InterlockedIncrement16 (&pool->pin);
1295 bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
1300 // place write, read, or parent lock on requested page_no.
1301 // pin to buffer pool and return latchset pointer
1303 void bt_lockpage(BtLock mode, BtLatchSet *set)
1307 bt_spinreadlock (set->readwr, 0);
1310 bt_spinwritelock (set->readwr, 0);
1313 bt_spinreadlock (set->access, 0);
1316 bt_spinwritelock (set->access, 0);
1319 bt_spinwritelock (set->parent, 0);
1324 // remove write, read, or parent lock on requested page_no.
1326 void bt_unlockpage(BtLock mode, BtLatchSet *set)
1330 bt_spinreleaseread (set->readwr, 0);
1333 bt_spinreleasewrite (set->readwr, 0);
1336 bt_spinreleaseread (set->access, 0);
1339 bt_spinreleasewrite (set->access, 0);
1342 bt_spinreleasewrite (set->parent, 0);
1347 // allocate a new page and write page into it
1349 uid bt_newpage(BtDb *bt, BtPage page)
1357 // lock allocation page
1359 bt_spinwritelock(bt->mgr->latchmgr->lock, 0);
1361 // use empty chain first
1362 // else allocate empty page
1364 if( new_page = bt_getid(bt->mgr->latchmgr->alloc[1].right) ) {
1365 if( pool = bt_pinpool (bt, new_page) )
1366 pmap = bt_page (bt, pool, new_page);
1369 bt_putid(bt->mgr->latchmgr->alloc[1].right, bt_getid(pmap->right));
1370 bt_unpinpool (pool);
1373 new_page = bt_getid(bt->mgr->latchmgr->alloc->right);
1374 bt_putid(bt->mgr->latchmgr->alloc->right, new_page+1);
1378 // if writing first page of pool block, zero last page in the block
1380 if ( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1382 // use zero buffer to write zeros
1383 if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1384 return bt->err = BTERR_wrt, 0;
1387 // unlock allocation latch
1389 bt_spinreleasewrite(bt->mgr->latchmgr->lock, 0);
1391 if ( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1392 return bt->err = BTERR_wrt, 0;
1395 // unlock allocation latch
1397 bt_spinreleasewrite(bt->mgr->latchmgr->lock, 0);
1399 // bring new page into pool and copy page.
1400 // this will extend the file into the new pages.
1401 // NB -- no latch required
1403 if( pool = bt_pinpool (bt, new_page) )
1404 pmap = bt_page (bt, pool, new_page);
1408 memcpy(pmap, page, bt->mgr->page_size);
1409 bt_unpinpool (pool);
1414 // find slot in page for given key at a given level
1416 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1418 uint diff, higher = bt->page->cnt, low = 1, slot;
1420 // low is the lowest candidate, higher is already
1421 // tested as .ge. the given key, loop ends when they meet
1423 while( diff = higher - low ) {
1424 slot = low + ( diff >> 1 );
1425 if( keycmp (keyptr(bt->page, slot), key, len) < 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, BtLock lock)
1439 uid page_no = ROOT_page, prevpage = 0;
1440 BtLatchSet *set, *prevset;
1441 uint drill = 0xff, slot;
1442 uint mode, prevmode;
1445 // start at root of btree and drill down
1448 // determine lock mode of drill level
1449 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1451 // obtain latch set for this page
1453 bt->set = bt_pinlatch (bt, page_no);
1454 bt->page_no = page_no;
1456 // pin page contents
1458 if( bt->pool = bt_pinpool (bt, page_no) )
1459 bt->page = bt_page (bt, bt->pool, page_no);
1463 // obtain access lock using lock chaining with Access mode
1465 if( page_no > ROOT_page )
1466 bt_lockpage(BtLockAccess, bt->set);
1468 // now unlock and unpin our (possibly foster) parent
1471 bt_unlockpage(prevmode, prevset);
1472 bt_unpinlatch (prevset);
1473 bt_unpinpool (prevpool);
1477 // obtain read lock using lock chaining
1479 bt_lockpage(mode, bt->set);
1481 if( page_no > ROOT_page )
1482 bt_unlockpage(BtLockAccess, bt->set);
1484 // re-read and re-lock root after determining actual level of root
1486 if( page_no == ROOT_page )
1487 if( bt->page->lvl != drill) {
1488 drill = bt->page->lvl;
1490 if( lock == BtLockWrite && drill == lvl ) {
1491 bt_unlockpage(mode, bt->set);
1492 bt_unpinlatch (bt->set);
1493 bt_unpinpool (bt->pool);
1498 prevpage = bt->page_no;
1499 prevpool = bt->pool;
1503 // find key on page at this level
1504 // and either descend to requested level
1505 // or return key slot
1507 slot = bt_findslot (bt, key, len);
1509 // is this slot < foster child area
1510 // on the requested level?
1512 // if so, return actual slot even if dead
1514 if( slot <= bt->page->cnt - bt->page->foster )
1518 // find next active slot
1520 // note: foster children are never dead
1521 // nor fence keys for interiour nodes
1523 while( slotptr(bt->page, slot)->dead )
1524 if( slot++ < bt->page->cnt )
1527 return bt->err = BTERR_struct, 0; // last key shouldn't be deleted
1529 // is this slot < foster child area
1530 // if so, drill to next level
1532 if( slot <= bt->page->cnt - bt->page->foster )
1535 // continue right onto foster child
1536 // or down to next level.
1538 page_no = bt_getid(slotptr(bt->page, slot)->id);
1542 // return error on end of chain
1544 bt->err = BTERR_struct;
1545 return 0; // return error
1548 // find and delete key on page by marking delete flag bit
1549 // when leaf page becomes empty, delete it from the btree
1551 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len)
1553 unsigned char leftkey[256];
1554 BtLatchSet *rset, *set;
1555 BtPool *pool, *rpool;
1561 if( slot = bt_loadpage (bt, key, len, 0, BtLockWrite) )
1562 ptr = keyptr(bt->page, slot);
1566 // if key is found delete it, otherwise ignore request
1567 // note that fence keys of interiour nodes are not deleted.
1569 if( bt->found = !keycmp (ptr, key, len) )
1570 if( bt->found = slotptr(bt->page, slot)->dead == 0 ) {
1571 slotptr(bt->page,slot)->dead = 1;
1572 if( slot < bt->page->cnt )
1573 bt->page->dirty = 1;
1577 page_no = bt->page_no;
1582 // return if page is not empty or not found
1584 if( page->act || !bt->found ) {
1585 bt_unlockpage(BtLockWrite, set);
1586 bt_unpinlatch (set);
1587 bt_unpinpool (pool);
1591 // cache copy of fence key of empty node
1593 ptr = keyptr(page, page->cnt);
1594 memcpy(leftkey, ptr, ptr->len + 1);
1596 // release write lock on empty node
1597 // obtain Parent lock
1599 bt_unlockpage(BtLockWrite, set);
1600 bt_lockpage(BtLockParent, set);
1602 // load and lock parent to see
1603 // if delete of empty node is OK
1604 // ie, not a fence key of parent
1607 if( slot = bt_loadpage (bt, leftkey+1, *leftkey, 1, BtLockWrite) )
1608 ptr = keyptr(bt->page, slot);
1612 // does parent level contain our fence key yet?
1613 // and is it free of foster children?
1615 if( !bt->page->foster )
1616 if( !keycmp (ptr, leftkey+1, *leftkey) )
1619 bt_unlockpage(BtLockWrite, bt->set);
1620 bt_unpinlatch (bt->set);
1621 bt_unpinpool (bt->pool);
1629 // find our left fence key
1631 while( slotptr(bt->page, slot)->dead )
1632 if( slot++ < bt->page->cnt )
1635 return bt->err = BTERR_struct; // last key shouldn't be deleted
1637 // now we have both parent and child
1639 bt_lockpage(BtLockDelete, set);
1640 bt_lockpage(BtLockWrite, set);
1642 // return if page has no right sibling within parent
1643 // or if empty node is no longer empty
1645 if( page->act || slot == bt->page->cnt ) {
1647 bt_unlockpage(BtLockWrite, bt->set);
1648 bt_unpinlatch (bt->set);
1649 bt_unpinpool (bt->pool);
1651 bt_unlockpage(BtLockParent, set);
1652 bt_unlockpage(BtLockDelete, set);
1653 bt_unlockpage(BtLockWrite, set);
1654 bt_unpinlatch (set);
1655 bt_unpinpool (pool);
1659 // lock and map our right page
1660 // note that it cannot be our foster child
1661 // since the our node is empty
1663 right = bt_getid(page->right);
1665 if( rpool = bt_pinpool (bt, right) )
1666 rpage = bt_page (bt, rpool, right);
1670 rset = bt_pinlatch (bt, right);
1671 bt_lockpage(BtLockWrite, rset);
1672 bt_lockpage(BtLockDelete, rset);
1674 // pull contents of right page into empty page
1676 memcpy (page, rpage, bt->mgr->page_size);
1678 // delete left parent slot for old empty page
1679 // and redirect right parent slot to it
1682 bt->page->dirty = 1;
1683 slotptr(bt->page, slot)->dead = 1;
1685 while( slot++ < bt->page->cnt )
1686 if( !slotptr(bt->page, slot)->dead )
1689 bt_putid(slotptr(bt->page,slot)->id, page_no);
1691 // release parent level lock
1692 // and our empty node lock
1694 bt_unlockpage(BtLockWrite, set);
1695 bt_unlockpage(BtLockWrite, bt->set);
1696 bt_unpinlatch (bt->set);
1697 bt_unpinpool (bt->pool);
1699 // add killed right block to free chain
1702 bt_spinwritelock(bt->mgr->latchmgr->lock, 0);
1704 // store free chain in allocation page second right
1705 bt_putid(rpage->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1706 bt_putid(bt->mgr->latchmgr->alloc[1].right, right);
1708 // unlock latch mgr and right page
1710 bt_spinreleasewrite(bt->mgr->latchmgr->lock, 0);
1712 bt_unlockpage(BtLockWrite, rset);
1713 bt_unlockpage(BtLockDelete, rset);
1714 bt_unpinlatch (rset);
1715 bt_unpinpool (rpool);
1717 // remove ParentModify lock
1719 bt_unlockpage(BtLockParent, set);
1720 bt_unlockpage(BtLockDelete, set);
1721 bt_unpinlatch (set);
1722 bt_unpinpool (pool);
1726 // find key in leaf level and return row-id
1728 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1734 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1735 ptr = keyptr(bt->page, slot);
1739 // if key exists, return row-id
1740 // otherwise return 0
1742 if( slot <= bt->page->cnt && !keycmp (ptr, key, len) )
1743 id = bt_getid(slotptr(bt->page,slot)->id);
1747 bt_unlockpage (BtLockRead, bt->set);
1748 bt_unpinlatch (bt->set);
1749 bt_unpinpool (bt->pool);
1753 // check page for space available,
1754 // clean if necessary and return
1755 // 0 - page needs splitting
1756 // >0 new slot value
1758 uint bt_cleanpage(BtDb *bt, uint amt, uint slot)
1760 uint nxt = bt->mgr->page_size;
1761 BtPage page = bt->page;
1762 uint cnt = 0, idx = 0;
1763 uint max = page->cnt;
1767 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1770 // skip cleanup if nothing to reclaim
1775 memcpy (bt->frame, page, bt->mgr->page_size);
1777 // skip page info and set rest of page to zero
1779 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1783 // try cleaning up page first
1785 // always leave fence key in the array
1786 // otherwise, remove deleted key
1788 // note: foster children are never dead
1789 // nor are fence keys for interiour nodes
1791 while( cnt++ < max ) {
1794 else if( cnt < max && slotptr(bt->frame,cnt)->dead )
1799 key = keyptr(bt->frame, cnt);
1800 nxt -= key->len + 1;
1801 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1804 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1805 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1807 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1808 slotptr(page, idx)->off = nxt;
1814 // see if page has enough space now, or does it need splitting?
1816 if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1822 // add key to current page
1823 // page must already be writelocked
1825 void bt_addkeytopage (BtDb *bt, uint slot, unsigned char *key, uint len, uid id, uint tod)
1827 BtPage page = bt->page;
1830 // find next available dead slot and copy key onto page
1831 // note that foster children on the page are never dead
1833 // look for next hole, but stay back from the fence key
1835 for( idx = slot; idx < page->cnt; idx++ )
1836 if( slotptr(page, idx)->dead )
1839 if( idx == page->cnt )
1844 // now insert key into array before slot
1847 *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
1849 page->min -= len + 1;
1850 ((unsigned char *)page)[page->min] = len;
1851 memcpy ((unsigned char *)page + page->min +1, key, len );
1853 bt_putid(slotptr(page,slot)->id, id);
1854 slotptr(page, slot)->off = page->min;
1855 slotptr(page, slot)->tod = tod;
1856 slotptr(page, slot)->dead = 0;
1859 // split the root and raise the height of the btree
1860 // call with current page locked and page no of foster child
1861 // return with current page (root) unlocked
1863 BTERR bt_splitroot(BtDb *bt, uid right)
1865 uint nxt = bt->mgr->page_size;
1866 unsigned char fencekey[256];
1867 BtPage root = bt->page;
1871 // Obtain an empty page to use, and copy the left page
1872 // contents into it from the root. Strip foster child key.
1873 // (it's the stopper key)
1875 memset (slotptr(root, root->cnt), 0, sizeof(BtSlot));
1881 // Save left fence key.
1883 key = keyptr(root, root->cnt);
1884 memcpy (fencekey, key, key->len + 1);
1886 // copy the lower keys into a new left page
1888 if( !(new_page = bt_newpage(bt, root)) )
1891 // preserve the page info at the bottom
1892 // and set rest of the root to zero
1894 memset (root+1, 0, bt->mgr->page_size - sizeof(*root));
1896 // insert left fence key on empty newroot page
1898 nxt -= *fencekey + 1;
1899 memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
1900 bt_putid(slotptr(root, 1)->id, new_page);
1901 slotptr(root, 1)->off = nxt;
1903 // insert stopper key on newroot page
1904 // and increase the root height
1910 memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
1911 bt_putid(slotptr(root, 2)->id, right);
1912 slotptr(root, 2)->off = nxt;
1914 bt_putid(root->right, 0);
1915 root->min = nxt; // reset lowest used offset and key count
1920 // release and unpin root (bt->page)
1922 bt_unlockpage(BtLockWrite, bt->set);
1923 bt_unpinlatch (bt->set);
1924 bt_unpinpool (bt->pool);
1928 // split already locked full node
1929 // in current page variables
1930 // return unlocked and unpinned.
1932 BTERR bt_splitpage (BtDb *bt)
1934 uint slot, cnt, idx, max, nxt = bt->mgr->page_size;
1935 unsigned char fencekey[256];
1936 uid page_no = bt->page_no;
1937 BtLatchSet *set = bt->set;
1938 BtPool *pool = bt->pool;
1939 BtPage page = bt->page;
1940 uint tod = time(NULL);
1941 uint lvl = page->lvl;
1942 uid new_page, right;
1945 // initialize frame buffer for right node
1947 memset (bt->frame, 0, bt->mgr->page_size);
1948 max = page->cnt - page->foster;
1949 tod = (uint)time(NULL);
1953 // split higher half of keys to bt->frame
1954 // leaving old foster children in the left node,
1955 // and adding a new foster child there.
1957 while( cnt++ < max ) {
1958 key = keyptr(page, cnt);
1959 nxt -= key->len + 1;
1960 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
1961 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
1962 if( !(slotptr(bt->frame, idx)->dead = slotptr(page, cnt)->dead) )
1964 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
1965 slotptr(bt->frame, idx)->off = nxt;
1968 // transfer right link node to new right node
1970 if( page_no > ROOT_page ) {
1971 right = bt_getid (page->right);
1972 bt_putid(bt->frame->right, right);
1975 bt->frame->bits = bt->mgr->page_bits;
1976 bt->frame->min = nxt;
1977 bt->frame->cnt = idx;
1978 bt->frame->lvl = lvl;
1980 // get new free page and write right frame to it.
1982 if( !(new_page = bt_newpage(bt, bt->frame)) )
1985 // remember fence key for new right page to add
1986 // as foster child to the left node
1988 key = keyptr(bt->frame, idx);
1989 memcpy (fencekey, key, key->len + 1);
1991 // update lower keys and foster children to continue in old page
1993 memcpy (bt->frame, page, bt->mgr->page_size);
1994 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1995 nxt = bt->mgr->page_size;
2001 // assemble page of smaller keys
2002 // to remain in the old page
2004 while( cnt++ < max / 2 ) {
2005 key = keyptr(bt->frame, cnt);
2006 nxt -= key->len + 1;
2007 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2008 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
2009 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
2011 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2012 slotptr(page, idx)->off = nxt;
2015 // insert new foster child for right page in queue
2016 // before any of the current foster children
2018 nxt -= *fencekey + 1;
2019 memcpy ((unsigned char *)page + nxt, fencekey, *fencekey + 1);
2021 bt_putid (slotptr(page,++idx)->id, new_page);
2022 slotptr(page, idx)->tod = tod;
2023 slotptr(page, idx)->off = nxt;
2027 // continue with old foster child keys
2028 // note that none will be dead
2030 cnt = bt->frame->cnt - bt->frame->foster;
2032 while( cnt++ < bt->frame->cnt ) {
2033 key = keyptr(bt->frame, cnt);
2034 nxt -= key->len + 1;
2035 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2036 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
2037 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2038 slotptr(page, idx)->off = nxt;
2045 // link new right page
2047 bt_putid (page->right, new_page);
2049 // if current page is the root page, split it
2051 if( page_no == ROOT_page )
2052 return bt_splitroot (bt, new_page);
2054 // release wr lock on our page
2056 bt_unlockpage (BtLockWrite, set);
2058 // obtain ParentModification lock for current page
2059 // to fix new fence key and oldest foster child on page
2061 bt_lockpage (BtLockParent, set);
2063 // get our new fence key to insert in parent node
2065 bt_lockpage (BtLockRead, set);
2067 key = keyptr(page, page->cnt-1);
2068 memcpy (fencekey, key, key->len+1);
2070 bt_unlockpage (BtLockRead, set);
2072 if( bt_insertkey (bt, fencekey + 1, *fencekey, page_no, tod, lvl + 1) )
2075 // lock our page for writing
2077 bt_lockpage (BtLockRead, set);
2079 // switch old parent key from us to our oldest foster child
2081 key = keyptr(page, page->cnt);
2082 memcpy (fencekey, key, key->len+1);
2084 new_page = bt_getid (slotptr(page, page->cnt)->id);
2085 bt_unlockpage (BtLockRead, set);
2087 if( bt_insertkey (bt, fencekey + 1, *fencekey, new_page, tod, lvl + 1) )
2090 // now that it has its own parent pointer,
2091 // remove oldest foster child from our page
2093 bt_lockpage (BtLockWrite, set);
2094 memset (slotptr(page, page->cnt), 0, sizeof(BtSlot));
2102 bt_unlockpage (BtLockWrite, set);
2103 bt_unlockpage (BtLockParent, set);
2104 bt_unpinlatch (set);
2105 bt_unpinpool (pool);
2109 // Insert new key into the btree at leaf level.
2111 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod, uint lvl)
2118 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
2119 ptr = keyptr(bt->page, slot);
2123 bt->err = BTERR_ovflw;
2127 // if key already exists, update id and return
2131 if( !keycmp (ptr, key, len) ) {
2132 if( slotptr(page, slot)->dead )
2134 slotptr(page, slot)->dead = 0;
2135 slotptr(page, slot)->tod = tod;
2136 bt_putid(slotptr(page,slot)->id, id);
2137 bt_unlockpage(BtLockWrite, bt->set);
2138 bt_unpinlatch (bt->set);
2139 bt_unpinpool (bt->pool);
2143 // check if page has enough space
2145 if( slot = bt_cleanpage (bt, len, slot) )
2148 if( bt_splitpage (bt) )
2152 bt_addkeytopage (bt, slot, key, len, id, tod);
2154 bt_unlockpage (BtLockWrite, bt->set);
2155 bt_unpinlatch (bt->set);
2156 bt_unpinpool (bt->pool);
2160 // cache page of keys into cursor and return starting slot for given key
2162 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2166 // cache page for retrieval
2167 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
2168 memcpy (bt->cursor, bt->page, bt->mgr->page_size);
2170 bt->cursor_page = bt->page_no;
2172 bt_unlockpage(BtLockRead, bt->set);
2173 bt_unpinlatch (bt->set);
2174 bt_unpinpool (bt->pool);
2178 // return next slot for cursor page
2179 // or slide cursor right into next page
2181 uint bt_nextkey (BtDb *bt, uint slot)
2189 right = bt_getid(bt->cursor->right);
2190 while( slot++ < bt->cursor->cnt - bt->cursor->foster )
2191 if( slotptr(bt->cursor,slot)->dead )
2193 else if( right || (slot < bt->cursor->cnt - bt->cursor->foster) )
2201 bt->cursor_page = right;
2202 if( pool = bt_pinpool (bt, right) )
2203 page = bt_page (bt, pool, right);
2207 set = bt_pinlatch (bt, right);
2208 bt_lockpage(BtLockRead, set);
2210 memcpy (bt->cursor, page, bt->mgr->page_size);
2212 bt_unlockpage(BtLockRead, set);
2213 bt_unpinlatch (set);
2214 bt_unpinpool (pool);
2221 BtKey bt_key(BtDb *bt, uint slot)
2223 return keyptr(bt->cursor, slot);
2226 uid bt_uid(BtDb *bt, uint slot)
2228 return bt_getid(slotptr(bt->cursor,slot)->id);
2231 uint bt_tod(BtDb *bt, uint slot)
2233 return slotptr(bt->cursor,slot)->tod;
2239 void bt_latchaudit (BtDb *bt)
2241 ushort idx, hashidx;
2248 for( idx = 1; idx < bt->mgr->latchmgr->latchdeployed; idx++ ) {
2249 set = bt->mgr->latchsets + idx;
2250 if( *(ushort *)set->readwr || *(ushort *)set->access || *(ushort *)set->parent ) {
2251 fprintf(stderr, "latchset %d locked for page %6x\n", idx, set->page_no);
2252 *(ushort *)set->readwr = 0;
2253 *(ushort *)set->access = 0;
2254 *(ushort *)set->parent = 0;
2257 fprintf(stderr, "latchset %d pinned\n", idx);
2262 for( hashidx = 0; hashidx < bt->mgr->latchmgr->latchhash; hashidx++ ) {
2263 if( *(uint *)bt->mgr->latchmgr->table[hashidx].latch )
2264 fprintf(stderr, "latchmgr locked\n");
2265 if( idx = bt->mgr->latchmgr->table[hashidx].slot ) do {
2266 set = bt->mgr->latchsets + idx;
2267 if( *(uint *)set->readwr || *(ushort *)set->access || *(ushort *)set->parent )
2268 fprintf(stderr, "latchset %d locked\n", idx);
2269 if( set->hash != hashidx )
2270 fprintf(stderr, "latchset %d wrong hashidx\n", idx);
2272 fprintf(stderr, "latchset %d pinned\n", idx);
2273 } while( idx = set->next );
2275 page_no = bt_getid(bt->mgr->latchmgr->alloc[1].right);
2278 fprintf(stderr, "free: %.6x\n", (uint)page_no);
2279 pool = bt_pinpool (bt, page_no);
2280 page = bt_page (bt, pool, page_no);
2281 page_no = bt_getid(page->right);
2282 bt_unpinpool (pool);
2294 // standalone program to index file of keys
2295 // then list them onto std-out
2298 void *index_file (void *arg)
2300 uint __stdcall index_file (void *arg)
2303 int line = 0, found = 0, cnt = 0;
2304 uid next, page_no = LEAF_page; // start on first page of leaves
2305 unsigned char key[256];
2306 ThreadArg *args = arg;
2307 int ch, len = 0, slot;
2316 bt = bt_open (args->mgr);
2319 switch(args->type | 0x20)
2322 fprintf(stderr, "started latch mgr audit\n");
2324 fprintf(stderr, "finished latch mgr audit\n");
2327 fprintf(stderr, "started indexing for %s\n", args->infile);
2328 if( in = fopen (args->infile, "rb") )
2329 while( ch = getc(in), ch != EOF )
2334 if( args->num == 1 )
2335 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2337 else if( args->num )
2338 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2340 if( bt_insertkey (bt, key, len, line, *tod, 0) )
2341 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2344 else if( len < 255 )
2346 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
2350 fprintf(stderr, "started deleting keys for %s\n", args->infile);
2351 if( in = fopen (args->infile, "rb") )
2352 while( ch = getc(in), ch != EOF )
2356 if( args->num == 1 )
2357 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2359 else if( args->num )
2360 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2362 if( bt_deletekey (bt, key, len) )
2363 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2366 else if( len < 255 )
2368 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2372 fprintf(stderr, "started finding keys for %s\n", args->infile);
2373 if( in = fopen (args->infile, "rb") )
2374 while( ch = getc(in), ch != EOF )
2378 if( args->num == 1 )
2379 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2381 else if( args->num )
2382 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2384 if( bt_findkey (bt, key, len) )
2387 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2390 else if( len < 255 )
2392 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2398 fprintf(stderr, "started reading\n");
2400 if( slot = bt_startkey (bt, key, len) )
2403 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
2405 while( slot = bt_nextkey (bt, slot) ) {
2406 ptr = bt_key(bt, slot);
2407 fwrite (ptr->key, ptr->len, 1, stdout);
2408 fputc ('\n', stdout);
2414 fprintf(stderr, "started reading\n");
2417 if( pool = bt_pinpool (bt, page_no) )
2418 page = bt_page (bt, pool, page_no);
2421 set = bt_pinlatch (bt, page_no);
2422 bt_lockpage (BtLockRead, set);
2424 next = bt_getid (page->right);
2425 bt_unlockpage (BtLockRead, set);
2426 bt_unpinlatch (set);
2427 bt_unpinpool (pool);
2428 } while( page_no = next );
2430 cnt--; // remove stopper key
2431 fprintf(stderr, " Total keys read %d\n", cnt);
2443 typedef struct timeval timer;
2445 int main (int argc, char **argv)
2447 int idx, cnt, len, slot, err;
2448 int segsize, bits = 16;
2453 time_t start[1], stop[1];
2466 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]);
2467 fprintf (stderr, " where page_bits is the page size in bits\n");
2468 fprintf (stderr, " mapped_segments is the number of mmap segments in buffer pool\n");
2469 fprintf (stderr, " seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2470 fprintf (stderr, " line_numbers = 1 to append line numbers to keys\n");
2471 fprintf (stderr, " src_file1 thru src_filen are files of keys separated by newline\n");
2476 gettimeofday(&start, NULL);
2482 bits = atoi(argv[3]);
2485 poolsize = atoi(argv[4]);
2488 fprintf (stderr, "Warning: no mapped_pool\n");
2490 if( poolsize > 65535 )
2491 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2494 segsize = atoi(argv[5]);
2496 segsize = 4; // 16 pages per mmap segment
2499 num = atoi(argv[6]);
2503 threads = malloc (cnt * sizeof(pthread_t));
2505 threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2507 args = malloc (cnt * sizeof(ThreadArg));
2509 mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2512 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2518 for( idx = 0; idx < cnt; idx++ ) {
2519 args[idx].infile = argv[idx + 7];
2520 args[idx].type = argv[2][0];
2521 args[idx].mgr = mgr;
2522 args[idx].num = num;
2523 args[idx].idx = idx;
2525 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2526 fprintf(stderr, "Error creating thread %d\n", err);
2528 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2532 // wait for termination
2535 for( idx = 0; idx < cnt; idx++ )
2536 pthread_join (threads[idx], NULL);
2537 gettimeofday(&stop, NULL);
2538 real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2540 WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2542 for( idx = 0; idx < cnt; idx++ )
2543 CloseHandle(threads[idx]);
2546 real_time = 1000 * (*stop - *start);
2548 fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);