1 // btree version threads2i sched_yield version
2 // with reworked bt_deletekey code
5 // author: karl malbrain, malbrain@cal.berkeley.edu
8 This work, including the source code, documentation
9 and related data, is placed into the public domain.
11 The orginal author is Karl Malbrain.
13 THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY
14 OF ANY KIND, NOT EVEN THE IMPLIED WARRANTY OF
15 MERCHANTABILITY. THE AUTHOR OF THIS SOFTWARE,
16 ASSUMES _NO_ RESPONSIBILITY FOR ANY CONSEQUENCE
17 RESULTING FROM THE USE, MODIFICATION, OR
18 REDISTRIBUTION OF THIS SOFTWARE.
21 // Please see the project home page for documentation
22 // code.google.com/p/high-concurrency-btree
24 #define _FILE_OFFSET_BITS 64
25 #define _LARGEFILE64_SOURCE
41 #define WIN32_LEAN_AND_MEAN
55 typedef unsigned long long uid;
58 typedef unsigned long long off64_t;
59 typedef unsigned short ushort;
60 typedef unsigned int uint;
63 #define BT_latchtable 128 // number of latch manager slots
65 #define BT_ro 0x6f72 // ro
66 #define BT_rw 0x7772 // rw
68 #define BT_maxbits 24 // maximum page size in bits
69 #define BT_minbits 9 // minimum page size in bits
70 #define BT_minpage (1 << BT_minbits) // minimum page size
71 #define BT_maxpage (1 << BT_maxbits) // maximum page size
74 There are five lock types for each node in three independent sets:
75 1. (set 1) AccessIntent: Sharable. Going to Read the node. Incompatible with NodeDelete.
76 2. (set 1) NodeDelete: Exclusive. About to release the node. Incompatible with AccessIntent.
77 3. (set 2) ReadLock: Sharable. Read the node. Incompatible with WriteLock.
78 4. (set 2) WriteLock: Exclusive. Modify the node. Incompatible with ReadLock and other WriteLocks.
79 5. (set 3) ParentModification: Exclusive. Change the node's parent keys. Incompatible with another ParentModification.
90 // definition for latch implementation
92 // exclusive is set for write access
93 // share is count of read accessors
94 // grant write lock when share == 0
97 volatile unsigned char mutex;
98 volatile unsigned char exclusive:1;
99 volatile unsigned char pending:1;
100 volatile ushort share;
103 // hash table entries
106 BtSpinLatch latch[1];
107 volatile ushort slot; // Latch table entry at head of chain
110 // latch manager table structure
113 BtSpinLatch readwr[1]; // read/write page lock
114 BtSpinLatch access[1]; // Access Intent/Page delete
115 BtSpinLatch parent[1]; // Posting of fence key in parent
116 BtSpinLatch busy[1]; // slot is being moved between chains
117 volatile ushort next; // next entry in hash table chain
118 volatile ushort prev; // prev entry in hash table chain
119 volatile ushort pin; // number of outstanding locks
120 volatile ushort hash; // hash slot entry is under
121 volatile uid page_no; // latch set page number
124 // Define the length of the page and key pointers
128 // Page key slot definition.
130 // If BT_maxbits is 15 or less, you can save 4 bytes
131 // for each key stored by making the first two uints
132 // into ushorts. You can also save 4 bytes by removing
133 // the tod field from the key.
135 // Keys are marked dead, but remain on the page until
136 // it cleanup is called. The fence key (highest key) for
137 // the page is always present, even after cleanup.
140 uint off:BT_maxbits; // page offset for key start
141 uint dead:1; // set for deleted key
142 uint tod; // time-stamp for key
143 unsigned char id[BtId]; // id associated with key
146 // The key structure occupies space at the upper end of
147 // each page. It's a length byte followed by the key
152 unsigned char key[1];
155 // The first part of an index page.
156 // It is immediately followed
157 // by the BtSlot array of keys.
159 typedef struct BtPage_ {
160 uint cnt; // count of keys in page
161 uint act; // count of active keys
162 uint min; // next key offset
163 unsigned char bits:7; // page size in bits
164 unsigned char free:1; // page is on free chain
165 unsigned char lvl:5; // level of page
166 unsigned char kill:1; // page is being deleted
167 unsigned char dirty:1; // page has deleted keys
168 unsigned char posted:1; // page fence is posted
169 unsigned char right[BtId]; // page number to right
172 // The memory mapping pool table buffer manager entry
175 unsigned long long int lru; // number of times accessed
176 uid basepage; // mapped base page number
177 char *map; // mapped memory pointer
178 ushort slot; // slot index in this array
179 ushort pin; // mapped page pin counter
180 void *hashprev; // previous pool entry for the same hash idx
181 void *hashnext; // next pool entry for the same hash idx
183 HANDLE hmap; // Windows memory mapping handle
187 // The loadpage interface object
190 uid page_no; // current page number
191 BtPage page; // current page pointer
192 BtPool *pool; // current page pool
193 BtLatchSet *latch; // current page latch set
196 // structure for latch manager on ALLOC_page
199 struct BtPage_ alloc[2]; // next & free page_nos in right ptr
200 BtSpinLatch lock[1]; // allocation area lite latch
201 ushort latchdeployed; // highest number of latch entries deployed
202 ushort nlatchpage; // number of latch pages at BT_latch
203 ushort latchtotal; // number of page latch entries
204 ushort latchhash; // number of latch hash table slots
205 ushort latchvictim; // next latch entry to examine
206 BtHashEntry table[0]; // the hash table
209 // The object structure for Btree access
212 uint page_size; // page size
213 uint page_bits; // page size in bits
214 uint seg_bits; // seg size in pages in bits
215 uint mode; // read-write mode
221 ushort poolcnt; // highest page pool node in use
222 ushort poolmax; // highest page pool node allocated
223 ushort poolmask; // total number of pages in mmap segment - 1
224 ushort hashsize; // size of Hash Table for pool entries
225 volatile uint evicted; // last evicted hash table slot
226 ushort *hash; // pool index for hash entries
227 BtSpinLatch *latch; // latches for hash table slots
228 BtLatchMgr *latchmgr; // mapped latch page from allocation page
229 BtLatchSet *latchsets; // mapped latch set from latch pages
230 BtPool *pool; // memory pool page segments
232 HANDLE halloc; // allocation and latch table handle
237 BtMgr *mgr; // buffer manager for thread
238 BtPage cursor; // cached frame for start/next (never mapped)
239 BtPage frame; // spare frame for the page split (never mapped)
240 BtPage zero; // page frame for zeroes at end of file
241 uid cursor_page; // current cursor page number
242 unsigned char *mem; // frame, cursor, page memory buffer
243 int found; // last delete or insert was found
244 int err; // last error
258 extern void bt_close (BtDb *bt);
259 extern BtDb *bt_open (BtMgr *mgr);
260 extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod);
261 extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl);
262 extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
263 extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
264 extern uint bt_nextkey (BtDb *bt, uint slot);
267 extern BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolsize, uint segsize, uint hashsize);
268 void bt_mgrclose (BtMgr *mgr);
270 // Helper functions to return slot values
272 extern BtKey bt_key (BtDb *bt, uint slot);
273 extern uid bt_uid (BtDb *bt, uint slot);
274 extern uint bt_tod (BtDb *bt, uint slot);
276 // BTree page number constants
277 #define ALLOC_page 0 // allocation & lock manager hash table
278 #define ROOT_page 1 // root of the btree
279 #define LEAF_page 2 // first page of leaves
280 #define LATCH_page 3 // pages for lock manager
282 // Number of levels to create in a new BTree
286 // The page is allocated from low and hi ends.
287 // The key offsets and row-id's are allocated
288 // from the bottom, while the text of the key
289 // is allocated from the top. When the two
290 // areas meet, the page is split into two.
292 // A key consists of a length byte, two bytes of
293 // index number (0 - 65534), and up to 253 bytes
294 // of key value. Duplicate keys are discarded.
295 // Associated with each key is a 48 bit row-id,
296 // or any other value desired.
298 // The b-tree root is always located at page 1.
299 // The first leaf page of level zero is always
300 // located on page 2.
302 // The b-tree pages are linked with next
303 // pointers to facilitate enumerators,
304 // and provide for concurrency.
306 // When to root page fills, it is split in two and
307 // the tree height is raised by a new root at page
308 // one with two keys.
310 // Deleted keys are marked with a dead bit until
311 // page cleanup. The fence key for a node is
314 // Groups of pages called segments from the btree are optionally
315 // cached with a memory mapped pool. A hash table is used to keep
316 // track of the cached segments. This behaviour is controlled
317 // by the cache block size parameter to bt_open.
319 // To achieve maximum concurrency one page is locked at a time
320 // as the tree is traversed to find leaf key in question. The right
321 // page numbers are used in cases where the page is being split,
324 // Page 0 is dedicated to lock for new page extensions,
325 // and chains empty pages together for reuse.
327 // The ParentModification lock on a node is obtained to serialize posting
328 // or changing the fence key for a node.
330 // Empty pages are chained together through the ALLOC page and reused.
332 // Access macros to address slot and key values from the page
333 // Page slots use 1 based indexing.
335 #define slotptr(page, slot) (((BtSlot *)(page+1)) + (slot-1))
336 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
338 void bt_putid(unsigned char *dest, uid id)
343 dest[i] = (unsigned char)id, id >>= 8;
346 uid bt_getid(unsigned char *src)
351 for( i = 0; i < BtId; i++ )
352 id <<= 8, id |= *src++;
359 // wait until write lock mode is clear
360 // and add 1 to the share count
362 void bt_spinreadlock(BtSpinLatch *latch)
367 // obtain latch mutex
369 if( __sync_lock_test_and_set(&latch->mutex, 1) )
372 if( _InterlockedExchange8(&latch->mutex, 1) )
375 // see if exclusive request is granted or pending
377 if( prev = !(latch->exclusive | latch->pending) )
381 __sync_lock_release (&latch->mutex);
383 _InterlockedExchange8(&latch->mutex, 0);
390 } while( sched_yield(), 1 );
392 } while( SwitchToThread(), 1 );
396 // wait for other read and write latches to relinquish
398 void bt_spinwritelock(BtSpinLatch *latch)
404 if( __sync_lock_test_and_set(&latch->mutex, 1) )
407 if( _InterlockedExchange8(&latch->mutex, 1) )
410 if( prev = !(latch->share | latch->exclusive) )
411 latch->exclusive = 1, latch->pending = 0;
415 __sync_lock_release (&latch->mutex);
417 _InterlockedExchange8(&latch->mutex, 0);
422 } while( sched_yield(), 1 );
424 } while( SwitchToThread(), 1 );
428 // try to obtain write lock
430 // return 1 if obtained,
433 int bt_spinwritetry(BtSpinLatch *latch)
438 if( __sync_lock_test_and_set(&latch->mutex, 1) )
441 if( _InterlockedExchange8(&latch->mutex, 1) )
444 // take write access if all bits are clear
446 if( prev = !(latch->exclusive | latch->share) )
447 latch->exclusive = 1;
450 __sync_lock_release (&latch->mutex);
452 _InterlockedExchange8(&latch->mutex, 0);
459 void bt_spinreleasewrite(BtSpinLatch *latch)
462 while( __sync_lock_test_and_set(&latch->mutex, 1) )
465 while( _InterlockedExchange8(&latch->mutex, 1) )
468 latch->exclusive = 0;
470 __sync_lock_release (&latch->mutex);
472 _InterlockedExchange8(&latch->mutex, 0);
476 // decrement reader count
478 void bt_spinreleaseread(BtSpinLatch *latch)
481 while( __sync_lock_test_and_set(&latch->mutex, 1) )
484 while( _InterlockedExchange8(&latch->mutex, 1) )
489 __sync_lock_release (&latch->mutex);
491 _InterlockedExchange8(&latch->mutex, 0);
495 // link latch table entry into latch hash table
497 void bt_latchlink (BtDb *bt, ushort hashidx, ushort victim, uid page_no)
499 BtLatchSet *set = bt->mgr->latchsets + victim;
501 if( set->next = bt->mgr->latchmgr->table[hashidx].slot )
502 bt->mgr->latchsets[set->next].prev = victim;
504 bt->mgr->latchmgr->table[hashidx].slot = victim;
505 set->page_no = page_no;
512 void bt_unpinlatch (BtLatchSet *set)
515 __sync_fetch_and_add(&set->pin, -1);
517 _InterlockedDecrement16 (&set->pin);
521 // find existing latchset or inspire new one
522 // return with latchset pinned
524 BtLatchSet *bt_pinlatch (BtDb *bt, uid page_no)
526 ushort hashidx = page_no % bt->mgr->latchmgr->latchhash;
527 ushort slot, avail = 0, victim, idx;
530 // obtain read lock on hash table entry
532 bt_spinreadlock(bt->mgr->latchmgr->table[hashidx].latch);
534 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
536 set = bt->mgr->latchsets + slot;
537 if( page_no == set->page_no )
539 } while( slot = set->next );
543 __sync_fetch_and_add(&set->pin, 1);
545 _InterlockedIncrement16 (&set->pin);
549 bt_spinreleaseread (bt->mgr->latchmgr->table[hashidx].latch);
554 // try again, this time with write lock
556 bt_spinwritelock(bt->mgr->latchmgr->table[hashidx].latch);
558 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
560 set = bt->mgr->latchsets + slot;
561 if( page_no == set->page_no )
563 if( !set->pin && !avail )
565 } while( slot = set->next );
567 // found our entry, or take over an unpinned one
569 if( slot || (slot = avail) ) {
570 set = bt->mgr->latchsets + slot;
572 __sync_fetch_and_add(&set->pin, 1);
574 _InterlockedIncrement16 (&set->pin);
576 set->page_no = page_no;
577 bt_spinreleasewrite(bt->mgr->latchmgr->table[hashidx].latch);
581 // see if there are any unused entries
583 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, 1) + 1;
585 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchdeployed);
588 if( victim < bt->mgr->latchmgr->latchtotal ) {
589 set = bt->mgr->latchsets + victim;
591 __sync_fetch_and_add(&set->pin, 1);
593 _InterlockedIncrement16 (&set->pin);
595 bt_latchlink (bt, hashidx, victim, page_no);
596 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
601 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, -1);
603 victim = _InterlockedDecrement16 (&bt->mgr->latchmgr->latchdeployed);
605 // find and reuse previous lock entry
609 victim = __sync_fetch_and_add(&bt->mgr->latchmgr->latchvictim, 1);
611 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchvictim) - 1;
613 // we don't use slot zero
615 if( victim %= bt->mgr->latchmgr->latchtotal )
616 set = bt->mgr->latchsets + victim;
620 // take control of our slot
621 // from other threads
623 if( set->pin || !bt_spinwritetry (set->busy) )
628 // try to get write lock on hash chain
629 // skip entry if not obtained
630 // or has outstanding locks
632 if( !bt_spinwritetry (bt->mgr->latchmgr->table[idx].latch) ) {
633 bt_spinreleasewrite (set->busy);
638 bt_spinreleasewrite (set->busy);
639 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
643 // unlink our available victim from its hash chain
646 bt->mgr->latchsets[set->prev].next = set->next;
648 bt->mgr->latchmgr->table[idx].slot = set->next;
651 bt->mgr->latchsets[set->next].prev = set->prev;
653 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
655 __sync_fetch_and_add(&set->pin, 1);
657 _InterlockedIncrement16 (&set->pin);
659 bt_latchlink (bt, hashidx, victim, page_no);
660 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
661 bt_spinreleasewrite (set->busy);
666 void bt_mgrclose (BtMgr *mgr)
671 // release mapped pages
672 // note that slot zero is never used
674 for( slot = 1; slot < mgr->poolmax; slot++ ) {
675 pool = mgr->pool + slot;
678 munmap (pool->map, (mgr->poolmask+1) << mgr->page_bits);
681 FlushViewOfFile(pool->map, 0);
682 UnmapViewOfFile(pool->map);
683 CloseHandle(pool->hmap);
689 munmap (mgr->latchsets, mgr->latchmgr->nlatchpage * mgr->page_size);
690 munmap (mgr->latchmgr, mgr->page_size);
692 FlushViewOfFile(mgr->latchmgr, 0);
693 UnmapViewOfFile(mgr->latchmgr);
694 CloseHandle(mgr->halloc);
703 FlushFileBuffers(mgr->idx);
704 CloseHandle(mgr->idx);
705 GlobalFree (mgr->pool);
706 GlobalFree (mgr->hash);
707 GlobalFree (mgr->latch);
712 // close and release memory
714 void bt_close (BtDb *bt)
721 VirtualFree (bt->mem, 0, MEM_RELEASE);
726 // open/create new btree buffer manager
728 // call with file_name, BT_openmode, bits in page size (e.g. 16),
729 // size of mapped page pool (e.g. 8192)
731 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
733 uint lvl, attr, cacheblk, last, slot, idx;
734 uint nlatchpage, latchhash;
735 BtLatchMgr *latchmgr;
743 SYSTEM_INFO sysinfo[1];
746 // determine sanity of page size and buffer pool
748 if( bits > BT_maxbits )
750 else if( bits < BT_minbits )
754 return NULL; // must have buffer pool
757 mgr = calloc (1, sizeof(BtMgr));
759 mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
762 return free(mgr), NULL;
764 cacheblk = 4096; // minimum mmap segment size for unix
767 mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
768 attr = FILE_ATTRIBUTE_NORMAL;
769 mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
771 if( mgr->idx == INVALID_HANDLE_VALUE )
772 return GlobalFree(mgr), NULL;
774 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
775 GetSystemInfo(sysinfo);
776 cacheblk = sysinfo->dwAllocationGranularity;
780 latchmgr = malloc (BT_maxpage);
783 // read minimum page size to get root info
785 if( size = lseek (mgr->idx, 0L, 2) ) {
786 if( pread(mgr->idx, latchmgr, BT_minpage, 0) == BT_minpage )
787 bits = latchmgr->alloc->bits;
789 return free(mgr), free(latchmgr), NULL;
790 } else if( mode == BT_ro )
791 return free(latchmgr), bt_mgrclose (mgr), NULL;
793 latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
794 size = GetFileSize(mgr->idx, amt);
797 if( !ReadFile(mgr->idx, (char *)latchmgr, BT_minpage, amt, NULL) )
798 return bt_mgrclose (mgr), NULL;
799 bits = latchmgr->alloc->bits;
800 } else if( mode == BT_ro )
801 return bt_mgrclose (mgr), NULL;
804 mgr->page_size = 1 << bits;
805 mgr->page_bits = bits;
807 mgr->poolmax = poolmax;
810 if( cacheblk < mgr->page_size )
811 cacheblk = mgr->page_size;
813 // mask for partial memmaps
815 mgr->poolmask = (cacheblk >> bits) - 1;
817 // see if requested size of pages per memmap is greater
819 if( (1 << segsize) > mgr->poolmask )
820 mgr->poolmask = (1 << segsize) - 1;
824 while( (1 << mgr->seg_bits) <= mgr->poolmask )
827 mgr->hashsize = hashsize;
830 mgr->pool = calloc (poolmax, sizeof(BtPool));
831 mgr->hash = calloc (hashsize, sizeof(ushort));
832 mgr->latch = calloc (hashsize, sizeof(BtSpinLatch));
834 mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * sizeof(BtPool));
835 mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
836 mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtSpinLatch));
842 // initialize an empty b-tree with latch page, root page, page of leaves
843 // and page(s) of latches
845 memset (latchmgr, 0, 1 << bits);
846 nlatchpage = BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1;
847 bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
848 latchmgr->alloc->bits = mgr->page_bits;
850 latchmgr->nlatchpage = nlatchpage;
851 latchmgr->latchtotal = nlatchpage * (mgr->page_size / sizeof(BtLatchSet));
853 // initialize latch manager
855 latchhash = (mgr->page_size - sizeof(BtLatchMgr)) / sizeof(BtHashEntry);
857 // size of hash table = total number of latchsets
859 if( latchhash > latchmgr->latchtotal )
860 latchhash = latchmgr->latchtotal;
862 latchmgr->latchhash = latchhash;
865 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
866 return bt_mgrclose (mgr), NULL;
868 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
869 return bt_mgrclose (mgr), NULL;
871 if( *amt < mgr->page_size )
872 return bt_mgrclose (mgr), NULL;
875 memset (latchmgr, 0, 1 << bits);
876 latchmgr->alloc->bits = mgr->page_bits;
878 for( lvl=MIN_lvl; lvl--; ) {
879 slotptr(latchmgr->alloc, 1)->off = mgr->page_size - 3;
880 bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
881 key = keyptr(latchmgr->alloc, 1);
882 key->len = 2; // create stopper key
885 latchmgr->alloc->min = mgr->page_size - 3;
886 latchmgr->alloc->lvl = lvl;
887 latchmgr->alloc->cnt = 1;
888 latchmgr->alloc->act = 1;
890 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
891 return bt_mgrclose (mgr), NULL;
893 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
894 return bt_mgrclose (mgr), NULL;
896 if( *amt < mgr->page_size )
897 return bt_mgrclose (mgr), NULL;
901 // clear out latch manager locks
902 // and rest of pages to round out segment
904 memset(latchmgr, 0, mgr->page_size);
907 while( last <= ((MIN_lvl + 1 + nlatchpage) | mgr->poolmask) ) {
909 pwrite(mgr->idx, latchmgr, mgr->page_size, last << mgr->page_bits);
911 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
912 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
913 return bt_mgrclose (mgr), NULL;
914 if( *amt < mgr->page_size )
915 return bt_mgrclose (mgr), NULL;
922 flag = PROT_READ | PROT_WRITE;
923 mgr->latchmgr = mmap (0, mgr->page_size, flag, MAP_SHARED, mgr->idx, ALLOC_page * mgr->page_size);
924 if( mgr->latchmgr == MAP_FAILED )
925 return bt_mgrclose (mgr), NULL;
926 mgr->latchsets = (BtLatchSet *)mmap (0, mgr->latchmgr->nlatchpage * mgr->page_size, flag, MAP_SHARED, mgr->idx, LATCH_page * mgr->page_size);
927 if( mgr->latchsets == MAP_FAILED )
928 return bt_mgrclose (mgr), NULL;
930 flag = PAGE_READWRITE;
931 mgr->halloc = CreateFileMapping(mgr->idx, NULL, flag, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size, NULL);
933 return bt_mgrclose (mgr), NULL;
935 flag = FILE_MAP_WRITE;
936 mgr->latchmgr = MapViewOfFile(mgr->halloc, flag, 0, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size);
938 return GetLastError(), bt_mgrclose (mgr), NULL;
940 mgr->latchsets = (void *)((char *)mgr->latchmgr + LATCH_page * mgr->page_size);
946 VirtualFree (latchmgr, 0, MEM_RELEASE);
951 // open BTree access method
952 // based on buffer manager
954 BtDb *bt_open (BtMgr *mgr)
956 BtDb *bt = malloc (sizeof(*bt));
958 memset (bt, 0, sizeof(*bt));
961 bt->mem = malloc (3 *mgr->page_size);
963 bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
965 bt->frame = (BtPage)bt->mem;
966 bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
967 bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
969 memset (bt->zero, 0, mgr->page_size);
973 // compare two keys, returning > 0, = 0, or < 0
974 // as the comparison value
976 int keycmp (BtKey key1, unsigned char *key2, uint len2)
978 uint len1 = key1->len;
981 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
994 // find segment in pool
995 // must be called with hashslot idx locked
996 // return NULL if not there
997 // otherwise return node
999 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
1004 // compute start of hash chain in pool
1006 if( slot = bt->mgr->hash[idx] )
1007 pool = bt->mgr->pool + slot;
1011 page_no &= ~bt->mgr->poolmask;
1013 while( pool->basepage != page_no )
1014 if( pool = pool->hashnext )
1022 // add segment to hash table
1024 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
1029 pool->hashprev = pool->hashnext = NULL;
1030 pool->basepage = page_no & ~bt->mgr->poolmask;
1033 if( slot = bt->mgr->hash[idx] ) {
1034 node = bt->mgr->pool + slot;
1035 pool->hashnext = node;
1036 node->hashprev = pool;
1039 bt->mgr->hash[idx] = pool->slot;
1042 // find best segment to evict from buffer pool
1044 BtPool *bt_findlru (BtDb *bt, uint hashslot)
1046 unsigned long long int target = ~0LL;
1047 BtPool *pool = NULL, *node;
1052 node = bt->mgr->pool + hashslot;
1054 // scan pool entries under hash table slot
1059 if( node->lru > target )
1063 } while( node = node->hashnext );
1068 // map new buffer pool segment to virtual memory
1070 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
1072 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
1073 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
1077 flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
1078 pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED, bt->mgr->idx, off);
1079 if( pool->map == MAP_FAILED )
1080 return bt->err = BTERR_map;
1083 flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
1084 pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
1086 return bt->err = BTERR_map;
1088 flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
1089 pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1091 return bt->err = BTERR_map;
1096 // calculate page within pool
1098 BtPage bt_page (BtDb *bt, BtPool *pool, uid page_no)
1100 uint subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1103 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1109 void bt_unpinpool (BtPool *pool)
1112 __sync_fetch_and_add(&pool->pin, -1);
1114 _InterlockedDecrement16 (&pool->pin);
1118 // find or place requested page in segment-pool
1119 // return pool table entry, incrementing pin
1121 BtPool *bt_pinpool(BtDb *bt, uid page_no)
1123 BtPool *pool, *node, *next;
1124 uint slot, idx, victim;
1126 // lock hash table chain
1128 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1129 bt_spinreadlock (&bt->mgr->latch[idx]);
1131 // look up in hash table
1133 if( pool = bt_findpool(bt, page_no, idx) ) {
1135 __sync_fetch_and_add(&pool->pin, 1);
1137 _InterlockedIncrement16 (&pool->pin);
1139 bt_spinreleaseread (&bt->mgr->latch[idx]);
1144 // upgrade to write lock
1146 bt_spinreleaseread (&bt->mgr->latch[idx]);
1147 bt_spinwritelock (&bt->mgr->latch[idx]);
1149 // try to find page in pool with write lock
1151 if( pool = bt_findpool(bt, page_no, idx) ) {
1153 __sync_fetch_and_add(&pool->pin, 1);
1155 _InterlockedIncrement16 (&pool->pin);
1157 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1162 // allocate a new pool node
1163 // and add to hash table
1166 slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
1168 slot = _InterlockedIncrement16 (&bt->mgr->poolcnt) - 1;
1171 if( ++slot < bt->mgr->poolmax ) {
1172 pool = bt->mgr->pool + slot;
1175 if( bt_mapsegment(bt, pool, page_no) )
1178 bt_linkhash(bt, pool, page_no, idx);
1180 __sync_fetch_and_add(&pool->pin, 1);
1182 _InterlockedIncrement16 (&pool->pin);
1184 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1188 // pool table is full
1189 // find best pool entry to evict
1192 __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
1194 _InterlockedDecrement16 (&bt->mgr->poolcnt);
1199 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
1201 victim = _InterlockedIncrement (&bt->mgr->evicted) - 1;
1203 victim %= bt->mgr->hashsize;
1205 // try to get write lock
1206 // skip entry if not obtained
1208 if( !bt_spinwritetry (&bt->mgr->latch[victim]) )
1211 // if pool entry is empty
1212 // or any pages are pinned
1215 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
1216 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1220 // unlink victim pool node from hash table
1222 if( node = pool->hashprev )
1223 node->hashnext = pool->hashnext;
1224 else if( node = pool->hashnext )
1225 bt->mgr->hash[victim] = node->slot;
1227 bt->mgr->hash[victim] = 0;
1229 if( node = pool->hashnext )
1230 node->hashprev = pool->hashprev;
1232 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1234 // remove old file mapping
1236 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1238 FlushViewOfFile(pool->map, 0);
1239 UnmapViewOfFile(pool->map);
1240 CloseHandle(pool->hmap);
1244 // create new pool mapping
1245 // and link into hash table
1247 if( bt_mapsegment(bt, pool, page_no) )
1250 bt_linkhash(bt, pool, page_no, idx);
1252 __sync_fetch_and_add(&pool->pin, 1);
1254 _InterlockedIncrement16 (&pool->pin);
1256 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1261 // place write, read, or parent lock on requested page_no.
1263 void bt_lockpage(BtLock mode, BtLatchSet *set)
1267 bt_spinreadlock (set->readwr);
1270 bt_spinwritelock (set->readwr);
1273 bt_spinreadlock (set->access);
1276 bt_spinwritelock (set->access);
1279 bt_spinwritelock (set->parent);
1284 // remove write, read, or parent lock on requested page
1286 void bt_unlockpage(BtLock mode, BtLatchSet *set)
1290 bt_spinreleaseread (set->readwr);
1293 bt_spinreleasewrite (set->readwr);
1296 bt_spinreleaseread (set->access);
1299 bt_spinreleasewrite (set->access);
1302 bt_spinreleasewrite (set->parent);
1307 // allocate a new page and write page into it
1309 uid bt_newpage(BtDb *bt, BtPage page)
1315 // lock allocation page
1317 bt_spinwritelock(bt->mgr->latchmgr->lock);
1319 // use empty chain first
1320 // else allocate empty page
1322 if( new_page = bt_getid(bt->mgr->latchmgr->alloc[1].right) ) {
1323 if( set->pool = bt_pinpool (bt, new_page) )
1324 set->page = bt_page (bt, set->pool, new_page);
1328 bt_putid(bt->mgr->latchmgr->alloc[1].right, bt_getid(set->page->right));
1329 bt_unpinpool (set->pool);
1332 new_page = bt_getid(bt->mgr->latchmgr->alloc->right);
1333 bt_putid(bt->mgr->latchmgr->alloc->right, new_page+1);
1337 if ( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1338 return bt->err = BTERR_wrt, 0;
1340 // if writing first page of pool block, zero last page in the block
1342 if ( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1344 // use zero buffer to write zeros
1345 if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1346 return bt->err = BTERR_wrt, 0;
1349 // bring new page into pool and copy page.
1350 // this will extend the file into the new pages.
1352 if( set->pool = bt_pinpool (bt, new_page) )
1353 set->page = bt_page (bt, set->pool, new_page);
1357 memcpy(set->page, page, bt->mgr->page_size);
1358 bt_unpinpool (set->pool);
1360 // unlock allocation latch and return new page no
1362 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1366 // find slot in page for given key at a given level
1368 int bt_findslot (BtPageSet *set, unsigned char *key, uint len)
1370 uint diff, higher = set->page->cnt, low = 1, slot;
1373 // make stopper key an infinite fence value
1375 if( bt_getid (set->page->right) )
1380 // low is the lowest candidate.
1381 // loop ends when they meet
1383 // higher is already
1384 // tested as .ge. the passed key.
1386 while( diff = higher - low ) {
1387 slot = low + ( diff >> 1 );
1388 if( keycmp (keyptr(set->page, slot), key, len) < 0 )
1391 higher = slot, good++;
1394 // return zero if key is on right link page
1396 return good ? higher : 0;
1399 // find and load page at given level for given key
1400 // leave page rd or wr locked as requested
1402 int bt_loadpage (BtDb *bt, BtPageSet *set, unsigned char *key, uint len, uint lvl, BtLock lock)
1404 uid page_no = ROOT_page, prevpage = 0;
1405 uint drill = 0xff, slot;
1406 BtLatchSet *prevlatch;
1407 uint mode, prevmode;
1410 // start at root of btree and drill down
1413 // determine lock mode of drill level
1414 mode = (drill == lvl) ? lock : BtLockRead;
1416 set->latch = bt_pinlatch (bt, page_no);
1417 set->page_no = page_no;
1419 // pin page contents
1421 if( set->pool = bt_pinpool (bt, page_no) )
1422 set->page = bt_page (bt, set->pool, page_no);
1426 // obtain access lock using lock chaining with Access mode
1428 if( page_no > ROOT_page )
1429 bt_lockpage(BtLockAccess, set->latch);
1431 // release & unpin parent page
1434 bt_unlockpage(prevmode, prevlatch);
1435 bt_unpinlatch (prevlatch);
1436 bt_unpinpool (prevpool);
1440 // obtain read lock using lock chaining
1442 bt_lockpage(mode, set->latch);
1444 if( set->page->free )
1445 return bt->err = BTERR_struct, 0;
1447 if( page_no > ROOT_page )
1448 bt_unlockpage(BtLockAccess, set->latch);
1450 // re-read and re-lock root after determining actual level of root
1452 if( set->page->lvl != drill) {
1453 if ( set->page_no != ROOT_page )
1454 return bt->err = BTERR_struct, 0;
1456 drill = set->page->lvl;
1458 if( lock != BtLockRead && drill == lvl ) {
1459 bt_unlockpage(mode, set->latch);
1460 bt_unpinlatch (set->latch);
1461 bt_unpinpool (set->pool);
1466 prevpage = set->page_no;
1467 prevlatch = set->latch;
1468 prevpool = set->pool;
1471 // find key on page at this level
1472 // and descend to requested level
1474 if( !set->page->kill )
1475 if( slot = bt_findslot (set, key, len) ) {
1479 while( slotptr(set->page, slot)->dead )
1480 if( slot++ < set->page->cnt )
1485 page_no = bt_getid(slotptr(set->page, slot)->id);
1490 // or slide right into next page
1493 page_no = bt_getid(set->page->right);
1497 // return error on end of right chain
1499 bt->err = BTERR_struct;
1500 return 0; // return error
1503 // return page to free list
1504 // page must be delete & write locked
1506 void bt_freepage (BtDb *bt, BtPageSet *set)
1508 // lock allocation page
1510 bt_spinwritelock (bt->mgr->latchmgr->lock);
1512 // store chain in second right
1513 bt_putid(set->page->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1514 bt_putid(bt->mgr->latchmgr->alloc[1].right, set->page_no);
1515 set->page->free = 1;
1517 // unlock released page
1519 bt_unlockpage (BtLockDelete, set->latch);
1520 bt_unlockpage (BtLockWrite, set->latch);
1521 bt_unpinlatch (set->latch);
1522 bt_unpinpool (set->pool);
1524 // unlock allocation page
1526 bt_spinreleasewrite (bt->mgr->latchmgr->lock);
1529 // a fence key was deleted from a page
1530 // push new fence value upwards
1532 BTERR bt_fixfence (BtDb *bt, BtPageSet *set, uint lvl)
1534 unsigned char leftkey[256], rightkey[256];
1538 // remove the old fence value
1540 ptr = keyptr(set->page, set->page->cnt);
1541 memcpy (rightkey, ptr, ptr->len + 1);
1543 memset (slotptr(set->page, set->page->cnt--), 0, sizeof(BtSlot));
1544 set->page->dirty = 1;
1546 ptr = keyptr(set->page, set->page->cnt);
1547 memcpy (leftkey, ptr, ptr->len + 1);
1548 page_no = set->page_no;
1550 bt_lockpage (BtLockParent, set->latch);
1551 bt_unlockpage (BtLockWrite, set->latch);
1553 // insert new (now smaller) fence key
1555 if( bt_insertkey (bt, leftkey+1, *leftkey, lvl+1, page_no, time(NULL)) )
1558 // now delete old fence key
1560 if( bt_deletekey (bt, rightkey+1, *rightkey, lvl+1) )
1563 bt_unlockpage (BtLockParent, set->latch);
1564 bt_unpinlatch(set->latch);
1565 bt_unpinpool (set->pool);
1569 // root has a single child
1570 // collapse a level from the tree
1572 BTERR bt_collapseroot (BtDb *bt, BtPageSet *root)
1577 // find the child entry and promote as new root contents
1580 for( idx = 0; idx++ < root->page->cnt; )
1581 if( !slotptr(root->page, idx)->dead )
1584 child->page_no = bt_getid (slotptr(root->page, idx)->id);
1586 child->latch = bt_pinlatch (bt, child->page_no);
1587 bt_lockpage (BtLockDelete, child->latch);
1588 bt_lockpage (BtLockWrite, child->latch);
1590 if( child->pool = bt_pinpool (bt, child->page_no) )
1591 child->page = bt_page (bt, child->pool, child->page_no);
1595 memcpy (root->page, child->page, bt->mgr->page_size);
1596 bt_freepage (bt, child);
1598 } while( root->page->lvl > 1 && root->page->act == 1 );
1600 bt_unlockpage (BtLockWrite, root->latch);
1601 bt_unpinlatch (root->latch);
1602 bt_unpinpool (root->pool);
1606 // find and delete key on page by marking delete flag bit
1607 // if page becomes empty, delete it from the btree
1609 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl)
1611 unsigned char lowerfence[256], higherfence[256];
1612 uint slot, idx, dirty = 0, fence, found;
1613 BtPageSet set[1], right[1];
1616 if( slot = bt_loadpage (bt, set, key, len, lvl, BtLockWrite) )
1617 ptr = keyptr(set->page, slot);
1621 // are we deleting a fence slot?
1623 fence = slot == set->page->cnt;
1625 // if key is found delete it, otherwise ignore request
1627 if( found = !keycmp (ptr, key, len) )
1628 if( found = slotptr(set->page, slot)->dead == 0 ) {
1629 dirty = slotptr(set->page, slot)->dead = 1;
1630 set->page->dirty = 1;
1633 // collapse empty slots
1635 while( idx = set->page->cnt - 1 )
1636 if( slotptr(set->page, idx)->dead ) {
1637 *slotptr(set->page, idx) = *slotptr(set->page, idx + 1);
1638 memset (slotptr(set->page, set->page->cnt--), 0, sizeof(BtSlot));
1643 // did we delete a fence key in an upper level?
1645 if( dirty && lvl && set->page->act && fence )
1646 if( bt_fixfence (bt, set, lvl) )
1649 return bt->found = found, 0;
1651 // is this a collapsed root?
1653 if( lvl > 1 && set->page_no == ROOT_page && set->page->act == 1 )
1654 if( bt_collapseroot (bt, set) )
1657 return bt->found = found, 0;
1659 // return if page is not empty
1661 if( set->page->act ) {
1662 bt_unlockpage(BtLockWrite, set->latch);
1663 bt_unpinlatch (set->latch);
1664 bt_unpinpool (set->pool);
1665 return bt->found = found, 0;
1668 // cache copy of fence key
1669 // to post in parent
1671 ptr = keyptr(set->page, set->page->cnt);
1672 memcpy (lowerfence, ptr, ptr->len + 1);
1674 // obtain lock on right page
1676 right->page_no = bt_getid(set->page->right);
1677 right->latch = bt_pinlatch (bt, right->page_no);
1678 bt_lockpage (BtLockWrite, right->latch);
1680 // pin page contents
1682 if( right->pool = bt_pinpool (bt, right->page_no) )
1683 right->page = bt_page (bt, right->pool, right->page_no);
1687 if( right->page->kill )
1688 return bt->err = BTERR_struct;
1690 // pull contents of right peer into our empty page
1692 memcpy (set->page, right->page, bt->mgr->page_size);
1694 // cache copy of key to update
1696 ptr = keyptr(right->page, right->page->cnt);
1697 memcpy (higherfence, ptr, ptr->len + 1);
1699 // mark right page deleted and point it to left page
1700 // until we can post parent updates
1702 bt_putid (right->page->right, set->page_no);
1703 right->page->kill = 1;
1705 bt_lockpage (BtLockParent, right->latch);
1706 bt_unlockpage (BtLockWrite, right->latch);
1708 bt_lockpage (BtLockParent, set->latch);
1709 bt_unlockpage (BtLockWrite, set->latch);
1711 // redirect higher key directly to our new node contents
1713 if( bt_insertkey (bt, higherfence+1, *higherfence, lvl+1, set->page_no, time(NULL)) )
1716 // delete old lower key to our node
1718 if( bt_deletekey (bt, lowerfence+1, *lowerfence, lvl+1) )
1721 // obtain delete and write locks to right node
1723 bt_unlockpage (BtLockParent, right->latch);
1724 bt_lockpage (BtLockDelete, right->latch);
1725 bt_lockpage (BtLockWrite, right->latch);
1726 bt_freepage (bt, right);
1728 bt_unlockpage (BtLockParent, set->latch);
1729 bt_unpinlatch (set->latch);
1730 bt_unpinpool (set->pool);
1735 // find key in leaf level and return row-id
1737 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1744 if( slot = bt_loadpage (bt, set, key, len, 0, BtLockRead) )
1745 ptr = keyptr(set->page, slot);
1749 // if key exists, return row-id
1750 // otherwise return 0
1752 if( slot <= set->page->cnt )
1753 if( !keycmp (ptr, key, len) )
1754 id = bt_getid(slotptr(set->page,slot)->id);
1756 bt_unlockpage (BtLockRead, set->latch);
1757 bt_unpinlatch (set->latch);
1758 bt_unpinpool (set->pool);
1762 // check page for space available,
1763 // clean if necessary and return
1764 // 0 - page needs splitting
1765 // >0 new slot value
1767 uint bt_cleanpage(BtDb *bt, BtPage page, uint amt, uint slot)
1769 uint nxt = bt->mgr->page_size;
1770 uint cnt = 0, idx = 0;
1771 uint max = page->cnt;
1775 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1778 // skip cleanup if nothing to reclaim
1783 memcpy (bt->frame, page, bt->mgr->page_size);
1785 // skip page info and set rest of page to zero
1787 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1791 // try cleaning up page first
1792 // by removing deleted keys
1794 while( cnt++ < max ) {
1797 if( cnt < max && slotptr(bt->frame,cnt)->dead )
1800 // copy the key across
1802 key = keyptr(bt->frame, cnt);
1803 nxt -= key->len + 1;
1804 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1808 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1809 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1811 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1812 slotptr(page, idx)->off = nxt;
1818 // see if page has enough space now, or does it need splitting?
1820 if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1826 // split the root and raise the height of the btree
1828 BTERR bt_splitroot(BtDb *bt, BtPageSet *root, unsigned char *leftkey, uid page_no2)
1830 uint nxt = bt->mgr->page_size;
1833 // Obtain an empty page to use, and copy the current
1834 // root contents into it, e.g. lower keys
1836 if( !(left = bt_newpage(bt, root->page)) )
1839 // preserve the page info at the bottom
1840 // of higher keys and set rest to zero
1842 memset(root->page+1, 0, bt->mgr->page_size - sizeof(*root->page));
1844 // insert lower keys page fence key on newroot page as first key
1846 nxt -= *leftkey + 1;
1847 memcpy ((unsigned char *)root->page + nxt, leftkey, *leftkey + 1);
1848 bt_putid(slotptr(root->page, 1)->id, left);
1849 slotptr(root->page, 1)->off = nxt;
1851 // insert stopper key on newroot page
1852 // and increase the root height
1855 ((unsigned char *)root->page)[nxt] = 2;
1856 ((unsigned char *)root->page)[nxt+1] = 0xff;
1857 ((unsigned char *)root->page)[nxt+2] = 0xff;
1858 bt_putid(slotptr(root->page, 2)->id, page_no2);
1859 slotptr(root->page, 2)->off = nxt;
1861 bt_putid(root->page->right, 0);
1862 root->page->min = nxt; // reset lowest used offset and key count
1863 root->page->cnt = 2;
1864 root->page->act = 2;
1867 // release and unpin root
1869 bt_unlockpage(BtLockWrite, root->latch);
1870 bt_unpinlatch (root->latch);
1871 bt_unpinpool (root->pool);
1875 // split already locked full node
1878 BTERR bt_splitpage (BtDb *bt, BtPageSet *set)
1880 uint cnt = 0, idx = 0, max, nxt = bt->mgr->page_size;
1881 unsigned char fencekey[256], rightkey[256];
1882 uint lvl = set->page->lvl;
1887 // split higher half of keys to bt->frame
1889 memset (bt->frame, 0, bt->mgr->page_size);
1890 max = set->page->cnt;
1894 while( cnt++ < max ) {
1895 key = keyptr(set->page, cnt);
1896 nxt -= key->len + 1;
1897 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
1899 memcpy(slotptr(bt->frame,++idx)->id, slotptr(set->page,cnt)->id, BtId);
1900 if( !(slotptr(bt->frame, idx)->dead = slotptr(set->page, cnt)->dead) )
1902 slotptr(bt->frame, idx)->tod = slotptr(set->page, cnt)->tod;
1903 slotptr(bt->frame, idx)->off = nxt;
1906 // remember existing fence key for new page to the right
1908 memcpy (rightkey, key, key->len + 1);
1910 bt->frame->bits = bt->mgr->page_bits;
1911 bt->frame->min = nxt;
1912 bt->frame->cnt = idx;
1913 bt->frame->lvl = lvl;
1917 if( set->page_no > ROOT_page )
1918 memcpy (bt->frame->right, set->page->right, BtId);
1920 // get new free page and write higher keys to it.
1922 if( !(right->page_no = bt_newpage(bt, bt->frame)) )
1925 // update lower keys to continue in old page
1927 memcpy (bt->frame, set->page, bt->mgr->page_size);
1928 memset (set->page+1, 0, bt->mgr->page_size - sizeof(*set->page));
1929 nxt = bt->mgr->page_size;
1930 set->page->dirty = 0;
1935 // assemble page of smaller keys
1937 while( cnt++ < max / 2 ) {
1938 key = keyptr(bt->frame, cnt);
1939 nxt -= key->len + 1;
1940 memcpy ((unsigned char *)set->page + nxt, key, key->len + 1);
1941 memcpy(slotptr(set->page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1942 slotptr(set->page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1943 slotptr(set->page, idx)->off = nxt;
1947 // remember fence key for smaller page
1949 memcpy(fencekey, key, key->len + 1);
1951 bt_putid(set->page->right, right->page_no);
1952 set->page->min = nxt;
1953 set->page->cnt = idx;
1955 // if current page is the root page, split it
1957 if( set->page_no == ROOT_page )
1958 return bt_splitroot (bt, set, fencekey, right->page_no);
1960 // insert new fences in their parent pages
1962 right->latch = bt_pinlatch (bt, right->page_no);
1963 bt_lockpage (BtLockParent, right->latch);
1965 bt_lockpage (BtLockParent, set->latch);
1966 bt_unlockpage (BtLockWrite, set->latch);
1968 // insert new fence for reformulated left block of smaller keys
1970 if( bt_insertkey (bt, fencekey+1, *fencekey, lvl+1, set->page_no, time(NULL)) )
1973 // switch fence for right block of larger keys to new right page
1975 if( bt_insertkey (bt, rightkey+1, *rightkey, lvl+1, right->page_no, time(NULL)) )
1978 bt_unlockpage (BtLockParent, set->latch);
1979 bt_unpinlatch (set->latch);
1980 bt_unpinpool (set->pool);
1982 bt_unlockpage (BtLockParent, right->latch);
1983 bt_unpinlatch (right->latch);
1986 // Insert new key into the btree at given level.
1988 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod)
1995 if( slot = bt_loadpage (bt, set, key, len, lvl, BtLockWrite) )
1996 ptr = keyptr(set->page, slot);
2000 bt->err = BTERR_ovflw;
2004 // if key already exists, update id and return
2006 if( !keycmp (ptr, key, len) ) {
2007 if( slotptr(set->page, slot)->dead )
2009 slotptr(set->page, slot)->dead = 0;
2010 slotptr(set->page, slot)->tod = tod;
2011 bt_putid(slotptr(set->page,slot)->id, id);
2012 bt_unlockpage(BtLockWrite, set->latch);
2013 bt_unpinlatch (set->latch);
2014 bt_unpinpool (set->pool);
2018 // check if page has enough space
2020 if( slot = bt_cleanpage (bt, set->page, len, slot) )
2023 if( bt_splitpage (bt, set) )
2027 // calculate next available slot and copy key into page
2029 set->page->min -= len + 1; // reset lowest used offset
2030 ((unsigned char *)set->page)[set->page->min] = len;
2031 memcpy ((unsigned char *)set->page + set->page->min +1, key, len );
2033 for( idx = slot; idx < set->page->cnt; idx++ )
2034 if( slotptr(set->page, idx)->dead )
2037 // now insert key into array before slot
2039 if( idx == set->page->cnt )
2040 idx++, set->page->cnt++;
2045 *slotptr(set->page, idx) = *slotptr(set->page, idx -1), idx--;
2047 bt_putid(slotptr(set->page,slot)->id, id);
2048 slotptr(set->page, slot)->off = set->page->min;
2049 slotptr(set->page, slot)->tod = tod;
2050 slotptr(set->page, slot)->dead = 0;
2052 bt_unlockpage (BtLockWrite, set->latch);
2053 bt_unpinlatch (set->latch);
2054 bt_unpinpool (set->pool);
2058 // cache page of keys into cursor and return starting slot for given key
2060 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2065 // cache page for retrieval
2067 if( slot = bt_loadpage (bt, set, key, len, 0, BtLockRead) )
2068 memcpy (bt->cursor, set->page, bt->mgr->page_size);
2072 bt->cursor_page = set->page_no;
2074 bt_unlockpage(BtLockRead, set->latch);
2075 bt_unpinlatch (set->latch);
2076 bt_unpinpool (set->pool);
2080 // return next slot for cursor page
2081 // or slide cursor right into next page
2083 uint bt_nextkey (BtDb *bt, uint slot)
2089 right = bt_getid(bt->cursor->right);
2091 while( slot++ < bt->cursor->cnt )
2092 if( slotptr(bt->cursor,slot)->dead )
2094 else if( right || (slot < bt->cursor->cnt) ) // skip infinite stopper
2102 bt->cursor_page = right;
2104 if( set->pool = bt_pinpool (bt, right) )
2105 set->page = bt_page (bt, set->pool, right);
2109 set->latch = bt_pinlatch (bt, right);
2110 bt_lockpage(BtLockRead, set->latch);
2112 memcpy (bt->cursor, set->page, bt->mgr->page_size);
2114 bt_unlockpage(BtLockRead, set->latch);
2115 bt_unpinlatch (set->latch);
2116 bt_unpinpool (set->pool);
2124 BtKey bt_key(BtDb *bt, uint slot)
2126 return keyptr(bt->cursor, slot);
2129 uid bt_uid(BtDb *bt, uint slot)
2131 return bt_getid(slotptr(bt->cursor,slot)->id);
2134 uint bt_tod(BtDb *bt, uint slot)
2136 return slotptr(bt->cursor,slot)->tod;
2142 void bt_latchaudit (BtDb *bt)
2144 ushort idx, hashidx;
2152 for( idx = 1; idx < bt->mgr->latchmgr->latchdeployed; idx++ ) {
2153 latch = bt->mgr->latchsets + idx;
2154 if( *(ushort *)latch->readwr ) {
2155 fprintf(stderr, "latchset %d r/w locked for page %.8x\n", idx, latch->page_no);
2156 *(ushort *)latch->readwr = 0;
2158 if( *(ushort *)latch->access ) {
2159 fprintf(stderr, "latchset %d access locked for page %.8x\n", idx, latch->page_no);
2160 *(ushort *)latch->access = 0;
2162 if( *(ushort *)latch->parent ) {
2163 fprintf(stderr, "latchset %d parent locked for page %.8x\n", idx, latch->page_no);
2164 *(ushort *)latch->parent = 0;
2166 if( *(ushort *)latch->busy ) {
2167 fprintf(stderr, "latchset %d busy locked for page %.8x\n", idx, latch->page_no);
2168 *(ushort *)latch->parent = 0;
2171 fprintf(stderr, "latchset %d pinned for page %.8x\n", idx, latch->page_no);
2176 for( hashidx = 0; hashidx < bt->mgr->latchmgr->latchhash; hashidx++ ) {
2177 if( idx = bt->mgr->latchmgr->table[hashidx].slot ) do {
2178 latch = bt->mgr->latchsets + idx;
2179 if( latch->hash != hashidx ) {
2180 fprintf(stderr, "latchset %d wrong hashidx\n", idx);
2181 latch->hash = hashidx;
2183 } while( idx = latch->next );
2186 next = bt->mgr->latchmgr->nlatchpage + LATCH_page;
2187 page_no = LEAF_page;
2189 while( page_no < bt_getid(bt->mgr->latchmgr->alloc->right) ) {
2190 pread (bt->mgr->idx, bt->frame, bt->mgr->page_size, page_no << bt->mgr->page_bits);
2191 if( !bt->frame->free )
2192 for( idx = 0; idx++ < bt->frame->cnt - 1; ) {
2193 ptr = keyptr(bt->frame, idx+1);
2194 if( keycmp (keyptr(bt->frame, idx), ptr->key, ptr->len) >= 0 )
2195 fprintf(stderr, "page %.8x idx %.2x out of order\n", page_no, idx);
2198 if( page_no > LEAF_page )
2212 // standalone program to index file of keys
2213 // then list them onto std-out
2216 void *index_file (void *arg)
2218 uint __stdcall index_file (void *arg)
2221 int line = 0, found = 0, cnt = 0;
2222 uid next, page_no = LEAF_page; // start on first page of leaves
2223 unsigned char key[256];
2224 ThreadArg *args = arg;
2225 int ch, len = 0, slot;
2232 bt = bt_open (args->mgr);
2235 switch(args->type | 0x20)
2238 fprintf(stderr, "started latch mgr audit\n");
2240 fprintf(stderr, "finished latch mgr audit\n");
2244 fprintf(stderr, "started indexing for %s\n", args->infile);
2245 if( in = fopen (args->infile, "rb") )
2246 while( ch = getc(in), ch != EOF )
2251 if( args->num == 1 )
2252 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2254 else if( args->num )
2255 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2257 if( bt_insertkey (bt, key, len, 0, line, *tod) )
2258 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2261 else if( len < 255 )
2263 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
2267 fprintf(stderr, "started deleting keys for %s\n", args->infile);
2268 if( in = fopen (args->infile, "rb") )
2269 while( ch = getc(in), ch != EOF )
2273 if( args->num == 1 )
2274 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2276 else if( args->num )
2277 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2279 if( bt_deletekey (bt, key, len, 0) )
2280 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2283 else if( len < 255 )
2285 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2289 fprintf(stderr, "started finding keys for %s\n", args->infile);
2290 if( in = fopen (args->infile, "rb") )
2291 while( ch = getc(in), ch != EOF )
2295 if( args->num == 1 )
2296 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2298 else if( args->num )
2299 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2301 if( bt_findkey (bt, key, len) )
2304 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2306 fprintf(stderr, "Unable to find key %.*s line %d\n", len, key, line);
2309 else if( len < 255 )
2311 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2315 fprintf(stderr, "started scanning\n");
2317 if( set->pool = bt_pinpool (bt, page_no) )
2318 set->page = bt_page (bt, set->pool, page_no);
2321 set->latch = bt_pinlatch (bt, page_no);
2322 bt_lockpage (BtLockRead, set->latch);
2323 next = bt_getid (set->page->right);
2324 cnt += set->page->act;
2326 for( slot = 0; slot++ < set->page->cnt; )
2327 if( next || slot < set->page->cnt )
2328 if( !slotptr(set->page, slot)->dead ) {
2329 ptr = keyptr(set->page, slot);
2330 fwrite (ptr->key, ptr->len, 1, stdout);
2331 fputc ('\n', stdout);
2334 bt_unlockpage (BtLockRead, set->latch);
2335 bt_unpinlatch (set->latch);
2336 bt_unpinpool (set->pool);
2337 } while( page_no = next );
2339 cnt--; // remove stopper key
2340 fprintf(stderr, " Total keys read %d\n", cnt);
2344 fprintf(stderr, "started counting\n");
2345 next = bt->mgr->latchmgr->nlatchpage + LATCH_page;
2346 page_no = LEAF_page;
2348 while( page_no < bt_getid(bt->mgr->latchmgr->alloc->right) ) {
2349 uid off = page_no << bt->mgr->page_bits;
2351 pread (bt->mgr->idx, bt->frame, bt->mgr->page_size, off);
2355 SetFilePointer (bt->mgr->idx, (long)off, (long*)(&off)+1, FILE_BEGIN);
2357 if( !ReadFile(bt->mgr->idx, bt->frame, bt->mgr->page_size, amt, NULL))
2358 return bt->err = BTERR_map;
2360 if( *amt < bt->mgr->page_size )
2361 return bt->err = BTERR_map;
2363 if( !bt->frame->free && !bt->frame->lvl )
2364 cnt += bt->frame->act;
2365 if( page_no > LEAF_page )
2370 cnt--; // remove stopper key
2371 fprintf(stderr, " Total keys read %d\n", cnt);
2383 typedef struct timeval timer;
2385 int main (int argc, char **argv)
2387 int idx, cnt, len, slot, err;
2388 int segsize, bits = 16;
2393 time_t start[1], stop[1];
2406 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]);
2407 fprintf (stderr, " where page_bits is the page size in bits\n");
2408 fprintf (stderr, " mapped_segments is the number of mmap segments in buffer pool\n");
2409 fprintf (stderr, " seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2410 fprintf (stderr, " line_numbers = 1 to append line numbers to keys\n");
2411 fprintf (stderr, " src_file1 thru src_filen are files of keys separated by newline\n");
2416 gettimeofday(&start, NULL);
2422 bits = atoi(argv[3]);
2425 poolsize = atoi(argv[4]);
2428 fprintf (stderr, "Warning: no mapped_pool\n");
2430 if( poolsize > 65535 )
2431 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2434 segsize = atoi(argv[5]);
2436 segsize = 4; // 16 pages per mmap segment
2439 num = atoi(argv[6]);
2443 threads = malloc (cnt * sizeof(pthread_t));
2445 threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2447 args = malloc (cnt * sizeof(ThreadArg));
2449 mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2452 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2458 for( idx = 0; idx < cnt; idx++ ) {
2459 args[idx].infile = argv[idx + 7];
2460 args[idx].type = argv[2][0];
2461 args[idx].mgr = mgr;
2462 args[idx].num = num;
2463 args[idx].idx = idx;
2465 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2466 fprintf(stderr, "Error creating thread %d\n", err);
2468 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2472 // wait for termination
2475 for( idx = 0; idx < cnt; idx++ )
2476 pthread_join (threads[idx], NULL);
2477 gettimeofday(&stop, NULL);
2478 real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2480 WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2482 for( idx = 0; idx < cnt; idx++ )
2483 CloseHandle(threads[idx]);
2486 real_time = 1000 * (*stop - *start);
2488 fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);