1 // btree version threads2h pthread rw lock version
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_latchtable 128 // number of latch manager slots
63 #define BT_ro 0x6f72 // ro
64 #define BT_rw 0x7772 // rw
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) ParentModification: Exclusive. Change the node's parent keys. Incompatible with another ParentModification.
88 // mode & definition for latch implementation
97 // exclusive is set for write access
98 // share is count of read accessors
99 // grant write lock when share == 0
102 volatile ushort mutex:1;
103 volatile ushort exclusive:1;
104 volatile ushort pending:1;
105 volatile ushort share:13;
108 // hash table entries
111 BtSpinLatch latch[1];
112 volatile ushort slot; // Latch table entry at head of chain
115 // latch manager table structure
119 pthread_rwlock_t lock[1];
126 BtLatch readwr[1]; // read/write page lock
127 BtLatch access[1]; // Access Intent/Page delete
128 BtLatch parent[1]; // Posting of fence key in parent
129 BtSpinLatch busy[1]; // slot is being moved between chains
130 volatile ushort next; // next entry in hash table chain
131 volatile ushort prev; // prev entry in hash table chain
132 volatile ushort pin; // number of outstanding locks
133 volatile ushort hash; // hash slot entry is under
134 volatile uid page_no; // latch set page number
137 // Define the length of the page and key pointers
141 // Page key slot definition.
143 // If BT_maxbits is 15 or less, you can save 4 bytes
144 // for each key stored by making the first two uints
145 // into ushorts. You can also save 4 bytes by removing
146 // the tod field from the key.
148 // Keys are marked dead, but remain on the page until
149 // it cleanup is called. The fence key (highest key) for
150 // the page is always present, even after cleanup.
153 uint off:BT_maxbits; // page offset for key start
154 uint dead:1; // set for deleted key
155 uint tod; // time-stamp for key
156 unsigned char id[BtId]; // id associated with key
159 // The key structure occupies space at the upper end of
160 // each page. It's a length byte followed by the value
165 unsigned char key[1];
168 // The first part of an index page.
169 // It is immediately followed
170 // by the BtSlot array of keys.
172 typedef struct Page {
173 uint cnt; // count of keys in page
174 uint act; // count of active keys
175 uint min; // next key offset
176 unsigned char bits; // page size in bits
177 unsigned char lvl:7; // level of page
178 unsigned char dirty:1; // page has deleted keys
179 unsigned char right[BtId]; // page number to right
182 // The memory mapping pool table buffer manager entry
185 unsigned long long int lru; // number of times accessed
186 uid basepage; // mapped base page number
187 char *map; // mapped memory pointer
188 ushort slot; // slot index in this array
189 ushort pin; // mapped page pin counter
190 void *hashprev; // previous pool entry for the same hash idx
191 void *hashnext; // next pool entry for the same hash idx
193 HANDLE hmap; // Windows memory mapping handle
197 // structure for latch manager on ALLOC_page
200 struct Page alloc[2]; // next & free page_nos in right ptr
201 BtSpinLatch lock[1]; // allocation area lite latch
202 ushort latchdeployed; // highest number of latch entries deployed
203 ushort nlatchpage; // number of latch pages at BT_latch
204 ushort latchtotal; // number of page latch entries
205 ushort latchhash; // number of latch hash table slots
206 ushort latchvictim; // next latch entry to examine
207 BtHashEntry table[0]; // the hash table
210 // The object structure for Btree access
213 uint page_size; // page size
214 uint page_bits; // page size in bits
215 uint seg_bits; // seg size in pages in bits
216 uint mode; // read-write mode
218 char *pooladvise; // bit maps for pool page advisements
223 ushort poolcnt; // highest page pool node in use
224 ushort poolmax; // highest page pool node allocated
225 ushort poolmask; // total number of pages in mmap segment - 1
226 ushort hashsize; // size of Hash Table for pool entries
227 volatile uint evicted; // last evicted hash table slot
228 ushort *hash; // pool index for hash entries
229 BtSpinLatch *latch; // latches for hash table slots
230 BtLatchMgr *latchmgr; // mapped latch page from allocation page
231 BtLatchSet *latchsets; // mapped latch set from latch pages
232 BtPool *pool; // memory pool page segments
234 HANDLE halloc; // allocation and latch table handle
239 BtMgr *mgr; // buffer manager for thread
240 BtPage cursor; // cached frame for start/next (never mapped)
241 BtPage frame; // spare frame for the page split (never mapped)
242 BtPage zero; // page frame for zeroes at end of file
243 BtPage page; // current page
244 uid page_no; // current page number
245 uid cursor_page; // current cursor page number
246 BtLatchSet *set; // current page latch set
247 BtPool *pool; // current page pool
248 unsigned char *mem; // frame, cursor, page memory buffer
249 int parent; // last loadpage was from a parent level
250 int found; // last delete or insert was found
251 int err; // last error
265 extern void bt_close (BtDb *bt);
266 extern BtDb *bt_open (BtMgr *mgr);
267 extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod, uint lvl);
268 extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len);
269 extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
270 extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
271 extern uint bt_nextkey (BtDb *bt, uint slot);
273 // internal functions
274 BTERR bt_splitpage (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no);
275 uint bt_cleanpage(BtDb *bt, BtPage page, uint amt, uint slot);
276 BTERR bt_mergeleft (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no, uint lvl);
279 extern BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolsize, uint segsize, uint hashsize);
280 void bt_mgrclose (BtMgr *mgr);
282 // Helper functions to return slot values
284 extern BtKey bt_key (BtDb *bt, uint slot);
285 extern uid bt_uid (BtDb *bt, uint slot);
286 extern uint bt_tod (BtDb *bt, uint slot);
288 // BTree page number constants
289 #define ALLOC_page 0 // allocation & lock manager hash table
290 #define ROOT_page 1 // root of the btree
291 #define LEAF_page 2 // first page of leaves
292 #define LATCH_page 3 // pages for lock manager
294 // Number of levels to create in a new BTree
298 // The page is allocated from low and hi ends.
299 // The key offsets and row-id's are allocated
300 // from the bottom, while the text of the key
301 // is allocated from the top. When the two
302 // areas meet, the page is split into two.
304 // A key consists of a length byte, two bytes of
305 // index number (0 - 65534), and up to 253 bytes
306 // of key value. Duplicate keys are discarded.
307 // Associated with each key is a 48 bit row-id.
309 // The b-tree root is always located at page 1.
310 // The first leaf page of level zero is always
311 // located on page 2.
313 // The b-tree pages are linked with next
314 // pointers to facilitate enumerators,
315 // and provide for concurrency.
317 // When to root page fills, it is split in two and
318 // the tree height is raised by a new root at page
319 // one with two keys.
321 // Deleted keys are marked with a dead bit until
322 // page cleanup The fence key for a node is always
323 // present, even after deletion and cleanup.
325 // Groups of pages called segments from the btree are optionally
326 // cached with a memory mapped pool. A hash table is used to keep
327 // track of the cached segments. This behaviour is controlled
328 // by the cache block size parameter to bt_open.
330 // To achieve maximum concurrency one page is locked at a time
331 // as the tree is traversed to find leaf key in question. The right
332 // page numbers are used in cases where the page is being split,
335 // Page 0 is dedicated to lock for new page extensions,
336 // and chains empty pages together for reuse.
338 // The ParentModification lock on a node is obtained to prevent resplitting
339 // or deleting a node before its fence is posted into its upper level.
341 // Empty pages are chained together through the ALLOC page and reused.
343 // Access macros to address slot and key values from the page
345 #define slotptr(page, slot) (((BtSlot *)(page+1)) + (slot-1))
346 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
348 void bt_putid(unsigned char *dest, uid id)
353 dest[i] = (unsigned char)id, id >>= 8;
356 uid bt_getid(unsigned char *src)
361 for( i = 0; i < BtId; i++ )
362 id <<= 8, id |= *src++;
369 // wait until write lock mode is clear
370 // and add 1 to the share count
372 void bt_spinreadlock(BtSpinLatch *latch)
377 // obtain latch mutex
379 if( __sync_fetch_and_or((ushort *)latch, Mutex) & Mutex )
382 if( prev = _InterlockedOr16((ushort *)latch, Mutex) & Mutex )
385 // see if exclusive request is granted or pending
387 if( prev = !(latch->exclusive | latch->pending) )
389 __sync_fetch_and_add((ushort *)latch, Share);
391 _InterlockedExchangeAdd16 ((ushort *)latch, Share);
395 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
397 _InterlockedAnd16((ushort *)latch, ~Mutex);
403 } while( sched_yield(), 1 );
405 } while( SwitchToThread(), 1 );
409 // wait for other read and write latches to relinquish
411 void bt_spinwritelock(BtSpinLatch *latch)
415 if( __sync_fetch_and_or((ushort *)latch, Mutex | Pending) & Mutex )
418 if( _InterlockedOr16((ushort *)latch, Mutex | Pending) & Mutex )
421 if( !(latch->share | latch->exclusive) ) {
423 __sync_fetch_and_or((ushort *)latch, Write);
424 __sync_fetch_and_and ((ushort *)latch, ~(Mutex | Pending));
426 _InterlockedOr16((ushort *)latch, Write);
427 _InterlockedAnd16((ushort *)latch, ~(Mutex | Pending));
433 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
435 _InterlockedAnd16((ushort *)latch, ~Mutex);
439 } while( sched_yield(), 1 );
441 } while( SwitchToThread(), 1 );
445 // try to obtain write lock
447 // return 1 if obtained,
450 int bt_spinwritetry(BtSpinLatch *latch)
455 if( prev = __sync_fetch_and_or((ushort *)latch, Mutex), prev & Mutex )
458 if( prev = _InterlockedOr16((ushort *)latch, Mutex), prev & Mutex )
461 // take write access if all bits are clear
465 __sync_fetch_and_or ((ushort *)latch, Write);
467 _InterlockedOr16((ushort *)latch, Write);
471 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
473 _InterlockedAnd16((ushort *)latch, ~Mutex);
480 void bt_spinreleasewrite(BtSpinLatch *latch)
483 __sync_fetch_and_and ((ushort *)latch, ~Write);
485 _InterlockedAnd16((ushort *)latch, ~Write);
489 // decrement reader count
491 void bt_spinreleaseread(BtSpinLatch *latch)
494 __sync_fetch_and_add((ushort *)latch, -Share);
496 _InterlockedExchangeAdd16 ((ushort *)latch, -Share);
500 void bt_readlock(BtLatch *latch)
503 pthread_rwlock_rdlock (latch->lock);
505 AcquireSRWLockShared (latch->srw);
509 // wait for other read and write latches to relinquish
511 void bt_writelock(BtLatch *latch)
514 pthread_rwlock_wrlock (latch->lock);
516 AcquireSRWLockExclusive (latch->srw);
520 // try to obtain write lock
522 // return 1 if obtained,
523 // 0 if already write or read locked
525 int bt_writetry(BtLatch *latch)
530 result = !pthread_rwlock_trywrlock (latch->lock);
532 result = TryAcquireSRWLockExclusive (latch->srw);
539 void bt_releasewrite(BtLatch *latch)
542 pthread_rwlock_unlock (latch->lock);
544 ReleaseSRWLockExclusive (latch->srw);
548 // decrement reader count
550 void bt_releaseread(BtLatch *latch)
553 pthread_rwlock_unlock (latch->lock);
555 ReleaseSRWLockShared (latch->srw);
559 void bt_initlockset (BtLatchSet *set, int reuse)
562 pthread_rwlockattr_t rwattr[1];
565 pthread_rwlock_destroy (set->readwr->lock);
566 pthread_rwlock_destroy (set->access->lock);
567 pthread_rwlock_destroy (set->parent->lock);
570 pthread_rwlockattr_init (rwattr);
571 pthread_rwlockattr_setkind_np (rwattr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
572 pthread_rwlockattr_setpshared (rwattr, PTHREAD_PROCESS_SHARED);
574 pthread_rwlock_init (set->readwr->lock, rwattr);
575 pthread_rwlock_init (set->access->lock, rwattr);
576 pthread_rwlock_init (set->parent->lock, rwattr);
577 pthread_rwlockattr_destroy (rwattr);
579 InitializeSRWLock (set->readwr->srw);
580 InitializeSRWLock (set->access->srw);
581 InitializeSRWLock (set->parent->srw);
585 // link latch table entry into latch hash table
587 void bt_latchlink (BtDb *bt, ushort hashidx, ushort victim, uid page_no)
589 BtLatchSet *set = bt->mgr->latchsets + victim;
591 if( set->next = bt->mgr->latchmgr->table[hashidx].slot )
592 bt->mgr->latchsets[set->next].prev = victim;
594 bt->mgr->latchmgr->table[hashidx].slot = victim;
595 set->page_no = page_no;
602 void bt_unpinlatch (BtLatchSet *set)
605 __sync_fetch_and_add(&set->pin, -1);
607 _InterlockedDecrement16 (&set->pin);
611 // find existing latchset or inspire new one
612 // return with latchset pinned
614 BtLatchSet *bt_pinlatch (BtDb *bt, uid page_no)
616 ushort hashidx = page_no % bt->mgr->latchmgr->latchhash;
617 ushort slot, avail = 0, victim, idx;
620 // obtain read lock on hash table entry
622 bt_spinreadlock(bt->mgr->latchmgr->table[hashidx].latch);
624 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
626 set = bt->mgr->latchsets + slot;
627 if( page_no == set->page_no )
629 } while( slot = set->next );
633 __sync_fetch_and_add(&set->pin, 1);
635 _InterlockedIncrement16 (&set->pin);
639 bt_spinreleaseread (bt->mgr->latchmgr->table[hashidx].latch);
644 // try again, this time with write lock
646 bt_spinwritelock(bt->mgr->latchmgr->table[hashidx].latch);
648 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
650 set = bt->mgr->latchsets + slot;
651 if( page_no == set->page_no )
653 if( !set->pin && !avail )
655 } while( slot = set->next );
657 // found our entry, or take over an unpinned one
659 if( slot || (slot = avail) ) {
660 set = bt->mgr->latchsets + slot;
662 __sync_fetch_and_add(&set->pin, 1);
664 _InterlockedIncrement16 (&set->pin);
666 set->page_no = page_no;
667 bt_spinreleasewrite(bt->mgr->latchmgr->table[hashidx].latch);
671 // see if there are any unused entries
673 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, 1) + 1;
675 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchdeployed);
678 if( victim < bt->mgr->latchmgr->latchtotal ) {
679 set = bt->mgr->latchsets + victim;
681 __sync_fetch_and_add(&set->pin, 1);
683 _InterlockedIncrement16 (&set->pin);
685 bt_initlockset (set, 0);
686 bt_latchlink (bt, hashidx, victim, page_no);
687 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
692 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, -1);
694 victim = _InterlockedDecrement16 (&bt->mgr->latchmgr->latchdeployed);
696 // find and reuse previous lock entry
700 victim = __sync_fetch_and_add(&bt->mgr->latchmgr->latchvictim, 1);
702 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchvictim) - 1;
704 // we don't use slot zero
706 if( victim %= bt->mgr->latchmgr->latchtotal )
707 set = bt->mgr->latchsets + victim;
711 // take control of our slot
712 // from other threads
714 if( set->pin || !bt_spinwritetry (set->busy) )
719 // try to get write lock on hash chain
720 // skip entry if not obtained
721 // or has outstanding locks
723 if( !bt_spinwritetry (bt->mgr->latchmgr->table[idx].latch) ) {
724 bt_spinreleasewrite (set->busy);
729 bt_spinreleasewrite (set->busy);
730 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
734 // unlink our available victim from its hash chain
737 bt->mgr->latchsets[set->prev].next = set->next;
739 bt->mgr->latchmgr->table[idx].slot = set->next;
742 bt->mgr->latchsets[set->next].prev = set->prev;
744 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
746 __sync_fetch_and_add(&set->pin, 1);
748 _InterlockedIncrement16 (&set->pin);
750 bt_initlockset (set, 1);
751 bt_latchlink (bt, hashidx, victim, page_no);
752 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
753 bt_spinreleasewrite (set->busy);
758 void bt_mgrclose (BtMgr *mgr)
763 // release mapped pages
764 // note that slot zero is never used
766 for( slot = 1; slot < mgr->poolmax; slot++ ) {
767 pool = mgr->pool + slot;
770 munmap (pool->map, (mgr->poolmask+1) << mgr->page_bits);
773 FlushViewOfFile(pool->map, 0);
774 UnmapViewOfFile(pool->map);
775 CloseHandle(pool->hmap);
781 munmap (mgr->latchsets, mgr->latchmgr->nlatchpage * mgr->page_size);
782 munmap (mgr->latchmgr, mgr->page_size);
784 FlushViewOfFile(mgr->latchmgr, 0);
785 UnmapViewOfFile(mgr->latchmgr);
786 CloseHandle(mgr->halloc);
793 free (mgr->pooladvise);
796 FlushFileBuffers(mgr->idx);
797 CloseHandle(mgr->idx);
798 GlobalFree (mgr->pool);
799 GlobalFree (mgr->hash);
800 GlobalFree (mgr->latch);
805 // close and release memory
807 void bt_close (BtDb *bt)
814 VirtualFree (bt->mem, 0, MEM_RELEASE);
819 // open/create new btree buffer manager
821 // call with file_name, BT_openmode, bits in page size (e.g. 16),
822 // size of mapped page pool (e.g. 8192)
824 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
826 uint lvl, attr, cacheblk, last, slot, idx;
827 uint nlatchpage, latchhash;
828 BtLatchMgr *latchmgr;
836 SYSTEM_INFO sysinfo[1];
839 // determine sanity of page size and buffer pool
841 if( bits > BT_maxbits )
843 else if( bits < BT_minbits )
847 return NULL; // must have buffer pool
850 mgr = calloc (1, sizeof(BtMgr));
852 mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
855 return free(mgr), NULL;
857 cacheblk = 4096; // minimum mmap segment size for unix
860 mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
861 attr = FILE_ATTRIBUTE_NORMAL;
862 mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
864 if( mgr->idx == INVALID_HANDLE_VALUE )
865 return GlobalFree(mgr), NULL;
867 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
868 GetSystemInfo(sysinfo);
869 cacheblk = sysinfo->dwAllocationGranularity;
873 latchmgr = malloc (BT_maxpage);
876 // read minimum page size to get root info
878 if( size = lseek (mgr->idx, 0L, 2) ) {
879 if( pread(mgr->idx, latchmgr, BT_minpage, 0) == BT_minpage )
880 bits = latchmgr->alloc->bits;
882 return free(mgr), free(latchmgr), NULL;
883 } else if( mode == BT_ro )
884 return free(latchmgr), bt_mgrclose (mgr), NULL;
886 latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
887 size = GetFileSize(mgr->idx, amt);
890 if( !ReadFile(mgr->idx, (char *)latchmgr, BT_minpage, amt, NULL) )
891 return bt_mgrclose (mgr), NULL;
892 bits = latchmgr->alloc->bits;
893 } else if( mode == BT_ro )
894 return bt_mgrclose (mgr), NULL;
897 mgr->page_size = 1 << bits;
898 mgr->page_bits = bits;
900 mgr->poolmax = poolmax;
903 if( cacheblk < mgr->page_size )
904 cacheblk = mgr->page_size;
906 // mask for partial memmaps
908 mgr->poolmask = (cacheblk >> bits) - 1;
910 // see if requested size of pages per memmap is greater
912 if( (1 << segsize) > mgr->poolmask )
913 mgr->poolmask = (1 << segsize) - 1;
917 while( (1 << mgr->seg_bits) <= mgr->poolmask )
920 mgr->hashsize = hashsize;
923 mgr->pool = calloc (poolmax, sizeof(BtPool));
924 mgr->hash = calloc (hashsize, sizeof(ushort));
925 mgr->latch = calloc (hashsize, sizeof(BtSpinLatch));
926 mgr->pooladvise = calloc (poolmax, (mgr->poolmask + 8) / 8);
928 mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * sizeof(BtPool));
929 mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
930 mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtSpinLatch));
936 // initialize an empty b-tree with latch page, root page, page of leaves
937 // and page(s) of latches
939 memset (latchmgr, 0, 1 << bits);
940 nlatchpage = BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1;
941 bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
942 latchmgr->alloc->bits = mgr->page_bits;
944 latchmgr->nlatchpage = nlatchpage;
945 latchmgr->latchtotal = nlatchpage * (mgr->page_size / sizeof(BtLatchSet));
947 // initialize latch manager
949 latchhash = (mgr->page_size - sizeof(BtLatchMgr)) / sizeof(BtHashEntry);
951 // size of hash table = total number of latchsets
953 if( latchhash > latchmgr->latchtotal )
954 latchhash = latchmgr->latchtotal;
956 latchmgr->latchhash = latchhash;
959 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
960 return bt_mgrclose (mgr), NULL;
962 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
963 return bt_mgrclose (mgr), NULL;
965 if( *amt < mgr->page_size )
966 return bt_mgrclose (mgr), NULL;
969 memset (latchmgr, 0, 1 << bits);
970 latchmgr->alloc->bits = mgr->page_bits;
972 for( lvl=MIN_lvl; lvl--; ) {
973 slotptr(latchmgr->alloc, 1)->off = mgr->page_size - 3;
974 bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
975 key = keyptr(latchmgr->alloc, 1);
976 key->len = 2; // create stopper key
979 latchmgr->alloc->min = mgr->page_size - 3;
980 latchmgr->alloc->lvl = lvl;
981 latchmgr->alloc->cnt = 1;
982 latchmgr->alloc->act = 1;
984 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
985 return bt_mgrclose (mgr), NULL;
987 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
988 return bt_mgrclose (mgr), NULL;
990 if( *amt < mgr->page_size )
991 return bt_mgrclose (mgr), NULL;
995 // clear out latch manager locks
996 // and rest of pages to round out segment
998 memset(latchmgr, 0, mgr->page_size);
1001 while( last <= ((MIN_lvl + 1 + nlatchpage) | mgr->poolmask) ) {
1003 pwrite(mgr->idx, latchmgr, mgr->page_size, last << mgr->page_bits);
1005 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
1006 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
1007 return bt_mgrclose (mgr), NULL;
1008 if( *amt < mgr->page_size )
1009 return bt_mgrclose (mgr), NULL;
1016 flag = PROT_READ | PROT_WRITE;
1017 mgr->latchmgr = mmap (0, mgr->page_size, flag, MAP_SHARED, mgr->idx, ALLOC_page * mgr->page_size);
1018 if( mgr->latchmgr == MAP_FAILED )
1019 return bt_mgrclose (mgr), NULL;
1020 mgr->latchsets = (BtLatchSet *)mmap (0, mgr->latchmgr->nlatchpage * mgr->page_size, flag, MAP_SHARED, mgr->idx, LATCH_page * mgr->page_size);
1021 if( mgr->latchsets == MAP_FAILED )
1022 return bt_mgrclose (mgr), NULL;
1024 flag = PAGE_READWRITE;
1025 mgr->halloc = CreateFileMapping(mgr->idx, NULL, flag, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size, NULL);
1027 return bt_mgrclose (mgr), NULL;
1029 flag = FILE_MAP_WRITE;
1030 mgr->latchmgr = MapViewOfFile(mgr->halloc, flag, 0, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size);
1031 if( !mgr->latchmgr )
1032 return GetLastError(), bt_mgrclose (mgr), NULL;
1034 mgr->latchsets = (void *)((char *)mgr->latchmgr + LATCH_page * mgr->page_size);
1040 VirtualFree (latchmgr, 0, MEM_RELEASE);
1045 // open BTree access method
1046 // based on buffer manager
1048 BtDb *bt_open (BtMgr *mgr)
1050 BtDb *bt = malloc (sizeof(*bt));
1052 memset (bt, 0, sizeof(*bt));
1055 bt->mem = malloc (3 *mgr->page_size);
1057 bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
1059 bt->frame = (BtPage)bt->mem;
1060 bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
1061 bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
1063 memset (bt->zero, 0, mgr->page_size);
1067 // compare two keys, returning > 0, = 0, or < 0
1068 // as the comparison value
1070 int keycmp (BtKey key1, unsigned char *key2, uint len2)
1072 uint len1 = key1->len;
1075 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
1088 // find segment in pool
1089 // must be called with hashslot idx locked
1090 // return NULL if not there
1091 // otherwise return node
1093 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
1098 // compute start of hash chain in pool
1100 if( slot = bt->mgr->hash[idx] )
1101 pool = bt->mgr->pool + slot;
1105 page_no &= ~bt->mgr->poolmask;
1107 while( pool->basepage != page_no )
1108 if( pool = pool->hashnext )
1116 // add segment to hash table
1118 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
1123 pool->hashprev = pool->hashnext = NULL;
1124 pool->basepage = page_no & ~bt->mgr->poolmask;
1127 if( slot = bt->mgr->hash[idx] ) {
1128 node = bt->mgr->pool + slot;
1129 pool->hashnext = node;
1130 node->hashprev = pool;
1133 bt->mgr->hash[idx] = pool->slot;
1136 // find best segment to evict from buffer pool
1138 BtPool *bt_findlru (BtDb *bt, uint hashslot)
1140 unsigned long long int target = ~0LL;
1141 BtPool *pool = NULL, *node;
1146 node = bt->mgr->pool + hashslot;
1148 // scan pool entries under hash table slot
1153 if( node->lru > target )
1157 } while( node = node->hashnext );
1162 // map new buffer pool segment to virtual memory
1164 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
1166 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
1167 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
1171 flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
1172 pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED, bt->mgr->idx, off);
1173 if( pool->map == MAP_FAILED )
1174 return bt->err = BTERR_map;
1176 // clear out madvise issued bits
1177 memset (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8) / 8), 0, (bt->mgr->poolmask + 8)/8);
1179 flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
1180 pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
1182 return bt->err = BTERR_map;
1184 flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
1185 pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1187 return bt->err = BTERR_map;
1192 // calculate page within pool
1194 BtPage bt_page (BtDb *bt, BtPool *pool, uid page_no)
1196 uint subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1199 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1202 uint idx = subpage / 8;
1203 uint bit = subpage % 8;
1205 if( ~((bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] >> bit) & 1 ) {
1206 madvise (page, bt->mgr->page_size, MADV_WILLNEED);
1207 (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] |= 1 << bit;
1216 void bt_unpinpool (BtPool *pool)
1219 __sync_fetch_and_add(&pool->pin, -1);
1221 _InterlockedDecrement16 (&pool->pin);
1225 // find or place requested page in segment-pool
1226 // return pool table entry, incrementing pin
1228 BtPool *bt_pinpool(BtDb *bt, uid page_no)
1230 BtPool *pool, *node, *next;
1231 uint slot, idx, victim;
1233 // lock hash table chain
1235 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1236 bt_spinreadlock (&bt->mgr->latch[idx]);
1238 // look up in hash table
1240 if( pool = bt_findpool(bt, page_no, idx) ) {
1242 __sync_fetch_and_add(&pool->pin, 1);
1244 _InterlockedIncrement16 (&pool->pin);
1246 bt_spinreleaseread (&bt->mgr->latch[idx]);
1251 // upgrade to write lock
1253 bt_spinreleaseread (&bt->mgr->latch[idx]);
1254 bt_spinwritelock (&bt->mgr->latch[idx]);
1256 // try to find page in pool with write lock
1258 if( pool = bt_findpool(bt, page_no, idx) ) {
1260 __sync_fetch_and_add(&pool->pin, 1);
1262 _InterlockedIncrement16 (&pool->pin);
1264 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1269 // allocate a new pool node
1270 // and add to hash table
1273 slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
1275 slot = _InterlockedIncrement16 (&bt->mgr->poolcnt) - 1;
1278 if( ++slot < bt->mgr->poolmax ) {
1279 pool = bt->mgr->pool + slot;
1282 if( bt_mapsegment(bt, pool, page_no) )
1285 bt_linkhash(bt, pool, page_no, idx);
1287 __sync_fetch_and_add(&pool->pin, 1);
1289 _InterlockedIncrement16 (&pool->pin);
1291 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1295 // pool table is full
1296 // find best pool entry to evict
1299 __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
1301 _InterlockedDecrement16 (&bt->mgr->poolcnt);
1306 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
1308 victim = _InterlockedIncrement (&bt->mgr->evicted) - 1;
1310 victim %= bt->mgr->hashsize;
1312 // try to get write lock
1313 // skip entry if not obtained
1315 if( !bt_spinwritetry (&bt->mgr->latch[victim]) )
1318 // if pool entry is empty
1319 // or any pages are pinned
1322 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
1323 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1327 // unlink victim pool node from hash table
1329 if( node = pool->hashprev )
1330 node->hashnext = pool->hashnext;
1331 else if( node = pool->hashnext )
1332 bt->mgr->hash[victim] = node->slot;
1334 bt->mgr->hash[victim] = 0;
1336 if( node = pool->hashnext )
1337 node->hashprev = pool->hashprev;
1339 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1341 // remove old file mapping
1343 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1345 FlushViewOfFile(pool->map, 0);
1346 UnmapViewOfFile(pool->map);
1347 CloseHandle(pool->hmap);
1351 // create new pool mapping
1352 // and link into hash table
1354 if( bt_mapsegment(bt, pool, page_no) )
1357 bt_linkhash(bt, pool, page_no, idx);
1359 __sync_fetch_and_add(&pool->pin, 1);
1361 _InterlockedIncrement16 (&pool->pin);
1363 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1368 // place write, read, or parent lock on requested page_no.
1370 void bt_lockpage(BtLock mode, BtLatchSet *set)
1374 bt_readlock (set->readwr);
1377 bt_writelock (set->readwr);
1380 bt_readlock (set->access);
1383 bt_writelock (set->access);
1386 bt_writelock (set->parent);
1391 // remove write, read, or parent lock on requested page
1393 void bt_unlockpage(BtLock mode, BtLatchSet *set)
1397 bt_releaseread (set->readwr);
1400 bt_releasewrite (set->readwr);
1403 bt_releaseread (set->access);
1406 bt_releasewrite (set->access);
1409 bt_releasewrite (set->parent);
1414 // allocate a new page and write page into it
1416 uid bt_newpage(BtDb *bt, BtPage page)
1424 // lock allocation page
1426 bt_spinwritelock(bt->mgr->latchmgr->lock);
1428 // use empty chain first
1429 // else allocate empty page
1431 if( new_page = bt_getid(bt->mgr->latchmgr->alloc[1].right) ) {
1432 if( pool = bt_pinpool (bt, new_page) )
1433 pmap = bt_page (bt, pool, new_page);
1436 bt_putid(bt->mgr->latchmgr->alloc[1].right, bt_getid(pmap->right));
1437 bt_unpinpool (pool);
1440 new_page = bt_getid(bt->mgr->latchmgr->alloc->right);
1441 bt_putid(bt->mgr->latchmgr->alloc->right, new_page+1);
1445 if ( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1446 return bt->err = BTERR_wrt, 0;
1448 // if writing first page of pool block, zero last page in the block
1450 if ( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1452 // use zero buffer to write zeros
1453 memset(bt->zero, 0, bt->mgr->page_size);
1454 if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1455 return bt->err = BTERR_wrt, 0;
1458 // bring new page into pool and copy page.
1459 // this will extend the file into the new pages.
1461 if( pool = bt_pinpool (bt, new_page) )
1462 pmap = bt_page (bt, pool, new_page);
1466 memcpy(pmap, page, bt->mgr->page_size);
1467 bt_unpinpool (pool);
1469 // unlock allocation latch and return new page no
1471 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1475 // find slot in page for given key at a given level
1477 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1479 uint diff, higher = bt->page->cnt, low = 1, slot;
1483 // make stopper key an infinite fence value
1484 // by setting the good flag
1486 if( bt_getid (bt->page->right) )
1491 // low is the next candidate.
1492 // loop ends when they meet
1494 // if good, higher is already
1495 // tested as .ge. the given key.
1497 while( diff = higher - low ) {
1498 slot = low + ( diff >> 1 );
1499 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1502 higher = slot, good++;
1505 // return zero if key is on right link page
1507 return good ? higher : 0;
1510 // find and load page at given level for given key
1511 // leave page rd or wr locked as requested
1513 int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, uint lock)
1515 uid page_no = ROOT_page, prevpage = 0;
1516 BtLatchSet *set, *prevset;
1517 uint drill = 0xff, slot;
1518 uint mode, prevmode;
1522 // start at root of btree and drill down
1527 // determine lock mode of drill level
1528 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1530 bt->set = bt_pinlatch (bt, page_no);
1531 bt->page_no = page_no;
1533 // pin page contents
1535 if( bt->pool = bt_pinpool (bt, page_no) )
1536 bt->page = bt_page (bt, bt->pool, page_no);
1540 // obtain access lock using lock chaining with Access mode
1542 if( page_no > ROOT_page )
1543 bt_lockpage(BtLockAccess, bt->set);
1545 // release & unpin parent page
1548 bt_unlockpage(prevmode, prevset);
1549 bt_unpinlatch (prevset);
1550 bt_unpinpool (prevpool);
1554 // obtain read lock using lock chaining
1556 bt_lockpage(mode, bt->set);
1558 if( page_no > ROOT_page )
1559 bt_unlockpage(BtLockAccess, bt->set);
1561 // re-read and re-lock root after determining actual level of root
1563 if( bt->page->lvl != drill) {
1564 if ( bt->page_no != ROOT_page )
1565 return bt->err = BTERR_struct, 0;
1567 drill = bt->page->lvl;
1569 if( lock == BtLockWrite && drill == lvl ) {
1570 bt_unlockpage(mode, bt->set);
1571 bt_unpinlatch (bt->set);
1572 bt_unpinpool (bt->pool);
1577 // find key on page at this level
1578 // and descend to requested level
1580 if( slot = bt_findslot (bt, key, len) ) {
1582 return bt->parent = parent, slot;
1584 while( slotptr(bt->page, slot)->dead )
1585 if( slot++ < bt->page->cnt )
1588 page_no = bt_getid(bt->page->right);
1593 page_no = bt_getid(slotptr(bt->page, slot)->id);
1598 // or slide right into next page
1601 page_no = bt_getid(bt->page->right);
1605 // continue down / right using overlapping locks
1606 // to protect pages being split.
1609 prevpage = bt->page_no;
1610 prevpool = bt->pool;
1616 // return error on end of right chain
1618 bt->err = BTERR_struct;
1619 return 0; // return error
1622 // remove empty page from the B-tree
1623 // by pulling our right node left over ourselves
1625 // call with bt->page, etc, set to page's locked parent
1626 // returns with page locked.
1628 BTERR bt_mergeright (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no, uint lvl, uint slot)
1630 BtLatchSet *rset, *pset, *rpset;
1631 BtPool *rpool, *ppool, *rppool;
1632 BtPage rpage, ppage, rppage;
1633 uid right, parent, rparent;
1637 // cache node's parent page
1639 parent = bt->page_no;
1644 // lock and map our right page
1645 // it cannot be NULL because of the stopper
1646 // in the last right page
1648 bt_lockpage (BtLockWrite, set);
1650 // if we aren't dead yet
1655 if( right = bt_getid (page->right) )
1656 if( rpool = bt_pinpool (bt, right) )
1657 rpage = bt_page (bt, rpool, right);
1661 return bt->err = BTERR_struct;
1663 rset = bt_pinlatch (bt, right);
1665 // find our right neighbor
1667 if( ppage->act > 1 ) {
1668 for( idx = slot; idx++ < ppage->cnt; )
1669 if( !slotptr(ppage, idx)->dead )
1672 if( idx > ppage->cnt )
1673 return bt->err = BTERR_struct;
1675 // redirect right neighbor in parent to left node
1677 bt_putid(slotptr(ppage,idx)->id, page_no);
1680 // if parent has only our deleted page, e.g. no right neighbor
1681 // prepare to merge parent itself
1683 if( ppage->act == 1 ) {
1684 if( rparent = bt_getid (ppage->right) )
1685 if( rppool = bt_pinpool (bt, rparent) )
1686 rppage = bt_page (bt, rppool, rparent);
1690 return bt->err = BTERR_struct;
1692 rpset = bt_pinlatch (bt, rparent);
1693 bt_lockpage (BtLockWrite, rpset);
1695 // find our right neighbor on right parent page
1697 for( idx = 0; idx++ < rppage->cnt; )
1698 if( !slotptr(rppage, idx)->dead ) {
1699 bt_putid (slotptr(rppage, idx)->id, page_no);
1703 if( idx > rppage->cnt )
1704 return bt->err = BTERR_struct;
1707 // now that there are no more pointers to our right node
1708 // we can wait for delete lock on it
1710 bt_lockpage(BtLockDelete, rset);
1711 bt_lockpage(BtLockWrite, rset);
1713 // pull contents of right page into our empty page
1715 memcpy (page, rpage, bt->mgr->page_size);
1717 // ready to release right parent lock
1718 // now that we have a new page in place
1720 if( ppage->act == 1 ) {
1721 bt_unlockpage (BtLockWrite, rpset);
1722 bt_unpinlatch (rpset);
1723 bt_unpinpool (rppool);
1726 // add killed right block to free chain
1729 bt_spinwritelock(bt->mgr->latchmgr->lock);
1731 // store free chain in allocation page second right
1733 bt_putid(rpage->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1734 bt_putid(bt->mgr->latchmgr->alloc[1].right, right);
1736 // unlock latch mgr and right page
1738 bt_unlockpage(BtLockDelete, rset);
1739 bt_unlockpage(BtLockWrite, rset);
1740 bt_unpinlatch (rset);
1741 bt_unpinpool (rpool);
1743 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1745 // delete our obsolete fence key from our parent
1747 slotptr(ppage, slot)->dead = 1;
1750 // if our parent now empty
1751 // remove it from the tree
1753 if( ppage->act-- == 1 )
1754 if( bt_mergeleft (bt, ppage, ppool, pset, parent, lvl+1) )
1758 bt_unlockpage (BtLockWrite, pset);
1759 bt_unpinlatch (pset);
1760 bt_unpinpool (ppool);
1766 // remove empty page from the B-tree
1767 // try merging left first. If no left
1768 // sibling, then merge right.
1770 // call with page loaded and locked,
1771 // return with page locked.
1773 BTERR bt_mergeleft (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no, uint lvl)
1775 unsigned char fencekey[256], postkey[256];
1776 uint slot, idx, postfence = 0;
1777 BtLatchSet *lset, *pset;
1778 BtPool *lpool, *ppool;
1779 BtPage lpage, ppage;
1783 ptr = keyptr(page, page->cnt);
1784 memcpy(fencekey, ptr, ptr->len + 1);
1785 bt_unlockpage (BtLockWrite, set);
1787 // load and lock our parent
1790 if( !(slot = bt_loadpage (bt, fencekey+1, *fencekey, lvl+1, BtLockWrite)) )
1793 parent = bt->page_no;
1798 // wait until we are posted in our parent
1801 bt_unlockpage (BtLockWrite, pset);
1802 bt_unpinlatch (pset);
1803 bt_unpinpool (ppool);
1812 // find our left neighbor in our parent page
1814 for( idx = slot; --idx; )
1815 if( !slotptr(ppage, idx)->dead )
1818 // if no left neighbor, do right merge
1821 return bt_mergeright (bt, page, pool, set, page_no, lvl, slot);
1823 // lock and map our left neighbor's page
1825 left = bt_getid (slotptr(ppage, idx)->id);
1827 if( lpool = bt_pinpool (bt, left) )
1828 lpage = bt_page (bt, lpool, left);
1832 lset = bt_pinlatch (bt, left);
1833 bt_lockpage(BtLockWrite, lset);
1835 // wait until sibling is in our parent
1837 if( bt_getid (lpage->right) != page_no ) {
1838 bt_unlockpage (BtLockWrite, pset);
1839 bt_unpinlatch (pset);
1840 bt_unpinpool (ppool);
1841 bt_unlockpage (BtLockWrite, lset);
1842 bt_unpinlatch (lset);
1843 bt_unpinpool (lpool);
1852 // since our page will have no more pointers to it,
1853 // obtain Delete lock and wait for write locks to clear
1855 bt_lockpage(BtLockDelete, set);
1856 bt_lockpage(BtLockWrite, set);
1858 // if we aren't dead yet,
1859 // get ready for exit
1862 bt_unlockpage(BtLockDelete, set);
1863 bt_unlockpage(BtLockWrite, lset);
1864 bt_unpinlatch (lset);
1865 bt_unpinpool (lpool);
1869 // are we are the fence key for our parent?
1870 // if so, grab our old fence key
1872 if( postfence = slot == ppage->cnt ) {
1873 ptr = keyptr (ppage, ppage->cnt);
1874 memcpy(fencekey, ptr, ptr->len + 1);
1875 memset(slotptr(ppage, ppage->cnt), 0, sizeof(BtSlot));
1877 // clear out other dead slots
1879 while( --ppage->cnt )
1880 if( slotptr(ppage, ppage->cnt)->dead )
1881 memset(slotptr(ppage, ppage->cnt), 0, sizeof(BtSlot));
1885 ptr = keyptr (ppage, ppage->cnt);
1886 memcpy(postkey, ptr, ptr->len + 1);
1888 slotptr(ppage,slot)->dead = 1;
1893 // push our right neighbor pointer to our left
1895 memcpy (lpage->right, page->right, BtId);
1897 // add ourselves to free chain
1900 bt_spinwritelock(bt->mgr->latchmgr->lock);
1902 // store free chain in allocation page second right
1903 bt_putid(page->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1904 bt_putid(bt->mgr->latchmgr->alloc[1].right, page_no);
1906 // unlock latch mgr and pages
1908 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1909 bt_unlockpage(BtLockWrite, lset);
1910 bt_unpinlatch (lset);
1911 bt_unpinpool (lpool);
1913 // release our node's delete lock
1915 bt_unlockpage(BtLockDelete, set);
1918 bt_unlockpage (BtLockWrite, pset);
1919 bt_unpinpool (ppool);
1921 // do we need to post parent's fence key in its parent?
1923 if( !postfence || parent == ROOT_page ) {
1924 bt_unpinlatch (pset);
1929 // interlock parent fence post
1931 bt_lockpage (BtLockParent, pset);
1933 // load parent's parent page
1935 if( !(slot = bt_loadpage (bt, fencekey+1, *fencekey, lvl+2, BtLockWrite)) )
1938 if( !(slot = bt_cleanpage (bt, bt->page, *fencekey, slot)) )
1939 if( bt_splitpage (bt, bt->page, bt->pool, bt->set, bt->page_no) )
1946 page->min -= *postkey + 1;
1947 ((unsigned char *)page)[page->min] = *postkey;
1948 memcpy ((unsigned char *)page + page->min +1, postkey + 1, *postkey );
1949 slotptr(page, slot)->off = page->min;
1951 bt_unlockpage (BtLockParent, pset);
1952 bt_unpinlatch (pset);
1954 bt_unlockpage (BtLockWrite, bt->set);
1955 bt_unpinlatch (bt->set);
1956 bt_unpinpool (bt->pool);
1962 // find and delete key on page by marking delete flag bit
1963 // if page becomes empty, delete it from the btree
1965 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len)
1974 if( !(slot = bt_loadpage (bt, key, len, 0, BtLockWrite)) )
1977 page_no = bt->page_no;
1982 // if key is found delete it, otherwise ignore request
1984 ptr = keyptr(page, slot);
1986 if( bt->found = !keycmp (ptr, key, len) )
1987 if( bt->found = slotptr(page, slot)->dead == 0 ) {
1988 slotptr(page,slot)->dead = 1;
1989 if( slot < page->cnt )
1992 if( bt_mergeleft (bt, page, pool, set, page_no, 0) )
1996 bt_unlockpage(BtLockWrite, set);
1997 bt_unpinlatch (set);
1998 bt_unpinpool (pool);
2002 // find key in leaf level and return row-id
2004 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
2010 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
2011 ptr = keyptr(bt->page, slot);
2015 // if key exists, return row-id
2016 // otherwise return 0
2018 if( slot <= bt->page->cnt && !keycmp (ptr, key, len) )
2019 id = bt_getid(slotptr(bt->page,slot)->id);
2023 bt_unlockpage (BtLockRead, bt->set);
2024 bt_unpinlatch (bt->set);
2025 bt_unpinpool (bt->pool);
2029 // check page for space available,
2030 // clean if necessary and return
2031 // 0 - page needs splitting
2032 // >0 new slot value
2034 uint bt_cleanpage(BtDb *bt, BtPage page, uint amt, uint slot)
2036 uint nxt = bt->mgr->page_size;
2037 uint cnt = 0, idx = 0;
2038 uint max = page->cnt;
2042 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
2045 // skip cleanup if nothing to reclaim
2050 memcpy (bt->frame, page, bt->mgr->page_size);
2052 // skip page info and set rest of page to zero
2054 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
2058 // try cleaning up page first
2060 // always leave fence key in the array
2061 // otherwise, remove deleted key
2063 while( cnt++ < max ) {
2066 if( cnt < max && slotptr(bt->frame,cnt)->dead )
2071 key = keyptr(bt->frame, cnt);
2072 nxt -= key->len + 1;
2073 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2076 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
2077 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
2079 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2080 slotptr(page, idx)->off = nxt;
2086 // see if page has enough space now, or does it need splitting?
2088 if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
2094 // add key to current page
2095 // page must already be writelocked
2097 void bt_addkeytopage (BtDb *bt, BtPage page, uint slot, unsigned char *key, uint len, uid id, uint tod)
2101 // find next available dead slot and copy key onto page
2103 for( idx = slot; idx < page->cnt; idx++ )
2104 if( slotptr(page, idx)->dead )
2107 if( idx == page->cnt )
2112 // now insert key into array before slot
2115 *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
2117 page->min -= len + 1;
2118 ((unsigned char *)page)[page->min] = len;
2119 memcpy ((unsigned char *)page + page->min +1, key, len );
2121 bt_putid(slotptr(page,slot)->id, id);
2122 slotptr(page, slot)->off = page->min;
2123 slotptr(page, slot)->tod = tod;
2124 slotptr(page, slot)->dead = 0;
2127 BTERR bt_splitroot(BtDb *bt, unsigned char *leftkey, uid page_no2)
2129 uint nxt = bt->mgr->page_size;
2130 BtPage root = bt->page;
2133 // Obtain an empty page to use, and copy the current
2134 // root contents into it
2136 if( !(new_page = bt_newpage(bt, root)) )
2139 // preserve the page info at the bottom
2140 // and set rest to zero
2142 memset(root+1, 0, bt->mgr->page_size - sizeof(*root));
2144 // insert first key on newroot page
2146 nxt -= *leftkey + 1;
2147 memcpy ((unsigned char *)root + nxt, leftkey, *leftkey + 1);
2148 bt_putid(slotptr(root, 1)->id, new_page);
2149 slotptr(root, 1)->off = nxt;
2151 // insert second key (stopper key) on newroot page
2152 // and increase the root height
2155 *((unsigned char *)root + nxt) = 2;
2156 memset ((unsigned char *)root + nxt + 1, 0xff, 2);
2157 bt_putid(slotptr(root, 2)->id, page_no2);
2158 slotptr(root, 2)->off = nxt;
2160 bt_putid(root->right, 0);
2161 root->min = nxt; // reset lowest used offset and key count
2166 // release and unpin root (bt->page)
2168 bt_unlockpage(BtLockWrite, bt->set);
2169 bt_unpinlatch (bt->set);
2170 bt_unpinpool (bt->pool);
2174 // split already locked full node
2175 // return unlocked and unpinned.
2177 BTERR bt_splitpage (BtDb *bt, BtPage page, BtPool *pool, BtLatchSet *set, uid page_no)
2179 uint slot, cnt, idx, max, nxt = bt->mgr->page_size;
2180 unsigned char rightkey[256], leftkey[256];
2181 uint tod = time(NULL);
2182 uint lvl = page->lvl;
2186 // initialize frame buffer for right node
2188 memset (bt->frame, 0, bt->mgr->page_size);
2193 // split higher half of keys to bt->frame
2195 while( cnt++ < max ) {
2196 key = keyptr(page, cnt);
2197 nxt -= key->len + 1;
2198 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
2199 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
2200 if( !(slotptr(bt->frame, idx)->dead = slotptr(page, cnt)->dead) )
2202 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
2203 slotptr(bt->frame, idx)->off = nxt;
2206 // transfer right link node to new right node
2208 if( page_no > ROOT_page )
2209 memcpy (bt->frame->right, page->right, BtId);
2211 bt->frame->bits = bt->mgr->page_bits;
2212 bt->frame->min = nxt;
2213 bt->frame->cnt = idx;
2214 bt->frame->lvl = lvl;
2216 // get new free page and write right frame to it.
2218 if( !(new_page = bt_newpage(bt, bt->frame)) )
2221 // remember fence key for new right page to add
2222 // as right sibling to the left node
2224 key = keyptr(bt->frame, idx);
2225 memcpy (rightkey, key, key->len + 1);
2227 // update lower keys to continue in old page
2229 memcpy (bt->frame, page, bt->mgr->page_size);
2230 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
2231 nxt = bt->mgr->page_size;
2237 // assemble page of smaller keys
2238 // to remain in the old page
2240 while( cnt++ < max / 2 ) {
2241 key = keyptr(bt->frame, cnt);
2242 nxt -= key->len + 1;
2243 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2244 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
2245 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
2247 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2248 slotptr(page, idx)->off = nxt;
2251 // finalize left page and save fence key
2253 memcpy(leftkey, key, key->len + 1);
2257 // link new right page
2259 bt_putid (page->right, new_page);
2261 // if current page is the root page, split it
2263 if( page_no == ROOT_page )
2264 return bt_splitroot (bt, leftkey, new_page);
2266 // obtain ParentModification lock for current page
2268 bt_lockpage (BtLockParent, set);
2270 // release wr lock on our page.
2271 // this will keep out another SMO
2273 bt_unlockpage (BtLockWrite, set);
2275 // insert key for old page (lower keys)
2277 if( bt_insertkey (bt, leftkey + 1, *leftkey, page_no, tod, lvl + 1) )
2280 // switch old parent key from us to our right page
2282 if( bt_insertkey (bt, rightkey + 1, *rightkey, new_page, tod, lvl + 1) )
2287 bt_unlockpage (BtLockParent, set);
2288 bt_unpinlatch (set);
2289 bt_unpinpool (pool);
2293 // Insert new key into the btree at given level.
2295 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod, uint lvl)
2302 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
2303 ptr = keyptr(bt->page, slot);
2307 bt->err = BTERR_ovflw;
2311 // if key already exists, update id and return
2315 if( !keycmp (ptr, key, len) ) {
2316 if( slotptr(page, slot)->dead )
2318 slotptr(page, slot)->dead = 0;
2319 slotptr(page, slot)->tod = tod;
2320 bt_putid(slotptr(page,slot)->id, id);
2321 bt_unlockpage(BtLockWrite, bt->set);
2322 bt_unpinlatch (bt->set);
2323 bt_unpinpool (bt->pool);
2327 // check if page has enough space
2329 if( slot = bt_cleanpage (bt, bt->page, len, slot) )
2332 if( bt_splitpage (bt, bt->page, bt->pool, bt->set, bt->page_no) )
2336 bt_addkeytopage (bt, bt->page, slot, key, len, id, tod);
2338 bt_unlockpage (BtLockWrite, bt->set);
2339 bt_unpinlatch (bt->set);
2340 bt_unpinpool (bt->pool);
2344 // cache page of keys into cursor and return starting slot for given key
2346 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2350 // cache page for retrieval
2351 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
2352 memcpy (bt->cursor, bt->page, bt->mgr->page_size);
2354 bt->cursor_page = bt->page_no;
2356 bt_unlockpage(BtLockRead, bt->set);
2357 bt_unpinlatch (bt->set);
2358 bt_unpinpool (bt->pool);
2362 // return next slot for cursor page
2363 // or slide cursor right into next page
2365 uint bt_nextkey (BtDb *bt, uint slot)
2373 right = bt_getid(bt->cursor->right);
2374 while( slot++ < bt->cursor->cnt )
2375 if( slotptr(bt->cursor,slot)->dead )
2377 else if( right || (slot < bt->cursor->cnt) )
2385 bt->cursor_page = right;
2386 if( pool = bt_pinpool (bt, right) )
2387 page = bt_page (bt, pool, right);
2391 set = bt_pinlatch (bt, right);
2392 bt_lockpage(BtLockRead, set);
2394 memcpy (bt->cursor, page, bt->mgr->page_size);
2396 bt_unlockpage(BtLockRead, set);
2397 bt_unpinlatch (set);
2398 bt_unpinpool (pool);
2405 BtKey bt_key(BtDb *bt, uint slot)
2407 return keyptr(bt->cursor, slot);
2410 uid bt_uid(BtDb *bt, uint slot)
2412 return bt_getid(slotptr(bt->cursor,slot)->id);
2415 uint bt_tod(BtDb *bt, uint slot)
2417 return slotptr(bt->cursor,slot)->tod;
2423 void bt_latchaudit (BtDb *bt)
2425 ushort idx, hashidx;
2432 for( idx = 1; idx < bt->mgr->latchmgr->latchdeployed; idx++ ) {
2433 set = bt->mgr->latchsets + idx;
2435 fprintf(stderr, "latchset %d pinned\n", idx);
2440 for( hashidx = 0; hashidx < bt->mgr->latchmgr->latchhash; hashidx++ ) {
2441 if( *(uint *)bt->mgr->latchmgr->table[hashidx].latch )
2442 fprintf(stderr, "latchmgr locked\n");
2443 if( idx = bt->mgr->latchmgr->table[hashidx].slot ) do {
2444 set = bt->mgr->latchsets + idx;
2445 if( set->hash != hashidx )
2446 fprintf(stderr, "latchset %d wrong hashidx\n", idx);
2448 fprintf(stderr, "latchset %d pinned\n", idx);
2449 } while( idx = set->next );
2451 page_no = bt_getid(bt->mgr->latchmgr->alloc[1].right);
2454 fprintf(stderr, "free: %.6x\n", (uint)page_no);
2455 pool = bt_pinpool (bt, page_no);
2456 page = bt_page (bt, pool, page_no);
2457 page_no = bt_getid(page->right);
2458 bt_unpinpool (pool);
2470 // standalone program to index file of keys
2471 // then list them onto std-out
2474 void *index_file (void *arg)
2476 uint __stdcall index_file (void *arg)
2479 int line = 0, found = 0, cnt = 0;
2480 uid next, page_no = LEAF_page; // start on first page of leaves
2481 unsigned char key[256];
2482 ThreadArg *args = arg;
2483 int ch, len = 0, slot;
2492 bt = bt_open (args->mgr);
2495 switch(args->type | 0x20)
2498 fprintf(stderr, "started latch mgr audit\n");
2500 fprintf(stderr, "finished latch mgr audit\n");
2504 fprintf(stderr, "started indexing for %s\n", args->infile);
2505 if( in = fopen (args->infile, "rb") )
2506 while( ch = getc(in), ch != EOF )
2511 if( args->num == 1 )
2512 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2514 else if( args->num )
2515 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2517 if( bt_insertkey (bt, key, len, line, *tod, 0) )
2518 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2521 else if( len < 255 )
2523 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
2527 fprintf(stderr, "started deleting keys for %s\n", args->infile);
2528 if( in = fopen (args->infile, "rb") )
2529 while( ch = getc(in), ch != EOF )
2533 if( args->num == 1 )
2534 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2536 else if( args->num )
2537 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2539 if( bt_deletekey (bt, key, len) )
2540 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2543 else if( len < 255 )
2545 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2549 fprintf(stderr, "started finding keys for %s\n", args->infile);
2550 if( in = fopen (args->infile, "rb") )
2551 while( ch = getc(in), ch != EOF )
2555 if( args->num == 1 )
2556 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2558 else if( args->num )
2559 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2561 if( bt_findkey (bt, key, len) )
2564 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2567 else if( len < 255 )
2569 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2575 fprintf(stderr, "started reading\n");
2577 if( slot = bt_startkey (bt, key, len) )
2580 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
2582 while( slot = bt_nextkey (bt, slot) ) {
2583 ptr = bt_key(bt, slot);
2584 fwrite (ptr->key, ptr->len, 1, stdout);
2585 fputc ('\n', stdout);
2591 fprintf(stderr, "started reading\n");
2594 if( pool = bt_pinpool (bt, page_no) )
2595 page = bt_page (bt, pool, page_no);
2598 set = bt_pinlatch (bt, page_no);
2599 bt_lockpage (BtLockRead, set);
2601 next = bt_getid (page->right);
2602 bt_unlockpage (BtLockRead, set);
2603 bt_unpinlatch (set);
2604 bt_unpinpool (pool);
2605 } while( page_no = next );
2607 cnt--; // remove stopper key
2608 fprintf(stderr, " Total keys read %d\n", cnt);
2620 typedef struct timeval timer;
2622 int main (int argc, char **argv)
2624 int idx, cnt, len, slot, err;
2625 int segsize, bits = 16;
2630 time_t start[1], stop[1];
2643 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]);
2644 fprintf (stderr, " where page_bits is the page size in bits\n");
2645 fprintf (stderr, " mapped_segments is the number of mmap segments in buffer pool\n");
2646 fprintf (stderr, " seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2647 fprintf (stderr, " line_numbers = 1 to append line numbers to keys\n");
2648 fprintf (stderr, " src_file1 thru src_filen are files of keys separated by newline\n");
2653 gettimeofday(&start, NULL);
2659 bits = atoi(argv[3]);
2662 poolsize = atoi(argv[4]);
2665 fprintf (stderr, "Warning: no mapped_pool\n");
2667 if( poolsize > 65535 )
2668 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2671 segsize = atoi(argv[5]);
2673 segsize = 4; // 16 pages per mmap segment
2676 num = atoi(argv[6]);
2680 threads = malloc (cnt * sizeof(pthread_t));
2682 threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2684 args = malloc (cnt * sizeof(ThreadArg));
2686 mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2689 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2695 for( idx = 0; idx < cnt; idx++ ) {
2696 args[idx].infile = argv[idx + 7];
2697 args[idx].type = argv[2][0];
2698 args[idx].mgr = mgr;
2699 args[idx].num = num;
2700 args[idx].idx = idx;
2702 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2703 fprintf(stderr, "Error creating thread %d\n", err);
2705 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2709 // wait for termination
2712 for( idx = 0; idx < cnt; idx++ )
2713 pthread_join (threads[idx], NULL);
2714 gettimeofday(&stop, NULL);
2715 real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2717 WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2719 for( idx = 0; idx < cnt; idx++ )
2720 CloseHandle(threads[idx]);
2723 real_time = 1000 * (*stop - *start);
2725 fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);