1 // btree version threads2j linux futex concurrency 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
28 #include <linux/futex.h>
43 #define WIN32_LEAN_AND_MEAN
56 typedef unsigned long long uid;
59 typedef unsigned long long off64_t;
60 typedef unsigned short ushort;
61 typedef unsigned int uint;
64 #define BT_ro 0x6f72 // ro
65 #define BT_rw 0x7772 // rw
67 #define BT_latchtable 128 // number of latch manager slots
69 #define BT_maxbits 24 // maximum page size in bits
70 #define BT_minbits 9 // minimum page size in bits
71 #define BT_minpage (1 << BT_minbits) // minimum page size
72 #define BT_maxpage (1 << BT_maxbits) // maximum page size
75 There are five lock types for each node in three independent sets:
76 1. (set 1) AccessIntent: Sharable. Going to Read the node. Incompatible with NodeDelete.
77 2. (set 1) NodeDelete: Exclusive. About to release the node. Incompatible with AccessIntent.
78 3. (set 2) ReadLock: Sharable. Read the node. Incompatible with WriteLock.
79 4. (set 2) WriteLock: Exclusive. Modify the node. Incompatible with ReadLock and other WriteLocks.
80 5. (set 3) ParentModification: Exclusive. Change the node's parent keys. Incompatible with another ParentModification.
91 // mode & definition for latch implementation
94 Mutex = 1 << 0, // the mutex bit
95 Write = 1 << 1, // the writers bit
96 Share = 1 << 2, // reader count
97 PendRd = 1 << 12, // reader contended count
98 PendWr = 1 << 22 // writer contended count
102 QueRd = 1, // reader queue
103 QueWr = 2 // writer queue
106 // share is count of read accessors
107 // grant write lock when share == 0
110 volatile uint mutex:1; // 1 = busy
111 volatile uint write:1; // 1 = exclusive
112 volatile uint share:10; // count of readers holding locks
113 volatile uint readwait:10; // count of readers waiting
114 volatile uint writewait:10; // count of writers waiting
117 // Define the length of the page and key pointers
121 // Page key slot definition.
123 // If BT_maxbits is 15 or less, you can save 4 bytes
124 // for each key stored by making the first two uints
125 // into ushorts. You can also save 4 bytes by removing
126 // the tod field from the key.
128 // Keys are marked dead, but remain on the page until
129 // it cleanup is called. The fence key (highest key) for
130 // the page is always present, even after cleanup.
133 uint off:BT_maxbits; // page offset for key start
134 uint dead:1; // set for deleted key
135 uint tod; // time-stamp for key
136 unsigned char id[BtId]; // id associated with key
139 // The key structure occupies space at the upper end of
140 // each page. It's a length byte followed by the value
145 unsigned char key[1];
148 // The first part of an index page.
149 // It is immediately followed
150 // by the BtSlot array of keys.
152 typedef struct Page {
153 uint cnt; // count of keys in page
154 uint act; // count of active keys
155 uint min; // next key offset
156 unsigned char bits; // page size in bits
157 unsigned char lvl:6; // level of page
158 unsigned char kill:1; // page is being deleted
159 unsigned char dirty:1; // page has deleted keys
160 unsigned char right[BtId]; // page number to right
161 BtSlot table[0]; // array of key slots
164 // hash table entries
168 volatile ushort slot; // Latch table entry at head of chain
171 // latch manager table structure
174 BtLatch readwr[1]; // read/write page lock
175 BtLatch access[1]; // Access Intent/Page delete
176 BtLatch parent[1]; // adoption of foster children
177 BtLatch busy[1]; // slot is being moved between chains
178 volatile ushort next; // next entry in hash table chain
179 volatile ushort prev; // prev entry in hash table chain
180 volatile ushort pin; // number of outstanding locks
181 volatile ushort hash; // hash slot entry is under
182 volatile uid page_no; // latch set page number
185 // The memory mapping pool table buffer manager entry
188 unsigned long long int lru; // number of times accessed
189 uid basepage; // mapped base page number
190 char *map; // mapped memory pointer
191 ushort slot; // slot index in this array
192 ushort pin; // mapped page pin counter
193 void *hashprev; // previous pool entry for the same hash idx
194 void *hashnext; // next pool entry for the same hash idx
196 HANDLE hmap; // Windows memory mapping handle
200 // structure for latch manager on ALLOC_page
203 struct Page alloc[2]; // next & free page_nos in right ptr
204 BtLatch lock[1]; // allocation area lite latch
205 ushort latchdeployed; // highest number of latch entries deployed
206 ushort nlatchpage; // number of latch pages at BT_latch
207 ushort latchtotal; // number of page latch entries
208 ushort latchhash; // number of latch hash table slots
209 ushort latchvictim; // next latch entry to examine
210 BtHashEntry table[0]; // the hash table
213 // The object structure for Btree access
216 uint page_size; // page size
217 uint page_bits; // page size in bits
218 uint seg_bits; // seg size in pages in bits
219 uint mode; // read-write mode
221 char *pooladvise; // bit maps for pool page advisements
226 ushort poolcnt; // highest page pool node in use
227 ushort poolmax; // highest page pool node allocated
228 ushort poolmask; // total number of pages in mmap segment - 1
229 ushort evicted; // last evicted hash table slot
230 ushort hashsize; // size of Hash Table for pool entries
231 ushort *hash; // pool index for hash entries
232 BtLatch *latch; // latches for pool hash slots
233 BtLatchMgr *latchmgr; // mapped latch page from allocation page
234 BtLatchSet *latchsets; // mapped latch set from latch pages
235 BtPool *pool; // memory pool page segments
237 HANDLE halloc; // allocation and latch table handle
242 BtMgr *mgr; // buffer manager for thread
243 BtPage cursor; // cached frame for start/next (never mapped)
244 BtPage frame; // spare frame for the page split (never mapped)
245 BtPage zero; // page of zeroes to extend the file (never mapped)
246 BtPage page; // current page mapped from file
247 uid page_no; // current page number
248 uid cursor_page; // current cursor page number
249 BtLatchSet *set; // current page latchset
250 BtPool *pool; // current page pool
251 unsigned char *mem; // frame, cursor, page memory buffer
252 int found; // last delete or insert was found
253 int err; // last error
267 extern void bt_close (BtDb *bt);
268 extern BtDb *bt_open (BtMgr *mgr);
269 extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod);
270 extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl);
271 extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
272 extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
273 extern uint bt_nextkey (BtDb *bt, uint slot);
276 extern BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolsize, uint segsize, uint hashsize);
277 void bt_mgrclose (BtMgr *mgr);
279 // Helper functions to return slot values
281 extern BtKey bt_key (BtDb *bt, uint slot);
282 extern uid bt_uid (BtDb *bt, uint slot);
283 extern uint bt_tod (BtDb *bt, uint slot);
285 // BTree page number constants
286 #define ALLOC_page 0 // allocation & lock manager hash table
287 #define ROOT_page 1 // root of the btree
288 #define LEAF_page 2 // first page of leaves
289 #define LATCH_page 3 // pages for lock manager
291 // Number of levels to create in a new BTree
295 // The page is allocated from low and hi ends.
296 // The key offsets and row-id's are allocated
297 // from the bottom, while the text of the key
298 // is allocated from the top. When the two
299 // areas meet, the page is split into two.
301 // A key consists of a length byte, two bytes of
302 // index number (0 - 65534), and up to 253 bytes
303 // of key value. Duplicate keys are discarded.
304 // Associated with each key is a 48 bit row-id.
306 // The b-tree root is always located at page 1.
307 // The first leaf page of level zero is always
308 // located on page 2.
310 // The b-tree pages are linked with next
311 // pointers to facilitate enumerators,
312 // and provide for concurrency.
314 // When to root page fills, it is split in two and
315 // the tree height is raised by a new root at page
316 // one with two keys.
318 // Deleted keys are marked with a dead bit until
319 // page cleanup The fence key for a node is always
320 // present, even after deletion and cleanup.
322 // Groups of pages called segments from the btree are optionally
323 // cached with a memory mapped pool. A hash table is used to keep
324 // track of the cached segments. This behaviour is controlled
325 // by the cache block size parameter to bt_open.
327 // To achieve maximum concurrency one page is locked at a time
328 // as the tree is traversed to find leaf key in question. The right
329 // page numbers are used in cases where the page is being split,
332 // Page 0 is dedicated to lock for new page extensions,
333 // and chains empty pages together for reuse.
335 // The ParentModification lock on a node is obtained to prevent resplitting
336 // or deleting a node before its fence is posted into its upper level.
338 // Empty pages are chained together through the ALLOC page and reused.
340 // Access macros to address slot and key values from the page
342 #define slotptr(page, slot) (page->table + slot-1)
343 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
345 void bt_putid(unsigned char *dest, uid id)
350 dest[i] = (unsigned char)id, id >>= 8;
353 uid bt_getid(unsigned char *src)
358 for( i = 0; i < BtId; i++ )
359 id <<= 8, id |= *src++;
366 int sys_futex(void *addr1, int op, int val1, struct timespec *timeout, void *addr2, int val3)
368 return syscall(SYS_futex, addr1, op, val1, timeout, addr2, val3);
371 // wait until write lock mode is clear
372 // and add 1 to the share count
374 void bt_spinreadlock(BtLatch *latch, int private)
379 private = FUTEX_PRIVATE_FLAG;
382 // obtain latch mutex
383 if( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex ) {
388 // wait for writers to clear
389 // increment read waiters and wait
391 if( latch->write || latch->writewait ) {
392 __sync_fetch_and_add ((uint *)latch, PendRd);
393 prev = __sync_fetch_and_and ((uint *)latch, ~Mutex) & ~Mutex;
394 sys_futex( (uint *)latch, FUTEX_WAIT_BITSET | private, prev, NULL, NULL, QueRd );
395 __sync_fetch_and_sub ((uint *)latch, PendRd);
399 // increment reader lock count
400 // and release latch mutex
402 __sync_fetch_and_add ((uint *)latch, Share);
403 __sync_fetch_and_and ((uint *)latch, ~Mutex);
408 // wait for other read and write latches to relinquish
410 void bt_spinwritelock(BtLatch *latch, int private)
415 private = FUTEX_PRIVATE_FLAG;
418 // obtain latch mutex
419 if( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex ) {
424 // wait for write and reader count to clear
426 if( latch->write || latch->share ) {
427 __sync_fetch_and_add ((uint *)latch, PendWr);
428 prev = __sync_fetch_and_and ((uint *)latch, ~Mutex) & ~Mutex;
429 sys_futex( (uint *)latch, FUTEX_WAIT_BITSET | private, prev, NULL, NULL, QueWr );
430 __sync_fetch_and_sub ((uint *)latch, PendWr);
435 // release latch mutex
437 __sync_fetch_and_or ((uint *)latch, Write);
438 __sync_fetch_and_and ((uint *)latch, ~Mutex);
443 // try to obtain write lock
445 // return 1 if obtained,
448 int bt_spinwritetry(BtLatch *latch)
453 // abandon request if not taken
455 if( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex )
458 // see if write mode is available
460 if( !latch->write && !latch->share ) {
461 __sync_fetch_and_or ((uint *)latch, Write);
466 // release latch mutex
468 __sync_fetch_and_and ((uint *)latch, ~Mutex);
474 void bt_spinreleasewrite(BtLatch *latch, int private)
477 private = FUTEX_PRIVATE_FLAG;
479 // obtain latch mutex
481 while( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex )
484 __sync_fetch_and_and ((uint *)latch, ~Write);
488 if( latch->writewait )
489 if( sys_futex( (uint *)latch, FUTEX_WAKE_BITSET | private, 1, NULL, NULL, QueWr ) )
492 if( latch->readwait )
493 sys_futex( (uint *)latch, FUTEX_WAKE_BITSET | private, INT_MAX, NULL, NULL, QueRd );
495 // release latch mutex
498 __sync_fetch_and_and ((uint *)latch, ~Mutex);
501 // decrement reader count
503 void bt_spinreleaseread(BtLatch *latch, int private)
506 private = FUTEX_PRIVATE_FLAG;
508 // obtain latch mutex
510 while( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex )
513 __sync_fetch_and_sub ((uint *)latch, Share);
515 // wake waiting writers
517 if( !latch->share && latch->writewait )
518 sys_futex( (uint *)latch, FUTEX_WAKE_BITSET | private, 1, NULL, NULL, QueWr );
520 // release latch mutex
522 __sync_fetch_and_and ((uint *)latch, ~Mutex);
525 // link latch table entry into latch hash table
527 void bt_latchlink (BtDb *bt, ushort hashidx, ushort victim, uid page_no)
529 BtLatchSet *set = bt->mgr->latchsets + victim;
531 if( set->next = bt->mgr->latchmgr->table[hashidx].slot )
532 bt->mgr->latchsets[set->next].prev = victim;
534 bt->mgr->latchmgr->table[hashidx].slot = victim;
535 set->page_no = page_no;
542 void bt_unpinlatch (BtLatchSet *set)
545 __sync_fetch_and_add(&set->pin, -1);
547 _InterlockedDecrement16 (&set->pin);
551 // find existing latchset or inspire new one
552 // return with latchset pinned
554 BtLatchSet *bt_pinlatch (BtDb *bt, uid page_no)
556 ushort hashidx = page_no % bt->mgr->latchmgr->latchhash;
557 ushort slot, avail = 0, victim, idx;
560 // obtain read lock on hash table entry
562 bt_spinreadlock(bt->mgr->latchmgr->table[hashidx].latch, 0);
564 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
566 set = bt->mgr->latchsets + slot;
567 if( page_no == set->page_no )
569 } while( slot = set->next );
573 __sync_fetch_and_add(&set->pin, 1);
575 _InterlockedIncrement16 (&set->pin);
579 bt_spinreleaseread (bt->mgr->latchmgr->table[hashidx].latch, 0);
584 // try again, this time with write lock
586 bt_spinwritelock(bt->mgr->latchmgr->table[hashidx].latch, 0);
588 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
590 set = bt->mgr->latchsets + slot;
591 if( page_no == set->page_no )
593 if( !set->pin && !avail )
595 } while( slot = set->next );
597 // found our entry, or take over an unpinned one
599 if( slot || (slot = avail) ) {
600 set = bt->mgr->latchsets + slot;
602 __sync_fetch_and_add(&set->pin, 1);
604 _InterlockedIncrement16 (&set->pin);
606 set->page_no = page_no;
607 bt_spinreleasewrite(bt->mgr->latchmgr->table[hashidx].latch, 0);
611 // see if there are any unused entries
613 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, 1) + 1;
615 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchdeployed);
618 if( victim < bt->mgr->latchmgr->latchtotal ) {
619 set = bt->mgr->latchsets + victim;
621 __sync_fetch_and_add(&set->pin, 1);
623 _InterlockedIncrement16 (&set->pin);
625 bt_latchlink (bt, hashidx, victim, page_no);
626 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch, 0);
631 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, -1);
633 victim = _InterlockedDecrement16 (&bt->mgr->latchmgr->latchdeployed);
635 // find and reuse previous lock entry
639 victim = __sync_fetch_and_add(&bt->mgr->latchmgr->latchvictim, 1);
641 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchvictim) - 1;
643 // we don't use slot zero
645 if( victim %= bt->mgr->latchmgr->latchtotal )
646 set = bt->mgr->latchsets + victim;
650 // take control of our slot
651 // from other threads
653 if( set->pin || !bt_spinwritetry (set->busy) )
658 // try to get write lock on hash chain
659 // skip entry if not obtained
660 // or has outstanding locks
662 if( !bt_spinwritetry (bt->mgr->latchmgr->table[idx].latch) ) {
663 bt_spinreleasewrite (set->busy, 0);
668 bt_spinreleasewrite (set->busy, 0);
669 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch, 0);
673 // unlink our available victim from its hash chain
676 bt->mgr->latchsets[set->prev].next = set->next;
678 bt->mgr->latchmgr->table[idx].slot = set->next;
681 bt->mgr->latchsets[set->next].prev = set->prev;
683 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch, 0);
685 __sync_fetch_and_add(&set->pin, 1);
687 _InterlockedIncrement16 (&set->pin);
689 bt_latchlink (bt, hashidx, victim, page_no);
690 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch, 0);
691 bt_spinreleasewrite (set->busy, 0);
696 void bt_mgrclose (BtMgr *mgr)
701 // release mapped pages
702 // note that slot zero is never used
704 for( slot = 1; slot < mgr->poolmax; slot++ ) {
705 pool = mgr->pool + slot;
708 munmap (pool->map, (mgr->poolmask+1) << mgr->page_bits);
711 FlushViewOfFile(pool->map, 0);
712 UnmapViewOfFile(pool->map);
713 CloseHandle(pool->hmap);
719 munmap (mgr->latchsets, mgr->latchmgr->nlatchpage * mgr->page_size);
720 munmap (mgr->latchmgr, mgr->page_size);
722 FlushViewOfFile(mgr->latchmgr, 0);
723 UnmapViewOfFile(mgr->latchmgr);
724 CloseHandle(mgr->halloc);
731 free (mgr->pooladvise);
734 FlushFileBuffers(mgr->idx);
735 CloseHandle(mgr->idx);
736 GlobalFree (mgr->pool);
737 GlobalFree (mgr->hash);
738 GlobalFree (mgr->latch);
743 // close and release memory
745 void bt_close (BtDb *bt)
752 VirtualFree (bt->mem, 0, MEM_RELEASE);
757 // open/create new btree buffer manager
759 // call with file_name, BT_openmode, bits in page size (e.g. 16),
760 // size of mapped page pool (e.g. 8192)
762 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
764 uint lvl, attr, cacheblk, last, slot, idx;
765 uint nlatchpage, latchhash;
766 BtLatchMgr *latchmgr;
773 SYSTEM_INFO sysinfo[1];
776 // determine sanity of page size and buffer pool
778 if( bits > BT_maxbits )
780 else if( bits < BT_minbits )
784 return NULL; // must have buffer pool
787 mgr = calloc (1, sizeof(BtMgr));
788 mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
791 return free(mgr), NULL;
793 cacheblk = 4096; // minimum mmap segment size for unix
796 mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
797 attr = FILE_ATTRIBUTE_NORMAL;
798 mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
800 if( mgr->idx == INVALID_HANDLE_VALUE )
801 return GlobalFree(mgr), NULL;
803 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
804 GetSystemInfo(sysinfo);
805 cacheblk = sysinfo->dwAllocationGranularity;
809 latchmgr = malloc (BT_maxpage);
812 // read minimum page size to get root info
814 if( size = lseek (mgr->idx, 0L, 2) ) {
815 if( pread(mgr->idx, latchmgr, BT_minpage, 0) == BT_minpage )
816 bits = latchmgr->alloc->bits;
818 return free(mgr), free(latchmgr), NULL;
819 } else if( mode == BT_ro )
820 return free(latchmgr), free (mgr), NULL;
822 latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
823 size = GetFileSize(mgr->idx, amt);
826 if( !ReadFile(mgr->idx, (char *)latchmgr, BT_minpage, amt, NULL) )
827 return bt_mgrclose (mgr), NULL;
828 bits = latchmgr->alloc->bits;
829 } else if( mode == BT_ro )
830 return bt_mgrclose (mgr), NULL;
833 mgr->page_size = 1 << bits;
834 mgr->page_bits = bits;
836 mgr->poolmax = poolmax;
839 if( cacheblk < mgr->page_size )
840 cacheblk = mgr->page_size;
842 // mask for partial memmaps
844 mgr->poolmask = (cacheblk >> bits) - 1;
846 // see if requested size of pages per memmap is greater
848 if( (1 << segsize) > mgr->poolmask )
849 mgr->poolmask = (1 << segsize) - 1;
853 while( (1 << mgr->seg_bits) <= mgr->poolmask )
856 mgr->hashsize = hashsize;
859 mgr->pool = calloc (poolmax, sizeof(BtPool));
860 mgr->hash = calloc (hashsize, sizeof(ushort));
861 mgr->latch = calloc (hashsize, sizeof(BtLatch));
862 mgr->pooladvise = calloc (poolmax, (mgr->poolmask + 8) / 8);
864 mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * sizeof(BtPool));
865 mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
866 mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtLatch));
872 // initialize an empty b-tree with latch page, root page, page of leaves
873 // and page(s) of latches
875 memset (latchmgr, 0, 1 << bits);
876 nlatchpage = BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1;
877 bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
878 latchmgr->alloc->bits = mgr->page_bits;
880 latchmgr->nlatchpage = nlatchpage;
881 latchmgr->latchtotal = nlatchpage * (mgr->page_size / sizeof(BtLatchSet));
883 // initialize latch manager
885 latchhash = (mgr->page_size - sizeof(BtLatchMgr)) / sizeof(BtHashEntry);
887 // size of hash table = total number of latchsets
889 if( latchhash > latchmgr->latchtotal )
890 latchhash = latchmgr->latchtotal;
892 latchmgr->latchhash = latchhash;
895 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
896 return bt_mgrclose (mgr), NULL;
898 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
899 return bt_mgrclose (mgr), NULL;
901 if( *amt < mgr->page_size )
902 return bt_mgrclose (mgr), NULL;
905 memset (latchmgr, 0, 1 << bits);
906 latchmgr->alloc->bits = mgr->page_bits;
908 for( lvl=MIN_lvl; lvl--; ) {
909 slotptr(latchmgr->alloc, 1)->off = mgr->page_size - 3;
910 bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
911 key = keyptr(latchmgr->alloc, 1);
912 key->len = 2; // create stopper key
915 latchmgr->alloc->min = mgr->page_size - 3;
916 latchmgr->alloc->lvl = lvl;
917 latchmgr->alloc->cnt = 1;
918 latchmgr->alloc->act = 1;
920 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
921 return bt_mgrclose (mgr), NULL;
923 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
924 return bt_mgrclose (mgr), NULL;
926 if( *amt < mgr->page_size )
927 return bt_mgrclose (mgr), NULL;
931 // clear out latch manager locks
932 // and rest of pages to round out segment
934 memset(latchmgr, 0, mgr->page_size);
937 while( last <= ((MIN_lvl + 1 + nlatchpage) | mgr->poolmask) ) {
939 pwrite(mgr->idx, latchmgr, mgr->page_size, last << mgr->page_bits);
941 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
942 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
943 return bt_mgrclose (mgr), NULL;
944 if( *amt < mgr->page_size )
945 return bt_mgrclose (mgr), NULL;
952 flag = PROT_READ | PROT_WRITE;
953 mgr->latchmgr = mmap (0, mgr->page_size, flag, MAP_SHARED, mgr->idx, ALLOC_page * mgr->page_size);
954 if( mgr->latchmgr == MAP_FAILED )
955 return bt_mgrclose (mgr), NULL;
956 mgr->latchsets = (BtLatchSet *)mmap (0, mgr->latchmgr->nlatchpage * mgr->page_size, flag, MAP_SHARED, mgr->idx, LATCH_page * mgr->page_size);
957 if( mgr->latchsets == MAP_FAILED )
958 return bt_mgrclose (mgr), NULL;
960 flag = PAGE_READWRITE;
961 mgr->halloc = CreateFileMapping(mgr->idx, NULL, flag, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size, NULL);
963 return bt_mgrclose (mgr), NULL;
965 flag = FILE_MAP_WRITE;
966 mgr->latchmgr = MapViewOfFile(mgr->halloc, flag, 0, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size);
968 return GetLastError(), bt_mgrclose (mgr), NULL;
970 mgr->latchsets = (void *)((char *)mgr->latchmgr + LATCH_page * mgr->page_size);
976 VirtualFree (latchmgr, 0, MEM_RELEASE);
981 // open BTree access method
982 // based on buffer manager
984 BtDb *bt_open (BtMgr *mgr)
986 BtDb *bt = malloc (sizeof(*bt));
988 memset (bt, 0, sizeof(*bt));
991 bt->mem = malloc (3 *mgr->page_size);
993 bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
995 bt->frame = (BtPage)bt->mem;
996 bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
997 bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
999 memset (bt->zero, 0, mgr->page_size);
1003 // compare two keys, returning > 0, = 0, or < 0
1004 // as the comparison value
1006 int keycmp (BtKey key1, unsigned char *key2, uint len2)
1008 uint len1 = key1->len;
1011 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
1024 // find segment in pool
1025 // must be called with hashslot idx locked
1026 // return NULL if not there
1027 // otherwise return node
1029 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
1034 // compute start of hash chain in pool
1036 if( slot = bt->mgr->hash[idx] )
1037 pool = bt->mgr->pool + slot;
1041 page_no &= ~bt->mgr->poolmask;
1043 while( pool->basepage != page_no )
1044 if( pool = pool->hashnext )
1052 // add segment to hash table
1054 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
1059 pool->hashprev = pool->hashnext = NULL;
1060 pool->basepage = page_no & ~bt->mgr->poolmask;
1063 if( slot = bt->mgr->hash[idx] ) {
1064 node = bt->mgr->pool + slot;
1065 pool->hashnext = node;
1066 node->hashprev = pool;
1069 bt->mgr->hash[idx] = pool->slot;
1072 // find best segment to evict from buffer pool
1074 BtPool *bt_findlru (BtDb *bt, uint hashslot)
1076 unsigned long long int target = ~0LL;
1077 BtPool *pool = NULL, *node;
1082 node = bt->mgr->pool + hashslot;
1084 // scan pool entries under hash table slot
1089 if( node->lru > target )
1093 } while( node = node->hashnext );
1098 // map new buffer pool segment to virtual memory
1100 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
1102 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
1103 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
1107 flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
1108 pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED, bt->mgr->idx, off);
1109 if( pool->map == MAP_FAILED )
1110 return bt->err = BTERR_map;
1112 // clear out madvise issued bits
1113 memset (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8) / 8), 0, (bt->mgr->poolmask + 8)/8);
1115 flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
1116 pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
1118 return bt->err = BTERR_map;
1120 flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
1121 pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1123 return bt->err = BTERR_map;
1128 // calculate page within pool
1130 BtPage bt_page (BtDb *bt, BtPool *pool, uid page_no)
1132 uint subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1135 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1138 uint idx = subpage / 8;
1139 uint bit = subpage % 8;
1141 if( ~((bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] >> bit) & 1 ) {
1142 madvise (page, bt->mgr->page_size, MADV_WILLNEED);
1143 (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] |= 1 << bit;
1152 void bt_unpinpool (BtPool *pool)
1155 __sync_fetch_and_add(&pool->pin, -1);
1157 _InterlockedDecrement16 (&pool->pin);
1161 // find or place requested page in segment-pool
1162 // return pool table entry, incrementing pin
1164 BtPool *bt_pinpool(BtDb *bt, uid page_no)
1166 BtPool *pool, *node, *next;
1167 uint slot, idx, victim;
1169 // lock hash table chain
1171 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1172 bt_spinreadlock (&bt->mgr->latch[idx], 1);
1174 // look up in hash table
1176 if( pool = bt_findpool(bt, page_no, idx) ) {
1178 __sync_fetch_and_add(&pool->pin, 1);
1180 _InterlockedIncrement16 (&pool->pin);
1182 bt_spinreleaseread (&bt->mgr->latch[idx], 1);
1187 // upgrade to write lock
1189 bt_spinreleaseread (&bt->mgr->latch[idx], 1);
1190 bt_spinwritelock (&bt->mgr->latch[idx], 1);
1192 // try to find page in pool with write lock
1194 if( pool = bt_findpool(bt, page_no, idx) ) {
1196 __sync_fetch_and_add(&pool->pin, 1);
1198 _InterlockedIncrement16 (&pool->pin);
1200 bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
1205 // allocate a new pool node
1206 // and add to hash table
1209 slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
1211 slot = _InterlockedIncrement16 (&bt->mgr->poolcnt) - 1;
1214 if( ++slot < bt->mgr->poolmax ) {
1215 pool = bt->mgr->pool + slot;
1218 if( bt_mapsegment(bt, pool, page_no) )
1221 bt_linkhash(bt, pool, page_no, idx);
1223 __sync_fetch_and_add(&pool->pin, 1);
1225 _InterlockedIncrement16 (&pool->pin);
1227 bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
1231 // pool table is full
1232 // find best pool entry to evict
1235 __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
1237 _InterlockedDecrement16 (&bt->mgr->poolcnt);
1242 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
1244 victim = _InterlockedIncrement16 (&bt->mgr->evicted) - 1;
1246 victim %= bt->mgr->hashsize;
1248 // try to get write lock
1249 // skip entry if not obtained
1251 if( !bt_spinwritetry (&bt->mgr->latch[victim]) )
1254 // if pool entry is empty
1255 // or any pages are pinned
1258 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
1259 bt_spinreleasewrite (&bt->mgr->latch[victim], 1);
1263 // unlink victim pool node from hash table
1265 if( node = pool->hashprev )
1266 node->hashnext = pool->hashnext;
1267 else if( node = pool->hashnext )
1268 bt->mgr->hash[victim] = node->slot;
1270 bt->mgr->hash[victim] = 0;
1272 if( node = pool->hashnext )
1273 node->hashprev = pool->hashprev;
1275 bt_spinreleasewrite (&bt->mgr->latch[victim], 1);
1277 // remove old file mapping
1279 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1281 FlushViewOfFile(pool->map, 0);
1282 UnmapViewOfFile(pool->map);
1283 CloseHandle(pool->hmap);
1287 // create new pool mapping
1288 // and link into hash table
1290 if( bt_mapsegment(bt, pool, page_no) )
1293 bt_linkhash(bt, pool, page_no, idx);
1295 __sync_fetch_and_add(&pool->pin, 1);
1297 _InterlockedIncrement16 (&pool->pin);
1299 bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
1304 // place write, read, or parent lock on requested page_no.
1306 void bt_lockpage(BtLock mode, BtLatchSet *set)
1310 bt_spinreadlock (set->readwr, 0);
1313 bt_spinwritelock (set->readwr, 0);
1316 bt_spinreadlock (set->access, 0);
1319 bt_spinwritelock (set->access, 0);
1322 bt_spinwritelock (set->parent, 0);
1327 // remove write, read, or parent lock on requested page
1329 void bt_unlockpage(BtLock mode, BtLatchSet *set)
1333 bt_spinreleaseread (set->readwr, 0);
1336 bt_spinreleasewrite (set->readwr, 0);
1339 bt_spinreleaseread (set->access, 0);
1342 bt_spinreleasewrite (set->access, 0);
1345 bt_spinreleasewrite (set->parent, 0);
1350 // allocate a new page and write page into it
1352 uid bt_newpage(BtDb *bt, BtPage page)
1360 // lock allocation page
1362 bt_spinwritelock(bt->mgr->latchmgr->lock, 0);
1364 // use empty chain first
1365 // else allocate empty page
1367 if( new_page = bt_getid(bt->mgr->latchmgr->alloc[1].right) ) {
1368 if( pool = bt_pinpool (bt, new_page) )
1369 pmap = bt_page (bt, pool, new_page);
1372 bt_putid(bt->mgr->latchmgr->alloc[1].right, bt_getid(pmap->right));
1373 bt_unpinpool (pool);
1376 new_page = bt_getid(bt->mgr->latchmgr->alloc->right);
1377 bt_putid(bt->mgr->latchmgr->alloc->right, new_page+1);
1381 if ( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1382 return bt->err = BTERR_wrt, 0;
1384 // if writing first page of pool block, zero last page in the block
1386 if ( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1388 // use zero buffer to write zeros
1389 memset(bt->zero, 0, bt->mgr->page_size);
1390 if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1391 return bt->err = BTERR_wrt, 0;
1394 // bring new page into pool and copy page.
1395 // this will extend the file into the new pages.
1397 if( pool = bt_pinpool (bt, new_page) )
1398 pmap = bt_page (bt, pool, new_page);
1402 memcpy(pmap, page, bt->mgr->page_size);
1403 bt_unpinpool (pool);
1405 // unlock allocation latch and return new page no
1407 bt_spinreleasewrite(bt->mgr->latchmgr->lock, 0);
1411 // find slot in page for given key at a given level
1413 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1415 uint diff, higher = bt->page->cnt, low = 1, slot;
1418 // make stopper key an infinite fence value
1420 if( bt_getid (bt->page->right) )
1425 // low is the next candidate, higher is already
1426 // tested as .ge. the given key, loop ends when they meet
1428 while( diff = higher - low ) {
1429 slot = low + ( diff >> 1 );
1430 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1433 higher = slot, good++;
1436 // return zero if key is on right link page
1438 return good ? higher : 0;
1441 // find and load page at given level for given key
1442 // leave page rd or wr locked as requested
1444 int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, uint lock)
1446 uid page_no = ROOT_page, prevpage = 0;
1447 BtLatchSet *set, *prevset;
1448 uint drill = 0xff, slot;
1449 uint mode, prevmode;
1452 // start at root of btree and drill down
1457 // determine lock mode of drill level
1458 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1460 bt->set = bt_pinlatch (bt, page_no);
1461 bt->page_no = page_no;
1463 // pin page contents
1465 if( bt->pool = bt_pinpool (bt, page_no) )
1466 bt->page = bt_page (bt, bt->pool, page_no);
1470 // obtain access lock using lock chaining with Access mode
1472 if( page_no > ROOT_page )
1473 bt_lockpage(BtLockAccess, bt->set);
1475 // release & unpin parent page
1478 bt_unlockpage(prevmode, prevset);
1479 bt_unpinlatch (prevset);
1480 bt_unpinpool (prevpool);
1484 // obtain read lock using lock chaining
1486 bt_lockpage(mode, bt->set);
1488 if( page_no > ROOT_page )
1489 bt_unlockpage(BtLockAccess, bt->set);
1491 // re-read and re-lock root after determining actual level of root
1493 if( bt->page->lvl != drill) {
1494 if ( bt->page_no != ROOT_page )
1495 return bt->err = BTERR_struct, 0;
1497 drill = bt->page->lvl;
1499 if( lock == BtLockWrite && drill == lvl ) {
1500 bt_unlockpage(mode, bt->set);
1501 bt_unpinlatch (bt->set);
1502 bt_unpinpool (bt->pool);
1507 // find key on page at this level
1508 // and descend to requested level
1510 if( !bt->page->kill && (slot = bt_findslot (bt, key, len)) ) {
1514 while( slotptr(bt->page, slot)->dead )
1515 if( slot++ < bt->page->cnt )
1518 page_no = bt_getid(bt->page->right);
1522 page_no = bt_getid(slotptr(bt->page, slot)->id);
1526 // or slide right into next page
1527 // (slide left from deleted page)
1530 page_no = bt_getid(bt->page->right);
1532 // continue down / right using overlapping locks
1533 // to protect pages being killed or split.
1536 prevpage = bt->page_no;
1537 prevpool = bt->pool;
1542 // return error on end of right chain
1544 bt->err = BTERR_struct;
1545 return 0; // return error
1548 // find and delete key on page by marking delete flag bit
1549 // when page becomes empty, delete it
1551 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl)
1553 unsigned char lowerkey[256], higherkey[256];
1554 BtLatchSet *rset, *set;
1555 BtPool *pool, *rpool;
1561 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1562 ptr = keyptr(bt->page, slot);
1566 // if key is found delete it, otherwise ignore request
1568 if( bt->found = !keycmp (ptr, key, len) )
1569 if( bt->found = slotptr(bt->page, slot)->dead == 0 ) {
1570 slotptr(bt->page,slot)->dead = 1;
1571 if( slot < bt->page->cnt )
1572 bt->page->dirty = 1;
1576 // return if page is not empty, or it has no right sibling
1578 right = bt_getid(bt->page->right);
1579 page_no = bt->page_no;
1583 if( !right || bt->page->act ) {
1584 bt_unlockpage(BtLockWrite, set);
1585 bt_unpinlatch (set);
1586 bt_unpinpool (pool);
1590 // obtain Parent lock over write lock
1592 bt_lockpage(BtLockParent, set);
1594 // keep copy of key to delete
1596 ptr = keyptr(bt->page, bt->page->cnt);
1597 memcpy(lowerkey, ptr, ptr->len + 1);
1599 // lock and map right page
1601 if( rpool = bt_pinpool (bt, right) )
1602 rpage = bt_page (bt, rpool, right);
1606 rset = bt_pinlatch (bt, right);
1607 bt_lockpage(BtLockWrite, rset);
1609 // pull contents of next page into current empty page
1611 memcpy (bt->page, rpage, bt->mgr->page_size);
1613 // keep copy of key to update
1615 ptr = keyptr(rpage, rpage->cnt);
1616 memcpy(higherkey, ptr, ptr->len + 1);
1618 // Mark right page as deleted and point it to left page
1619 // until we can post updates at higher level.
1621 bt_putid(rpage->right, page_no);
1625 bt_unlockpage(BtLockWrite, rset);
1626 bt_unlockpage(BtLockWrite, set);
1628 // delete old lower key to consolidated node
1630 if( bt_deletekey (bt, lowerkey + 1, *lowerkey, lvl + 1) )
1633 // redirect higher key directly to consolidated node
1635 tod = (uint)time(NULL);
1637 if( bt_insertkey (bt, higherkey+1, *higherkey, lvl + 1, page_no, tod) )
1640 // add killed right block to free chain
1643 bt_spinwritelock(bt->mgr->latchmgr->lock, 0);
1645 // store free chain in allocation page second right
1646 bt_putid(rpage->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1647 bt_putid(bt->mgr->latchmgr->alloc[1].right, right);
1649 // unlock latch mgr and unpin right page
1651 bt_spinreleasewrite(bt->mgr->latchmgr->lock, 0);
1652 bt_unpinlatch (rset);
1653 bt_unpinpool (rpool);
1655 // remove ParentModify lock
1657 bt_unlockpage(BtLockParent, set);
1658 bt_unpinlatch (set);
1659 bt_unpinpool (pool);
1663 // find key in leaf level and return row-id
1665 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1671 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1672 ptr = keyptr(bt->page, slot);
1676 // if key exists, return row-id
1677 // otherwise return 0
1679 if( ptr->len == len && !memcmp (ptr->key, key, len) )
1680 id = bt_getid(slotptr(bt->page,slot)->id);
1684 bt_unlockpage (BtLockRead, bt->set);
1685 bt_unpinlatch (bt->set);
1686 bt_unpinpool (bt->pool);
1690 // check page for space available,
1691 // clean if necessary and return
1692 // =0 - page needs splitting
1693 // >0 - go ahead at returned slot
1695 uint bt_cleanpage(BtDb *bt, uint amt, uint slot)
1697 uint nxt = bt->mgr->page_size;
1698 BtPage page = bt->page;
1699 uint cnt = 0, idx = 0;
1700 uint max = page->cnt;
1704 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1707 // skip cleanup if nothing to reclaim
1712 memcpy (bt->frame, page, bt->mgr->page_size);
1714 // skip page info and set rest of page to zero
1716 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1720 // always leave fence key in list
1722 while( cnt++ < max ) {
1725 else if( cnt < max && slotptr(bt->frame,cnt)->dead )
1729 key = keyptr(bt->frame, cnt);
1730 nxt -= key->len + 1;
1731 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1734 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1735 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1737 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1738 slotptr(page, idx)->off = nxt;
1743 if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1749 // split the root and raise the height of the btree
1751 BTERR bt_splitroot(BtDb *bt, unsigned char *newkey, unsigned char *oldkey, uid page_no2)
1753 uint nxt = bt->mgr->page_size;
1754 BtPage root = bt->page;
1757 // Obtain an empty page to use, and copy the current
1758 // root contents into it which is the lower half of
1761 if( !(new_page = bt_newpage(bt, root)) )
1764 // preserve the page info at the bottom
1765 // and set rest to zero
1767 memset(root+1, 0, bt->mgr->page_size - sizeof(*root));
1769 // insert first key on newroot page
1772 memcpy ((unsigned char *)root + nxt, newkey, *newkey + 1);
1773 bt_putid(slotptr(root, 1)->id, new_page);
1774 slotptr(root, 1)->off = nxt;
1776 // insert second key on newroot page
1777 // and increase the root height
1780 memcpy ((unsigned char *)root + nxt, oldkey, *oldkey + 1);
1781 bt_putid(slotptr(root, 2)->id, page_no2);
1782 slotptr(root, 2)->off = nxt;
1784 bt_putid(root->right, 0);
1785 root->min = nxt; // reset lowest used offset and key count
1790 // release and unpin root (bt->page)
1792 bt_unlockpage(BtLockWrite, bt->set);
1793 bt_unpinlatch (bt->set);
1794 bt_unpinpool (bt->pool);
1798 // split already locked full node
1801 BTERR bt_splitpage (BtDb *bt)
1803 uint cnt = 0, idx = 0, max, nxt = bt->mgr->page_size;
1804 unsigned char oldkey[256], lowerkey[256];
1805 uid page_no = bt->page_no, right;
1806 BtLatchSet *nset, *set = bt->set;
1807 BtPool *pool = bt->pool;
1808 BtPage page = bt->page;
1809 uint lvl = page->lvl;
1814 // split higher half of keys to bt->frame
1815 // the last key (fence key) might be dead
1817 tod = (uint)time(NULL);
1819 memset (bt->frame, 0, bt->mgr->page_size);
1820 max = (int)page->cnt;
1824 while( cnt++ < max ) {
1825 key = keyptr(page, cnt);
1826 nxt -= key->len + 1;
1827 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
1828 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
1829 if( !(slotptr(bt->frame, idx)->dead = slotptr(page, cnt)->dead) )
1831 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
1832 slotptr(bt->frame, idx)->off = nxt;
1835 // remember existing fence key for new page to the right
1837 memcpy (oldkey, key, key->len + 1);
1839 bt->frame->bits = bt->mgr->page_bits;
1840 bt->frame->min = nxt;
1841 bt->frame->cnt = idx;
1842 bt->frame->lvl = lvl;
1846 if( page_no > ROOT_page ) {
1847 right = bt_getid (page->right);
1848 bt_putid(bt->frame->right, right);
1851 // get new free page and write frame to it.
1853 if( !(new_page = bt_newpage(bt, bt->frame)) )
1856 // update lower keys to continue in old page
1858 memcpy (bt->frame, page, bt->mgr->page_size);
1859 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1860 nxt = bt->mgr->page_size;
1865 // assemble page of smaller keys
1866 // (they're all active keys)
1868 while( cnt++ < max / 2 ) {
1869 key = keyptr(bt->frame, cnt);
1870 nxt -= key->len + 1;
1871 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1872 memcpy(slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1873 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1874 slotptr(page, idx)->off = nxt;
1878 // remember fence key for old page
1880 memcpy(lowerkey, key, key->len + 1);
1881 bt_putid(page->right, new_page);
1885 // if current page is the root page, split it
1887 if( page_no == ROOT_page )
1888 return bt_splitroot (bt, lowerkey, oldkey, new_page);
1890 // obtain Parent/Write locks
1891 // for left and right node pages
1893 nset = bt_pinlatch (bt, new_page);
1895 bt_lockpage (BtLockParent, nset);
1896 bt_lockpage (BtLockParent, set);
1898 // release wr lock on left page
1899 // (keep the SMO in sequence)
1901 bt_unlockpage (BtLockWrite, set);
1903 // insert new fence for reformulated left block
1905 if( bt_insertkey (bt, lowerkey+1, *lowerkey, lvl + 1, page_no, tod) )
1908 // fix old fence for newly allocated right block page
1910 if( bt_insertkey (bt, oldkey+1, *oldkey, lvl + 1, new_page, tod) )
1913 // release Parent locks
1915 bt_unlockpage (BtLockParent, nset);
1916 bt_unlockpage (BtLockParent, set);
1917 bt_unpinlatch (nset);
1918 bt_unpinlatch (set);
1919 bt_unpinpool (pool);
1923 // Insert new key into the btree at requested level.
1924 // Level zero pages are leaf pages. Page is unlocked at exit.
1926 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod)
1933 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1934 ptr = keyptr(bt->page, slot);
1938 bt->err = BTERR_ovflw;
1942 // if key already exists, update id and return
1946 if( bt->found = !keycmp (ptr, key, len) ) {
1947 slotptr(page, slot)->dead = 0;
1948 slotptr(page, slot)->tod = tod;
1949 bt_putid(slotptr(page,slot)->id, id);
1950 bt_unlockpage(BtLockWrite, bt->set);
1951 bt_unpinlatch(bt->set);
1952 bt_unpinpool (bt->pool);
1956 // check if page has enough space
1958 if( slot = bt_cleanpage (bt, len, slot) )
1961 if( bt_splitpage (bt) )
1965 // calculate next available slot and copy key into page
1967 page->min -= len + 1; // reset lowest used offset
1968 ((unsigned char *)page)[page->min] = len;
1969 memcpy ((unsigned char *)page + page->min +1, key, len );
1971 for( idx = slot; idx < page->cnt; idx++ )
1972 if( slotptr(page, idx)->dead )
1975 // now insert key into array before slot
1976 // preserving the fence slot
1978 if( idx == page->cnt )
1984 *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
1986 bt_putid(slotptr(page,slot)->id, id);
1987 slotptr(page, slot)->off = page->min;
1988 slotptr(page, slot)->tod = tod;
1989 slotptr(page, slot)->dead = 0;
1991 bt_unlockpage (BtLockWrite, bt->set);
1992 bt_unpinlatch (bt->set);
1993 bt_unpinpool (bt->pool);
1997 // cache page of keys into cursor and return starting slot for given key
1999 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2003 // cache page for retrieval
2004 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
2005 memcpy (bt->cursor, bt->page, bt->mgr->page_size);
2006 bt->cursor_page = bt->page_no;
2007 bt_unlockpage(BtLockRead, bt->set);
2008 bt_unpinlatch (bt->set);
2009 bt_unpinpool (bt->pool);
2013 // return next slot for cursor page
2014 // or slide cursor right into next page
2016 uint bt_nextkey (BtDb *bt, uint slot)
2023 right = bt_getid(bt->cursor->right);
2024 while( slot++ < bt->cursor->cnt )
2025 if( slotptr(bt->cursor,slot)->dead )
2027 else if( right || (slot < bt->cursor->cnt))
2035 bt->cursor_page = right;
2037 if( pool = bt_pinpool (bt, right) )
2038 page = bt_page (bt, pool, right);
2042 bt->set = bt_pinlatch (bt, right);
2043 bt_lockpage(BtLockRead, bt->set);
2045 memcpy (bt->cursor, page, bt->mgr->page_size);
2047 bt_unlockpage(BtLockRead, bt->set);
2048 bt_unpinlatch (bt->set);
2049 bt_unpinpool (pool);
2056 BtKey bt_key(BtDb *bt, uint slot)
2058 return keyptr(bt->cursor, slot);
2061 uid bt_uid(BtDb *bt, uint slot)
2063 return bt_getid(slotptr(bt->cursor,slot)->id);
2066 uint bt_tod(BtDb *bt, uint slot)
2068 return slotptr(bt->cursor,slot)->tod;
2073 void bt_latchaudit (BtDb *bt)
2075 ushort idx, hashidx;
2082 for( idx = 1; idx < bt->mgr->latchmgr->latchdeployed; idx++ ) {
2083 set = bt->mgr->latchsets + idx;
2084 if( *(ushort *)set->readwr || *(ushort *)set->access || *(ushort *)set->parent ) {
2085 fprintf(stderr, "latchset %d locked for page %6x\n", idx, set->page_no);
2086 *(ushort *)set->readwr = 0;
2087 *(ushort *)set->access = 0;
2088 *(ushort *)set->parent = 0;
2091 fprintf(stderr, "latchset %d pinned\n", idx);
2096 for( hashidx = 0; hashidx < bt->mgr->latchmgr->latchhash; hashidx++ ) {
2097 if( *(uint *)bt->mgr->latchmgr->table[hashidx].latch )
2098 fprintf(stderr, "latchmgr locked\n");
2099 if( idx = bt->mgr->latchmgr->table[hashidx].slot ) do {
2100 set = bt->mgr->latchsets + idx;
2101 if( *(uint *)set->readwr || *(ushort *)set->access || *(ushort *)set->parent )
2102 fprintf(stderr, "latchset %d locked\n", idx);
2103 if( set->hash != hashidx )
2104 fprintf(stderr, "latchset %d wrong hashidx\n", idx);
2106 fprintf(stderr, "latchset %d pinned\n", idx);
2107 } while( idx = set->next );
2109 page_no = bt_getid(bt->mgr->latchmgr->alloc[1].right);
2112 fprintf(stderr, "free: %.6x\n", (uint)page_no);
2113 pool = bt_pinpool (bt, page_no);
2114 page = bt_page (bt, pool, page_no);
2115 page_no = bt_getid(page->right);
2116 bt_unpinpool (pool);
2128 // standalone program to index file of keys
2129 // then list them onto std-out
2132 void *index_file (void *arg)
2134 uint __stdcall index_file (void *arg)
2137 int line = 0, found = 0, cnt = 0;
2138 uid next, page_no = LEAF_page; // start on first page of leaves
2139 unsigned char key[256];
2140 ThreadArg *args = arg;
2141 int ch, len = 0, slot;
2149 bt = bt_open (args->mgr);
2152 switch(args->type | 0x20)
2155 fprintf(stderr, "started latch mgr audit\n");
2157 fprintf(stderr, "finished latch mgr audit\n");
2161 fprintf(stderr, "started indexing for %s\n", args->infile);
2162 if( in = fopen (args->infile, "rb") )
2163 while( ch = getc(in), ch != EOF )
2168 if( args->num == 1 )
2169 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2171 else if( args->num )
2172 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2174 if( bt_insertkey (bt, key, len, 0, line, *tod) )
2175 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2178 else if( len < 255 )
2180 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
2184 fprintf(stderr, "started deleting keys for %s\n", args->infile);
2185 if( in = fopen (args->infile, "rb") )
2186 while( ch = getc(in), ch != EOF )
2190 if( args->num == 1 )
2191 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2193 else if( args->num )
2194 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2196 if( bt_deletekey (bt, key, len, 0) )
2197 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2200 else if( len < 255 )
2202 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2206 fprintf(stderr, "started finding keys for %s\n", args->infile);
2207 if( in = fopen (args->infile, "rb") )
2208 while( ch = getc(in), ch != EOF )
2212 if( args->num == 1 )
2213 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2215 else if( args->num )
2216 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2218 if( bt_findkey (bt, key, len) )
2221 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2224 else if( len < 255 )
2226 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2232 fprintf(stderr, "started reading\n");
2234 if( slot = bt_startkey (bt, key, len) )
2237 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
2239 while( slot = bt_nextkey (bt, slot) ) {
2240 ptr = bt_key(bt, slot);
2241 fwrite (ptr->key, ptr->len, 1, stdout);
2242 fputc ('\n', stdout);
2248 fprintf(stderr, "started reading\n");
2251 if( bt->pool = bt_pinpool (bt, page_no) )
2252 page = bt_page (bt, bt->pool, page_no);
2255 bt->set = bt_pinlatch (bt, page_no);
2256 bt_lockpage (BtLockRead, bt->set);
2258 next = bt_getid (page->right);
2259 bt_unlockpage (BtLockRead, bt->set);
2260 bt_unpinlatch (bt->set);
2261 bt_unpinpool (bt->pool);
2262 } while( page_no = next );
2264 cnt--; // remove stopper key
2265 fprintf(stderr, " Total keys read %d\n", cnt);
2277 typedef struct timeval timer;
2279 int main (int argc, char **argv)
2281 int idx, cnt, len, slot, err;
2282 int segsize, bits = 16;
2287 time_t start[1], stop[1];
2300 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]);
2301 fprintf (stderr, " where page_bits is the page size in bits\n");
2302 fprintf (stderr, " mapped_segments is the number of mmap segments in buffer pool\n");
2303 fprintf (stderr, " seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2304 fprintf (stderr, " line_numbers = 1 to append line numbers to keys\n");
2305 fprintf (stderr, " src_file1 thru src_filen are files of keys separated by newline\n");
2310 gettimeofday(&start, NULL);
2316 bits = atoi(argv[3]);
2319 poolsize = atoi(argv[4]);
2322 fprintf (stderr, "Warning: no mapped_pool\n");
2324 if( poolsize > 65535 )
2325 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2328 segsize = atoi(argv[5]);
2330 segsize = 4; // 16 pages per mmap segment
2333 num = atoi(argv[6]);
2337 threads = malloc (cnt * sizeof(pthread_t));
2339 threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2341 args = malloc (cnt * sizeof(ThreadArg));
2343 mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2346 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2352 for( idx = 0; idx < cnt; idx++ ) {
2353 args[idx].infile = argv[idx + 7];
2354 args[idx].type = argv[2][0];
2355 args[idx].mgr = mgr;
2356 args[idx].num = num;
2357 args[idx].idx = idx;
2359 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2360 fprintf(stderr, "Error creating thread %d\n", err);
2362 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2366 // wait for termination
2369 for( idx = 0; idx < cnt; idx++ )
2370 pthread_join (threads[idx], NULL);
2371 gettimeofday(&stop, NULL);
2372 real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2374 WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2376 for( idx = 0; idx < cnt; idx++ )
2377 CloseHandle(threads[idx]);
2380 real_time = 1000 * (*stop - *start);
2382 fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);