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
163 // hash table entries
167 volatile ushort slot; // Latch table entry at head of chain
170 // latch manager table structure
173 BtLatch readwr[1]; // read/write page lock
174 BtLatch access[1]; // Access Intent/Page delete
175 BtLatch parent[1]; // adoption of foster children
176 BtLatch busy[1]; // slot is being moved between chains
177 volatile ushort next; // next entry in hash table chain
178 volatile ushort prev; // prev entry in hash table chain
179 volatile ushort pin; // number of outstanding locks
180 volatile ushort hash; // hash slot entry is under
181 volatile uid page_no; // latch set page number
184 // The memory mapping pool table buffer manager entry
187 unsigned long long int lru; // number of times accessed
188 uid basepage; // mapped base page number
189 char *map; // mapped memory pointer
190 ushort slot; // slot index in this array
191 ushort pin; // mapped page pin counter
192 void *hashprev; // previous pool entry for the same hash idx
193 void *hashnext; // next pool entry for the same hash idx
195 HANDLE hmap; // Windows memory mapping handle
199 // structure for latch manager on ALLOC_page
202 struct Page alloc[2]; // next & free page_nos in right ptr
203 BtLatch lock[1]; // allocation area lite latch
204 ushort latchdeployed; // highest number of latch entries deployed
205 ushort nlatchpage; // number of latch pages at BT_latch
206 ushort latchtotal; // number of page latch entries
207 ushort latchhash; // number of latch hash table slots
208 ushort latchvictim; // next latch entry to examine
209 BtHashEntry table[0]; // the hash table
212 // The object structure for Btree access
215 uint page_size; // page size
216 uint page_bits; // page size in bits
217 uint seg_bits; // seg size in pages in bits
218 uint mode; // read-write mode
220 char *pooladvise; // bit maps for pool page advisements
225 ushort poolcnt; // highest page pool node in use
226 ushort poolmax; // highest page pool node allocated
227 ushort poolmask; // total number of pages in mmap segment - 1
228 ushort evicted; // last evicted hash table slot
229 ushort hashsize; // size of Hash Table for pool entries
230 ushort *hash; // pool index for hash entries
231 BtPool *pool; // memory pool page segments
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
236 HANDLE halloc; // allocation and latch table handle
241 BtMgr *mgr; // buffer manager for thread
242 BtPage cursor; // cached frame for start/next (never mapped)
243 BtPage frame; // spare frame for the page split (never mapped)
244 BtPage zero; // page of zeroes to extend the file (never mapped)
245 BtPage page; // current page mapped from file
246 uid page_no; // current page number
247 uid cursor_page; // current cursor page number
248 BtLatchSet *set; // current page latchset
249 BtPool *pool; // current page pool
250 unsigned char *mem; // frame, cursor, page memory buffer
251 int found; // last delete was found
252 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) (((BtSlot *)(page+1)) + (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;
950 // create empty page area by writing last page of first
951 // segment area (other pages are zeroed by O/S)
953 if( mgr->poolmask ) {
954 memset(latchmgr, 0, mgr->page_size);
955 last = mgr->poolmask;
957 while( last < MIN_lvl + 1 )
958 last += mgr->poolmask + 1;
961 pwrite(mgr->idx, latchmgr, mgr->page_size, last << mgr->page_bits);
963 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
964 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
965 return bt_mgrclose (mgr), NULL;
966 if( *amt < mgr->page_size )
967 return bt_mgrclose (mgr), NULL;
973 flag = PROT_READ | PROT_WRITE;
974 mgr->latchmgr = mmap (0, mgr->page_size, flag, MAP_SHARED, mgr->idx, ALLOC_page * mgr->page_size);
975 if( mgr->latchmgr == MAP_FAILED )
976 return bt_mgrclose (mgr), NULL;
977 mgr->latchsets = (BtLatchSet *)mmap (0, mgr->latchmgr->nlatchpage * mgr->page_size, flag, MAP_SHARED, mgr->idx, LATCH_page * mgr->page_size);
978 if( mgr->latchsets == MAP_FAILED )
979 return bt_mgrclose (mgr), NULL;
981 flag = PAGE_READWRITE;
982 mgr->halloc = CreateFileMapping(mgr->idx, NULL, flag, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size, NULL);
984 return bt_mgrclose (mgr), NULL;
986 flag = FILE_MAP_WRITE;
987 mgr->latchmgr = MapViewOfFile(mgr->halloc, flag, 0, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size);
989 return GetLastError(), bt_mgrclose (mgr), NULL;
991 mgr->latchsets = (void *)((char *)mgr->latchmgr + LATCH_page * mgr->page_size);
997 VirtualFree (latchmgr, 0, MEM_RELEASE);
1002 // open BTree access method
1003 // based on buffer manager
1005 BtDb *bt_open (BtMgr *mgr)
1007 BtDb *bt = malloc (sizeof(*bt));
1009 memset (bt, 0, sizeof(*bt));
1012 bt->mem = malloc (3 *mgr->page_size);
1014 bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
1016 bt->frame = (BtPage)bt->mem;
1017 bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
1018 bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
1020 memset (bt->zero, 0, mgr->page_size);
1024 // compare two keys, returning > 0, = 0, or < 0
1025 // as the comparison value
1027 int keycmp (BtKey key1, unsigned char *key2, uint len2)
1029 uint len1 = key1->len;
1032 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
1045 // find segment in pool
1046 // must be called with hashslot idx locked
1047 // return NULL if not there
1048 // otherwise return node
1050 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
1055 // compute start of hash chain in pool
1057 if( slot = bt->mgr->hash[idx] )
1058 pool = bt->mgr->pool + slot;
1062 page_no &= ~bt->mgr->poolmask;
1064 while( pool->basepage != page_no )
1065 if( pool = pool->hashnext )
1073 // add segment to hash table
1075 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
1080 pool->hashprev = pool->hashnext = NULL;
1081 pool->basepage = page_no & ~bt->mgr->poolmask;
1084 if( slot = bt->mgr->hash[idx] ) {
1085 node = bt->mgr->pool + slot;
1086 pool->hashnext = node;
1087 node->hashprev = pool;
1090 bt->mgr->hash[idx] = pool->slot;
1093 // find best segment to evict from buffer pool
1095 BtPool *bt_findlru (BtDb *bt, uint hashslot)
1097 unsigned long long int target = ~0LL;
1098 BtPool *pool = NULL, *node;
1103 node = bt->mgr->pool + hashslot;
1105 // scan pool entries under hash table slot
1110 if( node->lru > target )
1114 } while( node = node->hashnext );
1119 // map new buffer pool segment to virtual memory
1121 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
1123 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
1124 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
1128 flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
1129 pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED, bt->mgr->idx, off);
1130 if( pool->map == MAP_FAILED )
1131 return bt->err = BTERR_map;
1133 // clear out madvise issued bits
1134 memset (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8) / 8), 0, (bt->mgr->poolmask + 8)/8);
1136 flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
1137 pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
1139 return bt->err = BTERR_map;
1141 flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
1142 pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1144 return bt->err = BTERR_map;
1149 // calculate page within pool
1151 BtPage bt_page (BtDb *bt, BtPool *pool, uid page_no)
1153 uint subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1156 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1159 uint idx = subpage / 8;
1160 uint bit = subpage % 8;
1162 if( ~((bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] >> bit) & 1 ) {
1163 madvise (page, bt->mgr->page_size, MADV_WILLNEED);
1164 (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] |= 1 << bit;
1173 void bt_unpinpool (BtPool *pool)
1176 __sync_fetch_and_add(&pool->pin, -1);
1178 _InterlockedDecrement16 (&pool->pin);
1182 // find or place requested page in segment-pool
1183 // return pool table entry, incrementing pin
1185 BtPool *bt_pinpool(BtDb *bt, uid page_no)
1187 BtPool *pool, *node, *next;
1188 uint slot, idx, victim;
1190 // lock hash table chain
1192 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1193 bt_spinreadlock (&bt->mgr->latch[idx], 1);
1195 // look up in hash table
1197 if( pool = bt_findpool(bt, page_no, idx) ) {
1199 __sync_fetch_and_add(&pool->pin, 1);
1201 _InterlockedIncrement16 (&pool->pin);
1203 bt_spinreleaseread (&bt->mgr->latch[idx], 1);
1208 // upgrade to write lock
1210 bt_spinreleaseread (&bt->mgr->latch[idx], 1);
1211 bt_spinwritelock (&bt->mgr->latch[idx], 1);
1213 // try to find page in pool with write lock
1215 if( pool = bt_findpool(bt, page_no, idx) ) {
1217 __sync_fetch_and_add(&pool->pin, 1);
1219 _InterlockedIncrement16 (&pool->pin);
1221 bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
1226 // allocate a new pool node
1227 // and add to hash table
1230 slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
1232 slot = _InterlockedIncrement16 (&bt->mgr->poolcnt) - 1;
1235 if( ++slot < bt->mgr->poolmax ) {
1236 pool = bt->mgr->pool + slot;
1239 if( bt_mapsegment(bt, pool, page_no) )
1242 bt_linkhash(bt, pool, page_no, idx);
1244 __sync_fetch_and_add(&pool->pin, 1);
1246 _InterlockedIncrement16 (&pool->pin);
1248 bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
1252 // pool table is full
1253 // find best pool entry to evict
1256 __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
1258 _InterlockedDecrement16 (&bt->mgr->poolcnt);
1263 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
1265 victim = _InterlockedIncrement16 (&bt->mgr->evicted) - 1;
1267 victim %= bt->mgr->hashsize;
1269 // try to get write lock
1270 // skip entry if not obtained
1272 if( !bt_spinwritetry (&bt->mgr->latch[victim]) )
1275 // if pool entry is empty
1276 // or any pages are pinned
1279 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
1280 bt_spinreleasewrite (&bt->mgr->latch[victim], 1);
1284 // unlink victim pool node from hash table
1286 if( node = pool->hashprev )
1287 node->hashnext = pool->hashnext;
1288 else if( node = pool->hashnext )
1289 bt->mgr->hash[victim] = node->slot;
1291 bt->mgr->hash[victim] = 0;
1293 if( node = pool->hashnext )
1294 node->hashprev = pool->hashprev;
1296 bt_spinreleasewrite (&bt->mgr->latch[victim], 1);
1298 // remove old file mapping
1300 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1302 FlushViewOfFile(pool->map, 0);
1303 UnmapViewOfFile(pool->map);
1304 CloseHandle(pool->hmap);
1308 // create new pool mapping
1309 // and link into hash table
1311 if( bt_mapsegment(bt, pool, page_no) )
1314 bt_linkhash(bt, pool, page_no, idx);
1316 __sync_fetch_and_add(&pool->pin, 1);
1318 _InterlockedIncrement16 (&pool->pin);
1320 bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
1325 // place write, read, or parent lock on requested page_no.
1326 // pin to buffer pool and return page pointer
1328 void bt_lockpage(BtLock mode, BtLatchSet *set)
1332 bt_spinreadlock (set->readwr, 0);
1335 bt_spinwritelock (set->readwr, 0);
1338 bt_spinreadlock (set->access, 0);
1341 bt_spinwritelock (set->access, 0);
1344 bt_spinwritelock (set->parent, 0);
1349 // remove write, read, or parent lock on requested page
1351 void bt_unlockpage(BtLock mode, BtLatchSet *set)
1355 bt_spinreleaseread (set->readwr, 0);
1358 bt_spinreleasewrite (set->readwr, 0);
1361 bt_spinreleaseread (set->access, 0);
1364 bt_spinreleasewrite (set->access, 0);
1367 bt_spinreleasewrite (set->parent, 0);
1372 // allocate a new page and write page into it
1374 uid bt_newpage(BtDb *bt, BtPage page)
1382 // lock allocation page
1384 bt_spinwritelock(bt->mgr->latchmgr->lock, 0);
1386 // use empty chain first
1387 // else allocate empty page
1389 if( new_page = bt_getid(bt->mgr->latchmgr->alloc[1].right) ) {
1390 if( pool = bt_pinpool (bt, new_page) )
1391 pmap = bt_page (bt, pool, new_page);
1394 bt_putid(bt->mgr->latchmgr->alloc[1].right, bt_getid(pmap->right));
1395 bt_unpinpool (pool);
1398 new_page = bt_getid(bt->mgr->latchmgr->alloc->right);
1399 bt_putid(bt->mgr->latchmgr->alloc->right, new_page+1);
1403 if ( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1404 return bt->err = BTERR_wrt, 0;
1406 // if writing first page of pool block, zero last page in the block
1408 if ( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1410 // use zero buffer to write zeros
1411 memset(bt->zero, 0, bt->mgr->page_size);
1412 if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1413 return bt->err = BTERR_wrt, 0;
1416 // bring new page into pool and copy page.
1417 // this will extend the file into the new pages.
1419 if( pool = bt_pinpool (bt, new_page) )
1420 pmap = bt_page (bt, pool, new_page);
1424 memcpy(pmap, page, bt->mgr->page_size);
1425 bt_unpinpool (pool);
1427 // unlock allocation latch and return new page no
1429 bt_spinreleasewrite(bt->mgr->latchmgr->lock, 0);
1433 // find slot in page for given key at a given level
1435 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1437 uint diff, higher = bt->page->cnt, low = 1, slot;
1440 // make stopper key an infinite fence value
1442 if( bt_getid (bt->page->right) )
1447 // low is the next candidate, higher is already
1448 // tested as .ge. the given key, loop ends when they meet
1450 while( diff = higher - low ) {
1451 slot = low + ( diff >> 1 );
1452 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1455 higher = slot, good++;
1458 // return zero if key is on right link page
1460 return good ? higher : 0;
1463 // find and load page at given level for given key
1464 // leave page rd or wr locked as requested
1466 int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, uint lock)
1468 uid page_no = ROOT_page, prevpage = 0;
1469 BtLatchSet *set, *prevset;
1470 uint drill = 0xff, slot;
1471 uint mode, prevmode;
1474 // start at root of btree and drill down
1479 // determine lock mode of drill level
1480 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1482 bt->set = bt_pinlatch (bt, page_no);
1483 bt->page_no = page_no;
1485 // pin page contents
1487 if( bt->pool = bt_pinpool (bt, page_no) )
1488 bt->page = bt_page (bt, bt->pool, page_no);
1492 // obtain access lock using lock chaining with Access mode
1494 if( page_no > ROOT_page )
1495 bt_lockpage(BtLockAccess, bt->set);
1497 // release & unpin parent page
1500 bt_unlockpage(prevmode, prevset);
1501 bt_unpinlatch (prevset);
1502 bt_unpinpool (prevpool);
1506 // obtain read lock using lock chaining
1508 bt_lockpage(mode, bt->set);
1510 if( page_no > ROOT_page )
1511 bt_unlockpage(BtLockAccess, bt->set);
1513 // re-read and re-lock root after determining actual level of root
1515 if( bt->page->lvl != drill) {
1516 if ( bt->page_no != ROOT_page )
1517 return bt->err = BTERR_struct, 0;
1519 drill = bt->page->lvl;
1521 if( lock == BtLockWrite && drill == lvl ) {
1522 bt_unlockpage(mode, bt->set);
1523 bt_unpinlatch (bt->set);
1524 bt_unpinpool (bt->pool);
1529 // find key on page at this level
1530 // and descend to requested level
1532 if( !bt->page->kill && (slot = bt_findslot (bt, key, len)) ) {
1536 while( slotptr(bt->page, slot)->dead )
1537 if( slot++ < bt->page->cnt )
1540 page_no = bt_getid(bt->page->right);
1544 page_no = bt_getid(slotptr(bt->page, slot)->id);
1548 // or slide right into next page
1549 // (slide left from deleted page)
1552 page_no = bt_getid(bt->page->right);
1554 // continue down / right using overlapping locks
1555 // to protect pages being killed or split.
1558 prevpage = bt->page_no;
1559 prevpool = bt->pool;
1564 // return error on end of right chain
1566 bt->err = BTERR_struct;
1567 return 0; // return error
1570 // find and delete key on page by marking delete flag bit
1571 // when page becomes empty, delete it
1573 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl)
1575 unsigned char lowerkey[256], higherkey[256];
1576 BtLatchSet *rset, *set;
1577 BtPool *pool, *rpool;
1583 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1584 ptr = keyptr(bt->page, slot);
1588 // if key is found delete it, otherwise ignore request
1590 if( bt->found = !keycmp (ptr, key, len) )
1591 if( bt->found = slotptr(bt->page, slot)->dead == 0 ) {
1592 slotptr(bt->page,slot)->dead = 1;
1593 if( slot < bt->page->cnt )
1594 bt->page->dirty = 1;
1598 // return if page is not empty, or it has no right sibling
1600 right = bt_getid(bt->page->right);
1601 page_no = bt->page_no;
1605 if( !right || bt->page->act ) {
1606 bt_unlockpage(BtLockWrite, set);
1607 bt_unpinlatch (set);
1608 bt_unpinpool (pool);
1612 // obtain Parent lock over write lock
1614 bt_lockpage(BtLockParent, set);
1616 // keep copy of key to delete
1618 ptr = keyptr(bt->page, bt->page->cnt);
1619 memcpy(lowerkey, ptr, ptr->len + 1);
1621 // lock and map right page
1623 if( rpool = bt_pinpool (bt, right) )
1624 rpage = bt_page (bt, rpool, right);
1628 rset = bt_pinlatch (bt, right);
1629 bt_lockpage(BtLockWrite, rset);
1631 // pull contents of next page into current empty page
1633 memcpy (bt->page, rpage, bt->mgr->page_size);
1635 // keep copy of key to update
1637 ptr = keyptr(rpage, rpage->cnt);
1638 memcpy(higherkey, ptr, ptr->len + 1);
1640 // Mark right page as deleted and point it to left page
1641 // until we can post updates at higher level.
1643 bt_putid(rpage->right, page_no);
1647 bt_unlockpage(BtLockWrite, rset);
1648 bt_unlockpage(BtLockWrite, set);
1650 // delete old lower key to consolidated node
1652 if( bt_deletekey (bt, lowerkey + 1, *lowerkey, lvl + 1) )
1655 // redirect higher key directly to consolidated node
1657 tod = (uint)time(NULL);
1659 if( bt_insertkey (bt, higherkey+1, *higherkey, lvl + 1, page_no, tod) )
1662 // add killed right block to free chain
1665 bt_spinwritelock(bt->mgr->latchmgr->lock, 0);
1667 // store free chain in allocation page second right
1668 bt_putid(rpage->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1669 bt_putid(bt->mgr->latchmgr->alloc[1].right, right);
1671 // unlock latch mgr and right page
1673 bt_spinreleasewrite(bt->mgr->latchmgr->lock, 0);
1675 bt_unlockpage(BtLockWrite, rset);
1676 bt_unlockpage(BtLockDelete, rset);
1677 bt_unpinlatch (rset);
1678 bt_unpinpool (rpool);
1680 // remove ParentModify lock
1682 bt_unlockpage(BtLockParent, set);
1683 bt_unpinlatch (set);
1684 bt_unpinpool (pool);
1688 // find key in leaf level and return row-id
1690 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1696 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1697 ptr = keyptr(bt->page, slot);
1701 // if key exists, return row-id
1702 // otherwise return 0
1704 if( ptr->len == len && !memcmp (ptr->key, key, len) )
1705 id = bt_getid(slotptr(bt->page,slot)->id);
1709 bt_unlockpage (BtLockRead, bt->set);
1710 bt_unpinlatch (bt->set);
1711 bt_unpinpool (bt->pool);
1715 // check page for space available,
1716 // clean if necessary and return
1717 // =0 - page needs splitting
1718 // >0 - go ahead at returned slot
1720 uint bt_cleanpage(BtDb *bt, uint amt, uint slot)
1722 uint nxt = bt->mgr->page_size;
1723 BtPage page = bt->page;
1724 uint cnt = 0, idx = 0;
1725 uint max = page->cnt;
1729 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1732 // skip cleanup if nothing to reclaim
1737 memcpy (bt->frame, page, bt->mgr->page_size);
1739 // skip page info and set rest of page to zero
1741 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1745 // always leave fence key in list
1747 while( cnt++ < max ) {
1750 else if( cnt < max && slotptr(bt->frame,cnt)->dead )
1754 key = keyptr(bt->frame, cnt);
1755 nxt -= key->len + 1;
1756 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1759 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1760 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1762 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1763 slotptr(page, idx)->off = nxt;
1768 if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1774 // split the root and raise the height of the btree
1776 BTERR bt_splitroot(BtDb *bt, unsigned char *newkey, unsigned char *oldkey, uid page_no2)
1778 uint nxt = bt->mgr->page_size;
1779 BtPage root = bt->page;
1782 // Obtain an empty page to use, and copy the current
1783 // root contents into it which is the lower half of
1786 if( !(new_page = bt_newpage(bt, root)) )
1789 // preserve the page info at the bottom
1790 // and set rest to zero
1792 memset(root+1, 0, bt->mgr->page_size - sizeof(*root));
1794 // insert first key on newroot page
1797 memcpy ((unsigned char *)root + nxt, newkey, *newkey + 1);
1798 bt_putid(slotptr(root, 1)->id, new_page);
1799 slotptr(root, 1)->off = nxt;
1801 // insert second key on newroot page
1802 // and increase the root height
1805 memcpy ((unsigned char *)root + nxt, oldkey, *oldkey + 1);
1806 bt_putid(slotptr(root, 2)->id, page_no2);
1807 slotptr(root, 2)->off = nxt;
1809 bt_putid(root->right, 0);
1810 root->min = nxt; // reset lowest used offset and key count
1815 // release and unpin root (bt->page)
1817 bt_unlockpage(BtLockWrite, bt->set);
1818 bt_unpinlatch (bt->set);
1819 bt_unpinpool (bt->pool);
1823 // split already locked full node
1826 BTERR bt_splitpage (BtDb *bt)
1828 uint cnt = 0, idx = 0, max, nxt = bt->mgr->page_size;
1829 unsigned char oldkey[256], lowerkey[256];
1830 uid page_no = bt->page_no, right;
1831 BtLatchSet *nset, *set = bt->set;
1832 BtPool *pool = bt->pool;
1833 BtPage page = bt->page;
1834 uint lvl = page->lvl;
1839 // split higher half of keys to bt->frame
1840 // the last key (fence key) might be dead
1842 tod = (uint)time(NULL);
1844 memset (bt->frame, 0, bt->mgr->page_size);
1845 max = (int)page->cnt;
1849 while( cnt++ < max ) {
1850 key = keyptr(page, cnt);
1851 nxt -= key->len + 1;
1852 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
1853 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
1854 if( !(slotptr(bt->frame, idx)->dead = slotptr(page, cnt)->dead) )
1856 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
1857 slotptr(bt->frame, idx)->off = nxt;
1860 // remember existing fence key for new page to the right
1862 memcpy (oldkey, key, key->len + 1);
1864 bt->frame->bits = bt->mgr->page_bits;
1865 bt->frame->min = nxt;
1866 bt->frame->cnt = idx;
1867 bt->frame->lvl = lvl;
1871 if( page_no > ROOT_page ) {
1872 right = bt_getid (page->right);
1873 bt_putid(bt->frame->right, right);
1876 // get new free page and write frame to it.
1878 if( !(new_page = bt_newpage(bt, bt->frame)) )
1881 // update lower keys to continue in old page
1883 memcpy (bt->frame, page, bt->mgr->page_size);
1884 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1885 nxt = bt->mgr->page_size;
1890 // assemble page of smaller keys
1891 // (they're all active keys)
1893 while( cnt++ < max / 2 ) {
1894 key = keyptr(bt->frame, cnt);
1895 nxt -= key->len + 1;
1896 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1897 memcpy(slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1898 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1899 slotptr(page, idx)->off = nxt;
1903 // remember fence key for old page
1905 memcpy(lowerkey, key, key->len + 1);
1906 bt_putid(page->right, new_page);
1910 // if current page is the root page, split it
1912 if( page_no == ROOT_page )
1913 return bt_splitroot (bt, lowerkey, oldkey, new_page);
1915 // release wr lock on left page
1917 bt_unlockpage (BtLockWrite, set);
1919 // obtain Parent/Write locks
1920 // for left and right node pages
1922 nset = bt_pinlatch (bt, new_page);
1924 bt_lockpage (BtLockParent, nset);
1925 bt_lockpage (BtLockParent, set);
1927 // insert new fence for reformulated left block
1929 if( bt_insertkey (bt, lowerkey+1, *lowerkey, lvl + 1, page_no, tod) )
1932 // fix old fence for newly allocated right block page
1934 if( bt_insertkey (bt, oldkey+1, *oldkey, lvl + 1, new_page, tod) )
1937 // release Parent locks
1939 bt_unlockpage (BtLockParent, nset);
1940 bt_unlockpage (BtLockParent, set);
1941 bt_unpinlatch (nset);
1942 bt_unpinlatch (set);
1943 bt_unpinpool (pool);
1947 // Insert new key into the btree at requested level.
1948 // Level zero pages are leaf pages. Page is unlocked at exit.
1950 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod)
1957 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1958 ptr = keyptr(bt->page, slot);
1962 bt->err = BTERR_ovflw;
1966 // if key already exists, update id and return
1970 if( !keycmp (ptr, key, len) ) {
1971 slotptr(page, slot)->dead = 0;
1972 slotptr(page, slot)->tod = tod;
1973 bt_putid(slotptr(page,slot)->id, id);
1974 bt_unlockpage(BtLockWrite, bt->set);
1975 bt_unpinlatch(bt->set);
1976 bt_unpinpool (bt->pool);
1980 // check if page has enough space
1982 if( slot = bt_cleanpage (bt, len, slot) )
1985 if( bt_splitpage (bt) )
1989 // calculate next available slot and copy key into page
1991 page->min -= len + 1; // reset lowest used offset
1992 ((unsigned char *)page)[page->min] = len;
1993 memcpy ((unsigned char *)page + page->min +1, key, len );
1995 for( idx = slot; idx < page->cnt; idx++ )
1996 if( slotptr(page, idx)->dead )
1999 // now insert key into array before slot
2000 // preserving the fence slot
2002 if( idx == page->cnt )
2008 *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
2010 bt_putid(slotptr(page,slot)->id, id);
2011 slotptr(page, slot)->off = page->min;
2012 slotptr(page, slot)->tod = tod;
2013 slotptr(page, slot)->dead = 0;
2015 bt_unlockpage (BtLockWrite, bt->set);
2016 bt_unpinlatch (bt->set);
2017 bt_unpinpool (bt->pool);
2021 // cache page of keys into cursor and return starting slot for given key
2023 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2027 // cache page for retrieval
2028 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
2029 memcpy (bt->cursor, bt->page, bt->mgr->page_size);
2030 bt->cursor_page = bt->page_no;
2031 bt_unlockpage(BtLockRead, bt->set);
2032 bt_unpinlatch (bt->set);
2033 bt_unpinpool (bt->pool);
2037 // return next slot for cursor page
2038 // or slide cursor right into next page
2040 uint bt_nextkey (BtDb *bt, uint slot)
2047 right = bt_getid(bt->cursor->right);
2048 while( slot++ < bt->cursor->cnt )
2049 if( slotptr(bt->cursor,slot)->dead )
2051 else if( right || (slot < bt->cursor->cnt))
2059 bt->cursor_page = right;
2061 if( pool = bt_pinpool (bt, right) )
2062 page = bt_page (bt, pool, right);
2066 bt->set = bt_pinlatch (bt, right);
2067 bt_lockpage(BtLockRead, bt->set);
2069 memcpy (bt->cursor, page, bt->mgr->page_size);
2071 bt_unlockpage(BtLockRead, bt->set);
2072 bt_unpinlatch (bt->set);
2073 bt_unpinpool (pool);
2080 BtKey bt_key(BtDb *bt, uint slot)
2082 return keyptr(bt->cursor, slot);
2085 uid bt_uid(BtDb *bt, uint slot)
2087 return bt_getid(slotptr(bt->cursor,slot)->id);
2090 uint bt_tod(BtDb *bt, uint slot)
2092 return slotptr(bt->cursor,slot)->tod;
2097 void bt_latchaudit (BtDb *bt)
2099 ushort idx, hashidx;
2106 for( idx = 1; idx < bt->mgr->latchmgr->latchdeployed; idx++ ) {
2107 set = bt->mgr->latchsets + idx;
2108 if( *(ushort *)set->readwr || *(ushort *)set->access || *(ushort *)set->parent ) {
2109 fprintf(stderr, "latchset %d locked for page %6x\n", idx, set->page_no);
2110 *(ushort *)set->readwr = 0;
2111 *(ushort *)set->access = 0;
2112 *(ushort *)set->parent = 0;
2115 fprintf(stderr, "latchset %d pinned\n", idx);
2120 for( hashidx = 0; hashidx < bt->mgr->latchmgr->latchhash; hashidx++ ) {
2121 if( *(uint *)bt->mgr->latchmgr->table[hashidx].latch )
2122 fprintf(stderr, "latchmgr locked\n");
2123 if( idx = bt->mgr->latchmgr->table[hashidx].slot ) do {
2124 set = bt->mgr->latchsets + idx;
2125 if( *(uint *)set->readwr || *(ushort *)set->access || *(ushort *)set->parent )
2126 fprintf(stderr, "latchset %d locked\n", idx);
2127 if( set->hash != hashidx )
2128 fprintf(stderr, "latchset %d wrong hashidx\n", idx);
2130 fprintf(stderr, "latchset %d pinned\n", idx);
2131 } while( idx = set->next );
2133 page_no = bt_getid(bt->mgr->latchmgr->alloc[1].right);
2136 fprintf(stderr, "free: %.6x\n", (uint)page_no);
2137 pool = bt_pinpool (bt, page_no);
2138 page = bt_page (bt, pool, page_no);
2139 page_no = bt_getid(page->right);
2140 bt_unpinpool (pool);
2152 // standalone program to index file of keys
2153 // then list them onto std-out
2156 void *index_file (void *arg)
2158 uint __stdcall index_file (void *arg)
2161 int line = 0, found = 0, cnt = 0;
2162 uid next, page_no = LEAF_page; // start on first page of leaves
2163 unsigned char key[256];
2164 ThreadArg *args = arg;
2165 int ch, len = 0, slot;
2173 bt = bt_open (args->mgr);
2176 switch(args->type | 0x20)
2179 fprintf(stderr, "started latch mgr audit\n");
2181 fprintf(stderr, "finished latch mgr audit\n");
2185 fprintf(stderr, "started indexing for %s\n", args->infile);
2186 if( in = fopen (args->infile, "rb") )
2187 while( ch = getc(in), ch != EOF )
2192 if( args->num == 1 )
2193 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2195 else if( args->num )
2196 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2198 if( bt_insertkey (bt, key, len, 0, line, *tod) )
2199 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2202 else if( len < 255 )
2204 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
2208 fprintf(stderr, "started deleting keys for %s\n", args->infile);
2209 if( in = fopen (args->infile, "rb") )
2210 while( ch = getc(in), ch != EOF )
2214 if( args->num == 1 )
2215 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2217 else if( args->num )
2218 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2220 if( bt_deletekey (bt, key, len, 0) )
2221 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2224 else if( len < 255 )
2226 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2230 fprintf(stderr, "started finding keys for %s\n", args->infile);
2231 if( in = fopen (args->infile, "rb") )
2232 while( ch = getc(in), ch != EOF )
2236 if( args->num == 1 )
2237 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2239 else if( args->num )
2240 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2242 if( bt_findkey (bt, key, len) )
2245 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2248 else if( len < 255 )
2250 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2256 fprintf(stderr, "started reading\n");
2258 if( slot = bt_startkey (bt, key, len) )
2261 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
2263 while( slot = bt_nextkey (bt, slot) ) {
2264 ptr = bt_key(bt, slot);
2265 fwrite (ptr->key, ptr->len, 1, stdout);
2266 fputc ('\n', stdout);
2272 fprintf(stderr, "started reading\n");
2275 if( bt->pool = bt_pinpool (bt, page_no) )
2276 page = bt_page (bt, bt->pool, page_no);
2279 bt->set = bt_pinlatch (bt, page_no);
2280 bt_lockpage (BtLockRead, bt->set);
2282 next = bt_getid (page->right);
2283 bt_unlockpage (BtLockRead, bt->set);
2284 bt_unpinlatch (bt->set);
2285 bt_unpinpool (bt->pool);
2286 } while( page_no = next );
2288 cnt--; // remove stopper key
2289 fprintf(stderr, " Total keys read %d\n", cnt);
2301 typedef struct timeval timer;
2303 int main (int argc, char **argv)
2305 int idx, cnt, len, slot, err;
2306 int segsize, bits = 16;
2311 time_t start[1], stop[1];
2324 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]);
2325 fprintf (stderr, " where page_bits is the page size in bits\n");
2326 fprintf (stderr, " mapped_segments is the number of mmap segments in buffer pool\n");
2327 fprintf (stderr, " seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2328 fprintf (stderr, " line_numbers = 1 to append line numbers to keys\n");
2329 fprintf (stderr, " src_file1 thru src_filen are files of keys separated by newline\n");
2334 gettimeofday(&start, NULL);
2340 bits = atoi(argv[3]);
2343 poolsize = atoi(argv[4]);
2346 fprintf (stderr, "Warning: no mapped_pool\n");
2348 if( poolsize > 65535 )
2349 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2352 segsize = atoi(argv[5]);
2354 segsize = 4; // 16 pages per mmap segment
2357 num = atoi(argv[6]);
2361 threads = malloc (cnt * sizeof(pthread_t));
2363 threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2365 args = malloc (cnt * sizeof(ThreadArg));
2367 mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2370 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2376 for( idx = 0; idx < cnt; idx++ ) {
2377 args[idx].infile = argv[idx + 7];
2378 args[idx].type = argv[2][0];
2379 args[idx].mgr = mgr;
2380 args[idx].num = num;
2381 args[idx].idx = idx;
2383 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2384 fprintf(stderr, "Error creating thread %d\n", err);
2386 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2390 // wait for termination
2393 for( idx = 0; idx < cnt; idx++ )
2394 pthread_join (threads[idx], NULL);
2395 gettimeofday(&stop, NULL);
2396 real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2398 WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2400 for( idx = 0; idx < cnt; idx++ )
2401 CloseHandle(threads[idx]);
2404 real_time = 1000 * (*stop - *start);
2406 fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);