1 // btree version threads2i sched_yield version
2 // with reworked bt_deletekey code
5 // author: karl malbrain, malbrain@cal.berkeley.edu
8 This work, including the source code, documentation
9 and related data, is placed into the public domain.
11 The orginal author is Karl Malbrain.
13 THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY
14 OF ANY KIND, NOT EVEN THE IMPLIED WARRANTY OF
15 MERCHANTABILITY. THE AUTHOR OF THIS SOFTWARE,
16 ASSUMES _NO_ RESPONSIBILITY FOR ANY CONSEQUENCE
17 RESULTING FROM THE USE, MODIFICATION, OR
18 REDISTRIBUTION OF THIS SOFTWARE.
21 // Please see the project home page for documentation
22 // code.google.com/p/high-concurrency-btree
24 #define _FILE_OFFSET_BITS 64
25 #define _LARGEFILE64_SOURCE
41 #define WIN32_LEAN_AND_MEAN
55 typedef unsigned long long uid;
58 typedef unsigned long long off64_t;
59 typedef unsigned short ushort;
60 typedef unsigned int uint;
63 #define BT_latchtable 128 // number of latch manager slots
65 #define BT_ro 0x6f72 // ro
66 #define BT_rw 0x7772 // rw
68 #define BT_maxbits 24 // maximum page size in bits
69 #define BT_minbits 9 // minimum page size in bits
70 #define BT_minpage (1 << BT_minbits) // minimum page size
71 #define BT_maxpage (1 << BT_maxbits) // maximum page size
74 There are five lock types for each node in three independent sets:
75 1. (set 1) AccessIntent: Sharable. Going to Read the node. Incompatible with NodeDelete.
76 2. (set 1) NodeDelete: Exclusive. About to release the node. Incompatible with AccessIntent.
77 3. (set 2) ReadLock: Sharable. Read the node. Incompatible with WriteLock.
78 4. (set 2) WriteLock: Exclusive. Modify the node. Incompatible with ReadLock and other WriteLocks.
79 5. (set 3) ParentModification: Exclusive. Change the node's parent keys. Incompatible with another ParentModification.
90 // definition for latch implementation
92 // exclusive is set for write access
93 // share is count of read accessors
94 // grant write lock when share == 0
96 volatile typedef struct {
97 unsigned char mutex[1];
98 unsigned char exclusive:1;
99 unsigned char pending:1;
103 // hash table entries
106 BtSpinLatch latch[1];
107 volatile ushort slot; // Latch table entry at head of chain
110 // latch manager table structure
113 BtSpinLatch readwr[1]; // read/write page lock
114 BtSpinLatch access[1]; // Access Intent/Page delete
115 BtSpinLatch parent[1]; // Posting of fence key in parent
116 BtSpinLatch busy[1]; // slot is being moved between chains
117 volatile ushort next; // next entry in hash table chain
118 volatile ushort prev; // prev entry in hash table chain
119 volatile ushort pin; // number of outstanding locks
120 volatile ushort hash; // hash slot entry is under
121 volatile uid page_no; // latch set page number
124 // Define the length of the page and key pointers
128 // Page key slot definition.
130 // If BT_maxbits is 15 or less, you can save 4 bytes
131 // for each key stored by making the first two uints
132 // into ushorts. You can also save 4 bytes by removing
133 // the tod field from the key.
135 // Keys are marked dead, but remain on the page until
136 // it cleanup is called. The fence key (highest key) for
137 // the page is always present, even after cleanup.
140 uint off:BT_maxbits; // page offset for key start
141 uint dead:1; // set for deleted key
142 uint tod; // time-stamp for key
143 unsigned char id[BtId]; // id associated with key
146 // The key structure occupies space at the upper end of
147 // each page. It's a length byte followed by the key
152 unsigned char key[1];
155 // The first part of an index page.
156 // It is immediately followed
157 // by the BtSlot array of keys.
159 typedef struct BtPage_ {
160 uint cnt; // count of keys in page
161 uint act; // count of active keys
162 uint min; // next key offset
163 unsigned char bits:7; // page size in bits
164 unsigned char free:1; // page is on free chain
165 unsigned char lvl:6; // level of page
166 unsigned char kill:1; // page is being deleted
167 unsigned char dirty:1; // page has deleted keys
168 unsigned char right[BtId]; // page number to right
171 // The memory mapping pool table buffer manager entry
174 uid basepage; // mapped base page number
175 char *map; // mapped memory pointer
176 ushort slot; // slot index in this array
177 ushort pin; // mapped page pin counter
178 void *hashprev; // previous pool entry for the same hash idx
179 void *hashnext; // next pool entry for the same hash idx
181 HANDLE hmap; // Windows memory mapping handle
185 #define CLOCK_bit 0x8000 // bit in pool->pin
187 // The loadpage interface object
190 uid page_no; // current page number
191 BtPage page; // current page pointer
192 BtPool *pool; // current page pool
193 BtLatchSet *latch; // current page latch set
196 // structure for latch manager on ALLOC_page
199 struct BtPage_ alloc[2]; // next & free page_nos in right ptr
200 BtSpinLatch lock[1]; // allocation area lite latch
201 ushort latchdeployed; // highest number of latch entries deployed
202 ushort nlatchpage; // number of latch pages at BT_latch
203 ushort latchtotal; // number of page latch entries
204 ushort latchhash; // number of latch hash table slots
205 ushort latchvictim; // next latch entry to examine
206 BtHashEntry table[0]; // the hash table
209 // The object structure for Btree access
212 uint page_size; // page size
213 uint page_bits; // page size in bits
214 uint seg_bits; // seg size in pages in bits
215 uint mode; // read-write mode
221 ushort poolcnt; // highest page pool node in use
222 ushort poolmax; // highest page pool node allocated
223 ushort poolmask; // total number of pages in mmap segment - 1
224 ushort hashsize; // size of Hash Table for pool entries
225 volatile uint evicted; // last evicted hash table slot
226 ushort *hash; // pool index for hash entries
227 BtSpinLatch *latch; // latches for hash table slots
228 BtLatchMgr *latchmgr; // mapped latch page from allocation page
229 BtLatchSet *latchsets; // mapped latch set from latch pages
230 BtPool *pool; // memory pool page segments
232 HANDLE halloc; // allocation and latch table handle
237 BtMgr *mgr; // buffer manager for thread
238 BtPage cursor; // cached frame for start/next (never mapped)
239 BtPage frame; // spare frame for the page split (never mapped)
240 BtPage zero; // page frame for zeroes at end of file
241 uid cursor_page; // current cursor page number
242 unsigned char *mem; // frame, cursor, page memory buffer
243 int found; // last delete or insert was found
244 int err; // last error
258 extern void bt_close (BtDb *bt);
259 extern BtDb *bt_open (BtMgr *mgr);
260 extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod);
261 extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl);
262 extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
263 extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
264 extern uint bt_nextkey (BtDb *bt, uint slot);
267 extern BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolsize, uint segsize, uint hashsize);
268 void bt_mgrclose (BtMgr *mgr);
270 // Helper functions to return slot values
272 extern BtKey bt_key (BtDb *bt, uint slot);
273 extern uid bt_uid (BtDb *bt, uint slot);
274 extern uint bt_tod (BtDb *bt, uint slot);
276 // BTree page number constants
277 #define ALLOC_page 0 // allocation & lock manager hash table
278 #define ROOT_page 1 // root of the btree
279 #define LEAF_page 2 // first page of leaves
280 #define LATCH_page 3 // pages for lock manager
282 // Number of levels to create in a new BTree
286 // The page is allocated from low and hi ends.
287 // The key offsets and row-id's are allocated
288 // from the bottom, while the text of the key
289 // is allocated from the top. When the two
290 // areas meet, the page is split into two.
292 // A key consists of a length byte, two bytes of
293 // index number (0 - 65534), and up to 253 bytes
294 // of key value. Duplicate keys are discarded.
295 // Associated with each key is a 48 bit row-id,
296 // or any other value desired.
298 // The b-tree root is always located at page 1.
299 // The first leaf page of level zero is always
300 // located on page 2.
302 // The b-tree pages are linked with next
303 // pointers to facilitate enumerators,
304 // and provide for concurrency.
306 // When to root page fills, it is split in two and
307 // the tree height is raised by a new root at page
308 // one with two keys.
310 // Deleted keys are marked with a dead bit until
311 // page cleanup. The fence key for a node is
314 // Groups of pages called segments from the btree are optionally
315 // cached with a memory mapped pool. A hash table is used to keep
316 // track of the cached segments. This behaviour is controlled
317 // by the cache block size parameter to bt_open.
319 // To achieve maximum concurrency one page is locked at a time
320 // as the tree is traversed to find leaf key in question. The right
321 // page numbers are used in cases where the page is being split,
324 // Page 0 is dedicated to lock for new page extensions,
325 // and chains empty pages together for reuse.
327 // The ParentModification lock on a node is obtained to serialize posting
328 // or changing the fence key for a node.
330 // Empty pages are chained together through the ALLOC page and reused.
332 // Access macros to address slot and key values from the page
333 // Page slots use 1 based indexing.
335 #define slotptr(page, slot) (((BtSlot *)(page+1)) + (slot-1))
336 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
338 void bt_putid(unsigned char *dest, uid id)
343 dest[i] = (unsigned char)id, id >>= 8;
346 uid bt_getid(unsigned char *src)
351 for( i = 0; i < BtId; i++ )
352 id <<= 8, id |= *src++;
359 // wait until write lock mode is clear
360 // and add 1 to the share count
362 void bt_spinreadlock(BtSpinLatch *latch)
367 // obtain latch mutex
369 if( __sync_lock_test_and_set(latch->mutex, 1) )
372 if( _InterlockedExchange8(latch->mutex, 1) )
375 // see if exclusive request is granted or pending
377 if( prev = !(latch->exclusive | latch->pending) )
383 _InterlockedExchange8(latch->mutex, 0);
390 } while( sched_yield(), 1 );
392 } while( SwitchToThread(), 1 );
396 // wait for other read and write latches to relinquish
398 void bt_spinwritelock(BtSpinLatch *latch)
404 if( __sync_lock_test_and_set(latch->mutex, 1) )
407 if( _InterlockedExchange8(latch->mutex, 1) )
410 if( prev = !(latch->share | latch->exclusive) )
411 latch->exclusive = 1, latch->pending = 0;
417 _InterlockedExchange8(latch->mutex, 0);
422 } while( sched_yield(), 1 );
424 } while( SwitchToThread(), 1 );
428 // try to obtain write lock
430 // return 1 if obtained,
433 int bt_spinwritetry(BtSpinLatch *latch)
438 if( __sync_lock_test_and_set(latch->mutex, 1) )
441 if( _InterlockedExchange8(latch->mutex, 1) )
444 // take write access if all bits are clear
446 if( prev = !(latch->exclusive | latch->share) )
447 latch->exclusive = 1;
452 _InterlockedExchange8(latch->mutex, 0);
459 void bt_spinreleasewrite(BtSpinLatch *latch)
462 while( __sync_lock_test_and_set(latch->mutex, 1) )
465 while( _InterlockedExchange8(latch->mutex, 1) )
468 latch->exclusive = 0;
472 _InterlockedExchange8(latch->mutex, 0);
476 // decrement reader count
478 void bt_spinreleaseread(BtSpinLatch *latch)
481 while( __sync_lock_test_and_set(latch->mutex, 1) )
484 while( _InterlockedExchange8(latch->mutex, 1) )
491 _InterlockedExchange8(latch->mutex, 0);
495 // link latch table entry into latch hash table
497 void bt_latchlink (BtDb *bt, ushort hashidx, ushort victim, uid page_no)
499 BtLatchSet *set = bt->mgr->latchsets + victim;
501 if( set->next = bt->mgr->latchmgr->table[hashidx].slot )
502 bt->mgr->latchsets[set->next].prev = victim;
504 bt->mgr->latchmgr->table[hashidx].slot = victim;
505 set->page_no = page_no;
512 void bt_unpinlatch (BtLatchSet *set)
515 __sync_fetch_and_add(&set->pin, -1);
517 _InterlockedDecrement16 (&set->pin);
521 // find existing latchset or inspire new one
522 // return with latchset pinned
524 BtLatchSet *bt_pinlatch (BtDb *bt, uid page_no)
526 ushort hashidx = page_no % bt->mgr->latchmgr->latchhash;
527 ushort slot, avail = 0, victim, idx;
530 // obtain read lock on hash table entry
532 bt_spinreadlock(bt->mgr->latchmgr->table[hashidx].latch);
534 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
536 set = bt->mgr->latchsets + slot;
537 if( page_no == set->page_no )
539 } while( slot = set->next );
543 __sync_fetch_and_add(&set->pin, 1);
545 _InterlockedIncrement16 (&set->pin);
549 bt_spinreleaseread (bt->mgr->latchmgr->table[hashidx].latch);
554 // try again, this time with write lock
556 bt_spinwritelock(bt->mgr->latchmgr->table[hashidx].latch);
558 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
560 set = bt->mgr->latchsets + slot;
561 if( page_no == set->page_no )
563 if( !set->pin && !avail )
565 } while( slot = set->next );
567 // found our entry, or take over an unpinned one
569 if( slot || (slot = avail) ) {
570 set = bt->mgr->latchsets + slot;
572 __sync_fetch_and_add(&set->pin, 1);
574 _InterlockedIncrement16 (&set->pin);
576 set->page_no = page_no;
577 bt_spinreleasewrite(bt->mgr->latchmgr->table[hashidx].latch);
581 // see if there are any unused entries
583 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, 1) + 1;
585 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchdeployed);
588 if( victim < bt->mgr->latchmgr->latchtotal ) {
589 set = bt->mgr->latchsets + victim;
591 __sync_fetch_and_add(&set->pin, 1);
593 _InterlockedIncrement16 (&set->pin);
595 bt_latchlink (bt, hashidx, victim, page_no);
596 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
601 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, -1);
603 victim = _InterlockedDecrement16 (&bt->mgr->latchmgr->latchdeployed);
605 // find and reuse previous lock entry
609 victim = __sync_fetch_and_add(&bt->mgr->latchmgr->latchvictim, 1);
611 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchvictim) - 1;
613 // we don't use slot zero
615 if( victim %= bt->mgr->latchmgr->latchtotal )
616 set = bt->mgr->latchsets + victim;
620 // take control of our slot
621 // from other threads
623 if( set->pin || !bt_spinwritetry (set->busy) )
628 // try to get write lock on hash chain
629 // skip entry if not obtained
630 // or has outstanding locks
632 if( !bt_spinwritetry (bt->mgr->latchmgr->table[idx].latch) ) {
633 bt_spinreleasewrite (set->busy);
638 bt_spinreleasewrite (set->busy);
639 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
643 // unlink our available victim from its hash chain
646 bt->mgr->latchsets[set->prev].next = set->next;
648 bt->mgr->latchmgr->table[idx].slot = set->next;
651 bt->mgr->latchsets[set->next].prev = set->prev;
653 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
655 __sync_fetch_and_add(&set->pin, 1);
657 _InterlockedIncrement16 (&set->pin);
659 bt_latchlink (bt, hashidx, victim, page_no);
660 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
661 bt_spinreleasewrite (set->busy);
666 void bt_mgrclose (BtMgr *mgr)
671 // release mapped pages
672 // note that slot zero is never used
674 for( slot = 1; slot < mgr->poolmax; slot++ ) {
675 pool = mgr->pool + slot;
678 munmap (pool->map, (mgr->poolmask+1) << mgr->page_bits);
681 FlushViewOfFile(pool->map, 0);
682 UnmapViewOfFile(pool->map);
683 CloseHandle(pool->hmap);
689 munmap (mgr->latchsets, mgr->latchmgr->nlatchpage * mgr->page_size);
690 munmap (mgr->latchmgr, mgr->page_size);
692 FlushViewOfFile(mgr->latchmgr, 0);
693 UnmapViewOfFile(mgr->latchmgr);
694 CloseHandle(mgr->halloc);
700 free ((void *)mgr->latch);
703 FlushFileBuffers(mgr->idx);
704 CloseHandle(mgr->idx);
705 GlobalFree (mgr->pool);
706 GlobalFree (mgr->hash);
707 GlobalFree ((void *)mgr->latch);
712 // close and release memory
714 void bt_close (BtDb *bt)
721 VirtualFree (bt->mem, 0, MEM_RELEASE);
726 // open/create new btree buffer manager
728 // call with file_name, BT_openmode, bits in page size (e.g. 16),
729 // size of mapped page pool (e.g. 8192)
731 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
733 uint lvl, attr, cacheblk, last, slot, idx;
734 uint nlatchpage, latchhash;
735 BtLatchMgr *latchmgr;
743 SYSTEM_INFO sysinfo[1];
746 // determine sanity of page size and buffer pool
748 if( bits > BT_maxbits )
750 else if( bits < BT_minbits )
754 return NULL; // must have buffer pool
757 mgr = calloc (1, sizeof(BtMgr));
759 mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
762 return free(mgr), NULL;
764 cacheblk = 4096; // minimum mmap segment size for unix
767 mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
768 attr = FILE_ATTRIBUTE_NORMAL;
769 mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
771 if( mgr->idx == INVALID_HANDLE_VALUE )
772 return GlobalFree(mgr), NULL;
774 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
775 GetSystemInfo(sysinfo);
776 cacheblk = sysinfo->dwAllocationGranularity;
780 latchmgr = malloc (BT_maxpage);
783 // read minimum page size to get root info
785 if( size = lseek (mgr->idx, 0L, 2) ) {
786 if( pread(mgr->idx, latchmgr, BT_minpage, 0) == BT_minpage )
787 bits = latchmgr->alloc->bits;
789 return free(mgr), free(latchmgr), NULL;
790 } else if( mode == BT_ro )
791 return free(latchmgr), bt_mgrclose (mgr), NULL;
793 latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
794 size = GetFileSize(mgr->idx, amt);
797 if( !ReadFile(mgr->idx, (char *)latchmgr, BT_minpage, amt, NULL) )
798 return bt_mgrclose (mgr), NULL;
799 bits = latchmgr->alloc->bits;
800 } else if( mode == BT_ro )
801 return bt_mgrclose (mgr), NULL;
804 mgr->page_size = 1 << bits;
805 mgr->page_bits = bits;
807 mgr->poolmax = poolmax;
810 if( cacheblk < mgr->page_size )
811 cacheblk = mgr->page_size;
813 // mask for partial memmaps
815 mgr->poolmask = (cacheblk >> bits) - 1;
817 // see if requested size of pages per memmap is greater
819 if( (1 << segsize) > mgr->poolmask )
820 mgr->poolmask = (1 << segsize) - 1;
824 while( (1 << mgr->seg_bits) <= mgr->poolmask )
827 mgr->hashsize = hashsize;
830 mgr->pool = calloc (poolmax, sizeof(BtPool));
831 mgr->hash = calloc (hashsize, sizeof(ushort));
832 mgr->latch = calloc (hashsize, sizeof(BtSpinLatch));
834 mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * sizeof(BtPool));
835 mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
836 mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtSpinLatch));
842 // initialize an empty b-tree with latch page, root page, page of leaves
843 // and page(s) of latches
845 memset (latchmgr, 0, 1 << bits);
846 nlatchpage = BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1;
847 bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
848 latchmgr->alloc->bits = mgr->page_bits;
850 latchmgr->nlatchpage = nlatchpage;
851 latchmgr->latchtotal = nlatchpage * (mgr->page_size / sizeof(BtLatchSet));
853 // initialize latch manager
855 latchhash = (mgr->page_size - sizeof(BtLatchMgr)) / sizeof(BtHashEntry);
857 // size of hash table = total number of latchsets
859 if( latchhash > latchmgr->latchtotal )
860 latchhash = latchmgr->latchtotal;
862 latchmgr->latchhash = latchhash;
865 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
866 return bt_mgrclose (mgr), NULL;
868 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
869 return bt_mgrclose (mgr), NULL;
871 if( *amt < mgr->page_size )
872 return bt_mgrclose (mgr), NULL;
875 memset (latchmgr, 0, 1 << bits);
876 latchmgr->alloc->bits = mgr->page_bits;
878 for( lvl=MIN_lvl; lvl--; ) {
879 slotptr(latchmgr->alloc, 1)->off = mgr->page_size - 3;
880 bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
881 key = keyptr(latchmgr->alloc, 1);
882 key->len = 2; // create stopper key
885 latchmgr->alloc->min = mgr->page_size - 3;
886 latchmgr->alloc->lvl = lvl;
887 latchmgr->alloc->cnt = 1;
888 latchmgr->alloc->act = 1;
890 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
891 return bt_mgrclose (mgr), NULL;
893 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
894 return bt_mgrclose (mgr), NULL;
896 if( *amt < mgr->page_size )
897 return bt_mgrclose (mgr), NULL;
901 // clear out latch manager locks
902 // and rest of pages to round out segment
904 memset(latchmgr, 0, mgr->page_size);
907 while( last <= ((MIN_lvl + 1 + nlatchpage) | mgr->poolmask) ) {
909 pwrite(mgr->idx, latchmgr, mgr->page_size, last << mgr->page_bits);
911 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
912 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
913 return bt_mgrclose (mgr), NULL;
914 if( *amt < mgr->page_size )
915 return bt_mgrclose (mgr), NULL;
922 flag = PROT_READ | PROT_WRITE;
923 mgr->latchmgr = mmap (0, mgr->page_size, flag, MAP_SHARED, mgr->idx, ALLOC_page * mgr->page_size);
924 if( mgr->latchmgr == MAP_FAILED )
925 return bt_mgrclose (mgr), NULL;
926 mgr->latchsets = (BtLatchSet *)mmap (0, mgr->latchmgr->nlatchpage * mgr->page_size, flag, MAP_SHARED, mgr->idx, LATCH_page * mgr->page_size);
927 if( mgr->latchsets == MAP_FAILED )
928 return bt_mgrclose (mgr), NULL;
930 flag = PAGE_READWRITE;
931 mgr->halloc = CreateFileMapping(mgr->idx, NULL, flag, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size, NULL);
933 return bt_mgrclose (mgr), NULL;
935 flag = FILE_MAP_WRITE;
936 mgr->latchmgr = MapViewOfFile(mgr->halloc, flag, 0, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size);
938 return GetLastError(), bt_mgrclose (mgr), NULL;
940 mgr->latchsets = (void *)((char *)mgr->latchmgr + LATCH_page * mgr->page_size);
946 VirtualFree (latchmgr, 0, MEM_RELEASE);
951 // open BTree access method
952 // based on buffer manager
954 BtDb *bt_open (BtMgr *mgr)
956 BtDb *bt = malloc (sizeof(*bt));
958 memset (bt, 0, sizeof(*bt));
961 bt->mem = malloc (3 *mgr->page_size);
963 bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
965 bt->frame = (BtPage)bt->mem;
966 bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
967 bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
969 memset (bt->zero, 0, mgr->page_size);
973 // compare two keys, returning > 0, = 0, or < 0
974 // as the comparison value
976 int keycmp (BtKey key1, unsigned char *key2, uint len2)
978 uint len1 = key1->len;
981 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
994 // find segment in pool
995 // must be called with hashslot idx locked
996 // return NULL if not there
997 // otherwise return node
999 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
1004 // compute start of hash chain in pool
1006 if( slot = bt->mgr->hash[idx] )
1007 pool = bt->mgr->pool + slot;
1011 page_no &= ~bt->mgr->poolmask;
1013 while( pool->basepage != page_no )
1014 if( pool = pool->hashnext )
1022 // add segment to hash table
1024 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
1029 pool->hashprev = pool->hashnext = NULL;
1030 pool->basepage = page_no & ~bt->mgr->poolmask;
1031 pool->pin = CLOCK_bit + 1;
1033 if( slot = bt->mgr->hash[idx] ) {
1034 node = bt->mgr->pool + slot;
1035 pool->hashnext = node;
1036 node->hashprev = pool;
1039 bt->mgr->hash[idx] = pool->slot;
1042 // map new buffer pool segment to virtual memory
1044 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
1046 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
1047 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
1051 flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
1052 pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED, bt->mgr->idx, off);
1053 if( pool->map == MAP_FAILED )
1054 return bt->err = BTERR_map;
1057 flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
1058 pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
1060 return bt->err = BTERR_map;
1062 flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
1063 pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1065 return bt->err = BTERR_map;
1070 // calculate page within pool
1072 BtPage bt_page (BtDb *bt, BtPool *pool, uid page_no)
1074 uint subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1077 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1083 void bt_unpinpool (BtPool *pool)
1086 __sync_fetch_and_add(&pool->pin, -1);
1088 _InterlockedDecrement16 (&pool->pin);
1092 // find or place requested page in segment-pool
1093 // return pool table entry, incrementing pin
1095 BtPool *bt_pinpool(BtDb *bt, uid page_no)
1097 uint slot, hashidx, idx, victim;
1098 BtPool *pool, *node, *next;
1100 // lock hash table chain
1102 hashidx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1103 bt_spinwritelock (&bt->mgr->latch[hashidx]);
1105 // look up in hash table
1107 if( pool = bt_findpool(bt, page_no, hashidx) ) {
1109 __sync_fetch_and_or(&pool->pin, CLOCK_bit);
1110 __sync_fetch_and_add(&pool->pin, 1);
1112 _InterlockedOr16 (&pool->pin, CLOCK_bit);
1113 _InterlockedIncrement16 (&pool->pin);
1115 bt_spinreleasewrite (&bt->mgr->latch[hashidx]);
1119 // allocate a new pool node
1120 // and add to hash table
1123 slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
1125 slot = _InterlockedIncrement16 (&bt->mgr->poolcnt) - 1;
1128 if( ++slot < bt->mgr->poolmax ) {
1129 pool = bt->mgr->pool + slot;
1132 if( bt_mapsegment(bt, pool, page_no) )
1135 bt_linkhash(bt, pool, page_no, hashidx);
1136 bt_spinreleasewrite (&bt->mgr->latch[hashidx]);
1140 // pool table is full
1141 // find best pool entry to evict
1144 __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
1146 _InterlockedDecrement16 (&bt->mgr->poolcnt);
1151 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
1153 victim = _InterlockedIncrement (&bt->mgr->evicted) - 1;
1155 victim %= bt->mgr->poolmax;
1156 pool = bt->mgr->pool + victim;
1157 idx = (uint)(pool->basepage >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1162 // try to get write lock
1163 // skip entry if not obtained
1165 if( !bt_spinwritetry (&bt->mgr->latch[idx]) )
1168 // skip this entry if
1170 // or clock bit is set
1174 __sync_fetch_and_and(&pool->pin, ~CLOCK_bit);
1176 _InterlockedAnd16 (&pool->pin, ~CLOCK_bit);
1178 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1182 // unlink victim pool node from hash table
1184 if( node = pool->hashprev )
1185 node->hashnext = pool->hashnext;
1186 else if( node = pool->hashnext )
1187 bt->mgr->hash[idx] = node->slot;
1189 bt->mgr->hash[idx] = 0;
1191 if( node = pool->hashnext )
1192 node->hashprev = pool->hashprev;
1194 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1196 // remove old file mapping
1198 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1200 FlushViewOfFile(pool->map, 0);
1201 UnmapViewOfFile(pool->map);
1202 CloseHandle(pool->hmap);
1206 // create new pool mapping
1207 // and link into hash table
1209 if( bt_mapsegment(bt, pool, page_no) )
1212 bt_linkhash(bt, pool, page_no, hashidx);
1213 bt_spinreleasewrite (&bt->mgr->latch[hashidx]);
1218 // place write, read, or parent lock on requested page_no.
1220 void bt_lockpage(BtLock mode, BtLatchSet *set)
1224 bt_spinreadlock (set->readwr);
1227 bt_spinwritelock (set->readwr);
1230 bt_spinreadlock (set->access);
1233 bt_spinwritelock (set->access);
1236 bt_spinwritelock (set->parent);
1241 // remove write, read, or parent lock on requested page
1243 void bt_unlockpage(BtLock mode, BtLatchSet *set)
1247 bt_spinreleaseread (set->readwr);
1250 bt_spinreleasewrite (set->readwr);
1253 bt_spinreleaseread (set->access);
1256 bt_spinreleasewrite (set->access);
1259 bt_spinreleasewrite (set->parent);
1264 // allocate a new page and write page into it
1266 uid bt_newpage(BtDb *bt, BtPage page)
1272 // lock allocation page
1274 bt_spinwritelock(bt->mgr->latchmgr->lock);
1276 // use empty chain first
1277 // else allocate empty page
1279 if( new_page = bt_getid(bt->mgr->latchmgr->alloc[1].right) ) {
1280 if( set->pool = bt_pinpool (bt, new_page) )
1281 set->page = bt_page (bt, set->pool, new_page);
1285 bt_putid(bt->mgr->latchmgr->alloc[1].right, bt_getid(set->page->right));
1286 bt_unpinpool (set->pool);
1289 new_page = bt_getid(bt->mgr->latchmgr->alloc->right);
1290 bt_putid(bt->mgr->latchmgr->alloc->right, new_page+1);
1294 if( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1295 return bt->err = BTERR_wrt, 0;
1297 // if writing first page of pool block, zero last page in the block
1299 if( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1301 // use zero buffer to write zeros
1302 if( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1303 return bt->err = BTERR_wrt, 0;
1306 // bring new page into pool and copy page.
1307 // this will extend the file into the new pages.
1309 if( set->pool = bt_pinpool (bt, new_page) )
1310 set->page = bt_page (bt, set->pool, new_page);
1314 memcpy(set->page, page, bt->mgr->page_size);
1315 bt_unpinpool (set->pool);
1317 // unlock allocation latch and return new page no
1319 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1323 // find slot in page for given key at a given level
1325 int bt_findslot (BtPageSet *set, unsigned char *key, uint len)
1327 uint diff, higher = set->page->cnt, low = 1, slot;
1330 // make stopper key an infinite fence value
1332 if( bt_getid (set->page->right) )
1337 // low is the lowest candidate.
1338 // loop ends when they meet
1340 // higher is already
1341 // tested as .ge. the passed key.
1343 while( diff = higher - low ) {
1344 slot = low + ( diff >> 1 );
1345 if( keycmp (keyptr(set->page, slot), key, len) < 0 )
1348 higher = slot, good++;
1351 // return zero if key is on right link page
1353 return good ? higher : 0;
1356 // find and load page at given level for given key
1357 // leave page rd or wr locked as requested
1359 int bt_loadpage (BtDb *bt, BtPageSet *set, unsigned char *key, uint len, uint lvl, BtLock lock)
1361 uid page_no = ROOT_page, prevpage = 0;
1362 uint drill = 0xff, slot;
1363 BtLatchSet *prevlatch;
1364 uint mode, prevmode;
1367 // start at root of btree and drill down
1370 // determine lock mode of drill level
1371 mode = (drill == lvl) ? lock : BtLockRead;
1373 set->latch = bt_pinlatch (bt, page_no);
1374 set->page_no = page_no;
1376 // pin page contents
1378 if( set->pool = bt_pinpool (bt, page_no) )
1379 set->page = bt_page (bt, set->pool, page_no);
1383 // obtain access lock using lock chaining with Access mode
1385 if( page_no > ROOT_page )
1386 bt_lockpage(BtLockAccess, set->latch);
1388 // release & unpin parent page
1391 bt_unlockpage(prevmode, prevlatch);
1392 bt_unpinlatch (prevlatch);
1393 bt_unpinpool (prevpool);
1397 // obtain read lock using lock chaining
1399 bt_lockpage(mode, set->latch);
1401 if( set->page->free )
1402 return bt->err = BTERR_struct, 0;
1404 if( page_no > ROOT_page )
1405 bt_unlockpage(BtLockAccess, set->latch);
1407 // re-read and re-lock root after determining actual level of root
1409 if( set->page->lvl != drill) {
1410 if( set->page_no != ROOT_page )
1411 return bt->err = BTERR_struct, 0;
1413 drill = set->page->lvl;
1415 if( lock != BtLockRead && drill == lvl ) {
1416 bt_unlockpage(mode, set->latch);
1417 bt_unpinlatch (set->latch);
1418 bt_unpinpool (set->pool);
1423 prevpage = set->page_no;
1424 prevlatch = set->latch;
1425 prevpool = set->pool;
1428 // find key on page at this level
1429 // and descend to requested level
1431 if( !set->page->kill )
1432 if( slot = bt_findslot (set, key, len) ) {
1436 while( slotptr(set->page, slot)->dead )
1437 if( slot++ < set->page->cnt )
1442 page_no = bt_getid(slotptr(set->page, slot)->id);
1447 // or slide right into next page
1450 page_no = bt_getid(set->page->right);
1454 // return error on end of right chain
1456 bt->err = BTERR_struct;
1457 return 0; // return error
1460 // return page to free list
1461 // page must be delete & write locked
1463 void bt_freepage (BtDb *bt, BtPageSet *set)
1465 // lock allocation page
1467 bt_spinwritelock (bt->mgr->latchmgr->lock);
1469 // store chain in second right
1470 bt_putid(set->page->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1471 bt_putid(bt->mgr->latchmgr->alloc[1].right, set->page_no);
1472 set->page->free = 1;
1474 // unlock released page
1476 bt_unlockpage (BtLockDelete, set->latch);
1477 bt_unlockpage (BtLockWrite, set->latch);
1478 bt_unpinlatch (set->latch);
1479 bt_unpinpool (set->pool);
1481 // unlock allocation page
1483 bt_spinreleasewrite (bt->mgr->latchmgr->lock);
1486 // a fence key was deleted from a page
1487 // push new fence value upwards
1489 BTERR bt_fixfence (BtDb *bt, BtPageSet *set, uint lvl)
1491 unsigned char leftkey[256], rightkey[256];
1495 // remove the old fence value
1497 ptr = keyptr(set->page, set->page->cnt);
1498 memcpy (rightkey, ptr, ptr->len + 1);
1500 memset (slotptr(set->page, set->page->cnt--), 0, sizeof(BtSlot));
1501 set->page->dirty = 1;
1503 ptr = keyptr(set->page, set->page->cnt);
1504 memcpy (leftkey, ptr, ptr->len + 1);
1505 page_no = set->page_no;
1507 bt_lockpage (BtLockParent, set->latch);
1508 bt_unlockpage (BtLockWrite, set->latch);
1510 // insert new (now smaller) fence key
1512 if( bt_insertkey (bt, leftkey+1, *leftkey, lvl+1, page_no, time(NULL)) )
1515 // now delete old fence key
1517 if( bt_deletekey (bt, rightkey+1, *rightkey, lvl+1) )
1520 bt_unlockpage (BtLockParent, set->latch);
1521 bt_unpinlatch(set->latch);
1522 bt_unpinpool (set->pool);
1526 // root has a single child
1527 // collapse a level from the tree
1529 BTERR bt_collapseroot (BtDb *bt, BtPageSet *root)
1534 // find the child entry and promote as new root contents
1537 for( idx = 0; idx++ < root->page->cnt; )
1538 if( !slotptr(root->page, idx)->dead )
1541 child->page_no = bt_getid (slotptr(root->page, idx)->id);
1543 child->latch = bt_pinlatch (bt, child->page_no);
1544 bt_lockpage (BtLockDelete, child->latch);
1545 bt_lockpage (BtLockWrite, child->latch);
1547 if( child->pool = bt_pinpool (bt, child->page_no) )
1548 child->page = bt_page (bt, child->pool, child->page_no);
1552 memcpy (root->page, child->page, bt->mgr->page_size);
1553 bt_freepage (bt, child);
1555 } while( root->page->lvl > 1 && root->page->act == 1 );
1557 bt_unlockpage (BtLockWrite, root->latch);
1558 bt_unpinlatch (root->latch);
1559 bt_unpinpool (root->pool);
1563 // find and delete key on page by marking delete flag bit
1564 // if page becomes empty, delete it from the btree
1566 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl)
1568 unsigned char lowerfence[256], higherfence[256];
1569 uint slot, idx, dirty = 0, fence, found;
1570 BtPageSet set[1], right[1];
1573 if( slot = bt_loadpage (bt, set, key, len, lvl, BtLockWrite) )
1574 ptr = keyptr(set->page, slot);
1578 // are we deleting a fence slot?
1580 fence = slot == set->page->cnt;
1582 // if key is found delete it, otherwise ignore request
1584 if( found = !keycmp (ptr, key, len) )
1585 if( found = slotptr(set->page, slot)->dead == 0 ) {
1586 dirty = slotptr(set->page, slot)->dead = 1;
1587 set->page->dirty = 1;
1590 // collapse empty slots
1592 while( idx = set->page->cnt - 1 )
1593 if( slotptr(set->page, idx)->dead ) {
1594 *slotptr(set->page, idx) = *slotptr(set->page, idx + 1);
1595 memset (slotptr(set->page, set->page->cnt--), 0, sizeof(BtSlot));
1600 // did we delete a fence key in an upper level?
1602 if( dirty && lvl && set->page->act && fence )
1603 if( bt_fixfence (bt, set, lvl) )
1606 return bt->found = found, 0;
1608 // is this a collapsed root?
1610 if( lvl > 1 && set->page_no == ROOT_page && set->page->act == 1 )
1611 if( bt_collapseroot (bt, set) )
1614 return bt->found = found, 0;
1616 // return if page is not empty
1618 if( set->page->act ) {
1619 bt_unlockpage(BtLockWrite, set->latch);
1620 bt_unpinlatch (set->latch);
1621 bt_unpinpool (set->pool);
1622 return bt->found = found, 0;
1625 // cache copy of fence key
1626 // to post in parent
1628 ptr = keyptr(set->page, set->page->cnt);
1629 memcpy (lowerfence, ptr, ptr->len + 1);
1631 // obtain lock on right page
1633 right->page_no = bt_getid(set->page->right);
1634 right->latch = bt_pinlatch (bt, right->page_no);
1635 bt_lockpage (BtLockWrite, right->latch);
1637 // pin page contents
1639 if( right->pool = bt_pinpool (bt, right->page_no) )
1640 right->page = bt_page (bt, right->pool, right->page_no);
1644 if( right->page->kill )
1645 return bt->err = BTERR_struct;
1647 // pull contents of right peer into our empty page
1649 memcpy (set->page, right->page, bt->mgr->page_size);
1651 // cache copy of key to update
1653 ptr = keyptr(right->page, right->page->cnt);
1654 memcpy (higherfence, ptr, ptr->len + 1);
1656 // mark right page deleted and point it to left page
1657 // until we can post parent updates
1659 bt_putid (right->page->right, set->page_no);
1660 right->page->kill = 1;
1662 bt_lockpage (BtLockParent, right->latch);
1663 bt_unlockpage (BtLockWrite, right->latch);
1665 bt_lockpage (BtLockParent, set->latch);
1666 bt_unlockpage (BtLockWrite, set->latch);
1668 // redirect higher key directly to our new node contents
1670 if( bt_insertkey (bt, higherfence+1, *higherfence, lvl+1, set->page_no, time(NULL)) )
1673 // delete old lower key to our node
1675 if( bt_deletekey (bt, lowerfence+1, *lowerfence, lvl+1) )
1678 // obtain delete and write locks to right node
1680 bt_unlockpage (BtLockParent, right->latch);
1681 bt_lockpage (BtLockDelete, right->latch);
1682 bt_lockpage (BtLockWrite, right->latch);
1683 bt_freepage (bt, right);
1685 bt_unlockpage (BtLockParent, set->latch);
1686 bt_unpinlatch (set->latch);
1687 bt_unpinpool (set->pool);
1692 // find key in leaf level and return row-id
1694 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1701 if( slot = bt_loadpage (bt, set, key, len, 0, BtLockRead) )
1702 ptr = keyptr(set->page, slot);
1706 // if key exists, return row-id
1707 // otherwise return 0
1709 if( slot <= set->page->cnt )
1710 if( !keycmp (ptr, key, len) )
1711 id = bt_getid(slotptr(set->page,slot)->id);
1713 bt_unlockpage (BtLockRead, set->latch);
1714 bt_unpinlatch (set->latch);
1715 bt_unpinpool (set->pool);
1719 // check page for space available,
1720 // clean if necessary and return
1721 // 0 - page needs splitting
1722 // >0 new slot value
1724 uint bt_cleanpage(BtDb *bt, BtPage page, uint amt, uint slot)
1726 uint nxt = bt->mgr->page_size;
1727 uint cnt = 0, idx = 0;
1728 uint max = page->cnt;
1732 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1735 // skip cleanup if nothing to reclaim
1740 memcpy (bt->frame, page, bt->mgr->page_size);
1742 // skip page info and set rest of page to zero
1744 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1748 // try cleaning up page first
1749 // by removing deleted keys
1751 while( cnt++ < max ) {
1754 if( cnt < max && slotptr(bt->frame,cnt)->dead )
1757 // copy the key across
1759 key = keyptr(bt->frame, cnt);
1760 nxt -= key->len + 1;
1761 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1765 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1766 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1768 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1769 slotptr(page, idx)->off = nxt;
1775 // see if page has enough space now, or does it need splitting?
1777 if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1783 // split the root and raise the height of the btree
1785 BTERR bt_splitroot(BtDb *bt, BtPageSet *root, unsigned char *leftkey, uid page_no2)
1787 uint nxt = bt->mgr->page_size;
1790 // Obtain an empty page to use, and copy the current
1791 // root contents into it, e.g. lower keys
1793 if( !(left = bt_newpage(bt, root->page)) )
1796 // preserve the page info at the bottom
1797 // of higher keys and set rest to zero
1799 memset(root->page+1, 0, bt->mgr->page_size - sizeof(*root->page));
1801 // insert lower keys page fence key on newroot page as first key
1803 nxt -= *leftkey + 1;
1804 memcpy ((unsigned char *)root->page + nxt, leftkey, *leftkey + 1);
1805 bt_putid(slotptr(root->page, 1)->id, left);
1806 slotptr(root->page, 1)->off = nxt;
1808 // insert stopper key on newroot page
1809 // and increase the root height
1812 ((unsigned char *)root->page)[nxt] = 2;
1813 ((unsigned char *)root->page)[nxt+1] = 0xff;
1814 ((unsigned char *)root->page)[nxt+2] = 0xff;
1815 bt_putid(slotptr(root->page, 2)->id, page_no2);
1816 slotptr(root->page, 2)->off = nxt;
1818 bt_putid(root->page->right, 0);
1819 root->page->min = nxt; // reset lowest used offset and key count
1820 root->page->cnt = 2;
1821 root->page->act = 2;
1824 // release and unpin root
1826 bt_unlockpage(BtLockWrite, root->latch);
1827 bt_unpinlatch (root->latch);
1828 bt_unpinpool (root->pool);
1832 // split already locked full node
1835 BTERR bt_splitpage (BtDb *bt, BtPageSet *set)
1837 uint cnt = 0, idx = 0, max, nxt = bt->mgr->page_size;
1838 unsigned char fencekey[256], rightkey[256];
1839 uint lvl = set->page->lvl;
1844 // split higher half of keys to bt->frame
1846 memset (bt->frame, 0, bt->mgr->page_size);
1847 max = set->page->cnt;
1851 while( cnt++ < max ) {
1852 key = keyptr(set->page, cnt);
1853 nxt -= key->len + 1;
1854 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
1856 memcpy(slotptr(bt->frame,++idx)->id, slotptr(set->page,cnt)->id, BtId);
1857 if( !(slotptr(bt->frame, idx)->dead = slotptr(set->page, cnt)->dead) )
1859 slotptr(bt->frame, idx)->tod = slotptr(set->page, cnt)->tod;
1860 slotptr(bt->frame, idx)->off = nxt;
1863 // remember existing fence key for new page to the right
1865 memcpy (rightkey, key, key->len + 1);
1867 bt->frame->bits = bt->mgr->page_bits;
1868 bt->frame->min = nxt;
1869 bt->frame->cnt = idx;
1870 bt->frame->lvl = lvl;
1874 if( set->page_no > ROOT_page )
1875 memcpy (bt->frame->right, set->page->right, BtId);
1877 // get new free page and write higher keys to it.
1879 if( !(right->page_no = bt_newpage(bt, bt->frame)) )
1882 // update lower keys to continue in old page
1884 memcpy (bt->frame, set->page, bt->mgr->page_size);
1885 memset (set->page+1, 0, bt->mgr->page_size - sizeof(*set->page));
1886 nxt = bt->mgr->page_size;
1887 set->page->dirty = 0;
1892 // assemble page of smaller keys
1894 while( cnt++ < max / 2 ) {
1895 key = keyptr(bt->frame, cnt);
1896 nxt -= key->len + 1;
1897 memcpy ((unsigned char *)set->page + nxt, key, key->len + 1);
1898 memcpy(slotptr(set->page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1899 slotptr(set->page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1900 slotptr(set->page, idx)->off = nxt;
1904 // remember fence key for smaller page
1906 memcpy(fencekey, key, key->len + 1);
1908 bt_putid(set->page->right, right->page_no);
1909 set->page->min = nxt;
1910 set->page->cnt = idx;
1912 // if current page is the root page, split it
1914 if( set->page_no == ROOT_page )
1915 return bt_splitroot (bt, set, fencekey, right->page_no);
1917 // insert new fences in their parent pages
1919 right->latch = bt_pinlatch (bt, right->page_no);
1920 bt_lockpage (BtLockParent, right->latch);
1922 bt_lockpage (BtLockParent, set->latch);
1923 bt_unlockpage (BtLockWrite, set->latch);
1925 // insert new fence for reformulated left block of smaller keys
1927 if( bt_insertkey (bt, fencekey+1, *fencekey, lvl+1, set->page_no, time(NULL)) )
1930 // switch fence for right block of larger keys to new right page
1932 if( bt_insertkey (bt, rightkey+1, *rightkey, lvl+1, right->page_no, time(NULL)) )
1935 bt_unlockpage (BtLockParent, set->latch);
1936 bt_unpinlatch (set->latch);
1937 bt_unpinpool (set->pool);
1939 bt_unlockpage (BtLockParent, right->latch);
1940 bt_unpinlatch (right->latch);
1943 // Insert new key into the btree at given level.
1945 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod)
1952 if( slot = bt_loadpage (bt, set, key, len, lvl, BtLockWrite) )
1953 ptr = keyptr(set->page, slot);
1957 bt->err = BTERR_ovflw;
1961 // if key already exists, update id and return
1963 if( !keycmp (ptr, key, len) ) {
1964 if( slotptr(set->page, slot)->dead )
1966 slotptr(set->page, slot)->dead = 0;
1967 slotptr(set->page, slot)->tod = tod;
1968 bt_putid(slotptr(set->page,slot)->id, id);
1969 bt_unlockpage(BtLockWrite, set->latch);
1970 bt_unpinlatch (set->latch);
1971 bt_unpinpool (set->pool);
1975 // check if page has enough space
1977 if( slot = bt_cleanpage (bt, set->page, len, slot) )
1980 if( bt_splitpage (bt, set) )
1984 // calculate next available slot and copy key into page
1986 set->page->min -= len + 1; // reset lowest used offset
1987 ((unsigned char *)set->page)[set->page->min] = len;
1988 memcpy ((unsigned char *)set->page + set->page->min +1, key, len );
1990 for( idx = slot; idx < set->page->cnt; idx++ )
1991 if( slotptr(set->page, idx)->dead )
1994 // now insert key into array before slot
1996 if( idx == set->page->cnt )
1997 idx++, set->page->cnt++;
2002 *slotptr(set->page, idx) = *slotptr(set->page, idx -1), idx--;
2004 bt_putid(slotptr(set->page,slot)->id, id);
2005 slotptr(set->page, slot)->off = set->page->min;
2006 slotptr(set->page, slot)->tod = tod;
2007 slotptr(set->page, slot)->dead = 0;
2009 bt_unlockpage (BtLockWrite, set->latch);
2010 bt_unpinlatch (set->latch);
2011 bt_unpinpool (set->pool);
2015 // cache page of keys into cursor and return starting slot for given key
2017 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2022 // cache page for retrieval
2024 if( slot = bt_loadpage (bt, set, key, len, 0, BtLockRead) )
2025 memcpy (bt->cursor, set->page, bt->mgr->page_size);
2029 bt->cursor_page = set->page_no;
2031 bt_unlockpage(BtLockRead, set->latch);
2032 bt_unpinlatch (set->latch);
2033 bt_unpinpool (set->pool);
2037 // return next slot for cursor page
2038 // or slide cursor right into next page
2040 uint bt_nextkey (BtDb *bt, uint slot)
2046 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) ) // skip infinite stopper
2059 bt->cursor_page = right;
2061 if( set->pool = bt_pinpool (bt, right) )
2062 set->page = bt_page (bt, set->pool, right);
2066 set->latch = bt_pinlatch (bt, right);
2067 bt_lockpage(BtLockRead, set->latch);
2069 memcpy (bt->cursor, set->page, bt->mgr->page_size);
2071 bt_unlockpage(BtLockRead, set->latch);
2072 bt_unpinlatch (set->latch);
2073 bt_unpinpool (set->pool);
2081 BtKey bt_key(BtDb *bt, uint slot)
2083 return keyptr(bt->cursor, slot);
2086 uid bt_uid(BtDb *bt, uint slot)
2088 return bt_getid(slotptr(bt->cursor,slot)->id);
2091 uint bt_tod(BtDb *bt, uint slot)
2093 return slotptr(bt->cursor,slot)->tod;
2099 double getCpuTime(int type)
2102 FILETIME xittime[1];
2103 FILETIME systime[1];
2104 FILETIME usrtime[1];
2105 SYSTEMTIME timeconv[1];
2108 memset (timeconv, 0, sizeof(SYSTEMTIME));
2112 GetSystemTimeAsFileTime (xittime);
2113 FileTimeToSystemTime (xittime, timeconv);
2114 ans = (double)timeconv->wDayOfWeek * 3600 * 24;
2117 GetProcessTimes (GetCurrentProcess(), crtime, xittime, systime, usrtime);
2118 FileTimeToSystemTime (usrtime, timeconv);
2121 GetProcessTimes (GetCurrentProcess(), crtime, xittime, systime, usrtime);
2122 FileTimeToSystemTime (systime, timeconv);
2126 ans += (double)timeconv->wHour * 3600;
2127 ans += (double)timeconv->wMinute * 60;
2128 ans += (double)timeconv->wSecond;
2129 ans += (double)timeconv->wMilliseconds / 1000;
2134 #include <sys/resource.h>
2136 double getCpuTime(int type)
2138 struct rusage used[1];
2139 struct timeval tv[1];
2143 gettimeofday(tv, NULL);
2144 return (double)tv->tv_sec + (double)tv->tv_usec / 1000000;
2147 getrusage(RUSAGE_SELF, used);
2148 return (double)used->ru_utime.tv_sec + (double)used->ru_utime.tv_usec / 1000000;
2151 getrusage(RUSAGE_SELF, used);
2152 return (double)used->ru_stime.tv_sec + (double)used->ru_stime.tv_usec / 1000000;
2159 void bt_latchaudit (BtDb *bt)
2161 ushort idx, hashidx;
2167 if( *(uint *)(bt->mgr->latchmgr->lock) )
2168 fprintf(stderr, "Alloc page locked\n");
2169 *(uint *)(bt->mgr->latchmgr->lock) = 0;
2171 for( idx = 1; idx <= bt->mgr->latchmgr->latchdeployed; idx++ ) {
2172 latch = bt->mgr->latchsets + idx;
2173 if( *(uint *)latch->readwr )
2174 fprintf(stderr, "latchset %d rwlocked for page %.8x\n", idx, latch->page_no);
2175 *(uint *)latch->readwr = 0;
2177 if( *(uint *)latch->access )
2178 fprintf(stderr, "latchset %d accesslocked for page %.8x\n", idx, latch->page_no);
2179 *(uint *)latch->access = 0;
2181 if( *(uint *)latch->parent )
2182 fprintf(stderr, "latchset %d parentlocked for page %.8x\n", idx, latch->page_no);
2183 *(uint *)latch->parent = 0;
2186 fprintf(stderr, "latchset %d pinned for page %.8x\n", idx, latch->page_no);
2191 for( hashidx = 0; hashidx < bt->mgr->latchmgr->latchhash; hashidx++ ) {
2192 if( *(uint *)(bt->mgr->latchmgr->table[hashidx].latch) )
2193 fprintf(stderr, "hash entry %d locked\n", hashidx);
2195 *(uint *)(bt->mgr->latchmgr->table[hashidx].latch) = 0;
2197 if( idx = bt->mgr->latchmgr->table[hashidx].slot ) do {
2198 latch = bt->mgr->latchsets + idx;
2199 if( *(uint *)latch->busy )
2200 fprintf(stderr, "latchset %d busylocked for page %.8x\n", idx, latch->page_no);
2201 *(uint *)latch->busy = 0;
2202 if( latch->hash != hashidx )
2203 fprintf(stderr, "latchset %d wrong hashidx\n", idx);
2205 fprintf(stderr, "latchset %d pinned for page %.8x\n", idx, latch->page_no);
2206 } while( idx = latch->next );
2209 next = bt->mgr->latchmgr->nlatchpage + LATCH_page;
2210 page_no = LEAF_page;
2212 while( page_no < bt_getid(bt->mgr->latchmgr->alloc->right) ) {
2213 pread (bt->mgr->idx, bt->frame, bt->mgr->page_size, page_no << bt->mgr->page_bits);
2214 if( !bt->frame->free )
2215 for( idx = 0; idx++ < bt->frame->cnt - 1; ) {
2216 ptr = keyptr(bt->frame, idx+1);
2217 if( keycmp (keyptr(bt->frame, idx), ptr->key, ptr->len) >= 0 )
2218 fprintf(stderr, "page %.8x idx %.2x out of order\n", page_no, idx);
2221 if( page_no > LEAF_page )
2235 // standalone program to index file of keys
2236 // then list them onto std-out
2239 void *index_file (void *arg)
2241 uint __stdcall index_file (void *arg)
2244 int line = 0, found = 0, cnt = 0;
2245 uid next, page_no = LEAF_page; // start on first page of leaves
2246 unsigned char key[256];
2247 ThreadArg *args = arg;
2248 int ch, len = 0, slot;
2255 bt = bt_open (args->mgr);
2258 switch(args->type | 0x20)
2261 fprintf(stderr, "started latch mgr audit\n");
2263 fprintf(stderr, "finished latch mgr audit\n");
2267 fprintf(stderr, "started indexing for %s\n", args->infile);
2268 if( in = fopen (args->infile, "rb") )
2269 while( ch = getc(in), ch != EOF )
2274 if( args->num == 1 )
2275 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2277 else if( args->num )
2278 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2280 if( bt_insertkey (bt, key, len, 0, line, *tod) )
2281 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2284 else if( len < 255 )
2286 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
2290 fprintf(stderr, "started deleting keys for %s\n", args->infile);
2291 if( in = fopen (args->infile, "rb") )
2292 while( ch = getc(in), ch != EOF )
2296 if( args->num == 1 )
2297 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2299 else if( args->num )
2300 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2302 if( bt_deletekey (bt, key, len, 0) )
2303 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2306 else if( len < 255 )
2308 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2312 fprintf(stderr, "started finding keys for %s\n", args->infile);
2313 if( in = fopen (args->infile, "rb") )
2314 while( ch = getc(in), ch != EOF )
2318 if( args->num == 1 )
2319 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2321 else if( args->num )
2322 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2324 if( bt_findkey (bt, key, len) )
2327 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2330 else if( len < 255 )
2332 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2336 fprintf(stderr, "started scanning\n");
2338 if( set->pool = bt_pinpool (bt, page_no) )
2339 set->page = bt_page (bt, set->pool, page_no);
2342 set->latch = bt_pinlatch (bt, page_no);
2343 bt_lockpage (BtLockRead, set->latch);
2344 next = bt_getid (set->page->right);
2345 cnt += set->page->act;
2347 for( slot = 0; slot++ < set->page->cnt; )
2348 if( next || slot < set->page->cnt )
2349 if( !slotptr(set->page, slot)->dead ) {
2350 ptr = keyptr(set->page, slot);
2351 fwrite (ptr->key, ptr->len, 1, stdout);
2352 fputc ('\n', stdout);
2355 bt_unlockpage (BtLockRead, set->latch);
2356 bt_unpinlatch (set->latch);
2357 bt_unpinpool (set->pool);
2358 } while( page_no = next );
2360 cnt--; // remove stopper key
2361 fprintf(stderr, " Total keys read %d\n", cnt);
2365 fprintf(stderr, "started counting\n");
2366 next = bt->mgr->latchmgr->nlatchpage + LATCH_page;
2367 page_no = LEAF_page;
2369 while( page_no < bt_getid(bt->mgr->latchmgr->alloc->right) ) {
2370 uid off = page_no << bt->mgr->page_bits;
2372 pread (bt->mgr->idx, bt->frame, bt->mgr->page_size, off);
2376 SetFilePointer (bt->mgr->idx, (long)off, (long*)(&off)+1, FILE_BEGIN);
2378 if( !ReadFile(bt->mgr->idx, bt->frame, bt->mgr->page_size, amt, NULL))
2379 return bt->err = BTERR_map;
2381 if( *amt < bt->mgr->page_size )
2382 return bt->err = BTERR_map;
2384 if( !bt->frame->free && !bt->frame->lvl )
2385 cnt += bt->frame->act;
2386 if( page_no > LEAF_page )
2391 cnt--; // remove stopper key
2392 fprintf(stderr, " Total keys read %d\n", cnt);
2404 typedef struct timeval timer;
2406 int main (int argc, char **argv)
2408 int idx, cnt, len, slot, err;
2409 int segsize, bits = 16;
2426 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]);
2427 fprintf (stderr, " where page_bits is the page size in bits\n");
2428 fprintf (stderr, " mapped_segments is the number of mmap segments in buffer pool\n");
2429 fprintf (stderr, " seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2430 fprintf (stderr, " line_numbers = 1 to append line numbers to keys\n");
2431 fprintf (stderr, " src_file1 thru src_filen are files of keys separated by newline\n");
2435 start = getCpuTime(0);
2438 bits = atoi(argv[3]);
2441 poolsize = atoi(argv[4]);
2444 fprintf (stderr, "Warning: no mapped_pool\n");
2446 if( poolsize > 65535 )
2447 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2450 segsize = atoi(argv[5]);
2452 segsize = 4; // 16 pages per mmap segment
2455 num = atoi(argv[6]);
2459 threads = malloc (cnt * sizeof(pthread_t));
2461 threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2463 args = malloc (cnt * sizeof(ThreadArg));
2465 mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2468 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2474 for( idx = 0; idx < cnt; idx++ ) {
2475 args[idx].infile = argv[idx + 7];
2476 args[idx].type = argv[2][0];
2477 args[idx].mgr = mgr;
2478 args[idx].num = num;
2479 args[idx].idx = idx;
2481 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2482 fprintf(stderr, "Error creating thread %d\n", err);
2484 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2488 // wait for termination
2491 for( idx = 0; idx < cnt; idx++ )
2492 pthread_join (threads[idx], NULL);
2494 WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2496 for( idx = 0; idx < cnt; idx++ )
2497 CloseHandle(threads[idx]);
2500 elapsed = getCpuTime(0) - start;
2501 fprintf(stderr, " real %dm%.3fs\n", (int)(elapsed/60), elapsed - (int)(elapsed/60)*60);
2502 elapsed = getCpuTime(1);
2503 fprintf(stderr, " user %dm%.3fs\n", (int)(elapsed/60), elapsed - (int)(elapsed/60)*60);
2504 elapsed = getCpuTime(2);
2505 fprintf(stderr, " sys %dm%.3fs\n", (int)(elapsed/60), elapsed - (int)(elapsed/60)*60);