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
210 char *pooladvise; // bit maps for pool page advisements
215 ushort poolcnt; // highest page pool node in use
216 ushort poolmax; // highest page pool node allocated
217 ushort poolmask; // total number of pages in mmap segment - 1
218 ushort hashsize; // size of Hash Table for pool entries
219 volatile uint evicted; // last evicted hash table slot
220 ushort *hash; // pool index for hash entries
221 BtSpinLatch *latch; // latches for hash table slots
222 BtLatchMgr *latchmgr; // mapped latch page from allocation page
223 BtLatchSet *latchsets; // mapped latch set from latch pages
224 BtPool *pool; // memory pool page segments
226 HANDLE halloc; // allocation and latch table handle
231 BtMgr *mgr; // buffer manager for thread
232 BtPage cursor; // cached frame for start/next (never mapped)
233 BtPage frame; // spare frame for the page split (never mapped)
234 BtPage zero; // page frame for zeroes at end of file
235 BtPage page; // current page
236 uid page_no; // current page number
237 uid cursor_page; // current cursor page number
238 BtLatchSet *set; // current page latch set
239 BtPool *pool; // current page pool
240 unsigned char *mem; // frame, cursor, page memory buffer
241 int parent; // last loadpage was from a parent level
242 int found; // last delete or insert was found
243 int err; // last error
257 extern void bt_close (BtDb *bt);
258 extern BtDb *bt_open (BtMgr *mgr);
259 extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod, uint lvl);
260 extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len);
261 extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
262 extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
263 extern uint bt_nextkey (BtDb *bt, uint slot);
265 // internal functions
266 BTERR bt_splitpage (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no);
267 uint bt_cleanpage(BtDb *bt, BtPage page, uint amt, uint slot);
268 BTERR bt_mergeleft (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no, uint lvl);
271 extern BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolsize, uint segsize, uint hashsize);
272 void bt_mgrclose (BtMgr *mgr);
274 // Helper functions to return slot values
276 extern BtKey bt_key (BtDb *bt, uint slot);
277 extern uid bt_uid (BtDb *bt, uint slot);
278 extern uint bt_tod (BtDb *bt, uint slot);
280 // BTree page number constants
281 #define ALLOC_page 0 // allocation & lock manager hash table
282 #define ROOT_page 1 // root of the btree
283 #define LEAF_page 2 // first page of leaves
284 #define LATCH_page 3 // pages for lock manager
286 // Number of levels to create in a new BTree
290 // The page is allocated from low and hi ends.
291 // The key offsets and row-id's are allocated
292 // from the bottom, while the text of the key
293 // is allocated from the top. When the two
294 // areas meet, the page is split into two.
296 // A key consists of a length byte, two bytes of
297 // index number (0 - 65534), and up to 253 bytes
298 // of key value. Duplicate keys are discarded.
299 // Associated with each key is a 48 bit row-id.
301 // The b-tree root is always located at page 1.
302 // The first leaf page of level zero is always
303 // located on page 2.
305 // The b-tree pages are linked with next
306 // pointers to facilitate enumerators,
307 // and provide for concurrency.
309 // When to root page fills, it is split in two and
310 // the tree height is raised by a new root at page
311 // one with two keys.
313 // Deleted keys are marked with a dead bit until
314 // page cleanup The fence key for a node is always
315 // present, even after deletion and cleanup.
317 // Groups of pages called segments from the btree are optionally
318 // cached with a memory mapped pool. A hash table is used to keep
319 // track of the cached segments. This behaviour is controlled
320 // by the cache block size parameter to bt_open.
322 // To achieve maximum concurrency one page is locked at a time
323 // as the tree is traversed to find leaf key in question. The right
324 // page numbers are used in cases where the page is being split,
327 // Page 0 is dedicated to lock for new page extensions,
328 // and chains empty pages together for reuse.
330 // The ParentModification lock on a node is obtained to prevent resplitting
331 // or deleting a node before its fence is posted into its upper level.
333 // Empty pages are chained together through the ALLOC page and reused.
335 // Access macros to address slot and key values from the page
337 #define slotptr(page, slot) (((BtSlot *)(page+1)) + (slot-1))
338 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
340 void bt_putid(unsigned char *dest, uid id)
345 dest[i] = (unsigned char)id, id >>= 8;
348 uid bt_getid(unsigned char *src)
353 for( i = 0; i < BtId; i++ )
354 id <<= 8, id |= *src++;
361 // wait until write lock mode is clear
362 // and add 1 to the share count
364 void bt_spinreadlock(BtSpinLatch *latch)
369 // obtain latch mutex
371 if( __sync_fetch_and_or((ushort *)latch, Mutex) & Mutex )
374 if( prev = _InterlockedOr16((ushort *)latch, Mutex) & Mutex )
377 // see if exclusive request is granted or pending
379 if( prev = !(latch->exclusive | latch->pending) )
381 __sync_fetch_and_add((ushort *)latch, Share);
383 _InterlockedExchangeAdd16 ((ushort *)latch, Share);
387 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
389 _InterlockedAnd16((ushort *)latch, ~Mutex);
395 } while( sched_yield(), 1 );
397 } while( SwitchToThread(), 1 );
401 // wait for other read and write latches to relinquish
403 void bt_spinwritelock(BtSpinLatch *latch)
407 if( __sync_fetch_and_or((ushort *)latch, Mutex | Pending) & Mutex )
410 if( _InterlockedOr16((ushort *)latch, Mutex | Pending) & Mutex )
413 if( !(latch->share | latch->exclusive) ) {
415 __sync_fetch_and_or((ushort *)latch, Write);
416 __sync_fetch_and_and ((ushort *)latch, ~(Mutex | Pending));
418 _InterlockedOr16((ushort *)latch, Write);
419 _InterlockedAnd16((ushort *)latch, ~(Mutex | Pending));
425 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
427 _InterlockedAnd16((ushort *)latch, ~Mutex);
431 } while( sched_yield(), 1 );
433 } while( SwitchToThread(), 1 );
437 // try to obtain write lock
439 // return 1 if obtained,
442 int bt_spinwritetry(BtSpinLatch *latch)
447 if( prev = __sync_fetch_and_or((ushort *)latch, Mutex), prev & Mutex )
450 if( prev = _InterlockedOr16((ushort *)latch, Mutex), prev & Mutex )
453 // take write access if all bits are clear
457 __sync_fetch_and_or ((ushort *)latch, Write);
459 _InterlockedOr16((ushort *)latch, Write);
463 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
465 _InterlockedAnd16((ushort *)latch, ~Mutex);
472 void bt_spinreleasewrite(BtSpinLatch *latch)
475 __sync_fetch_and_and ((ushort *)latch, ~Write);
477 _InterlockedAnd16((ushort *)latch, ~Write);
481 // decrement reader count
483 void bt_spinreleaseread(BtSpinLatch *latch)
486 __sync_fetch_and_add((ushort *)latch, -Share);
488 _InterlockedExchangeAdd16 ((ushort *)latch, -Share);
492 // link latch table entry into latch hash table
494 void bt_latchlink (BtDb *bt, ushort hashidx, ushort victim, uid page_no)
496 BtLatchSet *set = bt->mgr->latchsets + victim;
498 if( set->next = bt->mgr->latchmgr->table[hashidx].slot )
499 bt->mgr->latchsets[set->next].prev = victim;
501 bt->mgr->latchmgr->table[hashidx].slot = victim;
502 set->page_no = page_no;
509 void bt_unpinlatch (BtLatchSet *set)
512 __sync_fetch_and_add(&set->pin, -1);
514 _InterlockedDecrement16 (&set->pin);
518 // find existing latchset or inspire new one
519 // return with latchset pinned
521 BtLatchSet *bt_pinlatch (BtDb *bt, uid page_no)
523 ushort hashidx = page_no % bt->mgr->latchmgr->latchhash;
524 ushort slot, avail = 0, victim, idx;
527 // obtain read lock on hash table entry
529 bt_spinreadlock(bt->mgr->latchmgr->table[hashidx].latch);
531 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
533 set = bt->mgr->latchsets + slot;
534 if( page_no == set->page_no )
536 } while( slot = set->next );
540 __sync_fetch_and_add(&set->pin, 1);
542 _InterlockedIncrement16 (&set->pin);
546 bt_spinreleaseread (bt->mgr->latchmgr->table[hashidx].latch);
551 // try again, this time with write lock
553 bt_spinwritelock(bt->mgr->latchmgr->table[hashidx].latch);
555 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
557 set = bt->mgr->latchsets + slot;
558 if( page_no == set->page_no )
560 if( !set->pin && !avail )
562 } while( slot = set->next );
564 // found our entry, or take over an unpinned one
566 if( slot || (slot = avail) ) {
567 set = bt->mgr->latchsets + slot;
569 __sync_fetch_and_add(&set->pin, 1);
571 _InterlockedIncrement16 (&set->pin);
573 set->page_no = page_no;
574 bt_spinreleasewrite(bt->mgr->latchmgr->table[hashidx].latch);
578 // see if there are any unused entries
580 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, 1) + 1;
582 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchdeployed);
585 if( victim < bt->mgr->latchmgr->latchtotal ) {
586 set = bt->mgr->latchsets + victim;
588 __sync_fetch_and_add(&set->pin, 1);
590 _InterlockedIncrement16 (&set->pin);
592 bt_latchlink (bt, hashidx, victim, page_no);
593 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
598 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, -1);
600 victim = _InterlockedDecrement16 (&bt->mgr->latchmgr->latchdeployed);
602 // find and reuse previous lock entry
606 victim = __sync_fetch_and_add(&bt->mgr->latchmgr->latchvictim, 1);
608 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchvictim) - 1;
610 // we don't use slot zero
612 if( victim %= bt->mgr->latchmgr->latchtotal )
613 set = bt->mgr->latchsets + victim;
617 // take control of our slot
618 // from other threads
620 if( set->pin || !bt_spinwritetry (set->busy) )
625 // try to get write lock on hash chain
626 // skip entry if not obtained
627 // or has outstanding locks
629 if( !bt_spinwritetry (bt->mgr->latchmgr->table[idx].latch) ) {
630 bt_spinreleasewrite (set->busy);
635 bt_spinreleasewrite (set->busy);
636 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
640 // unlink our available victim from its hash chain
643 bt->mgr->latchsets[set->prev].next = set->next;
645 bt->mgr->latchmgr->table[idx].slot = set->next;
648 bt->mgr->latchsets[set->next].prev = set->prev;
650 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
652 __sync_fetch_and_add(&set->pin, 1);
654 _InterlockedIncrement16 (&set->pin);
656 bt_latchlink (bt, hashidx, victim, page_no);
657 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
658 bt_spinreleasewrite (set->busy);
663 void bt_mgrclose (BtMgr *mgr)
668 // release mapped pages
669 // note that slot zero is never used
671 for( slot = 1; slot < mgr->poolmax; slot++ ) {
672 pool = mgr->pool + slot;
675 munmap (pool->map, (mgr->poolmask+1) << mgr->page_bits);
678 FlushViewOfFile(pool->map, 0);
679 UnmapViewOfFile(pool->map);
680 CloseHandle(pool->hmap);
686 munmap (mgr->latchsets, mgr->latchmgr->nlatchpage * mgr->page_size);
687 munmap (mgr->latchmgr, mgr->page_size);
689 FlushViewOfFile(mgr->latchmgr, 0);
690 UnmapViewOfFile(mgr->latchmgr);
691 CloseHandle(mgr->halloc);
698 free (mgr->pooladvise);
701 FlushFileBuffers(mgr->idx);
702 CloseHandle(mgr->idx);
703 GlobalFree (mgr->pool);
704 GlobalFree (mgr->hash);
705 GlobalFree (mgr->latch);
710 // close and release memory
712 void bt_close (BtDb *bt)
719 VirtualFree (bt->mem, 0, MEM_RELEASE);
724 // open/create new btree buffer manager
726 // call with file_name, BT_openmode, bits in page size (e.g. 16),
727 // size of mapped page pool (e.g. 8192)
729 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
731 uint lvl, attr, cacheblk, last, slot, idx;
732 uint nlatchpage, latchhash;
733 BtLatchMgr *latchmgr;
741 SYSTEM_INFO sysinfo[1];
744 // determine sanity of page size and buffer pool
746 if( bits > BT_maxbits )
748 else if( bits < BT_minbits )
752 return NULL; // must have buffer pool
755 mgr = calloc (1, sizeof(BtMgr));
757 mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
760 return free(mgr), NULL;
762 cacheblk = 4096; // minimum mmap segment size for unix
765 mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
766 attr = FILE_ATTRIBUTE_NORMAL;
767 mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
769 if( mgr->idx == INVALID_HANDLE_VALUE )
770 return GlobalFree(mgr), NULL;
772 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
773 GetSystemInfo(sysinfo);
774 cacheblk = sysinfo->dwAllocationGranularity;
778 latchmgr = malloc (BT_maxpage);
781 // read minimum page size to get root info
783 if( size = lseek (mgr->idx, 0L, 2) ) {
784 if( pread(mgr->idx, latchmgr, BT_minpage, 0) == BT_minpage )
785 bits = latchmgr->alloc->bits;
787 return free(mgr), free(latchmgr), NULL;
788 } else if( mode == BT_ro )
789 return free(latchmgr), bt_mgrclose (mgr), NULL;
791 latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
792 size = GetFileSize(mgr->idx, amt);
795 if( !ReadFile(mgr->idx, (char *)latchmgr, BT_minpage, amt, NULL) )
796 return bt_mgrclose (mgr), NULL;
797 bits = latchmgr->alloc->bits;
798 } else if( mode == BT_ro )
799 return bt_mgrclose (mgr), NULL;
802 mgr->page_size = 1 << bits;
803 mgr->page_bits = bits;
805 mgr->poolmax = poolmax;
808 if( cacheblk < mgr->page_size )
809 cacheblk = mgr->page_size;
811 // mask for partial memmaps
813 mgr->poolmask = (cacheblk >> bits) - 1;
815 // see if requested size of pages per memmap is greater
817 if( (1 << segsize) > mgr->poolmask )
818 mgr->poolmask = (1 << segsize) - 1;
822 while( (1 << mgr->seg_bits) <= mgr->poolmask )
825 mgr->hashsize = hashsize;
828 mgr->pool = calloc (poolmax, sizeof(BtPool));
829 mgr->hash = calloc (hashsize, sizeof(ushort));
830 mgr->latch = calloc (hashsize, sizeof(BtSpinLatch));
831 mgr->pooladvise = calloc (poolmax, (mgr->poolmask + 8) / 8);
833 mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * sizeof(BtPool));
834 mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
835 mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtSpinLatch));
841 // initialize an empty b-tree with latch page, root page, page of leaves
842 // and page(s) of latches
844 memset (latchmgr, 0, 1 << bits);
845 nlatchpage = BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1;
846 bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
847 latchmgr->alloc->bits = mgr->page_bits;
849 latchmgr->nlatchpage = nlatchpage;
850 latchmgr->latchtotal = nlatchpage * (mgr->page_size / sizeof(BtLatchSet));
852 // initialize latch manager
854 latchhash = (mgr->page_size - sizeof(BtLatchMgr)) / sizeof(BtHashEntry);
856 // size of hash table = total number of latchsets
858 if( latchhash > latchmgr->latchtotal )
859 latchhash = latchmgr->latchtotal;
861 latchmgr->latchhash = latchhash;
864 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
865 return bt_mgrclose (mgr), NULL;
867 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
868 return bt_mgrclose (mgr), NULL;
870 if( *amt < mgr->page_size )
871 return bt_mgrclose (mgr), NULL;
874 memset (latchmgr, 0, 1 << bits);
875 latchmgr->alloc->bits = mgr->page_bits;
877 for( lvl=MIN_lvl; lvl--; ) {
878 slotptr(latchmgr->alloc, 1)->off = mgr->page_size - 3;
879 bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
880 key = keyptr(latchmgr->alloc, 1);
881 key->len = 2; // create stopper key
884 latchmgr->alloc->min = mgr->page_size - 3;
885 latchmgr->alloc->lvl = lvl;
886 latchmgr->alloc->cnt = 1;
887 latchmgr->alloc->act = 1;
889 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
890 return bt_mgrclose (mgr), NULL;
892 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
893 return bt_mgrclose (mgr), NULL;
895 if( *amt < mgr->page_size )
896 return bt_mgrclose (mgr), NULL;
900 // clear out latch manager locks
901 // and rest of pages to round out segment
903 memset(latchmgr, 0, mgr->page_size);
906 while( last <= ((MIN_lvl + 1 + nlatchpage) | mgr->poolmask) ) {
908 pwrite(mgr->idx, latchmgr, mgr->page_size, last << mgr->page_bits);
910 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
911 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
912 return bt_mgrclose (mgr), NULL;
913 if( *amt < mgr->page_size )
914 return bt_mgrclose (mgr), NULL;
921 flag = PROT_READ | PROT_WRITE;
922 mgr->latchmgr = mmap (0, mgr->page_size, flag, MAP_SHARED, mgr->idx, ALLOC_page * mgr->page_size);
923 if( mgr->latchmgr == MAP_FAILED )
924 return bt_mgrclose (mgr), NULL;
925 mgr->latchsets = (BtLatchSet *)mmap (0, mgr->latchmgr->nlatchpage * mgr->page_size, flag, MAP_SHARED, mgr->idx, LATCH_page * mgr->page_size);
926 if( mgr->latchsets == MAP_FAILED )
927 return bt_mgrclose (mgr), NULL;
929 flag = PAGE_READWRITE;
930 mgr->halloc = CreateFileMapping(mgr->idx, NULL, flag, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size, NULL);
932 return bt_mgrclose (mgr), NULL;
934 flag = FILE_MAP_WRITE;
935 mgr->latchmgr = MapViewOfFile(mgr->halloc, flag, 0, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size);
937 return GetLastError(), bt_mgrclose (mgr), NULL;
939 mgr->latchsets = (void *)((char *)mgr->latchmgr + LATCH_page * mgr->page_size);
945 VirtualFree (latchmgr, 0, MEM_RELEASE);
950 // open BTree access method
951 // based on buffer manager
953 BtDb *bt_open (BtMgr *mgr)
955 BtDb *bt = malloc (sizeof(*bt));
957 memset (bt, 0, sizeof(*bt));
960 bt->mem = malloc (3 *mgr->page_size);
962 bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
964 bt->frame = (BtPage)bt->mem;
965 bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
966 bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
968 memset (bt->zero, 0, mgr->page_size);
972 // compare two keys, returning > 0, = 0, or < 0
973 // as the comparison value
975 int keycmp (BtKey key1, unsigned char *key2, uint len2)
977 uint len1 = key1->len;
980 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
993 // find segment in pool
994 // must be called with hashslot idx locked
995 // return NULL if not there
996 // otherwise return node
998 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
1003 // compute start of hash chain in pool
1005 if( slot = bt->mgr->hash[idx] )
1006 pool = bt->mgr->pool + slot;
1010 page_no &= ~bt->mgr->poolmask;
1012 while( pool->basepage != page_no )
1013 if( pool = pool->hashnext )
1021 // add segment to hash table
1023 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
1028 pool->hashprev = pool->hashnext = NULL;
1029 pool->basepage = page_no & ~bt->mgr->poolmask;
1032 if( slot = bt->mgr->hash[idx] ) {
1033 node = bt->mgr->pool + slot;
1034 pool->hashnext = node;
1035 node->hashprev = pool;
1038 bt->mgr->hash[idx] = pool->slot;
1041 // find best segment to evict from buffer pool
1043 BtPool *bt_findlru (BtDb *bt, uint hashslot)
1045 unsigned long long int target = ~0LL;
1046 BtPool *pool = NULL, *node;
1051 node = bt->mgr->pool + hashslot;
1053 // scan pool entries under hash table slot
1058 if( node->lru > target )
1062 } while( node = node->hashnext );
1067 // map new buffer pool segment to virtual memory
1069 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
1071 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
1072 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
1076 flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
1077 pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED, bt->mgr->idx, off);
1078 if( pool->map == MAP_FAILED )
1079 return bt->err = BTERR_map;
1081 // clear out madvise issued bits
1082 memset (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8) / 8), 0, (bt->mgr->poolmask + 8)/8);
1084 flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
1085 pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
1087 return bt->err = BTERR_map;
1089 flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
1090 pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1092 return bt->err = BTERR_map;
1097 // calculate page within pool
1099 BtPage bt_page (BtDb *bt, BtPool *pool, uid page_no)
1101 uint subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1104 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1107 uint idx = subpage / 8;
1108 uint bit = subpage % 8;
1110 if( ~((bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] >> bit) & 1 ) {
1111 madvise (page, bt->mgr->page_size, MADV_WILLNEED);
1112 (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] |= 1 << bit;
1121 void bt_unpinpool (BtPool *pool)
1124 __sync_fetch_and_add(&pool->pin, -1);
1126 _InterlockedDecrement16 (&pool->pin);
1130 // find or place requested page in segment-pool
1131 // return pool table entry, incrementing pin
1133 BtPool *bt_pinpool(BtDb *bt, uid page_no)
1135 BtPool *pool, *node, *next;
1136 uint slot, idx, victim;
1138 // lock hash table chain
1140 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1141 bt_spinreadlock (&bt->mgr->latch[idx]);
1143 // look up in hash table
1145 if( pool = bt_findpool(bt, page_no, idx) ) {
1147 __sync_fetch_and_add(&pool->pin, 1);
1149 _InterlockedIncrement16 (&pool->pin);
1151 bt_spinreleaseread (&bt->mgr->latch[idx]);
1156 // upgrade to write lock
1158 bt_spinreleaseread (&bt->mgr->latch[idx]);
1159 bt_spinwritelock (&bt->mgr->latch[idx]);
1161 // try to find page in pool with write lock
1163 if( pool = bt_findpool(bt, page_no, idx) ) {
1165 __sync_fetch_and_add(&pool->pin, 1);
1167 _InterlockedIncrement16 (&pool->pin);
1169 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1174 // allocate a new pool node
1175 // and add to hash table
1178 slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
1180 slot = _InterlockedIncrement16 (&bt->mgr->poolcnt) - 1;
1183 if( ++slot < bt->mgr->poolmax ) {
1184 pool = bt->mgr->pool + slot;
1187 if( bt_mapsegment(bt, pool, page_no) )
1190 bt_linkhash(bt, pool, page_no, idx);
1192 __sync_fetch_and_add(&pool->pin, 1);
1194 _InterlockedIncrement16 (&pool->pin);
1196 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1200 // pool table is full
1201 // find best pool entry to evict
1204 __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
1206 _InterlockedDecrement16 (&bt->mgr->poolcnt);
1211 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
1213 victim = _InterlockedIncrement (&bt->mgr->evicted) - 1;
1215 victim %= bt->mgr->hashsize;
1217 // try to get write lock
1218 // skip entry if not obtained
1220 if( !bt_spinwritetry (&bt->mgr->latch[victim]) )
1223 // if pool entry is empty
1224 // or any pages are pinned
1227 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
1228 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1232 // unlink victim pool node from hash table
1234 if( node = pool->hashprev )
1235 node->hashnext = pool->hashnext;
1236 else if( node = pool->hashnext )
1237 bt->mgr->hash[victim] = node->slot;
1239 bt->mgr->hash[victim] = 0;
1241 if( node = pool->hashnext )
1242 node->hashprev = pool->hashprev;
1244 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1246 // remove old file mapping
1248 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1250 FlushViewOfFile(pool->map, 0);
1251 UnmapViewOfFile(pool->map);
1252 CloseHandle(pool->hmap);
1256 // create new pool mapping
1257 // and link into hash table
1259 if( bt_mapsegment(bt, pool, page_no) )
1262 bt_linkhash(bt, pool, page_no, idx);
1264 __sync_fetch_and_add(&pool->pin, 1);
1266 _InterlockedIncrement16 (&pool->pin);
1268 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1273 // place write, read, or parent lock on requested page_no.
1275 void bt_lockpage(BtLock mode, BtLatchSet *set)
1279 bt_spinreadlock (set->readwr);
1282 bt_spinwritelock (set->readwr);
1285 bt_spinreadlock (set->access);
1288 bt_spinwritelock (set->access);
1291 bt_spinwritelock (set->parent);
1296 // remove write, read, or parent lock on requested page
1298 void bt_unlockpage(BtLock mode, BtLatchSet *set)
1302 bt_spinreleaseread (set->readwr);
1305 bt_spinreleasewrite (set->readwr);
1308 bt_spinreleaseread (set->access);
1311 bt_spinreleasewrite (set->access);
1314 bt_spinreleasewrite (set->parent);
1319 // allocate a new page and write page into it
1321 uid bt_newpage(BtDb *bt, BtPage page)
1329 // lock allocation page
1331 bt_spinwritelock(bt->mgr->latchmgr->lock);
1333 // use empty chain first
1334 // else allocate empty page
1336 if( new_page = bt_getid(bt->mgr->latchmgr->alloc[1].right) ) {
1337 if( pool = bt_pinpool (bt, new_page) )
1338 pmap = bt_page (bt, pool, new_page);
1341 bt_putid(bt->mgr->latchmgr->alloc[1].right, bt_getid(pmap->right));
1342 bt_unpinpool (pool);
1345 new_page = bt_getid(bt->mgr->latchmgr->alloc->right);
1346 bt_putid(bt->mgr->latchmgr->alloc->right, new_page+1);
1350 if ( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1351 return bt->err = BTERR_wrt, 0;
1353 // if writing first page of pool block, zero last page in the block
1355 if ( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1357 // use zero buffer to write zeros
1358 memset(bt->zero, 0, bt->mgr->page_size);
1359 if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1360 return bt->err = BTERR_wrt, 0;
1363 // bring new page into pool and copy page.
1364 // this will extend the file into the new pages.
1366 if( pool = bt_pinpool (bt, new_page) )
1367 pmap = bt_page (bt, pool, new_page);
1371 memcpy(pmap, page, bt->mgr->page_size);
1372 bt_unpinpool (pool);
1374 // unlock allocation latch and return new page no
1376 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1380 // find slot in page for given key at a given level
1382 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1384 uint diff, higher = bt->page->cnt, low = 1, slot;
1387 // make stopper key an infinite fence value
1389 if( bt_getid (bt->page->right) )
1394 // low is the next candidate, higher is already
1395 // tested as .ge. the given key, loop ends when they meet
1397 while( diff = higher - low ) {
1398 slot = low + ( diff >> 1 );
1399 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1402 higher = slot, good++;
1405 // return zero if key is on right link page
1407 return good ? higher : 0;
1410 // find and load page at given level for given key
1411 // leave page rd or wr locked as requested
1413 int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, uint lock)
1415 uid page_no = ROOT_page, prevpage = 0;
1416 BtLatchSet *set, *prevset;
1417 uint drill = 0xff, slot;
1418 uint mode, prevmode;
1422 // start at root of btree and drill down
1427 // determine lock mode of drill level
1428 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1430 bt->set = bt_pinlatch (bt, page_no);
1431 bt->page_no = page_no;
1433 // pin page contents
1435 if( bt->pool = bt_pinpool (bt, page_no) )
1436 bt->page = bt_page (bt, bt->pool, page_no);
1440 // obtain access lock using lock chaining with Access mode
1442 if( page_no > ROOT_page )
1443 bt_lockpage(BtLockAccess, bt->set);
1445 // release & unpin parent page
1448 bt_unlockpage(prevmode, prevset);
1449 bt_unpinlatch (prevset);
1450 bt_unpinpool (prevpool);
1454 // obtain read lock using lock chaining
1456 bt_lockpage(mode, bt->set);
1458 if( page_no > ROOT_page )
1459 bt_unlockpage(BtLockAccess, bt->set);
1461 // re-read and re-lock root after determining actual level of root
1463 if( bt->page->lvl != drill) {
1464 if ( bt->page_no != ROOT_page )
1465 return bt->err = BTERR_struct, 0;
1467 drill = bt->page->lvl;
1469 if( lock == BtLockWrite && drill == lvl ) {
1470 bt_unlockpage(mode, bt->set);
1471 bt_unpinlatch (bt->set);
1472 bt_unpinpool (bt->pool);
1477 // find key on page at this level
1478 // and descend to requested level
1480 if( slot = bt_findslot (bt, key, len) ) {
1482 return bt->parent = parent, slot;
1484 while( slotptr(bt->page, slot)->dead )
1485 if( slot++ < bt->page->cnt )
1488 page_no = bt_getid(bt->page->right);
1493 page_no = bt_getid(slotptr(bt->page, slot)->id);
1498 // or slide right into next page
1501 page_no = bt_getid(bt->page->right);
1505 // continue down / right using overlapping locks
1506 // to protect pages being split.
1509 prevpage = bt->page_no;
1510 prevpool = bt->pool;
1515 // return error on end of right chain
1517 bt->err = BTERR_struct;
1518 return 0; // return error
1521 // remove empty page from the B-tree
1522 // by pulling our right node left over ourselves
1524 // call with bt->page, etc, set to page's locked parent
1525 // returns with page locked.
1527 BTERR bt_mergeright (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no, uint lvl, uint slot)
1529 BtLatchSet *rset, *pset, *rpset;
1530 BtPool *rpool, *ppool, *rppool;
1531 BtPage rpage, ppage, rppage;
1532 uid right, parent, rparent;
1536 // cache node's parent page
1538 parent = bt->page_no;
1543 // lock and map our right page
1544 // it cannot be NULL because of the stopper
1545 // in the last right page
1547 bt_lockpage (BtLockWrite, set);
1549 // if we aren't dead yet
1554 if( right = bt_getid (page->right) )
1555 if( rpool = bt_pinpool (bt, right) )
1556 rpage = bt_page (bt, rpool, right);
1560 return bt->err = BTERR_struct;
1562 rset = bt_pinlatch (bt, right);
1564 // find our right neighbor
1566 if( ppage->act > 1 ) {
1567 for( idx = slot; idx++ < ppage->cnt; )
1568 if( !slotptr(ppage, idx)->dead )
1571 if( idx > ppage->cnt )
1572 return bt->err = BTERR_struct;
1574 // redirect right neighbor in parent to left node
1576 bt_putid(slotptr(ppage,idx)->id, page_no);
1579 // if parent has only our deleted page, e.g. no right neighbor
1580 // prepare to merge parent itself
1582 if( ppage->act == 1 ) {
1583 if( rparent = bt_getid (ppage->right) )
1584 if( rppool = bt_pinpool (bt, rparent) )
1585 rppage = bt_page (bt, rppool, rparent);
1589 return bt->err = BTERR_struct;
1591 rpset = bt_pinlatch (bt, rparent);
1592 bt_lockpage (BtLockWrite, rpset);
1594 // find our right neighbor on right parent page
1596 for( idx = 0; idx++ < rppage->cnt; )
1597 if( !slotptr(rppage, idx)->dead ) {
1598 bt_putid (slotptr(rppage, idx)->id, page_no);
1602 if( idx > rppage->cnt )
1603 return bt->err = BTERR_struct;
1606 // now that there are no more pointers to our right node
1607 // we can wait for delete lock on it
1609 bt_lockpage(BtLockDelete, rset);
1610 bt_lockpage(BtLockWrite, rset);
1612 // pull contents of right page into our empty page
1614 memcpy (page, rpage, bt->mgr->page_size);
1616 // ready to release right parent lock
1617 // now that we have a new page in place
1619 if( ppage->act == 1 ) {
1620 bt_unlockpage (BtLockWrite, rpset);
1621 bt_unpinlatch (rpset);
1622 bt_unpinpool (rppool);
1625 // add killed right block to free chain
1628 bt_spinwritelock(bt->mgr->latchmgr->lock);
1630 // store free chain in allocation page second right
1632 bt_putid(rpage->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1633 bt_putid(bt->mgr->latchmgr->alloc[1].right, right);
1635 // unlock latch mgr and right page
1637 bt_unlockpage(BtLockDelete, rset);
1638 bt_unlockpage(BtLockWrite, rset);
1639 bt_unpinlatch (rset);
1640 bt_unpinpool (rpool);
1642 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1644 // delete our obsolete fence key from our parent
1646 slotptr(ppage, slot)->dead = 1;
1649 // if our parent now empty
1650 // remove it from the tree
1652 if( ppage->act-- == 1 )
1653 if( bt_mergeleft (bt, ppage, ppool, pset, parent, lvl+1) )
1657 bt_unlockpage (BtLockWrite, pset);
1658 bt_unpinlatch (pset);
1659 bt_unpinpool (ppool);
1665 // remove empty page from the B-tree
1666 // try merging left first. If no left
1667 // sibling, then merge right.
1669 // call with page loaded and locked,
1670 // return with page locked.
1672 BTERR bt_mergeleft (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no, uint lvl)
1674 unsigned char fencekey[256], postkey[256];
1675 uint slot, idx, postfence = 0;
1676 BtLatchSet *lset, *pset;
1677 BtPool *lpool, *ppool;
1678 BtPage lpage, ppage;
1682 ptr = keyptr(page, page->cnt);
1683 memcpy(fencekey, ptr, ptr->len + 1);
1684 bt_unlockpage (BtLockWrite, set);
1686 // load and lock our parent
1689 if( !(slot = bt_loadpage (bt, fencekey+1, *fencekey, lvl+1, BtLockWrite)) )
1692 parent = bt->page_no;
1697 // wait until we are posted in our parent
1700 bt_unlockpage (BtLockWrite, pset);
1701 bt_unpinlatch (pset);
1702 bt_unpinpool (ppool);
1711 // find our left neighbor in our parent page
1713 for( idx = slot; --idx; )
1714 if( !slotptr(ppage, idx)->dead )
1717 // if no left neighbor, do right merge
1720 return bt_mergeright (bt, page, pool, set, page_no, lvl, slot);
1722 // lock and map our left neighbor's page
1724 left = bt_getid (slotptr(ppage, idx)->id);
1726 if( lpool = bt_pinpool (bt, left) )
1727 lpage = bt_page (bt, lpool, left);
1731 lset = bt_pinlatch (bt, left);
1732 bt_lockpage(BtLockWrite, lset);
1734 // wait until sibling is in our parent
1736 if( bt_getid (lpage->right) != page_no ) {
1737 bt_unlockpage (BtLockWrite, pset);
1738 bt_unpinlatch (pset);
1739 bt_unpinpool (ppool);
1740 bt_unlockpage (BtLockWrite, lset);
1741 bt_unpinlatch (lset);
1742 bt_unpinpool (lpool);
1751 // since our page will have no more pointers to it,
1752 // obtain Delete lock and wait for write locks to clear
1754 bt_lockpage(BtLockDelete, set);
1755 bt_lockpage(BtLockWrite, set);
1757 // if we aren't dead yet,
1758 // get ready for exit
1761 bt_unlockpage(BtLockDelete, set);
1762 bt_unlockpage(BtLockWrite, lset);
1763 bt_unpinlatch (lset);
1764 bt_unpinpool (lpool);
1768 // are we are the fence key for our parent?
1769 // if so, grab our old fence key
1771 if( postfence = slot == ppage->cnt ) {
1772 ptr = keyptr (ppage, ppage->cnt);
1773 memcpy(fencekey, ptr, ptr->len + 1);
1774 memset(slotptr(ppage, ppage->cnt), 0, sizeof(BtSlot));
1776 // clear out other dead slots
1778 while( --ppage->cnt )
1779 if( slotptr(ppage, ppage->cnt)->dead )
1780 memset(slotptr(ppage, ppage->cnt), 0, sizeof(BtSlot));
1784 ptr = keyptr (ppage, ppage->cnt);
1785 memcpy(postkey, ptr, ptr->len + 1);
1787 slotptr(ppage,slot)->dead = 1;
1792 // push our right neighbor pointer to our left
1794 memcpy (lpage->right, page->right, BtId);
1796 // add ourselves to free chain
1799 bt_spinwritelock(bt->mgr->latchmgr->lock);
1801 // store free chain in allocation page second right
1802 bt_putid(page->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1803 bt_putid(bt->mgr->latchmgr->alloc[1].right, page_no);
1805 // unlock latch mgr and pages
1807 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1808 bt_unlockpage(BtLockWrite, lset);
1809 bt_unpinlatch (lset);
1810 bt_unpinpool (lpool);
1812 // release our node's delete lock
1814 bt_unlockpage(BtLockDelete, set);
1817 bt_unlockpage (BtLockWrite, pset);
1818 bt_unpinpool (ppool);
1820 // do we need to post parent's fence key in its parent?
1822 if( !postfence || parent == ROOT_page ) {
1823 bt_unpinlatch (pset);
1828 // interlock parent fence post
1830 bt_lockpage (BtLockParent, pset);
1832 // load parent's parent page
1834 if( !(slot = bt_loadpage (bt, fencekey+1, *fencekey, lvl+2, BtLockWrite)) )
1837 if( !(slot = bt_cleanpage (bt, bt->page, *fencekey, slot)) )
1838 if( bt_splitpage (bt, bt->page, bt->pool, bt->set, bt->page_no) )
1845 page->min -= *postkey + 1;
1846 ((unsigned char *)page)[page->min] = *postkey;
1847 memcpy ((unsigned char *)page + page->min +1, postkey + 1, *postkey );
1848 slotptr(page, slot)->off = page->min;
1850 bt_unlockpage (BtLockParent, pset);
1851 bt_unpinlatch (pset);
1853 bt_unlockpage (BtLockWrite, bt->set);
1854 bt_unpinlatch (bt->set);
1855 bt_unpinpool (bt->pool);
1861 // find and delete key on page by marking delete flag bit
1862 // if page becomes empty, delete it from the btree
1864 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len)
1873 if( !(slot = bt_loadpage (bt, key, len, 0, BtLockWrite)) )
1876 page_no = bt->page_no;
1881 // if key is found delete it, otherwise ignore request
1883 ptr = keyptr(page, slot);
1885 if( bt->found = !keycmp (ptr, key, len) )
1886 if( bt->found = slotptr(page, slot)->dead == 0 ) {
1887 slotptr(page,slot)->dead = 1;
1888 if( slot < page->cnt )
1891 if( bt_mergeleft (bt, page, pool, set, page_no, 0) )
1895 bt_unlockpage(BtLockWrite, set);
1896 bt_unpinlatch (set);
1897 bt_unpinpool (pool);
1901 // find key in leaf level and return row-id
1903 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1909 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1910 ptr = keyptr(bt->page, slot);
1914 // if key exists, return row-id
1915 // otherwise return 0
1917 if( slot <= bt->page->cnt && !keycmp (ptr, key, len) )
1918 id = bt_getid(slotptr(bt->page,slot)->id);
1922 bt_unlockpage (BtLockRead, bt->set);
1923 bt_unpinlatch (bt->set);
1924 bt_unpinpool (bt->pool);
1928 // check page for space available,
1929 // clean if necessary and return
1930 // 0 - page needs splitting
1931 // >0 new slot value
1933 uint bt_cleanpage(BtDb *bt, BtPage page, uint amt, uint slot)
1935 uint nxt = bt->mgr->page_size;
1936 uint cnt = 0, idx = 0;
1937 uint max = page->cnt;
1941 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1944 // skip cleanup if nothing to reclaim
1949 memcpy (bt->frame, page, bt->mgr->page_size);
1951 // skip page info and set rest of page to zero
1953 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1957 // try cleaning up page first
1959 // always leave fence key in the array
1960 // otherwise, remove deleted key
1962 while( cnt++ < max ) {
1965 if( cnt < max && slotptr(bt->frame,cnt)->dead )
1970 key = keyptr(bt->frame, cnt);
1971 nxt -= key->len + 1;
1972 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1975 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1976 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1978 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1979 slotptr(page, idx)->off = nxt;
1985 // see if page has enough space now, or does it need splitting?
1987 if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1993 // add key to current page
1994 // page must already be writelocked
1996 void bt_addkeytopage (BtDb *bt, BtPage page, uint slot, unsigned char *key, uint len, uid id, uint tod)
2000 // find next available dead slot and copy key onto page
2002 for( idx = slot; idx < page->cnt; idx++ )
2003 if( slotptr(page, idx)->dead )
2006 if( idx == page->cnt )
2011 // now insert key into array before slot
2014 *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
2016 page->min -= len + 1;
2017 ((unsigned char *)page)[page->min] = len;
2018 memcpy ((unsigned char *)page + page->min +1, key, len );
2020 bt_putid(slotptr(page,slot)->id, id);
2021 slotptr(page, slot)->off = page->min;
2022 slotptr(page, slot)->tod = tod;
2023 slotptr(page, slot)->dead = 0;
2026 BTERR bt_splitroot(BtDb *bt, unsigned char *leftkey, uid page_no2)
2028 uint nxt = bt->mgr->page_size;
2029 BtPage root = bt->page;
2032 // Obtain an empty page to use, and copy the current
2033 // root contents into it
2035 if( !(new_page = bt_newpage(bt, root)) )
2038 // preserve the page info at the bottom
2039 // and set rest to zero
2041 memset(root+1, 0, bt->mgr->page_size - sizeof(*root));
2043 // insert first key on newroot page
2045 nxt -= *leftkey + 1;
2046 memcpy ((unsigned char *)root + nxt, leftkey, *leftkey + 1);
2047 bt_putid(slotptr(root, 1)->id, new_page);
2048 slotptr(root, 1)->off = nxt;
2050 // insert second key (stopper key) on newroot page
2051 // and increase the root height
2054 *((unsigned char *)root + nxt) = 2;
2055 memset ((unsigned char *)root + nxt + 1, 0xff, 2);
2056 bt_putid(slotptr(root, 2)->id, page_no2);
2057 slotptr(root, 2)->off = nxt;
2059 bt_putid(root->right, 0);
2060 root->min = nxt; // reset lowest used offset and key count
2065 // release and unpin root (bt->page)
2067 bt_unlockpage(BtLockWrite, bt->set);
2068 bt_unpinlatch (bt->set);
2069 bt_unpinpool (bt->pool);
2073 // split already locked full node
2074 // return unlocked and unpinned.
2076 BTERR bt_splitpage (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no)
2078 uint slot, cnt, idx, max, nxt = bt->mgr->page_size;
2079 unsigned char rightkey[256], leftkey[256];
2080 uint tod = time(NULL);
2081 uint lvl = page->lvl;
2085 // initialize frame buffer for right node
2087 memset (bt->frame, 0, bt->mgr->page_size);
2092 // split higher half of keys to bt->frame
2094 while( cnt++ < max ) {
2095 key = keyptr(page, cnt);
2096 nxt -= key->len + 1;
2097 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
2098 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
2099 if( !(slotptr(bt->frame, idx)->dead = slotptr(page, cnt)->dead) )
2101 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
2102 slotptr(bt->frame, idx)->off = nxt;
2105 // transfer right link node to new right node
2107 if( page_no > ROOT_page )
2108 memcpy (bt->frame->right, page->right, BtId);
2110 bt->frame->bits = bt->mgr->page_bits;
2111 bt->frame->min = nxt;
2112 bt->frame->cnt = idx;
2113 bt->frame->lvl = lvl;
2115 // get new free page and write right frame to it.
2117 if( !(new_page = bt_newpage(bt, bt->frame)) )
2120 // remember fence key for new right page to add
2121 // as right sibling to the left node
2123 key = keyptr(bt->frame, idx);
2124 memcpy (rightkey, key, key->len + 1);
2126 // update lower keys to continue in old page
2128 memcpy (bt->frame, page, bt->mgr->page_size);
2129 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
2130 nxt = bt->mgr->page_size;
2136 // assemble page of smaller keys
2137 // to remain in the old page
2139 while( cnt++ < max / 2 ) {
2140 key = keyptr(bt->frame, cnt);
2141 nxt -= key->len + 1;
2142 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2143 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
2144 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
2146 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2147 slotptr(page, idx)->off = nxt;
2150 // finalize left page and save fence key
2152 memcpy(leftkey, key, key->len + 1);
2156 // link new right page
2158 bt_putid (page->right, new_page);
2160 // if current page is the root page, split it
2162 if( page_no == ROOT_page )
2163 return bt_splitroot (bt, leftkey, new_page);
2165 // obtain ParentModification lock for current page
2167 bt_lockpage (BtLockParent, set);
2169 // release wr lock on our page.
2170 // this will keep out another SMO
2172 bt_unlockpage (BtLockWrite, set);
2174 // insert key for old page (lower keys)
2176 if( bt_insertkey (bt, leftkey + 1, *leftkey, page_no, tod, lvl + 1) )
2179 // switch old parent key from us to our right page
2181 if( bt_insertkey (bt, rightkey + 1, *rightkey, new_page, tod, lvl + 1) )
2186 bt_unlockpage (BtLockParent, set);
2187 bt_unpinlatch (set);
2188 bt_unpinpool (pool);
2192 // Insert new key into the btree at given level.
2194 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod, uint lvl)
2201 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
2202 ptr = keyptr(bt->page, slot);
2206 bt->err = BTERR_ovflw;
2210 // if key already exists, update id and return
2214 if( !keycmp (ptr, key, len) ) {
2215 if( slotptr(page, slot)->dead )
2217 slotptr(page, slot)->dead = 0;
2218 slotptr(page, slot)->tod = tod;
2219 bt_putid(slotptr(page,slot)->id, id);
2220 bt_unlockpage(BtLockWrite, bt->set);
2221 bt_unpinlatch (bt->set);
2222 bt_unpinpool (bt->pool);
2226 // check if page has enough space
2228 if( slot = bt_cleanpage (bt, bt->page, len, slot) )
2231 if( bt_splitpage (bt, bt->page, bt->pool, bt->set, bt->page_no) )
2235 bt_addkeytopage (bt, bt->page, slot, key, len, id, tod);
2237 bt_unlockpage (BtLockWrite, bt->set);
2238 bt_unpinlatch (bt->set);
2239 bt_unpinpool (bt->pool);
2243 // cache page of keys into cursor and return starting slot for given key
2245 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2249 // cache page for retrieval
2250 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
2251 memcpy (bt->cursor, bt->page, bt->mgr->page_size);
2253 bt->cursor_page = bt->page_no;
2255 bt_unlockpage(BtLockRead, bt->set);
2256 bt_unpinlatch (bt->set);
2257 bt_unpinpool (bt->pool);
2261 // return next slot for cursor page
2262 // or slide cursor right into next page
2264 uint bt_nextkey (BtDb *bt, uint slot)
2272 right = bt_getid(bt->cursor->right);
2273 while( slot++ < bt->cursor->cnt )
2274 if( slotptr(bt->cursor,slot)->dead )
2276 else if( right || (slot < bt->cursor->cnt) )
2284 bt->cursor_page = right;
2285 if( pool = bt_pinpool (bt, right) )
2286 page = bt_page (bt, pool, right);
2290 set = bt_pinlatch (bt, right);
2291 bt_lockpage(BtLockRead, set);
2293 memcpy (bt->cursor, page, bt->mgr->page_size);
2295 bt_unlockpage(BtLockRead, set);
2296 bt_unpinlatch (set);
2297 bt_unpinpool (pool);
2304 BtKey bt_key(BtDb *bt, uint slot)
2306 return keyptr(bt->cursor, slot);
2309 uid bt_uid(BtDb *bt, uint slot)
2311 return bt_getid(slotptr(bt->cursor,slot)->id);
2314 uint bt_tod(BtDb *bt, uint slot)
2316 return slotptr(bt->cursor,slot)->tod;
2322 void bt_latchaudit (BtDb *bt)
2324 ushort idx, hashidx;
2331 for( idx = 1; idx < bt->mgr->latchmgr->latchdeployed; idx++ ) {
2332 set = bt->mgr->latchsets + idx;
2333 if( *(ushort *)set->readwr || *(ushort *)set->access || *(ushort *)set->parent ) {
2334 fprintf(stderr, "latchset %d locked for page %6x\n", idx, set->page_no);
2335 *(ushort *)set->readwr = 0;
2336 *(ushort *)set->access = 0;
2337 *(ushort *)set->parent = 0;
2340 fprintf(stderr, "latchset %d pinned\n", idx);
2345 for( hashidx = 0; hashidx < bt->mgr->latchmgr->latchhash; hashidx++ ) {
2346 if( *(uint *)bt->mgr->latchmgr->table[hashidx].latch )
2347 fprintf(stderr, "latchmgr locked\n");
2348 if( idx = bt->mgr->latchmgr->table[hashidx].slot ) do {
2349 set = bt->mgr->latchsets + idx;
2350 if( *(uint *)set->readwr || *(ushort *)set->access || *(ushort *)set->parent )
2351 fprintf(stderr, "latchset %d locked\n", idx);
2352 if( set->hash != hashidx )
2353 fprintf(stderr, "latchset %d wrong hashidx\n", idx);
2355 fprintf(stderr, "latchset %d pinned\n", idx);
2356 } while( idx = set->next );
2358 page_no = bt_getid(bt->mgr->latchmgr->alloc[1].right);
2361 fprintf(stderr, "free: %.6x\n", (uint)page_no);
2362 pool = bt_pinpool (bt, page_no);
2363 page = bt_page (bt, pool, page_no);
2364 page_no = bt_getid(page->right);
2365 bt_unpinpool (pool);
2377 // standalone program to index file of keys
2378 // then list them onto std-out
2381 void *index_file (void *arg)
2383 uint __stdcall index_file (void *arg)
2386 int line = 0, found = 0, cnt = 0;
2387 uid next, page_no = LEAF_page; // start on first page of leaves
2388 unsigned char key[256];
2389 ThreadArg *args = arg;
2390 int ch, len = 0, slot;
2399 bt = bt_open (args->mgr);
2402 switch(args->type | 0x20)
2405 fprintf(stderr, "started latch mgr audit\n");
2407 fprintf(stderr, "finished latch mgr audit\n");
2411 fprintf(stderr, "started indexing for %s\n", args->infile);
2412 if( in = fopen (args->infile, "rb") )
2413 while( ch = getc(in), ch != EOF )
2418 if( args->num == 1 )
2419 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2421 else if( args->num )
2422 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2424 if( bt_insertkey (bt, key, len, line, *tod, 0) )
2425 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2428 else if( len < 255 )
2430 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
2434 fprintf(stderr, "started deleting keys for %s\n", args->infile);
2435 if( in = fopen (args->infile, "rb") )
2436 while( ch = getc(in), ch != EOF )
2440 if( args->num == 1 )
2441 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2443 else if( args->num )
2444 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2446 if( bt_deletekey (bt, key, len) )
2447 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2450 else if( len < 255 )
2452 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2456 fprintf(stderr, "started finding keys for %s\n", args->infile);
2457 if( in = fopen (args->infile, "rb") )
2458 while( ch = getc(in), ch != EOF )
2462 if( args->num == 1 )
2463 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2465 else if( args->num )
2466 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2468 if( bt_findkey (bt, key, len) )
2471 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2474 else if( len < 255 )
2476 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2482 fprintf(stderr, "started reading\n");
2484 if( slot = bt_startkey (bt, key, len) )
2487 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
2489 while( slot = bt_nextkey (bt, slot) ) {
2490 ptr = bt_key(bt, slot);
2491 fwrite (ptr->key, ptr->len, 1, stdout);
2492 fputc ('\n', stdout);
2498 fprintf(stderr, "started reading\n");
2501 if( pool = bt_pinpool (bt, page_no) )
2502 page = bt_page (bt, pool, page_no);
2505 set = bt_pinlatch (bt, page_no);
2506 bt_lockpage (BtLockRead, set);
2508 next = bt_getid (page->right);
2509 bt_unlockpage (BtLockRead, set);
2510 bt_unpinlatch (set);
2511 bt_unpinpool (pool);
2512 } while( page_no = next );
2514 cnt--; // remove stopper key
2515 fprintf(stderr, " Total keys read %d\n", cnt);
2527 typedef struct timeval timer;
2529 int main (int argc, char **argv)
2531 int idx, cnt, len, slot, err;
2532 int segsize, bits = 16;
2537 time_t start[1], stop[1];
2550 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]);
2551 fprintf (stderr, " where page_bits is the page size in bits\n");
2552 fprintf (stderr, " mapped_segments is the number of mmap segments in buffer pool\n");
2553 fprintf (stderr, " seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2554 fprintf (stderr, " line_numbers = 1 to append line numbers to keys\n");
2555 fprintf (stderr, " src_file1 thru src_filen are files of keys separated by newline\n");
2560 gettimeofday(&start, NULL);
2566 bits = atoi(argv[3]);
2569 poolsize = atoi(argv[4]);
2572 fprintf (stderr, "Warning: no mapped_pool\n");
2574 if( poolsize > 65535 )
2575 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2578 segsize = atoi(argv[5]);
2580 segsize = 4; // 16 pages per mmap segment
2583 num = atoi(argv[6]);
2587 threads = malloc (cnt * sizeof(pthread_t));
2589 threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2591 args = malloc (cnt * sizeof(ThreadArg));
2593 mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2596 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2602 for( idx = 0; idx < cnt; idx++ ) {
2603 args[idx].infile = argv[idx + 7];
2604 args[idx].type = argv[2][0];
2605 args[idx].mgr = mgr;
2606 args[idx].num = num;
2607 args[idx].idx = idx;
2609 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2610 fprintf(stderr, "Error creating thread %d\n", err);
2612 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2616 // wait for termination
2619 for( idx = 0; idx < cnt; idx++ )
2620 pthread_join (threads[idx], NULL);
2621 gettimeofday(&stop, NULL);
2622 real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2624 WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2626 for( idx = 0; idx < cnt; idx++ )
2627 CloseHandle(threads[idx]);
2630 real_time = 1000 * (*stop - *start);
2632 fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);