1 // foster btree version e
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 // it 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 uint cnt; // count of keys in page
125 uint act; // count of active keys
126 uint min; // next key offset
127 uint foster; // count of foster children
128 unsigned char bits; // page size in bits
129 unsigned char lvl:6; // level of page
130 unsigned char kill:1; // page is being deleted
131 unsigned char dirty:1; // page needs to be cleaned
132 unsigned char right[BtId]; // page number to right
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 table lock structure
163 // implements a fair read-write lock
167 pthread_rwlock_t lock[1];
174 BtLatch readwr[1]; // read/write page lock
175 BtLatch access[1]; // Access Intent/Page delete
176 BtLatch parent[1]; // adoption of foster children
177 BtSpinLatch busy[1]; // slot is being moved between chains
178 volatile ushort next; // next entry in hash table chain
179 volatile ushort prev; // prev entry in hash table chain
180 volatile ushort pin; // number of outstanding locks
181 volatile ushort hash; // hash slot entry is under
182 volatile uid page_no; // latch set page number
185 // The memory mapping pool table buffer manager entry
188 unsigned long long int lru; // number of times accessed
189 uid basepage; // mapped base page number
190 char *map; // mapped memory pointer
191 ushort pin; // mapped page pin counter
192 ushort slot; // slot index in this array
193 void *hashprev; // previous pool entry for the same hash idx
194 void *hashnext; // next pool entry for the same hash idx
196 HANDLE hmap; // Windows memory mapping handle
200 // structure for latch manager on ALLOC_page
203 struct Page alloc[2]; // next & free page_nos in right ptr
204 BtSpinLatch lock[1]; // allocation area lite latch
205 ushort latchdeployed; // highest number of latch entries deployed
206 ushort nlatchpage; // number of latch pages at BT_latch
207 ushort latchtotal; // number of page latch entries
208 ushort latchhash; // number of latch hash table slots
209 ushort latchvictim; // next latch entry to examine
210 BtHashEntry table[0]; // the hash table
213 // The object structure for Btree access
216 uint page_size; // page size
217 uint page_bits; // page size in bits
218 uint seg_bits; // seg size in pages in bits
219 uint mode; // read-write mode
222 char *pooladvise; // bit maps for pool page advisements
226 ushort poolcnt; // highest page pool node in use
227 ushort poolmax; // highest page pool node allocated
228 ushort poolmask; // total size of pages in mmap segment - 1
229 ushort hashsize; // size of Hash Table for pool entries
230 ushort evicted; // last evicted hash table slot
231 ushort *hash; // hash table of pool entries
232 BtPool *pool; // memory pool page segments
233 BtSpinLatch *latch; // latches for pool hash slots
234 BtLatchMgr *latchmgr; // mapped latch page from allocation page
235 BtLatchSet *latchset; // first mapped latch set from latch pages
237 HANDLE halloc, hlatch; // allocation and latch table handles
242 BtMgr *mgr; // buffer manager for thread
243 BtPage temp; // temporary frame buffer (memory mapped/file IO)
244 BtPage cursor; // cached frame for start/next (never mapped)
245 BtPage frame; // spare frame for the page split (never mapped)
246 BtPage zero; // page frame for zeroes at end of file
247 BtPage page; // current page
248 uid page_no; // current page number
249 uid cursor_page; // current cursor page number
250 unsigned char *mem; // frame, cursor, page memory buffer
251 int err; // last error
266 extern void bt_close (BtDb *bt);
267 extern BtDb *bt_open (BtMgr *mgr);
268 extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod);
269 extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl);
270 extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
271 extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
272 extern uint bt_nextkey (BtDb *bt, uint slot);
275 extern BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolsize, uint segsize, uint hashsize);
276 void bt_mgrclose (BtMgr *mgr);
278 // Helper functions to return cursor slot values
280 extern BtKey bt_key (BtDb *bt, uint slot);
281 extern uid bt_uid (BtDb *bt, uint slot);
282 extern uint bt_tod (BtDb *bt, uint slot);
284 // BTree page number constants
285 #define ALLOC_page 0 // allocation & lock manager hash table
286 #define ROOT_page 1 // root of the btree
287 #define LEAF_page 2 // first page of leaves
288 #define LATCH_page 3 // pages for lock manager
290 // Number of levels to create in a new BTree
294 // The page is allocated from low and hi ends.
295 // The key offsets and row-id's are allocated
296 // from the bottom, while the text of the key
297 // is allocated from the top. When the two
298 // areas meet, the page is split into two.
300 // A key consists of a length byte, two bytes of
301 // index number (0 - 65534), and up to 253 bytes
302 // of key value. Duplicate keys are discarded.
303 // Associated with each key is a 48 bit row-id.
305 // The b-tree root is always located at page 1.
306 // The first leaf page of level zero is always
307 // located on page 2.
309 // When to root page fills, it is split in two and
310 // the tree height is raised by a new root at page
311 // one with two keys.
313 // Deleted keys are marked with a dead bit until
314 // page cleanup The fence key for a node is always
315 // present, even after deletion and cleanup.
317 // Groups of pages called segments from the btree are
318 // cached with memory mapping. A hash table is used to keep
319 // track of the cached segments. This behaviour is controlled
320 // by the cache block size parameter to bt_open.
322 // To achieve maximum concurrency one page is locked at a time
323 // as the tree is traversed to find leaf key in question.
325 // An adoption traversal leaves the parent node locked as the
326 // tree is traversed to the level in quesiton.
328 // Page 0 is dedicated to lock for new page extensions,
329 // and chains empty pages together for reuse.
331 // Empty pages are chained together through the ALLOC page and reused.
333 // Access macros to address slot and key values from the page
335 #define slotptr(page, slot) (((BtSlot *)(page+1)) + (slot-1))
336 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
338 void bt_putid(unsigned char *dest, uid id)
343 dest[i] = (unsigned char)id, id >>= 8;
346 uid bt_getid(unsigned char *src)
351 for( i = 0; i < BtId; i++ )
352 id <<= 8, id |= *src++;
357 // wait until write lock mode is clear
358 // and add 1 to the share count
360 void bt_spinreadlock(BtSpinLatch *latch)
366 do prev = __sync_fetch_and_or((ushort *)latch, Mutex);
367 while( prev & Mutex );
369 do prev = _InterlockedOr16((ushort *)latch, Mutex);
370 while( prev & Mutex );
373 // see if exclusive request is pending, or granted
375 if( prev = !(latch->exclusive | latch->pending) )
383 } while( sched_yield(), 1 );
385 } while( SwitchToThread(), 1 );
389 // wait for other read and write latches to relinquish
391 void bt_spinwritelock(BtSpinLatch *latch)
397 do prev = __sync_fetch_and_or((ushort *)latch, (Pending | Mutex));
398 while( prev & Mutex );
400 do prev = _InterlockedOr16((ushort *)latch, (Pending | Mutex));
401 while( prev & Mutex );
403 if( prev = !(latch->share | latch->exclusive) )
404 latch->exclusive = 1, latch->pending = 0;
418 // try to obtain write lock
420 // return 1 if obtained,
423 int bt_spinwritetry(BtSpinLatch *latch)
428 do prev = __sync_fetch_and_or((ushort *)latch, Mutex);
429 while( prev & Mutex );
431 do prev = _InterlockedOr16((ushort *)latch, Mutex);
432 while( prev & Mutex );
434 // take write access if all bits are clear
437 latch->exclusive = 1;
445 void bt_spinreleasewrite(BtSpinLatch *latch)
450 do prev = __sync_fetch_and_or((ushort *)latch, Mutex);
451 while( prev & Mutex );
453 do prev = _InterlockedOr16((ushort *)latch, Mutex);
454 while( prev & Mutex );
457 latch->exclusive = 0;
461 // decrement reader count
463 void bt_spinreleaseread(BtSpinLatch *latch)
468 do prev = __sync_fetch_and_or((ushort *)latch, Mutex);
469 while( prev & Mutex );
471 do prev = _InterlockedOr16((ushort *)latch, Mutex);
472 while( prev & Mutex );
479 void bt_initlockset (BtLatchSet *set)
482 pthread_rwlockattr_t rwattr[1];
484 pthread_rwlockattr_init (rwattr);
485 pthread_rwlockattr_setkind_np (rwattr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
486 pthread_rwlockattr_setpshared (rwattr, PTHREAD_PROCESS_SHARED);
488 pthread_rwlock_init (set->readwr->lock, rwattr);
489 pthread_rwlock_init (set->access->lock, rwattr);
490 pthread_rwlock_init (set->parent->lock, rwattr);
491 pthread_rwlockattr_destroy (rwattr);
493 InitializeSRWLock (set->readwr->srw);
494 InitializeSRWLock (set->access->srw);
495 InitializeSRWLock (set->parent->srw);
499 // link latch table entry into latch hash table
501 void bt_latchlink (BtDb *bt, ushort hashidx, ushort victim, uid page_no)
503 BtLatchSet *set = bt->mgr->latchset + victim;
505 if( set->next = bt->mgr->latchmgr->table[hashidx].slot )
506 bt->mgr->latchset[set->next].prev = victim;
508 bt->mgr->latchmgr->table[hashidx].slot = victim;
509 set->page_no = page_no;
514 // find existing latchset or inspire new one
515 // return with latchset pinned
517 BtLatchSet *bt_bindlatch (BtDb *bt, uid page_no, int incr)
519 ushort hashidx = page_no % bt->mgr->latchmgr->latchhash;
520 ushort slot, avail = 0, victim, idx;
523 // obtain read lock on hash table entry
525 bt_spinreadlock(bt->mgr->latchmgr->table[hashidx].latch);
527 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
529 set = bt->mgr->latchset + slot;
530 if( page_no == set->page_no )
532 } while( slot = set->next );
536 __sync_fetch_and_add(&set->pin, 1);
538 _InterlockedIncrement16 (&set->pin);
542 bt_spinreleaseread (bt->mgr->latchmgr->table[hashidx].latch);
547 // try again, this time with write lock
549 bt_spinwritelock(bt->mgr->latchmgr->table[hashidx].latch);
551 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
553 set = bt->mgr->latchset + slot;
554 if( page_no == set->page_no )
556 if( !set->pin && !avail )
558 } while( slot = set->next );
560 // found our entry, or take over an unpinned one
562 if( slot || (slot = avail) ) {
563 set = bt->mgr->latchset + slot;
566 __sync_fetch_and_add(&set->pin, 1);
568 _InterlockedIncrement16 (&set->pin);
570 set->page_no = page_no;
571 bt_spinreleasewrite(bt->mgr->latchmgr->table[hashidx].latch);
575 // see if there are any unused entries
577 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, 1) + 1;
579 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchdeployed);
582 if( victim < bt->mgr->latchmgr->latchtotal ) {
583 set = bt->mgr->latchset + victim;
586 __sync_fetch_and_add(&set->pin, 1);
588 _InterlockedIncrement16 (&set->pin);
590 bt_initlockset (set);
591 bt_latchlink (bt, hashidx, victim, page_no);
592 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
597 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, -1);
599 victim = _InterlockedDecrement16 (&bt->mgr->latchmgr->latchdeployed);
601 // find and reuse previous lock entry
605 victim = __sync_fetch_and_add(&bt->mgr->latchmgr->latchvictim, 1);
607 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchvictim) - 1;
609 // we don't use slot zero
611 if( victim %= bt->mgr->latchmgr->latchtotal )
612 set = bt->mgr->latchset + victim;
616 // take control of our slot
617 // from other threads
619 if( set->pin || !bt_spinwritetry (set->busy) )
624 // try to get write lock on hash chain
625 // skip entry if not obtained
626 // or has outstanding locks
628 if( !bt_spinwritetry (bt->mgr->latchmgr->table[idx].latch) ) {
629 bt_spinreleasewrite (set->busy);
634 bt_spinreleasewrite (set->busy);
635 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
639 // unlink our available victim from its hash chain
642 bt->mgr->latchset[set->prev].next = set->next;
644 bt->mgr->latchmgr->table[idx].slot = set->next;
647 bt->mgr->latchset[set->next].prev = set->prev;
649 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
653 __sync_fetch_and_add(&set->pin, 1);
655 _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);
692 free (mgr->pooladvise);
695 FlushFileBuffers(mgr->idx);
696 CloseHandle(mgr->idx);
697 GlobalFree (mgr->pool);
698 GlobalFree (mgr->hash);
699 GlobalFree (mgr->latch);
704 // close and release memory
706 void bt_close (BtDb *bt)
713 VirtualFree (bt->mem, 0, MEM_RELEASE);
718 // open/create new btree buffer manager
720 // call with file_name, BT_openmode, bits in page size (e.g. 16),
721 // size of mapped page pool (e.g. 8192)
723 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
725 uint lvl, attr, cacheblk, last, slot, idx;
726 uint nlatchpage, latchhash;
727 BtLatchMgr *latchmgr;
736 SYSTEM_INFO sysinfo[1];
739 // determine sanity of page size and buffer pool
741 if( bits > BT_maxbits )
743 else if( bits < BT_minbits )
747 return NULL; // must have buffer pool
750 mgr = calloc (1, sizeof(BtMgr));
752 switch (mode & 0x7fff)
755 mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
761 mgr->idx = open ((char*)name, O_RDONLY);
766 return free(mgr), NULL;
768 cacheblk = 4096; // minimum mmap segment size for unix
771 mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
772 attr = FILE_ATTRIBUTE_NORMAL;
773 switch (mode & 0x7fff)
776 mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
782 mgr->idx = CreateFile(name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, attr, NULL);
786 if( mgr->idx == INVALID_HANDLE_VALUE )
787 return GlobalFree(mgr), NULL;
789 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
790 GetSystemInfo(sysinfo);
791 cacheblk = sysinfo->dwAllocationGranularity;
795 latchmgr = malloc (BT_maxpage);
798 // read minimum page size to get root info
800 if( size = lseek (mgr->idx, 0L, 2) ) {
801 if( pread(mgr->idx, latchmgr, BT_minpage, 0) == BT_minpage )
802 bits = latchmgr->alloc->bits;
804 return free(mgr), free(latchmgr), NULL;
805 } else if( mode == BT_ro )
806 return bt_mgrclose (mgr), NULL;
808 latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
809 size = GetFileSize(mgr->idx, amt);
812 if( !ReadFile(mgr->idx, (char *)latchmgr, BT_minpage, amt, NULL) )
813 return bt_mgrclose (mgr), NULL;
814 bits = latchmgr->alloc->bits;
815 } else if( mode == BT_ro )
816 return bt_mgrclose (mgr), NULL;
819 mgr->page_size = 1 << bits;
820 mgr->page_bits = bits;
822 mgr->poolmax = poolmax;
825 if( cacheblk < mgr->page_size )
826 cacheblk = mgr->page_size;
828 // mask for partial memmaps
830 mgr->poolmask = (cacheblk >> bits) - 1;
832 // see if requested size of pages per memmap is greater
834 if( (1 << segsize) > mgr->poolmask )
835 mgr->poolmask = (1 << segsize) - 1;
839 while( (1 << mgr->seg_bits) <= mgr->poolmask )
842 mgr->hashsize = hashsize;
845 mgr->pool = calloc (poolmax, sizeof(BtPool));
846 mgr->hash = calloc (hashsize, sizeof(ushort));
847 mgr->latch = calloc (hashsize, sizeof(BtSpinLatch));
848 mgr->pooladvise = calloc (poolmax, (mgr->poolmask + 8) / 8);
850 mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * sizeof(BtPool));
851 mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
852 mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtSpinLatch));
858 // initialize an empty b-tree with latch page, root page, page of leaves
859 // and page(s) of latches
861 memset (latchmgr, 0, 1 << bits);
862 nlatchpage = BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1;
863 bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
864 latchmgr->alloc->bits = mgr->page_bits;
866 latchmgr->nlatchpage = nlatchpage;
867 latchmgr->latchtotal = nlatchpage * (mgr->page_size / sizeof(BtLatchSet));
869 // initialize latch manager
871 latchhash = (mgr->page_size - sizeof(BtLatchMgr)) / sizeof(BtHashEntry);
873 // size of hash table = total number of latchsets
875 if( latchhash > latchmgr->latchtotal )
876 latchhash = latchmgr->latchtotal;
878 latchmgr->latchhash = latchhash;
881 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
882 return bt_mgrclose (mgr), NULL;
884 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
885 return bt_mgrclose (mgr), NULL;
887 if( *amt < mgr->page_size )
888 return bt_mgrclose (mgr), NULL;
891 memset (latchmgr, 0, 1 << bits);
892 latchmgr->alloc->bits = mgr->page_bits;
894 for( lvl=MIN_lvl; lvl--; ) {
895 slotptr(latchmgr->alloc, 1)->off = mgr->page_size - 3;
896 bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
897 key = keyptr(latchmgr->alloc, 1);
898 key->len = 2; // create stopper key
901 latchmgr->alloc->min = mgr->page_size - 3;
902 latchmgr->alloc->lvl = lvl;
903 latchmgr->alloc->cnt = 1;
904 latchmgr->alloc->act = 1;
906 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
907 return bt_mgrclose (mgr), NULL;
909 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
910 return bt_mgrclose (mgr), NULL;
912 if( *amt < mgr->page_size )
913 return bt_mgrclose (mgr), NULL;
917 // clear out latch manager locks
918 // and rest of pages to round out segment
920 memset(latchmgr, 0, mgr->page_size);
923 while( last <= ((MIN_lvl + 1 + nlatchpage) | mgr->poolmask) ) {
925 pwrite(mgr->idx, latchmgr, mgr->page_size, last << mgr->page_bits);
927 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
928 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
929 return bt_mgrclose (mgr), NULL;
930 if( *amt < mgr->page_size )
931 return bt_mgrclose (mgr), NULL;
938 flag = PROT_READ | ( mgr->mode == BT_ro ? 0 : PROT_WRITE );
939 mgr->latchmgr = mmap (0, mgr->page_size, flag, MAP_SHARED, mgr->idx, ALLOC_page * mgr->page_size);
940 if( mgr->latchmgr == MAP_FAILED )
941 return bt_mgrclose (mgr), NULL;
942 mgr->latchset = (BtLatchSet *)mmap (0, mgr->latchmgr->nlatchpage * mgr->page_size, flag, MAP_SHARED, mgr->idx, LATCH_page * mgr->page_size);
943 if( mgr->latchset == MAP_FAILED )
944 return bt_mgrclose (mgr), NULL;
946 flag = ( mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
947 mgr->halloc = CreateFileMapping(mgr->idx, NULL, flag, 0, mgr->page_size, NULL);
949 return bt_mgrclose (mgr), NULL;
951 flag = ( mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
952 mgr->latchmgr = MapViewOfFile(mgr->halloc, flag, 0, ALLOC_page * mgr->page_size, mgr->page_size);
954 return bt_mgrclose (mgr), NULL;
955 flag = ( mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
956 mgr->hlatch = CreateFileMapping(mgr->idx, NULL, flag, 0, (mgr->latchmgr->nlatchpage + LATCH_page) * mgr->page_size, NULL);
958 return bt_mgrclose (mgr), NULL;
960 flag = ( mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
961 mgr->latchset = MapViewOfFile(mgr->halloc, flag, 0, LATCH_page * mgr->page_size, mgr->page_size * mgr->latchmgr->nlatchpage);
963 return bt_mgrclose (mgr), NULL;
969 VirtualFree (latchmgr, 0, MEM_RELEASE);
974 // open BTree access method
975 // based on buffer manager
977 BtDb *bt_open (BtMgr *mgr)
979 BtDb *bt = malloc (sizeof(*bt));
981 memset (bt, 0, sizeof(*bt));
984 bt->mem = malloc (3 *mgr->page_size);
986 bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
988 bt->frame = (BtPage)bt->mem;
989 bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
990 bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
994 // compare two keys, returning > 0, = 0, or < 0
995 // as the comparison value
997 int keycmp (BtKey key1, unsigned char *key2, uint len2)
999 uint len1 = key1->len;
1002 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
1015 void bt_readlock(BtLatch *latch)
1018 pthread_rwlock_rdlock (latch->lock);
1020 AcquireSRWLockShared (latch->srw);
1024 // wait for other read and write latches to relinquish
1026 void bt_writelock(BtLatch *latch)
1029 pthread_rwlock_wrlock (latch->lock);
1031 AcquireSRWLockExclusive (latch->srw);
1035 // try to obtain write lock
1037 // return 1 if obtained,
1038 // 0 if already write or read locked
1040 int bt_writetry(BtLatch *latch)
1045 result = !pthread_rwlock_trywrlock (latch->lock);
1047 result = TryAcquireSRWLockExclusive (latch->srw);
1054 void bt_releasewrite(BtLatch *latch)
1057 pthread_rwlock_unlock (latch->lock);
1059 ReleaseSRWLockExclusive (latch->srw);
1063 // decrement reader count
1065 void bt_releaseread(BtLatch *latch)
1068 pthread_rwlock_unlock (latch->lock);
1070 ReleaseSRWLockShared (latch->srw);
1076 // find segment in pool
1077 // must be called with hashslot idx locked
1078 // return NULL if not there
1079 // otherwise return node
1081 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
1086 // compute start of hash chain in pool
1088 if( slot = bt->mgr->hash[idx] )
1089 pool = bt->mgr->pool + slot;
1093 page_no &= ~bt->mgr->poolmask;
1095 while( pool->basepage != page_no )
1096 if( pool = pool->hashnext )
1104 // add segment to hash table
1106 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
1111 pool->hashprev = pool->hashnext = NULL;
1112 pool->basepage = page_no & ~bt->mgr->poolmask;
1115 if( slot = bt->mgr->hash[idx] ) {
1116 node = bt->mgr->pool + slot;
1117 pool->hashnext = node;
1118 node->hashprev = pool;
1121 bt->mgr->hash[idx] = pool->slot;
1124 // find best segment to evict from buffer pool
1126 BtPool *bt_findlru (BtDb *bt, uint hashslot)
1128 unsigned long long int target = ~0LL;
1129 BtPool *pool = NULL, *node;
1134 node = bt->mgr->pool + hashslot;
1136 // scan pool entries under hash table slot
1141 if( node->lru > target )
1145 } while( node = node->hashnext );
1150 // map new buffer pool segment to virtual memory
1152 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
1154 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
1155 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
1159 flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
1160 pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED, bt->mgr->idx, off);
1161 if( pool->map == MAP_FAILED )
1162 return bt->err = BTERR_map;
1163 // clear out madvise issued bits
1164 memset (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8) / 8), 0, (bt->mgr->poolmask + 8)/8);
1166 flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
1167 pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
1169 return bt->err = BTERR_map;
1171 flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
1172 pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1174 return bt->err = BTERR_map;
1179 // find or place requested page in segment-pool
1180 // return pool table entry, incrementing pin
1182 BtPool *bt_pinpage(BtDb *bt, uid page_no)
1184 BtPool *pool, *node, *next;
1185 uint slot, idx, victim;
1188 // lock hash table chain
1190 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1191 bt_spinreadlock (&bt->mgr->latch[idx]);
1193 // look up in hash table
1195 if( pool = bt_findpool(bt, page_no, idx) ) {
1197 __sync_fetch_and_add(&pool->pin, 1);
1199 _InterlockedIncrement16 (&pool->pin);
1201 bt_spinreleaseread (&bt->mgr->latch[idx]);
1206 // upgrade to write lock
1208 bt_spinreleaseread (&bt->mgr->latch[idx]);
1209 bt_spinwritelock (&bt->mgr->latch[idx]);
1211 // try to find page in pool with write lock
1213 if( pool = bt_findpool(bt, page_no, idx) ) {
1215 __sync_fetch_and_add(&pool->pin, 1);
1217 _InterlockedIncrement16 (&pool->pin);
1219 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1224 // allocate a new pool node
1225 // and add to hash table
1228 slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
1230 slot = _InterlockedIncrement16 (&bt->mgr->poolcnt) - 1;
1233 if( ++slot < bt->mgr->poolmax ) {
1234 pool = bt->mgr->pool + slot;
1237 if( bt_mapsegment(bt, pool, page_no) )
1240 bt_linkhash(bt, pool, page_no, idx);
1242 __sync_fetch_and_add(&pool->pin, 1);
1244 _InterlockedIncrement16 (&pool->pin);
1246 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1250 // pool table is full
1251 // find best pool entry to evict
1254 __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
1256 _InterlockedDecrement16 (&bt->mgr->poolcnt);
1261 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
1263 victim = _InterlockedIncrement16 (&bt->mgr->evicted) - 1;
1265 victim %= bt->mgr->hashsize;
1267 // try to get write lock
1268 // skip entry if not obtained
1270 if( !bt_spinwritetry (&bt->mgr->latch[victim]) )
1273 // if cache entry is empty
1274 // or no slots are unpinned
1277 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
1278 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1282 // unlink victim pool node from hash table
1284 if( node = pool->hashprev )
1285 node->hashnext = pool->hashnext;
1286 else if( node = pool->hashnext )
1287 bt->mgr->hash[victim] = node->slot;
1289 bt->mgr->hash[victim] = 0;
1291 if( node = pool->hashnext )
1292 node->hashprev = pool->hashprev;
1294 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1296 // remove old file mapping
1298 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1300 FlushViewOfFile(pool->map, 0);
1301 UnmapViewOfFile(pool->map);
1302 CloseHandle(pool->hmap);
1306 // create new pool mapping
1307 // and link into hash table
1309 if( bt_mapsegment(bt, pool, page_no) )
1312 bt_linkhash(bt, pool, page_no, idx);
1314 __sync_fetch_and_add(&pool->pin, 1);
1316 _InterlockedIncrement16 (&pool->pin);
1318 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1323 // place write, read, or parent lock on requested page_no.
1324 // pin to buffer pool and return page pointer
1326 BTERR bt_lockpage(BtDb *bt, uid page_no, BtLock mode, BtPage *pageptr)
1333 // find/create maping in pool table
1334 // and pin our pool slot
1336 if( pool = bt_pinpage(bt, page_no) )
1337 subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1341 if( !(set = bt_bindlatch (bt, page_no, 1)) )
1344 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1348 uint idx = subpage / 8;
1349 uint bit = subpage % 8;
1351 if( mode == BtLockRead || mode == BtLockWrite )
1352 if( ~((bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] >> bit) & 1 ) {
1353 madvise (page, bt->mgr->page_size, MADV_WILLNEED);
1354 (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] |= 1 << bit;
1361 bt_readlock (set->readwr);
1364 bt_writelock (set->readwr);
1367 bt_readlock (set->access);
1370 bt_writelock (set->access);
1373 bt_writelock (set->parent);
1376 return bt->err = BTERR_lock;
1385 // remove write, read, or parent lock on requested page_no.
1387 BTERR bt_unlockpage(BtDb *bt, uid page_no, BtLock mode)
1393 // since page is pinned
1394 // it should still be in the buffer pool
1395 // and is in no danger of being a victim for reuse
1397 if( !(set = bt_bindlatch (bt, page_no, 0)) )
1398 return bt->err = BTERR_latch;
1400 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1401 bt_spinreadlock (&bt->mgr->latch[idx]);
1403 if( !(pool = bt_findpool(bt, page_no, idx)) )
1404 return bt->err = BTERR_hash;
1406 bt_spinreleaseread (&bt->mgr->latch[idx]);
1410 bt_releaseread (set->readwr);
1413 bt_releasewrite (set->readwr);
1416 bt_releaseread (set->access);
1419 bt_releasewrite (set->access);
1422 bt_releasewrite (set->parent);
1425 return bt->err = BTERR_lock;
1429 __sync_fetch_and_add(&pool->pin, -1);
1430 __sync_fetch_and_add (&set->pin, -1);
1432 _InterlockedDecrement16 (&pool->pin);
1433 _InterlockedDecrement16 (&set->pin);
1438 // deallocate a deleted page
1439 // place on free chain out of allocator page
1440 // fence key must already be removed from parent
1442 BTERR bt_freepage(BtDb *bt, uid page_no)
1444 // obtain delete lock on deleted page
1446 if( bt_lockpage(bt, page_no, BtLockDelete, NULL) )
1449 // obtain write lock on deleted page
1451 if( bt_lockpage(bt, page_no, BtLockWrite, &bt->temp) )
1454 // lock allocation page
1456 bt_spinwritelock(bt->mgr->latchmgr->lock);
1458 // store free chain in allocation page second right
1459 bt_putid(bt->temp->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1460 bt_putid(bt->mgr->latchmgr->alloc[1].right, page_no);
1464 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1466 // remove write lock on deleted node
1468 if( bt_unlockpage(bt, page_no, BtLockWrite) )
1471 // remove delete lock on deleted node
1473 if( bt_unlockpage(bt, page_no, BtLockDelete) )
1479 // allocate a new page and write page into it
1481 uid bt_newpage(BtDb *bt, BtPage page)
1487 // lock allocation page
1489 bt_spinwritelock(bt->mgr->latchmgr->lock);
1491 // use empty chain first
1492 // else allocate empty page
1494 if( new_page = bt_getid(bt->mgr->latchmgr->alloc[1].right) ) {
1495 if( bt_lockpage (bt, new_page, BtLockWrite, &bt->temp) )
1497 bt_putid(bt->mgr->latchmgr->alloc[1].right, bt_getid(bt->temp->right));
1498 if( bt_unlockpage (bt, new_page, BtLockWrite) )
1502 new_page = bt_getid(bt->mgr->latchmgr->alloc->right);
1503 bt_putid(bt->mgr->latchmgr->alloc->right, new_page+1);
1507 if ( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1508 return bt->err = BTERR_wrt, 0;
1510 // if writing first page of pool block, zero last page in the block
1512 if ( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1514 // use zero buffer to write zeros
1515 memset(bt->zero, 0, bt->mgr->page_size);
1516 if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1517 return bt->err = BTERR_wrt, 0;
1520 // bring new page into pool and copy page.
1521 // this will extend the file into the new pages.
1523 if( bt_lockpage(bt, new_page, BtLockWrite, &pmap) )
1526 memcpy(pmap, page, bt->mgr->page_size);
1528 if( bt_unlockpage (bt, new_page, BtLockWrite) )
1531 // unlock allocation latch and return new page no
1533 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1537 // find slot in page for given key at a given level
1539 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1541 uint diff, higher = bt->page->cnt, low = 1, slot;
1543 // low is the lowest candidate, higher is already
1544 // tested as .ge. the given key, loop ends when they meet
1546 while( diff = higher - low ) {
1547 slot = low + ( diff >> 1 );
1548 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1557 // find and load page at given level for given key
1558 // leave page rd or wr locked as requested
1560 int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, uint lock)
1562 uid page_no = ROOT_page, prevpage = 0;
1563 uint drill = 0xff, slot;
1564 uint mode, prevmode;
1566 // start at root of btree and drill down
1569 // determine lock mode of drill level
1570 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1572 bt->page_no = page_no;
1574 // obtain access lock using lock chaining with Access mode
1576 if( page_no > ROOT_page )
1577 if( bt_lockpage(bt, page_no, BtLockAccess, NULL) )
1580 // now unlock our (possibly foster) parent
1583 if( bt_unlockpage(bt, prevpage, prevmode) )
1588 // obtain read lock using lock chaining
1589 // and pin page contents
1591 if( bt_lockpage(bt, page_no, mode, &bt->page) )
1594 if( page_no > ROOT_page )
1595 if( bt_unlockpage(bt, page_no, BtLockAccess) )
1598 // re-read and re-lock root after determining actual level of root
1600 if( bt->page_no == ROOT_page )
1601 if( bt->page->lvl != drill) {
1602 drill = bt->page->lvl;
1604 if( lock == BtLockWrite && drill == lvl )
1605 if( bt_unlockpage(bt, page_no, mode) )
1611 prevpage = bt->page_no;
1614 // if page is being deleted,
1615 // move back to preceeding page
1617 if( bt->page->kill ) {
1618 page_no = bt_getid (bt->page->right);
1622 // find key on page at this level
1623 // and descend to requested level
1625 slot = bt_findslot (bt, key, len);
1627 // is this slot a foster child?
1629 if( slot <= bt->page->cnt - bt->page->foster )
1633 while( slotptr(bt->page, slot)->dead )
1634 if( slot++ < bt->page->cnt )
1639 if( slot <= bt->page->cnt - bt->page->foster )
1642 // continue down / right using overlapping locks
1643 // to protect pages being killed or split.
1645 page_no = bt_getid(slotptr(bt->page, slot)->id);
1649 page_no = bt_getid(bt->page->right);
1653 // return error on end of chain
1655 bt->err = BTERR_struct;
1656 return 0; // return error
1659 // find and delete key on page by marking delete flag bit
1660 // when page becomes empty, delete it from the btree
1662 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl)
1664 unsigned char leftkey[256], rightkey[256];
1669 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1670 ptr = keyptr(bt->page, slot);
1674 // if key is found delete it, otherwise ignore request
1676 if( !keycmp (ptr, key, len) )
1677 if( slotptr(bt->page, slot)->dead == 0 ) {
1678 slotptr(bt->page,slot)->dead = 1;
1679 if( slot < bt->page->cnt )
1680 bt->page->dirty = 1;
1684 // return if page is not empty, or it has no right sibling
1686 right = bt_getid(bt->page->right);
1687 page_no = bt->page_no;
1689 if( !right || bt->page->act )
1690 return bt_unlockpage(bt, page_no, BtLockWrite);
1692 // obtain Parent lock over write lock
1694 if( bt_lockpage(bt, page_no, BtLockParent, NULL) )
1697 // cache copy of key to delete
1699 ptr = keyptr(bt->page, bt->page->cnt);
1700 memcpy(leftkey, ptr, ptr->len + 1);
1702 // lock and map right page
1704 if( bt_lockpage(bt, right, BtLockWrite, &bt->temp) )
1707 // pull contents of next page into current empty page
1708 memcpy (bt->page, bt->temp, bt->mgr->page_size);
1710 // cache copy of key to update
1711 ptr = keyptr(bt->temp, bt->temp->cnt);
1712 memcpy(rightkey, ptr, ptr->len + 1);
1714 // Mark right page as deleted and point it to left page
1715 // until we can post updates at higher level.
1717 bt_putid(bt->temp->right, page_no);
1721 if( bt_unlockpage(bt, right, BtLockWrite) )
1723 if( bt_unlockpage(bt, page_no, BtLockWrite) )
1726 // delete old lower key to consolidated node
1728 if( bt_deletekey (bt, leftkey + 1, *leftkey, lvl + 1) )
1731 // redirect higher key directly to consolidated node
1733 if( slot = bt_loadpage (bt, rightkey+1, *rightkey, lvl+1, BtLockWrite) )
1734 ptr = keyptr(bt->page, slot);
1738 // since key already exists, update id
1740 if( keycmp (ptr, rightkey+1, *rightkey) )
1741 return bt->err = BTERR_struct;
1743 slotptr(bt->page, slot)->dead = 0;
1744 bt_putid(slotptr(bt->page,slot)->id, page_no);
1746 if( bt_unlockpage(bt, bt->page_no, BtLockWrite) )
1749 // obtain write lock and
1750 // add right block to free chain
1752 if( bt_freepage (bt, right) )
1755 // remove ParentModify lock
1757 if( bt_unlockpage(bt, page_no, BtLockParent) )
1763 // find key in leaf level and return row-id
1765 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1771 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1772 ptr = keyptr(bt->page, slot);
1776 // if key exists, return row-id
1777 // otherwise return 0
1779 if( ptr->len == len && !memcmp (ptr->key, key, len) )
1780 id = bt_getid(slotptr(bt->page,slot)->id);
1784 if( bt_unlockpage (bt, bt->page_no, BtLockRead) )
1790 // check page for space available,
1791 // clean if necessary and return
1792 // 0 - page needs splitting
1795 uint bt_cleanpage(BtDb *bt, uint amt)
1797 uint nxt = bt->mgr->page_size;
1798 BtPage page = bt->page;
1799 uint cnt = 0, idx = 0;
1800 uint max = page->cnt;
1803 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1806 // skip cleanup if nothing to reclaim
1811 memcpy (bt->frame, page, bt->mgr->page_size);
1813 // skip page info and set rest of page to zero
1815 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1819 // try cleaning up page first
1821 while( cnt++ < max ) {
1822 // always leave fence key and foster children in list
1823 if( cnt < max - page->foster && slotptr(bt->frame,cnt)->dead )
1827 key = keyptr(bt->frame, cnt);
1828 nxt -= key->len + 1;
1829 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1832 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1833 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1835 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1836 slotptr(page, idx)->off = nxt;
1842 // see if page has enough space now, or does it need splitting?
1844 if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1850 // add key to current page
1851 // page must already be writelocked
1853 void bt_addkeytopage (BtDb *bt, uint slot, unsigned char *key, uint len, uid id, uint tod)
1855 BtPage page = bt->page;
1858 // calculate next available slot and copy key into page
1860 page->min -= len + 1;
1861 ((unsigned char *)page)[page->min] = len;
1862 memcpy ((unsigned char *)page + page->min +1, key, len );
1864 for( idx = slot; idx < page->cnt; idx++ )
1865 if( slotptr(page, idx)->dead )
1868 // now insert key into array before slot
1869 // preserving the fence slot
1871 if( idx == page->cnt )
1877 *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
1879 bt_putid(slotptr(page,slot)->id, id);
1880 slotptr(page, slot)->off = page->min;
1881 slotptr(page, slot)->tod = tod;
1882 slotptr(page, slot)->dead = 0;
1885 // split the root and raise the height of the btree
1886 // call with current page locked and page no of foster child
1887 // return with current page (root) unlocked
1889 BTERR bt_splitroot(BtDb *bt, uid right)
1891 uint nxt = bt->mgr->page_size;
1892 unsigned char fencekey[256];
1893 BtPage root = bt->page;
1897 // Obtain an empty page to use, and copy the left page
1898 // contents into it from the root. Strip foster child key.
1899 // (it's the stopper key)
1905 // Save left fence key.
1907 key = keyptr(root, root->cnt);
1908 memcpy (fencekey, key, key->len + 1);
1910 // copy the lower keys into a new left page
1912 if( !(new_page = bt_newpage(bt, root)) )
1915 // preserve the page info at the bottom
1916 // and set rest of the root to zero
1918 memset (root+1, 0, bt->mgr->page_size - sizeof(*root));
1920 // insert left fence key on empty newroot page
1922 nxt -= *fencekey + 1;
1923 memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
1924 bt_putid(slotptr(root, 1)->id, new_page);
1925 slotptr(root, 1)->off = nxt;
1927 // insert stopper key on newroot page
1928 // and increase the root height
1934 memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
1935 bt_putid(slotptr(root, 2)->id, right);
1936 slotptr(root, 2)->off = nxt;
1938 bt_putid(root->right, 0);
1939 root->min = nxt; // reset lowest used offset and key count
1944 // release root (bt->page)
1946 return bt_unlockpage(bt, ROOT_page, BtLockWrite);
1949 // split already locked full node
1950 // in current page variables
1953 BTERR bt_splitpage (BtDb *bt)
1955 uint slot, cnt, idx, max, nxt = bt->mgr->page_size;
1956 unsigned char fencekey[256];
1957 uid page_no = bt->page_no;
1958 BtPage page = bt->page;
1959 uint tod = time(NULL);
1960 uint lvl = page->lvl;
1961 uid new_page, right;
1964 // initialize frame buffer
1966 memset (bt->frame, 0, bt->mgr->page_size);
1967 max = page->cnt - page->foster;
1968 tod = (uint)time(NULL);
1972 // split higher half of keys to bt->frame
1973 // leaving foster children in the left node.
1975 while( cnt++ < max ) {
1976 key = keyptr(page, cnt);
1977 nxt -= key->len + 1;
1978 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
1979 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
1980 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
1981 slotptr(bt->frame, idx)->off = nxt;
1985 // transfer right link node
1987 if( page_no > ROOT_page ) {
1988 right = bt_getid (page->right);
1989 bt_putid(bt->frame->right, right);
1992 bt->frame->bits = bt->mgr->page_bits;
1993 bt->frame->min = nxt;
1994 bt->frame->cnt = idx;
1995 bt->frame->lvl = lvl;
1997 // get new free page and write frame to it.
1999 if( !(new_page = bt_newpage(bt, bt->frame)) )
2002 // remember fence key for new page to add
2005 key = keyptr(bt->frame, idx);
2006 memcpy (fencekey, key, key->len + 1);
2008 // update lower keys and foster children to continue in old page
2010 memcpy (bt->frame, page, bt->mgr->page_size);
2011 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
2012 nxt = bt->mgr->page_size;
2017 // assemble page of smaller keys
2018 // to remain in the old page
2020 while( cnt++ < max / 2 ) {
2021 key = keyptr(bt->frame, cnt);
2022 nxt -= key->len + 1;
2023 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2024 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
2025 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2026 slotptr(page, idx)->off = nxt;
2030 // insert new foster child at beginning of the current foster children
2032 nxt -= *fencekey + 1;
2033 memcpy ((unsigned char *)page + nxt, fencekey, *fencekey + 1);
2034 bt_putid (slotptr(page,++idx)->id, new_page);
2035 slotptr(page, idx)->tod = tod;
2036 slotptr(page, idx)->off = nxt;
2040 // continue with old foster child keys if any
2042 cnt = bt->frame->cnt - bt->frame->foster;
2044 while( cnt++ < bt->frame->cnt ) {
2045 key = keyptr(bt->frame, cnt);
2046 nxt -= key->len + 1;
2047 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2048 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
2049 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2050 slotptr(page, idx)->off = nxt;
2057 // link new right page
2059 bt_putid (page->right, new_page);
2061 // if current page is the root page, split it
2063 if( page_no == ROOT_page )
2064 return bt_splitroot (bt, new_page);
2066 // release wr lock on our page
2068 if( bt_unlockpage (bt, page_no, BtLockWrite) )
2071 // obtain ParentModification lock for current page
2072 // to fix fence key and highest foster child on page
2074 if( bt_lockpage (bt, page_no, BtLockParent, NULL) )
2077 // get our highest foster child key to find in parent node
2079 if( bt_lockpage (bt, page_no, BtLockRead, &page) )
2082 key = keyptr(page, page->cnt);
2083 memcpy (fencekey, key, key->len+1);
2085 if( bt_unlockpage (bt, page_no, BtLockRead) )
2088 // update our parent
2092 slot = bt_loadpage (bt, fencekey + 1, *fencekey, lvl + 1, BtLockWrite);
2097 // check if parent page has enough space for any possible key
2099 if( bt_cleanpage (bt, 256) )
2102 if( bt_splitpage (bt) )
2106 // see if we are still a foster child from another node
2108 if( bt_getid (slotptr(bt->page, slot)->id) != page_no ) {
2109 if( bt_unlockpage (bt, bt->page_no, BtLockWrite) )
2119 // wait until readers from parent get their locks
2122 if( bt_lockpage (bt, page_no, BtLockDelete, NULL) )
2125 // lock our page for writing
2127 if( bt_lockpage (bt, page_no, BtLockWrite, &page) )
2130 // switch parent fence key to foster child
2132 if( slotptr(page, page->cnt)->dead )
2133 slotptr(bt->page, slot)->dead = 1;
2135 bt_putid (slotptr(bt->page, slot)->id, bt_getid(slotptr(page, page->cnt)->id));
2137 // remove highest foster child from our page
2143 key = keyptr(page, page->cnt);
2145 // add our new fence key for foster child to our parent
2147 bt_addkeytopage (bt, slot, key->key, key->len, page_no, tod);
2149 if( bt_unlockpage (bt, bt->page_no, BtLockWrite) )
2152 if( bt_unlockpage (bt, page_no, BtLockDelete) )
2155 if( bt_unlockpage (bt, page_no, BtLockWrite) )
2158 return bt_unlockpage (bt, page_no, BtLockParent);
2161 // Insert new key into the btree at leaf level.
2163 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod)
2170 if( slot = bt_loadpage (bt, key, len, 0, BtLockWrite) )
2171 ptr = keyptr(bt->page, slot);
2175 bt->err = BTERR_ovflw;
2179 // if key already exists, update id and return
2183 if( !keycmp (ptr, key, len) ) {
2184 slotptr(page, slot)->dead = 0;
2185 slotptr(page, slot)->tod = tod;
2186 bt_putid(slotptr(page,slot)->id, id);
2187 return bt_unlockpage(bt, bt->page_no, BtLockWrite);
2190 // check if page has enough space
2192 if( bt_cleanpage (bt, len) )
2195 if( bt_splitpage (bt) )
2199 bt_addkeytopage (bt, slot, key, len, id, tod);
2201 return bt_unlockpage (bt, bt->page_no, BtLockWrite);
2204 // cache page of keys into cursor and return starting slot for given key
2206 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2210 // cache page for retrieval
2211 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
2212 memcpy (bt->cursor, bt->page, bt->mgr->page_size);
2213 bt->cursor_page = bt->page_no;
2214 if ( bt_unlockpage(bt, bt->page_no, BtLockRead) )
2220 // return next slot for cursor page
2221 // or slide cursor right into next page
2223 uint bt_nextkey (BtDb *bt, uint slot)
2229 right = bt_getid(bt->cursor->right);
2230 while( slot++ < bt->cursor->cnt - bt->cursor->foster )
2231 if( slotptr(bt->cursor,slot)->dead )
2233 else if( right || (slot < bt->cursor->cnt - bt->cursor->foster) )
2241 bt->cursor_page = right;
2243 if( bt_lockpage(bt, right, BtLockRead, &page) )
2246 memcpy (bt->cursor, page, bt->mgr->page_size);
2248 if ( bt_unlockpage(bt, right, BtLockRead) )
2257 BtKey bt_key(BtDb *bt, uint slot)
2259 return keyptr(bt->cursor, slot);
2262 uid bt_uid(BtDb *bt, uint slot)
2264 return bt_getid(slotptr(bt->cursor,slot)->id);
2267 uint bt_tod(BtDb *bt, uint slot)
2269 return slotptr(bt->cursor,slot)->tod;
2282 // standalone program to index file of keys
2283 // then list them onto std-out
2286 void *index_file (void *arg)
2288 uint __stdcall index_file (void *arg)
2291 int line = 0, found = 0, cnt = 0;
2292 uid next, page_no = LEAF_page; // start on first page of leaves
2293 unsigned char key[256];
2294 ThreadArg *args = arg;
2295 int ch, len = 0, slot;
2302 bt = bt_open (args->mgr);
2305 switch(args->type | 0x20)
2308 fprintf(stderr, "started indexing for %s\n", args->infile);
2309 if( in = fopen (args->infile, "rb") )
2310 while( ch = getc(in), ch != EOF )
2315 if( args->num == 1 )
2316 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2318 else if( args->num )
2319 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2321 if( bt_insertkey (bt, key, len, line, *tod) )
2322 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2325 else if( len < 255 )
2327 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
2331 fprintf(stderr, "started deleting keys for %s\n", args->infile);
2332 if( in = fopen (args->infile, "rb") )
2333 while( ch = getc(in), ch != EOF )
2337 if( args->num == 1 )
2338 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2340 else if( args->num )
2341 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2343 if( bt_deletekey (bt, key, len, 0) )
2344 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2347 else if( len < 255 )
2349 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2353 fprintf(stderr, "started finding keys for %s\n", args->infile);
2354 if( in = fopen (args->infile, "rb") )
2355 while( ch = getc(in), ch != EOF )
2359 if( args->num == 1 )
2360 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2362 else if( args->num )
2363 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2365 if( bt_findkey (bt, key, len) )
2368 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2371 else if( len < 255 )
2373 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2379 fprintf(stderr, "started reading\n");
2381 if( slot = bt_startkey (bt, key, len) )
2384 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
2386 while( slot = bt_nextkey (bt, slot) ) {
2387 ptr = bt_key(bt, slot);
2388 fwrite (ptr->key, ptr->len, 1, stdout);
2389 fputc ('\n', stdout);
2395 fprintf(stderr, "started reading\n");
2398 bt_lockpage (bt, page_no, BtLockRead, &page);
2400 next = bt_getid (page->right);
2401 bt_unlockpage (bt, page_no, BtLockRead);
2402 } while( page_no = next );
2404 cnt--; // remove stopper key
2405 fprintf(stderr, " Total keys read %d\n", cnt);
2417 typedef struct timeval timer;
2419 int main (int argc, char **argv)
2421 int idx, cnt, len, slot, err;
2422 int segsize, bits = 16;
2427 time_t start[1], stop[1];
2440 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]);
2441 fprintf (stderr, " where page_bits is the page size in bits\n");
2442 fprintf (stderr, " mapped_segments is the number of mmap segments in buffer pool\n");
2443 fprintf (stderr, " seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2444 fprintf (stderr, " line_numbers = 1 to append line numbers to keys\n");
2445 fprintf (stderr, " src_file1 thru src_filen are files of keys separated by newline\n");
2450 gettimeofday(&start, NULL);
2456 bits = atoi(argv[3]);
2459 poolsize = atoi(argv[4]);
2462 fprintf (stderr, "Warning: no mapped_pool\n");
2464 if( poolsize > 65535 )
2465 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2468 segsize = atoi(argv[5]);
2470 segsize = 4; // 16 pages per mmap segment
2473 num = atoi(argv[6]);
2477 threads = malloc (cnt * sizeof(pthread_t));
2479 threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2481 args = malloc (cnt * sizeof(ThreadArg));
2483 mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2486 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2492 for( idx = 0; idx < cnt; idx++ ) {
2493 args[idx].infile = argv[idx + 7];
2494 args[idx].type = argv[2][0];
2495 args[idx].mgr = mgr;
2496 args[idx].num = num;
2497 args[idx].idx = idx;
2499 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2500 fprintf(stderr, "Error creating thread %d\n", err);
2502 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2506 // wait for termination
2509 for( idx = 0; idx < cnt; idx++ )
2510 pthread_join (threads[idx], NULL);
2511 gettimeofday(&stop, NULL);
2512 real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2514 WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2516 for( idx = 0; idx < cnt; idx++ )
2517 CloseHandle(threads[idx]);
2520 real_time = 1000 * (*stop - *start);
2522 fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);