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]; // adoption of foster children
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:6; // level of page
178 unsigned char kill:1; // page is being deleted
179 unsigned char dirty:1; // page has deleted keys
180 unsigned char right[BtId]; // page number to right
181 BtSlot table[0]; // array of key slots
184 // The memory mapping pool table buffer manager entry
187 unsigned long long int lru; // number of times accessed
188 uid basepage; // mapped base page number
189 char *map; // mapped memory pointer
190 ushort slot; // slot index in this array
191 ushort pin; // mapped page pin counter
192 void *hashprev; // previous pool entry for the same hash idx
193 void *hashnext; // next pool entry for the same hash idx
199 // structure for latch manager on ALLOC_page
202 struct Page alloc[2]; // next & free page_nos in right ptr
203 BtSpinLatch lock[1]; // allocation area lite latch
204 ushort latchdeployed; // highest number of latch entries deployed
205 ushort nlatchpage; // number of latch pages at BT_latch
206 ushort latchtotal; // number of page latch entries
207 ushort latchhash; // number of latch hash table slots
208 ushort latchvictim; // next latch entry to examine
209 BtHashEntry table[0]; // the hash table
212 // The object structure for Btree access
215 uint page_size; // page size
216 uint page_bits; // page size in bits
217 uint seg_bits; // seg size in pages in bits
218 uint mode; // read-write mode
220 char *pooladvise; // bit maps for pool page advisements
225 ushort poolcnt; // highest page pool node in use
226 ushort poolmax; // highest page pool node allocated
227 ushort poolmask; // total number of pages in mmap segment - 1
228 ushort hashsize; // size of Hash Table for pool entries
229 volatile uint evicted; // last evicted hash table slot
230 ushort *hash; // pool index for hash entries
231 BtSpinLatch *latch; // latches for hash table slots
232 BtLatchMgr *latchmgr; // mapped latch page from allocation page
233 BtLatchSet *latchsets; // mapped latch set from latch pages
234 BtPool *pool; // memory pool page segments
236 HANDLE halloc; // allocation and latch table handle
241 BtMgr *mgr; // buffer manager for thread
242 BtPage cursor; // cached frame for start/next (never mapped)
243 BtPage frame; // spare frame for the page split (never mapped)
244 BtPage zero; // page frame for zeroes at end of file
245 BtPage page; // current page
246 uid page_no; // current page number
247 uid cursor_page; // current cursor page number
248 BtLatchSet *set; // current page latch set
249 BtPool *pool; // current page pool
250 unsigned char *mem; // frame, cursor, page memory buffer
251 int found; // last delete or insert was found
252 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, uint lvl, 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 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 // The b-tree pages are linked with next
310 // pointers to facilitate enumerators,
311 // and provide for concurrency.
313 // When to root page fills, it is split in two and
314 // the tree height is raised by a new root at page
315 // one with two keys.
317 // Deleted keys are marked with a dead bit until
318 // page cleanup The fence key for a node is always
319 // present, even after deletion and cleanup.
321 // Groups of pages called segments from the btree are optionally
322 // cached with a memory mapped pool. A hash table is used to keep
323 // track of the cached segments. This behaviour is controlled
324 // by the cache block size parameter to bt_open.
326 // To achieve maximum concurrency one page is locked at a time
327 // as the tree is traversed to find leaf key in question. The right
328 // page numbers are used in cases where the page is being split,
331 // Page 0 is dedicated to lock for new page extensions,
332 // and chains empty pages together for reuse.
334 // The ParentModification lock on a node is obtained to prevent resplitting
335 // or deleting a node before its fence is posted into its upper level.
337 // Empty pages are chained together through the ALLOC page and reused.
339 // Access macros to address slot and key values from the page
341 #define slotptr(page, slot) (page->table + slot-1)
342 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
344 void bt_putid(unsigned char *dest, uid id)
349 dest[i] = (unsigned char)id, id >>= 8;
352 uid bt_getid(unsigned char *src)
357 for( i = 0; i < BtId; i++ )
358 id <<= 8, id |= *src++;
365 // wait until write lock mode is clear
366 // and add 1 to the share count
368 void bt_spinreadlock(BtSpinLatch *latch)
373 // obtain latch mutex
375 if( __sync_fetch_and_or((ushort *)latch, Mutex) & Mutex )
378 if( prev = _InterlockedOr16((ushort *)latch, Mutex) & Mutex )
381 // see if exclusive request is granted or pending
383 if( prev = !(latch->exclusive | latch->pending) )
385 __sync_fetch_and_add((ushort *)latch, Share);
387 _InterlockedExchangeAdd16 ((ushort *)latch, Share);
391 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
393 _InterlockedAnd16((ushort *)latch, ~Mutex);
399 } while( sched_yield(), 1 );
401 } while( SwitchToThread(), 1 );
405 // wait for other read and write latches to relinquish
407 void bt_spinwritelock(BtSpinLatch *latch)
411 if( __sync_fetch_and_or((ushort *)latch, Mutex | Pending) & Mutex )
414 if( _InterlockedOr16((ushort *)latch, Mutex | Pending) & Mutex )
417 if( !(latch->share | latch->exclusive) ) {
419 __sync_fetch_and_or((ushort *)latch, Write);
420 __sync_fetch_and_and ((ushort *)latch, ~(Mutex | Pending));
422 _InterlockedOr16((ushort *)latch, Write);
423 _InterlockedAnd16((ushort *)latch, ~(Mutex | Pending));
429 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
431 _InterlockedAnd16((ushort *)latch, ~Mutex);
435 } while( sched_yield(), 1 );
437 } while( SwitchToThread(), 1 );
441 // try to obtain write lock
443 // return 1 if obtained,
446 int bt_spinwritetry(BtSpinLatch *latch)
451 if( prev = __sync_fetch_and_or((ushort *)latch, Mutex), prev & Mutex )
454 if( prev = _InterlockedOr16((ushort *)latch, Mutex), prev & Mutex )
457 // take write access if all bits are clear
461 __sync_fetch_and_or ((ushort *)latch, Write);
463 _InterlockedOr16((ushort *)latch, Write);
467 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
469 _InterlockedAnd16((ushort *)latch, ~Mutex);
476 void bt_spinreleasewrite(BtSpinLatch *latch)
479 __sync_fetch_and_and ((ushort *)latch, ~Write);
481 _InterlockedAnd16((ushort *)latch, ~Write);
485 // decrement reader count
487 void bt_spinreleaseread(BtSpinLatch *latch)
490 __sync_fetch_and_add((ushort *)latch, -Share);
492 _InterlockedExchangeAdd16 ((ushort *)latch, -Share);
496 void bt_readlock(BtLatch *latch)
499 pthread_rwlock_rdlock (latch->lock);
501 AcquireSRWLockShared (latch->srw);
505 // wait for other read and write latches to relinquish
507 void bt_writelock(BtLatch *latch)
510 pthread_rwlock_wrlock (latch->lock);
512 AcquireSRWLockExclusive (latch->srw);
516 // try to obtain write lock
518 // return 1 if obtained,
519 // 0 if already write or read locked
521 int bt_writetry(BtLatch *latch)
526 result = !pthread_rwlock_trywrlock (latch->lock);
528 result = TryAcquireSRWLockExclusive (latch->srw);
535 void bt_releasewrite(BtLatch *latch)
538 pthread_rwlock_unlock (latch->lock);
540 ReleaseSRWLockExclusive (latch->srw);
544 // decrement reader count
546 void bt_releaseread(BtLatch *latch)
549 pthread_rwlock_unlock (latch->lock);
551 ReleaseSRWLockShared (latch->srw);
555 void bt_initlockset (BtLatchSet *set, int reuse)
558 pthread_rwlockattr_t rwattr[1];
561 pthread_rwlock_destroy (set->readwr->lock);
562 pthread_rwlock_destroy (set->access->lock);
563 pthread_rwlock_destroy (set->parent->lock);
566 pthread_rwlockattr_init (rwattr);
567 pthread_rwlockattr_setkind_np (rwattr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
568 pthread_rwlockattr_setpshared (rwattr, PTHREAD_PROCESS_SHARED);
570 pthread_rwlock_init (set->readwr->lock, rwattr);
571 pthread_rwlock_init (set->access->lock, rwattr);
572 pthread_rwlock_init (set->parent->lock, rwattr);
573 pthread_rwlockattr_destroy (rwattr);
575 InitializeSRWLock (set->readwr->srw);
576 InitializeSRWLock (set->access->srw);
577 InitializeSRWLock (set->parent->srw);
581 // link latch table entry into latch hash table
583 void bt_latchlink (BtDb *bt, ushort hashidx, ushort victim, uid page_no)
585 BtLatchSet *set = bt->mgr->latchsets + victim;
587 if( set->next = bt->mgr->latchmgr->table[hashidx].slot )
588 bt->mgr->latchsets[set->next].prev = victim;
590 bt->mgr->latchmgr->table[hashidx].slot = victim;
591 set->page_no = page_no;
598 void bt_unpinlatch (BtLatchSet *set)
601 __sync_fetch_and_add(&set->pin, -1);
603 _InterlockedDecrement16 (&set->pin);
607 // find existing latchset or inspire new one
608 // return with latchset pinned
610 BtLatchSet *bt_pinlatch (BtDb *bt, uid page_no)
612 ushort hashidx = page_no % bt->mgr->latchmgr->latchhash;
613 ushort slot, avail = 0, victim, idx;
616 // obtain read lock on hash table entry
618 bt_spinreadlock(bt->mgr->latchmgr->table[hashidx].latch);
620 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
622 set = bt->mgr->latchsets + slot;
623 if( page_no == set->page_no )
625 } while( slot = set->next );
629 __sync_fetch_and_add(&set->pin, 1);
631 _InterlockedIncrement16 (&set->pin);
635 bt_spinreleaseread (bt->mgr->latchmgr->table[hashidx].latch);
640 // try again, this time with write lock
642 bt_spinwritelock(bt->mgr->latchmgr->table[hashidx].latch);
644 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
646 set = bt->mgr->latchsets + slot;
647 if( page_no == set->page_no )
649 if( !set->pin && !avail )
651 } while( slot = set->next );
653 // found our entry, or take over an unpinned one
655 if( slot || (slot = avail) ) {
656 set = bt->mgr->latchsets + slot;
658 __sync_fetch_and_add(&set->pin, 1);
660 _InterlockedIncrement16 (&set->pin);
662 set->page_no = page_no;
663 bt_spinreleasewrite(bt->mgr->latchmgr->table[hashidx].latch);
667 // see if there are any unused entries
669 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, 1) + 1;
671 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchdeployed);
674 if( victim < bt->mgr->latchmgr->latchtotal ) {
675 set = bt->mgr->latchsets + victim;
677 __sync_fetch_and_add(&set->pin, 1);
679 _InterlockedIncrement16 (&set->pin);
681 bt_initlockset (set, 0);
682 bt_latchlink (bt, hashidx, victim, page_no);
683 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
688 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, -1);
690 victim = _InterlockedDecrement16 (&bt->mgr->latchmgr->latchdeployed);
692 // find and reuse previous lock entry
696 victim = __sync_fetch_and_add(&bt->mgr->latchmgr->latchvictim, 1);
698 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchvictim) - 1;
700 // we don't use slot zero
702 if( victim %= bt->mgr->latchmgr->latchtotal )
703 set = bt->mgr->latchsets + victim;
707 // take control of our slot
708 // from other threads
710 if( set->pin || !bt_spinwritetry (set->busy) )
715 // try to get write lock on hash chain
716 // skip entry if not obtained
717 // or has outstanding locks
719 if( !bt_spinwritetry (bt->mgr->latchmgr->table[idx].latch) ) {
720 bt_spinreleasewrite (set->busy);
725 bt_spinreleasewrite (set->busy);
726 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
730 // unlink our available victim from its hash chain
733 bt->mgr->latchsets[set->prev].next = set->next;
735 bt->mgr->latchmgr->table[idx].slot = set->next;
738 bt->mgr->latchsets[set->next].prev = set->prev;
740 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
742 __sync_fetch_and_add(&set->pin, 1);
744 _InterlockedIncrement16 (&set->pin);
746 bt_initlockset (set, 1);
747 bt_latchlink (bt, hashidx, victim, page_no);
748 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
749 bt_spinreleasewrite (set->busy);
754 void bt_mgrclose (BtMgr *mgr)
759 // release mapped pages
760 // note that slot zero is never used
762 for( slot = 1; slot < mgr->poolmax; slot++ ) {
763 pool = mgr->pool + slot;
766 munmap (pool->map, (mgr->poolmask+1) << mgr->page_bits);
769 FlushViewOfFile(pool->map, 0);
770 UnmapViewOfFile(pool->map);
771 CloseHandle(pool->hmap);
777 munmap (mgr->latchsets, mgr->latchmgr->nlatchpage * mgr->page_size);
778 munmap (mgr->latchmgr, mgr->page_size);
780 FlushViewOfFile(mgr->latchmgr, 0);
781 UnmapViewOfFile(mgr->latchmgr);
782 CloseHandle(mgr->halloc);
789 free (mgr->pooladvise);
792 FlushFileBuffers(mgr->idx);
793 CloseHandle(mgr->idx);
794 GlobalFree (mgr->pool);
795 GlobalFree (mgr->hash);
796 GlobalFree (mgr->latch);
801 // close and release memory
803 void bt_close (BtDb *bt)
810 VirtualFree (bt->mem, 0, MEM_RELEASE);
815 // open/create new btree buffer manager
817 // call with file_name, BT_openmode, bits in page size (e.g. 16),
818 // size of mapped page pool (e.g. 8192)
820 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
822 uint lvl, attr, cacheblk, last, slot, idx;
823 uint nlatchpage, latchhash;
824 BtLatchMgr *latchmgr;
832 SYSTEM_INFO sysinfo[1];
835 // determine sanity of page size and buffer pool
837 if( bits > BT_maxbits )
839 else if( bits < BT_minbits )
843 return NULL; // must have buffer pool
846 mgr = calloc (1, sizeof(BtMgr));
848 mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
851 return free(mgr), NULL;
853 cacheblk = 4096; // minimum mmap segment size for unix
856 mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
857 attr = FILE_ATTRIBUTE_NORMAL;
858 mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
860 if( mgr->idx == INVALID_HANDLE_VALUE )
861 return GlobalFree(mgr), NULL;
863 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
864 GetSystemInfo(sysinfo);
865 cacheblk = sysinfo->dwAllocationGranularity;
869 latchmgr = malloc (BT_maxpage);
872 // read minimum page size to get root info
874 if( size = lseek (mgr->idx, 0L, 2) ) {
875 if( pread(mgr->idx, latchmgr, BT_minpage, 0) == BT_minpage )
876 bits = latchmgr->alloc->bits;
878 return free(mgr), free(latchmgr), NULL;
879 } else if( mode == BT_ro )
880 return free(latchmgr), bt_mgrclose (mgr), NULL;
882 latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
883 size = GetFileSize(mgr->idx, amt);
886 if( !ReadFile(mgr->idx, (char *)latchmgr, BT_minpage, amt, NULL) )
887 return bt_mgrclose (mgr), NULL;
888 bits = latchmgr->alloc->bits;
889 } else if( mode == BT_ro )
890 return bt_mgrclose (mgr), NULL;
893 mgr->page_size = 1 << bits;
894 mgr->page_bits = bits;
896 mgr->poolmax = poolmax;
899 if( cacheblk < mgr->page_size )
900 cacheblk = mgr->page_size;
902 // mask for partial memmaps
904 mgr->poolmask = (cacheblk >> bits) - 1;
906 // see if requested size of pages per memmap is greater
908 if( (1 << segsize) > mgr->poolmask )
909 mgr->poolmask = (1 << segsize) - 1;
913 while( (1 << mgr->seg_bits) <= mgr->poolmask )
916 mgr->hashsize = hashsize;
919 mgr->pool = calloc (poolmax, sizeof(BtPool));
920 mgr->hash = calloc (hashsize, sizeof(ushort));
921 mgr->latch = calloc (hashsize, sizeof(BtSpinLatch));
922 mgr->pooladvise = calloc (poolmax, (mgr->poolmask + 8) / 8);
924 mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * sizeof(BtPool));
925 mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
926 mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtSpinLatch));
932 // initialize an empty b-tree with latch page, root page, page of leaves
933 // and page(s) of latches
935 memset (latchmgr, 0, 1 << bits);
936 nlatchpage = BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1;
937 bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
938 latchmgr->alloc->bits = mgr->page_bits;
940 latchmgr->nlatchpage = nlatchpage;
941 latchmgr->latchtotal = nlatchpage * (mgr->page_size / sizeof(BtLatchSet));
943 // initialize latch manager
945 latchhash = (mgr->page_size - sizeof(BtLatchMgr)) / sizeof(BtHashEntry);
947 // size of hash table = total number of latchsets
949 if( latchhash > latchmgr->latchtotal )
950 latchhash = latchmgr->latchtotal;
952 latchmgr->latchhash = latchhash;
955 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
956 return bt_mgrclose (mgr), NULL;
958 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
959 return bt_mgrclose (mgr), NULL;
961 if( *amt < mgr->page_size )
962 return bt_mgrclose (mgr), NULL;
965 memset (latchmgr, 0, 1 << bits);
966 latchmgr->alloc->bits = mgr->page_bits;
968 for( lvl=MIN_lvl; lvl--; ) {
969 slotptr(latchmgr->alloc, 1)->off = mgr->page_size - 3;
970 bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
971 key = keyptr(latchmgr->alloc, 1);
972 key->len = 2; // create stopper key
975 latchmgr->alloc->min = mgr->page_size - 3;
976 latchmgr->alloc->lvl = lvl;
977 latchmgr->alloc->cnt = 1;
978 latchmgr->alloc->act = 1;
980 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
981 return bt_mgrclose (mgr), NULL;
983 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
984 return bt_mgrclose (mgr), NULL;
986 if( *amt < mgr->page_size )
987 return bt_mgrclose (mgr), NULL;
991 // clear out latch manager locks
992 // and rest of pages to round out segment
994 memset(latchmgr, 0, mgr->page_size);
997 while( last <= ((MIN_lvl + 1 + nlatchpage) | mgr->poolmask) ) {
999 pwrite(mgr->idx, latchmgr, mgr->page_size, last << mgr->page_bits);
1001 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
1002 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
1003 return bt_mgrclose (mgr), NULL;
1004 if( *amt < mgr->page_size )
1005 return bt_mgrclose (mgr), NULL;
1012 flag = PROT_READ | PROT_WRITE;
1013 mgr->latchmgr = mmap (0, mgr->page_size, flag, MAP_SHARED, mgr->idx, ALLOC_page * mgr->page_size);
1014 if( mgr->latchmgr == MAP_FAILED )
1015 return bt_mgrclose (mgr), NULL;
1016 mgr->latchsets = (BtLatchSet *)mmap (0, mgr->latchmgr->nlatchpage * mgr->page_size, flag, MAP_SHARED, mgr->idx, LATCH_page * mgr->page_size);
1017 if( mgr->latchsets == MAP_FAILED )
1018 return bt_mgrclose (mgr), NULL;
1020 flag = PAGE_READWRITE;
1021 mgr->halloc = CreateFileMapping(mgr->idx, NULL, flag, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size, NULL);
1023 return bt_mgrclose (mgr), NULL;
1025 flag = FILE_MAP_WRITE;
1026 mgr->latchmgr = MapViewOfFile(mgr->halloc, flag, 0, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size);
1027 if( !mgr->latchmgr )
1028 return GetLastError(), bt_mgrclose (mgr), NULL;
1030 mgr->latchsets = (void *)((char *)mgr->latchmgr + LATCH_page * mgr->page_size);
1036 VirtualFree (latchmgr, 0, MEM_RELEASE);
1041 // open BTree access method
1042 // based on buffer manager
1044 BtDb *bt_open (BtMgr *mgr)
1046 BtDb *bt = malloc (sizeof(*bt));
1048 memset (bt, 0, sizeof(*bt));
1051 bt->mem = malloc (3 *mgr->page_size);
1053 bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
1055 bt->frame = (BtPage)bt->mem;
1056 bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
1057 bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
1059 memset (bt->zero, 0, mgr->page_size);
1063 // compare two keys, returning > 0, = 0, or < 0
1064 // as the comparison value
1066 int keycmp (BtKey key1, unsigned char *key2, uint len2)
1068 uint len1 = key1->len;
1071 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
1084 // find segment in pool
1085 // must be called with hashslot idx locked
1086 // return NULL if not there
1087 // otherwise return node
1089 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
1094 // compute start of hash chain in pool
1096 if( slot = bt->mgr->hash[idx] )
1097 pool = bt->mgr->pool + slot;
1101 page_no &= ~bt->mgr->poolmask;
1103 while( pool->basepage != page_no )
1104 if( pool = pool->hashnext )
1112 // add segment to hash table
1114 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
1119 pool->hashprev = pool->hashnext = NULL;
1120 pool->basepage = page_no & ~bt->mgr->poolmask;
1123 if( slot = bt->mgr->hash[idx] ) {
1124 node = bt->mgr->pool + slot;
1125 pool->hashnext = node;
1126 node->hashprev = pool;
1129 bt->mgr->hash[idx] = pool->slot;
1132 // find best segment to evict from buffer pool
1134 BtPool *bt_findlru (BtDb *bt, uint hashslot)
1136 unsigned long long int target = ~0LL;
1137 BtPool *pool = NULL, *node;
1142 node = bt->mgr->pool + hashslot;
1144 // scan pool entries under hash table slot
1149 if( node->lru > target )
1153 } while( node = node->hashnext );
1158 // map new buffer pool segment to virtual memory
1160 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
1162 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
1163 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
1167 flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
1168 pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED, bt->mgr->idx, off);
1169 if( pool->map == MAP_FAILED )
1170 return bt->err = BTERR_map;
1172 // clear out madvise issued bits
1173 memset (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8) / 8), 0, (bt->mgr->poolmask + 8)/8);
1175 flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
1176 pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
1178 return bt->err = BTERR_map;
1180 flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
1181 pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1183 return bt->err = BTERR_map;
1188 // calculate page within pool
1190 BtPage bt_page (BtDb *bt, BtPool *pool, uid page_no)
1192 uint subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1195 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1198 uint idx = subpage / 8;
1199 uint bit = subpage % 8;
1201 if( ~((bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] >> bit) & 1 ) {
1202 madvise (page, bt->mgr->page_size, MADV_WILLNEED);
1203 (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] |= 1 << bit;
1212 void bt_unpinpool (BtPool *pool)
1215 __sync_fetch_and_add(&pool->pin, -1);
1217 _InterlockedDecrement16 (&pool->pin);
1221 // find or place requested page in segment-pool
1222 // return pool table entry, incrementing pin
1224 BtPool *bt_pinpool(BtDb *bt, uid page_no)
1226 BtPool *pool, *node, *next;
1227 uint slot, idx, victim;
1229 // lock hash table chain
1231 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1232 bt_spinreadlock (&bt->mgr->latch[idx]);
1234 // look up in hash table
1236 if( pool = bt_findpool(bt, page_no, idx) ) {
1238 __sync_fetch_and_add(&pool->pin, 1);
1240 _InterlockedIncrement16 (&pool->pin);
1242 bt_spinreleaseread (&bt->mgr->latch[idx]);
1247 // upgrade to write lock
1249 bt_spinreleaseread (&bt->mgr->latch[idx]);
1250 bt_spinwritelock (&bt->mgr->latch[idx]);
1252 // try to find page in pool with write lock
1254 if( pool = bt_findpool(bt, page_no, idx) ) {
1256 __sync_fetch_and_add(&pool->pin, 1);
1258 _InterlockedIncrement16 (&pool->pin);
1260 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1265 // allocate a new pool node
1266 // and add to hash table
1269 slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
1271 slot = _InterlockedIncrement16 (&bt->mgr->poolcnt) - 1;
1274 if( ++slot < bt->mgr->poolmax ) {
1275 pool = bt->mgr->pool + slot;
1278 if( bt_mapsegment(bt, pool, page_no) )
1281 bt_linkhash(bt, pool, page_no, idx);
1283 __sync_fetch_and_add(&pool->pin, 1);
1285 _InterlockedIncrement16 (&pool->pin);
1287 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1291 // pool table is full
1292 // find best pool entry to evict
1295 __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
1297 _InterlockedDecrement16 (&bt->mgr->poolcnt);
1302 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
1304 victim = _InterlockedIncrement (&bt->mgr->evicted) - 1;
1306 victim %= bt->mgr->hashsize;
1308 // try to get write lock
1309 // skip entry if not obtained
1311 if( !bt_spinwritetry (&bt->mgr->latch[victim]) )
1314 // if pool entry is empty
1315 // or any pages are pinned
1318 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
1319 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1323 // unlink victim pool node from hash table
1325 if( node = pool->hashprev )
1326 node->hashnext = pool->hashnext;
1327 else if( node = pool->hashnext )
1328 bt->mgr->hash[victim] = node->slot;
1330 bt->mgr->hash[victim] = 0;
1332 if( node = pool->hashnext )
1333 node->hashprev = pool->hashprev;
1335 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1337 // remove old file mapping
1339 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1341 FlushViewOfFile(pool->map, 0);
1342 UnmapViewOfFile(pool->map);
1343 CloseHandle(pool->hmap);
1347 // create new pool mapping
1348 // and link into hash table
1350 if( bt_mapsegment(bt, pool, page_no) )
1353 bt_linkhash(bt, pool, page_no, idx);
1355 __sync_fetch_and_add(&pool->pin, 1);
1357 _InterlockedIncrement16 (&pool->pin);
1359 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1364 // place write, read, or parent lock on requested page_no.
1366 void bt_lockpage(BtLock mode, BtLatchSet *set)
1370 bt_readlock (set->readwr);
1373 bt_writelock (set->readwr);
1376 bt_readlock (set->access);
1379 bt_writelock (set->access);
1382 bt_writelock (set->parent);
1387 // remove write, read, or parent lock on requested page
1389 void bt_unlockpage(BtLock mode, BtLatchSet *set)
1393 bt_releaseread (set->readwr);
1396 bt_releasewrite (set->readwr);
1399 bt_releaseread (set->access);
1402 bt_releasewrite (set->access);
1405 bt_releasewrite (set->parent);
1410 // allocate a new page and write page into it
1412 uid bt_newpage(BtDb *bt, BtPage page)
1420 // lock allocation page
1422 bt_spinwritelock(bt->mgr->latchmgr->lock);
1424 // use empty chain first
1425 // else allocate empty page
1427 if( new_page = bt_getid(bt->mgr->latchmgr->alloc[1].right) ) {
1428 if( pool = bt_pinpool (bt, new_page) )
1429 pmap = bt_page (bt, pool, new_page);
1432 bt_putid(bt->mgr->latchmgr->alloc[1].right, bt_getid(pmap->right));
1433 bt_unpinpool (pool);
1436 new_page = bt_getid(bt->mgr->latchmgr->alloc->right);
1437 bt_putid(bt->mgr->latchmgr->alloc->right, new_page+1);
1441 if ( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1442 return bt->err = BTERR_wrt, 0;
1444 // if writing first page of pool block, zero last page in the block
1446 if ( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1448 // use zero buffer to write zeros
1449 memset(bt->zero, 0, bt->mgr->page_size);
1450 if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1451 return bt->err = BTERR_wrt, 0;
1454 // bring new page into pool and copy page.
1455 // this will extend the file into the new pages.
1457 if( pool = bt_pinpool (bt, new_page) )
1458 pmap = bt_page (bt, pool, new_page);
1462 memcpy(pmap, page, bt->mgr->page_size);
1463 bt_unpinpool (pool);
1465 // unlock allocation latch and return new page no
1467 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1471 // find slot in page for given key at a given level
1473 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1475 uint diff, higher = bt->page->cnt, low = 1, slot;
1478 // make stopper key an infinite fence value
1480 if( bt_getid (bt->page->right) )
1485 // low is the next candidate, higher is already
1486 // tested as .ge. the given key, loop ends when they meet
1488 while( diff = higher - low ) {
1489 slot = low + ( diff >> 1 );
1490 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1493 higher = slot, good++;
1496 // return zero if key is on right link page
1498 return good ? higher : 0;
1501 // find and load page at given level for given key
1502 // leave page rd or wr locked as requested
1504 int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, uint lock)
1506 uid page_no = ROOT_page, prevpage = 0;
1507 BtLatchSet *set, *prevset;
1508 uint drill = 0xff, slot;
1509 uint mode, prevmode;
1512 // start at root of btree and drill down
1517 // determine lock mode of drill level
1518 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1520 bt->set = bt_pinlatch (bt, page_no);
1521 bt->page_no = page_no;
1523 // pin page contents
1525 if( bt->pool = bt_pinpool (bt, page_no) )
1526 bt->page = bt_page (bt, bt->pool, page_no);
1530 // obtain access lock using lock chaining with Access mode
1532 if( page_no > ROOT_page )
1533 bt_lockpage(BtLockAccess, bt->set);
1535 // release & unpin parent page
1538 bt_unlockpage(prevmode, prevset);
1539 bt_unpinlatch (prevset);
1540 bt_unpinpool (prevpool);
1544 // obtain read lock using lock chaining
1546 bt_lockpage(mode, bt->set);
1548 if( page_no > ROOT_page )
1549 bt_unlockpage(BtLockAccess, bt->set);
1551 // re-read and re-lock root after determining actual level of root
1553 if( bt->page->lvl != drill) {
1554 if ( bt->page_no != ROOT_page )
1555 return bt->err = BTERR_struct, 0;
1557 drill = bt->page->lvl;
1559 if( lock == BtLockWrite && drill == lvl ) {
1560 bt_unlockpage(mode, bt->set);
1561 bt_unpinlatch (bt->set);
1562 bt_unpinpool (bt->pool);
1567 // find key on page at this level
1568 // and descend to requested level
1570 if( !bt->page->kill && (slot = bt_findslot (bt, key, len)) ) {
1574 while( slotptr(bt->page, slot)->dead )
1575 if( slot++ < bt->page->cnt )
1578 page_no = bt_getid(bt->page->right);
1582 page_no = bt_getid(slotptr(bt->page, slot)->id);
1586 // or slide right into next page
1587 // (slide left from deleted page)
1590 page_no = bt_getid(bt->page->right);
1592 // continue down / right using overlapping locks
1593 // to protect pages being killed or split.
1596 prevpage = bt->page_no;
1597 prevpool = bt->pool;
1602 // return error on end of right chain
1604 bt->err = BTERR_struct;
1605 return 0; // return error
1608 // find and delete key on page by marking delete flag bit
1609 // when page becomes empty, delete it
1611 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl)
1613 unsigned char lowerkey[256], higherkey[256];
1614 BtLatchSet *rset, *set;
1615 BtPool *pool, *rpool;
1621 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1622 ptr = keyptr(bt->page, slot);
1626 // if key is found delete it, otherwise ignore request
1628 if( bt->found = !keycmp (ptr, key, len) )
1629 if( bt->found = slotptr(bt->page, slot)->dead == 0 ) {
1630 slotptr(bt->page,slot)->dead = 1;
1631 if( slot < bt->page->cnt )
1632 bt->page->dirty = 1;
1636 // return if page is not empty, or it has no right sibling
1638 right = bt_getid(bt->page->right);
1639 page_no = bt->page_no;
1643 if( !right || bt->page->act ) {
1644 bt_unlockpage(BtLockWrite, set);
1645 bt_unpinlatch (set);
1646 bt_unpinpool (pool);
1650 // obtain Parent lock over write lock
1652 bt_lockpage(BtLockParent, set);
1654 // keep copy of key to delete
1656 ptr = keyptr(bt->page, bt->page->cnt);
1657 memcpy(lowerkey, ptr, ptr->len + 1);
1659 // lock and map right page
1661 if( rpool = bt_pinpool (bt, right) )
1662 rpage = bt_page (bt, rpool, right);
1666 rset = bt_pinlatch (bt, right);
1667 bt_lockpage(BtLockWrite, rset);
1669 // pull contents of next page into current empty page
1671 memcpy (bt->page, rpage, bt->mgr->page_size);
1673 // keep copy of key to update
1675 ptr = keyptr(rpage, rpage->cnt);
1676 memcpy(higherkey, ptr, ptr->len + 1);
1678 // Mark right page as deleted and point it to left page
1679 // until we can post updates at higher level.
1681 bt_putid(rpage->right, page_no);
1685 bt_unlockpage(BtLockWrite, rset);
1686 bt_unlockpage(BtLockWrite, set);
1688 // delete old lower key to consolidated node
1690 if( bt_deletekey (bt, lowerkey + 1, *lowerkey, lvl + 1) )
1693 // redirect higher key directly to consolidated node
1695 tod = (uint)time(NULL);
1697 if( bt_insertkey (bt, higherkey+1, *higherkey, lvl + 1, page_no, tod) )
1700 // add killed right block to free chain
1703 bt_spinwritelock(bt->mgr->latchmgr->lock);
1705 // store free chain in allocation page second right
1706 bt_putid(rpage->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1707 bt_putid(bt->mgr->latchmgr->alloc[1].right, right);
1709 // unlock latch mgr and unpin right page
1711 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1712 bt_unpinlatch (rset);
1713 bt_unpinpool (rpool);
1715 // remove ParentModify lock
1717 bt_unlockpage(BtLockParent, set);
1718 bt_unpinlatch (set);
1719 bt_unpinpool (pool);
1723 // find key in leaf level and return row-id
1725 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1731 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1732 ptr = keyptr(bt->page, slot);
1736 // if key exists, return row-id
1737 // otherwise return 0
1739 if( ptr->len == len && !memcmp (ptr->key, key, len) )
1740 id = bt_getid(slotptr(bt->page,slot)->id);
1744 bt_unlockpage (BtLockRead, bt->set);
1745 bt_unpinlatch (bt->set);
1746 bt_unpinpool (bt->pool);
1750 // check page for space available,
1751 // clean if necessary and return
1752 // =0 - page needs splitting
1753 // >0 - go ahead at returned slot
1755 uint bt_cleanpage(BtDb *bt, uint amt, uint slot)
1757 uint nxt = bt->mgr->page_size;
1758 BtPage page = bt->page;
1759 uint cnt = 0, idx = 0;
1760 uint max = page->cnt;
1764 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1767 // skip cleanup if nothing to reclaim
1772 memcpy (bt->frame, page, bt->mgr->page_size);
1774 // skip page info and set rest of page to zero
1776 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1780 // always leave fence key in list
1782 while( cnt++ < max ) {
1785 else if( cnt < max && slotptr(bt->frame,cnt)->dead )
1789 key = keyptr(bt->frame, cnt);
1790 nxt -= key->len + 1;
1791 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1794 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1795 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1797 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1798 slotptr(page, idx)->off = nxt;
1803 if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1809 // split the root and raise the height of the btree
1811 BTERR bt_splitroot(BtDb *bt, unsigned char *newkey, unsigned char *oldkey, uid page_no2)
1813 uint nxt = bt->mgr->page_size;
1814 BtPage root = bt->page;
1817 // Obtain an empty page to use, and copy the current
1818 // root contents into it which is the lower half of
1821 if( !(new_page = bt_newpage(bt, root)) )
1824 // preserve the page info at the bottom
1825 // and set rest to zero
1827 memset(root+1, 0, bt->mgr->page_size - sizeof(*root));
1829 // insert first key on newroot page
1832 memcpy ((unsigned char *)root + nxt, newkey, *newkey + 1);
1833 bt_putid(slotptr(root, 1)->id, new_page);
1834 slotptr(root, 1)->off = nxt;
1836 // insert second key on newroot page
1837 // and increase the root height
1840 memcpy ((unsigned char *)root + nxt, oldkey, *oldkey + 1);
1841 bt_putid(slotptr(root, 2)->id, page_no2);
1842 slotptr(root, 2)->off = nxt;
1844 bt_putid(root->right, 0);
1845 root->min = nxt; // reset lowest used offset and key count
1850 // release and unpin root (bt->page)
1852 bt_unlockpage(BtLockWrite, bt->set);
1853 bt_unpinlatch (bt->set);
1854 bt_unpinpool (bt->pool);
1858 // split already locked full node
1861 BTERR bt_splitpage (BtDb *bt)
1863 uint cnt = 0, idx = 0, max, nxt = bt->mgr->page_size;
1864 unsigned char oldkey[256], lowerkey[256];
1865 uid page_no = bt->page_no, right;
1866 BtLatchSet *nset, *set = bt->set;
1867 BtPool *pool = bt->pool;
1868 BtPage page = bt->page;
1869 uint lvl = page->lvl;
1874 // split higher half of keys to bt->frame
1875 // the last key (fence key) might be dead
1877 tod = (uint)time(NULL);
1879 memset (bt->frame, 0, bt->mgr->page_size);
1880 max = (int)page->cnt;
1884 while( cnt++ < max ) {
1885 key = keyptr(page, cnt);
1886 nxt -= key->len + 1;
1887 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
1888 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
1889 if( !(slotptr(bt->frame, idx)->dead = slotptr(page, cnt)->dead) )
1891 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
1892 slotptr(bt->frame, idx)->off = nxt;
1895 // remember existing fence key for new page to the right
1897 memcpy (oldkey, key, key->len + 1);
1899 bt->frame->bits = bt->mgr->page_bits;
1900 bt->frame->min = nxt;
1901 bt->frame->cnt = idx;
1902 bt->frame->lvl = lvl;
1906 if( page_no > ROOT_page ) {
1907 right = bt_getid (page->right);
1908 bt_putid(bt->frame->right, right);
1911 // get new free page and write frame to it.
1913 if( !(new_page = bt_newpage(bt, bt->frame)) )
1916 // update lower keys to continue in old page
1918 memcpy (bt->frame, page, bt->mgr->page_size);
1919 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1920 nxt = bt->mgr->page_size;
1925 // assemble page of smaller keys
1926 // (they're all active keys)
1928 while( cnt++ < max / 2 ) {
1929 key = keyptr(bt->frame, cnt);
1930 nxt -= key->len + 1;
1931 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1932 memcpy(slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1933 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1934 slotptr(page, idx)->off = nxt;
1938 // remember fence key for old page
1940 memcpy(lowerkey, key, key->len + 1);
1941 bt_putid(page->right, new_page);
1945 // if current page is the root page, split it
1947 if( page_no == ROOT_page )
1948 return bt_splitroot (bt, lowerkey, oldkey, new_page);
1950 // obtain Parent/Write locks
1951 // for left and right node pages
1953 nset = bt_pinlatch (bt, new_page);
1955 bt_lockpage (BtLockParent, nset);
1956 bt_lockpage (BtLockParent, set);
1958 // release wr lock on left page
1959 // (keep the SMO in sequence)
1961 bt_unlockpage (BtLockWrite, set);
1963 // insert new fence for reformulated left block
1965 if( bt_insertkey (bt, lowerkey+1, *lowerkey, lvl + 1, page_no, tod) )
1968 // fix old fence for newly allocated right block page
1970 if( bt_insertkey (bt, oldkey+1, *oldkey, lvl + 1, new_page, tod) )
1973 // release Parent locks
1975 bt_unlockpage (BtLockParent, nset);
1976 bt_unlockpage (BtLockParent, set);
1977 bt_unpinlatch (nset);
1978 bt_unpinlatch (set);
1979 bt_unpinpool (pool);
1983 // Insert new key into the btree at requested level.
1984 // Level zero pages are leaf pages. Page is unlocked at exit.
1986 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod)
1993 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1994 ptr = keyptr(bt->page, slot);
1998 bt->err = BTERR_ovflw;
2002 // if key already exists, update id and return
2006 if( bt->found = !keycmp (ptr, key, len) ) {
2007 slotptr(page, slot)->dead = 0;
2008 slotptr(page, slot)->tod = tod;
2009 bt_putid(slotptr(page,slot)->id, id);
2010 bt_unlockpage(BtLockWrite, bt->set);
2011 bt_unpinlatch(bt->set);
2012 bt_unpinpool (bt->pool);
2016 // check if page has enough space
2018 if( slot = bt_cleanpage (bt, len, slot) )
2021 if( bt_splitpage (bt) )
2025 // calculate next available slot and copy key into page
2027 page->min -= len + 1; // reset lowest used offset
2028 ((unsigned char *)page)[page->min] = len;
2029 memcpy ((unsigned char *)page + page->min +1, key, len );
2031 for( idx = slot; idx < page->cnt; idx++ )
2032 if( slotptr(page, idx)->dead )
2035 // now insert key into array before slot
2036 // preserving the fence slot
2038 if( idx == page->cnt )
2044 *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
2046 bt_putid(slotptr(page,slot)->id, id);
2047 slotptr(page, slot)->off = page->min;
2048 slotptr(page, slot)->tod = tod;
2049 slotptr(page, slot)->dead = 0;
2051 bt_unlockpage (BtLockWrite, bt->set);
2052 bt_unpinlatch (bt->set);
2053 bt_unpinpool (bt->pool);
2057 // cache page of keys into cursor and return starting slot for given key
2059 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2063 // cache page for retrieval
2064 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
2065 memcpy (bt->cursor, bt->page, bt->mgr->page_size);
2066 bt->cursor_page = bt->page_no;
2067 bt_unlockpage(BtLockRead, bt->set);
2068 bt_unpinlatch (bt->set);
2069 bt_unpinpool (bt->pool);
2073 // return next slot for cursor page
2074 // or slide cursor right into next page
2076 uint bt_nextkey (BtDb *bt, uint slot)
2083 right = bt_getid(bt->cursor->right);
2084 while( slot++ < bt->cursor->cnt )
2085 if( slotptr(bt->cursor,slot)->dead )
2087 else if( right || (slot < bt->cursor->cnt))
2095 bt->cursor_page = right;
2097 if( pool = bt_pinpool (bt, right) )
2098 page = bt_page (bt, pool, right);
2102 bt->set = bt_pinlatch (bt, right);
2103 bt_lockpage(BtLockRead, bt->set);
2105 memcpy (bt->cursor, page, bt->mgr->page_size);
2107 bt_unlockpage(BtLockRead, bt->set);
2108 bt_unpinlatch (bt->set);
2109 bt_unpinpool (pool);
2116 BtKey bt_key(BtDb *bt, uint slot)
2118 return keyptr(bt->cursor, slot);
2121 uid bt_uid(BtDb *bt, uint slot)
2123 return bt_getid(slotptr(bt->cursor,slot)->id);
2126 uint bt_tod(BtDb *bt, uint slot)
2128 return slotptr(bt->cursor,slot)->tod;
2133 void bt_latchaudit (BtDb *bt)
2135 ushort idx, hashidx;
2142 for( idx = 1; idx < bt->mgr->latchmgr->latchdeployed; idx++ ) {
2143 set = bt->mgr->latchsets + idx;
2144 if( *(ushort *)set->readwr || *(ushort *)set->access || *(ushort *)set->parent ) {
2145 fprintf(stderr, "latchset %d locked for page %6x\n", idx, set->page_no);
2146 *(ushort *)set->readwr = 0;
2147 *(ushort *)set->access = 0;
2148 *(ushort *)set->parent = 0;
2151 fprintf(stderr, "latchset %d pinned\n", idx);
2156 for( hashidx = 0; hashidx < bt->mgr->latchmgr->latchhash; hashidx++ ) {
2157 if( *(uint *)bt->mgr->latchmgr->table[hashidx].latch )
2158 fprintf(stderr, "latchmgr locked\n");
2159 if( idx = bt->mgr->latchmgr->table[hashidx].slot ) do {
2160 set = bt->mgr->latchsets + idx;
2161 if( *(uint *)set->readwr || *(ushort *)set->access || *(ushort *)set->parent )
2162 fprintf(stderr, "latchset %d locked\n", idx);
2163 if( set->hash != hashidx )
2164 fprintf(stderr, "latchset %d wrong hashidx\n", idx);
2166 fprintf(stderr, "latchset %d pinned\n", idx);
2167 } while( idx = set->next );
2169 page_no = bt_getid(bt->mgr->latchmgr->alloc[1].right);
2172 fprintf(stderr, "free: %.6x\n", (uint)page_no);
2173 pool = bt_pinpool (bt, page_no);
2174 page = bt_page (bt, pool, page_no);
2175 page_no = bt_getid(page->right);
2176 bt_unpinpool (pool);
2188 // standalone program to index file of keys
2189 // then list them onto std-out
2192 void *index_file (void *arg)
2194 uint __stdcall index_file (void *arg)
2197 int line = 0, found = 0, cnt = 0;
2198 uid next, page_no = LEAF_page; // start on first page of leaves
2199 unsigned char key[256];
2200 ThreadArg *args = arg;
2201 int ch, len = 0, slot;
2209 bt = bt_open (args->mgr);
2212 switch(args->type | 0x20)
2215 fprintf(stderr, "started latch mgr audit\n");
2217 fprintf(stderr, "finished latch mgr audit\n");
2221 fprintf(stderr, "started indexing for %s\n", args->infile);
2222 if( in = fopen (args->infile, "rb") )
2223 while( ch = getc(in), ch != EOF )
2228 if( args->num == 1 )
2229 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2231 else if( args->num )
2232 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2234 if( bt_insertkey (bt, key, len, 0, line, *tod) )
2235 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2238 else if( len < 255 )
2240 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
2244 fprintf(stderr, "started deleting keys for %s\n", args->infile);
2245 if( in = fopen (args->infile, "rb") )
2246 while( ch = getc(in), ch != EOF )
2250 if( args->num == 1 )
2251 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2253 else if( args->num )
2254 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2256 if( bt_deletekey (bt, key, len, 0) )
2257 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2260 else if( len < 255 )
2262 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2266 fprintf(stderr, "started finding keys for %s\n", args->infile);
2267 if( in = fopen (args->infile, "rb") )
2268 while( ch = getc(in), ch != EOF )
2272 if( args->num == 1 )
2273 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2275 else if( args->num )
2276 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2278 if( bt_findkey (bt, key, len) )
2281 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2284 else if( len < 255 )
2286 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2292 fprintf(stderr, "started reading\n");
2294 if( slot = bt_startkey (bt, key, len) )
2297 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
2299 while( slot = bt_nextkey (bt, slot) ) {
2300 ptr = bt_key(bt, slot);
2301 fwrite (ptr->key, ptr->len, 1, stdout);
2302 fputc ('\n', stdout);
2308 fprintf(stderr, "started reading\n");
2311 if( bt->pool = bt_pinpool (bt, page_no) )
2312 page = bt_page (bt, bt->pool, page_no);
2315 bt->set = bt_pinlatch (bt, page_no);
2316 bt_lockpage (BtLockRead, bt->set);
2318 next = bt_getid (page->right);
2319 bt_unlockpage (BtLockRead, bt->set);
2320 bt_unpinlatch (bt->set);
2321 bt_unpinpool (bt->pool);
2322 } while( page_no = next );
2324 cnt--; // remove stopper key
2325 fprintf(stderr, " Total keys read %d\n", cnt);
2337 typedef struct timeval timer;
2339 int main (int argc, char **argv)
2341 int idx, cnt, len, slot, err;
2342 int segsize, bits = 16;
2347 time_t start[1], stop[1];
2360 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]);
2361 fprintf (stderr, " where page_bits is the page size in bits\n");
2362 fprintf (stderr, " mapped_segments is the number of mmap segments in buffer pool\n");
2363 fprintf (stderr, " seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2364 fprintf (stderr, " line_numbers = 1 to append line numbers to keys\n");
2365 fprintf (stderr, " src_file1 thru src_filen are files of keys separated by newline\n");
2370 gettimeofday(&start, NULL);
2376 bits = atoi(argv[3]);
2379 poolsize = atoi(argv[4]);
2382 fprintf (stderr, "Warning: no mapped_pool\n");
2384 if( poolsize > 65535 )
2385 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2388 segsize = atoi(argv[5]);
2390 segsize = 4; // 16 pages per mmap segment
2393 num = atoi(argv[6]);
2397 threads = malloc (cnt * sizeof(pthread_t));
2399 threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2401 args = malloc (cnt * sizeof(ThreadArg));
2403 mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2406 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2412 for( idx = 0; idx < cnt; idx++ ) {
2413 args[idx].infile = argv[idx + 7];
2414 args[idx].type = argv[2][0];
2415 args[idx].mgr = mgr;
2416 args[idx].num = num;
2417 args[idx].idx = idx;
2419 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2420 fprintf(stderr, "Error creating thread %d\n", err);
2422 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2426 // wait for termination
2429 for( idx = 0; idx < cnt; idx++ )
2430 pthread_join (threads[idx], NULL);
2431 gettimeofday(&stop, NULL);
2432 real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2434 WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2436 for( idx = 0; idx < cnt; idx++ )
2437 CloseHandle(threads[idx]);
2440 real_time = 1000 * (*stop - *start);
2442 fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);