1 // btree version threads2i sched_yield version
4 // author: karl malbrain, malbrain@cal.berkeley.edu
7 This work, including the source code, documentation
8 and related data, is placed into the public domain.
10 The orginal author is Karl Malbrain.
12 THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY
13 OF ANY KIND, NOT EVEN THE IMPLIED WARRANTY OF
14 MERCHANTABILITY. THE AUTHOR OF THIS SOFTWARE,
15 ASSUMES _NO_ RESPONSIBILITY FOR ANY CONSEQUENCE
16 RESULTING FROM THE USE, MODIFICATION, OR
17 REDISTRIBUTION OF THIS SOFTWARE.
20 // Please see the project home page for documentation
21 // code.google.com/p/high-concurrency-btree
23 #define _FILE_OFFSET_BITS 64
24 #define _LARGEFILE64_SOURCE
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_latchtable 128 // number of latch manager slots
63 #define BT_ro 0x6f72 // ro
64 #define BT_rw 0x7772 // rw
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) ParentModification: Exclusive. Change the node's parent keys. Incompatible with another ParentModification.
88 // mode & definition for latch implementation
97 // exclusive is set for write access
98 // share is count of read accessors
99 // grant write lock when share == 0
102 volatile ushort mutex:1;
103 volatile ushort exclusive:1;
104 volatile ushort pending:1;
105 volatile ushort share:13;
108 // hash table entries
111 BtSpinLatch latch[1];
112 volatile ushort slot; // Latch table entry at head of chain
115 // latch manager table structure
118 BtSpinLatch readwr[1]; // read/write page lock
119 BtSpinLatch access[1]; // Access Intent/Page delete
120 BtSpinLatch parent[1]; // adoption of foster children
121 BtSpinLatch busy[1]; // slot is being moved between chains
122 volatile ushort next; // next entry in hash table chain
123 volatile ushort prev; // prev entry in hash table chain
124 volatile ushort pin; // number of outstanding locks
125 volatile ushort hash; // hash slot entry is under
126 volatile uid page_no; // latch set page number
129 // Define the length of the page and key pointers
133 // Page key slot definition.
135 // If BT_maxbits is 15 or less, you can save 4 bytes
136 // for each key stored by making the first two uints
137 // into ushorts. You can also save 4 bytes by removing
138 // the tod field from the key.
140 // Keys are marked dead, but remain on the page until
141 // it cleanup is called. The fence key (highest key) for
142 // the page is always present, even after cleanup.
145 uint off:BT_maxbits; // page offset for key start
146 uint dead:1; // set for deleted key
147 uint tod; // time-stamp for key
148 unsigned char id[BtId]; // id associated with key
151 // The key structure occupies space at the upper end of
152 // each page. It's a length byte followed by the value
157 unsigned char key[1];
160 // The first part of an index page.
161 // It is immediately followed
162 // by the BtSlot array of keys.
164 typedef struct Page {
165 uint cnt; // count of keys in page
166 uint act; // count of active keys
167 uint min; // next key offset
168 unsigned char bits; // page size in bits
169 unsigned char lvl:7; // level of page
170 unsigned char dirty:1; // page has deleted keys
171 unsigned char right[BtId]; // page number to right
174 // The memory mapping pool table buffer manager entry
177 unsigned long long int lru; // number of times accessed
178 uid basepage; // mapped base page number
179 char *map; // mapped memory pointer
180 ushort slot; // slot index in this array
181 ushort pin; // mapped page pin counter
182 void *hashprev; // previous pool entry for the same hash idx
183 void *hashnext; // next pool entry for the same hash idx
185 HANDLE hmap; // Windows memory mapping handle
189 // structure for latch manager on ALLOC_page
192 struct Page alloc[2]; // next & free page_nos in right ptr
193 BtSpinLatch lock[1]; // allocation area lite latch
194 ushort latchdeployed; // highest number of latch entries deployed
195 ushort nlatchpage; // number of latch pages at BT_latch
196 ushort latchtotal; // number of page latch entries
197 ushort latchhash; // number of latch hash table slots
198 ushort latchvictim; // next latch entry to examine
199 BtHashEntry table[0]; // the hash table
202 // The object structure for Btree access
205 uint page_size; // page size
206 uint page_bits; // page size in bits
207 uint seg_bits; // seg size in pages in bits
208 uint mode; // read-write mode
214 ushort poolcnt; // highest page pool node in use
215 ushort poolmax; // highest page pool node allocated
216 ushort poolmask; // total number of pages in mmap segment - 1
217 ushort hashsize; // size of Hash Table for pool entries
218 volatile uint evicted; // last evicted hash table slot
219 ushort *hash; // pool index for hash entries
220 BtSpinLatch *latch; // latches for hash table slots
221 BtLatchMgr *latchmgr; // mapped latch page from allocation page
222 BtLatchSet *latchsets; // mapped latch set from latch pages
223 BtPool *pool; // memory pool page segments
225 HANDLE halloc; // allocation and latch table handle
230 BtMgr *mgr; // buffer manager for thread
231 BtPage cursor; // cached frame for start/next (never mapped)
232 BtPage frame; // spare frame for the page split (never mapped)
233 BtPage zero; // page frame for zeroes at end of file
234 BtPage page; // current page
235 uid page_no; // current page number
236 uid cursor_page; // current cursor page number
237 BtLatchSet *set; // current page latch set
238 BtPool *pool; // current page pool
239 unsigned char *mem; // frame, cursor, page memory buffer
240 int parent; // last loadpage was from a parent level
241 int found; // last delete or insert was found
242 int err; // last error
256 extern void bt_close (BtDb *bt);
257 extern BtDb *bt_open (BtMgr *mgr);
258 extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod, uint lvl);
259 extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len);
260 extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
261 extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
262 extern uint bt_nextkey (BtDb *bt, uint slot);
264 // internal functions
265 BTERR bt_splitpage (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no);
266 uint bt_cleanpage(BtDb *bt, BtPage page, uint amt, uint slot);
267 BTERR bt_mergeleft (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no, uint lvl);
270 extern BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolsize, uint segsize, uint hashsize);
271 void bt_mgrclose (BtMgr *mgr);
273 // Helper functions to return slot values
275 extern BtKey bt_key (BtDb *bt, uint slot);
276 extern uid bt_uid (BtDb *bt, uint slot);
277 extern uint bt_tod (BtDb *bt, uint slot);
279 // BTree page number constants
280 #define ALLOC_page 0 // allocation & lock manager hash table
281 #define ROOT_page 1 // root of the btree
282 #define LEAF_page 2 // first page of leaves
283 #define LATCH_page 3 // pages for lock manager
285 // Number of levels to create in a new BTree
289 // The page is allocated from low and hi ends.
290 // The key offsets and row-id's are allocated
291 // from the bottom, while the text of the key
292 // is allocated from the top. When the two
293 // areas meet, the page is split into two.
295 // A key consists of a length byte, two bytes of
296 // index number (0 - 65534), and up to 253 bytes
297 // of key value. Duplicate keys are discarded.
298 // Associated with each key is a 48 bit row-id.
300 // The b-tree root is always located at page 1.
301 // The first leaf page of level zero is always
302 // located on page 2.
304 // The b-tree pages are linked with next
305 // pointers to facilitate enumerators,
306 // and provide for concurrency.
308 // When to root page fills, it is split in two and
309 // the tree height is raised by a new root at page
310 // one with two keys.
312 // Deleted keys are marked with a dead bit until
313 // page cleanup The fence key for a node is always
314 // present, even after deletion and cleanup.
316 // Groups of pages called segments from the btree are optionally
317 // cached with a memory mapped pool. A hash table is used to keep
318 // track of the cached segments. This behaviour is controlled
319 // by the cache block size parameter to bt_open.
321 // To achieve maximum concurrency one page is locked at a time
322 // as the tree is traversed to find leaf key in question. The right
323 // page numbers are used in cases where the page is being split,
326 // Page 0 is dedicated to lock for new page extensions,
327 // and chains empty pages together for reuse.
329 // The ParentModification lock on a node is obtained to prevent resplitting
330 // or deleting a node before its fence is posted into its upper level.
332 // Empty pages are chained together through the ALLOC page and reused.
334 // Access macros to address slot and key values from the page
336 #define slotptr(page, slot) (((BtSlot *)(page+1)) + (slot-1))
337 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
339 void bt_putid(unsigned char *dest, uid id)
344 dest[i] = (unsigned char)id, id >>= 8;
347 uid bt_getid(unsigned char *src)
352 for( i = 0; i < BtId; i++ )
353 id <<= 8, id |= *src++;
360 // wait until write lock mode is clear
361 // and add 1 to the share count
363 void bt_spinreadlock(BtSpinLatch *latch)
368 // obtain latch mutex
370 if( __sync_fetch_and_or((ushort *)latch, Mutex) & Mutex )
373 if( prev = _InterlockedOr16((ushort *)latch, Mutex) & Mutex )
376 // see if exclusive request is granted or pending
378 if( prev = !(latch->exclusive | latch->pending) )
380 __sync_fetch_and_add((ushort *)latch, Share);
382 _InterlockedExchangeAdd16 ((ushort *)latch, Share);
386 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
388 _InterlockedAnd16((ushort *)latch, ~Mutex);
394 } while( sched_yield(), 1 );
396 } while( SwitchToThread(), 1 );
400 // wait for other read and write latches to relinquish
402 void bt_spinwritelock(BtSpinLatch *latch)
406 if( __sync_fetch_and_or((ushort *)latch, Mutex | Pending) & Mutex )
409 if( _InterlockedOr16((ushort *)latch, Mutex | Pending) & Mutex )
412 if( !(latch->share | latch->exclusive) ) {
414 __sync_fetch_and_or((ushort *)latch, Write);
415 __sync_fetch_and_and ((ushort *)latch, ~(Mutex | Pending));
417 _InterlockedOr16((ushort *)latch, Write);
418 _InterlockedAnd16((ushort *)latch, ~(Mutex | Pending));
424 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
426 _InterlockedAnd16((ushort *)latch, ~Mutex);
430 } while( sched_yield(), 1 );
432 } while( SwitchToThread(), 1 );
436 // try to obtain write lock
438 // return 1 if obtained,
441 int bt_spinwritetry(BtSpinLatch *latch)
446 if( prev = __sync_fetch_and_or((ushort *)latch, Mutex), prev & Mutex )
449 if( prev = _InterlockedOr16((ushort *)latch, Mutex), prev & Mutex )
452 // take write access if all bits are clear
456 __sync_fetch_and_or ((ushort *)latch, Write);
458 _InterlockedOr16((ushort *)latch, Write);
462 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
464 _InterlockedAnd16((ushort *)latch, ~Mutex);
471 void bt_spinreleasewrite(BtSpinLatch *latch)
474 __sync_fetch_and_and ((ushort *)latch, ~Write);
476 _InterlockedAnd16((ushort *)latch, ~Write);
480 // decrement reader count
482 void bt_spinreleaseread(BtSpinLatch *latch)
485 __sync_fetch_and_add((ushort *)latch, -Share);
487 _InterlockedExchangeAdd16 ((ushort *)latch, -Share);
491 // link latch table entry into latch hash table
493 void bt_latchlink (BtDb *bt, ushort hashidx, ushort victim, uid page_no)
495 BtLatchSet *set = bt->mgr->latchsets + victim;
497 if( set->next = bt->mgr->latchmgr->table[hashidx].slot )
498 bt->mgr->latchsets[set->next].prev = victim;
500 bt->mgr->latchmgr->table[hashidx].slot = victim;
501 set->page_no = page_no;
508 void bt_unpinlatch (BtLatchSet *set)
511 __sync_fetch_and_add(&set->pin, -1);
513 _InterlockedDecrement16 (&set->pin);
517 // find existing latchset or inspire new one
518 // return with latchset pinned
520 BtLatchSet *bt_pinlatch (BtDb *bt, uid page_no)
522 ushort hashidx = page_no % bt->mgr->latchmgr->latchhash;
523 ushort slot, avail = 0, victim, idx;
526 // obtain read lock on hash table entry
528 bt_spinreadlock(bt->mgr->latchmgr->table[hashidx].latch);
530 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
532 set = bt->mgr->latchsets + slot;
533 if( page_no == set->page_no )
535 } while( slot = set->next );
539 __sync_fetch_and_add(&set->pin, 1);
541 _InterlockedIncrement16 (&set->pin);
545 bt_spinreleaseread (bt->mgr->latchmgr->table[hashidx].latch);
550 // try again, this time with write lock
552 bt_spinwritelock(bt->mgr->latchmgr->table[hashidx].latch);
554 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
556 set = bt->mgr->latchsets + slot;
557 if( page_no == set->page_no )
559 if( !set->pin && !avail )
561 } while( slot = set->next );
563 // found our entry, or take over an unpinned one
565 if( slot || (slot = avail) ) {
566 set = bt->mgr->latchsets + slot;
568 __sync_fetch_and_add(&set->pin, 1);
570 _InterlockedIncrement16 (&set->pin);
572 set->page_no = page_no;
573 bt_spinreleasewrite(bt->mgr->latchmgr->table[hashidx].latch);
577 // see if there are any unused entries
579 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, 1) + 1;
581 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchdeployed);
584 if( victim < bt->mgr->latchmgr->latchtotal ) {
585 set = bt->mgr->latchsets + victim;
587 __sync_fetch_and_add(&set->pin, 1);
589 _InterlockedIncrement16 (&set->pin);
591 bt_latchlink (bt, hashidx, victim, page_no);
592 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
597 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, -1);
599 victim = _InterlockedDecrement16 (&bt->mgr->latchmgr->latchdeployed);
601 // find and reuse previous lock entry
605 victim = __sync_fetch_and_add(&bt->mgr->latchmgr->latchvictim, 1);
607 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchvictim) - 1;
609 // we don't use slot zero
611 if( victim %= bt->mgr->latchmgr->latchtotal )
612 set = bt->mgr->latchsets + victim;
616 // take control of our slot
617 // from other threads
619 if( set->pin || !bt_spinwritetry (set->busy) )
624 // try to get write lock on hash chain
625 // skip entry if not obtained
626 // or has outstanding locks
628 if( !bt_spinwritetry (bt->mgr->latchmgr->table[idx].latch) ) {
629 bt_spinreleasewrite (set->busy);
634 bt_spinreleasewrite (set->busy);
635 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
639 // unlink our available victim from its hash chain
642 bt->mgr->latchsets[set->prev].next = set->next;
644 bt->mgr->latchmgr->table[idx].slot = set->next;
647 bt->mgr->latchsets[set->next].prev = set->prev;
649 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
651 __sync_fetch_and_add(&set->pin, 1);
653 _InterlockedIncrement16 (&set->pin);
655 bt_latchlink (bt, hashidx, victim, page_no);
656 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
657 bt_spinreleasewrite (set->busy);
662 void bt_mgrclose (BtMgr *mgr)
667 // release mapped pages
668 // note that slot zero is never used
670 for( slot = 1; slot < mgr->poolmax; slot++ ) {
671 pool = mgr->pool + slot;
674 munmap (pool->map, (mgr->poolmask+1) << mgr->page_bits);
677 FlushViewOfFile(pool->map, 0);
678 UnmapViewOfFile(pool->map);
679 CloseHandle(pool->hmap);
685 munmap (mgr->latchsets, mgr->latchmgr->nlatchpage * mgr->page_size);
686 munmap (mgr->latchmgr, mgr->page_size);
688 FlushViewOfFile(mgr->latchmgr, 0);
689 UnmapViewOfFile(mgr->latchmgr);
690 CloseHandle(mgr->halloc);
699 FlushFileBuffers(mgr->idx);
700 CloseHandle(mgr->idx);
701 GlobalFree (mgr->pool);
702 GlobalFree (mgr->hash);
703 GlobalFree (mgr->latch);
708 // close and release memory
710 void bt_close (BtDb *bt)
717 VirtualFree (bt->mem, 0, MEM_RELEASE);
722 // open/create new btree buffer manager
724 // call with file_name, BT_openmode, bits in page size (e.g. 16),
725 // size of mapped page pool (e.g. 8192)
727 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
729 uint lvl, attr, cacheblk, last, slot, idx;
730 uint nlatchpage, latchhash;
731 BtLatchMgr *latchmgr;
739 SYSTEM_INFO sysinfo[1];
742 // determine sanity of page size and buffer pool
744 if( bits > BT_maxbits )
746 else if( bits < BT_minbits )
750 return NULL; // must have buffer pool
753 mgr = calloc (1, sizeof(BtMgr));
755 mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
758 return free(mgr), NULL;
760 cacheblk = 4096; // minimum mmap segment size for unix
763 mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
764 attr = FILE_ATTRIBUTE_NORMAL;
765 mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
767 if( mgr->idx == INVALID_HANDLE_VALUE )
768 return GlobalFree(mgr), NULL;
770 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
771 GetSystemInfo(sysinfo);
772 cacheblk = sysinfo->dwAllocationGranularity;
776 latchmgr = malloc (BT_maxpage);
779 // read minimum page size to get root info
781 if( size = lseek (mgr->idx, 0L, 2) ) {
782 if( pread(mgr->idx, latchmgr, BT_minpage, 0) == BT_minpage )
783 bits = latchmgr->alloc->bits;
785 return free(mgr), free(latchmgr), NULL;
786 } else if( mode == BT_ro )
787 return free(latchmgr), bt_mgrclose (mgr), NULL;
789 latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
790 size = GetFileSize(mgr->idx, amt);
793 if( !ReadFile(mgr->idx, (char *)latchmgr, BT_minpage, amt, NULL) )
794 return bt_mgrclose (mgr), NULL;
795 bits = latchmgr->alloc->bits;
796 } else if( mode == BT_ro )
797 return bt_mgrclose (mgr), NULL;
800 mgr->page_size = 1 << bits;
801 mgr->page_bits = bits;
803 mgr->poolmax = poolmax;
806 if( cacheblk < mgr->page_size )
807 cacheblk = mgr->page_size;
809 // mask for partial memmaps
811 mgr->poolmask = (cacheblk >> bits) - 1;
813 // see if requested size of pages per memmap is greater
815 if( (1 << segsize) > mgr->poolmask )
816 mgr->poolmask = (1 << segsize) - 1;
820 while( (1 << mgr->seg_bits) <= mgr->poolmask )
823 mgr->hashsize = hashsize;
826 mgr->pool = calloc (poolmax, sizeof(BtPool));
827 mgr->hash = calloc (hashsize, sizeof(ushort));
828 mgr->latch = calloc (hashsize, sizeof(BtSpinLatch));
830 mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * sizeof(BtPool));
831 mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
832 mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtSpinLatch));
838 // initialize an empty b-tree with latch page, root page, page of leaves
839 // and page(s) of latches
841 memset (latchmgr, 0, 1 << bits);
842 nlatchpage = BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1;
843 bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
844 latchmgr->alloc->bits = mgr->page_bits;
846 latchmgr->nlatchpage = nlatchpage;
847 latchmgr->latchtotal = nlatchpage * (mgr->page_size / sizeof(BtLatchSet));
849 // initialize latch manager
851 latchhash = (mgr->page_size - sizeof(BtLatchMgr)) / sizeof(BtHashEntry);
853 // size of hash table = total number of latchsets
855 if( latchhash > latchmgr->latchtotal )
856 latchhash = latchmgr->latchtotal;
858 latchmgr->latchhash = latchhash;
861 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
862 return bt_mgrclose (mgr), NULL;
864 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
865 return bt_mgrclose (mgr), NULL;
867 if( *amt < mgr->page_size )
868 return bt_mgrclose (mgr), NULL;
871 memset (latchmgr, 0, 1 << bits);
872 latchmgr->alloc->bits = mgr->page_bits;
874 for( lvl=MIN_lvl; lvl--; ) {
875 slotptr(latchmgr->alloc, 1)->off = mgr->page_size - 3;
876 bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
877 key = keyptr(latchmgr->alloc, 1);
878 key->len = 2; // create stopper key
881 latchmgr->alloc->min = mgr->page_size - 3;
882 latchmgr->alloc->lvl = lvl;
883 latchmgr->alloc->cnt = 1;
884 latchmgr->alloc->act = 1;
886 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
887 return bt_mgrclose (mgr), NULL;
889 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
890 return bt_mgrclose (mgr), NULL;
892 if( *amt < mgr->page_size )
893 return bt_mgrclose (mgr), NULL;
897 // clear out latch manager locks
898 // and rest of pages to round out segment
900 memset(latchmgr, 0, mgr->page_size);
903 while( last <= ((MIN_lvl + 1 + nlatchpage) | mgr->poolmask) ) {
905 pwrite(mgr->idx, latchmgr, mgr->page_size, last << mgr->page_bits);
907 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
908 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
909 return bt_mgrclose (mgr), NULL;
910 if( *amt < mgr->page_size )
911 return bt_mgrclose (mgr), NULL;
918 flag = PROT_READ | PROT_WRITE;
919 mgr->latchmgr = mmap (0, mgr->page_size, flag, MAP_SHARED, mgr->idx, ALLOC_page * mgr->page_size);
920 if( mgr->latchmgr == MAP_FAILED )
921 return bt_mgrclose (mgr), NULL;
922 mgr->latchsets = (BtLatchSet *)mmap (0, mgr->latchmgr->nlatchpage * mgr->page_size, flag, MAP_SHARED, mgr->idx, LATCH_page * mgr->page_size);
923 if( mgr->latchsets == MAP_FAILED )
924 return bt_mgrclose (mgr), NULL;
926 flag = PAGE_READWRITE;
927 mgr->halloc = CreateFileMapping(mgr->idx, NULL, flag, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size, NULL);
929 return bt_mgrclose (mgr), NULL;
931 flag = FILE_MAP_WRITE;
932 mgr->latchmgr = MapViewOfFile(mgr->halloc, flag, 0, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size);
934 return GetLastError(), bt_mgrclose (mgr), NULL;
936 mgr->latchsets = (void *)((char *)mgr->latchmgr + LATCH_page * mgr->page_size);
942 VirtualFree (latchmgr, 0, MEM_RELEASE);
947 // open BTree access method
948 // based on buffer manager
950 BtDb *bt_open (BtMgr *mgr)
952 BtDb *bt = malloc (sizeof(*bt));
954 memset (bt, 0, sizeof(*bt));
957 bt->mem = malloc (3 *mgr->page_size);
959 bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
961 bt->frame = (BtPage)bt->mem;
962 bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
963 bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
965 memset (bt->zero, 0, mgr->page_size);
969 // compare two keys, returning > 0, = 0, or < 0
970 // as the comparison value
972 int keycmp (BtKey key1, unsigned char *key2, uint len2)
974 uint len1 = key1->len;
977 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
990 // find segment in pool
991 // must be called with hashslot idx locked
992 // return NULL if not there
993 // otherwise return node
995 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
1000 // compute start of hash chain in pool
1002 if( slot = bt->mgr->hash[idx] )
1003 pool = bt->mgr->pool + slot;
1007 page_no &= ~bt->mgr->poolmask;
1009 while( pool->basepage != page_no )
1010 if( pool = pool->hashnext )
1018 // add segment to hash table
1020 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
1025 pool->hashprev = pool->hashnext = NULL;
1026 pool->basepage = page_no & ~bt->mgr->poolmask;
1029 if( slot = bt->mgr->hash[idx] ) {
1030 node = bt->mgr->pool + slot;
1031 pool->hashnext = node;
1032 node->hashprev = pool;
1035 bt->mgr->hash[idx] = pool->slot;
1038 // find best segment to evict from buffer pool
1040 BtPool *bt_findlru (BtDb *bt, uint hashslot)
1042 unsigned long long int target = ~0LL;
1043 BtPool *pool = NULL, *node;
1048 node = bt->mgr->pool + hashslot;
1050 // scan pool entries under hash table slot
1055 if( node->lru > target )
1059 } while( node = node->hashnext );
1064 // map new buffer pool segment to virtual memory
1066 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
1068 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
1069 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
1073 flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
1074 pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED, bt->mgr->idx, off);
1075 if( pool->map == MAP_FAILED )
1076 return bt->err = BTERR_map;
1079 flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
1080 pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
1082 return bt->err = BTERR_map;
1084 flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
1085 pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1087 return bt->err = BTERR_map;
1092 // calculate page within pool
1094 BtPage bt_page (BtDb *bt, BtPool *pool, uid page_no)
1096 uint subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1099 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1105 void bt_unpinpool (BtPool *pool)
1108 __sync_fetch_and_add(&pool->pin, -1);
1110 _InterlockedDecrement16 (&pool->pin);
1114 // find or place requested page in segment-pool
1115 // return pool table entry, incrementing pin
1117 BtPool *bt_pinpool(BtDb *bt, uid page_no)
1119 BtPool *pool, *node, *next;
1120 uint slot, idx, victim;
1122 // lock hash table chain
1124 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1125 bt_spinreadlock (&bt->mgr->latch[idx]);
1127 // look up in hash table
1129 if( pool = bt_findpool(bt, page_no, idx) ) {
1131 __sync_fetch_and_add(&pool->pin, 1);
1133 _InterlockedIncrement16 (&pool->pin);
1135 bt_spinreleaseread (&bt->mgr->latch[idx]);
1140 // upgrade to write lock
1142 bt_spinreleaseread (&bt->mgr->latch[idx]);
1143 bt_spinwritelock (&bt->mgr->latch[idx]);
1145 // try to find page in pool with write lock
1147 if( pool = bt_findpool(bt, page_no, idx) ) {
1149 __sync_fetch_and_add(&pool->pin, 1);
1151 _InterlockedIncrement16 (&pool->pin);
1153 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1158 // allocate a new pool node
1159 // and add to hash table
1162 slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
1164 slot = _InterlockedIncrement16 (&bt->mgr->poolcnt) - 1;
1167 if( ++slot < bt->mgr->poolmax ) {
1168 pool = bt->mgr->pool + slot;
1171 if( bt_mapsegment(bt, pool, page_no) )
1174 bt_linkhash(bt, pool, page_no, idx);
1176 __sync_fetch_and_add(&pool->pin, 1);
1178 _InterlockedIncrement16 (&pool->pin);
1180 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1184 // pool table is full
1185 // find best pool entry to evict
1188 __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
1190 _InterlockedDecrement16 (&bt->mgr->poolcnt);
1195 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
1197 victim = _InterlockedIncrement (&bt->mgr->evicted) - 1;
1199 victim %= bt->mgr->hashsize;
1201 // try to get write lock
1202 // skip entry if not obtained
1204 if( !bt_spinwritetry (&bt->mgr->latch[victim]) )
1207 // if pool entry is empty
1208 // or any pages are pinned
1211 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
1212 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1216 // unlink victim pool node from hash table
1218 if( node = pool->hashprev )
1219 node->hashnext = pool->hashnext;
1220 else if( node = pool->hashnext )
1221 bt->mgr->hash[victim] = node->slot;
1223 bt->mgr->hash[victim] = 0;
1225 if( node = pool->hashnext )
1226 node->hashprev = pool->hashprev;
1228 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1230 // remove old file mapping
1232 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1234 FlushViewOfFile(pool->map, 0);
1235 UnmapViewOfFile(pool->map);
1236 CloseHandle(pool->hmap);
1240 // create new pool mapping
1241 // and link into hash table
1243 if( bt_mapsegment(bt, pool, page_no) )
1246 bt_linkhash(bt, pool, page_no, idx);
1248 __sync_fetch_and_add(&pool->pin, 1);
1250 _InterlockedIncrement16 (&pool->pin);
1252 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1257 // place write, read, or parent lock on requested page_no.
1259 void bt_lockpage(BtLock mode, BtLatchSet *set)
1263 bt_spinreadlock (set->readwr);
1266 bt_spinwritelock (set->readwr);
1269 bt_spinreadlock (set->access);
1272 bt_spinwritelock (set->access);
1275 bt_spinwritelock (set->parent);
1280 // remove write, read, or parent lock on requested page
1282 void bt_unlockpage(BtLock mode, BtLatchSet *set)
1286 bt_spinreleaseread (set->readwr);
1289 bt_spinreleasewrite (set->readwr);
1292 bt_spinreleaseread (set->access);
1295 bt_spinreleasewrite (set->access);
1298 bt_spinreleasewrite (set->parent);
1303 // allocate a new page and write page into it
1305 uid bt_newpage(BtDb *bt, BtPage page)
1313 // lock allocation page
1315 bt_spinwritelock(bt->mgr->latchmgr->lock);
1317 // use empty chain first
1318 // else allocate empty page
1320 if( new_page = bt_getid(bt->mgr->latchmgr->alloc[1].right) ) {
1321 if( pool = bt_pinpool (bt, new_page) )
1322 pmap = bt_page (bt, pool, new_page);
1325 bt_putid(bt->mgr->latchmgr->alloc[1].right, bt_getid(pmap->right));
1326 bt_unpinpool (pool);
1329 new_page = bt_getid(bt->mgr->latchmgr->alloc->right);
1330 bt_putid(bt->mgr->latchmgr->alloc->right, new_page+1);
1334 if ( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1335 return bt->err = BTERR_wrt, 0;
1337 // if writing first page of pool block, zero last page in the block
1339 if ( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1341 // use zero buffer to write zeros
1342 memset(bt->zero, 0, bt->mgr->page_size);
1343 if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1344 return bt->err = BTERR_wrt, 0;
1347 // bring new page into pool and copy page.
1348 // this will extend the file into the new pages.
1350 if( pool = bt_pinpool (bt, new_page) )
1351 pmap = bt_page (bt, pool, new_page);
1355 memcpy(pmap, page, bt->mgr->page_size);
1356 bt_unpinpool (pool);
1358 // unlock allocation latch and return new page no
1360 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1364 // find slot in page for given key at a given level
1366 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1368 uint diff, higher = bt->page->cnt, low = 1, slot;
1372 // make stopper key an infinite fence value
1373 // by setting the good flag
1375 if( bt_getid (bt->page->right) )
1380 // low is the next candidate.
1381 // loop ends when they meet
1383 // if good, higher is already
1384 // tested as .ge. the given key.
1386 while( diff = higher - low ) {
1387 slot = low + ( diff >> 1 );
1388 if( keycmp (keyptr(bt->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, unsigned char *key, uint len, uint lvl, uint lock)
1404 uid page_no = ROOT_page, prevpage = 0;
1405 BtLatchSet *set, *prevset;
1406 uint drill = 0xff, slot;
1407 uint mode, prevmode;
1411 // start at root of btree and drill down
1416 // determine lock mode of drill level
1417 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1419 bt->set = bt_pinlatch (bt, page_no);
1420 bt->page_no = page_no;
1422 // pin page contents
1424 if( bt->pool = bt_pinpool (bt, page_no) )
1425 bt->page = bt_page (bt, bt->pool, page_no);
1429 // obtain access lock using lock chaining with Access mode
1431 if( page_no > ROOT_page )
1432 bt_lockpage(BtLockAccess, bt->set);
1434 // release & unpin parent page
1437 bt_unlockpage(prevmode, prevset);
1438 bt_unpinlatch (prevset);
1439 bt_unpinpool (prevpool);
1443 // obtain read lock using lock chaining
1445 bt_lockpage(mode, bt->set);
1447 if( page_no > ROOT_page )
1448 bt_unlockpage(BtLockAccess, bt->set);
1450 // re-read and re-lock root after determining actual level of root
1452 if( bt->page->lvl != drill) {
1453 if ( bt->page_no != ROOT_page )
1454 return bt->err = BTERR_struct, 0;
1456 drill = bt->page->lvl;
1458 if( lock == BtLockWrite && drill == lvl ) {
1459 bt_unlockpage(mode, bt->set);
1460 bt_unpinlatch (bt->set);
1461 bt_unpinpool (bt->pool);
1466 // find key on page at this level
1467 // and descend to requested level
1469 if( slot = bt_findslot (bt, key, len) ) {
1471 return bt->parent = parent, slot;
1473 while( slotptr(bt->page, slot)->dead )
1474 if( slot++ < bt->page->cnt )
1477 page_no = bt_getid(bt->page->right);
1482 page_no = bt_getid(slotptr(bt->page, slot)->id);
1487 // or slide right into next page
1490 page_no = bt_getid(bt->page->right);
1494 // continue down / right using overlapping locks
1495 // to protect pages being split.
1498 prevpage = bt->page_no;
1499 prevpool = bt->pool;
1504 // return error on end of right chain
1506 bt->err = BTERR_struct;
1507 return 0; // return error
1510 // remove empty page from the B-tree
1511 // by pulling our right node left over ourselves
1513 // call with bt->page, etc, set to page's locked parent
1514 // returns with page locked.
1516 BTERR bt_mergeright (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no, uint lvl, uint slot)
1518 BtLatchSet *rset, *pset, *rpset;
1519 BtPool *rpool, *ppool, *rppool;
1520 BtPage rpage, ppage, rppage;
1521 uid right, parent, rparent;
1525 // cache node's parent page
1527 parent = bt->page_no;
1532 // lock and map our right page
1533 // it cannot be NULL because of the stopper
1534 // in the last right page
1536 bt_lockpage (BtLockWrite, set);
1538 // if we aren't dead yet
1543 if( right = bt_getid (page->right) )
1544 if( rpool = bt_pinpool (bt, right) )
1545 rpage = bt_page (bt, rpool, right);
1549 return bt->err = BTERR_struct;
1551 rset = bt_pinlatch (bt, right);
1553 // find our right neighbor
1555 if( ppage->act > 1 ) {
1556 for( idx = slot; idx++ < ppage->cnt; )
1557 if( !slotptr(ppage, idx)->dead )
1560 if( idx > ppage->cnt )
1561 return bt->err = BTERR_struct;
1563 // redirect right neighbor in parent to left node
1565 bt_putid(slotptr(ppage,idx)->id, page_no);
1568 // if parent has only our deleted page, e.g. no right neighbor
1569 // prepare to merge parent itself
1571 if( ppage->act == 1 ) {
1572 if( rparent = bt_getid (ppage->right) )
1573 if( rppool = bt_pinpool (bt, rparent) )
1574 rppage = bt_page (bt, rppool, rparent);
1578 return bt->err = BTERR_struct;
1580 rpset = bt_pinlatch (bt, rparent);
1581 bt_lockpage (BtLockWrite, rpset);
1583 // find our right neighbor on right parent page
1585 for( idx = 0; idx++ < rppage->cnt; )
1586 if( !slotptr(rppage, idx)->dead ) {
1587 bt_putid (slotptr(rppage, idx)->id, page_no);
1591 if( idx > rppage->cnt )
1592 return bt->err = BTERR_struct;
1595 // now that there are no more pointers to our right node
1596 // we can wait for delete lock on it
1598 bt_lockpage(BtLockDelete, rset);
1599 bt_lockpage(BtLockWrite, rset);
1601 // pull contents of right page into our empty page
1603 memcpy (page, rpage, bt->mgr->page_size);
1605 // ready to release right parent lock
1606 // now that we have a new page in place
1608 if( ppage->act == 1 ) {
1609 bt_unlockpage (BtLockWrite, rpset);
1610 bt_unpinlatch (rpset);
1611 bt_unpinpool (rppool);
1614 // add killed right block to free chain
1617 bt_spinwritelock(bt->mgr->latchmgr->lock);
1619 // store free chain in allocation page second right
1621 bt_putid(rpage->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1622 bt_putid(bt->mgr->latchmgr->alloc[1].right, right);
1624 // unlock latch mgr and right page
1626 bt_unlockpage(BtLockDelete, rset);
1627 bt_unlockpage(BtLockWrite, rset);
1628 bt_unpinlatch (rset);
1629 bt_unpinpool (rpool);
1631 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1633 // delete our obsolete fence key from our parent
1635 slotptr(ppage, slot)->dead = 1;
1638 // if our parent now empty
1639 // remove it from the tree
1641 if( ppage->act-- == 1 )
1642 if( bt_mergeleft (bt, ppage, ppool, pset, parent, lvl+1) )
1646 bt_unlockpage (BtLockWrite, pset);
1647 bt_unpinlatch (pset);
1648 bt_unpinpool (ppool);
1654 // remove empty page from the B-tree
1655 // try merging left first. If no left
1656 // sibling, then merge right.
1658 // call with page loaded and locked,
1659 // return with page locked.
1661 BTERR bt_mergeleft (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no, uint lvl)
1663 unsigned char fencekey[256], postkey[256];
1664 uint slot, idx, postfence = 0;
1665 BtLatchSet *lset, *pset;
1666 BtPool *lpool, *ppool;
1667 BtPage lpage, ppage;
1671 ptr = keyptr(page, page->cnt);
1672 memcpy(fencekey, ptr, ptr->len + 1);
1673 bt_unlockpage (BtLockWrite, set);
1675 // load and lock our parent
1678 if( !(slot = bt_loadpage (bt, fencekey+1, *fencekey, lvl+1, BtLockWrite)) )
1681 parent = bt->page_no;
1686 // wait until we are posted in our parent
1689 bt_unlockpage (BtLockWrite, pset);
1690 bt_unpinlatch (pset);
1691 bt_unpinpool (ppool);
1700 // find our left neighbor in our parent page
1702 for( idx = slot; --idx; )
1703 if( !slotptr(ppage, idx)->dead )
1706 // if no left neighbor, do right merge
1709 return bt_mergeright (bt, page, pool, set, page_no, lvl, slot);
1711 // lock and map our left neighbor's page
1713 left = bt_getid (slotptr(ppage, idx)->id);
1715 if( lpool = bt_pinpool (bt, left) )
1716 lpage = bt_page (bt, lpool, left);
1720 lset = bt_pinlatch (bt, left);
1721 bt_lockpage(BtLockWrite, lset);
1723 // wait until sibling is in our parent
1725 if( bt_getid (lpage->right) != page_no ) {
1726 bt_unlockpage (BtLockWrite, pset);
1727 bt_unpinlatch (pset);
1728 bt_unpinpool (ppool);
1729 bt_unlockpage (BtLockWrite, lset);
1730 bt_unpinlatch (lset);
1731 bt_unpinpool (lpool);
1740 // since our page will have no more pointers to it,
1741 // obtain Delete lock and wait for write locks to clear
1743 bt_lockpage(BtLockDelete, set);
1744 bt_lockpage(BtLockWrite, set);
1746 // if we aren't dead yet,
1747 // get ready for exit
1750 bt_unlockpage(BtLockDelete, set);
1751 bt_unlockpage(BtLockWrite, lset);
1752 bt_unpinlatch (lset);
1753 bt_unpinpool (lpool);
1757 // are we are the fence key for our parent?
1758 // if so, grab our old fence key
1760 if( postfence = slot == ppage->cnt ) {
1761 ptr = keyptr (ppage, ppage->cnt);
1762 memcpy(fencekey, ptr, ptr->len + 1);
1763 memset(slotptr(ppage, ppage->cnt), 0, sizeof(BtSlot));
1765 // clear out other dead slots
1767 while( --ppage->cnt )
1768 if( slotptr(ppage, ppage->cnt)->dead )
1769 memset(slotptr(ppage, ppage->cnt), 0, sizeof(BtSlot));
1773 ptr = keyptr (ppage, ppage->cnt);
1774 memcpy(postkey, ptr, ptr->len + 1);
1776 slotptr(ppage,slot)->dead = 1;
1781 // push our right neighbor pointer to our left
1783 memcpy (lpage->right, page->right, BtId);
1785 // add ourselves to free chain
1788 bt_spinwritelock(bt->mgr->latchmgr->lock);
1790 // store free chain in allocation page second right
1791 bt_putid(page->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1792 bt_putid(bt->mgr->latchmgr->alloc[1].right, page_no);
1794 // unlock latch mgr and pages
1796 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1797 bt_unlockpage(BtLockWrite, lset);
1798 bt_unpinlatch (lset);
1799 bt_unpinpool (lpool);
1801 // release our node's delete lock
1803 bt_unlockpage(BtLockDelete, set);
1806 bt_unlockpage (BtLockWrite, pset);
1807 bt_unpinpool (ppool);
1809 // do we need to post parent's fence key in its parent?
1811 if( !postfence || parent == ROOT_page ) {
1812 bt_unpinlatch (pset);
1817 // interlock parent fence post
1819 bt_lockpage (BtLockParent, pset);
1821 // load parent's parent page
1823 if( !(slot = bt_loadpage (bt, fencekey+1, *fencekey, lvl+2, BtLockWrite)) )
1826 if( !(slot = bt_cleanpage (bt, bt->page, *fencekey, slot)) )
1827 if( bt_splitpage (bt, bt->page, bt->pool, bt->set, bt->page_no) )
1834 page->min -= *postkey + 1;
1835 ((unsigned char *)page)[page->min] = *postkey;
1836 memcpy ((unsigned char *)page + page->min +1, postkey + 1, *postkey );
1837 slotptr(page, slot)->off = page->min;
1839 bt_unlockpage (BtLockParent, pset);
1840 bt_unpinlatch (pset);
1842 bt_unlockpage (BtLockWrite, bt->set);
1843 bt_unpinlatch (bt->set);
1844 bt_unpinpool (bt->pool);
1850 // find and delete key on page by marking delete flag bit
1851 // if page becomes empty, delete it from the btree
1853 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len)
1862 if( !(slot = bt_loadpage (bt, key, len, 0, BtLockWrite)) )
1865 page_no = bt->page_no;
1870 // if key is found delete it, otherwise ignore request
1872 ptr = keyptr(page, slot);
1874 if( bt->found = !keycmp (ptr, key, len) )
1875 if( bt->found = slotptr(page, slot)->dead == 0 ) {
1876 slotptr(page,slot)->dead = 1;
1877 if( slot < page->cnt )
1880 if( bt_mergeleft (bt, page, pool, set, page_no, 0) )
1884 bt_unlockpage(BtLockWrite, set);
1885 bt_unpinlatch (set);
1886 bt_unpinpool (pool);
1890 // find key in leaf level and return row-id
1892 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1898 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1899 ptr = keyptr(bt->page, slot);
1903 // if key exists, return row-id
1904 // otherwise return 0
1906 if( slot <= bt->page->cnt && !keycmp (ptr, key, len) )
1907 id = bt_getid(slotptr(bt->page,slot)->id);
1911 bt_unlockpage (BtLockRead, bt->set);
1912 bt_unpinlatch (bt->set);
1913 bt_unpinpool (bt->pool);
1917 // check page for space available,
1918 // clean if necessary and return
1919 // 0 - page needs splitting
1920 // >0 new slot value
1922 uint bt_cleanpage(BtDb *bt, BtPage page, uint amt, uint slot)
1924 uint nxt = bt->mgr->page_size;
1925 uint cnt = 0, idx = 0;
1926 uint max = page->cnt;
1930 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1933 // skip cleanup if nothing to reclaim
1938 memcpy (bt->frame, page, bt->mgr->page_size);
1940 // skip page info and set rest of page to zero
1942 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1946 // try cleaning up page first
1948 // always leave fence key in the array
1949 // otherwise, remove deleted key
1951 while( cnt++ < max ) {
1954 if( cnt < max && slotptr(bt->frame,cnt)->dead )
1959 key = keyptr(bt->frame, cnt);
1960 nxt -= key->len + 1;
1961 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1964 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1965 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1967 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1968 slotptr(page, idx)->off = nxt;
1974 // see if page has enough space now, or does it need splitting?
1976 if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1982 // add key to current page
1983 // page must already be writelocked
1985 void bt_addkeytopage (BtDb *bt, BtPage page, uint slot, unsigned char *key, uint len, uid id, uint tod)
1989 // find next available dead slot and copy key onto page
1991 for( idx = slot; idx < page->cnt; idx++ )
1992 if( slotptr(page, idx)->dead )
1995 if( idx == page->cnt )
2000 // now insert key into array before slot
2003 *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
2005 page->min -= len + 1;
2006 ((unsigned char *)page)[page->min] = len;
2007 memcpy ((unsigned char *)page + page->min +1, key, len );
2009 bt_putid(slotptr(page,slot)->id, id);
2010 slotptr(page, slot)->off = page->min;
2011 slotptr(page, slot)->tod = tod;
2012 slotptr(page, slot)->dead = 0;
2015 BTERR bt_splitroot(BtDb *bt, unsigned char *leftkey, uid page_no2)
2017 uint nxt = bt->mgr->page_size;
2018 BtPage root = bt->page;
2021 // Obtain an empty page to use, and copy the current
2022 // root contents into it
2024 if( !(new_page = bt_newpage(bt, root)) )
2027 // preserve the page info at the bottom
2028 // and set rest to zero
2030 memset(root+1, 0, bt->mgr->page_size - sizeof(*root));
2032 // insert first key on newroot page
2034 nxt -= *leftkey + 1;
2035 memcpy ((unsigned char *)root + nxt, leftkey, *leftkey + 1);
2036 bt_putid(slotptr(root, 1)->id, new_page);
2037 slotptr(root, 1)->off = nxt;
2039 // insert second key (stopper key) on newroot page
2040 // and increase the root height
2043 *((unsigned char *)root + nxt) = 2;
2044 memset ((unsigned char *)root + nxt + 1, 0xff, 2);
2045 bt_putid(slotptr(root, 2)->id, page_no2);
2046 slotptr(root, 2)->off = nxt;
2048 bt_putid(root->right, 0);
2049 root->min = nxt; // reset lowest used offset and key count
2054 // release and unpin root (bt->page)
2056 bt_unlockpage(BtLockWrite, bt->set);
2057 bt_unpinlatch (bt->set);
2058 bt_unpinpool (bt->pool);
2062 // split already locked full node
2063 // return unlocked and unpinned.
2065 BTERR bt_splitpage (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no)
2067 uint slot, cnt, idx, max, nxt = bt->mgr->page_size;
2068 unsigned char rightkey[256], leftkey[256];
2069 uint tod = time(NULL);
2070 uint lvl = page->lvl;
2074 // initialize frame buffer for right node
2076 memset (bt->frame, 0, bt->mgr->page_size);
2081 // split higher half of keys to bt->frame
2083 while( cnt++ < max ) {
2084 key = keyptr(page, cnt);
2085 nxt -= key->len + 1;
2086 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
2087 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
2088 if( !(slotptr(bt->frame, idx)->dead = slotptr(page, cnt)->dead) )
2090 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
2091 slotptr(bt->frame, idx)->off = nxt;
2094 // transfer right link node to new right node
2096 if( page_no > ROOT_page )
2097 memcpy (bt->frame->right, page->right, BtId);
2099 bt->frame->bits = bt->mgr->page_bits;
2100 bt->frame->min = nxt;
2101 bt->frame->cnt = idx;
2102 bt->frame->lvl = lvl;
2104 // get new free page and write right frame to it.
2106 if( !(new_page = bt_newpage(bt, bt->frame)) )
2109 // remember fence key for new right page to add
2110 // as right sibling to the left node
2112 key = keyptr(bt->frame, idx);
2113 memcpy (rightkey, key, key->len + 1);
2115 // update lower keys to continue in old page
2117 memcpy (bt->frame, page, bt->mgr->page_size);
2118 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
2119 nxt = bt->mgr->page_size;
2125 // assemble page of smaller keys
2126 // to remain in the old page
2128 while( cnt++ < max / 2 ) {
2129 key = keyptr(bt->frame, cnt);
2130 nxt -= key->len + 1;
2131 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2132 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
2133 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
2135 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2136 slotptr(page, idx)->off = nxt;
2139 // finalize left page and save fence key
2141 memcpy(leftkey, key, key->len + 1);
2145 // link new right page
2147 bt_putid (page->right, new_page);
2149 // if current page is the root page, split it
2151 if( page_no == ROOT_page )
2152 return bt_splitroot (bt, leftkey, new_page);
2154 // obtain ParentModification lock for current page
2156 bt_lockpage (BtLockParent, set);
2158 // release wr lock on our page.
2159 // this will keep out another SMO
2161 bt_unlockpage (BtLockWrite, set);
2163 // insert key for old page (lower keys)
2165 if( bt_insertkey (bt, leftkey + 1, *leftkey, page_no, tod, lvl + 1) )
2168 // switch old parent key from us to our right page
2170 if( bt_insertkey (bt, rightkey + 1, *rightkey, new_page, tod, lvl + 1) )
2175 bt_unlockpage (BtLockParent, set);
2176 bt_unpinlatch (set);
2177 bt_unpinpool (pool);
2181 // Insert new key into the btree at given level.
2183 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod, uint lvl)
2190 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
2191 ptr = keyptr(bt->page, slot);
2195 bt->err = BTERR_ovflw;
2199 // if key already exists, update id and return
2203 if( !keycmp (ptr, key, len) ) {
2204 if( slotptr(page, slot)->dead )
2206 slotptr(page, slot)->dead = 0;
2207 slotptr(page, slot)->tod = tod;
2208 bt_putid(slotptr(page,slot)->id, id);
2209 bt_unlockpage(BtLockWrite, bt->set);
2210 bt_unpinlatch (bt->set);
2211 bt_unpinpool (bt->pool);
2215 // check if page has enough space
2217 if( slot = bt_cleanpage (bt, bt->page, len, slot) )
2220 if( bt_splitpage (bt, bt->page, bt->pool, bt->set, bt->page_no) )
2224 bt_addkeytopage (bt, bt->page, slot, key, len, id, tod);
2226 bt_unlockpage (BtLockWrite, bt->set);
2227 bt_unpinlatch (bt->set);
2228 bt_unpinpool (bt->pool);
2232 // cache page of keys into cursor and return starting slot for given key
2234 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2238 // cache page for retrieval
2239 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
2240 memcpy (bt->cursor, bt->page, bt->mgr->page_size);
2242 bt->cursor_page = bt->page_no;
2244 bt_unlockpage(BtLockRead, bt->set);
2245 bt_unpinlatch (bt->set);
2246 bt_unpinpool (bt->pool);
2250 // return next slot for cursor page
2251 // or slide cursor right into next page
2253 uint bt_nextkey (BtDb *bt, uint slot)
2261 right = bt_getid(bt->cursor->right);
2262 while( slot++ < bt->cursor->cnt )
2263 if( slotptr(bt->cursor,slot)->dead )
2265 else if( right || (slot < bt->cursor->cnt) )
2273 bt->cursor_page = right;
2274 if( pool = bt_pinpool (bt, right) )
2275 page = bt_page (bt, pool, right);
2279 set = bt_pinlatch (bt, right);
2280 bt_lockpage(BtLockRead, set);
2282 memcpy (bt->cursor, page, bt->mgr->page_size);
2284 bt_unlockpage(BtLockRead, set);
2285 bt_unpinlatch (set);
2286 bt_unpinpool (pool);
2293 BtKey bt_key(BtDb *bt, uint slot)
2295 return keyptr(bt->cursor, slot);
2298 uid bt_uid(BtDb *bt, uint slot)
2300 return bt_getid(slotptr(bt->cursor,slot)->id);
2303 uint bt_tod(BtDb *bt, uint slot)
2305 return slotptr(bt->cursor,slot)->tod;
2311 void bt_latchaudit (BtDb *bt)
2313 ushort idx, hashidx;
2320 for( idx = 1; idx < bt->mgr->latchmgr->latchdeployed; idx++ ) {
2321 set = bt->mgr->latchsets + idx;
2322 if( *(ushort *)set->readwr || *(ushort *)set->access || *(ushort *)set->parent ) {
2323 fprintf(stderr, "latchset %d locked for page %6x\n", idx, set->page_no);
2324 *(ushort *)set->readwr = 0;
2325 *(ushort *)set->access = 0;
2326 *(ushort *)set->parent = 0;
2329 fprintf(stderr, "latchset %d pinned\n", idx);
2334 for( hashidx = 0; hashidx < bt->mgr->latchmgr->latchhash; hashidx++ ) {
2335 if( *(uint *)bt->mgr->latchmgr->table[hashidx].latch )
2336 fprintf(stderr, "latchmgr locked\n");
2337 if( idx = bt->mgr->latchmgr->table[hashidx].slot ) do {
2338 set = bt->mgr->latchsets + idx;
2339 if( *(uint *)set->readwr || *(ushort *)set->access || *(ushort *)set->parent )
2340 fprintf(stderr, "latchset %d locked\n", idx);
2341 if( set->hash != hashidx )
2342 fprintf(stderr, "latchset %d wrong hashidx\n", idx);
2344 fprintf(stderr, "latchset %d pinned\n", idx);
2345 } while( idx = set->next );
2347 page_no = bt_getid(bt->mgr->latchmgr->alloc[1].right);
2350 fprintf(stderr, "free: %.6x\n", (uint)page_no);
2351 pool = bt_pinpool (bt, page_no);
2352 page = bt_page (bt, pool, page_no);
2353 page_no = bt_getid(page->right);
2354 bt_unpinpool (pool);
2366 // standalone program to index file of keys
2367 // then list them onto std-out
2370 void *index_file (void *arg)
2372 uint __stdcall index_file (void *arg)
2375 int line = 0, found = 0, cnt = 0;
2376 uid next, page_no = LEAF_page; // start on first page of leaves
2377 unsigned char key[256];
2378 ThreadArg *args = arg;
2379 int ch, len = 0, slot;
2388 bt = bt_open (args->mgr);
2391 switch(args->type | 0x20)
2394 fprintf(stderr, "started latch mgr audit\n");
2396 fprintf(stderr, "finished latch mgr audit\n");
2400 fprintf(stderr, "started indexing for %s\n", args->infile);
2401 if( in = fopen (args->infile, "rb") )
2402 while( ch = getc(in), ch != EOF )
2407 if( args->num == 1 )
2408 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2410 else if( args->num )
2411 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2413 if( bt_insertkey (bt, key, len, line, *tod, 0) )
2414 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2417 else if( len < 255 )
2419 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
2423 fprintf(stderr, "started deleting keys for %s\n", args->infile);
2424 if( in = fopen (args->infile, "rb") )
2425 while( ch = getc(in), ch != EOF )
2429 if( args->num == 1 )
2430 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2432 else if( args->num )
2433 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2435 if( bt_deletekey (bt, key, len) )
2436 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2439 else if( len < 255 )
2441 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2445 fprintf(stderr, "started finding keys for %s\n", args->infile);
2446 if( in = fopen (args->infile, "rb") )
2447 while( ch = getc(in), ch != EOF )
2451 if( args->num == 1 )
2452 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2454 else if( args->num )
2455 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2457 if( bt_findkey (bt, key, len) )
2460 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2463 else if( len < 255 )
2465 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2471 fprintf(stderr, "started reading\n");
2473 if( slot = bt_startkey (bt, key, len) )
2476 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
2478 while( slot = bt_nextkey (bt, slot) ) {
2479 ptr = bt_key(bt, slot);
2480 fwrite (ptr->key, ptr->len, 1, stdout);
2481 fputc ('\n', stdout);
2487 fprintf(stderr, "started reading\n");
2490 if( pool = bt_pinpool (bt, page_no) )
2491 page = bt_page (bt, pool, page_no);
2494 set = bt_pinlatch (bt, page_no);
2495 bt_lockpage (BtLockRead, set);
2497 next = bt_getid (page->right);
2498 bt_unlockpage (BtLockRead, set);
2499 bt_unpinlatch (set);
2500 bt_unpinpool (pool);
2501 } while( page_no = next );
2503 cnt--; // remove stopper key
2504 fprintf(stderr, " Total keys read %d\n", cnt);
2516 typedef struct timeval timer;
2518 int main (int argc, char **argv)
2520 int idx, cnt, len, slot, err;
2521 int segsize, bits = 16;
2526 time_t start[1], stop[1];
2539 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]);
2540 fprintf (stderr, " where page_bits is the page size in bits\n");
2541 fprintf (stderr, " mapped_segments is the number of mmap segments in buffer pool\n");
2542 fprintf (stderr, " seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2543 fprintf (stderr, " line_numbers = 1 to append line numbers to keys\n");
2544 fprintf (stderr, " src_file1 thru src_filen are files of keys separated by newline\n");
2549 gettimeofday(&start, NULL);
2555 bits = atoi(argv[3]);
2558 poolsize = atoi(argv[4]);
2561 fprintf (stderr, "Warning: no mapped_pool\n");
2563 if( poolsize > 65535 )
2564 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2567 segsize = atoi(argv[5]);
2569 segsize = 4; // 16 pages per mmap segment
2572 num = atoi(argv[6]);
2576 threads = malloc (cnt * sizeof(pthread_t));
2578 threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2580 args = malloc (cnt * sizeof(ThreadArg));
2582 mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2585 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2591 for( idx = 0; idx < cnt; idx++ ) {
2592 args[idx].infile = argv[idx + 7];
2593 args[idx].type = argv[2][0];
2594 args[idx].mgr = mgr;
2595 args[idx].num = num;
2596 args[idx].idx = idx;
2598 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2599 fprintf(stderr, "Error creating thread %d\n", err);
2601 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2605 // wait for termination
2608 for( idx = 0; idx < cnt; idx++ )
2609 pthread_join (threads[idx], NULL);
2610 gettimeofday(&stop, NULL);
2611 real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2613 WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2615 for( idx = 0; idx < cnt; idx++ )
2616 CloseHandle(threads[idx]);
2619 real_time = 1000 * (*stop - *start);
2621 fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);