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 unsigned long long int lru; // number of times accessed
175 uid basepage; // mapped base page number
176 char *map; // mapped memory pointer
177 ushort slot; // slot index in this array
178 ushort pin; // mapped page pin counter
179 void *hashprev; // previous pool entry for the same hash idx
180 void *hashnext; // next pool entry for the same hash idx
182 HANDLE hmap; // Windows memory mapping handle
186 // The loadpage interface object
189 uid page_no; // current page number
190 BtPage page; // current page pointer
191 BtPool *pool; // current page pool
192 BtLatchSet *latch; // current page latch set
195 // structure for latch manager on ALLOC_page
198 struct BtPage_ alloc[2]; // next & free page_nos in right ptr
199 BtSpinLatch lock[1]; // allocation area lite latch
200 ushort latchdeployed; // highest number of latch entries deployed
201 ushort nlatchpage; // number of latch pages at BT_latch
202 ushort latchtotal; // number of page latch entries
203 ushort latchhash; // number of latch hash table slots
204 ushort latchvictim; // next latch entry to examine
205 BtHashEntry table[0]; // the hash table
208 // The object structure for Btree access
211 uint page_size; // page size
212 uint page_bits; // page size in bits
213 uint seg_bits; // seg size in pages in bits
214 uint mode; // read-write mode
220 ushort poolcnt; // highest page pool node in use
221 ushort poolmax; // highest page pool node allocated
222 ushort poolmask; // total number of pages in mmap segment - 1
223 ushort hashsize; // size of Hash Table for pool entries
224 volatile uint evicted; // last evicted hash table slot
225 ushort *hash; // pool index for hash entries
226 BtSpinLatch *latch; // latches for hash table slots
227 BtLatchMgr *latchmgr; // mapped latch page from allocation page
228 BtLatchSet *latchsets; // mapped latch set from latch pages
229 BtPool *pool; // memory pool page segments
231 HANDLE halloc; // allocation and latch table handle
236 BtMgr *mgr; // buffer manager for thread
237 BtPage cursor; // cached frame for start/next (never mapped)
238 BtPage frame; // spare frame for the page split (never mapped)
239 BtPage zero; // page frame for zeroes at end of file
240 uid cursor_page; // current cursor page number
241 unsigned char *mem; // frame, cursor, page memory buffer
242 int found; // last delete or insert was found
243 int err; // last error
257 extern void bt_close (BtDb *bt);
258 extern BtDb *bt_open (BtMgr *mgr);
259 extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod);
260 extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl);
261 extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
262 extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
263 extern uint bt_nextkey (BtDb *bt, uint slot);
266 extern BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolsize, uint segsize, uint hashsize);
267 void bt_mgrclose (BtMgr *mgr);
269 // Helper functions to return slot values
271 extern BtKey bt_key (BtDb *bt, uint slot);
272 extern uid bt_uid (BtDb *bt, uint slot);
273 extern uint bt_tod (BtDb *bt, uint slot);
275 // BTree page number constants
276 #define ALLOC_page 0 // allocation & lock manager hash table
277 #define ROOT_page 1 // root of the btree
278 #define LEAF_page 2 // first page of leaves
279 #define LATCH_page 3 // pages for lock manager
281 // Number of levels to create in a new BTree
285 // The page is allocated from low and hi ends.
286 // The key offsets and row-id's are allocated
287 // from the bottom, while the text of the key
288 // is allocated from the top. When the two
289 // areas meet, the page is split into two.
291 // A key consists of a length byte, two bytes of
292 // index number (0 - 65534), and up to 253 bytes
293 // of key value. Duplicate keys are discarded.
294 // Associated with each key is a 48 bit row-id,
295 // or any other value desired.
297 // The b-tree root is always located at page 1.
298 // The first leaf page of level zero is always
299 // located on page 2.
301 // The b-tree pages are linked with next
302 // pointers to facilitate enumerators,
303 // and provide for concurrency.
305 // When to root page fills, it is split in two and
306 // the tree height is raised by a new root at page
307 // one with two keys.
309 // Deleted keys are marked with a dead bit until
310 // page cleanup. The fence key for a node is
313 // Groups of pages called segments from the btree are optionally
314 // cached with a memory mapped pool. A hash table is used to keep
315 // track of the cached segments. This behaviour is controlled
316 // by the cache block size parameter to bt_open.
318 // To achieve maximum concurrency one page is locked at a time
319 // as the tree is traversed to find leaf key in question. The right
320 // page numbers are used in cases where the page is being split,
323 // Page 0 is dedicated to lock for new page extensions,
324 // and chains empty pages together for reuse.
326 // The ParentModification lock on a node is obtained to serialize posting
327 // or changing the fence key for a node.
329 // Empty pages are chained together through the ALLOC page and reused.
331 // Access macros to address slot and key values from the page
332 // Page slots use 1 based indexing.
334 #define slotptr(page, slot) (((BtSlot *)(page+1)) + (slot-1))
335 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
337 void bt_putid(unsigned char *dest, uid id)
342 dest[i] = (unsigned char)id, id >>= 8;
345 uid bt_getid(unsigned char *src)
350 for( i = 0; i < BtId; i++ )
351 id <<= 8, id |= *src++;
358 // wait until write lock mode is clear
359 // and add 1 to the share count
361 void bt_spinreadlock(BtSpinLatch *latch)
366 // obtain latch mutex
368 if( __sync_lock_test_and_set(latch->mutex, 1) )
371 if( _InterlockedExchange8(latch->mutex, 1) )
374 // see if exclusive request is granted or pending
376 if( prev = !(latch->exclusive | latch->pending) )
382 _InterlockedExchange8(latch->mutex, 0);
389 } while( sched_yield(), 1 );
391 } while( SwitchToThread(), 1 );
395 // wait for other read and write latches to relinquish
397 void bt_spinwritelock(BtSpinLatch *latch)
403 if( __sync_lock_test_and_set(latch->mutex, 1) )
406 if( _InterlockedExchange8(latch->mutex, 1) )
409 if( prev = !(latch->share | latch->exclusive) )
410 latch->exclusive = 1, latch->pending = 0;
416 _InterlockedExchange8(latch->mutex, 0);
421 } while( sched_yield(), 1 );
423 } while( SwitchToThread(), 1 );
427 // try to obtain write lock
429 // return 1 if obtained,
432 int bt_spinwritetry(BtSpinLatch *latch)
437 if( __sync_lock_test_and_set(latch->mutex, 1) )
440 if( _InterlockedExchange8(latch->mutex, 1) )
443 // take write access if all bits are clear
445 if( prev = !(latch->exclusive | latch->share) )
446 latch->exclusive = 1;
451 _InterlockedExchange8(latch->mutex, 0);
458 void bt_spinreleasewrite(BtSpinLatch *latch)
461 while( __sync_lock_test_and_set(latch->mutex, 1) )
464 while( _InterlockedExchange8(latch->mutex, 1) )
467 latch->exclusive = 0;
471 _InterlockedExchange8(latch->mutex, 0);
475 // decrement reader count
477 void bt_spinreleaseread(BtSpinLatch *latch)
480 while( __sync_lock_test_and_set(latch->mutex, 1) )
483 while( _InterlockedExchange8(latch->mutex, 1) )
490 _InterlockedExchange8(latch->mutex, 0);
494 // link latch table entry into latch hash table
496 void bt_latchlink (BtDb *bt, ushort hashidx, ushort victim, uid page_no)
498 BtLatchSet *set = bt->mgr->latchsets + victim;
500 if( set->next = bt->mgr->latchmgr->table[hashidx].slot )
501 bt->mgr->latchsets[set->next].prev = victim;
503 bt->mgr->latchmgr->table[hashidx].slot = victim;
504 set->page_no = page_no;
511 void bt_unpinlatch (BtLatchSet *set)
514 __sync_fetch_and_add(&set->pin, -1);
516 _InterlockedDecrement16 (&set->pin);
520 // find existing latchset or inspire new one
521 // return with latchset pinned
523 BtLatchSet *bt_pinlatch (BtDb *bt, uid page_no)
525 ushort hashidx = page_no % bt->mgr->latchmgr->latchhash;
526 ushort slot, avail = 0, victim, idx;
529 // obtain read lock on hash table entry
531 bt_spinreadlock(bt->mgr->latchmgr->table[hashidx].latch);
533 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
535 set = bt->mgr->latchsets + slot;
536 if( page_no == set->page_no )
538 } while( slot = set->next );
542 __sync_fetch_and_add(&set->pin, 1);
544 _InterlockedIncrement16 (&set->pin);
548 bt_spinreleaseread (bt->mgr->latchmgr->table[hashidx].latch);
553 // try again, this time with write lock
555 bt_spinwritelock(bt->mgr->latchmgr->table[hashidx].latch);
557 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
559 set = bt->mgr->latchsets + slot;
560 if( page_no == set->page_no )
562 if( !set->pin && !avail )
564 } while( slot = set->next );
566 // found our entry, or take over an unpinned one
568 if( slot || (slot = avail) ) {
569 set = bt->mgr->latchsets + slot;
571 __sync_fetch_and_add(&set->pin, 1);
573 _InterlockedIncrement16 (&set->pin);
575 set->page_no = page_no;
576 bt_spinreleasewrite(bt->mgr->latchmgr->table[hashidx].latch);
580 // see if there are any unused entries
582 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, 1) + 1;
584 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchdeployed);
587 if( victim < bt->mgr->latchmgr->latchtotal ) {
588 set = bt->mgr->latchsets + victim;
590 __sync_fetch_and_add(&set->pin, 1);
592 _InterlockedIncrement16 (&set->pin);
594 bt_latchlink (bt, hashidx, victim, page_no);
595 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
600 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, -1);
602 victim = _InterlockedDecrement16 (&bt->mgr->latchmgr->latchdeployed);
604 // find and reuse previous lock entry
608 victim = __sync_fetch_and_add(&bt->mgr->latchmgr->latchvictim, 1);
610 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchvictim) - 1;
612 // we don't use slot zero
614 if( victim %= bt->mgr->latchmgr->latchtotal )
615 set = bt->mgr->latchsets + victim;
619 // take control of our slot
620 // from other threads
622 if( set->pin || !bt_spinwritetry (set->busy) )
627 // try to get write lock on hash chain
628 // skip entry if not obtained
629 // or has outstanding locks
631 if( !bt_spinwritetry (bt->mgr->latchmgr->table[idx].latch) ) {
632 bt_spinreleasewrite (set->busy);
637 bt_spinreleasewrite (set->busy);
638 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
642 // unlink our available victim from its hash chain
645 bt->mgr->latchsets[set->prev].next = set->next;
647 bt->mgr->latchmgr->table[idx].slot = set->next;
650 bt->mgr->latchsets[set->next].prev = set->prev;
652 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
654 __sync_fetch_and_add(&set->pin, 1);
656 _InterlockedIncrement16 (&set->pin);
658 bt_latchlink (bt, hashidx, victim, page_no);
659 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
660 bt_spinreleasewrite (set->busy);
665 void bt_mgrclose (BtMgr *mgr)
670 // release mapped pages
671 // note that slot zero is never used
673 for( slot = 1; slot < mgr->poolmax; slot++ ) {
674 pool = mgr->pool + slot;
677 munmap (pool->map, (mgr->poolmask+1) << mgr->page_bits);
680 FlushViewOfFile(pool->map, 0);
681 UnmapViewOfFile(pool->map);
682 CloseHandle(pool->hmap);
688 munmap (mgr->latchsets, mgr->latchmgr->nlatchpage * mgr->page_size);
689 munmap (mgr->latchmgr, mgr->page_size);
691 FlushViewOfFile(mgr->latchmgr, 0);
692 UnmapViewOfFile(mgr->latchmgr);
693 CloseHandle(mgr->halloc);
699 free ((void *)mgr->latch);
702 FlushFileBuffers(mgr->idx);
703 CloseHandle(mgr->idx);
704 GlobalFree (mgr->pool);
705 GlobalFree (mgr->hash);
706 GlobalFree ((void *)mgr->latch);
711 // close and release memory
713 void bt_close (BtDb *bt)
720 VirtualFree (bt->mem, 0, MEM_RELEASE);
725 // open/create new btree buffer manager
727 // call with file_name, BT_openmode, bits in page size (e.g. 16),
728 // size of mapped page pool (e.g. 8192)
730 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
732 uint lvl, attr, cacheblk, last, slot, idx;
733 uint nlatchpage, latchhash;
734 BtLatchMgr *latchmgr;
742 SYSTEM_INFO sysinfo[1];
745 // determine sanity of page size and buffer pool
747 if( bits > BT_maxbits )
749 else if( bits < BT_minbits )
753 return NULL; // must have buffer pool
756 mgr = calloc (1, sizeof(BtMgr));
758 mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
761 return free(mgr), NULL;
763 cacheblk = 4096; // minimum mmap segment size for unix
766 mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
767 attr = FILE_ATTRIBUTE_NORMAL;
768 mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
770 if( mgr->idx == INVALID_HANDLE_VALUE )
771 return GlobalFree(mgr), NULL;
773 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
774 GetSystemInfo(sysinfo);
775 cacheblk = sysinfo->dwAllocationGranularity;
779 latchmgr = malloc (BT_maxpage);
782 // read minimum page size to get root info
784 if( size = lseek (mgr->idx, 0L, 2) ) {
785 if( pread(mgr->idx, latchmgr, BT_minpage, 0) == BT_minpage )
786 bits = latchmgr->alloc->bits;
788 return free(mgr), free(latchmgr), NULL;
789 } else if( mode == BT_ro )
790 return free(latchmgr), bt_mgrclose (mgr), NULL;
792 latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
793 size = GetFileSize(mgr->idx, amt);
796 if( !ReadFile(mgr->idx, (char *)latchmgr, BT_minpage, amt, NULL) )
797 return bt_mgrclose (mgr), NULL;
798 bits = latchmgr->alloc->bits;
799 } else if( mode == BT_ro )
800 return bt_mgrclose (mgr), NULL;
803 mgr->page_size = 1 << bits;
804 mgr->page_bits = bits;
806 mgr->poolmax = poolmax;
809 if( cacheblk < mgr->page_size )
810 cacheblk = mgr->page_size;
812 // mask for partial memmaps
814 mgr->poolmask = (cacheblk >> bits) - 1;
816 // see if requested size of pages per memmap is greater
818 if( (1 << segsize) > mgr->poolmask )
819 mgr->poolmask = (1 << segsize) - 1;
823 while( (1 << mgr->seg_bits) <= mgr->poolmask )
826 mgr->hashsize = hashsize;
829 mgr->pool = calloc (poolmax, sizeof(BtPool));
830 mgr->hash = calloc (hashsize, sizeof(ushort));
831 mgr->latch = calloc (hashsize, sizeof(BtSpinLatch));
833 mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * sizeof(BtPool));
834 mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
835 mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtSpinLatch));
841 // initialize an empty b-tree with latch page, root page, page of leaves
842 // and page(s) of latches
844 memset (latchmgr, 0, 1 << bits);
845 nlatchpage = BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1;
846 bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
847 latchmgr->alloc->bits = mgr->page_bits;
849 latchmgr->nlatchpage = nlatchpage;
850 latchmgr->latchtotal = nlatchpage * (mgr->page_size / sizeof(BtLatchSet));
852 // initialize latch manager
854 latchhash = (mgr->page_size - sizeof(BtLatchMgr)) / sizeof(BtHashEntry);
856 // size of hash table = total number of latchsets
858 if( latchhash > latchmgr->latchtotal )
859 latchhash = latchmgr->latchtotal;
861 latchmgr->latchhash = latchhash;
864 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
865 return bt_mgrclose (mgr), NULL;
867 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
868 return bt_mgrclose (mgr), NULL;
870 if( *amt < mgr->page_size )
871 return bt_mgrclose (mgr), NULL;
874 memset (latchmgr, 0, 1 << bits);
875 latchmgr->alloc->bits = mgr->page_bits;
877 for( lvl=MIN_lvl; lvl--; ) {
878 slotptr(latchmgr->alloc, 1)->off = mgr->page_size - 3;
879 bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
880 key = keyptr(latchmgr->alloc, 1);
881 key->len = 2; // create stopper key
884 latchmgr->alloc->min = mgr->page_size - 3;
885 latchmgr->alloc->lvl = lvl;
886 latchmgr->alloc->cnt = 1;
887 latchmgr->alloc->act = 1;
889 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
890 return bt_mgrclose (mgr), NULL;
892 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
893 return bt_mgrclose (mgr), NULL;
895 if( *amt < mgr->page_size )
896 return bt_mgrclose (mgr), NULL;
900 // clear out latch manager locks
901 // and rest of pages to round out segment
903 memset(latchmgr, 0, mgr->page_size);
906 while( last <= ((MIN_lvl + 1 + nlatchpage) | mgr->poolmask) ) {
908 pwrite(mgr->idx, latchmgr, mgr->page_size, last << mgr->page_bits);
910 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
911 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
912 return bt_mgrclose (mgr), NULL;
913 if( *amt < mgr->page_size )
914 return bt_mgrclose (mgr), NULL;
921 flag = PROT_READ | PROT_WRITE;
922 mgr->latchmgr = mmap (0, mgr->page_size, flag, MAP_SHARED, mgr->idx, ALLOC_page * mgr->page_size);
923 if( mgr->latchmgr == MAP_FAILED )
924 return bt_mgrclose (mgr), NULL;
925 mgr->latchsets = (BtLatchSet *)mmap (0, mgr->latchmgr->nlatchpage * mgr->page_size, flag, MAP_SHARED, mgr->idx, LATCH_page * mgr->page_size);
926 if( mgr->latchsets == MAP_FAILED )
927 return bt_mgrclose (mgr), NULL;
929 flag = PAGE_READWRITE;
930 mgr->halloc = CreateFileMapping(mgr->idx, NULL, flag, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size, NULL);
932 return bt_mgrclose (mgr), NULL;
934 flag = FILE_MAP_WRITE;
935 mgr->latchmgr = MapViewOfFile(mgr->halloc, flag, 0, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size);
937 return GetLastError(), bt_mgrclose (mgr), NULL;
939 mgr->latchsets = (void *)((char *)mgr->latchmgr + LATCH_page * mgr->page_size);
945 VirtualFree (latchmgr, 0, MEM_RELEASE);
950 // open BTree access method
951 // based on buffer manager
953 BtDb *bt_open (BtMgr *mgr)
955 BtDb *bt = malloc (sizeof(*bt));
957 memset (bt, 0, sizeof(*bt));
960 bt->mem = malloc (3 *mgr->page_size);
962 bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
964 bt->frame = (BtPage)bt->mem;
965 bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
966 bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
968 memset (bt->zero, 0, mgr->page_size);
972 // compare two keys, returning > 0, = 0, or < 0
973 // as the comparison value
975 int keycmp (BtKey key1, unsigned char *key2, uint len2)
977 uint len1 = key1->len;
980 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
993 // find segment in pool
994 // must be called with hashslot idx locked
995 // return NULL if not there
996 // otherwise return node
998 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
1003 // compute start of hash chain in pool
1005 if( slot = bt->mgr->hash[idx] )
1006 pool = bt->mgr->pool + slot;
1010 page_no &= ~bt->mgr->poolmask;
1012 while( pool->basepage != page_no )
1013 if( pool = pool->hashnext )
1021 // add segment to hash table
1023 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
1028 pool->hashprev = pool->hashnext = NULL;
1029 pool->basepage = page_no & ~bt->mgr->poolmask;
1032 if( slot = bt->mgr->hash[idx] ) {
1033 node = bt->mgr->pool + slot;
1034 pool->hashnext = node;
1035 node->hashprev = pool;
1038 bt->mgr->hash[idx] = pool->slot;
1041 // find best segment to evict from buffer pool
1043 BtPool *bt_findlru (BtDb *bt, uint hashslot)
1045 unsigned long long int target = ~0LL;
1046 BtPool *pool = NULL, *node;
1051 node = bt->mgr->pool + hashslot;
1053 // scan pool entries under hash table slot
1058 if( node->lru > target )
1062 } while( node = node->hashnext );
1067 // map new buffer pool segment to virtual memory
1069 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
1071 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
1072 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
1076 flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
1077 pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED, bt->mgr->idx, off);
1078 if( pool->map == MAP_FAILED )
1079 return bt->err = BTERR_map;
1082 flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
1083 pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
1085 return bt->err = BTERR_map;
1087 flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
1088 pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1090 return bt->err = BTERR_map;
1095 // calculate page within pool
1097 BtPage bt_page (BtDb *bt, BtPool *pool, uid page_no)
1099 uint subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1102 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1108 void bt_unpinpool (BtPool *pool)
1111 __sync_fetch_and_add(&pool->pin, -1);
1113 _InterlockedDecrement16 (&pool->pin);
1117 // find or place requested page in segment-pool
1118 // return pool table entry, incrementing pin
1120 BtPool *bt_pinpool(BtDb *bt, uid page_no)
1122 BtPool *pool, *node, *next;
1123 uint slot, idx, victim;
1125 // lock hash table chain
1127 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1128 bt_spinreadlock (&bt->mgr->latch[idx]);
1130 // look up in hash table
1132 if( pool = bt_findpool(bt, page_no, idx) ) {
1134 __sync_fetch_and_add(&pool->pin, 1);
1136 _InterlockedIncrement16 (&pool->pin);
1138 bt_spinreleaseread (&bt->mgr->latch[idx]);
1143 // upgrade to write lock
1145 bt_spinreleaseread (&bt->mgr->latch[idx]);
1146 bt_spinwritelock (&bt->mgr->latch[idx]);
1148 // try to find page in pool with write lock
1150 if( pool = bt_findpool(bt, page_no, idx) ) {
1152 __sync_fetch_and_add(&pool->pin, 1);
1154 _InterlockedIncrement16 (&pool->pin);
1156 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1161 // allocate a new pool node
1162 // and add to hash table
1165 slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
1167 slot = _InterlockedIncrement16 (&bt->mgr->poolcnt) - 1;
1170 if( ++slot < bt->mgr->poolmax ) {
1171 pool = bt->mgr->pool + slot;
1174 if( bt_mapsegment(bt, pool, page_no) )
1177 bt_linkhash(bt, pool, page_no, idx);
1179 __sync_fetch_and_add(&pool->pin, 1);
1181 _InterlockedIncrement16 (&pool->pin);
1183 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1187 // pool table is full
1188 // find best pool entry to evict
1191 __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
1193 _InterlockedDecrement16 (&bt->mgr->poolcnt);
1198 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
1200 victim = _InterlockedIncrement (&bt->mgr->evicted) - 1;
1202 victim %= bt->mgr->hashsize;
1204 // try to get write lock
1205 // skip entry if not obtained
1207 if( !bt_spinwritetry (&bt->mgr->latch[victim]) )
1210 // if pool entry is empty
1211 // or any pages are pinned
1214 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
1215 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1219 // unlink victim pool node from hash table
1221 if( node = pool->hashprev )
1222 node->hashnext = pool->hashnext;
1223 else if( node = pool->hashnext )
1224 bt->mgr->hash[victim] = node->slot;
1226 bt->mgr->hash[victim] = 0;
1228 if( node = pool->hashnext )
1229 node->hashprev = pool->hashprev;
1231 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1233 // remove old file mapping
1235 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1237 FlushViewOfFile(pool->map, 0);
1238 UnmapViewOfFile(pool->map);
1239 CloseHandle(pool->hmap);
1243 // create new pool mapping
1244 // and link into hash table
1246 if( bt_mapsegment(bt, pool, page_no) )
1249 bt_linkhash(bt, pool, page_no, idx);
1251 __sync_fetch_and_add(&pool->pin, 1);
1253 _InterlockedIncrement16 (&pool->pin);
1255 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1260 // place write, read, or parent lock on requested page_no.
1262 void bt_lockpage(BtLock mode, BtLatchSet *set)
1266 bt_spinreadlock (set->readwr);
1269 bt_spinwritelock (set->readwr);
1272 bt_spinreadlock (set->access);
1275 bt_spinwritelock (set->access);
1278 bt_spinwritelock (set->parent);
1283 // remove write, read, or parent lock on requested page
1285 void bt_unlockpage(BtLock mode, BtLatchSet *set)
1289 bt_spinreleaseread (set->readwr);
1292 bt_spinreleasewrite (set->readwr);
1295 bt_spinreleaseread (set->access);
1298 bt_spinreleasewrite (set->access);
1301 bt_spinreleasewrite (set->parent);
1306 // allocate a new page and write page into it
1308 uid bt_newpage(BtDb *bt, BtPage page)
1314 // lock allocation page
1316 bt_spinwritelock(bt->mgr->latchmgr->lock);
1318 // use empty chain first
1319 // else allocate empty page
1321 if( new_page = bt_getid(bt->mgr->latchmgr->alloc[1].right) ) {
1322 if( set->pool = bt_pinpool (bt, new_page) )
1323 set->page = bt_page (bt, set->pool, new_page);
1327 bt_putid(bt->mgr->latchmgr->alloc[1].right, bt_getid(set->page->right));
1328 bt_unpinpool (set->pool);
1331 new_page = bt_getid(bt->mgr->latchmgr->alloc->right);
1332 bt_putid(bt->mgr->latchmgr->alloc->right, new_page+1);
1336 if ( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1337 return bt->err = BTERR_wrt, 0;
1339 // if writing first page of pool block, zero last page in the block
1341 if ( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1343 // use zero buffer to write zeros
1344 if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1345 return bt->err = BTERR_wrt, 0;
1348 // bring new page into pool and copy page.
1349 // this will extend the file into the new pages.
1351 if( set->pool = bt_pinpool (bt, new_page) )
1352 set->page = bt_page (bt, set->pool, new_page);
1356 memcpy(set->page, page, bt->mgr->page_size);
1357 bt_unpinpool (set->pool);
1359 // unlock allocation latch and return new page no
1361 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1365 // find slot in page for given key at a given level
1367 int bt_findslot (BtPageSet *set, unsigned char *key, uint len)
1369 uint diff, higher = set->page->cnt, low = 1, slot;
1372 // make stopper key an infinite fence value
1374 if( bt_getid (set->page->right) )
1379 // low is the lowest candidate.
1380 // loop ends when they meet
1382 // higher is already
1383 // tested as .ge. the passed key.
1385 while( diff = higher - low ) {
1386 slot = low + ( diff >> 1 );
1387 if( keycmp (keyptr(set->page, slot), key, len) < 0 )
1390 higher = slot, good++;
1393 // return zero if key is on right link page
1395 return good ? higher : 0;
1398 // find and load page at given level for given key
1399 // leave page rd or wr locked as requested
1401 int bt_loadpage (BtDb *bt, BtPageSet *set, unsigned char *key, uint len, uint lvl, BtLock lock)
1403 uid page_no = ROOT_page, prevpage = 0;
1404 uint drill = 0xff, slot;
1405 BtLatchSet *prevlatch;
1406 uint mode, prevmode;
1409 // start at root of btree and drill down
1412 // determine lock mode of drill level
1413 mode = (drill == lvl) ? lock : BtLockRead;
1415 set->latch = bt_pinlatch (bt, page_no);
1416 set->page_no = page_no;
1418 // pin page contents
1420 if( set->pool = bt_pinpool (bt, page_no) )
1421 set->page = bt_page (bt, set->pool, page_no);
1425 // obtain access lock using lock chaining with Access mode
1427 if( page_no > ROOT_page )
1428 bt_lockpage(BtLockAccess, set->latch);
1430 // release & unpin parent page
1433 bt_unlockpage(prevmode, prevlatch);
1434 bt_unpinlatch (prevlatch);
1435 bt_unpinpool (prevpool);
1439 // obtain read lock using lock chaining
1441 bt_lockpage(mode, set->latch);
1443 if( set->page->free )
1444 return bt->err = BTERR_struct, 0;
1446 if( page_no > ROOT_page )
1447 bt_unlockpage(BtLockAccess, set->latch);
1449 // re-read and re-lock root after determining actual level of root
1451 if( set->page->lvl != drill) {
1452 if ( set->page_no != ROOT_page )
1453 return bt->err = BTERR_struct, 0;
1455 drill = set->page->lvl;
1457 if( lock != BtLockRead && drill == lvl ) {
1458 bt_unlockpage(mode, set->latch);
1459 bt_unpinlatch (set->latch);
1460 bt_unpinpool (set->pool);
1465 prevpage = set->page_no;
1466 prevlatch = set->latch;
1467 prevpool = set->pool;
1470 // find key on page at this level
1471 // and descend to requested level
1473 if( !set->page->kill )
1474 if( slot = bt_findslot (set, key, len) ) {
1478 while( slotptr(set->page, slot)->dead )
1479 if( slot++ < set->page->cnt )
1484 page_no = bt_getid(slotptr(set->page, slot)->id);
1489 // or slide right into next page
1492 page_no = bt_getid(set->page->right);
1496 // return error on end of right chain
1498 bt->err = BTERR_struct;
1499 return 0; // return error
1502 // return page to free list
1503 // page must be delete & write locked
1505 void bt_freepage (BtDb *bt, BtPageSet *set)
1507 // lock allocation page
1509 bt_spinwritelock (bt->mgr->latchmgr->lock);
1511 // store chain in second right
1512 bt_putid(set->page->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1513 bt_putid(bt->mgr->latchmgr->alloc[1].right, set->page_no);
1514 set->page->free = 1;
1516 // unlock released page
1518 bt_unlockpage (BtLockDelete, set->latch);
1519 bt_unlockpage (BtLockWrite, set->latch);
1520 bt_unpinlatch (set->latch);
1521 bt_unpinpool (set->pool);
1523 // unlock allocation page
1525 bt_spinreleasewrite (bt->mgr->latchmgr->lock);
1528 // a fence key was deleted from a page
1529 // push new fence value upwards
1531 BTERR bt_fixfence (BtDb *bt, BtPageSet *set, uint lvl)
1533 unsigned char leftkey[256], rightkey[256];
1537 // remove the old fence value
1539 ptr = keyptr(set->page, set->page->cnt);
1540 memcpy (rightkey, ptr, ptr->len + 1);
1542 memset (slotptr(set->page, set->page->cnt--), 0, sizeof(BtSlot));
1543 set->page->dirty = 1;
1545 ptr = keyptr(set->page, set->page->cnt);
1546 memcpy (leftkey, ptr, ptr->len + 1);
1547 page_no = set->page_no;
1549 bt_lockpage (BtLockParent, set->latch);
1550 bt_unlockpage (BtLockWrite, set->latch);
1552 // insert new (now smaller) fence key
1554 if( bt_insertkey (bt, leftkey+1, *leftkey, lvl+1, page_no, time(NULL)) )
1557 // now delete old fence key
1559 if( bt_deletekey (bt, rightkey+1, *rightkey, lvl+1) )
1562 bt_unlockpage (BtLockParent, set->latch);
1563 bt_unpinlatch(set->latch);
1564 bt_unpinpool (set->pool);
1568 // root has a single child
1569 // collapse a level from the tree
1571 BTERR bt_collapseroot (BtDb *bt, BtPageSet *root)
1576 // find the child entry and promote as new root contents
1579 for( idx = 0; idx++ < root->page->cnt; )
1580 if( !slotptr(root->page, idx)->dead )
1583 child->page_no = bt_getid (slotptr(root->page, idx)->id);
1585 child->latch = bt_pinlatch (bt, child->page_no);
1586 bt_lockpage (BtLockDelete, child->latch);
1587 bt_lockpage (BtLockWrite, child->latch);
1589 if( child->pool = bt_pinpool (bt, child->page_no) )
1590 child->page = bt_page (bt, child->pool, child->page_no);
1594 memcpy (root->page, child->page, bt->mgr->page_size);
1595 bt_freepage (bt, child);
1597 } while( root->page->lvl > 1 && root->page->act == 1 );
1599 bt_unlockpage (BtLockWrite, root->latch);
1600 bt_unpinlatch (root->latch);
1601 bt_unpinpool (root->pool);
1605 // find and delete key on page by marking delete flag bit
1606 // if page becomes empty, delete it from the btree
1608 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl)
1610 unsigned char lowerfence[256], higherfence[256];
1611 uint slot, idx, dirty = 0, fence, found;
1612 BtPageSet set[1], right[1];
1615 if( slot = bt_loadpage (bt, set, key, len, lvl, BtLockWrite) )
1616 ptr = keyptr(set->page, slot);
1620 // are we deleting a fence slot?
1622 fence = slot == set->page->cnt;
1624 // if key is found delete it, otherwise ignore request
1626 if( found = !keycmp (ptr, key, len) )
1627 if( found = slotptr(set->page, slot)->dead == 0 ) {
1628 dirty = slotptr(set->page, slot)->dead = 1;
1629 set->page->dirty = 1;
1632 // collapse empty slots
1634 while( idx = set->page->cnt - 1 )
1635 if( slotptr(set->page, idx)->dead ) {
1636 *slotptr(set->page, idx) = *slotptr(set->page, idx + 1);
1637 memset (slotptr(set->page, set->page->cnt--), 0, sizeof(BtSlot));
1642 // did we delete a fence key in an upper level?
1644 if( dirty && lvl && set->page->act && fence )
1645 if( bt_fixfence (bt, set, lvl) )
1648 return bt->found = found, 0;
1650 // is this a collapsed root?
1652 if( lvl > 1 && set->page_no == ROOT_page && set->page->act == 1 )
1653 if( bt_collapseroot (bt, set) )
1656 return bt->found = found, 0;
1658 // return if page is not empty
1660 if( set->page->act ) {
1661 bt_unlockpage(BtLockWrite, set->latch);
1662 bt_unpinlatch (set->latch);
1663 bt_unpinpool (set->pool);
1664 return bt->found = found, 0;
1667 // cache copy of fence key
1668 // to post in parent
1670 ptr = keyptr(set->page, set->page->cnt);
1671 memcpy (lowerfence, ptr, ptr->len + 1);
1673 // obtain lock on right page
1675 right->page_no = bt_getid(set->page->right);
1676 right->latch = bt_pinlatch (bt, right->page_no);
1677 bt_lockpage (BtLockWrite, right->latch);
1679 // pin page contents
1681 if( right->pool = bt_pinpool (bt, right->page_no) )
1682 right->page = bt_page (bt, right->pool, right->page_no);
1686 if( right->page->kill )
1687 return bt->err = BTERR_struct;
1689 // pull contents of right peer into our empty page
1691 memcpy (set->page, right->page, bt->mgr->page_size);
1693 // cache copy of key to update
1695 ptr = keyptr(right->page, right->page->cnt);
1696 memcpy (higherfence, ptr, ptr->len + 1);
1698 // mark right page deleted and point it to left page
1699 // until we can post parent updates
1701 bt_putid (right->page->right, set->page_no);
1702 right->page->kill = 1;
1704 bt_lockpage (BtLockParent, right->latch);
1705 bt_unlockpage (BtLockWrite, right->latch);
1707 bt_lockpage (BtLockParent, set->latch);
1708 bt_unlockpage (BtLockWrite, set->latch);
1710 // redirect higher key directly to our new node contents
1712 if( bt_insertkey (bt, higherfence+1, *higherfence, lvl+1, set->page_no, time(NULL)) )
1715 // delete old lower key to our node
1717 if( bt_deletekey (bt, lowerfence+1, *lowerfence, lvl+1) )
1720 // obtain delete and write locks to right node
1722 bt_unlockpage (BtLockParent, right->latch);
1723 bt_lockpage (BtLockDelete, right->latch);
1724 bt_lockpage (BtLockWrite, right->latch);
1725 bt_freepage (bt, right);
1727 bt_unlockpage (BtLockParent, set->latch);
1728 bt_unpinlatch (set->latch);
1729 bt_unpinpool (set->pool);
1734 // find key in leaf level and return row-id
1736 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1743 if( slot = bt_loadpage (bt, set, key, len, 0, BtLockRead) )
1744 ptr = keyptr(set->page, slot);
1748 // if key exists, return row-id
1749 // otherwise return 0
1751 if( slot <= set->page->cnt )
1752 if( !keycmp (ptr, key, len) )
1753 id = bt_getid(slotptr(set->page,slot)->id);
1755 bt_unlockpage (BtLockRead, set->latch);
1756 bt_unpinlatch (set->latch);
1757 bt_unpinpool (set->pool);
1761 // check page for space available,
1762 // clean if necessary and return
1763 // 0 - page needs splitting
1764 // >0 new slot value
1766 uint bt_cleanpage(BtDb *bt, BtPage page, uint amt, uint slot)
1768 uint nxt = bt->mgr->page_size;
1769 uint cnt = 0, idx = 0;
1770 uint max = page->cnt;
1774 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1777 // skip cleanup if nothing to reclaim
1782 memcpy (bt->frame, page, bt->mgr->page_size);
1784 // skip page info and set rest of page to zero
1786 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1790 // try cleaning up page first
1791 // by removing deleted keys
1793 while( cnt++ < max ) {
1796 if( cnt < max && slotptr(bt->frame,cnt)->dead )
1799 // copy the key across
1801 key = keyptr(bt->frame, cnt);
1802 nxt -= key->len + 1;
1803 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1807 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1808 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1810 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1811 slotptr(page, idx)->off = nxt;
1817 // see if page has enough space now, or does it need splitting?
1819 if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1825 // split the root and raise the height of the btree
1827 BTERR bt_splitroot(BtDb *bt, BtPageSet *root, unsigned char *leftkey, uid page_no2)
1829 uint nxt = bt->mgr->page_size;
1832 // Obtain an empty page to use, and copy the current
1833 // root contents into it, e.g. lower keys
1835 if( !(left = bt_newpage(bt, root->page)) )
1838 // preserve the page info at the bottom
1839 // of higher keys and set rest to zero
1841 memset(root->page+1, 0, bt->mgr->page_size - sizeof(*root->page));
1843 // insert lower keys page fence key on newroot page as first key
1845 nxt -= *leftkey + 1;
1846 memcpy ((unsigned char *)root->page + nxt, leftkey, *leftkey + 1);
1847 bt_putid(slotptr(root->page, 1)->id, left);
1848 slotptr(root->page, 1)->off = nxt;
1850 // insert stopper key on newroot page
1851 // and increase the root height
1854 ((unsigned char *)root->page)[nxt] = 2;
1855 ((unsigned char *)root->page)[nxt+1] = 0xff;
1856 ((unsigned char *)root->page)[nxt+2] = 0xff;
1857 bt_putid(slotptr(root->page, 2)->id, page_no2);
1858 slotptr(root->page, 2)->off = nxt;
1860 bt_putid(root->page->right, 0);
1861 root->page->min = nxt; // reset lowest used offset and key count
1862 root->page->cnt = 2;
1863 root->page->act = 2;
1866 // release and unpin root
1868 bt_unlockpage(BtLockWrite, root->latch);
1869 bt_unpinlatch (root->latch);
1870 bt_unpinpool (root->pool);
1874 // split already locked full node
1877 BTERR bt_splitpage (BtDb *bt, BtPageSet *set)
1879 uint cnt = 0, idx = 0, max, nxt = bt->mgr->page_size;
1880 unsigned char fencekey[256], rightkey[256];
1881 uint lvl = set->page->lvl;
1886 // split higher half of keys to bt->frame
1888 memset (bt->frame, 0, bt->mgr->page_size);
1889 max = set->page->cnt;
1893 while( cnt++ < max ) {
1894 key = keyptr(set->page, cnt);
1895 nxt -= key->len + 1;
1896 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
1898 memcpy(slotptr(bt->frame,++idx)->id, slotptr(set->page,cnt)->id, BtId);
1899 if( !(slotptr(bt->frame, idx)->dead = slotptr(set->page, cnt)->dead) )
1901 slotptr(bt->frame, idx)->tod = slotptr(set->page, cnt)->tod;
1902 slotptr(bt->frame, idx)->off = nxt;
1905 // remember existing fence key for new page to the right
1907 memcpy (rightkey, key, key->len + 1);
1909 bt->frame->bits = bt->mgr->page_bits;
1910 bt->frame->min = nxt;
1911 bt->frame->cnt = idx;
1912 bt->frame->lvl = lvl;
1916 if( set->page_no > ROOT_page )
1917 memcpy (bt->frame->right, set->page->right, BtId);
1919 // get new free page and write higher keys to it.
1921 if( !(right->page_no = bt_newpage(bt, bt->frame)) )
1924 // update lower keys to continue in old page
1926 memcpy (bt->frame, set->page, bt->mgr->page_size);
1927 memset (set->page+1, 0, bt->mgr->page_size - sizeof(*set->page));
1928 nxt = bt->mgr->page_size;
1929 set->page->dirty = 0;
1934 // assemble page of smaller keys
1936 while( cnt++ < max / 2 ) {
1937 key = keyptr(bt->frame, cnt);
1938 nxt -= key->len + 1;
1939 memcpy ((unsigned char *)set->page + nxt, key, key->len + 1);
1940 memcpy(slotptr(set->page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1941 slotptr(set->page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1942 slotptr(set->page, idx)->off = nxt;
1946 // remember fence key for smaller page
1948 memcpy(fencekey, key, key->len + 1);
1950 bt_putid(set->page->right, right->page_no);
1951 set->page->min = nxt;
1952 set->page->cnt = idx;
1954 // if current page is the root page, split it
1956 if( set->page_no == ROOT_page )
1957 return bt_splitroot (bt, set, fencekey, right->page_no);
1959 // insert new fences in their parent pages
1961 right->latch = bt_pinlatch (bt, right->page_no);
1962 bt_lockpage (BtLockParent, right->latch);
1964 bt_lockpage (BtLockParent, set->latch);
1965 bt_unlockpage (BtLockWrite, set->latch);
1967 // insert new fence for reformulated left block of smaller keys
1969 if( bt_insertkey (bt, fencekey+1, *fencekey, lvl+1, set->page_no, time(NULL)) )
1972 // switch fence for right block of larger keys to new right page
1974 if( bt_insertkey (bt, rightkey+1, *rightkey, lvl+1, right->page_no, time(NULL)) )
1977 bt_unlockpage (BtLockParent, set->latch);
1978 bt_unpinlatch (set->latch);
1979 bt_unpinpool (set->pool);
1981 bt_unlockpage (BtLockParent, right->latch);
1982 bt_unpinlatch (right->latch);
1985 // Insert new key into the btree at given level.
1987 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod)
1994 if( slot = bt_loadpage (bt, set, key, len, lvl, BtLockWrite) )
1995 ptr = keyptr(set->page, slot);
1999 bt->err = BTERR_ovflw;
2003 // if key already exists, update id and return
2005 if( !keycmp (ptr, key, len) ) {
2006 if( slotptr(set->page, slot)->dead )
2008 slotptr(set->page, slot)->dead = 0;
2009 slotptr(set->page, slot)->tod = tod;
2010 bt_putid(slotptr(set->page,slot)->id, id);
2011 bt_unlockpage(BtLockWrite, set->latch);
2012 bt_unpinlatch (set->latch);
2013 bt_unpinpool (set->pool);
2017 // check if page has enough space
2019 if( slot = bt_cleanpage (bt, set->page, len, slot) )
2022 if( bt_splitpage (bt, set) )
2026 // calculate next available slot and copy key into page
2028 set->page->min -= len + 1; // reset lowest used offset
2029 ((unsigned char *)set->page)[set->page->min] = len;
2030 memcpy ((unsigned char *)set->page + set->page->min +1, key, len );
2032 for( idx = slot; idx < set->page->cnt; idx++ )
2033 if( slotptr(set->page, idx)->dead )
2036 // now insert key into array before slot
2038 if( idx == set->page->cnt )
2039 idx++, set->page->cnt++;
2044 *slotptr(set->page, idx) = *slotptr(set->page, idx -1), idx--;
2046 bt_putid(slotptr(set->page,slot)->id, id);
2047 slotptr(set->page, slot)->off = set->page->min;
2048 slotptr(set->page, slot)->tod = tod;
2049 slotptr(set->page, slot)->dead = 0;
2051 bt_unlockpage (BtLockWrite, set->latch);
2052 bt_unpinlatch (set->latch);
2053 bt_unpinpool (set->pool);
2057 // cache page of keys into cursor and return starting slot for given key
2059 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2064 // cache page for retrieval
2066 if( slot = bt_loadpage (bt, set, key, len, 0, BtLockRead) )
2067 memcpy (bt->cursor, set->page, bt->mgr->page_size);
2071 bt->cursor_page = set->page_no;
2073 bt_unlockpage(BtLockRead, set->latch);
2074 bt_unpinlatch (set->latch);
2075 bt_unpinpool (set->pool);
2079 // return next slot for cursor page
2080 // or slide cursor right into next page
2082 uint bt_nextkey (BtDb *bt, uint slot)
2088 right = bt_getid(bt->cursor->right);
2090 while( slot++ < bt->cursor->cnt )
2091 if( slotptr(bt->cursor,slot)->dead )
2093 else if( right || (slot < bt->cursor->cnt) ) // skip infinite stopper
2101 bt->cursor_page = right;
2103 if( set->pool = bt_pinpool (bt, right) )
2104 set->page = bt_page (bt, set->pool, right);
2108 set->latch = bt_pinlatch (bt, right);
2109 bt_lockpage(BtLockRead, set->latch);
2111 memcpy (bt->cursor, set->page, bt->mgr->page_size);
2113 bt_unlockpage(BtLockRead, set->latch);
2114 bt_unpinlatch (set->latch);
2115 bt_unpinpool (set->pool);
2123 BtKey bt_key(BtDb *bt, uint slot)
2125 return keyptr(bt->cursor, slot);
2128 uid bt_uid(BtDb *bt, uint slot)
2130 return bt_getid(slotptr(bt->cursor,slot)->id);
2133 uint bt_tod(BtDb *bt, uint slot)
2135 return slotptr(bt->cursor,slot)->tod;
2141 double getCpuTime(int type)
2144 FILETIME xittime[1];
2145 FILETIME systime[1];
2146 FILETIME usrtime[1];
2147 SYSTEMTIME timeconv[1];
2150 GetProcessTimes (GetCurrentProcess(), crtime, xittime, systime, usrtime);
2151 memset (timeconv, 0, sizeof(SYSTEMTIME));
2155 FileTimeToSystemTime (usrtime, timeconv);
2158 FileTimeToSystemTime (systime, timeconv);
2162 ans = (double)timeconv->wHour * 3600;
2163 ans += (double)timeconv->wMinute * 60;
2164 ans += (double)timeconv->wSecond;
2165 ans += (double)timeconv->wMilliseconds / 1000;
2169 #include <sys/time.h>
2170 #include <sys/resource.h>
2172 double getCpuTime(int type)
2174 struct rusage used[1];
2176 getrusage(RUSAGE_SELF, used);
2179 return (double)used->ru_utime.tv_sec + (double)used->ru_utime.tv_usec / 1000000;
2182 return (double)used->ru_stime.tv_sec + (double)used->ru_stime.tv_usec / 1000000;
2189 void bt_latchaudit (BtDb *bt)
2191 ushort idx, hashidx;
2197 for( idx = 1; idx < bt->mgr->latchmgr->latchdeployed; idx++ ) {
2198 set->latch = bt->mgr->latchsets + idx;
2199 if( set->latch->pin ) {
2200 fprintf(stderr, "latchset %d pinned for page %.6x\n", idx, set->latch->page_no);
2201 set->latch->pin = 0;
2205 for( hashidx = 0; hashidx < bt->mgr->latchmgr->latchhash; hashidx++ ) {
2206 if( idx = bt->mgr->latchmgr->table[hashidx].slot ) do {
2207 set->latch = bt->mgr->latchsets + idx;
2208 if( set->latch->hash != hashidx )
2209 fprintf(stderr, "latchset %d wrong hashidx\n", idx);
2210 if( set->latch->pin )
2211 fprintf(stderr, "latchset %d pinned for page %.8x\n", idx, set->latch->page_no);
2212 } while( idx = set->latch->next );
2215 next = bt->mgr->latchmgr->nlatchpage + LATCH_page;
2216 page_no = LEAF_page;
2218 while( page_no < bt_getid(bt->mgr->latchmgr->alloc->right) ) {
2219 pread (bt->mgr->idx, bt->frame, bt->mgr->page_size, page_no << bt->mgr->page_bits);
2220 if( !bt->frame->free )
2221 for( idx = 0; idx++ < bt->frame->cnt - 1; ) {
2222 ptr = keyptr(bt->frame, idx+1);
2223 if( keycmp (keyptr(bt->frame, idx), ptr->key, ptr->len) >= 0 )
2224 fprintf(stderr, "page %.8x idx %.2x out of order\n", page_no, idx);
2227 if( page_no > LEAF_page )
2241 // standalone program to index file of keys
2242 // then list them onto std-out
2245 void *index_file (void *arg)
2247 uint __stdcall index_file (void *arg)
2250 int line = 0, found = 0, cnt = 0;
2251 uid next, page_no = LEAF_page; // start on first page of leaves
2252 unsigned char key[256];
2253 ThreadArg *args = arg;
2254 int ch, len = 0, slot;
2261 bt = bt_open (args->mgr);
2264 switch(args->type | 0x20)
2267 fprintf(stderr, "started latch mgr audit\n");
2269 fprintf(stderr, "finished latch mgr audit\n");
2273 fprintf(stderr, "started indexing for %s\n", args->infile);
2274 if( in = fopen (args->infile, "rb") )
2275 while( ch = getc(in), ch != EOF )
2280 if( args->num == 1 )
2281 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2283 else if( args->num )
2284 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2286 if( bt_insertkey (bt, key, len, 0, line, *tod) )
2287 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2290 else if( len < 255 )
2292 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
2296 fprintf(stderr, "started deleting keys for %s\n", args->infile);
2297 if( in = fopen (args->infile, "rb") )
2298 while( ch = getc(in), ch != EOF )
2302 if( args->num == 1 )
2303 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2305 else if( args->num )
2306 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2308 if( bt_deletekey (bt, key, len, 0) )
2309 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2312 else if( len < 255 )
2314 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2318 fprintf(stderr, "started finding keys for %s\n", args->infile);
2319 if( in = fopen (args->infile, "rb") )
2320 while( ch = getc(in), ch != EOF )
2324 if( args->num == 1 )
2325 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2327 else if( args->num )
2328 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2330 if( bt_findkey (bt, key, len) )
2333 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2335 fprintf(stderr, "Unable to find key %.*s line %d\n", len, key, line);
2338 else if( len < 255 )
2340 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2344 fprintf(stderr, "started scanning\n");
2346 if( set->pool = bt_pinpool (bt, page_no) )
2347 set->page = bt_page (bt, set->pool, page_no);
2350 set->latch = bt_pinlatch (bt, page_no);
2351 bt_lockpage (BtLockRead, set->latch);
2352 next = bt_getid (set->page->right);
2353 cnt += set->page->act;
2355 for( slot = 0; slot++ < set->page->cnt; )
2356 if( next || slot < set->page->cnt )
2357 if( !slotptr(set->page, slot)->dead ) {
2358 ptr = keyptr(set->page, slot);
2359 fwrite (ptr->key, ptr->len, 1, stdout);
2360 fputc ('\n', stdout);
2363 bt_unlockpage (BtLockRead, set->latch);
2364 bt_unpinlatch (set->latch);
2365 bt_unpinpool (set->pool);
2366 } while( page_no = next );
2368 cnt--; // remove stopper key
2369 fprintf(stderr, " Total keys read %d\n", cnt);
2373 fprintf(stderr, "started counting\n");
2374 next = bt->mgr->latchmgr->nlatchpage + LATCH_page;
2375 page_no = LEAF_page;
2377 while( page_no < bt_getid(bt->mgr->latchmgr->alloc->right) ) {
2378 uid off = page_no << bt->mgr->page_bits;
2380 pread (bt->mgr->idx, bt->frame, bt->mgr->page_size, off);
2384 SetFilePointer (bt->mgr->idx, (long)off, (long*)(&off)+1, FILE_BEGIN);
2386 if( !ReadFile(bt->mgr->idx, bt->frame, bt->mgr->page_size, amt, NULL))
2387 return bt->err = BTERR_map;
2389 if( *amt < bt->mgr->page_size )
2390 return bt->err = BTERR_map;
2392 if( !bt->frame->free && !bt->frame->lvl )
2393 cnt += bt->frame->act;
2394 if( page_no > LEAF_page )
2399 cnt--; // remove stopper key
2400 fprintf(stderr, " Total keys read %d\n", cnt);
2412 typedef struct timeval timer;
2414 int main (int argc, char **argv)
2416 int idx, cnt, len, slot, err;
2417 int segsize, bits = 16;
2422 time_t start[1], stop[1];
2436 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]);
2437 fprintf (stderr, " where page_bits is the page size in bits\n");
2438 fprintf (stderr, " mapped_segments is the number of mmap segments in buffer pool\n");
2439 fprintf (stderr, " seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2440 fprintf (stderr, " line_numbers = 1 to append line numbers to keys\n");
2441 fprintf (stderr, " src_file1 thru src_filen are files of keys separated by newline\n");
2446 gettimeofday(&start, NULL);
2452 bits = atoi(argv[3]);
2455 poolsize = atoi(argv[4]);
2458 fprintf (stderr, "Warning: no mapped_pool\n");
2460 if( poolsize > 65535 )
2461 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2464 segsize = atoi(argv[5]);
2466 segsize = 4; // 16 pages per mmap segment
2469 num = atoi(argv[6]);
2473 threads = malloc (cnt * sizeof(pthread_t));
2475 threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2477 args = malloc (cnt * sizeof(ThreadArg));
2479 mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2482 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2488 for( idx = 0; idx < cnt; idx++ ) {
2489 args[idx].infile = argv[idx + 7];
2490 args[idx].type = argv[2][0];
2491 args[idx].mgr = mgr;
2492 args[idx].num = num;
2493 args[idx].idx = idx;
2495 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2496 fprintf(stderr, "Error creating thread %d\n", err);
2498 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2502 // wait for termination
2505 for( idx = 0; idx < cnt; idx++ )
2506 pthread_join (threads[idx], NULL);
2507 gettimeofday(&stop, NULL);
2508 real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2510 WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2512 for( idx = 0; idx < cnt; idx++ )
2513 CloseHandle(threads[idx]);
2516 real_time = 1000 * (*stop - *start);
2518 elapsed = real_time / 1000;
2519 fprintf(stderr, " real %dm%.3fs\n", (int)(elapsed/60), elapsed - (int)(elapsed/60)*60);
2520 elapsed = getCpuTime(1);
2521 fprintf(stderr, " user %dm%.3fs\n", (int)(elapsed/60), elapsed - (int)(elapsed/60)*60);
2522 elapsed = getCpuTime(2);
2523 fprintf(stderr, " sys %dm%.3fs\n", (int)(elapsed/60), elapsed - (int)(elapsed/60)*60);