1 // foster btree version f
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
40 #define WIN32_LEAN_AND_MEAN
53 typedef unsigned long long uid;
56 typedef unsigned long long off64_t;
57 typedef unsigned short ushort;
58 typedef unsigned int uint;
61 #define BT_ro 0x6f72 // ro
62 #define BT_rw 0x7772 // rw
64 #define BT_latchtable 128 // number of latch manager slots
66 #define BT_maxbits 24 // maximum page size in bits
67 #define BT_minbits 9 // minimum page size in bits
68 #define BT_minpage (1 << BT_minbits) // minimum page size
69 #define BT_maxpage (1 << BT_maxbits) // maximum page size
72 There are five lock types for each node in three independent sets:
73 1. (set 1) AccessIntent: Sharable. Going to Read the node. Incompatible with NodeDelete.
74 2. (set 1) NodeDelete: Exclusive. About to release the node. Incompatible with AccessIntent.
75 3. (set 2) ReadLock: Sharable. Read the node. Incompatible with WriteLock.
76 4. (set 2) WriteLock: Exclusive. Modify the node. Incompatible with ReadLock and other WriteLocks.
77 5. (set 3) ParentLock: Exclusive. Have parent adopt/delete maximum foster child from the node.
88 // Define the length of the page and key pointers
92 // Page key slot definition.
94 // If BT_maxbits is 15 or less, you can save 4 bytes
95 // for each key stored by making the first two uints
96 // into ushorts. You can also save 4 bytes by removing
97 // the tod field from the key.
99 // Keys are marked dead, but remain on the page until
100 // cleanup is called. The fence key (highest key) for
101 // the page is always present, even after cleanup.
104 uint off:BT_maxbits; // page offset for key start
105 uint dead:1; // set for deleted key
106 uint tod; // time-stamp for key
107 unsigned char id[BtId]; // id associated with key
110 // The key structure occupies space at the upper end of
111 // each page. It's a length byte followed by the value
116 unsigned char key[1];
119 // The first part of an index page.
120 // It is immediately followed
121 // by the BtSlot array of keys.
123 typedef struct Page {
124 volatile uint cnt; // count of keys in page
125 volatile uint act; // count of active keys
126 volatile uint min; // next key offset
127 volatile uint foster; // count of foster children
128 unsigned char bits; // page size in bits
129 unsigned char lvl:7; // level of page
130 unsigned char dirty:1; // page needs to be cleaned
131 unsigned char right[BtId]; // page number to right
134 // mode & definition for hash latch implementation
143 // mutex locks the other fields
144 // exclusive is set for write access
145 // share is count of read accessors
148 volatile ushort mutex:1;
149 volatile ushort exclusive:1;
150 volatile ushort pending:1;
151 volatile ushort share:13;
154 // hash table entries
157 BtSpinLatch latch[1];
158 volatile ushort slot; // Latch table entry at head of chain
161 // latch manager table structure
164 BtSpinLatch readwr[1]; // read/write page lock
165 BtSpinLatch access[1]; // Access Intent/Page delete
166 BtSpinLatch parent[1]; // adoption of foster children
167 BtSpinLatch busy[1]; // slot is being moved between chains
168 volatile ushort next; // next entry in hash table chain
169 volatile ushort prev; // prev entry in hash table chain
170 volatile ushort pin; // number of outstanding locks
171 volatile ushort hash; // hash slot entry is under
172 volatile uid page_no; // latch set page number
175 // The memory mapping pool table buffer manager entry
178 unsigned long long int lru; // number of times accessed
179 uid basepage; // mapped base page number
180 char *map; // mapped memory pointer
181 ushort pin; // mapped page pin counter
182 ushort slot; // slot index in this array
183 void *hashprev; // previous pool entry for the same hash idx
184 void *hashnext; // next pool entry for the same hash idx
186 HANDLE hmap; // Windows memory mapping handle
190 // structure for latch manager on ALLOC_page
193 struct Page alloc[2]; // next & free page_nos in right ptr
194 BtSpinLatch lock[1]; // allocation area lite latch
195 ushort latchdeployed; // highest number of latch entries deployed
196 ushort nlatchpage; // number of latch pages at BT_latch
197 ushort latchtotal; // number of page latch entries
198 ushort latchhash; // number of latch hash table slots
199 ushort latchvictim; // next latch entry to examine
200 BtHashEntry table[0]; // the hash table
203 // The object structure for Btree access
206 uint page_size; // page size
207 uint page_bits; // page size in bits
208 uint seg_bits; // seg size in pages in bits
209 uint mode; // read-write mode
212 char *pooladvise; // bit maps for pool page advisements
216 ushort poolcnt; // highest page pool node in use
217 ushort poolmax; // highest page pool node allocated
218 ushort poolmask; // total number of pages in mmap segment - 1
219 ushort hashsize; // size of Hash Table for pool entries
220 ushort evicted; // last evicted hash table slot
221 ushort *hash; // hash table of pool entries
222 BtPool *pool; // memory pool page segments
223 BtSpinLatch *latch; // latches for pool hash slots
224 BtLatchMgr *latchmgr; // mapped latch page from allocation page
225 BtLatchSet *latchsets; // mapped latch set from latch pages
227 HANDLE halloc; // allocation and latch table handle
232 BtMgr *mgr; // buffer manager for thread
233 BtPage cursor; // cached frame for start/next (never mapped)
234 BtPage frame; // spare frame for the page split (never mapped)
235 BtPage zero; // page frame for zeroes at end of file
236 BtPage page; // current page
237 uid page_no; // current page number
238 uid cursor_page; // current cursor page number
239 BtLatchSet *set; // current page latch set
240 BtPool *pool; // current page pool
241 unsigned char *mem; // frame, cursor, page memory buffer
242 int foster; // last search was to foster child
243 int found; // last delete was found
244 int err; // last error
259 extern void bt_close (BtDb *bt);
260 extern BtDb *bt_open (BtMgr *mgr);
261 extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod, uint lvl);
262 extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len);
263 extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
264 extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
265 extern uint bt_nextkey (BtDb *bt, uint slot);
267 // internal functions
268 BTERR bt_splitpage (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no);
269 uint bt_cleanpage(BtDb *bt, BtPage page, uint amt, uint slot);
270 BTERR bt_mergeleft (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no, uint lvl);
273 extern BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolsize, uint segsize, uint hashsize);
274 void bt_mgrclose (BtMgr *mgr);
276 // Helper functions to return cursor slot values
278 extern BtKey bt_key (BtDb *bt, uint slot);
279 extern uid bt_uid (BtDb *bt, uint slot);
280 extern uint bt_tod (BtDb *bt, uint slot);
282 // BTree page number constants
283 #define ALLOC_page 0 // allocation & lock manager hash table
284 #define ROOT_page 1 // root of the btree
285 #define LEAF_page 2 // first page of leaves
286 #define LATCH_page 3 // pages for lock manager
288 // Number of levels to create in a new BTree
292 // The page is allocated from low and hi ends.
293 // The key offsets and row-id's are allocated
294 // from the bottom, while the text of the key
295 // is allocated from the top. When the two
296 // areas meet, the page is split into two.
298 // A key consists of a length byte, two bytes of
299 // index number (0 - 65534), and up to 253 bytes
300 // of key value. Duplicate keys are discarded.
301 // Associated with each key is a 48 bit row-id.
303 // The b-tree root is always located at page 1.
304 // The first leaf page of level zero is always
305 // located on page 2.
307 // When to root page fills, it is split in two and
308 // the tree height is raised by a new root at page
309 // one with two keys.
311 // Deleted keys are marked with a dead bit until
312 // page cleanup The fence key for a node is always
313 // present, even after deletion and cleanup.
315 // Groups of pages called segments from the btree are
316 // cached with memory mapping. A hash table is used to keep
317 // track of the cached segments. This behaviour is controlled
318 // by the cache block size parameter to bt_open.
320 // To achieve maximum concurrency one page is locked at a time
321 // as the tree is traversed to find leaf key in question.
323 // An adoption traversal leaves the parent node locked as the
324 // tree is traversed to the level in quesiton.
326 // Page 0 is dedicated to lock for new page extensions,
327 // and chains empty pages together for reuse.
329 // Empty pages are chained together through the ALLOC page and reused.
331 // Access macros to address slot and key values from the page
333 #define slotptr(page, slot) (((BtSlot *)(page+1)) + (slot-1))
334 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
336 void bt_putid(unsigned char *dest, uid id)
341 dest[i] = (unsigned char)id, id >>= 8;
344 uid bt_getid(unsigned char *src)
349 for( i = 0; i < BtId; i++ )
350 id <<= 8, id |= *src++;
355 // wait until write lock mode is clear
356 // and add 1 to the share count
358 void bt_spinreadlock(BtSpinLatch *latch)
364 while( __sync_fetch_and_or((ushort *)latch, Mutex) & Mutex )
367 while( _InterlockedOr16((ushort *)latch, Mutex) & Mutex )
371 // see if exclusive request is granted or pending
373 if( prev = !(latch->exclusive | latch->pending) )
375 __sync_fetch_and_add((ushort *)latch, Share);
377 _InterlockedExchangeAdd16 ((ushort *)latch, Share);
381 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
383 _InterlockedAnd16((ushort *)latch, ~Mutex);
388 } while( sched_yield(), 1 );
390 } while( SwitchToThread(), 1 );
394 // wait for other read and write latches to relinquish
396 void bt_spinwritelock(BtSpinLatch *latch)
400 while( __sync_fetch_and_or((ushort *)latch, Mutex | Pending) & Mutex )
403 while( _InterlockedOr16((ushort *)latch, Mutex | Pending) & Mutex )
406 if( !(latch->share | latch->exclusive) ) {
408 __sync_fetch_and_or((ushort *)latch, Write);
409 __sync_fetch_and_and ((ushort *)latch, ~(Mutex | Pending));
411 _InterlockedOr16((ushort *)latch, Write);
412 _InterlockedAnd16((ushort *)latch, ~(Mutex | Pending));
418 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
421 _InterlockedAnd16((ushort *)latch, ~Mutex);
427 // try to obtain write lock
429 // return 1 if obtained,
432 int bt_spinwritetry(BtSpinLatch *latch)
437 if( prev = __sync_fetch_and_or((ushort *)latch, Mutex), prev & Mutex )
440 if( prev = _InterlockedOr16((ushort *)latch, Mutex), prev & Mutex )
443 // take write access if all bits are clear
447 __sync_fetch_and_or ((ushort *)latch, Write);
449 _InterlockedOr16((ushort *)latch, Write);
453 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
455 _InterlockedAnd16((ushort *)latch, ~Mutex);
462 void bt_spinreleasewrite(BtSpinLatch *latch)
465 __sync_fetch_and_and ((ushort *)latch, ~Write);
467 _InterlockedAnd16((ushort *)latch, ~Write);
471 // decrement reader count
473 void bt_spinreleaseread(BtSpinLatch *latch)
476 __sync_fetch_and_add((ushort *)latch, -Share);
478 _InterlockedExchangeAdd16 ((ushort *)latch, -Share);
482 // link latch table entry into latch hash table
484 void bt_latchlink (BtDb *bt, ushort hashidx, ushort victim, uid page_no)
486 BtLatchSet *set = bt->mgr->latchsets + victim;
488 if( set->next = bt->mgr->latchmgr->table[hashidx].slot )
489 bt->mgr->latchsets[set->next].prev = victim;
491 bt->mgr->latchmgr->table[hashidx].slot = victim;
492 set->page_no = page_no;
499 void bt_unpinlatch (BtLatchSet *set)
502 __sync_fetch_and_add(&set->pin, -1);
504 _InterlockedDecrement16 (&set->pin);
508 // find existing latchset or inspire new one
509 // return with latchset pinned
511 BtLatchSet *bt_pinlatch (BtDb *bt, uid page_no)
513 ushort hashidx = page_no % bt->mgr->latchmgr->latchhash;
514 ushort slot, avail = 0, victim, idx;
517 // obtain read lock on hash table entry
519 bt_spinreadlock(bt->mgr->latchmgr->table[hashidx].latch);
521 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
523 set = bt->mgr->latchsets + slot;
524 if( page_no == set->page_no )
526 } while( slot = set->next );
530 __sync_fetch_and_add(&set->pin, 1);
532 _InterlockedIncrement16 (&set->pin);
536 bt_spinreleaseread (bt->mgr->latchmgr->table[hashidx].latch);
541 // try again, this time with write lock
543 bt_spinwritelock(bt->mgr->latchmgr->table[hashidx].latch);
545 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
547 set = bt->mgr->latchsets + slot;
548 if( page_no == set->page_no )
550 if( !set->pin && !avail )
552 } while( slot = set->next );
554 // found our entry, or take over an unpinned one
556 if( slot || (slot = avail) ) {
557 set = bt->mgr->latchsets + slot;
559 __sync_fetch_and_add(&set->pin, 1);
561 _InterlockedIncrement16 (&set->pin);
563 set->page_no = page_no;
564 bt_spinreleasewrite(bt->mgr->latchmgr->table[hashidx].latch);
568 // see if there are any unused entries
570 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, 1) + 1;
572 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchdeployed);
575 if( victim < bt->mgr->latchmgr->latchtotal ) {
576 set = bt->mgr->latchsets + victim;
578 __sync_fetch_and_add(&set->pin, 1);
580 _InterlockedIncrement16 (&set->pin);
582 bt_latchlink (bt, hashidx, victim, page_no);
583 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
588 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, -1);
590 victim = _InterlockedDecrement16 (&bt->mgr->latchmgr->latchdeployed);
592 // find and reuse previous lock entry
596 victim = __sync_fetch_and_add(&bt->mgr->latchmgr->latchvictim, 1);
598 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchvictim) - 1;
600 // we don't use slot zero
602 if( victim %= bt->mgr->latchmgr->latchtotal )
603 set = bt->mgr->latchsets + victim;
607 // take control of our slot
608 // from other threads
610 if( set->pin || !bt_spinwritetry (set->busy) )
615 // try to get write lock on hash chain
616 // skip entry if not obtained
617 // or has outstanding locks
619 if( !bt_spinwritetry (bt->mgr->latchmgr->table[idx].latch) ) {
620 bt_spinreleasewrite (set->busy);
625 bt_spinreleasewrite (set->busy);
626 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
630 // unlink our available victim from its hash chain
633 bt->mgr->latchsets[set->prev].next = set->next;
635 bt->mgr->latchmgr->table[idx].slot = set->next;
638 bt->mgr->latchsets[set->next].prev = set->prev;
640 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
642 __sync_fetch_and_add(&set->pin, 1);
644 _InterlockedIncrement16 (&set->pin);
646 bt_latchlink (bt, hashidx, victim, page_no);
647 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
648 bt_spinreleasewrite (set->busy);
653 void bt_mgrclose (BtMgr *mgr)
658 // release mapped pages
659 // note that slot zero is never used
661 for( slot = 1; slot < mgr->poolmax; slot++ ) {
662 pool = mgr->pool + slot;
665 munmap (pool->map, (mgr->poolmask+1) << mgr->page_bits);
668 FlushViewOfFile(pool->map, 0);
669 UnmapViewOfFile(pool->map);
670 CloseHandle(pool->hmap);
676 munmap (mgr->latchsets, mgr->latchmgr->nlatchpage * mgr->page_size);
677 munmap (mgr->latchmgr, mgr->page_size);
679 FlushViewOfFile(mgr->latchmgr, 0);
680 UnmapViewOfFile(mgr->latchmgr);
681 CloseHandle(mgr->halloc);
688 free (mgr->pooladvise);
691 FlushFileBuffers(mgr->idx);
692 CloseHandle(mgr->idx);
693 GlobalFree (mgr->pool);
694 GlobalFree (mgr->hash);
695 GlobalFree (mgr->latch);
700 // close and release memory
702 void bt_close (BtDb *bt)
709 VirtualFree (bt->mem, 0, MEM_RELEASE);
714 // open/create new btree buffer manager
716 // call with file_name, BT_openmode, bits in page size (e.g. 16),
717 // size of mapped page pool (e.g. 8192)
719 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
721 uint lvl, attr, cacheblk, last, slot, idx;
722 uint nlatchpage, latchhash;
723 BtLatchMgr *latchmgr;
731 SYSTEM_INFO sysinfo[1];
734 // determine sanity of page size and buffer pool
736 if( bits > BT_maxbits )
738 else if( bits < BT_minbits )
742 return NULL; // must have buffer pool
745 mgr = calloc (1, sizeof(BtMgr));
747 mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
750 return free(mgr), NULL;
752 cacheblk = 4096; // minimum mmap segment size for unix
755 mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
756 attr = FILE_ATTRIBUTE_NORMAL;
757 mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
759 if( mgr->idx == INVALID_HANDLE_VALUE )
760 return GlobalFree(mgr), NULL;
762 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
763 GetSystemInfo(sysinfo);
764 cacheblk = sysinfo->dwAllocationGranularity;
768 latchmgr = malloc (BT_maxpage);
771 // read minimum page size to get root info
773 if( size = lseek (mgr->idx, 0L, 2) ) {
774 if( pread(mgr->idx, latchmgr, BT_minpage, 0) == BT_minpage )
775 bits = latchmgr->alloc->bits;
777 return free(mgr), free(latchmgr), NULL;
778 } else if( mode == BT_ro )
779 return free(latchmgr), bt_mgrclose (mgr), NULL;
781 latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
782 size = GetFileSize(mgr->idx, amt);
785 if( !ReadFile(mgr->idx, (char *)latchmgr, BT_minpage, amt, NULL) )
786 return bt_mgrclose (mgr), NULL;
787 bits = latchmgr->alloc->bits;
788 } else if( mode == BT_ro )
789 return bt_mgrclose (mgr), NULL;
792 mgr->page_size = 1 << bits;
793 mgr->page_bits = bits;
795 mgr->poolmax = poolmax;
798 if( cacheblk < mgr->page_size )
799 cacheblk = mgr->page_size;
801 // mask for partial memmaps
803 mgr->poolmask = (cacheblk >> bits) - 1;
805 // see if requested size of pages per memmap is greater
807 if( (1 << segsize) > mgr->poolmask )
808 mgr->poolmask = (1 << segsize) - 1;
812 while( (1 << mgr->seg_bits) <= mgr->poolmask )
815 mgr->hashsize = hashsize;
818 mgr->pool = calloc (poolmax, sizeof(BtPool));
819 mgr->hash = calloc (hashsize, sizeof(ushort));
820 mgr->latch = calloc (hashsize, sizeof(BtSpinLatch));
821 mgr->pooladvise = calloc (poolmax, (mgr->poolmask + 8) / 8);
823 mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * sizeof(BtPool));
824 mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
825 mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtSpinLatch));
831 // initialize an empty b-tree with latch page, root page, page of leaves
832 // and page(s) of latches
834 memset (latchmgr, 0, 1 << bits);
835 nlatchpage = BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1;
836 bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
837 latchmgr->alloc->bits = mgr->page_bits;
839 latchmgr->nlatchpage = nlatchpage;
840 latchmgr->latchtotal = nlatchpage * (mgr->page_size / sizeof(BtLatchSet));
842 // initialize latch manager
844 latchhash = (mgr->page_size - sizeof(BtLatchMgr)) / sizeof(BtHashEntry);
846 // size of hash table = total number of latchsets
848 if( latchhash > latchmgr->latchtotal )
849 latchhash = latchmgr->latchtotal;
851 latchmgr->latchhash = latchhash;
854 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
855 return bt_mgrclose (mgr), NULL;
857 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
858 return bt_mgrclose (mgr), NULL;
860 if( *amt < mgr->page_size )
861 return bt_mgrclose (mgr), NULL;
864 memset (latchmgr, 0, 1 << bits);
865 latchmgr->alloc->bits = mgr->page_bits;
867 for( lvl=MIN_lvl; lvl--; ) {
868 slotptr(latchmgr->alloc, 1)->off = mgr->page_size - 3;
869 bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
870 key = keyptr(latchmgr->alloc, 1);
871 key->len = 2; // create stopper key
874 latchmgr->alloc->min = mgr->page_size - 3;
875 latchmgr->alloc->lvl = lvl;
876 latchmgr->alloc->cnt = 1;
877 latchmgr->alloc->act = 1;
879 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
880 return bt_mgrclose (mgr), NULL;
882 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
883 return bt_mgrclose (mgr), NULL;
885 if( *amt < mgr->page_size )
886 return bt_mgrclose (mgr), NULL;
890 // clear out latch manager locks
891 // and rest of pages to round out segment
893 memset(latchmgr, 0, mgr->page_size);
896 while( last <= ((MIN_lvl + 1 + nlatchpage) | mgr->poolmask) ) {
898 pwrite(mgr->idx, latchmgr, mgr->page_size, last << mgr->page_bits);
900 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
901 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
902 return bt_mgrclose (mgr), NULL;
903 if( *amt < mgr->page_size )
904 return bt_mgrclose (mgr), NULL;
911 flag = PROT_READ | PROT_WRITE;
912 mgr->latchmgr = mmap (0, mgr->page_size, flag, MAP_SHARED, mgr->idx, ALLOC_page * mgr->page_size);
913 if( mgr->latchmgr == MAP_FAILED )
914 return bt_mgrclose (mgr), NULL;
915 mgr->latchsets = (BtLatchSet *)mmap (0, mgr->latchmgr->nlatchpage * mgr->page_size, flag, MAP_SHARED, mgr->idx, LATCH_page * mgr->page_size);
916 if( mgr->latchsets == MAP_FAILED )
917 return bt_mgrclose (mgr), NULL;
919 flag = PAGE_READWRITE;
920 mgr->halloc = CreateFileMapping(mgr->idx, NULL, flag, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size, NULL);
922 return bt_mgrclose (mgr), NULL;
924 flag = FILE_MAP_WRITE;
925 mgr->latchmgr = MapViewOfFile(mgr->halloc, flag, 0, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size);
927 return GetLastError(), bt_mgrclose (mgr), NULL;
929 mgr->latchsets = (void *)((char *)mgr->latchmgr + LATCH_page * mgr->page_size);
935 VirtualFree (latchmgr, 0, MEM_RELEASE);
940 // open BTree access method
941 // based on buffer manager
943 BtDb *bt_open (BtMgr *mgr)
945 BtDb *bt = malloc (sizeof(*bt));
947 memset (bt, 0, sizeof(*bt));
950 bt->mem = malloc (3 *mgr->page_size);
952 bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
954 bt->frame = (BtPage)bt->mem;
955 bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
956 bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
958 memset(bt->zero, 0, mgr->page_size);
962 // compare two keys, returning > 0, = 0, or < 0
963 // as the comparison value
965 int keycmp (BtKey key1, unsigned char *key2, uint len2)
967 uint len1 = key1->len;
970 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
983 // find segment in pool
984 // must be called with hashslot idx locked
985 // return NULL if not there
986 // otherwise return node
988 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
993 // compute start of hash chain in pool
995 if( slot = bt->mgr->hash[idx] )
996 pool = bt->mgr->pool + slot;
1000 page_no &= ~bt->mgr->poolmask;
1002 while( pool->basepage != page_no )
1003 if( pool = pool->hashnext )
1011 // add segment to hash table
1013 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
1018 pool->hashprev = pool->hashnext = NULL;
1019 pool->basepage = page_no & ~bt->mgr->poolmask;
1022 if( slot = bt->mgr->hash[idx] ) {
1023 node = bt->mgr->pool + slot;
1024 pool->hashnext = node;
1025 node->hashprev = pool;
1028 bt->mgr->hash[idx] = pool->slot;
1031 // find best segment to evict from buffer pool
1033 BtPool *bt_findlru (BtDb *bt, uint hashslot)
1035 unsigned long long int target = ~0LL;
1036 BtPool *pool = NULL, *node;
1041 node = bt->mgr->pool + hashslot;
1043 // scan pool entries under hash table slot
1048 if( node->lru > target )
1052 } while( node = node->hashnext );
1057 // map new buffer pool segment to virtual memory
1059 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
1061 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
1062 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
1066 flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
1067 pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED, bt->mgr->idx, off);
1068 if( pool->map == MAP_FAILED )
1069 return bt->err = BTERR_map;
1070 // clear out madvise issued bits
1071 memset (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8) / 8), 0, (bt->mgr->poolmask + 8)/8);
1073 flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
1074 pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
1076 return bt->err = BTERR_map;
1078 flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
1079 pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1081 return bt->err = BTERR_map;
1086 // calculate page within pool
1088 BtPage bt_page (BtDb *bt, BtPool *pool, uid page_no)
1090 uint subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1093 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1096 uint idx = subpage / 8;
1097 uint bit = subpage % 8;
1099 if( ~((bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] >> bit) & 1 ) {
1100 madvise (page, bt->mgr->page_size, MADV_WILLNEED);
1101 (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] |= 1 << bit;
1110 void bt_unpinpool (BtPool *pool)
1113 __sync_fetch_and_add(&pool->pin, -1);
1115 _InterlockedDecrement16 (&pool->pin);
1119 // find or place requested page in segment-pool
1120 // return pool table entry, incrementing pin
1122 BtPool *bt_pinpool(BtDb *bt, uid page_no)
1124 BtPool *pool, *node, *next;
1125 uint slot, idx, victim;
1128 // lock hash table chain
1130 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1131 bt_spinreadlock (&bt->mgr->latch[idx]);
1133 // look up in hash table
1135 if( pool = bt_findpool(bt, page_no, idx) ) {
1137 __sync_fetch_and_add(&pool->pin, 1);
1139 _InterlockedIncrement16 (&pool->pin);
1141 bt_spinreleaseread (&bt->mgr->latch[idx]);
1146 // upgrade to write lock
1148 bt_spinreleaseread (&bt->mgr->latch[idx]);
1149 bt_spinwritelock (&bt->mgr->latch[idx]);
1151 // try to find page in pool with write lock
1153 if( pool = bt_findpool(bt, page_no, idx) ) {
1155 __sync_fetch_and_add(&pool->pin, 1);
1157 _InterlockedIncrement16 (&pool->pin);
1159 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1164 // allocate a new pool node
1165 // and add to hash table
1168 slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
1170 slot = _InterlockedIncrement16 (&bt->mgr->poolcnt) - 1;
1173 if( ++slot < bt->mgr->poolmax ) {
1174 pool = bt->mgr->pool + slot;
1177 if( bt_mapsegment(bt, pool, page_no) )
1180 bt_linkhash(bt, pool, page_no, idx);
1182 __sync_fetch_and_add(&pool->pin, 1);
1184 _InterlockedIncrement16 (&pool->pin);
1186 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1190 // pool table is full
1191 // find best pool entry to evict
1194 __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
1196 _InterlockedDecrement16 (&bt->mgr->poolcnt);
1201 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
1203 victim = _InterlockedIncrement16 (&bt->mgr->evicted) - 1;
1205 victim %= bt->mgr->hashsize;
1207 // try to get write lock
1208 // skip entry if not obtained
1210 if( !bt_spinwritetry (&bt->mgr->latch[victim]) )
1213 // if cache entry is empty
1214 // or no slots are unpinned
1217 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
1218 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1222 // unlink victim pool node from hash table
1224 if( node = pool->hashprev )
1225 node->hashnext = pool->hashnext;
1226 else if( node = pool->hashnext )
1227 bt->mgr->hash[victim] = node->slot;
1229 bt->mgr->hash[victim] = 0;
1231 if( node = pool->hashnext )
1232 node->hashprev = pool->hashprev;
1234 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1236 // remove old file mapping
1238 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1240 FlushViewOfFile(pool->map, 0);
1241 UnmapViewOfFile(pool->map);
1242 CloseHandle(pool->hmap);
1246 // create new pool mapping
1247 // and link into hash table
1249 if( bt_mapsegment(bt, pool, page_no) )
1252 bt_linkhash(bt, pool, page_no, idx);
1254 __sync_fetch_and_add(&pool->pin, 1);
1256 _InterlockedIncrement16 (&pool->pin);
1258 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1263 // place write, read, or parent lock on requested page_no.
1264 // pin to buffer pool and return latchset pointer
1266 void bt_lockpage(BtLock mode, BtLatchSet *set)
1270 bt_spinreadlock (set->readwr);
1273 bt_spinwritelock (set->readwr);
1276 bt_spinreadlock (set->access);
1279 bt_spinwritelock (set->access);
1282 bt_spinwritelock (set->parent);
1287 // remove write, read, or parent lock on requested page_no.
1289 void bt_unlockpage(BtLock mode, BtLatchSet *set)
1293 bt_spinreleaseread (set->readwr);
1296 bt_spinreleasewrite (set->readwr);
1299 bt_spinreleaseread (set->access);
1302 bt_spinreleasewrite (set->access);
1305 bt_spinreleasewrite (set->parent);
1310 // allocate a new page and write page into it
1312 uid bt_newpage(BtDb *bt, BtPage page)
1320 // lock allocation page
1322 bt_spinwritelock(bt->mgr->latchmgr->lock);
1324 // use empty chain first
1325 // else allocate empty page
1327 if( new_page = bt_getid(bt->mgr->latchmgr->alloc[1].right) ) {
1328 if( pool = bt_pinpool (bt, new_page) )
1329 pmap = bt_page (bt, pool, new_page);
1332 bt_putid(bt->mgr->latchmgr->alloc[1].right, bt_getid(pmap->right));
1333 bt_unpinpool (pool);
1336 new_page = bt_getid(bt->mgr->latchmgr->alloc->right);
1337 bt_putid(bt->mgr->latchmgr->alloc->right, new_page+1);
1341 // if writing first page of pool block, zero last page in the block
1343 if ( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1345 // use zero buffer to write zeros
1346 if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1347 return bt->err = BTERR_wrt, 0;
1350 // unlock allocation latch
1352 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1354 if ( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1355 return bt->err = BTERR_wrt, 0;
1358 // unlock allocation latch
1360 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1362 // bring new page into pool and copy page.
1363 // this will extend the file into the new pages.
1364 // NB -- no latch required
1366 if( pool = bt_pinpool (bt, new_page) )
1367 pmap = bt_page (bt, pool, new_page);
1371 memcpy(pmap, page, bt->mgr->page_size);
1372 bt_unpinpool (pool);
1377 // find slot in page for given key at a given level
1379 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1381 uint diff, higher = bt->page->cnt, low = 1, slot;
1383 // low is the lowest candidate, higher is already
1384 // tested as .ge. the given key, loop ends when they meet
1386 while( diff = higher - low ) {
1387 slot = low + ( diff >> 1 );
1388 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1397 // find and load page at given level for given key
1398 // leave page rd or wr locked as requested
1400 int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, BtLock lock)
1402 uid page_no = ROOT_page, prevpage = 0;
1403 BtLatchSet *set, *prevset;
1404 uint drill = 0xff, slot;
1405 uint mode, prevmode;
1409 // start at root of btree and drill down
1412 // determine lock mode of drill level
1413 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1415 // obtain latch set for this page
1417 bt->set = bt_pinlatch (bt, page_no);
1418 bt->page_no = page_no;
1420 // pin page contents
1422 if( bt->pool = bt_pinpool (bt, page_no) )
1423 bt->page = bt_page (bt, bt->pool, page_no);
1427 // obtain access lock using lock chaining with Access mode
1429 if( page_no > ROOT_page )
1430 bt_lockpage(BtLockAccess, bt->set);
1432 // now unlock and unpin our (possibly foster) parent
1435 bt_unlockpage(prevmode, prevset);
1436 bt_unpinlatch (prevset);
1437 bt_unpinpool (prevpool);
1441 // obtain read lock using lock chaining
1443 bt_lockpage(mode, bt->set);
1445 if( page_no > ROOT_page )
1446 bt_unlockpage(BtLockAccess, bt->set);
1448 // re-read and re-lock root after determining actual level of root
1450 if( page_no == ROOT_page )
1451 if( bt->page->lvl != drill) {
1452 drill = bt->page->lvl;
1454 if( lock == BtLockWrite && drill == lvl ) {
1455 bt_unlockpage(mode, bt->set);
1456 bt_unpinlatch (bt->set);
1457 bt_unpinpool (bt->pool);
1462 prevpage = bt->page_no;
1463 prevpool = bt->pool;
1467 // were we supposed to find a foster child?
1468 // if so, slide right onto it
1470 if( keycmp (keyptr(bt->page,bt->page->cnt), key, len) < 0 ) {
1471 page_no = bt_getid(bt->page->right);
1476 // find key on page at this level
1477 // and either descend to requested level
1478 // or return key slot
1480 slot = bt_findslot (bt, key, len);
1482 // is this slot < foster child area
1483 // on the requested level?
1485 // if so, return actual slot even if dead
1487 if( slot <= bt->page->cnt - bt->page->foster )
1489 return bt->foster = foster, slot;
1491 // find next active slot
1493 // note: foster children are never dead
1495 while( slotptr(bt->page, slot)->dead )
1496 if( slot++ < bt->page->cnt )
1499 // we are waiting for fence key posting
1500 page_no = bt_getid(bt->page->right);
1504 // is this slot < foster child area
1505 // if so, drill to next level
1507 if( slot <= bt->page->cnt - bt->page->foster )
1508 foster = 0, drill--;
1512 // continue right onto foster child
1513 // or down to next level.
1515 page_no = bt_getid(slotptr(bt->page, slot)->id);
1519 // return error on end of chain
1521 bt->err = BTERR_struct;
1522 return 0; // return error
1525 // remove empty page from the B-tree
1526 // by pulling our right node left over ourselves
1528 // call with bt->page, etc, set to page's locked parent
1529 // returns with page locked.
1531 BTERR bt_mergeright (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no, uint lvl, uint slot)
1533 BtLatchSet *rset, *pset, *rpset;
1534 BtPool *rpool, *ppool, *rppool;
1535 BtPage rpage, ppage, rppage;
1536 uid right, parent, rparent;
1540 // cache node's parent page
1542 parent = bt->page_no;
1547 // lock and map our right page
1548 // note that it cannot be our foster child
1549 // since the our node is empty
1550 // and it cannot be NULL because of the stopper
1551 // in the last right page
1553 bt_lockpage (BtLockWrite, set);
1555 // if we aren't dead yet
1560 if( right = bt_getid (page->right) )
1561 if( rpool = bt_pinpool (bt, right) )
1562 rpage = bt_page (bt, rpool, right);
1566 return bt->err = BTERR_struct;
1568 rset = bt_pinlatch (bt, right);
1570 // find our right neighbor
1572 if( ppage->act > 1 ) {
1573 for( idx = slot; idx++ < ppage->cnt; )
1574 if( !slotptr(ppage, idx)->dead )
1577 if( idx > ppage->cnt )
1578 return bt->err = BTERR_struct;
1580 // redirect right neighbor in parent to left node
1582 bt_putid(slotptr(ppage,idx)->id, page_no);
1585 // if parent has only our deleted page, e.g. no right neighbor
1586 // prepare to merge parent itself
1588 if( ppage->act == 1 ) {
1589 if( rparent = bt_getid (ppage->right) )
1590 if( rppool = bt_pinpool (bt, rparent) )
1591 rppage = bt_page (bt, rppool, rparent);
1595 return bt->err = BTERR_struct;
1597 rpset = bt_pinlatch (bt, rparent);
1598 bt_lockpage (BtLockWrite, rpset);
1600 // find our right neighbor on right parent page
1602 for( idx = 0; idx++ < rppage->cnt; )
1603 if( !slotptr(rppage, idx)->dead ) {
1604 bt_putid (slotptr(rppage, idx)->id, page_no);
1608 if( idx > rppage->cnt )
1609 return bt->err = BTERR_struct;
1612 // now that there are no more pointers to our right node
1613 // we can wait for delete lock on it
1615 bt_lockpage(BtLockDelete, rset);
1616 bt_lockpage(BtLockWrite, rset);
1618 // pull contents of right page into our empty page
1620 memcpy (page, rpage, bt->mgr->page_size);
1622 // ready to release right parent lock
1623 // now that we have a new page in place
1625 if( ppage->act == 1 ) {
1626 bt_unlockpage (BtLockWrite, rpset);
1627 bt_unpinlatch (rpset);
1628 bt_unpinpool (rppool);
1631 // add killed right block to free chain
1634 bt_spinwritelock(bt->mgr->latchmgr->lock);
1636 // store free chain in allocation page second right
1638 bt_putid(rpage->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1639 bt_putid(bt->mgr->latchmgr->alloc[1].right, right);
1641 // unlock latch mgr and right page
1643 bt_unlockpage(BtLockDelete, rset);
1644 bt_unlockpage(BtLockWrite, rset);
1645 bt_unpinlatch (rset);
1646 bt_unpinpool (rpool);
1648 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1650 // delete our obsolete fence key from our parent
1652 slotptr(ppage, slot)->dead = 1;
1655 // if our parent now empty
1656 // remove it from the tree
1658 if( ppage->act-- == 1 )
1659 if( bt_mergeleft (bt, ppage, ppool, pset, parent, lvl+1) )
1663 bt_unlockpage (BtLockWrite, pset);
1664 bt_unpinlatch (pset);
1665 bt_unpinpool (ppool);
1671 // remove empty page from the B-tree
1672 // try merging left first. If no left
1673 // sibling, then merge right.
1675 // call with page loaded and locked,
1676 // return with page locked.
1678 BTERR bt_mergeleft (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no, uint lvl)
1680 unsigned char fencekey[256], postkey[256];
1681 uint slot, idx, postfence = 0;
1682 BtLatchSet *lset, *pset;
1683 BtPool *lpool, *ppool;
1684 BtPage lpage, ppage;
1688 ptr = keyptr(page, page->cnt);
1689 memcpy(fencekey, ptr, ptr->len + 1);
1690 bt_unlockpage (BtLockWrite, set);
1692 // load and lock our parent
1695 if( !(slot = bt_loadpage (bt, fencekey+1, *fencekey, lvl+1, BtLockWrite)) )
1698 parent = bt->page_no;
1703 // wait until we are not a foster child
1706 bt_unlockpage (BtLockWrite, pset);
1707 bt_unpinlatch (pset);
1708 bt_unpinpool (ppool);
1717 // find our left neighbor in our parent page
1719 for( idx = slot; --idx; )
1720 if( !slotptr(ppage, idx)->dead )
1723 // if no left neighbor, do right merge
1726 return bt_mergeright (bt, page, pool, set, page_no, lvl, slot);
1728 // lock and map our left neighbor's page
1730 left = bt_getid (slotptr(ppage, idx)->id);
1732 if( lpool = bt_pinpool (bt, left) )
1733 lpage = bt_page (bt, lpool, left);
1737 lset = bt_pinlatch (bt, left);
1738 bt_lockpage(BtLockWrite, lset);
1740 // wait until foster sibling is in our parent
1742 if( bt_getid (lpage->right) != page_no ) {
1743 bt_unlockpage (BtLockWrite, pset);
1744 bt_unpinlatch (pset);
1745 bt_unpinpool (ppool);
1746 bt_unlockpage (BtLockWrite, lset);
1747 bt_unpinlatch (lset);
1748 bt_unpinpool (lpool);
1757 // since our page will have no more pointers to it,
1758 // obtain Delete lock and wait for write locks to clear
1760 bt_lockpage(BtLockDelete, set);
1761 bt_lockpage(BtLockWrite, set);
1763 // if we aren't dead yet,
1764 // get ready for exit
1767 bt_unlockpage(BtLockDelete, set);
1768 bt_unlockpage(BtLockWrite, lset);
1769 bt_unpinlatch (lset);
1770 bt_unpinpool (lpool);
1774 // are we are the fence key for our parent?
1775 // if so, grab our old fence key
1777 if( postfence = slot == ppage->cnt ) {
1778 ptr = keyptr (ppage, ppage->cnt);
1779 memcpy(fencekey, ptr, ptr->len + 1);
1780 memset(slotptr(ppage, ppage->cnt), 0, sizeof(BtSlot));
1782 // clear out other dead slots
1784 while( --ppage->cnt )
1785 if( slotptr(ppage, ppage->cnt)->dead )
1786 memset(slotptr(ppage, ppage->cnt), 0, sizeof(BtSlot));
1790 ptr = keyptr (ppage, ppage->cnt);
1791 memcpy(postkey, ptr, ptr->len + 1);
1793 slotptr(ppage,slot)->dead = 1;
1798 // push our right neighbor pointer to our left
1800 memcpy (lpage->right, page->right, BtId);
1802 // add ourselves to free chain
1805 bt_spinwritelock(bt->mgr->latchmgr->lock);
1807 // store free chain in allocation page second right
1808 bt_putid(page->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1809 bt_putid(bt->mgr->latchmgr->alloc[1].right, page_no);
1811 // unlock latch mgr and pages
1813 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1814 bt_unlockpage(BtLockWrite, lset);
1815 bt_unpinlatch (lset);
1816 bt_unpinpool (lpool);
1818 // release our node's delete lock
1820 bt_unlockpage(BtLockDelete, set);
1823 bt_unlockpage (BtLockWrite, pset);
1824 bt_unpinpool (ppool);
1826 // do we need to post parent's fence key in its parent?
1828 if( !postfence || parent == ROOT_page ) {
1829 bt_unpinlatch (pset);
1834 // interlock parent fence post
1836 bt_lockpage (BtLockParent, pset);
1838 // load parent's parent page
1840 if( !(slot = bt_loadpage (bt, fencekey+1, *fencekey, lvl+2, BtLockWrite)) )
1843 if( !(slot = bt_cleanpage (bt, bt->page, *fencekey, slot)) )
1844 if( bt_splitpage (bt, bt->page, bt->pool, bt->set, bt->page_no) )
1851 page->min -= *postkey + 1;
1852 ((unsigned char *)page)[page->min] = *postkey;
1853 memcpy ((unsigned char *)page + page->min +1, postkey + 1, *postkey );
1854 slotptr(page, slot)->off = page->min;
1856 bt_unlockpage (BtLockParent, pset);
1857 bt_unpinlatch (pset);
1859 bt_unlockpage (BtLockWrite, bt->set);
1860 bt_unpinlatch (bt->set);
1861 bt_unpinpool (bt->pool);
1867 // find and delete key on page by marking delete flag bit
1868 // if page becomes empty, delete it from the btree
1870 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len)
1879 if( !(slot = bt_loadpage (bt, key, len, 0, BtLockWrite)) )
1882 page_no = bt->page_no;
1887 // if key is found delete it, otherwise ignore request
1889 ptr = keyptr(page, slot);
1891 if( bt->found = !keycmp (ptr, key, len) )
1892 if( bt->found = slotptr(page, slot)->dead == 0 ) {
1893 slotptr(page,slot)->dead = 1;
1894 if( slot < page->cnt )
1897 if( bt_mergeleft (bt, page, pool, set, page_no, 0) )
1901 bt_unlockpage(BtLockWrite, set);
1902 bt_unpinlatch (set);
1903 bt_unpinpool (pool);
1907 // find key in leaf level and return row-id
1909 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1915 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1916 ptr = keyptr(bt->page, slot);
1920 // if key exists, return row-id
1921 // otherwise return 0
1923 if( slot <= bt->page->cnt && !keycmp (ptr, key, len) )
1924 id = bt_getid(slotptr(bt->page,slot)->id);
1928 bt_unlockpage (BtLockRead, bt->set);
1929 bt_unpinlatch (bt->set);
1930 bt_unpinpool (bt->pool);
1934 // check page for space available,
1935 // clean if necessary and return
1936 // 0 - page needs splitting
1937 // >0 new slot value
1939 uint bt_cleanpage(BtDb *bt, BtPage page, uint amt, uint slot)
1941 uint nxt = bt->mgr->page_size;
1942 uint cnt = 0, idx = 0;
1943 uint max = page->cnt;
1947 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1950 // skip cleanup if nothing to reclaim
1955 memcpy (bt->frame, page, bt->mgr->page_size);
1957 // skip page info and set rest of page to zero
1959 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1963 // try cleaning up page first
1965 // always leave fence key in the array
1966 // otherwise, remove deleted key
1968 // note: foster children are never dead
1970 while( cnt++ < max ) {
1973 if( cnt < max && slotptr(bt->frame,cnt)->dead )
1978 key = keyptr(bt->frame, cnt);
1979 nxt -= key->len + 1;
1980 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1983 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1984 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1986 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1987 slotptr(page, idx)->off = nxt;
1993 // see if page has enough space now, or does it need splitting?
1995 if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
2001 // add key to current page
2002 // page must already be writelocked
2004 void bt_addkeytopage (BtDb *bt, BtPage page, uint slot, unsigned char *key, uint len, uid id, uint tod)
2008 // find next available dead slot and copy key onto page
2009 // note that foster children on the page are never dead
2011 // look for next hole, but stay back from the fence key
2013 for( idx = slot; idx < page->cnt; idx++ )
2014 if( slotptr(page, idx)->dead )
2017 if( idx == page->cnt )
2022 // now insert key into array before slot
2025 *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
2027 page->min -= len + 1;
2028 ((unsigned char *)page)[page->min] = len;
2029 memcpy ((unsigned char *)page + page->min +1, key, len );
2031 bt_putid(slotptr(page,slot)->id, id);
2032 slotptr(page, slot)->off = page->min;
2033 slotptr(page, slot)->tod = tod;
2034 slotptr(page, slot)->dead = 0;
2037 // split the root and raise the height of the btree
2038 // call with current page locked and page no of foster child
2039 // return with current page (root) unlocked
2041 BTERR bt_splitroot(BtDb *bt, uid right)
2043 uint nxt = bt->mgr->page_size;
2044 unsigned char fencekey[256];
2045 BtPage root = bt->page;
2049 // Obtain an empty page to use, and copy the left page
2050 // contents into it from the root. Strip foster child key.
2051 // (it's the stopper key)
2053 memset (slotptr(root, root->cnt), 0, sizeof(BtSlot));
2059 // Save left fence key.
2061 key = keyptr(root, root->cnt);
2062 memcpy (fencekey, key, key->len + 1);
2064 // copy the lower keys into a new left page
2066 if( !(new_page = bt_newpage(bt, root)) )
2069 // preserve the page info at the bottom
2070 // and set rest of the root to zero
2072 memset (root+1, 0, bt->mgr->page_size - sizeof(*root));
2074 // insert left fence key on empty newroot page
2076 nxt -= *fencekey + 1;
2077 memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
2078 bt_putid(slotptr(root, 1)->id, new_page);
2079 slotptr(root, 1)->off = nxt;
2081 // insert stopper key on newroot page
2082 // and increase the root height
2088 memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
2089 bt_putid(slotptr(root, 2)->id, right);
2090 slotptr(root, 2)->off = nxt;
2092 bt_putid(root->right, 0);
2093 root->min = nxt; // reset lowest used offset and key count
2098 // release and unpin root (bt->page)
2100 bt_unlockpage(BtLockWrite, bt->set);
2101 bt_unpinlatch (bt->set);
2102 bt_unpinpool (bt->pool);
2106 // split already locked full node
2107 // return unlocked and unpinned.
2109 BTERR bt_splitpage (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no)
2111 uint slot, cnt, idx, max, nxt = bt->mgr->page_size;
2112 unsigned char fencekey[256];
2113 uint tod = time(NULL);
2114 uint lvl = page->lvl;
2118 // initialize frame buffer for right node
2120 memset (bt->frame, 0, bt->mgr->page_size);
2121 max = page->cnt - page->foster;
2125 // split higher half of keys to bt->frame
2126 // leaving old foster children in the left node,
2127 // and adding a new foster child there.
2129 while( cnt++ < max ) {
2130 key = keyptr(page, cnt);
2131 nxt -= key->len + 1;
2132 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
2133 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
2134 if( !(slotptr(bt->frame, idx)->dead = slotptr(page, cnt)->dead) )
2136 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
2137 slotptr(bt->frame, idx)->off = nxt;
2140 // transfer right link node to new right node
2142 if( page_no > ROOT_page )
2143 memcpy (bt->frame->right, page->right, BtId);
2145 bt->frame->bits = bt->mgr->page_bits;
2146 bt->frame->min = nxt;
2147 bt->frame->cnt = idx;
2148 bt->frame->lvl = lvl;
2150 // get new free page and write right frame to it.
2152 if( !(new_page = bt_newpage(bt, bt->frame)) )
2155 // remember fence key for new right page to add
2156 // as foster child to the left node
2158 key = keyptr(bt->frame, idx);
2159 memcpy (fencekey, key, key->len + 1);
2161 // update lower keys and foster children to continue in old page
2163 memcpy (bt->frame, page, bt->mgr->page_size);
2164 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
2165 nxt = bt->mgr->page_size;
2171 // assemble page of smaller keys
2172 // to remain in the old page
2174 while( cnt++ < max / 2 ) {
2175 key = keyptr(bt->frame, cnt);
2176 nxt -= key->len + 1;
2177 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2178 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
2179 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
2181 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2182 slotptr(page, idx)->off = nxt;
2185 // insert new foster child for right page in queue
2186 // before any of the current foster children
2188 nxt -= *fencekey + 1;
2189 memcpy ((unsigned char *)page + nxt, fencekey, *fencekey + 1);
2191 bt_putid (slotptr(page,++idx)->id, new_page);
2192 slotptr(page, idx)->tod = tod;
2193 slotptr(page, idx)->off = nxt;
2197 // continue with old foster child keys
2198 // note that none will be dead
2200 cnt = bt->frame->cnt - bt->frame->foster;
2202 while( cnt++ < bt->frame->cnt ) {
2203 key = keyptr(bt->frame, cnt);
2204 nxt -= key->len + 1;
2205 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2206 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
2207 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2208 slotptr(page, idx)->off = nxt;
2215 // link new right page
2217 bt_putid (page->right, new_page);
2219 // if current page is the root page, split it
2221 if( page_no == ROOT_page )
2222 return bt_splitroot (bt, new_page);
2224 // release wr lock on our page
2226 bt_unlockpage (BtLockWrite, set);
2228 // obtain ParentModification lock for current page
2229 // to fix new fence key and oldest foster child on page
2231 bt_lockpage (BtLockParent, set);
2233 // get our new fence key to insert in parent node
2235 bt_lockpage (BtLockRead, set);
2237 key = keyptr(page, page->cnt-1);
2238 memcpy (fencekey, key, key->len+1);
2240 bt_unlockpage (BtLockRead, set);
2242 if( bt_insertkey (bt, fencekey + 1, *fencekey, page_no, tod, lvl + 1) )
2245 // lock our page for writing
2247 bt_lockpage (BtLockRead, set);
2249 // switch old parent key from us to our oldest foster child
2251 key = keyptr(page, page->cnt);
2252 memcpy (fencekey, key, key->len+1);
2254 new_page = bt_getid (slotptr(page, page->cnt)->id);
2255 bt_unlockpage (BtLockRead, set);
2257 if( bt_insertkey (bt, fencekey + 1, *fencekey, new_page, tod, lvl + 1) )
2260 // now that it has its own parent pointer,
2261 // remove oldest foster child from our page
2263 bt_lockpage (BtLockWrite, set);
2264 memset (slotptr(page, page->cnt), 0, sizeof(BtSlot));
2270 bt_unlockpage (BtLockParent, set);
2272 // if this emptied page,
2273 // undo the foster child
2276 if( bt_mergeleft (bt, page, pool, set, page_no, lvl) )
2281 bt_unlockpage (BtLockWrite, set);
2282 bt_unpinlatch (set);
2283 bt_unpinpool (pool);
2287 // Insert new key into the btree at leaf level.
2289 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod, uint lvl)
2296 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
2297 ptr = keyptr(bt->page, slot);
2301 bt->err = BTERR_ovflw;
2305 // if key already exists, update id and return
2309 if( !keycmp (ptr, key, len) ) {
2310 if( slotptr(page, slot)->dead )
2312 slotptr(page, slot)->dead = 0;
2313 slotptr(page, slot)->tod = tod;
2314 bt_putid(slotptr(page,slot)->id, id);
2315 bt_unlockpage(BtLockWrite, bt->set);
2316 bt_unpinlatch (bt->set);
2317 bt_unpinpool (bt->pool);
2321 // check if page has enough space
2323 if( slot = bt_cleanpage (bt, bt->page, len, slot) )
2326 if( bt_splitpage (bt, bt->page, bt->pool, bt->set, bt->page_no) )
2330 bt_addkeytopage (bt, bt->page, slot, key, len, id, tod);
2332 bt_unlockpage (BtLockWrite, bt->set);
2333 bt_unpinlatch (bt->set);
2334 bt_unpinpool (bt->pool);
2338 // cache page of keys into cursor and return starting slot for given key
2340 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2344 // cache page for retrieval
2345 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
2346 memcpy (bt->cursor, bt->page, bt->mgr->page_size);
2348 bt->cursor_page = bt->page_no;
2350 bt_unlockpage(BtLockRead, bt->set);
2351 bt_unpinlatch (bt->set);
2352 bt_unpinpool (bt->pool);
2356 // return next slot for cursor page
2357 // or slide cursor right into next page
2359 uint bt_nextkey (BtDb *bt, uint slot)
2367 right = bt_getid(bt->cursor->right);
2368 while( slot++ < bt->cursor->cnt - bt->cursor->foster )
2369 if( slotptr(bt->cursor,slot)->dead )
2371 else if( right || (slot < bt->cursor->cnt - bt->cursor->foster) )
2379 bt->cursor_page = right;
2380 if( pool = bt_pinpool (bt, right) )
2381 page = bt_page (bt, pool, right);
2385 set = bt_pinlatch (bt, right);
2386 bt_lockpage(BtLockRead, set);
2388 memcpy (bt->cursor, page, bt->mgr->page_size);
2390 bt_unlockpage(BtLockRead, set);
2391 bt_unpinlatch (set);
2392 bt_unpinpool (pool);
2399 BtKey bt_key(BtDb *bt, uint slot)
2401 return keyptr(bt->cursor, slot);
2404 uid bt_uid(BtDb *bt, uint slot)
2406 return bt_getid(slotptr(bt->cursor,slot)->id);
2409 uint bt_tod(BtDb *bt, uint slot)
2411 return slotptr(bt->cursor,slot)->tod;
2424 // standalone program to index file of keys
2425 // then list them onto std-out
2428 void *index_file (void *arg)
2430 uint __stdcall index_file (void *arg)
2433 int line = 0, found = 0, cnt = 0;
2434 uid next, page_no = LEAF_page; // start on first page of leaves
2435 unsigned char key[256];
2436 ThreadArg *args = arg;
2437 int ch, len = 0, slot;
2446 bt = bt_open (args->mgr);
2449 switch(args->type | 0x20)
2452 fprintf(stderr, "started indexing for %s\n", args->infile);
2453 if( in = fopen (args->infile, "rb") )
2454 while( ch = getc(in), ch != EOF )
2459 if( args->num == 1 )
2460 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2462 else if( args->num )
2463 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2465 if( bt_insertkey (bt, key, len, line, *tod, 0) )
2466 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2469 else if( len < 255 )
2471 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
2475 fprintf(stderr, "started deleting keys for %s\n", args->infile);
2476 if( in = fopen (args->infile, "rb") )
2477 while( ch = getc(in), ch != EOF )
2481 if( args->num == 1 )
2482 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2484 else if( args->num )
2485 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2487 if( bt_deletekey (bt, key, len) )
2488 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2491 else if( len < 255 )
2493 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2497 fprintf(stderr, "started finding keys for %s\n", args->infile);
2498 if( in = fopen (args->infile, "rb") )
2499 while( ch = getc(in), ch != EOF )
2503 if( args->num == 1 )
2504 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2506 else if( args->num )
2507 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2509 if( bt_findkey (bt, key, len) )
2512 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2515 else if( len < 255 )
2517 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2523 fprintf(stderr, "started reading\n");
2525 if( slot = bt_startkey (bt, key, len) )
2528 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
2530 while( slot = bt_nextkey (bt, slot) ) {
2531 ptr = bt_key(bt, slot);
2532 fwrite (ptr->key, ptr->len, 1, stdout);
2533 fputc ('\n', stdout);
2539 fprintf(stderr, "started reading\n");
2542 if( pool = bt_pinpool (bt, page_no) )
2543 page = bt_page (bt, pool, page_no);
2546 set = bt_pinlatch (bt, page_no);
2547 bt_lockpage (BtLockRead, set);
2549 next = bt_getid (page->right);
2550 bt_unlockpage (BtLockRead, set);
2551 bt_unpinlatch (set);
2552 bt_unpinpool (pool);
2553 } while( page_no = next );
2555 cnt--; // remove stopper key
2556 fprintf(stderr, " Total keys read %d\n", cnt);
2568 typedef struct timeval timer;
2570 int main (int argc, char **argv)
2572 int idx, cnt, len, slot, err;
2573 int segsize, bits = 16;
2578 time_t start[1], stop[1];
2591 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]);
2592 fprintf (stderr, " where page_bits is the page size in bits\n");
2593 fprintf (stderr, " mapped_segments is the number of mmap segments in buffer pool\n");
2594 fprintf (stderr, " seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2595 fprintf (stderr, " line_numbers = 1 to append line numbers to keys\n");
2596 fprintf (stderr, " src_file1 thru src_filen are files of keys separated by newline\n");
2601 gettimeofday(&start, NULL);
2607 bits = atoi(argv[3]);
2610 poolsize = atoi(argv[4]);
2613 fprintf (stderr, "Warning: no mapped_pool\n");
2615 if( poolsize > 65535 )
2616 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2619 segsize = atoi(argv[5]);
2621 segsize = 4; // 16 pages per mmap segment
2624 num = atoi(argv[6]);
2628 threads = malloc (cnt * sizeof(pthread_t));
2630 threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2632 args = malloc (cnt * sizeof(ThreadArg));
2634 mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2637 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2643 for( idx = 0; idx < cnt; idx++ ) {
2644 args[idx].infile = argv[idx + 7];
2645 args[idx].type = argv[2][0];
2646 args[idx].mgr = mgr;
2647 args[idx].num = num;
2648 args[idx].idx = idx;
2650 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2651 fprintf(stderr, "Error creating thread %d\n", err);
2653 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2657 // wait for termination
2660 for( idx = 0; idx < cnt; idx++ )
2661 pthread_join (threads[idx], NULL);
2662 gettimeofday(&stop, NULL);
2663 real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2665 WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2667 for( idx = 0; idx < cnt; idx++ )
2668 CloseHandle(threads[idx]);
2671 real_time = 1000 * (*stop - *start);
2673 fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);