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; // allocation and latch table handle
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 while( __sync_fetch_and_or((ushort *)latch, Mutex) & Mutex )
369 while( _InterlockedOr16((ushort *)latch, Mutex) & Mutex )
373 // see if exclusive request is granted or pending
375 if( prev = !(latch->exclusive | latch->pending) )
377 __sync_fetch_and_add((ushort *)latch, Share);
379 _InterlockedExchangeAdd16 ((ushort *)latch, Share);
383 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
385 _InterlockedAnd16((ushort *)latch, ~Mutex);
390 } while( sched_yield(), 1 );
392 } while( SwitchToThread(), 1 );
396 // wait for other read and write latches to relinquish
398 void bt_spinwritelock(BtSpinLatch *latch)
404 while( __sync_fetch_and_or((ushort *)latch, Mutex | Pending) & Mutex )
407 while( _InterlockedOr16((ushort *)latch, Mutex | Pending) & Mutex )
410 if( prev = !(latch->share | latch->exclusive) )
412 __sync_fetch_and_or((ushort *)latch, Write);
414 _InterlockedOr16((ushort *)latch, Write);
418 __sync_fetch_and_and ((ushort *)latch, ~(Mutex | Pending));
420 _InterlockedAnd16((ushort *)latch, ~(Mutex | Pending));
432 // try to obtain write lock
434 // return 1 if obtained,
437 int bt_spinwritetry(BtSpinLatch *latch)
442 if( prev = __sync_fetch_and_or((ushort *)latch, Mutex), prev & Mutex )
445 if( prev = _InterlockedOr16((ushort *)latch, Mutex), prev & Mutex )
448 // take write access if all bits are clear
452 __sync_fetch_and_or ((ushort *)latch, Write);
454 _InterlockedOr16((ushort *)latch, Write);
458 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
460 _InterlockedAnd16((ushort *)latch, ~Mutex);
467 void bt_spinreleasewrite(BtSpinLatch *latch)
470 __sync_fetch_and_and ((ushort *)latch, ~Write);
472 _InterlockedAnd16((ushort *)latch, ~Write);
476 // decrement reader count
478 void bt_spinreleaseread(BtSpinLatch *latch)
481 __sync_fetch_and_add((ushort *)latch, -Share);
483 _InterlockedExchangeAdd16 ((ushort *)latch, -Share);
487 void bt_initlockset (BtLatchSet *set)
490 pthread_rwlockattr_t rwattr[1];
492 pthread_rwlockattr_init (rwattr);
493 pthread_rwlockattr_setkind_np (rwattr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
494 pthread_rwlockattr_setpshared (rwattr, PTHREAD_PROCESS_SHARED);
496 pthread_rwlock_init (set->readwr->lock, rwattr);
497 pthread_rwlock_init (set->access->lock, rwattr);
498 pthread_rwlock_init (set->parent->lock, rwattr);
499 pthread_rwlockattr_destroy (rwattr);
501 InitializeSRWLock (set->readwr->srw);
502 InitializeSRWLock (set->access->srw);
503 InitializeSRWLock (set->parent->srw);
507 // link latch table entry into latch hash table
509 void bt_latchlink (BtDb *bt, ushort hashidx, ushort victim, uid page_no)
511 BtLatchSet *set = bt->mgr->latchset + victim;
513 if( set->next = bt->mgr->latchmgr->table[hashidx].slot )
514 bt->mgr->latchset[set->next].prev = victim;
516 bt->mgr->latchmgr->table[hashidx].slot = victim;
517 set->page_no = page_no;
522 // find existing latchset or inspire new one
523 // return with latchset pinned
525 BtLatchSet *bt_bindlatch (BtDb *bt, uid page_no, int incr)
527 ushort hashidx = page_no % bt->mgr->latchmgr->latchhash;
528 ushort slot, avail = 0, victim, idx;
531 // obtain read lock on hash table entry
533 bt_spinreadlock(bt->mgr->latchmgr->table[hashidx].latch);
535 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
537 set = bt->mgr->latchset + slot;
538 if( page_no == set->page_no )
540 } while( slot = set->next );
544 __sync_fetch_and_add(&set->pin, 1);
546 _InterlockedIncrement16 (&set->pin);
550 bt_spinreleaseread (bt->mgr->latchmgr->table[hashidx].latch);
555 // try again, this time with write lock
557 bt_spinwritelock(bt->mgr->latchmgr->table[hashidx].latch);
559 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
561 set = bt->mgr->latchset + slot;
562 if( page_no == set->page_no )
564 if( !set->pin && !avail )
566 } while( slot = set->next );
568 // found our entry, or take over an unpinned one
570 if( slot || (slot = avail) ) {
571 set = bt->mgr->latchset + slot;
574 __sync_fetch_and_add(&set->pin, 1);
576 _InterlockedIncrement16 (&set->pin);
578 set->page_no = page_no;
579 bt_spinreleasewrite(bt->mgr->latchmgr->table[hashidx].latch);
583 // see if there are any unused entries
585 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, 1) + 1;
587 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchdeployed);
590 if( victim < bt->mgr->latchmgr->latchtotal ) {
591 set = bt->mgr->latchset + victim;
594 __sync_fetch_and_add(&set->pin, 1);
596 _InterlockedIncrement16 (&set->pin);
598 bt_initlockset (set);
599 bt_latchlink (bt, hashidx, victim, page_no);
600 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
605 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, -1);
607 victim = _InterlockedDecrement16 (&bt->mgr->latchmgr->latchdeployed);
609 // find and reuse previous lock entry
613 victim = __sync_fetch_and_add(&bt->mgr->latchmgr->latchvictim, 1);
615 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchvictim) - 1;
617 // we don't use slot zero
619 if( victim %= bt->mgr->latchmgr->latchtotal )
620 set = bt->mgr->latchset + victim;
624 // take control of our slot
625 // from other threads
627 if( set->pin || !bt_spinwritetry (set->busy) )
632 // try to get write lock on hash chain
633 // skip entry if not obtained
634 // or has outstanding locks
636 if( !bt_spinwritetry (bt->mgr->latchmgr->table[idx].latch) ) {
637 bt_spinreleasewrite (set->busy);
642 bt_spinreleasewrite (set->busy);
643 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
647 // unlink our available victim from its hash chain
650 bt->mgr->latchset[set->prev].next = set->next;
652 bt->mgr->latchmgr->table[idx].slot = set->next;
655 bt->mgr->latchset[set->next].prev = set->prev;
657 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
661 __sync_fetch_and_add(&set->pin, 1);
663 _InterlockedIncrement16 (&set->pin);
666 bt_latchlink (bt, hashidx, victim, page_no);
667 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
668 bt_spinreleasewrite (set->busy);
673 void bt_mgrclose (BtMgr *mgr)
678 // release mapped pages
679 // note that slot zero is never used
681 for( slot = 1; slot < mgr->poolmax; slot++ ) {
682 pool = mgr->pool + slot;
685 munmap (pool->map, (mgr->poolmask+1) << mgr->page_bits);
688 FlushViewOfFile(pool->map, 0);
689 UnmapViewOfFile(pool->map);
690 CloseHandle(pool->hmap);
700 free (mgr->pooladvise);
703 FlushFileBuffers(mgr->idx);
704 CloseHandle(mgr->idx);
705 GlobalFree (mgr->pool);
706 GlobalFree (mgr->hash);
707 GlobalFree (mgr->latch);
712 // close and release memory
714 void bt_close (BtDb *bt)
721 VirtualFree (bt->mem, 0, MEM_RELEASE);
726 // open/create new btree buffer manager
728 // call with file_name, BT_openmode, bits in page size (e.g. 16),
729 // size of mapped page pool (e.g. 8192)
731 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
733 uint lvl, attr, cacheblk, last, slot, idx;
734 uint nlatchpage, latchhash;
735 BtLatchMgr *latchmgr;
744 SYSTEM_INFO sysinfo[1];
747 // determine sanity of page size and buffer pool
749 if( bits > BT_maxbits )
751 else if( bits < BT_minbits )
755 return NULL; // must have buffer pool
758 mgr = calloc (1, sizeof(BtMgr));
760 switch (mode & 0x7fff)
763 mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
769 mgr->idx = open ((char*)name, O_RDONLY);
774 return free(mgr), NULL;
776 cacheblk = 4096; // minimum mmap segment size for unix
779 mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
780 attr = FILE_ATTRIBUTE_NORMAL;
781 switch (mode & 0x7fff)
784 mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
790 mgr->idx = CreateFile(name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, attr, NULL);
794 if( mgr->idx == INVALID_HANDLE_VALUE )
795 return GlobalFree(mgr), NULL;
797 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
798 GetSystemInfo(sysinfo);
799 cacheblk = sysinfo->dwAllocationGranularity;
803 latchmgr = malloc (BT_maxpage);
806 // read minimum page size to get root info
808 if( size = lseek (mgr->idx, 0L, 2) ) {
809 if( pread(mgr->idx, latchmgr, BT_minpage, 0) == BT_minpage )
810 bits = latchmgr->alloc->bits;
812 return free(mgr), free(latchmgr), NULL;
813 } else if( mode == BT_ro )
814 return bt_mgrclose (mgr), NULL;
816 latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
817 size = GetFileSize(mgr->idx, amt);
820 if( !ReadFile(mgr->idx, (char *)latchmgr, BT_minpage, amt, NULL) )
821 return bt_mgrclose (mgr), NULL;
822 bits = latchmgr->alloc->bits;
823 } else if( mode == BT_ro )
824 return bt_mgrclose (mgr), NULL;
827 mgr->page_size = 1 << bits;
828 mgr->page_bits = bits;
830 mgr->poolmax = poolmax;
833 if( cacheblk < mgr->page_size )
834 cacheblk = mgr->page_size;
836 // mask for partial memmaps
838 mgr->poolmask = (cacheblk >> bits) - 1;
840 // see if requested size of pages per memmap is greater
842 if( (1 << segsize) > mgr->poolmask )
843 mgr->poolmask = (1 << segsize) - 1;
847 while( (1 << mgr->seg_bits) <= mgr->poolmask )
850 mgr->hashsize = hashsize;
853 mgr->pool = calloc (poolmax, sizeof(BtPool));
854 mgr->hash = calloc (hashsize, sizeof(ushort));
855 mgr->latch = calloc (hashsize, sizeof(BtSpinLatch));
856 mgr->pooladvise = calloc (poolmax, (mgr->poolmask + 8) / 8);
858 mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * sizeof(BtPool));
859 mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
860 mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtSpinLatch));
866 // initialize an empty b-tree with latch page, root page, page of leaves
867 // and page(s) of latches
869 memset (latchmgr, 0, 1 << bits);
870 nlatchpage = BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1;
871 bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
872 latchmgr->alloc->bits = mgr->page_bits;
874 latchmgr->nlatchpage = nlatchpage;
875 latchmgr->latchtotal = nlatchpage * (mgr->page_size / sizeof(BtLatchSet));
877 // initialize latch manager
879 latchhash = (mgr->page_size - sizeof(BtLatchMgr)) / sizeof(BtHashEntry);
881 // size of hash table = total number of latchsets
883 if( latchhash > latchmgr->latchtotal )
884 latchhash = latchmgr->latchtotal;
886 latchmgr->latchhash = latchhash;
889 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
890 return bt_mgrclose (mgr), NULL;
892 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
893 return bt_mgrclose (mgr), NULL;
895 if( *amt < mgr->page_size )
896 return bt_mgrclose (mgr), NULL;
899 memset (latchmgr, 0, 1 << bits);
900 latchmgr->alloc->bits = mgr->page_bits;
902 for( lvl=MIN_lvl; lvl--; ) {
903 slotptr(latchmgr->alloc, 1)->off = mgr->page_size - 3;
904 bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
905 key = keyptr(latchmgr->alloc, 1);
906 key->len = 2; // create stopper key
909 latchmgr->alloc->min = mgr->page_size - 3;
910 latchmgr->alloc->lvl = lvl;
911 latchmgr->alloc->cnt = 1;
912 latchmgr->alloc->act = 1;
914 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
915 return bt_mgrclose (mgr), NULL;
917 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
918 return bt_mgrclose (mgr), NULL;
920 if( *amt < mgr->page_size )
921 return bt_mgrclose (mgr), NULL;
925 // clear out latch manager locks
926 // and rest of pages to round out segment
928 memset(latchmgr, 0, mgr->page_size);
931 while( last <= ((MIN_lvl + 1 + nlatchpage) | mgr->poolmask) ) {
933 pwrite(mgr->idx, latchmgr, mgr->page_size, last << mgr->page_bits);
935 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
936 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
937 return bt_mgrclose (mgr), NULL;
938 if( *amt < mgr->page_size )
939 return bt_mgrclose (mgr), NULL;
946 flag = PROT_READ | ( mgr->mode == BT_ro ? 0 : PROT_WRITE );
947 mgr->latchmgr = mmap (0, mgr->page_size, flag, MAP_SHARED, mgr->idx, ALLOC_page * mgr->page_size);
948 if( mgr->latchmgr == MAP_FAILED )
949 return bt_mgrclose (mgr), NULL;
950 mgr->latchset = (BtLatchSet *)mmap (0, mgr->latchmgr->nlatchpage * mgr->page_size, flag, MAP_SHARED, mgr->idx, LATCH_page * mgr->page_size);
951 if( mgr->latchset == MAP_FAILED )
952 return bt_mgrclose (mgr), NULL;
954 flag = ( mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
955 mgr->halloc = CreateFileMapping(mgr->idx, NULL, flag, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size, NULL);
957 return bt_mgrclose (mgr), NULL;
959 flag = ( mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
960 mgr->latchmgr = MapViewOfFile(mgr->halloc, flag, 0, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size);
962 return GetLastError(), bt_mgrclose (mgr), NULL;
964 mgr->latchset = (void *)((char *)mgr->latchmgr + LATCH_page * mgr->page_size);
970 VirtualFree (latchmgr, 0, MEM_RELEASE);
975 // open BTree access method
976 // based on buffer manager
978 BtDb *bt_open (BtMgr *mgr)
980 BtDb *bt = malloc (sizeof(*bt));
982 memset (bt, 0, sizeof(*bt));
985 bt->mem = malloc (3 *mgr->page_size);
987 bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
989 bt->frame = (BtPage)bt->mem;
990 bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
991 bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
995 // compare two keys, returning > 0, = 0, or < 0
996 // as the comparison value
998 int keycmp (BtKey key1, unsigned char *key2, uint len2)
1000 uint len1 = key1->len;
1003 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
1016 void bt_readlock(BtLatch *latch)
1019 pthread_rwlock_rdlock (latch->lock);
1021 AcquireSRWLockShared (latch->srw);
1025 // wait for other read and write latches to relinquish
1027 void bt_writelock(BtLatch *latch)
1030 pthread_rwlock_wrlock (latch->lock);
1032 AcquireSRWLockExclusive (latch->srw);
1036 // try to obtain write lock
1038 // return 1 if obtained,
1039 // 0 if already write or read locked
1041 int bt_writetry(BtLatch *latch)
1046 result = !pthread_rwlock_trywrlock (latch->lock);
1048 result = TryAcquireSRWLockExclusive (latch->srw);
1055 void bt_releasewrite(BtLatch *latch)
1058 pthread_rwlock_unlock (latch->lock);
1060 ReleaseSRWLockExclusive (latch->srw);
1064 // decrement reader count
1066 void bt_releaseread(BtLatch *latch)
1069 pthread_rwlock_unlock (latch->lock);
1071 ReleaseSRWLockShared (latch->srw);
1077 // find segment in pool
1078 // must be called with hashslot idx locked
1079 // return NULL if not there
1080 // otherwise return node
1082 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
1087 // compute start of hash chain in pool
1089 if( slot = bt->mgr->hash[idx] )
1090 pool = bt->mgr->pool + slot;
1094 page_no &= ~bt->mgr->poolmask;
1096 while( pool->basepage != page_no )
1097 if( pool = pool->hashnext )
1105 // add segment to hash table
1107 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
1112 pool->hashprev = pool->hashnext = NULL;
1113 pool->basepage = page_no & ~bt->mgr->poolmask;
1116 if( slot = bt->mgr->hash[idx] ) {
1117 node = bt->mgr->pool + slot;
1118 pool->hashnext = node;
1119 node->hashprev = pool;
1122 bt->mgr->hash[idx] = pool->slot;
1125 // find best segment to evict from buffer pool
1127 BtPool *bt_findlru (BtDb *bt, uint hashslot)
1129 unsigned long long int target = ~0LL;
1130 BtPool *pool = NULL, *node;
1135 node = bt->mgr->pool + hashslot;
1137 // scan pool entries under hash table slot
1142 if( node->lru > target )
1146 } while( node = node->hashnext );
1151 // map new buffer pool segment to virtual memory
1153 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
1155 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
1156 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
1160 flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
1161 pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED, bt->mgr->idx, off);
1162 if( pool->map == MAP_FAILED )
1163 return bt->err = BTERR_map;
1164 // clear out madvise issued bits
1165 memset (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8) / 8), 0, (bt->mgr->poolmask + 8)/8);
1167 flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
1168 pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
1170 return bt->err = BTERR_map;
1172 flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
1173 pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1175 return bt->err = BTERR_map;
1180 // find or place requested page in segment-pool
1181 // return pool table entry, incrementing pin
1183 BtPool *bt_pinpage(BtDb *bt, uid page_no)
1185 BtPool *pool, *node, *next;
1186 uint slot, idx, victim;
1189 // lock hash table chain
1191 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1192 bt_spinreadlock (&bt->mgr->latch[idx]);
1194 // look up in hash table
1196 if( pool = bt_findpool(bt, page_no, idx) ) {
1198 __sync_fetch_and_add(&pool->pin, 1);
1200 _InterlockedIncrement16 (&pool->pin);
1202 bt_spinreleaseread (&bt->mgr->latch[idx]);
1207 // upgrade to write lock
1209 bt_spinreleaseread (&bt->mgr->latch[idx]);
1210 bt_spinwritelock (&bt->mgr->latch[idx]);
1212 // try to find page in pool with write lock
1214 if( pool = bt_findpool(bt, page_no, idx) ) {
1216 __sync_fetch_and_add(&pool->pin, 1);
1218 _InterlockedIncrement16 (&pool->pin);
1220 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1225 // allocate a new pool node
1226 // and add to hash table
1229 slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
1231 slot = _InterlockedIncrement16 (&bt->mgr->poolcnt) - 1;
1234 if( ++slot < bt->mgr->poolmax ) {
1235 pool = bt->mgr->pool + slot;
1238 if( bt_mapsegment(bt, pool, page_no) )
1241 bt_linkhash(bt, pool, page_no, idx);
1243 __sync_fetch_and_add(&pool->pin, 1);
1245 _InterlockedIncrement16 (&pool->pin);
1247 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1251 // pool table is full
1252 // find best pool entry to evict
1255 __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
1257 _InterlockedDecrement16 (&bt->mgr->poolcnt);
1262 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
1264 victim = _InterlockedIncrement16 (&bt->mgr->evicted) - 1;
1266 victim %= bt->mgr->hashsize;
1268 // try to get write lock
1269 // skip entry if not obtained
1271 if( !bt_spinwritetry (&bt->mgr->latch[victim]) )
1274 // if cache entry is empty
1275 // or no slots are unpinned
1278 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
1279 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1283 // unlink victim pool node from hash table
1285 if( node = pool->hashprev )
1286 node->hashnext = pool->hashnext;
1287 else if( node = pool->hashnext )
1288 bt->mgr->hash[victim] = node->slot;
1290 bt->mgr->hash[victim] = 0;
1292 if( node = pool->hashnext )
1293 node->hashprev = pool->hashprev;
1295 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1297 // remove old file mapping
1299 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1301 FlushViewOfFile(pool->map, 0);
1302 UnmapViewOfFile(pool->map);
1303 CloseHandle(pool->hmap);
1307 // create new pool mapping
1308 // and link into hash table
1310 if( bt_mapsegment(bt, pool, page_no) )
1313 bt_linkhash(bt, pool, page_no, idx);
1315 __sync_fetch_and_add(&pool->pin, 1);
1317 _InterlockedIncrement16 (&pool->pin);
1319 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1324 // place write, read, or parent lock on requested page_no.
1325 // pin to buffer pool and return page pointer
1327 BTERR bt_lockpage(BtDb *bt, uid page_no, BtLock mode, BtPage *pageptr)
1334 // find/create maping in pool table
1335 // and pin our pool slot
1337 if( pool = bt_pinpage(bt, page_no) )
1338 subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1342 if( !(set = bt_bindlatch (bt, page_no, 1)) )
1345 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1349 uint idx = subpage / 8;
1350 uint bit = subpage % 8;
1352 if( mode == BtLockRead || mode == BtLockWrite )
1353 if( ~((bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] >> bit) & 1 ) {
1354 madvise (page, bt->mgr->page_size, MADV_WILLNEED);
1355 (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] |= 1 << bit;
1362 bt_readlock (set->readwr);
1365 bt_writelock (set->readwr);
1368 bt_readlock (set->access);
1371 bt_writelock (set->access);
1374 bt_writelock (set->parent);
1377 return bt->err = BTERR_lock;
1386 // remove write, read, or parent lock on requested page_no.
1388 BTERR bt_unlockpage(BtDb *bt, uid page_no, BtLock mode)
1394 // since page is pinned
1395 // it should still be in the buffer pool
1396 // and is in no danger of being a victim for reuse
1398 if( !(set = bt_bindlatch (bt, page_no, 0)) )
1399 return bt->err = BTERR_latch;
1401 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1402 bt_spinreadlock (&bt->mgr->latch[idx]);
1404 if( !(pool = bt_findpool(bt, page_no, idx)) )
1405 return bt->err = BTERR_hash;
1407 bt_spinreleaseread (&bt->mgr->latch[idx]);
1411 bt_releaseread (set->readwr);
1414 bt_releasewrite (set->readwr);
1417 bt_releaseread (set->access);
1420 bt_releasewrite (set->access);
1423 bt_releasewrite (set->parent);
1426 return bt->err = BTERR_lock;
1430 __sync_fetch_and_add(&pool->pin, -1);
1431 __sync_fetch_and_add (&set->pin, -1);
1433 _InterlockedDecrement16 (&pool->pin);
1434 _InterlockedDecrement16 (&set->pin);
1439 // deallocate a deleted page
1440 // place on free chain out of allocator page
1441 // fence key must already be removed from parent
1443 BTERR bt_freepage(BtDb *bt, uid page_no)
1445 // obtain delete lock on deleted page
1447 if( bt_lockpage(bt, page_no, BtLockDelete, NULL) )
1450 // obtain write lock on deleted page
1452 if( bt_lockpage(bt, page_no, BtLockWrite, &bt->temp) )
1455 // lock allocation page
1457 bt_spinwritelock(bt->mgr->latchmgr->lock);
1459 // store free chain in allocation page second right
1460 bt_putid(bt->temp->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1461 bt_putid(bt->mgr->latchmgr->alloc[1].right, page_no);
1465 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1467 // remove write lock on deleted node
1469 if( bt_unlockpage(bt, page_no, BtLockWrite) )
1472 // remove delete lock on deleted node
1474 if( bt_unlockpage(bt, page_no, BtLockDelete) )
1480 // allocate a new page and write page into it
1482 uid bt_newpage(BtDb *bt, BtPage page)
1488 // lock allocation page
1490 bt_spinwritelock(bt->mgr->latchmgr->lock);
1492 // use empty chain first
1493 // else allocate empty page
1495 if( new_page = bt_getid(bt->mgr->latchmgr->alloc[1].right) ) {
1496 if( bt_lockpage (bt, new_page, BtLockWrite, &bt->temp) )
1498 bt_putid(bt->mgr->latchmgr->alloc[1].right, bt_getid(bt->temp->right));
1499 if( bt_unlockpage (bt, new_page, BtLockWrite) )
1503 new_page = bt_getid(bt->mgr->latchmgr->alloc->right);
1504 bt_putid(bt->mgr->latchmgr->alloc->right, new_page+1);
1508 if ( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1509 return bt->err = BTERR_wrt, 0;
1511 // if writing first page of pool block, zero last page in the block
1513 if ( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1515 // use zero buffer to write zeros
1516 memset(bt->zero, 0, bt->mgr->page_size);
1517 if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1518 return bt->err = BTERR_wrt, 0;
1521 // bring new page into pool and copy page.
1522 // this will extend the file into the new pages.
1524 if( bt_lockpage(bt, new_page, BtLockWrite, &pmap) )
1527 memcpy(pmap, page, bt->mgr->page_size);
1529 if( bt_unlockpage (bt, new_page, BtLockWrite) )
1532 // unlock allocation latch and return new page no
1534 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1538 // find slot in page for given key at a given level
1540 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1542 uint diff, higher = bt->page->cnt, low = 1, slot;
1544 // low is the lowest candidate, higher is already
1545 // tested as .ge. the given key, loop ends when they meet
1547 while( diff = higher - low ) {
1548 slot = low + ( diff >> 1 );
1549 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1558 // find and load page at given level for given key
1559 // leave page rd or wr locked as requested
1561 int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, uint lock)
1563 uid page_no = ROOT_page, prevpage = 0;
1564 uint drill = 0xff, slot;
1565 uint mode, prevmode;
1567 // start at root of btree and drill down
1570 // determine lock mode of drill level
1571 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1573 bt->page_no = page_no;
1575 // obtain access lock using lock chaining with Access mode
1577 if( page_no > ROOT_page )
1578 if( bt_lockpage(bt, page_no, BtLockAccess, NULL) )
1581 // now unlock our (possibly foster) parent
1584 if( bt_unlockpage(bt, prevpage, prevmode) )
1589 // obtain read lock using lock chaining
1590 // and pin page contents
1592 if( bt_lockpage(bt, page_no, mode, &bt->page) )
1595 if( page_no > ROOT_page )
1596 if( bt_unlockpage(bt, page_no, BtLockAccess) )
1599 // re-read and re-lock root after determining actual level of root
1601 if( bt->page_no == ROOT_page )
1602 if( bt->page->lvl != drill) {
1603 drill = bt->page->lvl;
1605 if( lock == BtLockWrite && drill == lvl )
1606 if( bt_unlockpage(bt, page_no, mode) )
1612 prevpage = bt->page_no;
1615 // if page is being deleted,
1616 // move back to preceeding page
1618 if( bt->page->kill ) {
1619 page_no = bt_getid (bt->page->right);
1623 // find key on page at this level
1624 // and descend to requested level
1626 slot = bt_findslot (bt, key, len);
1628 // is this slot a foster child?
1630 if( slot <= bt->page->cnt - bt->page->foster )
1634 while( slotptr(bt->page, slot)->dead )
1635 if( slot++ < bt->page->cnt )
1640 if( slot <= bt->page->cnt - bt->page->foster )
1643 // continue down / right using overlapping locks
1644 // to protect pages being killed or split.
1646 page_no = bt_getid(slotptr(bt->page, slot)->id);
1650 page_no = bt_getid(bt->page->right);
1654 // return error on end of chain
1656 bt->err = BTERR_struct;
1657 return 0; // return error
1660 // find and delete key on page by marking delete flag bit
1661 // when page becomes empty, delete it from the btree
1663 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl)
1665 unsigned char leftkey[256], rightkey[256];
1670 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1671 ptr = keyptr(bt->page, slot);
1675 // if key is found delete it, otherwise ignore request
1677 if( !keycmp (ptr, key, len) )
1678 if( slotptr(bt->page, slot)->dead == 0 ) {
1679 slotptr(bt->page,slot)->dead = 1;
1680 if( slot < bt->page->cnt )
1681 bt->page->dirty = 1;
1685 // return if page is not empty, or it has no right sibling
1687 right = bt_getid(bt->page->right);
1688 page_no = bt->page_no;
1690 if( !right || bt->page->act )
1691 return bt_unlockpage(bt, page_no, BtLockWrite);
1693 // obtain Parent lock over write lock
1695 if( bt_lockpage(bt, page_no, BtLockParent, NULL) )
1698 // cache copy of key to delete
1700 ptr = keyptr(bt->page, bt->page->cnt);
1701 memcpy(leftkey, ptr, ptr->len + 1);
1703 // lock and map right page
1705 if( bt_lockpage(bt, right, BtLockWrite, &bt->temp) )
1708 // pull contents of next page into current empty page
1709 memcpy (bt->page, bt->temp, bt->mgr->page_size);
1711 // cache copy of key to update
1712 ptr = keyptr(bt->temp, bt->temp->cnt);
1713 memcpy(rightkey, ptr, ptr->len + 1);
1715 // Mark right page as deleted and point it to left page
1716 // until we can post updates at higher level.
1718 bt_putid(bt->temp->right, page_no);
1722 if( bt_unlockpage(bt, right, BtLockWrite) )
1724 if( bt_unlockpage(bt, page_no, BtLockWrite) )
1727 // delete old lower key to consolidated node
1729 if( bt_deletekey (bt, leftkey + 1, *leftkey, lvl + 1) )
1732 // redirect higher key directly to consolidated node
1734 if( slot = bt_loadpage (bt, rightkey+1, *rightkey, lvl+1, BtLockWrite) )
1735 ptr = keyptr(bt->page, slot);
1739 // since key already exists, update id
1741 if( keycmp (ptr, rightkey+1, *rightkey) )
1742 return bt->err = BTERR_struct;
1744 slotptr(bt->page, slot)->dead = 0;
1745 bt_putid(slotptr(bt->page,slot)->id, page_no);
1747 if( bt_unlockpage(bt, bt->page_no, BtLockWrite) )
1750 // obtain write lock and
1751 // add right block to free chain
1753 if( bt_freepage (bt, right) )
1756 // remove ParentModify lock
1758 if( bt_unlockpage(bt, page_no, BtLockParent) )
1764 // find key in leaf level and return row-id
1766 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1772 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1773 ptr = keyptr(bt->page, slot);
1777 // if key exists, return row-id
1778 // otherwise return 0
1780 if( ptr->len == len && !memcmp (ptr->key, key, len) )
1781 id = bt_getid(slotptr(bt->page,slot)->id);
1785 if( bt_unlockpage (bt, bt->page_no, BtLockRead) )
1791 // check page for space available,
1792 // clean if necessary and return
1793 // 0 - page needs splitting
1796 uint bt_cleanpage(BtDb *bt, uint amt)
1798 uint nxt = bt->mgr->page_size;
1799 BtPage page = bt->page;
1800 uint cnt = 0, idx = 0;
1801 uint max = page->cnt;
1804 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1807 // skip cleanup if nothing to reclaim
1812 memcpy (bt->frame, page, bt->mgr->page_size);
1814 // skip page info and set rest of page to zero
1816 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1820 // try cleaning up page first
1822 while( cnt++ < max ) {
1823 // always leave fence key and foster children in list
1824 if( cnt < max - page->foster && slotptr(bt->frame,cnt)->dead )
1828 key = keyptr(bt->frame, cnt);
1829 nxt -= key->len + 1;
1830 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1833 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1834 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1836 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1837 slotptr(page, idx)->off = nxt;
1843 // see if page has enough space now, or does it need splitting?
1845 if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1851 // add key to current page
1852 // page must already be writelocked
1854 void bt_addkeytopage (BtDb *bt, uint slot, unsigned char *key, uint len, uid id, uint tod)
1856 BtPage page = bt->page;
1859 // calculate next available slot and copy key into page
1861 page->min -= len + 1;
1862 ((unsigned char *)page)[page->min] = len;
1863 memcpy ((unsigned char *)page + page->min +1, key, len );
1865 for( idx = slot; idx < page->cnt; idx++ )
1866 if( slotptr(page, idx)->dead )
1869 // now insert key into array before slot
1870 // preserving the fence slot
1872 if( idx == page->cnt )
1878 *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
1880 bt_putid(slotptr(page,slot)->id, id);
1881 slotptr(page, slot)->off = page->min;
1882 slotptr(page, slot)->tod = tod;
1883 slotptr(page, slot)->dead = 0;
1886 // split the root and raise the height of the btree
1887 // call with current page locked and page no of foster child
1888 // return with current page (root) unlocked
1890 BTERR bt_splitroot(BtDb *bt, uid right)
1892 uint nxt = bt->mgr->page_size;
1893 unsigned char fencekey[256];
1894 BtPage root = bt->page;
1898 // Obtain an empty page to use, and copy the left page
1899 // contents into it from the root. Strip foster child key.
1900 // (it's the stopper key)
1906 // Save left fence key.
1908 key = keyptr(root, root->cnt);
1909 memcpy (fencekey, key, key->len + 1);
1911 // copy the lower keys into a new left page
1913 if( !(new_page = bt_newpage(bt, root)) )
1916 // preserve the page info at the bottom
1917 // and set rest of the root to zero
1919 memset (root+1, 0, bt->mgr->page_size - sizeof(*root));
1921 // insert left fence key on empty newroot page
1923 nxt -= *fencekey + 1;
1924 memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
1925 bt_putid(slotptr(root, 1)->id, new_page);
1926 slotptr(root, 1)->off = nxt;
1928 // insert stopper key on newroot page
1929 // and increase the root height
1935 memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
1936 bt_putid(slotptr(root, 2)->id, right);
1937 slotptr(root, 2)->off = nxt;
1939 bt_putid(root->right, 0);
1940 root->min = nxt; // reset lowest used offset and key count
1945 // release root (bt->page)
1947 return bt_unlockpage(bt, ROOT_page, BtLockWrite);
1950 // split already locked full node
1951 // in current page variables
1954 BTERR bt_splitpage (BtDb *bt)
1956 uint slot, cnt, idx, max, nxt = bt->mgr->page_size;
1957 unsigned char fencekey[256];
1958 uid page_no = bt->page_no;
1959 BtPage page = bt->page;
1960 uint tod = time(NULL);
1961 uint lvl = page->lvl;
1962 uid new_page, right;
1965 // initialize frame buffer
1967 memset (bt->frame, 0, bt->mgr->page_size);
1968 max = page->cnt - page->foster;
1969 tod = (uint)time(NULL);
1973 // split higher half of keys to bt->frame
1974 // leaving foster children in the left node.
1976 while( cnt++ < max ) {
1977 key = keyptr(page, cnt);
1978 nxt -= key->len + 1;
1979 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
1980 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
1981 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
1982 slotptr(bt->frame, idx)->off = nxt;
1986 // transfer right link node
1988 if( page_no > ROOT_page ) {
1989 right = bt_getid (page->right);
1990 bt_putid(bt->frame->right, right);
1993 bt->frame->bits = bt->mgr->page_bits;
1994 bt->frame->min = nxt;
1995 bt->frame->cnt = idx;
1996 bt->frame->lvl = lvl;
1998 // get new free page and write frame to it.
2000 if( !(new_page = bt_newpage(bt, bt->frame)) )
2003 // remember fence key for new page to add
2006 key = keyptr(bt->frame, idx);
2007 memcpy (fencekey, key, key->len + 1);
2009 // update lower keys and foster children to continue in old page
2011 memcpy (bt->frame, page, bt->mgr->page_size);
2012 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
2013 nxt = bt->mgr->page_size;
2018 // assemble page of smaller keys
2019 // to remain in the old page
2021 while( cnt++ < max / 2 ) {
2022 key = keyptr(bt->frame, cnt);
2023 nxt -= key->len + 1;
2024 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2025 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
2026 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2027 slotptr(page, idx)->off = nxt;
2031 // insert new foster child at beginning of the current foster children
2033 nxt -= *fencekey + 1;
2034 memcpy ((unsigned char *)page + nxt, fencekey, *fencekey + 1);
2035 bt_putid (slotptr(page,++idx)->id, new_page);
2036 slotptr(page, idx)->tod = tod;
2037 slotptr(page, idx)->off = nxt;
2041 // continue with old foster child keys if any
2043 cnt = bt->frame->cnt - bt->frame->foster;
2045 while( cnt++ < bt->frame->cnt ) {
2046 key = keyptr(bt->frame, cnt);
2047 nxt -= key->len + 1;
2048 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2049 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
2050 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2051 slotptr(page, idx)->off = nxt;
2058 // link new right page
2060 bt_putid (page->right, new_page);
2062 // if current page is the root page, split it
2064 if( page_no == ROOT_page )
2065 return bt_splitroot (bt, new_page);
2067 // release wr lock on our page
2069 if( bt_unlockpage (bt, page_no, BtLockWrite) )
2072 // obtain ParentModification lock for current page
2073 // to fix fence key and highest foster child on page
2075 if( bt_lockpage (bt, page_no, BtLockParent, NULL) )
2078 // get our highest foster child key to find in parent node
2080 if( bt_lockpage (bt, page_no, BtLockRead, &page) )
2083 key = keyptr(page, page->cnt);
2084 memcpy (fencekey, key, key->len+1);
2086 if( bt_unlockpage (bt, page_no, BtLockRead) )
2089 // update our parent
2093 slot = bt_loadpage (bt, fencekey + 1, *fencekey, lvl + 1, BtLockWrite);
2098 // check if parent page has enough space for any possible key
2100 if( bt_cleanpage (bt, 256) )
2103 if( bt_splitpage (bt) )
2107 // see if we are still a foster child from another node
2109 if( bt_getid (slotptr(bt->page, slot)->id) != page_no ) {
2110 if( bt_unlockpage (bt, bt->page_no, BtLockWrite) )
2120 // wait until readers from parent get their locks
2123 if( bt_lockpage (bt, page_no, BtLockDelete, NULL) )
2126 // lock our page for writing
2128 if( bt_lockpage (bt, page_no, BtLockWrite, &page) )
2131 // switch parent fence key to foster child
2133 if( slotptr(page, page->cnt)->dead )
2134 slotptr(bt->page, slot)->dead = 1;
2136 bt_putid (slotptr(bt->page, slot)->id, bt_getid(slotptr(page, page->cnt)->id));
2138 // remove highest foster child from our page
2144 key = keyptr(page, page->cnt);
2146 // add our new fence key for foster child to our parent
2148 bt_addkeytopage (bt, slot, key->key, key->len, page_no, tod);
2150 if( bt_unlockpage (bt, bt->page_no, BtLockWrite) )
2153 if( bt_unlockpage (bt, page_no, BtLockDelete) )
2156 if( bt_unlockpage (bt, page_no, BtLockWrite) )
2159 return bt_unlockpage (bt, page_no, BtLockParent);
2162 // Insert new key into the btree at leaf level.
2164 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod)
2171 if( slot = bt_loadpage (bt, key, len, 0, BtLockWrite) )
2172 ptr = keyptr(bt->page, slot);
2176 bt->err = BTERR_ovflw;
2180 // if key already exists, update id and return
2184 if( !keycmp (ptr, key, len) ) {
2185 slotptr(page, slot)->dead = 0;
2186 slotptr(page, slot)->tod = tod;
2187 bt_putid(slotptr(page,slot)->id, id);
2188 return bt_unlockpage(bt, bt->page_no, BtLockWrite);
2191 // check if page has enough space
2193 if( bt_cleanpage (bt, len) )
2196 if( bt_splitpage (bt) )
2200 bt_addkeytopage (bt, slot, key, len, id, tod);
2202 return bt_unlockpage (bt, bt->page_no, BtLockWrite);
2205 // cache page of keys into cursor and return starting slot for given key
2207 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2211 // cache page for retrieval
2212 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
2213 memcpy (bt->cursor, bt->page, bt->mgr->page_size);
2214 bt->cursor_page = bt->page_no;
2215 if ( bt_unlockpage(bt, bt->page_no, BtLockRead) )
2221 // return next slot for cursor page
2222 // or slide cursor right into next page
2224 uint bt_nextkey (BtDb *bt, uint slot)
2230 right = bt_getid(bt->cursor->right);
2231 while( slot++ < bt->cursor->cnt - bt->cursor->foster )
2232 if( slotptr(bt->cursor,slot)->dead )
2234 else if( right || (slot < bt->cursor->cnt - bt->cursor->foster) )
2242 bt->cursor_page = right;
2244 if( bt_lockpage(bt, right, BtLockRead, &page) )
2247 memcpy (bt->cursor, page, bt->mgr->page_size);
2249 if ( bt_unlockpage(bt, right, BtLockRead) )
2258 BtKey bt_key(BtDb *bt, uint slot)
2260 return keyptr(bt->cursor, slot);
2263 uid bt_uid(BtDb *bt, uint slot)
2265 return bt_getid(slotptr(bt->cursor,slot)->id);
2268 uint bt_tod(BtDb *bt, uint slot)
2270 return slotptr(bt->cursor,slot)->tod;
2283 // standalone program to index file of keys
2284 // then list them onto std-out
2287 void *index_file (void *arg)
2289 uint __stdcall index_file (void *arg)
2292 int line = 0, found = 0, cnt = 0;
2293 uid next, page_no = LEAF_page; // start on first page of leaves
2294 unsigned char key[256];
2295 ThreadArg *args = arg;
2296 int ch, len = 0, slot;
2303 bt = bt_open (args->mgr);
2306 switch(args->type | 0x20)
2309 fprintf(stderr, "started indexing for %s\n", args->infile);
2310 if( in = fopen (args->infile, "rb") )
2311 while( ch = getc(in), ch != EOF )
2316 if( args->num == 1 )
2317 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2319 else if( args->num )
2320 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2322 if( bt_insertkey (bt, key, len, line, *tod) )
2323 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2326 else if( len < 255 )
2328 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
2332 fprintf(stderr, "started deleting keys for %s\n", args->infile);
2333 if( in = fopen (args->infile, "rb") )
2334 while( ch = getc(in), ch != EOF )
2338 if( args->num == 1 )
2339 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2341 else if( args->num )
2342 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2344 if( bt_deletekey (bt, key, len, 0) )
2345 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2348 else if( len < 255 )
2350 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2354 fprintf(stderr, "started finding keys for %s\n", args->infile);
2355 if( in = fopen (args->infile, "rb") )
2356 while( ch = getc(in), ch != EOF )
2360 if( args->num == 1 )
2361 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2363 else if( args->num )
2364 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2366 if( bt_findkey (bt, key, len) )
2369 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2372 else if( len < 255 )
2374 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2380 fprintf(stderr, "started reading\n");
2382 if( slot = bt_startkey (bt, key, len) )
2385 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
2387 while( slot = bt_nextkey (bt, slot) ) {
2388 ptr = bt_key(bt, slot);
2389 fwrite (ptr->key, ptr->len, 1, stdout);
2390 fputc ('\n', stdout);
2396 fprintf(stderr, "started reading\n");
2399 bt_lockpage (bt, page_no, BtLockRead, &page);
2401 next = bt_getid (page->right);
2402 bt_unlockpage (bt, page_no, BtLockRead);
2403 } while( page_no = next );
2405 cnt--; // remove stopper key
2406 fprintf(stderr, " Total keys read %d\n", cnt);
2418 typedef struct timeval timer;
2420 int main (int argc, char **argv)
2422 int idx, cnt, len, slot, err;
2423 int segsize, bits = 16;
2428 time_t start[1], stop[1];
2441 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]);
2442 fprintf (stderr, " where page_bits is the page size in bits\n");
2443 fprintf (stderr, " mapped_segments is the number of mmap segments in buffer pool\n");
2444 fprintf (stderr, " seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2445 fprintf (stderr, " line_numbers = 1 to append line numbers to keys\n");
2446 fprintf (stderr, " src_file1 thru src_filen are files of keys separated by newline\n");
2451 gettimeofday(&start, NULL);
2457 bits = atoi(argv[3]);
2460 poolsize = atoi(argv[4]);
2463 fprintf (stderr, "Warning: no mapped_pool\n");
2465 if( poolsize > 65535 )
2466 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2469 segsize = atoi(argv[5]);
2471 segsize = 4; // 16 pages per mmap segment
2474 num = atoi(argv[6]);
2478 threads = malloc (cnt * sizeof(pthread_t));
2480 threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2482 args = malloc (cnt * sizeof(ThreadArg));
2484 mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2487 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2493 for( idx = 0; idx < cnt; idx++ ) {
2494 args[idx].infile = argv[idx + 7];
2495 args[idx].type = argv[2][0];
2496 args[idx].mgr = mgr;
2497 args[idx].num = num;
2498 args[idx].idx = idx;
2500 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2501 fprintf(stderr, "Error creating thread %d\n", err);
2503 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2507 // wait for termination
2510 for( idx = 0; idx < cnt; idx++ )
2511 pthread_join (threads[idx], NULL);
2512 gettimeofday(&stop, NULL);
2513 real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2515 WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2517 for( idx = 0; idx < cnt; idx++ )
2518 CloseHandle(threads[idx]);
2521 real_time = 1000 * (*stop - *start);
2523 fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);