1 // foster btree version e2
4 // author: karl malbrain, malbrain@cal.berkeley.edu
7 This work, including the source code, documentation
8 and related data, is placed into the public domain.
10 The orginal author is Karl Malbrain.
12 THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY
13 OF ANY KIND, NOT EVEN THE IMPLIED WARRANTY OF
14 MERCHANTABILITY. THE AUTHOR OF THIS SOFTWARE,
15 ASSUMES _NO_ RESPONSIBILITY FOR ANY CONSEQUENCE
16 RESULTING FROM THE USE, MODIFICATION, OR
17 REDISTRIBUTION OF THIS SOFTWARE.
20 // Please see the project home page for documentation
21 // code.google.com/p/high-concurrency-btree
23 #define _FILE_OFFSET_BITS 64
24 #define _LARGEFILE64_SOURCE
40 #define WIN32_LEAN_AND_MEAN
53 typedef unsigned long long uid;
56 typedef unsigned long long off64_t;
57 typedef unsigned short ushort;
58 typedef unsigned int uint;
61 #define BT_ro 0x6f72 // ro
62 #define BT_rw 0x7772 // rw
64 #define BT_latchtable 128 // number of latch manager slots
66 #define BT_maxbits 24 // maximum page size in bits
67 #define BT_minbits 9 // minimum page size in bits
68 #define BT_minpage (1 << BT_minbits) // minimum page size
69 #define BT_maxpage (1 << BT_maxbits) // maximum page size
72 There are five lock types for each node in three independent sets:
73 1. (set 1) AccessIntent: Sharable. Going to Read the node. Incompatible with NodeDelete.
74 2. (set 1) NodeDelete: Exclusive. About to release the node. Incompatible with AccessIntent.
75 3. (set 2) ReadLock: Sharable. Read the node. Incompatible with WriteLock.
76 4. (set 2) WriteLock: Exclusive. Modify the node. Incompatible with ReadLock and other WriteLocks.
77 5. (set 3) ParentLock: Exclusive. Have parent adopt/delete maximum foster child from the node.
88 // Define the length of the page and key pointers
92 // Page key slot definition.
94 // If BT_maxbits is 15 or less, you can save 4 bytes
95 // for each key stored by making the first two uints
96 // into ushorts. You can also save 4 bytes by removing
97 // the tod field from the key.
99 // Keys are marked dead, but remain on the page until
100 // cleanup is called. The fence key (highest key) for
101 // the page is always present, even after cleanup.
104 uint off:BT_maxbits; // page offset for key start
105 uint dead:1; // set for deleted key
106 uint tod; // time-stamp for key
107 unsigned char id[BtId]; // id associated with key
110 // The key structure occupies space at the upper end of
111 // each page. It's a length byte followed by the value
116 unsigned char key[1];
119 // The first part of an index page.
120 // It is immediately followed
121 // by the BtSlot array of keys.
123 typedef struct Page {
124 volatile uint cnt; // count of keys in page
125 volatile uint act; // count of active keys
126 volatile uint min; // next key offset
127 volatile uint foster; // count of foster children
128 unsigned char bits; // page size in bits
129 unsigned char lvl:7; // level of page
130 unsigned char dirty:1; // page needs to be cleaned
131 unsigned char right[BtId]; // page number to right
132 BtSlot table[0]; // the key slots
135 // mode & definition for hash latch implementation
144 // mutex locks the other fields
145 // exclusive is set for write access
146 // share is count of read accessors
149 volatile ushort mutex:1;
150 volatile ushort exclusive:1;
151 volatile ushort pending:1;
152 volatile ushort share:13;
155 // hash table entries
158 BtSpinLatch latch[1];
159 volatile ushort slot; // Latch table entry at head of chain
162 // latch manager table structure
166 pthread_rwlock_t lock[1];
173 BtLatch readwr[1]; // read/write page lock
174 BtLatch access[1]; // Access Intent/Page delete
175 BtLatch parent[1]; // adoption of foster children
176 BtSpinLatch busy[1]; // slot is being moved between chains
177 volatile ushort next; // next entry in hash table chain
178 volatile ushort prev; // prev entry in hash table chain
179 volatile ushort pin; // number of outstanding locks
180 volatile ushort hash; // hash slot entry is under
181 volatile uid page_no; // latch set page number
184 // The memory mapping pool table buffer manager entry
187 unsigned long long int lru; // number of times accessed
188 uid basepage; // mapped base page number
189 char *map; // mapped memory pointer
190 ushort pin; // mapped page pin counter
191 ushort slot; // slot index in this array
192 void *hashprev; // previous pool entry for the same hash idx
193 void *hashnext; // next pool entry for the same hash idx
195 HANDLE hmap; // Windows memory mapping handle
199 // structure for latch manager on ALLOC_page
202 struct Page alloc[2]; // next & free page_nos in right ptr
203 BtSpinLatch lock[1]; // allocation area lite latch
204 ushort latchdeployed; // highest number of latch entries deployed
205 ushort nlatchpage; // number of latch pages at BT_latch
206 ushort latchtotal; // number of page latch entries
207 ushort latchhash; // number of latch hash table slots
208 ushort latchvictim; // next latch entry to examine
209 BtHashEntry table[0]; // the hash table
212 // The object structure for Btree access
215 uint page_size; // page size
216 uint page_bits; // page size in bits
217 uint seg_bits; // seg size in pages in bits
218 uint mode; // read-write mode
221 char *pooladvise; // bit maps for pool page advisements
225 ushort poolcnt; // highest page pool node in use
226 ushort poolmax; // highest page pool node allocated
227 ushort poolmask; // total number of pages in mmap segment - 1
228 ushort hashsize; // size of Hash Table for pool entries
229 ushort evicted; // last evicted hash table slot
230 ushort *hash; // hash table of pool entries
231 BtPool *pool; // memory pool page segments
232 BtSpinLatch *latch; // latches for pool hash slots
233 BtLatchMgr *latchmgr; // mapped latch page from allocation page
234 BtLatchSet *latchsets; // mapped latch set from latch pages
236 HANDLE halloc; // allocation and latch table handle
241 BtMgr *mgr; // buffer manager for thread
242 BtPage cursor; // cached frame for start/next (never mapped)
243 BtPage frame; // spare frame for the page split (never mapped)
244 BtPage zero; // page frame for zeroes at end of file
245 BtPage page; // current page
246 uid page_no; // current page number
247 uid cursor_page; // current cursor page number
248 BtLatchSet *set; // current page latch set
249 BtPool *pool; // current page pool
250 unsigned char *mem; // frame, cursor, page memory buffer
251 int foster; // last search was to foster child
252 int found; // last delete was found
253 int err; // last error
268 extern void bt_close (BtDb *bt);
269 extern BtDb *bt_open (BtMgr *mgr);
270 extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod, uint lvl);
271 extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len);
272 extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
273 extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
274 extern uint bt_nextkey (BtDb *bt, uint slot);
277 extern BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolsize, uint segsize, uint hashsize);
278 void bt_mgrclose (BtMgr *mgr);
280 // internal functions
281 BTERR bt_splitpage (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no);
282 uint bt_cleanpage(BtDb *bt, BtPage page, uint amt, uint slot);
283 BTERR bt_mergeleft (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no, uint lvl);
285 // Helper functions to return cursor slot values
287 extern BtKey bt_key (BtDb *bt, uint slot);
288 extern uid bt_uid (BtDb *bt, uint slot);
289 extern uint bt_tod (BtDb *bt, uint slot);
291 // BTree page number constants
292 #define ALLOC_page 0 // allocation & lock manager hash table
293 #define ROOT_page 1 // root of the btree
294 #define LEAF_page 2 // first page of leaves
295 #define LATCH_page 3 // pages for lock manager
297 // Number of levels to create in a new BTree
301 // The page is allocated from low and hi ends.
302 // The key offsets and row-id's are allocated
303 // from the bottom, while the text of the key
304 // is allocated from the top. When the two
305 // areas meet, the page is split into two.
307 // A key consists of a length byte, two bytes of
308 // index number (0 - 65534), and up to 253 bytes
309 // of key value. Duplicate keys are discarded.
310 // Associated with each key is a 48 bit row-id.
312 // The b-tree root is always located at page 1.
313 // The first leaf page of level zero is always
314 // located on page 2.
316 // When to root page fills, it is split in two and
317 // the tree height is raised by a new root at page
318 // one with two keys.
320 // Deleted keys are marked with a dead bit until
321 // page cleanup The fence key for a node is always
322 // present, even after deletion and cleanup.
324 // Groups of pages called segments from the btree are
325 // cached with memory mapping. A hash table is used to keep
326 // track of the cached segments. This behaviour is controlled
327 // by the cache block size parameter to bt_open.
329 // To achieve maximum concurrency one page is locked at a time
330 // as the tree is traversed to find leaf key in question.
332 // An adoption traversal leaves the parent node locked as the
333 // tree is traversed to the level in quesiton.
335 // Page 0 is dedicated to lock for new page extensions,
336 // and chains empty pages together for reuse.
338 // Empty pages are chained together through the ALLOC page and reused.
340 // Access macros to address slot and key values from the page
342 #define slotptr(page, slot) (page->table + slot-1)
343 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
345 void bt_putid(unsigned char *dest, uid id)
350 dest[i] = (unsigned char)id, id >>= 8;
353 uid bt_getid(unsigned char *src)
358 for( i = 0; i < BtId; i++ )
359 id <<= 8, id |= *src++;
364 // wait until write lock mode is clear
365 // and add 1 to the share count
367 void bt_spinreadlock(BtSpinLatch *latch)
373 while( __sync_fetch_and_or((ushort *)latch, Mutex) & Mutex )
376 while( _InterlockedOr16((ushort *)latch, Mutex) & Mutex )
380 // see if exclusive request is granted or pending
382 if( prev = !(latch->exclusive | latch->pending) )
384 __sync_fetch_and_add((ushort *)latch, Share);
386 _InterlockedExchangeAdd16 ((ushort *)latch, Share);
390 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
392 _InterlockedAnd16((ushort *)latch, ~Mutex);
397 } while( sched_yield(), 1 );
399 } while( SwitchToThread(), 1 );
403 // wait for other read and write latches to relinquish
405 void bt_spinwritelock(BtSpinLatch *latch)
409 while( __sync_fetch_and_or((ushort *)latch, Mutex | Pending) & Mutex )
412 while( _InterlockedOr16((ushort *)latch, Mutex | Pending) & Mutex )
415 if( !(latch->share | latch->exclusive) ) {
417 __sync_fetch_and_or((ushort *)latch, Write);
418 __sync_fetch_and_and ((ushort *)latch, ~(Mutex | Pending));
420 _InterlockedOr16((ushort *)latch, Write);
421 _InterlockedAnd16((ushort *)latch, ~(Mutex | Pending));
427 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
429 _InterlockedAnd16((ushort *)latch, ~Mutex);
439 // try to obtain write lock
441 // return 1 if obtained,
444 int bt_spinwritetry(BtSpinLatch *latch)
449 if( prev = __sync_fetch_and_or((ushort *)latch, Mutex), prev & Mutex )
452 if( prev = _InterlockedOr16((ushort *)latch, Mutex), prev & Mutex )
455 // take write access if all bits are clear
459 __sync_fetch_and_or ((ushort *)latch, Write);
461 _InterlockedOr16((ushort *)latch, Write);
465 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
467 _InterlockedAnd16((ushort *)latch, ~Mutex);
474 void bt_spinreleasewrite(BtSpinLatch *latch)
477 __sync_fetch_and_and ((ushort *)latch, ~Write);
479 _InterlockedAnd16((ushort *)latch, ~Write);
483 // decrement reader count
485 void bt_spinreleaseread(BtSpinLatch *latch)
488 __sync_fetch_and_add((ushort *)latch, -Share);
490 _InterlockedExchangeAdd16 ((ushort *)latch, -Share);
494 void bt_initlockset (BtLatchSet *set, int reuse)
497 pthread_rwlockattr_t rwattr[1];
500 pthread_rwlock_destroy (set->readwr->lock);
501 pthread_rwlock_destroy (set->access->lock);
502 pthread_rwlock_destroy (set->parent->lock);
505 pthread_rwlockattr_init (rwattr);
506 pthread_rwlockattr_setkind_np (rwattr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
507 pthread_rwlockattr_setpshared (rwattr, PTHREAD_PROCESS_SHARED);
509 pthread_rwlock_init (set->readwr->lock, rwattr);
510 pthread_rwlock_init (set->access->lock, rwattr);
511 pthread_rwlock_init (set->parent->lock, rwattr);
512 pthread_rwlockattr_destroy (rwattr);
514 InitializeSRWLock (set->readwr->srw);
515 InitializeSRWLock (set->access->srw);
516 InitializeSRWLock (set->parent->srw);
520 // link latch table entry into latch hash table
522 void bt_latchlink (BtDb *bt, ushort hashidx, ushort victim, uid page_no)
524 BtLatchSet *set = bt->mgr->latchsets + victim;
526 if( set->next = bt->mgr->latchmgr->table[hashidx].slot )
527 bt->mgr->latchsets[set->next].prev = victim;
529 bt->mgr->latchmgr->table[hashidx].slot = victim;
530 set->page_no = page_no;
535 void bt_unpinlatch (BtLatchSet *set)
538 __sync_fetch_and_add(&set->pin, -1);
540 _InterlockedDecrement16 (&set->pin);
544 // find existing latchset or inspire new one
545 // return with latchset pinned
547 BtLatchSet *bt_pinlatch (BtDb *bt, uid page_no)
549 ushort hashidx = page_no % bt->mgr->latchmgr->latchhash;
550 ushort slot, avail = 0, victim, idx;
553 // obtain read lock on hash table entry
555 bt_spinreadlock(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 } while( slot = set->next );
566 __sync_fetch_and_add(&set->pin, 1);
568 _InterlockedIncrement16 (&set->pin);
572 bt_spinreleaseread (bt->mgr->latchmgr->table[hashidx].latch);
577 // try again, this time with write lock
579 bt_spinwritelock(bt->mgr->latchmgr->table[hashidx].latch);
581 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
583 set = bt->mgr->latchsets + slot;
584 if( page_no == set->page_no )
586 if( !set->pin && !avail )
588 } while( slot = set->next );
590 // found our entry, or take over an unpinned one
592 if( slot || (slot = avail) ) {
593 set = bt->mgr->latchsets + slot;
595 __sync_fetch_and_add(&set->pin, 1);
597 _InterlockedIncrement16 (&set->pin);
599 set->page_no = page_no;
600 bt_spinreleasewrite(bt->mgr->latchmgr->table[hashidx].latch);
604 // see if there are any unused entries
606 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, 1) + 1;
608 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchdeployed);
611 if( victim < bt->mgr->latchmgr->latchtotal ) {
612 set = bt->mgr->latchsets + victim;
614 __sync_fetch_and_add(&set->pin, 1);
616 _InterlockedIncrement16 (&set->pin);
618 bt_initlockset (set, 0);
619 bt_latchlink (bt, hashidx, victim, page_no);
620 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
625 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, -1);
627 victim = _InterlockedDecrement16 (&bt->mgr->latchmgr->latchdeployed);
629 // find and reuse previous lock entry
633 victim = __sync_fetch_and_add(&bt->mgr->latchmgr->latchvictim, 1);
635 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchvictim) - 1;
637 // we don't use slot zero
639 if( victim %= bt->mgr->latchmgr->latchtotal )
640 set = bt->mgr->latchsets + victim;
644 // take control of our slot
645 // from other threads
647 if( set->pin || !bt_spinwritetry (set->busy) )
652 // try to get write lock on hash chain
653 // skip entry if not obtained
654 // or has outstanding locks
656 if( !bt_spinwritetry (bt->mgr->latchmgr->table[idx].latch) ) {
657 bt_spinreleasewrite (set->busy);
662 bt_spinreleasewrite (set->busy);
663 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
667 // unlink our available victim from its hash chain
670 bt->mgr->latchsets[set->prev].next = set->next;
672 bt->mgr->latchmgr->table[idx].slot = set->next;
675 bt->mgr->latchsets[set->next].prev = set->prev;
677 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
679 __sync_fetch_and_add(&set->pin, 1);
681 _InterlockedIncrement16 (&set->pin);
683 bt_initlockset (set, 1);
684 bt_latchlink (bt, hashidx, victim, page_no);
685 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
686 bt_spinreleasewrite (set->busy);
691 void bt_mgrclose (BtMgr *mgr)
696 // release mapped pages
697 // note that slot zero is never used
699 for( slot = 1; slot < mgr->poolmax; slot++ ) {
700 pool = mgr->pool + slot;
703 munmap (pool->map, (mgr->poolmask+1) << mgr->page_bits);
706 FlushViewOfFile(pool->map, 0);
707 UnmapViewOfFile(pool->map);
708 CloseHandle(pool->hmap);
714 munmap (mgr->latchsets, mgr->latchmgr->nlatchpage * mgr->page_size);
715 munmap (mgr->latchmgr, mgr->page_size);
717 FlushViewOfFile(mgr->latchmgr, 0);
718 UnmapViewOfFile(mgr->latchmgr);
719 CloseHandle(mgr->halloc);
726 free (mgr->pooladvise);
729 FlushFileBuffers(mgr->idx);
730 CloseHandle(mgr->idx);
731 GlobalFree (mgr->pool);
732 GlobalFree (mgr->hash);
733 GlobalFree (mgr->latch);
738 // close and release memory
740 void bt_close (BtDb *bt)
747 VirtualFree (bt->mem, 0, MEM_RELEASE);
752 // open/create new btree buffer manager
754 // call with file_name, BT_openmode, bits in page size (e.g. 16),
755 // size of mapped page pool (e.g. 8192)
757 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
759 uint lvl, attr, cacheblk, last, slot, idx;
760 uint nlatchpage, latchhash;
761 BtLatchMgr *latchmgr;
769 SYSTEM_INFO sysinfo[1];
772 // determine sanity of page size and buffer pool
774 if( bits > BT_maxbits )
776 else if( bits < BT_minbits )
780 return NULL; // must have buffer pool
783 mgr = calloc (1, sizeof(BtMgr));
785 mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
788 return free(mgr), NULL;
790 cacheblk = 4096; // minimum mmap segment size for unix
793 mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
794 attr = FILE_ATTRIBUTE_NORMAL;
795 mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
797 if( mgr->idx == INVALID_HANDLE_VALUE )
798 return GlobalFree(mgr), NULL;
800 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
801 GetSystemInfo(sysinfo);
802 cacheblk = sysinfo->dwAllocationGranularity;
806 latchmgr = malloc (BT_maxpage);
809 // read minimum page size to get root info
811 if( size = lseek (mgr->idx, 0L, 2) ) {
812 if( pread(mgr->idx, latchmgr, BT_minpage, 0) == BT_minpage )
813 bits = latchmgr->alloc->bits;
815 return free(mgr), free(latchmgr), NULL;
816 } else if( mode == BT_ro )
817 return free(latchmgr), free (mgr), NULL;
819 latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
820 size = GetFileSize(mgr->idx, amt);
823 if( !ReadFile(mgr->idx, (char *)latchmgr, BT_minpage, amt, NULL) )
824 return bt_mgrclose (mgr), NULL;
825 bits = latchmgr->alloc->bits;
826 } else if( mode == BT_ro )
827 return bt_mgrclose (mgr), NULL;
830 mgr->page_size = 1 << bits;
831 mgr->page_bits = bits;
833 mgr->poolmax = poolmax;
836 if( cacheblk < mgr->page_size )
837 cacheblk = mgr->page_size;
839 // mask for partial memmaps
841 mgr->poolmask = (cacheblk >> bits) - 1;
843 // see if requested size of pages per memmap is greater
845 if( (1 << segsize) > mgr->poolmask )
846 mgr->poolmask = (1 << segsize) - 1;
850 while( (1 << mgr->seg_bits) <= mgr->poolmask )
853 mgr->hashsize = hashsize;
856 mgr->pool = calloc (poolmax, sizeof(BtPool));
857 mgr->hash = calloc (hashsize, sizeof(ushort));
858 mgr->latch = calloc (hashsize, sizeof(BtSpinLatch));
859 mgr->pooladvise = calloc (poolmax, (mgr->poolmask + 8) / 8);
861 mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * sizeof(BtPool));
862 mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
863 mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtSpinLatch));
869 // initialize an empty b-tree with latch page, root page, page of leaves
870 // and page(s) of latches
872 memset (latchmgr, 0, 1 << bits);
873 nlatchpage = BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1;
874 bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
875 latchmgr->alloc->bits = mgr->page_bits;
877 latchmgr->nlatchpage = nlatchpage;
878 latchmgr->latchtotal = nlatchpage * (mgr->page_size / sizeof(BtLatchSet));
880 // initialize latch manager
882 latchhash = (mgr->page_size - sizeof(BtLatchMgr)) / sizeof(BtHashEntry);
884 // size of hash table = total number of latchsets
886 if( latchhash > latchmgr->latchtotal )
887 latchhash = latchmgr->latchtotal;
889 latchmgr->latchhash = latchhash;
892 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
893 return free(latchmgr), bt_mgrclose (mgr), NULL;
895 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
896 return bt_mgrclose (mgr), NULL;
898 if( *amt < mgr->page_size )
899 return bt_mgrclose (mgr), NULL;
902 memset (latchmgr, 0, 1 << bits);
903 latchmgr->alloc->bits = mgr->page_bits;
905 for( lvl=MIN_lvl; lvl--; ) {
906 slotptr(latchmgr->alloc, 1)->off = mgr->page_size - 3;
907 bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
908 key = keyptr(latchmgr->alloc, 1);
909 key->len = 2; // create stopper key
912 latchmgr->alloc->min = mgr->page_size - 3;
913 latchmgr->alloc->lvl = lvl;
914 latchmgr->alloc->cnt = 1;
915 latchmgr->alloc->act = 1;
917 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
918 return bt_mgrclose (mgr), NULL;
920 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
921 return bt_mgrclose (mgr), NULL;
923 if( *amt < mgr->page_size )
924 return bt_mgrclose (mgr), NULL;
928 // clear out latch manager locks
929 // and rest of pages to round out segment
931 memset(latchmgr, 0, mgr->page_size);
934 while( last <= ((MIN_lvl + 1 + nlatchpage) | mgr->poolmask) ) {
936 pwrite(mgr->idx, latchmgr, mgr->page_size, last << mgr->page_bits);
938 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
939 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
940 return bt_mgrclose (mgr), NULL;
941 if( *amt < mgr->page_size )
942 return bt_mgrclose (mgr), NULL;
949 flag = PROT_READ | PROT_WRITE;
950 mgr->latchmgr = mmap (0, mgr->page_size, flag, MAP_SHARED, mgr->idx, ALLOC_page * mgr->page_size);
951 if( mgr->latchmgr == MAP_FAILED )
952 return bt_mgrclose (mgr), NULL;
953 mgr->latchsets = (BtLatchSet *)mmap (0, mgr->latchmgr->nlatchpage * mgr->page_size, flag, MAP_SHARED, mgr->idx, LATCH_page * mgr->page_size);
954 if( mgr->latchsets == MAP_FAILED )
955 return bt_mgrclose (mgr), NULL;
957 flag = PAGE_READWRITE;
958 mgr->halloc = CreateFileMapping(mgr->idx, NULL, flag, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size, NULL);
960 return bt_mgrclose (mgr), NULL;
962 flag = FILE_MAP_WRITE;
963 mgr->latchmgr = MapViewOfFile(mgr->halloc, flag, 0, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size);
965 return GetLastError(), bt_mgrclose (mgr), NULL;
967 mgr->latchsets = (void *)((char *)mgr->latchmgr + LATCH_page * mgr->page_size);
973 VirtualFree (latchmgr, 0, MEM_RELEASE);
978 // open BTree access method
979 // based on buffer manager
981 BtDb *bt_open (BtMgr *mgr)
983 BtDb *bt = malloc (sizeof(*bt));
985 memset (bt, 0, sizeof(*bt));
988 bt->mem = malloc (3 *mgr->page_size);
990 bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
992 bt->frame = (BtPage)bt->mem;
993 bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
994 bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
996 memset(bt->zero, 0, mgr->page_size);
1000 // compare two keys, returning > 0, = 0, or < 0
1001 // as the comparison value
1003 int keycmp (BtKey key1, unsigned char *key2, uint len2)
1005 uint len1 = key1->len;
1008 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
1021 void bt_readlock(BtLatch *latch)
1024 pthread_rwlock_rdlock (latch->lock);
1026 AcquireSRWLockShared (latch->srw);
1030 // wait for other read and write latches to relinquish
1032 void bt_writelock(BtLatch *latch)
1035 pthread_rwlock_wrlock (latch->lock);
1037 AcquireSRWLockExclusive (latch->srw);
1041 // try to obtain write lock
1043 // return 1 if obtained,
1044 // 0 if already write or read locked
1046 int bt_writetry(BtLatch *latch)
1051 result = !pthread_rwlock_trywrlock (latch->lock);
1053 result = TryAcquireSRWLockExclusive (latch->srw);
1060 void bt_releasewrite(BtLatch *latch)
1063 pthread_rwlock_unlock (latch->lock);
1065 ReleaseSRWLockExclusive (latch->srw);
1069 // decrement reader count
1071 void bt_releaseread(BtLatch *latch)
1074 pthread_rwlock_unlock (latch->lock);
1076 ReleaseSRWLockShared (latch->srw);
1082 // find segment in pool
1083 // must be called with hashslot idx locked
1084 // return NULL if not there
1085 // otherwise return node
1087 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
1092 // compute start of hash chain in pool
1094 if( slot = bt->mgr->hash[idx] )
1095 pool = bt->mgr->pool + slot;
1099 page_no &= ~bt->mgr->poolmask;
1101 while( pool->basepage != page_no )
1102 if( pool = pool->hashnext )
1110 // add segment to hash table
1112 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
1117 pool->hashprev = pool->hashnext = NULL;
1118 pool->basepage = page_no & ~bt->mgr->poolmask;
1121 if( slot = bt->mgr->hash[idx] ) {
1122 node = bt->mgr->pool + slot;
1123 pool->hashnext = node;
1124 node->hashprev = pool;
1127 bt->mgr->hash[idx] = pool->slot;
1130 // find best segment to evict from buffer pool
1132 BtPool *bt_findlru (BtDb *bt, uint hashslot)
1134 unsigned long long int target = ~0LL;
1135 BtPool *pool = NULL, *node;
1140 node = bt->mgr->pool + hashslot;
1142 // scan pool entries under hash table slot
1147 if( node->lru > target )
1151 } while( node = node->hashnext );
1156 // map new buffer pool segment to virtual memory
1158 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
1160 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
1161 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
1165 flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
1166 pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED, bt->mgr->idx, off);
1167 if( pool->map == MAP_FAILED )
1168 return bt->err = BTERR_map;
1169 // clear out madvise issued bits
1170 memset (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8) / 8), 0, (bt->mgr->poolmask + 8)/8);
1172 flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
1173 pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
1175 return bt->err = BTERR_map;
1177 flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
1178 pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1180 return bt->err = BTERR_map;
1185 // calculate page within pool
1187 BtPage bt_page (BtDb *bt, BtPool *pool, uid page_no)
1189 uint subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1192 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1195 uint idx = subpage / 8;
1196 uint bit = subpage % 8;
1198 if( ~((bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] >> bit) & 1 ) {
1199 madvise (page, bt->mgr->page_size, MADV_WILLNEED);
1200 (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] |= 1 << bit;
1209 void bt_unpinpool (BtPool *pool)
1212 __sync_fetch_and_add(&pool->pin, -1);
1214 _InterlockedDecrement16 (&pool->pin);
1218 // find or place requested page in segment-pool
1219 // return pool table entry, incrementing pin
1221 BtPool *bt_pinpool(BtDb *bt, uid page_no)
1223 BtPool *pool, *node, *next;
1224 uint slot, idx, victim;
1227 // lock hash table chain
1229 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1230 bt_spinreadlock (&bt->mgr->latch[idx]);
1232 // look up in hash table
1234 if( pool = bt_findpool(bt, page_no, idx) ) {
1236 __sync_fetch_and_add(&pool->pin, 1);
1238 _InterlockedIncrement16 (&pool->pin);
1240 bt_spinreleaseread (&bt->mgr->latch[idx]);
1245 // upgrade to write lock
1247 bt_spinreleaseread (&bt->mgr->latch[idx]);
1248 bt_spinwritelock (&bt->mgr->latch[idx]);
1250 // try to find page in pool with write lock
1252 if( pool = bt_findpool(bt, page_no, idx) ) {
1254 __sync_fetch_and_add(&pool->pin, 1);
1256 _InterlockedIncrement16 (&pool->pin);
1258 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1263 // allocate a new pool node
1264 // and add to hash table
1267 slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
1269 slot = _InterlockedIncrement16 (&bt->mgr->poolcnt) - 1;
1272 if( ++slot < bt->mgr->poolmax ) {
1273 pool = bt->mgr->pool + slot;
1276 if( bt_mapsegment(bt, pool, page_no) )
1279 bt_linkhash(bt, pool, page_no, idx);
1281 __sync_fetch_and_add(&pool->pin, 1);
1283 _InterlockedIncrement16 (&pool->pin);
1285 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1289 // pool table is full
1290 // find best pool entry to evict
1293 __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
1295 _InterlockedDecrement16 (&bt->mgr->poolcnt);
1300 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
1302 victim = _InterlockedIncrement16 (&bt->mgr->evicted) - 1;
1304 victim %= bt->mgr->hashsize;
1306 // try to get write lock
1307 // skip entry if not obtained
1309 if( !bt_spinwritetry (&bt->mgr->latch[victim]) )
1312 // if cache entry is empty
1313 // or no slots are unpinned
1316 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
1317 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1321 // unlink victim pool node from hash table
1323 if( node = pool->hashprev )
1324 node->hashnext = pool->hashnext;
1325 else if( node = pool->hashnext )
1326 bt->mgr->hash[victim] = node->slot;
1328 bt->mgr->hash[victim] = 0;
1330 if( node = pool->hashnext )
1331 node->hashprev = pool->hashprev;
1333 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1335 // remove old file mapping
1337 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1339 FlushViewOfFile(pool->map, 0);
1340 UnmapViewOfFile(pool->map);
1341 CloseHandle(pool->hmap);
1345 // create new pool mapping
1346 // and link into hash table
1348 if( bt_mapsegment(bt, pool, page_no) )
1351 bt_linkhash(bt, pool, page_no, idx);
1353 __sync_fetch_and_add(&pool->pin, 1);
1355 _InterlockedIncrement16 (&pool->pin);
1357 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1362 // place write, read, or parent lock on requested page_no.
1363 // pin to buffer pool and return latchset pointer
1365 void bt_lockpage(BtLock mode, BtLatchSet *set)
1369 bt_readlock (set->readwr);
1372 bt_writelock (set->readwr);
1375 bt_readlock (set->access);
1378 bt_writelock (set->access);
1381 bt_writelock (set->parent);
1386 // remove write, read, or parent lock on requested page_no.
1388 void bt_unlockpage(BtLock mode, BtLatchSet *set)
1392 bt_releaseread (set->readwr);
1395 bt_releasewrite (set->readwr);
1398 bt_releaseread (set->access);
1401 bt_releasewrite (set->access);
1404 bt_releasewrite (set->parent);
1409 // allocate a new page and write page into it
1411 uid bt_newpage(BtDb *bt, BtPage page)
1419 // lock allocation page
1421 bt_spinwritelock(bt->mgr->latchmgr->lock);
1423 // use empty chain first
1424 // else allocate empty page
1426 if( new_page = bt_getid(bt->mgr->latchmgr->alloc[1].right) ) {
1427 if( pool = bt_pinpool (bt, new_page) )
1428 pmap = bt_page (bt, pool, new_page);
1431 bt_putid(bt->mgr->latchmgr->alloc[1].right, bt_getid(pmap->right));
1432 bt_unpinpool (pool);
1435 new_page = bt_getid(bt->mgr->latchmgr->alloc->right);
1436 bt_putid(bt->mgr->latchmgr->alloc->right, new_page+1);
1440 // if writing first page of pool block, zero last page in the block
1442 if ( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1444 // use zero buffer to write zeros
1445 if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1446 return bt->err = BTERR_wrt, 0;
1449 // unlock allocation latch
1451 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1453 if ( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1454 return bt->err = BTERR_wrt, 0;
1457 // unlock allocation latch
1459 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1461 // bring new page into pool and copy page.
1462 // this will extend the file into the new pages.
1463 // NB -- no latch required
1465 if( pool = bt_pinpool (bt, new_page) )
1466 pmap = bt_page (bt, pool, new_page);
1470 memcpy(pmap, page, bt->mgr->page_size);
1471 bt_unpinpool (pool);
1476 // find slot in page for given key at a given level
1478 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1480 uint diff, higher = bt->page->cnt, low = 1, slot;
1482 // low is the lowest candidate, higher is already
1483 // tested as .ge. the given key, loop ends when they meet
1485 while( diff = higher - low ) {
1486 slot = low + ( diff >> 1 );
1487 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1496 // find and load page at given level for given key
1497 // leave page rd or wr locked as requested
1499 int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, BtLock lock)
1501 uid page_no = ROOT_page, prevpage = 0;
1502 BtLatchSet *set, *prevset;
1503 uint drill = 0xff, slot;
1504 uint mode, prevmode;
1508 // start at root of btree and drill down
1511 // determine lock mode of drill level
1512 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1514 // obtain latch set for this page
1516 bt->set = bt_pinlatch (bt, page_no);
1517 bt->page_no = page_no;
1519 // pin page contents
1521 if( bt->pool = bt_pinpool (bt, page_no) )
1522 bt->page = bt_page (bt, bt->pool, page_no);
1526 // obtain access lock using lock chaining with Access mode
1528 if( page_no > ROOT_page )
1529 bt_lockpage(BtLockAccess, bt->set);
1531 // now unlock and unpin our (possibly foster) parent
1534 bt_unlockpage(prevmode, prevset);
1535 bt_unpinlatch (prevset);
1536 bt_unpinpool (prevpool);
1540 // obtain read lock using lock chaining
1542 bt_lockpage(mode, bt->set);
1544 if( page_no > ROOT_page )
1545 bt_unlockpage(BtLockAccess, bt->set);
1547 // re-read and re-lock root after determining actual level of root
1549 if( page_no == ROOT_page )
1550 if( bt->page->lvl != drill) {
1551 drill = bt->page->lvl;
1553 if( lock == BtLockWrite && drill == lvl ) {
1554 bt_unlockpage(mode, bt->set);
1555 bt_unpinlatch (bt->set);
1556 bt_unpinpool (bt->pool);
1561 prevpage = bt->page_no;
1562 prevpool = bt->pool;
1566 // were we supposed to find a foster child?
1567 // if so, slide right onto it
1569 if( keycmp (keyptr(bt->page,bt->page->cnt), key, len) < 0 ) {
1570 page_no = bt_getid(bt->page->right);
1574 // find key on page at this level
1575 // and either descend to requested level
1576 // or return key slot
1578 slot = bt_findslot (bt, key, len);
1580 // is this slot < foster child area
1581 // on the requested level?
1583 // if so, return actual slot even if dead
1585 if( slot <= bt->page->cnt - bt->page->foster )
1587 return bt->foster = foster, slot;
1589 // find next active slot
1591 // note: foster children are never dead
1593 while( slotptr(bt->page, slot)->dead )
1594 if( slot++ < bt->page->cnt )
1597 // we are waiting for fence key posting
1598 page_no = bt_getid(bt->page->right);
1602 // is this slot < foster child area
1603 // if so, drill to next level
1605 if( slot <= bt->page->cnt - bt->page->foster )
1606 foster = 0, drill--;
1610 // continue right onto foster child
1611 // or down to next level.
1613 page_no = bt_getid(slotptr(bt->page, slot)->id);
1617 // return error on end of chain
1619 bt->err = BTERR_struct;
1620 return 0; // return error
1623 // remove empty page from the B-tree
1624 // by pulling our right node left over ourselves
1626 // call with bt->page, etc, set to page's locked parent
1627 // returns with page locked.
1629 BTERR bt_mergeright (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no, uint lvl, uint slot)
1631 BtLatchSet *rset, *pset, *rpset;
1632 BtPool *rpool, *ppool, *rppool;
1633 BtPage rpage, ppage, rppage;
1634 uid right, parent, rparent;
1638 // cache node's parent page
1640 parent = bt->page_no;
1645 // lock and map our right page
1646 // note that it cannot be our foster child
1647 // since the our node is empty
1648 // and it cannot be NULL because of the stopper
1649 // in the last right page
1651 bt_lockpage (BtLockWrite, set);
1653 // if we aren't dead yet
1658 if( right = bt_getid (page->right) )
1659 if( rpool = bt_pinpool (bt, right) )
1660 rpage = bt_page (bt, rpool, right);
1664 return bt->err = BTERR_struct;
1666 rset = bt_pinlatch (bt, right);
1668 // find our right neighbor
1670 if( ppage->act > 1 ) {
1671 for( idx = slot; idx++ < ppage->cnt; )
1672 if( !slotptr(ppage, idx)->dead )
1675 if( idx > ppage->cnt )
1676 return bt->err = BTERR_struct;
1678 // redirect right neighbor in parent to left node
1680 bt_putid(slotptr(ppage,idx)->id, page_no);
1683 // if parent has only our deleted page, e.g. no right neighbor
1684 // prepare to merge parent itself
1686 if( ppage->act == 1 ) {
1687 if( rparent = bt_getid (ppage->right) )
1688 if( rppool = bt_pinpool (bt, rparent) )
1689 rppage = bt_page (bt, rppool, rparent);
1693 return bt->err = BTERR_struct;
1695 rpset = bt_pinlatch (bt, rparent);
1696 bt_lockpage (BtLockWrite, rpset);
1698 // find our right neighbor on right parent page
1700 for( idx = 0; idx++ < rppage->cnt; )
1701 if( !slotptr(rppage, idx)->dead ) {
1702 bt_putid (slotptr(rppage, idx)->id, page_no);
1706 if( idx > rppage->cnt )
1707 return bt->err = BTERR_struct;
1710 // now that there are no more pointers to our right node
1711 // we can wait for delete lock on it
1713 bt_lockpage(BtLockDelete, rset);
1714 bt_lockpage(BtLockWrite, rset);
1716 // pull contents of right page into our empty page
1718 memcpy (page, rpage, bt->mgr->page_size);
1720 // ready to release right parent lock
1721 // now that we have a new page in place
1723 if( ppage->act == 1 ) {
1724 bt_unlockpage (BtLockWrite, rpset);
1725 bt_unpinlatch (rpset);
1726 bt_unpinpool (rppool);
1729 // add killed right block to free chain
1732 bt_spinwritelock(bt->mgr->latchmgr->lock);
1734 // store free chain in allocation page second right
1736 bt_putid(rpage->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1737 bt_putid(bt->mgr->latchmgr->alloc[1].right, right);
1739 // unlock latch mgr and right page
1741 bt_unlockpage(BtLockDelete, rset);
1742 bt_unlockpage(BtLockWrite, rset);
1743 bt_unpinlatch (rset);
1744 bt_unpinpool (rpool);
1746 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1748 // delete our obsolete fence key from our parent
1750 slotptr(ppage, slot)->dead = 1;
1753 // if our parent now empty
1754 // remove it from the tree
1756 if( ppage->act-- == 1 )
1757 if( bt_mergeleft (bt, ppage, ppool, pset, parent, lvl+1) )
1761 bt_unlockpage (BtLockWrite, pset);
1762 bt_unpinlatch (pset);
1763 bt_unpinpool (ppool);
1769 // remove empty page from the B-tree
1770 // try merging left first. If no left
1771 // sibling, then merge right.
1773 // call with page loaded and locked,
1774 // return with page locked.
1776 BTERR bt_mergeleft (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no, uint lvl)
1778 unsigned char fencekey[256], postkey[256];
1779 uint slot, idx, postfence = 0;
1780 BtLatchSet *lset, *pset;
1781 BtPool *lpool, *ppool;
1782 BtPage lpage, ppage;
1786 ptr = keyptr(page, page->cnt);
1787 memcpy(fencekey, ptr, ptr->len + 1);
1788 bt_unlockpage (BtLockWrite, set);
1790 // load and lock our parent
1793 if( !(slot = bt_loadpage (bt, fencekey+1, *fencekey, lvl+1, BtLockWrite)) )
1796 parent = bt->page_no;
1801 // wait until we are not a foster child
1804 bt_unlockpage (BtLockWrite, pset);
1805 bt_unpinlatch (pset);
1806 bt_unpinpool (ppool);
1815 // find our left neighbor in our parent page
1817 for( idx = slot; --idx; )
1818 if( !slotptr(ppage, idx)->dead )
1821 // if no left neighbor, do right merge
1824 return bt_mergeright (bt, page, pool, set, page_no, lvl, slot);
1826 // lock and map our left neighbor's page
1828 left = bt_getid (slotptr(ppage, idx)->id);
1830 if( lpool = bt_pinpool (bt, left) )
1831 lpage = bt_page (bt, lpool, left);
1835 lset = bt_pinlatch (bt, left);
1836 bt_lockpage(BtLockWrite, lset);
1838 // wait until foster sibling is in our parent
1840 if( bt_getid (lpage->right) != page_no ) {
1841 bt_unlockpage (BtLockWrite, pset);
1842 bt_unpinlatch (pset);
1843 bt_unpinpool (ppool);
1844 bt_unlockpage (BtLockWrite, lset);
1845 bt_unpinlatch (lset);
1846 bt_unpinpool (lpool);
1855 // since our page will have no more pointers to it,
1856 // obtain Delete lock and wait for write locks to clear
1858 bt_lockpage(BtLockDelete, set);
1859 bt_lockpage(BtLockWrite, set);
1861 // if we aren't dead yet,
1862 // get ready for exit
1865 bt_unlockpage(BtLockDelete, set);
1866 bt_unlockpage(BtLockWrite, lset);
1867 bt_unpinlatch (lset);
1868 bt_unpinpool (lpool);
1872 // are we are the fence key for our parent?
1873 // if so, grab our old fence key
1875 if( postfence = slot == ppage->cnt ) {
1876 ptr = keyptr (ppage, ppage->cnt);
1877 memcpy(fencekey, ptr, ptr->len + 1);
1878 memset(slotptr(ppage, ppage->cnt), 0, sizeof(BtSlot));
1880 // clear out other dead slots
1882 while( --ppage->cnt )
1883 if( slotptr(ppage, ppage->cnt)->dead )
1884 memset(slotptr(ppage, ppage->cnt), 0, sizeof(BtSlot));
1888 ptr = keyptr (ppage, ppage->cnt);
1889 memcpy(postkey, ptr, ptr->len + 1);
1891 slotptr(ppage,slot)->dead = 1;
1896 // push our right neighbor pointer to our left
1898 memcpy (lpage->right, page->right, BtId);
1900 // add ourselves to free chain
1903 bt_spinwritelock(bt->mgr->latchmgr->lock);
1905 // store free chain in allocation page second right
1906 bt_putid(page->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1907 bt_putid(bt->mgr->latchmgr->alloc[1].right, page_no);
1909 // unlock latch mgr and pages
1911 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1912 bt_unlockpage(BtLockWrite, lset);
1913 bt_unpinlatch (lset);
1914 bt_unpinpool (lpool);
1916 // release our node's delete lock
1918 bt_unlockpage(BtLockDelete, set);
1921 bt_unlockpage (BtLockWrite, pset);
1922 bt_unpinpool (ppool);
1924 // do we need to post parent's fence key in its parent?
1926 if( !postfence || parent == ROOT_page ) {
1927 bt_unpinlatch (pset);
1932 // interlock parent fence post
1934 bt_lockpage (BtLockParent, pset);
1936 // load parent's parent page
1938 if( !(slot = bt_loadpage (bt, fencekey+1, *fencekey, lvl+2, BtLockWrite)) )
1941 if( !(slot = bt_cleanpage (bt, bt->page, *fencekey, slot)) )
1942 if( bt_splitpage (bt, bt->page, bt->pool, bt->set, bt->page_no) )
1949 page->min -= *postkey + 1;
1950 ((unsigned char *)page)[page->min] = *postkey;
1951 memcpy ((unsigned char *)page + page->min +1, postkey + 1, *postkey );
1952 slotptr(page, slot)->off = page->min;
1954 bt_unlockpage (BtLockParent, pset);
1955 bt_unpinlatch (pset);
1957 bt_unlockpage (BtLockWrite, bt->set);
1958 bt_unpinlatch (bt->set);
1959 bt_unpinpool (bt->pool);
1965 // find and delete key on page by marking delete flag bit
1966 // if page becomes empty, delete it from the btree
1968 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len)
1977 if( !(slot = bt_loadpage (bt, key, len, 0, BtLockWrite)) )
1980 page_no = bt->page_no;
1985 // if key is found delete it, otherwise ignore request
1987 ptr = keyptr(page, slot);
1989 if( bt->found = !keycmp (ptr, key, len) )
1990 if( bt->found = slotptr(page, slot)->dead == 0 ) {
1991 slotptr(page,slot)->dead = 1;
1992 if( slot < page->cnt )
1995 if( bt_mergeleft (bt, page, pool, set, page_no, 0) )
1999 bt_unlockpage(BtLockWrite, set);
2000 bt_unpinlatch (set);
2001 bt_unpinpool (pool);
2005 // find key in leaf level and return row-id
2007 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
2013 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
2014 ptr = keyptr(bt->page, slot);
2018 // if key exists, return row-id
2019 // otherwise return 0
2021 if( slot <= bt->page->cnt && !keycmp (ptr, key, len) )
2022 id = bt_getid(slotptr(bt->page,slot)->id);
2026 bt_unlockpage (BtLockRead, bt->set);
2027 bt_unpinlatch (bt->set);
2028 bt_unpinpool (bt->pool);
2032 // check page for space available,
2033 // clean if necessary and return
2034 // 0 - page needs splitting
2035 // >0 new slot value
2037 uint bt_cleanpage(BtDb *bt, BtPage page, uint amt, uint slot)
2039 uint nxt = bt->mgr->page_size;
2040 uint cnt = 0, idx = 0;
2041 uint max = page->cnt;
2045 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
2048 // skip cleanup if nothing to reclaim
2053 memcpy (bt->frame, page, bt->mgr->page_size);
2055 // skip page info and set rest of page to zero
2057 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
2061 // try cleaning up page first
2063 // always leave fence key in the array
2064 // otherwise, remove deleted key
2066 // note: foster children are never dead
2068 while( cnt++ < max ) {
2071 if( cnt < max && slotptr(bt->frame,cnt)->dead )
2076 key = keyptr(bt->frame, cnt);
2077 nxt -= key->len + 1;
2078 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2081 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
2082 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
2084 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2085 slotptr(page, idx)->off = nxt;
2091 // see if page has enough space now, or does it need splitting?
2093 if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
2099 // add key to current page
2100 // page must already be writelocked
2102 void bt_addkeytopage (BtDb *bt, BtPage page, uint slot, unsigned char *key, uint len, uid id, uint tod)
2106 // find next available dead slot and copy key onto page
2107 // note that foster children on the page are never dead
2109 // look for next hole, but stay back from the fence key
2111 for( idx = slot; idx < page->cnt; idx++ )
2112 if( slotptr(page, idx)->dead )
2115 if( idx == page->cnt )
2120 // now insert key into array before slot
2123 *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
2125 page->min -= len + 1;
2126 ((unsigned char *)page)[page->min] = len;
2127 memcpy ((unsigned char *)page + page->min +1, key, len );
2129 bt_putid(slotptr(page,slot)->id, id);
2130 slotptr(page, slot)->off = page->min;
2131 slotptr(page, slot)->tod = tod;
2132 slotptr(page, slot)->dead = 0;
2135 // split the root and raise the height of the btree
2136 // call with current page locked and page no of foster child
2137 // return with current page (root) unlocked
2139 BTERR bt_splitroot(BtDb *bt, uid right)
2141 uint nxt = bt->mgr->page_size;
2142 unsigned char fencekey[256];
2143 BtPage root = bt->page;
2147 // Obtain an empty page to use, and copy the left page
2148 // contents into it from the root. Strip foster child key.
2149 // (it's the stopper key)
2151 memset (slotptr(root, root->cnt), 0, sizeof(BtSlot));
2157 // Save left fence key.
2159 key = keyptr(root, root->cnt);
2160 memcpy (fencekey, key, key->len + 1);
2162 // copy the lower keys into a new left page
2164 if( !(new_page = bt_newpage(bt, root)) )
2167 // preserve the page info at the bottom
2168 // and set rest of the root to zero
2170 memset (root+1, 0, bt->mgr->page_size - sizeof(*root));
2172 // insert left fence key on empty newroot page
2174 nxt -= *fencekey + 1;
2175 memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
2176 bt_putid(slotptr(root, 1)->id, new_page);
2177 slotptr(root, 1)->off = nxt;
2179 // insert stopper key on newroot page
2180 // and increase the root height
2186 memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
2187 bt_putid(slotptr(root, 2)->id, right);
2188 slotptr(root, 2)->off = nxt;
2190 bt_putid(root->right, 0);
2191 root->min = nxt; // reset lowest used offset and key count
2196 // release and unpin root (bt->page)
2198 bt_unlockpage(BtLockWrite, bt->set);
2199 bt_unpinlatch (bt->set);
2200 bt_unpinpool (bt->pool);
2204 // split already locked full node
2205 // return unlocked and unpinned.
2207 BTERR bt_splitpage (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no)
2209 uint slot, cnt, idx, max, nxt = bt->mgr->page_size;
2210 unsigned char fencekey[256];
2211 uint tod = time(NULL);
2212 uint lvl = page->lvl;
2216 // initialize frame buffer for right node
2218 memset (bt->frame, 0, bt->mgr->page_size);
2219 max = page->cnt - page->foster;
2223 // split higher half of keys to bt->frame
2224 // leaving old foster children in the left node,
2225 // and adding a new foster child there.
2227 while( cnt++ < max ) {
2228 key = keyptr(page, cnt);
2229 nxt -= key->len + 1;
2230 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
2231 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
2232 if( !(slotptr(bt->frame, idx)->dead = slotptr(page, cnt)->dead) )
2234 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
2235 slotptr(bt->frame, idx)->off = nxt;
2238 // transfer right link node to new right node
2240 if( page_no > ROOT_page )
2241 memcpy (bt->frame->right, page->right, BtId);
2243 bt->frame->bits = bt->mgr->page_bits;
2244 bt->frame->min = nxt;
2245 bt->frame->cnt = idx;
2246 bt->frame->lvl = lvl;
2248 // get new free page and write right frame to it.
2250 if( !(new_page = bt_newpage(bt, bt->frame)) )
2253 // remember fence key for new right page to add
2254 // as foster child to the left node
2256 key = keyptr(bt->frame, idx);
2257 memcpy (fencekey, key, key->len + 1);
2259 // update lower keys and foster children to continue in old page
2261 memcpy (bt->frame, page, bt->mgr->page_size);
2262 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
2263 nxt = bt->mgr->page_size;
2269 // assemble page of smaller keys
2270 // to remain in the old page
2272 while( cnt++ < max / 2 ) {
2273 key = keyptr(bt->frame, cnt);
2274 nxt -= key->len + 1;
2275 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2276 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
2277 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
2279 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2280 slotptr(page, idx)->off = nxt;
2283 // insert new foster child for right page in queue
2284 // before any of the current foster children
2286 nxt -= *fencekey + 1;
2287 memcpy ((unsigned char *)page + nxt, fencekey, *fencekey + 1);
2289 bt_putid (slotptr(page,++idx)->id, new_page);
2290 slotptr(page, idx)->tod = tod;
2291 slotptr(page, idx)->off = nxt;
2295 // continue with old foster child keys
2296 // note that none will be dead
2298 cnt = bt->frame->cnt - bt->frame->foster;
2300 while( cnt++ < bt->frame->cnt ) {
2301 key = keyptr(bt->frame, cnt);
2302 nxt -= key->len + 1;
2303 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2304 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
2305 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2306 slotptr(page, idx)->off = nxt;
2313 // link new right page
2315 bt_putid (page->right, new_page);
2317 // if current page is the root page, split it
2319 if( page_no == ROOT_page )
2320 return bt_splitroot (bt, new_page);
2322 // release wr lock on our page
2324 bt_unlockpage (BtLockWrite, set);
2326 // obtain ParentModification lock for current page
2327 // to fix new fence key and oldest foster child on page
2329 bt_lockpage (BtLockParent, set);
2331 // get our new fence key to insert in parent node
2333 bt_lockpage (BtLockRead, set);
2335 key = keyptr(page, page->cnt-1);
2336 memcpy (fencekey, key, key->len+1);
2338 bt_unlockpage (BtLockRead, set);
2340 if( bt_insertkey (bt, fencekey + 1, *fencekey, page_no, tod, lvl + 1) )
2343 // lock our page for writing
2345 bt_lockpage (BtLockRead, set);
2347 // switch old parent key from us to our oldest foster child
2349 key = keyptr(page, page->cnt);
2350 memcpy (fencekey, key, key->len+1);
2352 new_page = bt_getid (slotptr(page, page->cnt)->id);
2353 bt_unlockpage (BtLockRead, set);
2355 if( bt_insertkey (bt, fencekey + 1, *fencekey, new_page, tod, lvl + 1) )
2358 // now that it has its own parent pointer,
2359 // remove oldest foster child from our page
2361 bt_lockpage (BtLockWrite, set);
2362 memset (slotptr(page, page->cnt), 0, sizeof(BtSlot));
2368 bt_unlockpage (BtLockParent, set);
2370 // if this emptied page,
2371 // undo the foster child
2374 if( bt_mergeleft (bt, page, pool, set, page_no, lvl) )
2379 bt_unlockpage (BtLockWrite, set);
2380 bt_unpinlatch (set);
2381 bt_unpinpool (pool);
2385 // Insert new key into the btree at leaf level.
2387 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod, uint lvl)
2394 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
2395 ptr = keyptr(bt->page, slot);
2399 bt->err = BTERR_ovflw;
2403 // if key already exists, update id and return
2407 if( !keycmp (ptr, key, len) ) {
2408 if( slotptr(page, slot)->dead )
2410 slotptr(page, slot)->dead = 0;
2411 slotptr(page, slot)->tod = tod;
2412 bt_putid(slotptr(page,slot)->id, id);
2413 bt_unlockpage(BtLockWrite, bt->set);
2414 bt_unpinlatch (bt->set);
2415 bt_unpinpool (bt->pool);
2419 // check if page has enough space
2421 if( slot = bt_cleanpage (bt, bt->page, len, slot) )
2424 if( bt_splitpage (bt, bt->page, bt->pool, bt->set, bt->page_no) )
2428 bt_addkeytopage (bt, bt->page, slot, key, len, id, tod);
2430 bt_unlockpage (BtLockWrite, bt->set);
2431 bt_unpinlatch (bt->set);
2432 bt_unpinpool (bt->pool);
2436 // cache page of keys into cursor and return starting slot for given key
2438 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2442 // cache page for retrieval
2443 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
2444 memcpy (bt->cursor, bt->page, bt->mgr->page_size);
2446 bt->cursor_page = bt->page_no;
2448 bt_unlockpage(BtLockRead, bt->set);
2449 bt_unpinlatch (bt->set);
2450 bt_unpinpool (bt->pool);
2454 // return next slot for cursor page
2455 // or slide cursor right into next page
2457 uint bt_nextkey (BtDb *bt, uint slot)
2465 right = bt_getid(bt->cursor->right);
2466 while( slot++ < bt->cursor->cnt - bt->cursor->foster )
2467 if( slotptr(bt->cursor,slot)->dead )
2469 else if( right || (slot < bt->cursor->cnt - bt->cursor->foster) )
2477 bt->cursor_page = right;
2478 if( pool = bt_pinpool (bt, right) )
2479 page = bt_page (bt, pool, right);
2483 set = bt_pinlatch (bt, right);
2484 bt_lockpage(BtLockRead, set);
2486 memcpy (bt->cursor, page, bt->mgr->page_size);
2488 bt_unlockpage(BtLockRead, set);
2489 bt_unpinlatch (set);
2490 bt_unpinpool (pool);
2497 BtKey bt_key(BtDb *bt, uint slot)
2499 return keyptr(bt->cursor, slot);
2502 uid bt_uid(BtDb *bt, uint slot)
2504 return bt_getid(slotptr(bt->cursor,slot)->id);
2507 uint bt_tod(BtDb *bt, uint slot)
2509 return slotptr(bt->cursor,slot)->tod;
2522 // standalone program to index file of keys
2523 // then list them onto std-out
2526 void *index_file (void *arg)
2528 uint __stdcall index_file (void *arg)
2531 int line = 0, found = 0, cnt = 0;
2532 uid next, page_no = LEAF_page; // start on first page of leaves
2533 unsigned char key[256];
2534 ThreadArg *args = arg;
2535 int ch, len = 0, slot;
2544 bt = bt_open (args->mgr);
2547 switch(args->type | 0x20)
2550 fprintf(stderr, "started indexing for %s\n", args->infile);
2551 if( in = fopen (args->infile, "rb") )
2552 while( ch = getc(in), ch != EOF )
2557 if( args->num == 1 )
2558 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2560 else if( args->num )
2561 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2563 if( bt_insertkey (bt, key, len, line, *tod, 0) )
2564 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2567 else if( len < 255 )
2569 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
2573 fprintf(stderr, "started deleting keys for %s\n", args->infile);
2574 if( in = fopen (args->infile, "rb") )
2575 while( ch = getc(in), ch != EOF )
2579 if( args->num == 1 )
2580 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2582 else if( args->num )
2583 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2585 if( bt_deletekey (bt, key, len) )
2586 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2589 else if( len < 255 )
2591 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2595 fprintf(stderr, "started finding keys for %s\n", args->infile);
2596 if( in = fopen (args->infile, "rb") )
2597 while( ch = getc(in), ch != EOF )
2601 if( args->num == 1 )
2602 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2604 else if( args->num )
2605 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2607 if( bt_findkey (bt, key, len) )
2610 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2613 else if( len < 255 )
2615 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2621 fprintf(stderr, "started reading\n");
2623 if( slot = bt_startkey (bt, key, len) )
2626 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
2628 while( slot = bt_nextkey (bt, slot) ) {
2629 ptr = bt_key(bt, slot);
2630 fwrite (ptr->key, ptr->len, 1, stdout);
2631 fputc ('\n', stdout);
2637 fprintf(stderr, "started reading\n");
2640 if( pool = bt_pinpool (bt, page_no) )
2641 page = bt_page (bt, pool, page_no);
2644 set = bt_pinlatch (bt, page_no);
2645 bt_lockpage (BtLockRead, set);
2647 next = bt_getid (page->right);
2648 bt_unlockpage (BtLockRead, set);
2649 bt_unpinlatch (set);
2650 bt_unpinpool (pool);
2651 } while( page_no = next );
2653 cnt--; // remove stopper key
2654 fprintf(stderr, " Total keys read %d\n", cnt);
2666 typedef struct timeval timer;
2668 int main (int argc, char **argv)
2670 int idx, cnt, len, slot, err;
2671 int segsize, bits = 16;
2676 time_t start[1], stop[1];
2689 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]);
2690 fprintf (stderr, " where page_bits is the page size in bits\n");
2691 fprintf (stderr, " mapped_segments is the number of mmap segments in buffer pool\n");
2692 fprintf (stderr, " seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2693 fprintf (stderr, " line_numbers = 1 to append line numbers to keys\n");
2694 fprintf (stderr, " src_file1 thru src_filen are files of keys separated by newline\n");
2699 gettimeofday(&start, NULL);
2705 bits = atoi(argv[3]);
2708 poolsize = atoi(argv[4]);
2711 fprintf (stderr, "Warning: no mapped_pool\n");
2713 if( poolsize > 65535 )
2714 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2717 segsize = atoi(argv[5]);
2719 segsize = 4; // 16 pages per mmap segment
2722 num = atoi(argv[6]);
2726 threads = malloc (cnt * sizeof(pthread_t));
2728 threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2730 args = malloc (cnt * sizeof(ThreadArg));
2732 mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2735 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2741 for( idx = 0; idx < cnt; idx++ ) {
2742 args[idx].infile = argv[idx + 7];
2743 args[idx].type = argv[2][0];
2744 args[idx].mgr = mgr;
2745 args[idx].num = num;
2746 args[idx].idx = idx;
2748 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2749 fprintf(stderr, "Error creating thread %d\n", err);
2751 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2755 // wait for termination
2758 for( idx = 0; idx < cnt; idx++ )
2759 pthread_join (threads[idx], NULL);
2760 gettimeofday(&stop, NULL);
2761 real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2763 WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2765 for( idx = 0; idx < cnt; idx++ )
2766 CloseHandle(threads[idx]);
2769 real_time = 1000 * (*stop - *start);
2771 fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);