1 // foster btree version g
4 // author: karl malbrain, malbrain@cal.berkeley.edu
7 This work, including the source code, documentation
8 and related data, is placed into the public domain.
10 The orginal author is Karl Malbrain.
12 THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY
13 OF ANY KIND, NOT EVEN THE IMPLIED WARRANTY OF
14 MERCHANTABILITY. THE AUTHOR OF THIS SOFTWARE,
15 ASSUMES _NO_ RESPONSIBILITY FOR ANY CONSEQUENCE
16 RESULTING FROM THE USE, MODIFICATION, OR
17 REDISTRIBUTION OF THIS SOFTWARE.
20 // Please see the project home page for documentation
21 // code.google.com/p/high-concurrency-btree
23 #define _FILE_OFFSET_BITS 64
24 #define _LARGEFILE64_SOURCE
28 #include <linux/futex.h>
43 #define WIN32_LEAN_AND_MEAN
56 typedef unsigned long long uid;
59 typedef unsigned long long off64_t;
60 typedef unsigned short ushort;
61 typedef unsigned int uint;
64 #define BT_ro 0x6f72 // ro
65 #define BT_rw 0x7772 // rw
67 #define BT_latchtable 128 // number of latch manager slots
69 #define BT_maxbits 24 // maximum page size in bits
70 #define BT_minbits 9 // minimum page size in bits
71 #define BT_minpage (1 << BT_minbits) // minimum page size
72 #define BT_maxpage (1 << BT_maxbits) // maximum page size
75 There are five lock types for each node in three independent sets:
76 1. (set 1) AccessIntent: Sharable. Going to Read the node. Incompatible with NodeDelete.
77 2. (set 1) NodeDelete: Exclusive. About to release the node. Incompatible with AccessIntent.
78 3. (set 2) ReadLock: Sharable. Read the node. Incompatible with WriteLock.
79 4. (set 2) WriteLock: Exclusive. Modify the node. Incompatible with ReadLock and other WriteLocks.
80 5. (set 3) ParentLock: Exclusive. Have parent adopt/delete maximum foster child from the node.
91 // Define the length of the page and key pointers
95 // Page key slot definition.
97 // If BT_maxbits is 15 or less, you can save 4 bytes
98 // for each key stored by making the first two uints
99 // into ushorts. You can also save 4 bytes by removing
100 // the tod field from the key.
102 // Keys are marked dead, but remain on the page until
103 // cleanup is called. The fence key (highest key) for
104 // the page is always present, even after cleanup.
107 uint off:BT_maxbits; // page offset for key start
108 uint dead:1; // set for deleted key
109 uint tod; // time-stamp for key
110 unsigned char id[BtId]; // id associated with key
113 // The key structure occupies space at the upper end of
114 // each page. It's a length byte followed by the value
119 unsigned char key[1];
122 // The first part of an index page.
123 // It is immediately followed
124 // by the BtSlot array of keys.
126 typedef struct Page {
127 volatile uint cnt; // count of keys in page
128 volatile uint act; // count of active keys
129 volatile uint min; // next key offset
130 volatile uint foster; // count of foster children
131 unsigned char bits; // page size in bits
132 unsigned char lvl:7; // level of page
133 unsigned char dirty:1; // page needs to be cleaned
134 unsigned char right[BtId]; // page number to right
137 // mode & definition for latch implementation
140 Mutex = 1 << 0, // the mutex bit
141 Write = 1 << 1, // the writers bit
142 Share = 1 << 2, // reader count
143 PendRd = 1 << 12, // reader contended count
144 PendWr = 1 << 22 // writer contended count
148 QueRd = 1, // reader queue
149 QueWr = 2 // writer queue
152 // share is count of read accessors
153 // grant write lock when share == 0
156 volatile uint mutex:1; // 1 = busy
157 volatile uint write:1; // 1 = exclusive
158 volatile uint share:10; // count of readers holding locks
159 volatile uint readwait:10; // count of readers waiting
160 volatile uint writewait:10; // count of writers waiting
163 // hash table entries
167 volatile ushort slot; // Latch table entry at head of chain
170 // latch manager table structure
173 BtLatch readwr[1]; // read/write page lock
174 BtLatch access[1]; // Access Intent/Page delete
175 BtLatch parent[1]; // adoption of foster children
176 BtLatch busy[1]; // slot is being moved between chains
177 volatile ushort next; // next entry in hash table chain
178 volatile ushort prev; // prev entry in hash table chain
179 volatile ushort pin; // number of outstanding locks
180 volatile ushort hash; // hash slot entry is under
181 volatile uid page_no; // latch set page number
184 // The memory mapping pool table buffer manager entry
187 unsigned long long int lru; // number of times accessed
188 uid basepage; // mapped base page number
189 char *map; // mapped memory pointer
190 ushort pin; // mapped page pin counter
191 ushort slot; // slot index in this array
192 void *hashprev; // previous pool entry for the same hash idx
193 void *hashnext; // next pool entry for the same hash idx
195 HANDLE hmap; // Windows memory mapping handle
199 // structure for latch manager on ALLOC_page
202 struct Page alloc[2]; // next & free page_nos in right ptr
203 BtLatch lock[1]; // allocation area lite latch
204 ushort latchdeployed; // highest number of latch entries deployed
205 ushort nlatchpage; // number of latch pages at BT_latch
206 ushort latchtotal; // number of page latch entries
207 ushort latchhash; // number of latch hash table slots
208 ushort latchvictim; // next latch entry to examine
209 BtHashEntry table[0]; // the hash table
212 // The object structure for Btree access
215 uint page_size; // page size
216 uint page_bits; // page size in bits
217 uint seg_bits; // seg size in pages in bits
218 uint mode; // read-write mode
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 foster; // last search was to foster child
252 int found; // last delete was found
253 int err; // last error
268 extern void bt_close (BtDb *bt);
269 extern BtDb *bt_open (BtMgr *mgr);
270 extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod, uint lvl);
271 extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len);
272 extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
273 extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
274 extern uint bt_nextkey (BtDb *bt, uint slot);
276 // internal functions
277 BTERR bt_splitpage (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no);
278 uint bt_cleanpage(BtDb *bt, BtPage page, uint amt, uint slot);
279 BTERR bt_mergeleft (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no, uint lvl);
282 extern BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolsize, uint segsize, uint hashsize);
283 void bt_mgrclose (BtMgr *mgr);
285 // Helper functions to return cursor slot values
287 extern BtKey bt_key (BtDb *bt, uint slot);
288 extern uid bt_uid (BtDb *bt, uint slot);
289 extern uint bt_tod (BtDb *bt, uint slot);
291 // BTree page number constants
292 #define ALLOC_page 0 // allocation & lock manager hash table
293 #define ROOT_page 1 // root of the btree
294 #define LEAF_page 2 // first page of leaves
295 #define LATCH_page 3 // pages for lock manager
297 // Number of levels to create in a new BTree
301 // The page is allocated from low and hi ends.
302 // The key offsets and row-id's are allocated
303 // from the bottom, while the text of the key
304 // is allocated from the top. When the two
305 // areas meet, the page is split into two.
307 // A key consists of a length byte, two bytes of
308 // index number (0 - 65534), and up to 253 bytes
309 // of key value. Duplicate keys are discarded.
310 // Associated with each key is a 48 bit row-id.
312 // The b-tree root is always located at page 1.
313 // The first leaf page of level zero is always
314 // located on page 2.
316 // When to root page fills, it is split in two and
317 // the tree height is raised by a new root at page
318 // one with two keys.
320 // Deleted keys are marked with a dead bit until
321 // page cleanup The fence key for a node is always
322 // present, even after deletion and cleanup.
324 // Groups of pages called segments from the btree are
325 // cached with memory mapping. A hash table is used to keep
326 // track of the cached segments. This behaviour is controlled
327 // by the cache block size parameter to bt_open.
329 // To achieve maximum concurrency one page is locked at a time
330 // as the tree is traversed to find leaf key in question.
332 // An adoption traversal leaves the parent node locked as the
333 // tree is traversed to the level in quesiton.
335 // Page 0 is dedicated to lock for new page extensions,
336 // and chains empty pages together for reuse.
338 // Empty pages are chained together through the ALLOC page and reused.
340 // Access macros to address slot and key values from the page
342 #define slotptr(page, slot) (((BtSlot *)(page+1)) + (slot-1))
343 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
345 void bt_putid(unsigned char *dest, uid id)
350 dest[i] = (unsigned char)id, id >>= 8;
353 uid bt_getid(unsigned char *src)
358 for( i = 0; i < BtId; i++ )
359 id <<= 8, id |= *src++;
366 int sys_futex(void *addr1, int op, int val1, struct timespec *timeout, void *addr2, int val3)
368 return syscall(SYS_futex, addr1, op, val1, timeout, addr2, val3);
371 // wait until write lock mode is clear
372 // and add 1 to the share count
374 void bt_spinreadlock(BtLatch *latch, int private)
379 private = FUTEX_PRIVATE_FLAG;
382 // obtain latch mutex
383 if( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex ) {
388 // wait for writers to clear
389 // increment read waiters and wait
391 if( latch->write || latch->writewait ) {
392 __sync_fetch_and_add ((uint *)latch, PendRd);
393 prev = __sync_fetch_and_and ((uint *)latch, ~Mutex) & ~Mutex;
394 sys_futex( (uint *)latch, FUTEX_WAIT_BITSET | private, prev, NULL, NULL, QueRd );
395 __sync_fetch_and_sub ((uint *)latch, PendRd);
399 // increment reader lock count
400 // and release latch mutex
402 __sync_fetch_and_add ((uint *)latch, Share);
403 __sync_fetch_and_and ((uint *)latch, ~Mutex);
408 // wait for other read and write latches to relinquish
410 void bt_spinwritelock(BtLatch *latch, int private)
415 private = FUTEX_PRIVATE_FLAG;
418 // obtain latch mutex
419 if( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex ) {
424 // wait for write and reader count to clear
426 if( latch->write || latch->share ) {
427 __sync_fetch_and_add ((uint *)latch, PendWr);
428 prev = __sync_fetch_and_and ((uint *)latch, ~Mutex) & ~Mutex;
429 sys_futex( (uint *)latch, FUTEX_WAIT_BITSET | private, prev, NULL, NULL, QueWr );
430 __sync_fetch_and_sub ((uint *)latch, PendWr);
435 // release latch mutex
437 __sync_fetch_and_or ((uint *)latch, Write);
438 __sync_fetch_and_and ((uint *)latch, ~Mutex);
443 // try to obtain write lock
445 // return 1 if obtained,
448 int bt_spinwritetry(BtLatch *latch)
453 // abandon request if not taken
455 if( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex )
458 // see if write mode is available
460 if( !latch->write && !latch->share ) {
461 __sync_fetch_and_or ((uint *)latch, Write);
466 // release latch mutex
468 __sync_fetch_and_and ((uint *)latch, ~Mutex);
474 void bt_spinreleasewrite(BtLatch *latch, int private)
477 private = FUTEX_PRIVATE_FLAG;
479 // obtain latch mutex
481 while( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex )
484 __sync_fetch_and_and ((uint *)latch, ~Write);
488 if( latch->writewait )
489 if( sys_futex( (uint *)latch, FUTEX_WAKE_BITSET | private, 1, NULL, NULL, QueWr ) )
492 if( latch->readwait )
493 sys_futex( (uint *)latch, FUTEX_WAKE_BITSET | private, INT_MAX, NULL, NULL, QueRd );
495 // release latch mutex
498 __sync_fetch_and_and ((uint *)latch, ~Mutex);
501 // decrement reader count
503 void bt_spinreleaseread(BtLatch *latch, int private)
506 private = FUTEX_PRIVATE_FLAG;
508 // obtain latch mutex
510 while( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex )
513 __sync_fetch_and_sub ((uint *)latch, Share);
515 // wake waiting writers
517 if( !latch->share && latch->writewait )
518 sys_futex( (uint *)latch, FUTEX_WAKE_BITSET | private, 1, NULL, NULL, QueWr );
520 // release latch mutex
522 __sync_fetch_and_and ((uint *)latch, ~Mutex);
525 // link latch table entry into latch hash table
527 void bt_latchlink (BtDb *bt, ushort hashidx, ushort victim, uid page_no)
529 BtLatchSet *set = bt->mgr->latchsets + victim;
531 if( set->next = bt->mgr->latchmgr->table[hashidx].slot )
532 bt->mgr->latchsets[set->next].prev = victim;
534 bt->mgr->latchmgr->table[hashidx].slot = victim;
535 set->page_no = page_no;
542 void bt_unpinlatch (BtLatchSet *set)
545 __sync_fetch_and_add(&set->pin, -1);
547 _InterlockedDecrement16 (&set->pin);
551 // find existing latchset or inspire new one
552 // return with latchset pinned
554 BtLatchSet *bt_pinlatch (BtDb *bt, uid page_no)
556 ushort hashidx = page_no % bt->mgr->latchmgr->latchhash;
557 ushort slot, avail = 0, victim, idx;
560 // obtain read lock on hash table entry
562 bt_spinreadlock(bt->mgr->latchmgr->table[hashidx].latch, 0);
564 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
566 set = bt->mgr->latchsets + slot;
567 if( page_no == set->page_no )
569 } while( slot = set->next );
573 __sync_fetch_and_add(&set->pin, 1);
575 _InterlockedIncrement16 (&set->pin);
579 bt_spinreleaseread (bt->mgr->latchmgr->table[hashidx].latch, 0);
584 // try again, this time with write lock
586 bt_spinwritelock(bt->mgr->latchmgr->table[hashidx].latch, 0);
588 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
590 set = bt->mgr->latchsets + slot;
591 if( page_no == set->page_no )
593 if( !set->pin && !avail )
595 } while( slot = set->next );
597 // found our entry, or take over an unpinned one
599 if( slot || (slot = avail) ) {
600 set = bt->mgr->latchsets + slot;
602 __sync_fetch_and_add(&set->pin, 1);
604 _InterlockedIncrement16 (&set->pin);
606 set->page_no = page_no;
607 bt_spinreleasewrite(bt->mgr->latchmgr->table[hashidx].latch, 0);
611 // see if there are any unused entries
613 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, 1) + 1;
615 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchdeployed);
618 if( victim < bt->mgr->latchmgr->latchtotal ) {
619 set = bt->mgr->latchsets + victim;
621 __sync_fetch_and_add(&set->pin, 1);
623 _InterlockedIncrement16 (&set->pin);
625 bt_latchlink (bt, hashidx, victim, page_no);
626 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch, 0);
631 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, -1);
633 victim = _InterlockedDecrement16 (&bt->mgr->latchmgr->latchdeployed);
635 // find and reuse previous lock entry
639 victim = __sync_fetch_and_add(&bt->mgr->latchmgr->latchvictim, 1);
641 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchvictim) - 1;
643 // we don't use slot zero
645 if( victim %= bt->mgr->latchmgr->latchtotal )
646 set = bt->mgr->latchsets + victim;
650 // take control of our slot
651 // from other threads
653 if( set->pin || !bt_spinwritetry (set->busy) )
658 // try to get write lock on hash chain
659 // skip entry if not obtained
660 // or has outstanding locks
662 if( !bt_spinwritetry (bt->mgr->latchmgr->table[idx].latch) ) {
663 bt_spinreleasewrite (set->busy, 0);
668 bt_spinreleasewrite (set->busy, 0);
669 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch, 0);
673 // unlink our available victim from its hash chain
676 bt->mgr->latchsets[set->prev].next = set->next;
678 bt->mgr->latchmgr->table[idx].slot = set->next;
681 bt->mgr->latchsets[set->next].prev = set->prev;
683 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch, 0);
685 __sync_fetch_and_add(&set->pin, 1);
687 _InterlockedIncrement16 (&set->pin);
689 bt_latchlink (bt, hashidx, victim, page_no);
690 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch, 0);
691 bt_spinreleasewrite (set->busy, 0);
696 void bt_mgrclose (BtMgr *mgr)
701 // release mapped pages
702 // note that slot zero is never used
704 for( slot = 1; slot < mgr->poolmax; slot++ ) {
705 pool = mgr->pool + slot;
708 munmap (pool->map, (mgr->poolmask+1) << mgr->page_bits);
711 FlushViewOfFile(pool->map, 0);
712 UnmapViewOfFile(pool->map);
713 CloseHandle(pool->hmap);
719 munmap (mgr->latchsets, mgr->latchmgr->nlatchpage * mgr->page_size);
720 munmap (mgr->latchmgr, mgr->page_size);
722 FlushViewOfFile(mgr->latchmgr, 0);
723 UnmapViewOfFile(mgr->latchmgr);
724 CloseHandle(mgr->halloc);
731 free (mgr->pooladvise);
734 FlushFileBuffers(mgr->idx);
735 CloseHandle(mgr->idx);
736 GlobalFree (mgr->pool);
737 GlobalFree (mgr->hash);
738 GlobalFree (mgr->latch);
743 // close and release memory
745 void bt_close (BtDb *bt)
752 VirtualFree (bt->mem, 0, MEM_RELEASE);
757 // open/create new btree buffer manager
759 // call with file_name, BT_openmode, bits in page size (e.g. 16),
760 // size of mapped page pool (e.g. 8192)
762 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
764 uint lvl, attr, cacheblk, last, slot, idx;
765 uint nlatchpage, latchhash;
766 BtLatchMgr *latchmgr;
774 SYSTEM_INFO sysinfo[1];
777 // determine sanity of page size and buffer pool
779 if( bits > BT_maxbits )
781 else if( bits < BT_minbits )
785 return NULL; // must have buffer pool
788 mgr = calloc (1, sizeof(BtMgr));
790 mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
793 return free(mgr), NULL;
795 cacheblk = 4096; // minimum mmap segment size for unix
798 mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
799 attr = FILE_ATTRIBUTE_NORMAL;
800 mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
802 if( mgr->idx == INVALID_HANDLE_VALUE )
803 return GlobalFree(mgr), NULL;
805 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
806 GetSystemInfo(sysinfo);
807 cacheblk = sysinfo->dwAllocationGranularity;
811 latchmgr = malloc (BT_maxpage);
814 // read minimum page size to get root info
816 if( size = lseek (mgr->idx, 0L, 2) ) {
817 if( pread(mgr->idx, latchmgr, BT_minpage, 0) == BT_minpage )
818 bits = latchmgr->alloc->bits;
820 return free(mgr), free(latchmgr), NULL;
821 } else if( mode == BT_ro )
822 return free(latchmgr), bt_mgrclose (mgr), NULL;
824 latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
825 size = GetFileSize(mgr->idx, amt);
828 if( !ReadFile(mgr->idx, (char *)latchmgr, BT_minpage, amt, NULL) )
829 return bt_mgrclose (mgr), NULL;
830 bits = latchmgr->alloc->bits;
831 } else if( mode == BT_ro )
832 return bt_mgrclose (mgr), NULL;
835 mgr->page_size = 1 << bits;
836 mgr->page_bits = bits;
838 mgr->poolmax = poolmax;
841 if( cacheblk < mgr->page_size )
842 cacheblk = mgr->page_size;
844 // mask for partial memmaps
846 mgr->poolmask = (cacheblk >> bits) - 1;
848 // see if requested size of pages per memmap is greater
850 if( (1 << segsize) > mgr->poolmask )
851 mgr->poolmask = (1 << segsize) - 1;
855 while( (1 << mgr->seg_bits) <= mgr->poolmask )
858 mgr->hashsize = hashsize;
861 mgr->pool = calloc (poolmax, sizeof(BtPool));
862 mgr->hash = calloc (hashsize, sizeof(ushort));
863 mgr->latch = calloc (hashsize, sizeof(BtLatch));
864 mgr->pooladvise = calloc (poolmax, (mgr->poolmask + 8) / 8);
866 mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * sizeof(BtPool));
867 mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
868 mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtLatch));
874 // initialize an empty b-tree with latch page, root page, page of leaves
875 // and page(s) of latches
877 memset (latchmgr, 0, 1 << bits);
878 nlatchpage = BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1;
879 bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
880 latchmgr->alloc->bits = mgr->page_bits;
882 latchmgr->nlatchpage = nlatchpage;
883 latchmgr->latchtotal = nlatchpage * (mgr->page_size / sizeof(BtLatchSet));
885 // initialize latch manager
887 latchhash = (mgr->page_size - sizeof(BtLatchMgr)) / sizeof(BtHashEntry);
889 // size of hash table = total number of latchsets
891 if( latchhash > latchmgr->latchtotal )
892 latchhash = latchmgr->latchtotal;
894 latchmgr->latchhash = latchhash;
897 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
898 return bt_mgrclose (mgr), NULL;
900 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
901 return bt_mgrclose (mgr), NULL;
903 if( *amt < mgr->page_size )
904 return bt_mgrclose (mgr), NULL;
907 memset (latchmgr, 0, 1 << bits);
908 latchmgr->alloc->bits = mgr->page_bits;
910 for( lvl=MIN_lvl; lvl--; ) {
911 slotptr(latchmgr->alloc, 1)->off = mgr->page_size - 3;
912 bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
913 key = keyptr(latchmgr->alloc, 1);
914 key->len = 2; // create stopper key
917 latchmgr->alloc->min = mgr->page_size - 3;
918 latchmgr->alloc->lvl = lvl;
919 latchmgr->alloc->cnt = 1;
920 latchmgr->alloc->act = 1;
922 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
923 return bt_mgrclose (mgr), NULL;
925 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
926 return bt_mgrclose (mgr), NULL;
928 if( *amt < mgr->page_size )
929 return bt_mgrclose (mgr), NULL;
933 // clear out latch manager locks
934 // and rest of pages to round out segment
936 memset(latchmgr, 0, mgr->page_size);
939 while( last <= ((MIN_lvl + 1 + nlatchpage) | mgr->poolmask) ) {
941 pwrite(mgr->idx, latchmgr, mgr->page_size, last << mgr->page_bits);
943 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
944 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
945 return bt_mgrclose (mgr), NULL;
946 if( *amt < mgr->page_size )
947 return bt_mgrclose (mgr), NULL;
954 flag = PROT_READ | PROT_WRITE;
955 mgr->latchmgr = mmap (0, mgr->page_size, flag, MAP_SHARED, mgr->idx, ALLOC_page * mgr->page_size);
956 if( mgr->latchmgr == MAP_FAILED )
957 return bt_mgrclose (mgr), NULL;
958 mgr->latchsets = (BtLatchSet *)mmap (0, mgr->latchmgr->nlatchpage * mgr->page_size, flag, MAP_SHARED, mgr->idx, LATCH_page * mgr->page_size);
959 if( mgr->latchsets == MAP_FAILED )
960 return bt_mgrclose (mgr), NULL;
962 flag = PAGE_READWRITE;
963 mgr->halloc = CreateFileMapping(mgr->idx, NULL, flag, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size, NULL);
965 return bt_mgrclose (mgr), NULL;
967 flag = FILE_MAP_WRITE;
968 mgr->latchmgr = MapViewOfFile(mgr->halloc, flag, 0, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size);
970 return GetLastError(), bt_mgrclose (mgr), NULL;
972 mgr->latchsets = (void *)((char *)mgr->latchmgr + LATCH_page * mgr->page_size);
978 VirtualFree (latchmgr, 0, MEM_RELEASE);
983 // open BTree access method
984 // based on buffer manager
986 BtDb *bt_open (BtMgr *mgr)
988 BtDb *bt = malloc (sizeof(*bt));
990 memset (bt, 0, sizeof(*bt));
993 bt->mem = malloc (3 *mgr->page_size);
995 bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
997 bt->frame = (BtPage)bt->mem;
998 bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
999 bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
1001 memset(bt->zero, 0, mgr->page_size);
1005 // compare two keys, returning > 0, = 0, or < 0
1006 // as the comparison value
1008 int keycmp (BtKey key1, unsigned char *key2, uint len2)
1010 uint len1 = key1->len;
1013 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
1026 // find segment in pool
1027 // must be called with hashslot idx locked
1028 // return NULL if not there
1029 // otherwise return node
1031 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
1036 // compute start of hash chain in pool
1038 if( slot = bt->mgr->hash[idx] )
1039 pool = bt->mgr->pool + slot;
1043 page_no &= ~bt->mgr->poolmask;
1045 while( pool->basepage != page_no )
1046 if( pool = pool->hashnext )
1054 // add segment to hash table
1056 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
1061 pool->hashprev = pool->hashnext = NULL;
1062 pool->basepage = page_no & ~bt->mgr->poolmask;
1065 if( slot = bt->mgr->hash[idx] ) {
1066 node = bt->mgr->pool + slot;
1067 pool->hashnext = node;
1068 node->hashprev = pool;
1071 bt->mgr->hash[idx] = pool->slot;
1074 // find best segment to evict from buffer pool
1076 BtPool *bt_findlru (BtDb *bt, uint hashslot)
1078 unsigned long long int target = ~0LL;
1079 BtPool *pool = NULL, *node;
1084 node = bt->mgr->pool + hashslot;
1086 // scan pool entries under hash table slot
1091 if( node->lru > target )
1095 } while( node = node->hashnext );
1100 // map new buffer pool segment to virtual memory
1102 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
1104 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
1105 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
1109 flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
1110 pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED, bt->mgr->idx, off);
1111 if( pool->map == MAP_FAILED )
1112 return bt->err = BTERR_map;
1113 // clear out madvise issued bits
1114 memset (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8) / 8), 0, (bt->mgr->poolmask + 8)/8);
1116 flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
1117 pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
1119 return bt->err = BTERR_map;
1121 flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
1122 pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1124 return bt->err = BTERR_map;
1129 // calculate page within pool
1131 BtPage bt_page (BtDb *bt, BtPool *pool, uid page_no)
1133 uint subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1136 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1139 uint idx = subpage / 8;
1140 uint bit = subpage % 8;
1142 if( ~((bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] >> bit) & 1 ) {
1143 madvise (page, bt->mgr->page_size, MADV_WILLNEED);
1144 (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] |= 1 << bit;
1153 void bt_unpinpool (BtPool *pool)
1156 __sync_fetch_and_add(&pool->pin, -1);
1158 _InterlockedDecrement16 (&pool->pin);
1162 // find or place requested page in segment-pool
1163 // return pool table entry, incrementing pin
1165 BtPool *bt_pinpool(BtDb *bt, uid page_no)
1167 BtPool *pool, *node, *next;
1168 uint slot, idx, victim;
1171 // lock hash table chain
1173 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1174 bt_spinreadlock (&bt->mgr->latch[idx], 1);
1176 // look up in hash table
1178 if( pool = bt_findpool(bt, page_no, idx) ) {
1180 __sync_fetch_and_add(&pool->pin, 1);
1182 _InterlockedIncrement16 (&pool->pin);
1184 bt_spinreleaseread (&bt->mgr->latch[idx], 1);
1189 // upgrade to write lock
1191 bt_spinreleaseread (&bt->mgr->latch[idx], 1);
1192 bt_spinwritelock (&bt->mgr->latch[idx], 1);
1194 // try to find page in pool with write lock
1196 if( pool = bt_findpool(bt, page_no, idx) ) {
1198 __sync_fetch_and_add(&pool->pin, 1);
1200 _InterlockedIncrement16 (&pool->pin);
1202 bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
1207 // allocate a new pool node
1208 // and add to hash table
1211 slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
1213 slot = _InterlockedIncrement16 (&bt->mgr->poolcnt) - 1;
1216 if( ++slot < bt->mgr->poolmax ) {
1217 pool = bt->mgr->pool + slot;
1220 if( bt_mapsegment(bt, pool, page_no) )
1223 bt_linkhash(bt, pool, page_no, idx);
1225 __sync_fetch_and_add(&pool->pin, 1);
1227 _InterlockedIncrement16 (&pool->pin);
1229 bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
1233 // pool table is full
1234 // find best pool entry to evict
1237 __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
1239 _InterlockedDecrement16 (&bt->mgr->poolcnt);
1244 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
1246 victim = _InterlockedIncrement16 (&bt->mgr->evicted) - 1;
1248 victim %= bt->mgr->hashsize;
1250 // try to get write lock
1251 // skip entry if not obtained
1253 if( !bt_spinwritetry (&bt->mgr->latch[victim]) )
1256 // if cache entry is empty
1257 // or no slots are unpinned
1260 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
1261 bt_spinreleasewrite (&bt->mgr->latch[victim], 1);
1265 // unlink victim pool node from hash table
1267 if( node = pool->hashprev )
1268 node->hashnext = pool->hashnext;
1269 else if( node = pool->hashnext )
1270 bt->mgr->hash[victim] = node->slot;
1272 bt->mgr->hash[victim] = 0;
1274 if( node = pool->hashnext )
1275 node->hashprev = pool->hashprev;
1277 bt_spinreleasewrite (&bt->mgr->latch[victim], 1);
1279 // remove old file mapping
1281 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1283 FlushViewOfFile(pool->map, 0);
1284 UnmapViewOfFile(pool->map);
1285 CloseHandle(pool->hmap);
1289 // create new pool mapping
1290 // and link into hash table
1292 if( bt_mapsegment(bt, pool, page_no) )
1295 bt_linkhash(bt, pool, page_no, idx);
1297 __sync_fetch_and_add(&pool->pin, 1);
1299 _InterlockedIncrement16 (&pool->pin);
1301 bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
1306 // place write, read, or parent lock on requested page_no.
1307 // pin to buffer pool and return latchset pointer
1309 void bt_lockpage(BtLock mode, BtLatchSet *set)
1313 bt_spinreadlock (set->readwr, 0);
1316 bt_spinwritelock (set->readwr, 0);
1319 bt_spinreadlock (set->access, 0);
1322 bt_spinwritelock (set->access, 0);
1325 bt_spinwritelock (set->parent, 0);
1330 // remove write, read, or parent lock on requested page_no.
1332 void bt_unlockpage(BtLock mode, BtLatchSet *set)
1336 bt_spinreleaseread (set->readwr, 0);
1339 bt_spinreleasewrite (set->readwr, 0);
1342 bt_spinreleaseread (set->access, 0);
1345 bt_spinreleasewrite (set->access, 0);
1348 bt_spinreleasewrite (set->parent, 0);
1353 // allocate a new page and write page into it
1355 uid bt_newpage(BtDb *bt, BtPage page)
1363 // lock allocation page
1365 bt_spinwritelock(bt->mgr->latchmgr->lock, 0);
1367 // use empty chain first
1368 // else allocate empty page
1370 if( new_page = bt_getid(bt->mgr->latchmgr->alloc[1].right) ) {
1371 if( pool = bt_pinpool (bt, new_page) )
1372 pmap = bt_page (bt, pool, new_page);
1375 bt_putid(bt->mgr->latchmgr->alloc[1].right, bt_getid(pmap->right));
1376 bt_unpinpool (pool);
1379 new_page = bt_getid(bt->mgr->latchmgr->alloc->right);
1380 bt_putid(bt->mgr->latchmgr->alloc->right, new_page+1);
1384 // if writing first page of pool block, zero last page in the block
1386 if ( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1388 // use zero buffer to write zeros
1389 if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1390 return bt->err = BTERR_wrt, 0;
1393 // unlock allocation latch
1395 bt_spinreleasewrite(bt->mgr->latchmgr->lock, 0);
1397 if ( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1398 return bt->err = BTERR_wrt, 0;
1401 // unlock allocation latch
1403 bt_spinreleasewrite(bt->mgr->latchmgr->lock, 0);
1405 // bring new page into pool and copy page.
1406 // this will extend the file into the new pages.
1407 // NB -- no latch required
1409 if( pool = bt_pinpool (bt, new_page) )
1410 pmap = bt_page (bt, pool, new_page);
1414 memcpy(pmap, page, bt->mgr->page_size);
1415 bt_unpinpool (pool);
1420 // find slot in page for given key at a given level
1422 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1424 uint diff, higher = bt->page->cnt, low = 1, slot;
1426 // low is the lowest candidate, higher is already
1427 // tested as .ge. the given key, loop ends when they meet
1429 while( diff = higher - low ) {
1430 slot = low + ( diff >> 1 );
1431 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1440 // find and load page at given level for given key
1441 // leave page rd or wr locked as requested
1443 uint bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, BtLock lock)
1445 uid page_no = ROOT_page, prevpage = 0;
1446 BtLatchSet *set, *prevset;
1447 uint drill = 0xff, slot;
1448 uint mode, prevmode;
1452 // start at root of btree and drill down
1455 // determine lock mode of drill level
1456 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1458 // obtain latch set for this page
1460 bt->set = bt_pinlatch (bt, page_no);
1461 bt->page_no = page_no;
1463 // pin page contents
1465 if( bt->pool = bt_pinpool (bt, page_no) )
1466 bt->page = bt_page (bt, bt->pool, page_no);
1470 // obtain access lock using lock chaining with Access mode
1472 if( page_no > ROOT_page )
1473 bt_lockpage(BtLockAccess, bt->set);
1475 // now unlock and unpin our (possibly foster) parent
1478 bt_unlockpage(prevmode, prevset);
1479 bt_unpinlatch (prevset);
1480 bt_unpinpool (prevpool);
1484 // obtain read lock using lock chaining
1486 bt_lockpage(mode, bt->set);
1488 if( page_no > ROOT_page )
1489 bt_unlockpage(BtLockAccess, bt->set);
1491 // re-read and re-lock root after determining actual level of root
1493 if( page_no == ROOT_page )
1494 if( bt->page->lvl != drill) {
1495 drill = bt->page->lvl;
1497 if( lock == BtLockWrite && drill == lvl ) {
1498 bt_unlockpage(mode, bt->set);
1499 bt_unpinlatch (bt->set);
1500 bt_unpinpool (bt->pool);
1505 prevpage = bt->page_no;
1506 prevpool = bt->pool;
1510 // were we supposed to find a foster child?
1511 // if so, slide right onto it
1513 if( keycmp (keyptr(bt->page,bt->page->cnt), key, len) < 0 ) {
1514 page_no = bt_getid(bt->page->right);
1519 // find key on page at this level
1520 // and either descend to requested level
1521 // or return key slot
1523 slot = bt_findslot (bt, key, len);
1525 // is this slot < foster child area
1526 // on the requested level?
1528 // if so, return actual slot even if dead
1530 if( slot <= bt->page->cnt - bt->page->foster )
1532 return bt->foster = foster, slot;
1534 // find next active slot
1536 // note: foster children are never dead
1538 while( slotptr(bt->page, slot)->dead )
1539 if( slot++ < bt->page->cnt )
1542 // we are waiting for fence key posting
1543 page_no = bt_getid(bt->page->right);
1547 // is this slot < foster child area
1548 // if so, drill to next level
1550 if( slot <= bt->page->cnt - bt->page->foster )
1551 foster = 0, drill--;
1555 // continue right onto foster child
1556 // or down to next level.
1558 page_no = bt_getid(slotptr(bt->page, slot)->id);
1562 // return error on end of chain
1564 bt->err = BTERR_struct;
1565 return 0; // return error
1568 // remove empty page from the B-tree
1569 // by pulling our right node left over ourselves
1571 // call with bt->page, etc, set to page's locked parent
1572 // returns with page locked.
1574 BTERR bt_mergeright (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no, uint lvl, uint slot)
1576 BtLatchSet *rset, *pset, *rpset;
1577 BtPool *rpool, *ppool, *rppool;
1578 BtPage rpage, ppage, rppage;
1579 uid right, parent, rparent;
1583 // cache node's parent page
1585 parent = bt->page_no;
1590 // lock and map our right page
1591 // note that it cannot be our foster child
1592 // since the our node is empty
1593 // and it cannot be NULL because of the stopper
1594 // in the last right page
1596 bt_lockpage (BtLockWrite, set);
1598 // if we aren't dead yet
1603 if( right = bt_getid (page->right) )
1604 if( rpool = bt_pinpool (bt, right) )
1605 rpage = bt_page (bt, rpool, right);
1609 return bt->err = BTERR_struct;
1611 rset = bt_pinlatch (bt, right);
1613 // find our right neighbor
1615 if( ppage->act > 1 ) {
1616 for( idx = slot; idx++ < ppage->cnt; )
1617 if( !slotptr(ppage, idx)->dead )
1620 if( idx > ppage->cnt )
1621 return bt->err = BTERR_struct;
1623 // redirect right neighbor in parent to left node
1625 bt_putid(slotptr(ppage,idx)->id, page_no);
1628 // if parent has only our deleted page, e.g. no right neighbor
1629 // prepare to merge parent itself
1631 if( ppage->act == 1 ) {
1632 if( rparent = bt_getid (ppage->right) )
1633 if( rppool = bt_pinpool (bt, rparent) )
1634 rppage = bt_page (bt, rppool, rparent);
1638 return bt->err = BTERR_struct;
1640 rpset = bt_pinlatch (bt, rparent);
1641 bt_lockpage (BtLockWrite, rpset);
1643 // find our right neighbor on right parent page
1645 for( idx = 0; idx++ < rppage->cnt; )
1646 if( !slotptr(rppage, idx)->dead ) {
1647 bt_putid (slotptr(rppage, idx)->id, page_no);
1651 if( idx > rppage->cnt )
1652 return bt->err = BTERR_struct;
1655 // now that there are no more pointers to our right node
1656 // we can wait for delete lock on it
1658 bt_lockpage(BtLockDelete, rset);
1659 bt_lockpage(BtLockWrite, rset);
1661 // pull contents of right page into our empty page
1663 memcpy (page, rpage, bt->mgr->page_size);
1665 // ready to release right parent lock
1666 // now that we have a new page in place
1668 if( ppage->act == 1 ) {
1669 bt_unlockpage (BtLockWrite, rpset);
1670 bt_unpinlatch (rpset);
1671 bt_unpinpool (rppool);
1674 // add killed right block to free chain
1677 bt_spinwritelock(bt->mgr->latchmgr->lock);
1679 // store free chain in allocation page second right
1681 bt_putid(rpage->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1682 bt_putid(bt->mgr->latchmgr->alloc[1].right, right);
1684 // unlock latch mgr and right page
1686 bt_unlockpage(BtLockDelete, rset);
1687 bt_unlockpage(BtLockWrite, rset);
1688 bt_unpinlatch (rset);
1689 bt_unpinpool (rpool);
1691 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1693 // delete our obsolete fence key from our parent
1695 slotptr(ppage, slot)->dead = 1;
1698 // if our parent now empty
1699 // remove it from the tree
1701 if( ppage->act-- == 1 )
1702 if( bt_mergeleft (bt, ppage, ppool, pset, parent, lvl+1) )
1706 bt_unlockpage (BtLockWrite, pset);
1707 bt_unpinlatch (pset);
1708 bt_unpinpool (ppool);
1714 // remove empty page from the B-tree
1715 // try merging left first. If no left
1716 // sibling, then merge right.
1718 // call with page loaded and locked,
1719 // return with page locked.
1721 BTERR bt_mergeleft (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no, uint lvl)
1723 unsigned char fencekey[256], postkey[256];
1724 uint slot, idx, postfence = 0;
1725 BtLatchSet *lset, *pset;
1726 BtPool *lpool, *ppool;
1727 BtPage lpage, ppage;
1731 ptr = keyptr(page, page->cnt);
1732 memcpy(fencekey, ptr, ptr->len + 1);
1733 bt_unlockpage (BtLockWrite, set);
1735 // load and lock our parent
1738 if( !(slot = bt_loadpage (bt, fencekey+1, *fencekey, lvl+1, BtLockWrite)) )
1741 parent = bt->page_no;
1746 // wait until we are not a foster child
1749 bt_unlockpage (BtLockWrite, pset);
1750 bt_unpinlatch (pset);
1751 bt_unpinpool (ppool);
1760 // find our left neighbor in our parent page
1762 for( idx = slot; --idx; )
1763 if( !slotptr(ppage, idx)->dead )
1766 // if no left neighbor, do right merge
1769 return bt_mergeright (bt, page, pool, set, page_no, lvl, slot);
1771 // lock and map our left neighbor's page
1773 left = bt_getid (slotptr(ppage, idx)->id);
1775 if( lpool = bt_pinpool (bt, left) )
1776 lpage = bt_page (bt, lpool, left);
1780 lset = bt_pinlatch (bt, left);
1781 bt_lockpage(BtLockWrite, lset);
1783 // wait until foster sibling is in our parent
1785 if( bt_getid (lpage->right) != page_no ) {
1786 bt_unlockpage (BtLockWrite, pset);
1787 bt_unpinlatch (pset);
1788 bt_unpinpool (ppool);
1789 bt_unlockpage (BtLockWrite, lset);
1790 bt_unpinlatch (lset);
1791 bt_unpinpool (lpool);
1800 // since our page will have no more pointers to it,
1801 // obtain Delete lock and wait for write locks to clear
1803 bt_lockpage(BtLockDelete, set);
1804 bt_lockpage(BtLockWrite, set);
1806 // if we aren't dead yet,
1807 // get ready for exit
1810 bt_unlockpage(BtLockDelete, set);
1811 bt_unlockpage(BtLockWrite, lset);
1812 bt_unpinlatch (lset);
1813 bt_unpinpool (lpool);
1817 // are we are the fence key for our parent?
1818 // if so, grab our old fence key
1820 if( postfence = slot == ppage->cnt ) {
1821 ptr = keyptr (ppage, ppage->cnt);
1822 memcpy(fencekey, ptr, ptr->len + 1);
1823 memset(slotptr(ppage, ppage->cnt), 0, sizeof(BtSlot));
1825 // clear out other dead slots
1827 while( --ppage->cnt )
1828 if( slotptr(ppage, ppage->cnt)->dead )
1829 memset(slotptr(ppage, ppage->cnt), 0, sizeof(BtSlot));
1833 ptr = keyptr (ppage, ppage->cnt);
1834 memcpy(postkey, ptr, ptr->len + 1);
1836 slotptr(ppage,slot)->dead = 1;
1841 // push our right neighbor pointer to our left
1843 memcpy (lpage->right, page->right, BtId);
1845 // add ourselves to free chain
1848 bt_spinwritelock(bt->mgr->latchmgr->lock);
1850 // store free chain in allocation page second right
1851 bt_putid(page->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1852 bt_putid(bt->mgr->latchmgr->alloc[1].right, page_no);
1854 // unlock latch mgr and pages
1856 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1857 bt_unlockpage(BtLockWrite, lset);
1858 bt_unpinlatch (lset);
1859 bt_unpinpool (lpool);
1861 // release our node's delete lock
1863 bt_unlockpage(BtLockDelete, set);
1866 bt_unlockpage (BtLockWrite, pset);
1867 bt_unpinpool (ppool);
1869 // do we need to post parent's fence key in its parent?
1871 if( !postfence || parent == ROOT_page ) {
1872 bt_unpinlatch (pset);
1877 // interlock parent fence post
1879 bt_lockpage (BtLockParent, pset);
1881 // load parent's parent page
1883 if( !(slot = bt_loadpage (bt, fencekey+1, *fencekey, lvl+2, BtLockWrite)) )
1886 if( !(slot = bt_cleanpage (bt, bt->page, *fencekey, slot)) )
1887 if( bt_splitpage (bt, bt->page, bt->pool, bt->set, bt->page_no) )
1894 page->min -= *postkey + 1;
1895 ((unsigned char *)page)[page->min] = *postkey;
1896 memcpy ((unsigned char *)page + page->min +1, postkey + 1, *postkey );
1897 slotptr(page, slot)->off = page->min;
1899 bt_unlockpage (BtLockParent, pset);
1900 bt_unpinlatch (pset);
1902 bt_unlockpage (BtLockWrite, bt->set);
1903 bt_unpinlatch (bt->set);
1904 bt_unpinpool (bt->pool);
1910 // find and delete key on page by marking delete flag bit
1911 // if page becomes empty, delete it from the btree
1913 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len)
1922 if( !(slot = bt_loadpage (bt, key, len, 0, BtLockWrite)) )
1925 page_no = bt->page_no;
1930 // if key is found delete it, otherwise ignore request
1932 ptr = keyptr(page, slot);
1934 if( bt->found = !keycmp (ptr, key, len) )
1935 if( bt->found = slotptr(page, slot)->dead == 0 ) {
1936 slotptr(page,slot)->dead = 1;
1937 if( slot < page->cnt )
1940 if( bt_mergeleft (bt, page, pool, set, page_no, 0) )
1944 bt_unlockpage(BtLockWrite, set);
1945 bt_unpinlatch (set);
1946 bt_unpinpool (pool);
1950 // find key in leaf level and return row-id
1952 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1958 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1959 ptr = keyptr(bt->page, slot);
1963 // if key exists, return row-id
1964 // otherwise return 0
1966 if( slot <= bt->page->cnt && !keycmp (ptr, key, len) )
1967 id = bt_getid(slotptr(bt->page,slot)->id);
1971 bt_unlockpage (BtLockRead, bt->set);
1972 bt_unpinlatch (bt->set);
1973 bt_unpinpool (bt->pool);
1977 // check page for space available,
1978 // clean if necessary and return
1979 // 0 - page needs splitting
1980 // >0 new slot value
1982 uint bt_cleanpage(BtDb *bt, BtPage page, uint amt, uint slot)
1984 uint nxt = bt->mgr->page_size;
1985 uint cnt = 0, idx = 0;
1986 uint max = page->cnt;
1990 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1993 // skip cleanup if nothing to reclaim
1998 memcpy (bt->frame, page, bt->mgr->page_size);
2000 // skip page info and set rest of page to zero
2002 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
2006 // try cleaning up page first
2008 // always leave fence key in the array
2009 // otherwise, remove deleted key
2011 // note: foster children are never dead
2013 while( cnt++ < max ) {
2016 if( cnt < max && slotptr(bt->frame,cnt)->dead )
2021 key = keyptr(bt->frame, cnt);
2022 nxt -= key->len + 1;
2023 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2026 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
2027 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
2029 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2030 slotptr(page, idx)->off = nxt;
2036 // see if page has enough space now, or does it need splitting?
2038 if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
2044 // add key to current page
2045 // page must already be writelocked
2047 void bt_addkeytopage (BtDb *bt, BtPage page, uint slot, unsigned char *key, uint len, uid id, uint tod)
2051 // find next available dead slot and copy key onto page
2052 // note that foster children on the page are never dead
2054 // look for next hole, but stay back from the fence key
2056 for( idx = slot; idx < page->cnt; idx++ )
2057 if( slotptr(page, idx)->dead )
2060 if( idx == page->cnt )
2065 // now insert key into array before slot
2068 *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
2070 page->min -= len + 1;
2071 ((unsigned char *)page)[page->min] = len;
2072 memcpy ((unsigned char *)page + page->min +1, key, len );
2074 bt_putid(slotptr(page,slot)->id, id);
2075 slotptr(page, slot)->off = page->min;
2076 slotptr(page, slot)->tod = tod;
2077 slotptr(page, slot)->dead = 0;
2080 // split the root and raise the height of the btree
2081 // call with current page locked and page no of foster child
2082 // return with current page (root) unlocked
2084 BTERR bt_splitroot(BtDb *bt, uid right)
2086 uint nxt = bt->mgr->page_size;
2087 unsigned char fencekey[256];
2088 BtPage root = bt->page;
2092 // Obtain an empty page to use, and copy the left page
2093 // contents into it from the root. Strip foster child key.
2094 // (it's the stopper key)
2096 memset (slotptr(root, root->cnt), 0, sizeof(BtSlot));
2102 // Save left fence key.
2104 key = keyptr(root, root->cnt);
2105 memcpy (fencekey, key, key->len + 1);
2107 // copy the lower keys into a new left page
2109 if( !(new_page = bt_newpage(bt, root)) )
2112 // preserve the page info at the bottom
2113 // and set rest of the root to zero
2115 memset (root+1, 0, bt->mgr->page_size - sizeof(*root));
2117 // insert left fence key on empty newroot page
2119 nxt -= *fencekey + 1;
2120 memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
2121 bt_putid(slotptr(root, 1)->id, new_page);
2122 slotptr(root, 1)->off = nxt;
2124 // insert stopper key on newroot page
2125 // and increase the root height
2131 memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
2132 bt_putid(slotptr(root, 2)->id, right);
2133 slotptr(root, 2)->off = nxt;
2135 bt_putid(root->right, 0);
2136 root->min = nxt; // reset lowest used offset and key count
2141 // release and unpin root (bt->page)
2143 bt_unlockpage(BtLockWrite, bt->set);
2144 bt_unpinlatch (bt->set);
2145 bt_unpinpool (bt->pool);
2149 // split already locked full node
2150 // return unlocked and unpinned.
2152 BTERR bt_splitpage (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no)
2154 uint slot, cnt, idx, max, nxt = bt->mgr->page_size;
2155 unsigned char fencekey[256];
2156 uint tod = time(NULL);
2157 uint lvl = page->lvl;
2161 // initialize frame buffer for right node
2163 memset (bt->frame, 0, bt->mgr->page_size);
2164 max = page->cnt - page->foster;
2168 // split higher half of keys to bt->frame
2169 // leaving old foster children in the left node,
2170 // and adding a new foster child there.
2172 while( cnt++ < max ) {
2173 key = keyptr(page, cnt);
2174 nxt -= key->len + 1;
2175 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
2176 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
2177 if( !(slotptr(bt->frame, idx)->dead = slotptr(page, cnt)->dead) )
2179 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
2180 slotptr(bt->frame, idx)->off = nxt;
2183 // transfer right link node to new right node
2185 if( page_no > ROOT_page )
2186 memcpy (bt->frame->right, page->right, BtId);
2188 bt->frame->bits = bt->mgr->page_bits;
2189 bt->frame->min = nxt;
2190 bt->frame->cnt = idx;
2191 bt->frame->lvl = lvl;
2193 // get new free page and write right frame to it.
2195 if( !(new_page = bt_newpage(bt, bt->frame)) )
2198 // remember fence key for new right page to add
2199 // as foster child to the left node
2201 key = keyptr(bt->frame, idx);
2202 memcpy (fencekey, key, key->len + 1);
2204 // update lower keys and foster children to continue in old page
2206 memcpy (bt->frame, page, bt->mgr->page_size);
2207 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
2208 nxt = bt->mgr->page_size;
2214 // assemble page of smaller keys
2215 // to remain in the old page
2217 while( cnt++ < max / 2 ) {
2218 key = keyptr(bt->frame, cnt);
2219 nxt -= key->len + 1;
2220 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2221 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
2222 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
2224 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2225 slotptr(page, idx)->off = nxt;
2228 // insert new foster child for right page in queue
2229 // before any of the current foster children
2231 nxt -= *fencekey + 1;
2232 memcpy ((unsigned char *)page + nxt, fencekey, *fencekey + 1);
2234 bt_putid (slotptr(page,++idx)->id, new_page);
2235 slotptr(page, idx)->tod = tod;
2236 slotptr(page, idx)->off = nxt;
2240 // continue with old foster child keys
2241 // note that none will be dead
2243 cnt = bt->frame->cnt - bt->frame->foster;
2245 while( cnt++ < bt->frame->cnt ) {
2246 key = keyptr(bt->frame, cnt);
2247 nxt -= key->len + 1;
2248 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2249 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
2250 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2251 slotptr(page, idx)->off = nxt;
2258 // link new right page
2260 bt_putid (page->right, new_page);
2262 // if current page is the root page, split it
2264 if( page_no == ROOT_page )
2265 return bt_splitroot (bt, new_page);
2267 // release wr lock on our page
2269 bt_unlockpage (BtLockWrite, set);
2271 // obtain ParentModification lock for current page
2272 // to fix new fence key and oldest foster child on page
2274 bt_lockpage (BtLockParent, set);
2276 // get our new fence key to insert in parent node
2278 bt_lockpage (BtLockRead, set);
2280 key = keyptr(page, page->cnt-1);
2281 memcpy (fencekey, key, key->len+1);
2283 bt_unlockpage (BtLockRead, set);
2285 if( bt_insertkey (bt, fencekey + 1, *fencekey, page_no, tod, lvl + 1) )
2288 // lock our page for writing
2290 bt_lockpage (BtLockRead, set);
2292 // switch old parent key from us to our oldest foster child
2294 key = keyptr(page, page->cnt);
2295 memcpy (fencekey, key, key->len+1);
2297 new_page = bt_getid (slotptr(page, page->cnt)->id);
2298 bt_unlockpage (BtLockRead, set);
2300 if( bt_insertkey (bt, fencekey + 1, *fencekey, new_page, tod, lvl + 1) )
2303 // now that it has its own parent pointer,
2304 // remove oldest foster child from our page
2306 bt_lockpage (BtLockWrite, set);
2307 memset (slotptr(page, page->cnt), 0, sizeof(BtSlot));
2313 bt_unlockpage (BtLockParent, set);
2315 // if this emptied page,
2316 // undo the foster child
2319 if( bt_mergeleft (bt, page, pool, set, page_no, lvl) )
2324 bt_unlockpage (BtLockWrite, set);
2325 bt_unpinlatch (set);
2326 bt_unpinpool (pool);
2330 // Insert new key into the btree at leaf level.
2332 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod, uint lvl)
2339 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
2340 ptr = keyptr(bt->page, slot);
2344 bt->err = BTERR_ovflw;
2348 // if key already exists, update id and return
2352 if( !keycmp (ptr, key, len) ) {
2353 if( slotptr(page, slot)->dead )
2355 slotptr(page, slot)->dead = 0;
2356 slotptr(page, slot)->tod = tod;
2357 bt_putid(slotptr(page,slot)->id, id);
2358 bt_unlockpage(BtLockWrite, bt->set);
2359 bt_unpinlatch (bt->set);
2360 bt_unpinpool (bt->pool);
2364 // check if page has enough space
2366 if( slot = bt_cleanpage (bt, bt->page, len, slot) )
2369 if( bt_splitpage (bt, bt->page, bt->pool, bt->set, bt->page_no) )
2373 bt_addkeytopage (bt, bt->page, slot, key, len, id, tod);
2375 bt_unlockpage (BtLockWrite, bt->set);
2376 bt_unpinlatch (bt->set);
2377 bt_unpinpool (bt->pool);
2381 // cache page of keys into cursor and return starting slot for given key
2383 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2387 // cache page for retrieval
2388 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
2389 memcpy (bt->cursor, bt->page, bt->mgr->page_size);
2391 bt->cursor_page = bt->page_no;
2393 bt_unlockpage(BtLockRead, bt->set);
2394 bt_unpinlatch (bt->set);
2395 bt_unpinpool (bt->pool);
2399 // return next slot for cursor page
2400 // or slide cursor right into next page
2402 uint bt_nextkey (BtDb *bt, uint slot)
2410 right = bt_getid(bt->cursor->right);
2411 while( slot++ < bt->cursor->cnt - bt->cursor->foster )
2412 if( slotptr(bt->cursor,slot)->dead )
2414 else if( right || (slot < bt->cursor->cnt - bt->cursor->foster) )
2422 bt->cursor_page = right;
2423 if( pool = bt_pinpool (bt, right) )
2424 page = bt_page (bt, pool, right);
2428 set = bt_pinlatch (bt, right);
2429 bt_lockpage(BtLockRead, set);
2431 memcpy (bt->cursor, page, bt->mgr->page_size);
2433 bt_unlockpage(BtLockRead, set);
2434 bt_unpinlatch (set);
2435 bt_unpinpool (pool);
2442 BtKey bt_key(BtDb *bt, uint slot)
2444 return keyptr(bt->cursor, slot);
2447 uid bt_uid(BtDb *bt, uint slot)
2449 return bt_getid(slotptr(bt->cursor,slot)->id);
2452 uint bt_tod(BtDb *bt, uint slot)
2454 return slotptr(bt->cursor,slot)->tod;
2467 // standalone program to index file of keys
2468 // then list them onto std-out
2471 void *index_file (void *arg)
2473 uint __stdcall index_file (void *arg)
2476 int line = 0, found = 0, cnt = 0;
2477 uid next, page_no = LEAF_page; // start on first page of leaves
2478 unsigned char key[256];
2479 ThreadArg *args = arg;
2480 int ch, len = 0, slot;
2489 bt = bt_open (args->mgr);
2492 switch(args->type | 0x20)
2495 fprintf(stderr, "started indexing for %s\n", args->infile);
2496 if( in = fopen (args->infile, "rb") )
2497 while( ch = getc(in), ch != EOF )
2502 if( args->num == 1 )
2503 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2505 else if( args->num )
2506 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2508 if( bt_insertkey (bt, key, len, line, *tod, 0) )
2509 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2512 else if( len < 255 )
2514 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
2518 fprintf(stderr, "started deleting keys for %s\n", args->infile);
2519 if( in = fopen (args->infile, "rb") )
2520 while( ch = getc(in), ch != EOF )
2524 if( args->num == 1 )
2525 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2527 else if( args->num )
2528 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2530 if( bt_deletekey (bt, key, len) )
2531 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2534 else if( len < 255 )
2536 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2540 fprintf(stderr, "started finding keys for %s\n", args->infile);
2541 if( in = fopen (args->infile, "rb") )
2542 while( ch = getc(in), ch != EOF )
2546 if( args->num == 1 )
2547 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2549 else if( args->num )
2550 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2552 if( bt_findkey (bt, key, len) )
2555 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2558 else if( len < 255 )
2560 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2566 fprintf(stderr, "started reading\n");
2568 if( slot = bt_startkey (bt, key, len) )
2571 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
2573 while( slot = bt_nextkey (bt, slot) ) {
2574 ptr = bt_key(bt, slot);
2575 fwrite (ptr->key, ptr->len, 1, stdout);
2576 fputc ('\n', stdout);
2582 fprintf(stderr, "started reading\n");
2585 if( pool = bt_pinpool (bt, page_no) )
2586 page = bt_page (bt, pool, page_no);
2589 set = bt_pinlatch (bt, page_no);
2590 bt_lockpage (BtLockRead, set);
2592 next = bt_getid (page->right);
2593 bt_unlockpage (BtLockRead, set);
2594 bt_unpinlatch (set);
2595 bt_unpinpool (pool);
2596 } while( page_no = next );
2598 cnt--; // remove stopper key
2599 fprintf(stderr, " Total keys read %d\n", cnt);
2611 typedef struct timeval timer;
2613 int main (int argc, char **argv)
2615 int idx, cnt, len, slot, err;
2616 int segsize, bits = 16;
2621 time_t start[1], stop[1];
2634 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]);
2635 fprintf (stderr, " where page_bits is the page size in bits\n");
2636 fprintf (stderr, " mapped_segments is the number of mmap segments in buffer pool\n");
2637 fprintf (stderr, " seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2638 fprintf (stderr, " line_numbers = 1 to append line numbers to keys\n");
2639 fprintf (stderr, " src_file1 thru src_filen are files of keys separated by newline\n");
2644 gettimeofday(&start, NULL);
2650 bits = atoi(argv[3]);
2653 poolsize = atoi(argv[4]);
2656 fprintf (stderr, "Warning: no mapped_pool\n");
2658 if( poolsize > 65535 )
2659 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2662 segsize = atoi(argv[5]);
2664 segsize = 4; // 16 pages per mmap segment
2667 num = atoi(argv[6]);
2671 threads = malloc (cnt * sizeof(pthread_t));
2673 threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2675 args = malloc (cnt * sizeof(ThreadArg));
2677 mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2680 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2686 for( idx = 0; idx < cnt; idx++ ) {
2687 args[idx].infile = argv[idx + 7];
2688 args[idx].type = argv[2][0];
2689 args[idx].mgr = mgr;
2690 args[idx].num = num;
2691 args[idx].idx = idx;
2693 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2694 fprintf(stderr, "Error creating thread %d\n", err);
2696 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2700 // wait for termination
2703 for( idx = 0; idx < cnt; idx++ )
2704 pthread_join (threads[idx], NULL);
2705 gettimeofday(&stop, NULL);
2706 real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2708 WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2710 for( idx = 0; idx < cnt; idx++ )
2711 CloseHandle(threads[idx]);
2714 real_time = 1000 * (*stop - *start);
2716 fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);