1 // btree version threads2h pthread rw lock/SRW version
2 // with fixed bt_deletekey code
5 // author: karl malbrain, malbrain@cal.berkeley.edu
8 This work, including the source code, documentation
9 and related data, is placed into the public domain.
11 The orginal author is Karl Malbrain.
13 THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY
14 OF ANY KIND, NOT EVEN THE IMPLIED WARRANTY OF
15 MERCHANTABILITY. THE AUTHOR OF THIS SOFTWARE,
16 ASSUMES _NO_ RESPONSIBILITY FOR ANY CONSEQUENCE
17 RESULTING FROM THE USE, MODIFICATION, OR
18 REDISTRIBUTION OF THIS SOFTWARE.
21 // Please see the project home page for documentation
22 // code.google.com/p/high-concurrency-btree
24 #define _FILE_OFFSET_BITS 64
25 #define _LARGEFILE64_SOURCE
41 #define WIN32_LEAN_AND_MEAN
55 typedef unsigned long long uid;
58 typedef unsigned long long off64_t;
59 typedef unsigned short ushort;
60 typedef unsigned int uint;
63 #define BT_latchtable 128 // number of latch manager slots
65 #define BT_ro 0x6f72 // ro
66 #define BT_rw 0x7772 // rw
68 #define BT_maxbits 24 // maximum page size in bits
69 #define BT_minbits 9 // minimum page size in bits
70 #define BT_minpage (1 << BT_minbits) // minimum page size
71 #define BT_maxpage (1 << BT_maxbits) // maximum page size
74 There are five lock types for each node in three independent sets:
75 1. (set 1) AccessIntent: Sharable. Going to Read the node. Incompatible with NodeDelete.
76 2. (set 1) NodeDelete: Exclusive. About to release the node. Incompatible with AccessIntent.
77 3. (set 2) ReadLock: Sharable. Read the node. Incompatible with WriteLock.
78 4. (set 2) WriteLock: Exclusive. Modify the node. Incompatible with ReadLock and other WriteLocks.
79 5. (set 3) ParentModification: Exclusive. Change the node's parent keys. Incompatible with another ParentModification.
90 // mode & definition for latch implementation
92 // exclusive is set for write access
93 // share is count of read accessors
94 // grant write lock when share == 0
96 volatile typedef struct {
97 unsigned char mutex[1];
98 unsigned char exclusive:1;
99 unsigned char pending:1;
103 // hash table entries
106 BtSpinLatch latch[1];
107 volatile ushort slot; // Latch table entry at head of chain
110 // latch manager table structure
114 pthread_rwlock_t lock[1];
121 BtLatch readwr[1]; // read/write page lock
122 BtLatch access[1]; // Access Intent/Page delete
123 BtLatch parent[1]; // Posting of fence key in parent
124 BtSpinLatch busy[1]; // slot is being moved between chains
125 volatile ushort next; // next entry in hash table chain
126 volatile ushort prev; // prev entry in hash table chain
127 volatile ushort pin; // number of outstanding locks
128 volatile ushort hash; // hash slot entry is under
129 volatile uid page_no; // latch set page number
132 // Define the length of the page and key pointers
136 // Page key slot definition.
138 // If BT_maxbits is 15 or less, you can save 4 bytes
139 // for each key stored by making the first two uints
140 // into ushorts. You can also save 4 bytes by removing
141 // the tod field from the key.
143 // Keys are marked dead, but remain on the page until
144 // it cleanup is called. The fence key (highest key) for
145 // the page is always present, even after cleanup.
148 uint off:BT_maxbits; // page offset for key start
149 uint dead:1; // set for deleted key
150 uint tod; // time-stamp for key
151 unsigned char id[BtId]; // id associated with key
154 // The key structure occupies space at the upper end of
155 // each page. It's a length byte followed by the value
160 unsigned char key[1];
163 // The first part of an index page.
164 // It is immediately followed
165 // by the BtSlot array of keys.
167 typedef struct BtPage_ {
168 uint cnt; // count of keys in page
169 uint act; // count of active keys
170 uint min; // next key offset
171 unsigned char bits:7; // page size in bits
172 unsigned char free:1; // page is on free list
173 unsigned char lvl:6; // level of page
174 unsigned char kill:1; // page is being killed
175 unsigned char dirty:1; // page has deleted keys
176 unsigned char right[BtId]; // page number to right
179 // The memory mapping pool table buffer manager entry
182 unsigned long long int lru; // number of times accessed
183 uid basepage; // mapped base page number
184 char *map; // mapped memory pointer
185 ushort slot; // slot index in this array
186 ushort pin; // mapped page pin counter
187 void *hashprev; // previous pool entry for the same hash idx
188 void *hashnext; // next pool entry for the same hash idx
190 HANDLE hmap; // Windows memory mapping handle
194 // The loadpage interface object
197 uid page_no; // current page number
198 BtPage page; // current page pointer
199 BtPool *pool; // current page pool
200 BtLatchSet *latch; // current page latch set
203 // structure for latch manager on ALLOC_page
206 struct BtPage_ alloc[2]; // next & free page_nos in right ptr
207 BtSpinLatch lock[1]; // allocation area lite latch
208 ushort latchdeployed; // highest number of latch entries deployed
209 ushort nlatchpage; // number of latch pages at BT_latch
210 ushort latchtotal; // number of page latch entries
211 ushort latchhash; // number of latch hash table slots
212 ushort latchvictim; // next latch entry to examine
213 BtHashEntry table[0]; // the hash table
216 // The object structure for Btree access
219 uint page_size; // page size
220 uint page_bits; // page size in bits
221 uint seg_bits; // seg size in pages in bits
222 uint mode; // read-write mode
228 ushort poolcnt; // highest page pool node in use
229 ushort poolmax; // highest page pool node allocated
230 ushort poolmask; // total number of pages in mmap segment - 1
231 ushort hashsize; // size of Hash Table for pool entries
232 volatile uint evicted; // last evicted hash table slot
233 ushort *hash; // pool index for hash entries
234 BtSpinLatch *latch; // latches for hash table slots
235 BtLatchMgr *latchmgr; // mapped latch page from allocation page
236 BtLatchSet *latchsets; // mapped latch set from latch pages
237 BtPool *pool; // memory pool page segments
239 HANDLE halloc; // allocation and latch table handle
244 BtMgr *mgr; // buffer manager for thread
245 BtPage cursor; // cached frame for start/next (never mapped)
246 BtPage frame; // spare frame for the page split (never mapped)
247 BtPage zero; // page frame for zeroes at end of file
248 uid cursor_page; // current cursor page number
249 unsigned char *mem; // frame, cursor, page memory buffer
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, uint lvl, uid id, uint tod);
268 extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl);
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);
274 extern BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolsize, uint segsize, uint hashsize);
275 void bt_mgrclose (BtMgr *mgr);
277 // Helper functions to return slot values
279 extern BtKey bt_key (BtDb *bt, uint slot);
280 extern uid bt_uid (BtDb *bt, uint slot);
281 extern uint bt_tod (BtDb *bt, uint slot);
283 // BTree page number constants
284 #define ALLOC_page 0 // allocation & lock manager hash table
285 #define ROOT_page 1 // root of the btree
286 #define LEAF_page 2 // first page of leaves
287 #define LATCH_page 3 // pages for lock manager
289 // Number of levels to create in a new BTree
293 // The page is allocated from low and hi ends.
294 // The key offsets and row-id's are allocated
295 // from the bottom, while the text of the key
296 // is allocated from the top. When the two
297 // areas meet, the page is split into two.
299 // A key consists of a length byte, two bytes of
300 // index number (0 - 65534), and up to 253 bytes
301 // of key value. Duplicate keys are discarded.
302 // Associated with each key is a 48 bit row-id.
304 // The b-tree root is always located at page 1.
305 // The first leaf page of level zero is always
306 // located on page 2.
308 // The b-tree pages are linked with next
309 // pointers to facilitate enumerators,
310 // and provide for concurrency.
312 // When to root page fills, it is split in two and
313 // the tree height is raised by a new root at page
314 // one with two keys.
316 // Deleted keys are marked with a dead bit until
317 // page cleanup The fence key for a node is
318 // present in a special array.
320 // Groups of pages called segments from the btree are optionally
321 // cached with a memory mapped pool. A hash table is used to keep
322 // track of the cached segments. This behaviour is controlled
323 // by the cache block size parameter to bt_open.
325 // To achieve maximum concurrency one page is locked at a time
326 // as the tree is traversed to find leaf key in question. The right
327 // page numbers are used in cases where the page is being split,
330 // Page 0 is dedicated to lock for new page extensions,
331 // and chains empty pages together for reuse.
333 // The ParentModification lock on a node is obtained to serialize posting
334 // or changing the fence key for a node.
336 // Empty pages are chained together through the ALLOC page and reused.
338 // Access macros to address slot and key values from the page.
339 // Page slots use 1 based indexing.
341 #define slotptr(page, slot) (((BtSlot *)(page+1)) + (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_lock_test_and_set(latch->mutex, 1) )
378 if( _InterlockedExchange8(latch->mutex, 1) )
381 // see if exclusive request is granted or pending
383 if( prev = !(latch->exclusive | latch->pending) )
387 __sync_lock_release (latch->mutex);
389 _InterlockedExchange8(latch->mutex, 0);
396 } while( sched_yield(), 1 );
398 } while( SwitchToThread(), 1 );
402 // wait for other read and write latches to relinquish
404 void bt_spinwritelock(BtSpinLatch *latch)
410 if( __sync_lock_test_and_set(latch->mutex, 1) )
413 if( _InterlockedExchange8(latch->mutex, 1) )
416 if( prev = !(latch->share | latch->exclusive) )
417 latch->exclusive = 1, latch->pending = 0;
421 __sync_lock_release (latch->mutex);
423 _InterlockedExchange8(latch->mutex, 0);
428 } while( sched_yield(), 1 );
430 } while( SwitchToThread(), 1 );
434 // try to obtain write lock
436 // return 1 if obtained,
439 int bt_spinwritetry(BtSpinLatch *latch)
444 if( __sync_lock_test_and_set(latch->mutex, 1) )
447 if( _InterlockedExchange8(latch->mutex, 1) )
450 // take write access if all bits are clear
452 if( prev = !(latch->exclusive | latch->share) )
453 latch->exclusive = 1;
456 __sync_lock_release (latch->mutex);
458 _InterlockedExchange8(latch->mutex, 0);
465 void bt_spinreleasewrite(BtSpinLatch *latch)
467 // obtain latch mutex
469 while( __sync_lock_test_and_set(latch->mutex, 1) )
472 while( _InterlockedExchange8(latch->mutex, 1) )
475 latch->exclusive = 0;
477 __sync_lock_release (latch->mutex);
479 _InterlockedExchange8(latch->mutex, 0);
483 // decrement reader count
485 void bt_spinreleaseread(BtSpinLatch *latch)
488 while( __sync_lock_test_and_set(latch->mutex, 1) )
491 while( _InterlockedExchange8(latch->mutex, 1) )
496 __sync_lock_release (latch->mutex);
498 _InterlockedExchange8(latch->mutex, 0);
502 void bt_readlock(BtLatch *latch)
505 pthread_rwlock_rdlock (latch->lock);
507 AcquireSRWLockShared (latch->srw);
511 // wait for other read and write latches to relinquish
513 void bt_writelock(BtLatch *latch)
516 pthread_rwlock_wrlock (latch->lock);
518 AcquireSRWLockExclusive (latch->srw);
522 // try to obtain write lock
524 // return 1 if obtained,
525 // 0 if already write or read locked
527 int bt_writetry(BtLatch *latch)
532 result = !pthread_rwlock_trywrlock (latch->lock);
534 result = TryAcquireSRWLockExclusive (latch->srw);
541 void bt_releasewrite(BtLatch *latch)
544 pthread_rwlock_unlock (latch->lock);
546 ReleaseSRWLockExclusive (latch->srw);
550 // decrement reader count
552 void bt_releaseread(BtLatch *latch)
555 pthread_rwlock_unlock (latch->lock);
557 ReleaseSRWLockShared (latch->srw);
561 void bt_initlockset (BtLatchSet *set)
564 pthread_rwlockattr_t rwattr[1];
566 pthread_rwlockattr_init (rwattr);
567 pthread_rwlockattr_setpshared (rwattr, PTHREAD_PROCESS_SHARED);
569 pthread_rwlock_init (set->readwr->lock, rwattr);
570 pthread_rwlock_init (set->access->lock, rwattr);
571 pthread_rwlock_init (set->parent->lock, rwattr);
572 pthread_rwlockattr_destroy (rwattr);
574 InitializeSRWLock (set->readwr->srw);
575 InitializeSRWLock (set->access->srw);
576 InitializeSRWLock (set->parent->srw);
580 // link latch table entry into latch hash table
582 void bt_latchlink (BtDb *bt, ushort hashidx, ushort victim, uid page_no)
584 BtLatchSet *set = bt->mgr->latchsets + victim;
586 if( set->next = bt->mgr->latchmgr->table[hashidx].slot )
587 bt->mgr->latchsets[set->next].prev = victim;
589 bt->mgr->latchmgr->table[hashidx].slot = victim;
590 set->page_no = page_no;
597 void bt_unpinlatch (BtLatchSet *set)
600 __sync_fetch_and_add(&set->pin, -1);
602 _InterlockedDecrement16 (&set->pin);
606 // find existing latchset or inspire new one
607 // return with latchset pinned
609 BtLatchSet *bt_pinlatch (BtDb *bt, uid page_no)
611 ushort hashidx = page_no % bt->mgr->latchmgr->latchhash;
612 ushort slot, avail = 0, victim, idx;
615 // try to find existing latch table entry for this page
617 // obtain read lock on hash table entry
619 bt_spinreadlock(bt->mgr->latchmgr->table[hashidx].latch);
621 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
623 set = bt->mgr->latchsets + slot;
624 if( page_no == set->page_no )
626 } while( slot = set->next );
630 __sync_fetch_and_add(&set->pin, 1);
632 _InterlockedIncrement16 (&set->pin);
636 bt_spinreleaseread (bt->mgr->latchmgr->table[hashidx].latch);
641 // try again, this time with write lock
643 bt_spinwritelock(bt->mgr->latchmgr->table[hashidx].latch);
645 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
647 set = bt->mgr->latchsets + slot;
648 if( page_no == set->page_no )
650 if( !set->pin && !avail )
652 } while( slot = set->next );
654 // found our entry, or take over an unpinned one
656 if( slot || (slot = avail) ) {
657 set = bt->mgr->latchsets + slot;
659 __sync_fetch_and_add(&set->pin, 1);
661 _InterlockedIncrement16 (&set->pin);
663 set->page_no = page_no;
664 bt_spinreleasewrite(bt->mgr->latchmgr->table[hashidx].latch);
668 // see if there are any unused entries
670 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, 1) + 1;
672 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchdeployed);
675 if( victim < bt->mgr->latchmgr->latchtotal ) {
676 set = bt->mgr->latchsets + victim;
678 __sync_fetch_and_add(&set->pin, 1);
680 _InterlockedIncrement16 (&set->pin);
682 bt_initlockset (set);
683 bt_latchlink (bt, hashidx, victim, page_no);
684 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
689 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, -1);
691 victim = _InterlockedDecrement16 (&bt->mgr->latchmgr->latchdeployed);
693 // find and reuse previous lock entry
697 victim = __sync_fetch_and_add(&bt->mgr->latchmgr->latchvictim, 1);
699 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchvictim) - 1;
701 // we don't use slot zero
703 if( victim %= bt->mgr->latchmgr->latchtotal )
704 set = bt->mgr->latchsets + victim;
708 // take control of our slot
709 // from other threads
711 if( set->pin || !bt_spinwritetry (set->busy) )
716 // try to get write lock on hash chain
717 // skip entry if not obtained
718 // or has outstanding locks
720 if( !bt_spinwritetry (bt->mgr->latchmgr->table[idx].latch) ) {
721 bt_spinreleasewrite (set->busy);
726 bt_spinreleasewrite (set->busy);
727 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
731 // unlink our available victim from its hash chain
734 bt->mgr->latchsets[set->prev].next = set->next;
736 bt->mgr->latchmgr->table[idx].slot = set->next;
739 bt->mgr->latchsets[set->next].prev = set->prev;
741 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
743 __sync_fetch_and_add(&set->pin, 1);
745 _InterlockedIncrement16 (&set->pin);
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);
788 free ((void *)mgr->latch);
791 FlushFileBuffers(mgr->idx);
792 CloseHandle(mgr->idx);
793 GlobalFree (mgr->pool);
794 GlobalFree (mgr->hash);
795 GlobalFree ((void *)mgr->latch);
800 // close and release memory
802 void bt_close (BtDb *bt)
809 VirtualFree (bt->mem, 0, MEM_RELEASE);
814 // open/create new btree buffer manager
816 // call with file_name, BT_openmode, bits in page size (e.g. 16),
817 // size of mapped page pool (e.g. 8192)
819 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
821 uint lvl, attr, cacheblk, last, slot, idx;
822 uint nlatchpage, latchhash;
823 BtLatchMgr *latchmgr;
831 SYSTEM_INFO sysinfo[1];
834 // determine sanity of page size and buffer pool
836 if( bits > BT_maxbits )
838 else if( bits < BT_minbits )
842 return NULL; // must have buffer pool
845 mgr = calloc (1, sizeof(BtMgr));
847 mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
850 return free(mgr), NULL;
852 cacheblk = 4096; // minimum mmap segment size for unix
855 mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
856 attr = FILE_ATTRIBUTE_NORMAL;
857 mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
859 if( mgr->idx == INVALID_HANDLE_VALUE )
860 return GlobalFree(mgr), NULL;
862 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
863 GetSystemInfo(sysinfo);
864 cacheblk = sysinfo->dwAllocationGranularity;
868 latchmgr = malloc (BT_maxpage);
871 // read minimum page size to get root info
873 if( size = lseek (mgr->idx, 0L, 2) ) {
874 if( pread(mgr->idx, latchmgr, BT_minpage, 0) == BT_minpage )
875 bits = latchmgr->alloc->bits;
877 return free(mgr), free(latchmgr), NULL;
878 } else if( mode == BT_ro )
879 return free(latchmgr), bt_mgrclose (mgr), NULL;
881 latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
882 size = GetFileSize(mgr->idx, amt);
885 if( !ReadFile(mgr->idx, (char *)latchmgr, BT_minpage, amt, NULL) )
886 return bt_mgrclose (mgr), NULL;
887 bits = latchmgr->alloc->bits;
888 } else if( mode == BT_ro )
889 return bt_mgrclose (mgr), NULL;
892 mgr->page_size = 1 << bits;
893 mgr->page_bits = bits;
895 mgr->poolmax = poolmax;
898 if( cacheblk < mgr->page_size )
899 cacheblk = mgr->page_size;
901 // mask for partial memmaps
903 mgr->poolmask = (cacheblk >> bits) - 1;
905 // see if requested size of pages per memmap is greater
907 if( (1 << segsize) > mgr->poolmask )
908 mgr->poolmask = (1 << segsize) - 1;
912 while( (1 << mgr->seg_bits) <= mgr->poolmask )
915 mgr->hashsize = hashsize;
918 mgr->pool = calloc (poolmax, sizeof(BtPool));
919 mgr->hash = calloc (hashsize, sizeof(ushort));
920 mgr->latch = calloc (hashsize, sizeof(BtSpinLatch));
922 mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * sizeof(BtPool));
923 mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
924 mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtSpinLatch));
930 // initialize an empty b-tree with latch page, root page, page of leaves
931 // and page(s) of latches
933 memset (latchmgr, 0, 1 << bits);
934 nlatchpage = BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1;
935 bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
936 latchmgr->alloc->bits = mgr->page_bits;
938 latchmgr->nlatchpage = nlatchpage;
939 latchmgr->latchtotal = nlatchpage * (mgr->page_size / sizeof(BtLatchSet));
941 // initialize latch manager
943 latchhash = (mgr->page_size - sizeof(BtLatchMgr)) / sizeof(BtHashEntry);
945 // size of hash table = total number of latchsets
947 if( latchhash > latchmgr->latchtotal )
948 latchhash = latchmgr->latchtotal;
950 latchmgr->latchhash = latchhash;
953 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
954 return bt_mgrclose (mgr), NULL;
956 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
957 return bt_mgrclose (mgr), NULL;
959 if( *amt < mgr->page_size )
960 return bt_mgrclose (mgr), NULL;
963 memset (latchmgr, 0, 1 << bits);
964 latchmgr->alloc->bits = mgr->page_bits;
966 for( lvl=MIN_lvl; lvl--; ) {
967 slotptr(latchmgr->alloc, 1)->off = mgr->page_size - 3;
968 bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
969 key = keyptr(latchmgr->alloc, 1);
970 key->len = 2; // create stopper key
973 latchmgr->alloc->min = mgr->page_size - 3;
974 latchmgr->alloc->lvl = lvl;
975 latchmgr->alloc->cnt = 1;
976 latchmgr->alloc->act = 1;
978 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
979 return bt_mgrclose (mgr), NULL;
981 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
982 return bt_mgrclose (mgr), NULL;
984 if( *amt < mgr->page_size )
985 return bt_mgrclose (mgr), NULL;
989 // clear out latch manager locks
990 // and rest of pages to round out segment
992 memset(latchmgr, 0, mgr->page_size);
995 while( last <= ((MIN_lvl + 1 + nlatchpage) | mgr->poolmask) ) {
997 pwrite(mgr->idx, latchmgr, mgr->page_size, last << mgr->page_bits);
999 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
1000 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
1001 return bt_mgrclose (mgr), NULL;
1002 if( *amt < mgr->page_size )
1003 return bt_mgrclose (mgr), NULL;
1010 flag = PROT_READ | PROT_WRITE;
1011 mgr->latchmgr = mmap (0, mgr->page_size, flag, MAP_SHARED, mgr->idx, ALLOC_page * mgr->page_size);
1012 if( mgr->latchmgr == MAP_FAILED )
1013 return bt_mgrclose (mgr), NULL;
1014 mgr->latchsets = (BtLatchSet *)mmap (0, mgr->latchmgr->nlatchpage * mgr->page_size, flag, MAP_SHARED, mgr->idx, LATCH_page * mgr->page_size);
1015 if( mgr->latchsets == MAP_FAILED )
1016 return bt_mgrclose (mgr), NULL;
1018 flag = PAGE_READWRITE;
1019 mgr->halloc = CreateFileMapping(mgr->idx, NULL, flag, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size, NULL);
1021 return bt_mgrclose (mgr), NULL;
1023 flag = FILE_MAP_WRITE;
1024 mgr->latchmgr = MapViewOfFile(mgr->halloc, flag, 0, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size);
1025 if( !mgr->latchmgr )
1026 return GetLastError(), bt_mgrclose (mgr), NULL;
1028 mgr->latchsets = (void *)((char *)mgr->latchmgr + LATCH_page * mgr->page_size);
1034 VirtualFree (latchmgr, 0, MEM_RELEASE);
1039 // open BTree access method
1040 // based on buffer manager
1042 BtDb *bt_open (BtMgr *mgr)
1044 BtDb *bt = malloc (sizeof(*bt));
1046 memset (bt, 0, sizeof(*bt));
1049 bt->mem = malloc (3 *mgr->page_size);
1051 bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
1053 bt->frame = (BtPage)bt->mem;
1054 bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
1055 bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
1057 memset (bt->zero, 0, mgr->page_size);
1061 // compare two keys, returning > 0, = 0, or < 0
1062 // as the comparison value
1064 int keycmp (BtKey key1, unsigned char *key2, uint len2)
1066 uint len1 = key1->len;
1069 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
1082 // find segment in pool
1083 // must be called with hashslot idx locked
1084 // return NULL if not there
1085 // otherwise return node
1087 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
1092 // compute start of hash chain in pool
1094 if( slot = bt->mgr->hash[idx] )
1095 pool = bt->mgr->pool + slot;
1099 page_no &= ~bt->mgr->poolmask;
1101 while( pool->basepage != page_no )
1102 if( pool = pool->hashnext )
1110 // add segment to hash table
1112 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
1117 pool->hashprev = pool->hashnext = NULL;
1118 pool->basepage = page_no & ~bt->mgr->poolmask;
1121 if( slot = bt->mgr->hash[idx] ) {
1122 node = bt->mgr->pool + slot;
1123 pool->hashnext = node;
1124 node->hashprev = pool;
1127 bt->mgr->hash[idx] = pool->slot;
1130 // find best segment to evict from buffer pool
1132 BtPool *bt_findlru (BtDb *bt, uint hashslot)
1134 unsigned long long int target = ~0LL;
1135 BtPool *pool = NULL, *node;
1140 node = bt->mgr->pool + hashslot;
1142 // scan pool entries under hash table slot
1147 if( node->lru > target )
1151 } while( node = node->hashnext );
1156 // map new buffer pool segment to virtual memory
1158 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
1160 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
1161 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
1165 flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
1166 pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED, bt->mgr->idx, off);
1167 if( pool->map == MAP_FAILED )
1168 return bt->err = BTERR_map;
1170 flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
1171 pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
1173 return bt->err = BTERR_map;
1175 flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
1176 pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1178 return bt->err = BTERR_map;
1183 // calculate page within pool
1185 BtPage bt_page (BtDb *bt, BtPool *pool, uid page_no)
1187 uint subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1190 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1196 void bt_unpinpool (BtPool *pool)
1199 __sync_fetch_and_add(&pool->pin, -1);
1201 _InterlockedDecrement16 (&pool->pin);
1205 // find or place requested page in segment-pool
1206 // return pool table entry, incrementing pin
1208 BtPool *bt_pinpool(BtDb *bt, uid page_no)
1210 BtPool *pool, *node, *next;
1211 uint slot, idx, victim;
1213 // lock hash table chain
1215 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1216 bt_spinreadlock (&bt->mgr->latch[idx]);
1218 // look up in hash table
1220 if( pool = bt_findpool(bt, page_no, idx) ) {
1222 __sync_fetch_and_add(&pool->pin, 1);
1224 _InterlockedIncrement16 (&pool->pin);
1226 bt_spinreleaseread (&bt->mgr->latch[idx]);
1231 // upgrade to write lock
1233 bt_spinreleaseread (&bt->mgr->latch[idx]);
1234 bt_spinwritelock (&bt->mgr->latch[idx]);
1236 // try to find page in pool with write lock
1238 if( pool = bt_findpool(bt, page_no, idx) ) {
1240 __sync_fetch_and_add(&pool->pin, 1);
1242 _InterlockedIncrement16 (&pool->pin);
1244 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1249 // allocate a new pool node
1250 // and add to hash table
1253 slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
1255 slot = _InterlockedIncrement16 (&bt->mgr->poolcnt) - 1;
1258 if( ++slot < bt->mgr->poolmax ) {
1259 pool = bt->mgr->pool + slot;
1262 if( bt_mapsegment(bt, pool, page_no) )
1265 bt_linkhash(bt, pool, page_no, idx);
1267 __sync_fetch_and_add(&pool->pin, 1);
1269 _InterlockedIncrement16 (&pool->pin);
1271 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1275 // pool table is full
1276 // find best pool entry to evict
1279 __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
1281 _InterlockedDecrement16 (&bt->mgr->poolcnt);
1286 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
1288 victim = _InterlockedIncrement (&bt->mgr->evicted) - 1;
1290 victim %= bt->mgr->hashsize;
1292 // try to get write lock
1293 // skip entry if not obtained
1295 if( !bt_spinwritetry (&bt->mgr->latch[victim]) )
1298 // if pool entry is empty
1299 // or any pages are pinned
1302 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
1303 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1307 // unlink victim pool node from hash table
1309 if( node = pool->hashprev )
1310 node->hashnext = pool->hashnext;
1311 else if( node = pool->hashnext )
1312 bt->mgr->hash[victim] = node->slot;
1314 bt->mgr->hash[victim] = 0;
1316 if( node = pool->hashnext )
1317 node->hashprev = pool->hashprev;
1319 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1321 // remove old file mapping
1323 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1325 FlushViewOfFile(pool->map, 0);
1326 UnmapViewOfFile(pool->map);
1327 CloseHandle(pool->hmap);
1331 // create new pool mapping
1332 // and link into hash table
1334 if( bt_mapsegment(bt, pool, page_no) )
1337 bt_linkhash(bt, pool, page_no, idx);
1339 __sync_fetch_and_add(&pool->pin, 1);
1341 _InterlockedIncrement16 (&pool->pin);
1343 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1348 // place write, read, or parent lock on requested page_no.
1350 void bt_lockpage(BtLock mode, BtLatchSet *set)
1354 bt_readlock (set->readwr);
1357 bt_writelock (set->readwr);
1360 bt_readlock (set->access);
1363 bt_writelock (set->access);
1366 bt_writelock (set->parent);
1371 // remove write, read, or parent lock on requested page
1373 void bt_unlockpage(BtLock mode, BtLatchSet *set)
1377 bt_releaseread (set->readwr);
1380 bt_releasewrite (set->readwr);
1383 bt_releaseread (set->access);
1386 bt_releasewrite (set->access);
1389 bt_releasewrite (set->parent);
1394 // allocate a new page and write page into it
1396 uid bt_newpage(BtDb *bt, BtPage page)
1402 // lock allocation page
1404 bt_spinwritelock(bt->mgr->latchmgr->lock);
1406 // use empty chain first
1407 // else allocate empty page
1409 if( new_page = bt_getid(bt->mgr->latchmgr->alloc[1].right) ) {
1410 if( set->pool = bt_pinpool (bt, new_page) )
1411 set->page = bt_page (bt, set->pool, new_page);
1415 bt_putid(bt->mgr->latchmgr->alloc[1].right, bt_getid(set->page->right));
1416 bt_unpinpool (set->pool);
1419 new_page = bt_getid(bt->mgr->latchmgr->alloc->right);
1420 bt_putid(bt->mgr->latchmgr->alloc->right, new_page+1);
1424 if( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1425 return bt->err = BTERR_wrt, 0;
1427 // if writing first page of pool block, zero last page in the block
1429 if( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1431 // use zero buffer to write zeros
1432 if( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1433 return bt->err = BTERR_wrt, 0;
1436 // bring new page into pool and copy page.
1437 // this will extend the file into the new pages.
1439 if( set->pool = bt_pinpool (bt, new_page) )
1440 set->page = bt_page (bt, set->pool, new_page);
1444 memcpy(set->page, page, bt->mgr->page_size);
1445 bt_unpinpool (set->pool);
1447 // unlock allocation latch and return new page no
1449 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1453 // find slot in page for given key at a given level
1455 int bt_findslot (BtPageSet *set, unsigned char *key, uint len)
1457 uint diff, higher = set->page->cnt, low = 1, slot;
1460 // make stopper key an infinite fence value
1462 if( bt_getid (set->page->right) )
1467 // low is the lowest candidate.
1468 // loop ends when they meet
1470 // higher is already
1471 // tested as .ge. the passed key.
1473 while( diff = higher - low ) {
1474 slot = low + ( diff >> 1 );
1475 if( keycmp (keyptr(set->page, slot), key, len) < 0 )
1478 higher = slot, good++;
1481 // return zero if key is on right link page
1483 return good ? higher : 0;
1486 // find and load page at given level for given key
1487 // leave page rd or wr locked as requested
1489 int bt_loadpage (BtDb *bt, BtPageSet *set, unsigned char *key, uint len, uint lvl, BtLock lock)
1491 uid page_no = ROOT_page, prevpage = 0;
1492 uint drill = 0xff, slot;
1493 BtLatchSet *prevlatch;
1494 uint mode, prevmode;
1497 // start at root of btree and drill down
1500 // determine lock mode of drill level
1501 mode = (drill == lvl) ? lock : BtLockRead;
1503 set->latch = bt_pinlatch (bt, page_no);
1504 set->page_no = page_no;
1506 // pin page contents
1508 if( set->pool = bt_pinpool (bt, page_no) )
1509 set->page = bt_page (bt, set->pool, page_no);
1513 // obtain access lock using lock chaining with Access mode
1515 if( page_no > ROOT_page )
1516 bt_lockpage(BtLockAccess, set->latch);
1518 // release & unpin parent page
1521 bt_unlockpage(prevmode, prevlatch);
1522 bt_unpinlatch (prevlatch);
1523 bt_unpinpool (prevpool);
1527 // obtain read lock using lock chaining
1529 bt_lockpage(mode, set->latch);
1531 if( set->page->free )
1532 return bt->err = BTERR_struct, 0;
1534 if( page_no > ROOT_page )
1535 bt_unlockpage(BtLockAccess, set->latch);
1537 // re-read and re-lock root after determining actual level of root
1539 if( set->page->lvl != drill) {
1540 if( set->page_no != ROOT_page )
1541 return bt->err = BTERR_struct, 0;
1543 drill = set->page->lvl;
1545 if( lock != BtLockRead && drill == lvl ) {
1546 bt_unlockpage(mode, set->latch);
1547 bt_unpinlatch (set->latch);
1548 bt_unpinpool (set->pool);
1553 prevpage = set->page_no;
1554 prevlatch = set->latch;
1555 prevpool = set->pool;
1558 // find key on page at this level
1559 // and descend to requested level
1561 if( !set->page->kill )
1562 if( slot = bt_findslot (set, key, len) ) {
1566 while( slotptr(set->page, slot)->dead )
1567 if( slot++ < set->page->cnt )
1572 page_no = bt_getid(slotptr(set->page, slot)->id);
1577 // or slide right into next page
1580 page_no = bt_getid(set->page->right);
1584 // return error on end of right chain
1586 bt->err = BTERR_struct;
1587 return 0; // return error
1590 // return page to free list
1591 // page must be delete & write locked
1593 void bt_freepage (BtDb *bt, BtPageSet *set)
1595 // lock allocation page
1597 bt_spinwritelock (bt->mgr->latchmgr->lock);
1599 // store chain in second right
1600 bt_putid(set->page->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1601 bt_putid(bt->mgr->latchmgr->alloc[1].right, set->page_no);
1602 set->page->free = 1;
1604 // unlock released page
1606 bt_unlockpage (BtLockDelete, set->latch);
1607 bt_unlockpage (BtLockWrite, set->latch);
1608 bt_unpinlatch (set->latch);
1609 bt_unpinpool (set->pool);
1611 // unlock allocation page
1613 bt_spinreleasewrite (bt->mgr->latchmgr->lock);
1616 // a fence key was deleted from a page
1617 // push new fence value upwards
1619 BTERR bt_fixfence (BtDb *bt, BtPageSet *set, uint lvl)
1621 unsigned char leftkey[256], rightkey[256];
1625 // remove the old fence value
1627 ptr = keyptr(set->page, set->page->cnt);
1628 memcpy (rightkey, ptr, ptr->len + 1);
1630 memset (slotptr(set->page, set->page->cnt--), 0, sizeof(BtSlot));
1631 set->page->dirty = 1;
1633 ptr = keyptr(set->page, set->page->cnt);
1634 memcpy (leftkey, ptr, ptr->len + 1);
1635 page_no = set->page_no;
1637 bt_lockpage (BtLockParent, set->latch);
1638 bt_unlockpage (BtLockWrite, set->latch);
1640 // insert new (now smaller) fence key
1642 if( bt_insertkey (bt, leftkey+1, *leftkey, lvl+1, page_no, time(NULL)) )
1645 // now delete old fence key
1647 if( bt_deletekey (bt, rightkey+1, *rightkey, lvl+1) )
1650 bt_unlockpage (BtLockParent, set->latch);
1651 bt_unpinlatch(set->latch);
1652 bt_unpinpool (set->pool);
1656 // root has a single child
1657 // collapse a level from the tree
1659 BTERR bt_collapseroot (BtDb *bt, BtPageSet *root)
1664 // find the child entry and promote as new root contents
1667 for( idx = 0; idx++ < root->page->cnt; )
1668 if( !slotptr(root->page, idx)->dead )
1671 child->page_no = bt_getid (slotptr(root->page, idx)->id);
1673 child->latch = bt_pinlatch (bt, child->page_no);
1674 bt_lockpage (BtLockDelete, child->latch);
1675 bt_lockpage (BtLockWrite, child->latch);
1677 if( child->pool = bt_pinpool (bt, child->page_no) )
1678 child->page = bt_page (bt, child->pool, child->page_no);
1682 memcpy (root->page, child->page, bt->mgr->page_size);
1683 bt_freepage (bt, child);
1685 } while( root->page->lvl > 1 && root->page->act == 1 );
1687 bt_unlockpage (BtLockWrite, root->latch);
1688 bt_unpinlatch (root->latch);
1689 bt_unpinpool (root->pool);
1693 // find and delete key on page by marking delete flag bit
1694 // if page becomes empty, delete it from the btree
1696 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl)
1698 unsigned char lowerfence[256], higherfence[256];
1699 uint slot, idx, dirty = 0, fence, found;
1700 BtPageSet set[1], right[1];
1703 if( slot = bt_loadpage (bt, set, key, len, lvl, BtLockWrite) )
1704 ptr = keyptr(set->page, slot);
1708 // are we deleting a fence slot?
1710 fence = slot == set->page->cnt;
1712 // if key is found delete it, otherwise ignore request
1714 if( found = !keycmp (ptr, key, len) )
1715 if( found = slotptr(set->page, slot)->dead == 0 ) {
1716 dirty = slotptr(set->page, slot)->dead = 1;
1717 set->page->dirty = 1;
1720 // collapse empty slots
1722 while( idx = set->page->cnt - 1 )
1723 if( slotptr(set->page, idx)->dead ) {
1724 *slotptr(set->page, idx) = *slotptr(set->page, idx + 1);
1725 memset (slotptr(set->page, set->page->cnt--), 0, sizeof(BtSlot));
1730 // did we delete a fence key in an upper level?
1732 if( dirty && lvl && set->page->act && fence )
1733 if( bt_fixfence (bt, set, lvl) )
1736 return bt->found = found, 0;
1738 // is this a collapsed root?
1740 if( lvl > 1 && set->page_no == ROOT_page && set->page->act == 1 )
1741 if( bt_collapseroot (bt, set) )
1744 return bt->found = found, 0;
1746 // return if page is not empty
1748 if( set->page->act ) {
1749 bt_unlockpage(BtLockWrite, set->latch);
1750 bt_unpinlatch (set->latch);
1751 bt_unpinpool (set->pool);
1752 return bt->found = found, 0;
1755 // cache copy of fence key
1756 // to post in parent
1758 ptr = keyptr(set->page, set->page->cnt);
1759 memcpy (lowerfence, ptr, ptr->len + 1);
1761 // obtain lock on right page
1763 right->page_no = bt_getid(set->page->right);
1764 right->latch = bt_pinlatch (bt, right->page_no);
1765 bt_lockpage (BtLockWrite, right->latch);
1767 // pin page contents
1769 if( right->pool = bt_pinpool (bt, right->page_no) )
1770 right->page = bt_page (bt, right->pool, right->page_no);
1774 if( right->page->kill )
1775 return bt->err = BTERR_struct;
1777 // pull contents of right peer into our empty page
1779 memcpy (set->page, right->page, bt->mgr->page_size);
1781 // cache copy of key to update
1783 ptr = keyptr(right->page, right->page->cnt);
1784 memcpy (higherfence, ptr, ptr->len + 1);
1786 // mark right page deleted and point it to left page
1787 // until we can post parent updates
1789 bt_putid (right->page->right, set->page_no);
1790 right->page->kill = 1;
1792 bt_lockpage (BtLockParent, right->latch);
1793 bt_unlockpage (BtLockWrite, right->latch);
1795 bt_lockpage (BtLockParent, set->latch);
1796 bt_unlockpage (BtLockWrite, set->latch);
1798 // redirect higher key directly to our new node contents
1800 if( bt_insertkey (bt, higherfence+1, *higherfence, lvl+1, set->page_no, time(NULL)) )
1803 // delete old lower key to our node
1805 if( bt_deletekey (bt, lowerfence+1, *lowerfence, lvl+1) )
1808 // obtain delete and write locks to right node
1810 bt_unlockpage (BtLockParent, right->latch);
1811 bt_lockpage (BtLockDelete, right->latch);
1812 bt_lockpage (BtLockWrite, right->latch);
1813 bt_freepage (bt, right);
1815 bt_unlockpage (BtLockParent, set->latch);
1816 bt_unpinlatch (set->latch);
1817 bt_unpinpool (set->pool);
1822 // find key in leaf level and return row-id
1824 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1831 if( slot = bt_loadpage (bt, set, key, len, 0, BtLockRead) )
1832 ptr = keyptr(set->page, slot);
1836 // if key exists, return row-id
1837 // otherwise return 0
1839 if( slot <= set->page->cnt )
1840 if( !keycmp (ptr, key, len) )
1841 id = bt_getid(slotptr(set->page,slot)->id);
1843 bt_unlockpage (BtLockRead, set->latch);
1844 bt_unpinlatch (set->latch);
1845 bt_unpinpool (set->pool);
1849 // check page for space available,
1850 // clean if necessary and return
1851 // 0 - page needs splitting
1852 // >0 new slot value
1854 uint bt_cleanpage(BtDb *bt, BtPage page, uint amt, uint slot)
1856 uint nxt = bt->mgr->page_size;
1857 uint cnt = 0, idx = 0;
1858 uint max = page->cnt;
1862 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1865 // skip cleanup if nothing to reclaim
1870 memcpy (bt->frame, page, bt->mgr->page_size);
1872 // skip page info and set rest of page to zero
1874 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1878 // try cleaning up page first
1879 // by removing deleted keys
1881 while( cnt++ < max ) {
1884 if( cnt < max && slotptr(bt->frame,cnt)->dead )
1887 // copy the key across
1889 key = keyptr(bt->frame, cnt);
1890 nxt -= key->len + 1;
1891 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1895 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1896 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1898 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1899 slotptr(page, idx)->off = nxt;
1905 // see if page has enough space now, or does it need splitting?
1907 if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1913 // split the root and raise the height of the btree
1915 BTERR bt_splitroot(BtDb *bt, BtPageSet *root, unsigned char *leftkey, uid page_no2)
1917 uint nxt = bt->mgr->page_size;
1920 // Obtain an empty page to use, and copy the current
1921 // root contents into it, e.g. lower keys
1923 if( !(left = bt_newpage(bt, root->page)) )
1926 // preserve the page info at the bottom
1927 // of higher keys and set rest to zero
1929 memset(root->page+1, 0, bt->mgr->page_size - sizeof(*root->page));
1931 // insert lower keys page fence key on newroot page as first key
1933 nxt -= *leftkey + 1;
1934 memcpy ((unsigned char *)root->page + nxt, leftkey, *leftkey + 1);
1935 bt_putid(slotptr(root->page, 1)->id, left);
1936 slotptr(root->page, 1)->off = nxt;
1938 // insert stopper key on newroot page
1939 // and increase the root height
1942 ((unsigned char *)root->page)[nxt] = 2;
1943 ((unsigned char *)root->page)[nxt+1] = 0xff;
1944 ((unsigned char *)root->page)[nxt+2] = 0xff;
1945 bt_putid(slotptr(root->page, 2)->id, page_no2);
1946 slotptr(root->page, 2)->off = nxt;
1948 bt_putid(root->page->right, 0);
1949 root->page->min = nxt; // reset lowest used offset and key count
1950 root->page->cnt = 2;
1951 root->page->act = 2;
1954 // release and unpin root
1956 bt_unlockpage(BtLockWrite, root->latch);
1957 bt_unpinlatch (root->latch);
1958 bt_unpinpool (root->pool);
1962 // split already locked full node
1965 BTERR bt_splitpage (BtDb *bt, BtPageSet *set)
1967 uint cnt = 0, idx = 0, max, nxt = bt->mgr->page_size;
1968 unsigned char fencekey[256], rightkey[256];
1969 uint lvl = set->page->lvl;
1974 // split higher half of keys to bt->frame
1976 memset (bt->frame, 0, bt->mgr->page_size);
1977 max = set->page->cnt;
1981 while( cnt++ < max ) {
1982 key = keyptr(set->page, cnt);
1983 nxt -= key->len + 1;
1984 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
1986 memcpy(slotptr(bt->frame,++idx)->id, slotptr(set->page,cnt)->id, BtId);
1987 if( !(slotptr(bt->frame, idx)->dead = slotptr(set->page, cnt)->dead) )
1989 slotptr(bt->frame, idx)->tod = slotptr(set->page, cnt)->tod;
1990 slotptr(bt->frame, idx)->off = nxt;
1993 // remember existing fence key for new page to the right
1995 memcpy (rightkey, key, key->len + 1);
1997 bt->frame->bits = bt->mgr->page_bits;
1998 bt->frame->min = nxt;
1999 bt->frame->cnt = idx;
2000 bt->frame->lvl = lvl;
2004 if( set->page_no > ROOT_page )
2005 memcpy (bt->frame->right, set->page->right, BtId);
2007 // get new free page and write higher keys to it.
2009 if( !(right->page_no = bt_newpage(bt, bt->frame)) )
2012 // update lower keys to continue in old page
2014 memcpy (bt->frame, set->page, bt->mgr->page_size);
2015 memset (set->page+1, 0, bt->mgr->page_size - sizeof(*set->page));
2016 nxt = bt->mgr->page_size;
2017 set->page->dirty = 0;
2022 // assemble page of smaller keys
2024 while( cnt++ < max / 2 ) {
2025 key = keyptr(bt->frame, cnt);
2026 nxt -= key->len + 1;
2027 memcpy ((unsigned char *)set->page + nxt, key, key->len + 1);
2028 memcpy(slotptr(set->page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
2029 slotptr(set->page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2030 slotptr(set->page, idx)->off = nxt;
2034 // remember fence key for smaller page
2036 memcpy(fencekey, key, key->len + 1);
2038 bt_putid(set->page->right, right->page_no);
2039 set->page->min = nxt;
2040 set->page->cnt = idx;
2042 // if current page is the root page, split it
2044 if( set->page_no == ROOT_page )
2045 return bt_splitroot (bt, set, fencekey, right->page_no);
2047 // insert new fences in their parent pages
2049 right->latch = bt_pinlatch (bt, right->page_no);
2050 bt_lockpage (BtLockParent, right->latch);
2052 bt_lockpage (BtLockParent, set->latch);
2053 bt_unlockpage (BtLockWrite, set->latch);
2055 // insert new fence for reformulated left block of smaller keys
2057 if( bt_insertkey (bt, fencekey+1, *fencekey, lvl+1, set->page_no, time(NULL)) )
2060 // switch fence for right block of larger keys to new right page
2062 if( bt_insertkey (bt, rightkey+1, *rightkey, lvl+1, right->page_no, time(NULL)) )
2065 bt_unlockpage (BtLockParent, set->latch);
2066 bt_unpinlatch (set->latch);
2067 bt_unpinpool (set->pool);
2069 bt_unlockpage (BtLockParent, right->latch);
2070 bt_unpinlatch (right->latch);
2074 // Insert new key into the btree at given level.
2076 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod)
2083 if( slot = bt_loadpage (bt, set, key, len, lvl, BtLockWrite) )
2084 ptr = keyptr(set->page, slot);
2088 bt->err = BTERR_ovflw;
2092 // if key already exists, update id and return
2094 if( !keycmp (ptr, key, len) ) {
2095 if( slotptr(set->page, slot)->dead )
2097 slotptr(set->page, slot)->dead = 0;
2098 slotptr(set->page, slot)->tod = tod;
2099 bt_putid(slotptr(set->page,slot)->id, id);
2100 bt_unlockpage(BtLockWrite, set->latch);
2101 bt_unpinlatch (set->latch);
2102 bt_unpinpool (set->pool);
2106 // check if page has enough space
2108 if( slot = bt_cleanpage (bt, set->page, len, slot) )
2111 if( bt_splitpage (bt, set) )
2115 // calculate next available slot and copy key into page
2117 set->page->min -= len + 1; // reset lowest used offset
2118 ((unsigned char *)set->page)[set->page->min] = len;
2119 memcpy ((unsigned char *)set->page + set->page->min +1, key, len );
2121 for( idx = slot; idx < set->page->cnt; idx++ )
2122 if( slotptr(set->page, idx)->dead )
2125 // now insert key into array before slot
2127 if( idx == set->page->cnt )
2128 idx++, set->page->cnt++;
2133 *slotptr(set->page, idx) = *slotptr(set->page, idx -1), idx--;
2135 bt_putid(slotptr(set->page,slot)->id, id);
2136 slotptr(set->page, slot)->off = set->page->min;
2137 slotptr(set->page, slot)->tod = tod;
2138 slotptr(set->page, slot)->dead = 0;
2140 bt_unlockpage (BtLockWrite, set->latch);
2141 bt_unpinlatch (set->latch);
2142 bt_unpinpool (set->pool);
2146 // cache page of keys into cursor and return starting slot for given key
2148 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2153 // cache page for retrieval
2155 if( slot = bt_loadpage (bt, set, key, len, 0, BtLockRead) )
2156 memcpy (bt->cursor, set->page, bt->mgr->page_size);
2160 bt->cursor_page = set->page_no;
2162 bt_unlockpage(BtLockRead, set->latch);
2163 bt_unpinlatch (set->latch);
2164 bt_unpinpool (set->pool);
2168 // return next slot for cursor page
2169 // or slide cursor right into next page
2171 uint bt_nextkey (BtDb *bt, uint slot)
2177 right = bt_getid(bt->cursor->right);
2179 while( slot++ < bt->cursor->cnt )
2180 if( slotptr(bt->cursor,slot)->dead )
2182 else if( right || (slot < bt->cursor->cnt) ) // skip infinite stopper
2190 bt->cursor_page = right;
2192 if( set->pool = bt_pinpool (bt, right) )
2193 set->page = bt_page (bt, set->pool, right);
2197 set->latch = bt_pinlatch (bt, right);
2198 bt_lockpage(BtLockRead, set->latch);
2200 memcpy (bt->cursor, set->page, bt->mgr->page_size);
2202 bt_unlockpage(BtLockRead, set->latch);
2203 bt_unpinlatch (set->latch);
2204 bt_unpinpool (set->pool);
2212 BtKey bt_key(BtDb *bt, uint slot)
2214 return keyptr(bt->cursor, slot);
2217 uid bt_uid(BtDb *bt, uint slot)
2219 return bt_getid(slotptr(bt->cursor,slot)->id);
2222 uint bt_tod(BtDb *bt, uint slot)
2224 return slotptr(bt->cursor,slot)->tod;
2231 double getCpuTime(int type)
2234 FILETIME xittime[1];
2235 FILETIME systime[1];
2236 FILETIME usrtime[1];
2237 SYSTEMTIME timeconv[1];
2240 memset (timeconv, 0, sizeof(SYSTEMTIME));
2244 GetSystemTimeAsFileTime (xittime);
2245 FileTimeToSystemTime (xittime, timeconv);
2246 ans = (double)timeconv->wDayOfWeek * 3600 * 24;
2249 GetProcessTimes (GetCurrentProcess(), crtime, xittime, systime, usrtime);
2250 FileTimeToSystemTime (usrtime, timeconv);
2253 GetProcessTimes (GetCurrentProcess(), crtime, xittime, systime, usrtime);
2254 FileTimeToSystemTime (systime, timeconv);
2258 ans += (double)timeconv->wHour * 3600;
2259 ans += (double)timeconv->wMinute * 60;
2260 ans += (double)timeconv->wSecond;
2261 ans += (double)timeconv->wMilliseconds / 1000;
2266 #include <sys/resource.h>
2268 double getCpuTime(int type)
2270 struct rusage used[1];
2271 struct timeval tv[1];
2275 gettimeofday(tv, NULL);
2276 return (double)tv->tv_sec + (double)tv->tv_usec / 1000000;
2279 getrusage(RUSAGE_SELF, used);
2280 return (double)used->ru_utime.tv_sec + (double)used->ru_utime.tv_usec / 1000000;
2283 getrusage(RUSAGE_SELF, used);
2284 return (double)used->ru_stime.tv_sec + (double)used->ru_stime.tv_usec / 1000000;
2291 void bt_latchaudit (BtDb *bt)
2293 ushort idx, hashidx;
2299 for( idx = 1; idx < bt->mgr->latchmgr->latchdeployed; idx++ ) {
2300 set->latch = bt->mgr->latchsets + idx;
2301 if( set->latch->pin ) {
2302 fprintf(stderr, "latchset %d pinned for page %.6x\n", idx, set->latch->page_no);
2303 set->latch->pin = 0;
2307 for( hashidx = 0; hashidx < bt->mgr->latchmgr->latchhash; hashidx++ ) {
2308 if( idx = bt->mgr->latchmgr->table[hashidx].slot ) do {
2309 set->latch = bt->mgr->latchsets + idx;
2310 if( set->latch->hash != hashidx )
2311 fprintf(stderr, "latchset %d wrong hashidx\n", idx);
2312 if( set->latch->pin )
2313 fprintf(stderr, "latchset %d pinned for page %.8x\n", idx, set->latch->page_no);
2314 } while( idx = set->latch->next );
2317 next = bt->mgr->latchmgr->nlatchpage + LATCH_page;
2318 page_no = LEAF_page;
2320 while( page_no < bt_getid(bt->mgr->latchmgr->alloc->right) ) {
2321 pread (bt->mgr->idx, bt->frame, bt->mgr->page_size, page_no << bt->mgr->page_bits);
2322 if( !bt->frame->free )
2323 for( idx = 0; idx++ < bt->frame->cnt - 1; ) {
2324 ptr = keyptr(bt->frame, idx+1);
2325 if( keycmp (keyptr(bt->frame, idx), ptr->key, ptr->len) >= 0 )
2326 fprintf(stderr, "page %.8x idx %.2x out of order\n", page_no, idx);
2329 if( page_no > LEAF_page )
2343 // standalone program to index file of keys
2344 // then list them onto std-out
2347 void *index_file (void *arg)
2349 uint __stdcall index_file (void *arg)
2352 int line = 0, found = 0, cnt = 0;
2353 uid next, page_no = LEAF_page; // start on first page of leaves
2354 unsigned char key[256];
2355 ThreadArg *args = arg;
2356 int ch, len = 0, slot;
2363 bt = bt_open (args->mgr);
2366 switch(args->type | 0x20)
2369 fprintf(stderr, "started latch mgr audit\n");
2371 fprintf(stderr, "finished latch mgr audit\n");
2375 fprintf(stderr, "started indexing for %s\n", args->infile);
2376 if( in = fopen (args->infile, "rb") )
2377 while( ch = getc(in), ch != EOF )
2382 if( args->num == 1 )
2383 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2385 else if( args->num )
2386 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2388 if( bt_insertkey (bt, key, len, 0, line, *tod) )
2389 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2392 else if( len < 255 )
2394 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
2398 fprintf(stderr, "started deleting keys for %s\n", args->infile);
2399 if( in = fopen (args->infile, "rb") )
2400 while( ch = getc(in), ch != EOF )
2404 if( args->num == 1 )
2405 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2407 else if( args->num )
2408 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2410 if( bt_deletekey (bt, key, len, 0) )
2411 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2414 else if( len < 255 )
2416 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2420 fprintf(stderr, "started finding keys for %s\n", args->infile);
2421 if( in = fopen (args->infile, "rb") )
2422 while( ch = getc(in), ch != EOF )
2426 if( args->num == 1 )
2427 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2429 else if( args->num )
2430 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2432 if( bt_findkey (bt, key, len) )
2435 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2437 fprintf(stderr, "Unable to find key %.*s line %d\n", len, key, line);
2440 else if( len < 255 )
2442 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2446 fprintf(stderr, "started scanning\n");
2448 if( set->pool = bt_pinpool (bt, page_no) )
2449 set->page = bt_page (bt, set->pool, page_no);
2452 set->latch = bt_pinlatch (bt, page_no);
2453 bt_lockpage (BtLockRead, set->latch);
2454 next = bt_getid (set->page->right);
2455 cnt += set->page->act;
2457 for( slot = 0; slot++ < set->page->cnt; )
2458 if( next || slot < set->page->cnt )
2459 if( !slotptr(set->page, slot)->dead ) {
2460 ptr = keyptr(set->page, slot);
2461 fwrite (ptr->key, ptr->len, 1, stdout);
2462 fputc ('\n', stdout);
2465 bt_unlockpage (BtLockRead, set->latch);
2466 bt_unpinlatch (set->latch);
2467 bt_unpinpool (set->pool);
2468 } while( page_no = next );
2470 cnt--; // remove stopper key
2471 fprintf(stderr, " Total keys read %d\n", cnt);
2475 fprintf(stderr, "started counting\n");
2476 next = bt->mgr->latchmgr->nlatchpage + LATCH_page;
2477 page_no = LEAF_page;
2479 while( page_no < bt_getid(bt->mgr->latchmgr->alloc->right) ) {
2480 uid off = page_no << bt->mgr->page_bits;
2482 pread (bt->mgr->idx, bt->frame, bt->mgr->page_size, off);
2486 SetFilePointer (bt->mgr->idx, (long)off, (long*)(&off)+1, FILE_BEGIN);
2488 if( !ReadFile(bt->mgr->idx, bt->frame, bt->mgr->page_size, amt, NULL))
2489 return bt->err = BTERR_map;
2491 if( *amt < bt->mgr->page_size )
2492 return bt->err = BTERR_map;
2494 if( !bt->frame->free && !bt->frame->lvl )
2495 cnt += bt->frame->act;
2496 if( page_no > LEAF_page )
2501 cnt--; // remove stopper key
2502 fprintf(stderr, " Total keys read %d\n", cnt);
2514 typedef struct timeval timer;
2516 int main (int argc, char **argv)
2518 int idx, cnt, len, slot, err;
2519 int segsize, bits = 16;
2536 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]);
2537 fprintf (stderr, " where page_bits is the page size in bits\n");
2538 fprintf (stderr, " mapped_segments is the number of mmap segments in buffer pool\n");
2539 fprintf (stderr, " seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2540 fprintf (stderr, " line_numbers = 1 to append line numbers to keys\n");
2541 fprintf (stderr, " src_file1 thru src_filen are files of keys separated by newline\n");
2545 start = getCpuTime(0);
2548 bits = atoi(argv[3]);
2551 poolsize = atoi(argv[4]);
2554 fprintf (stderr, "Warning: no mapped_pool\n");
2556 if( poolsize > 65535 )
2557 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2560 segsize = atoi(argv[5]);
2562 segsize = 4; // 16 pages per mmap segment
2565 num = atoi(argv[6]);
2569 threads = malloc (cnt * sizeof(pthread_t));
2571 threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2573 args = malloc (cnt * sizeof(ThreadArg));
2575 mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2578 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2584 for( idx = 0; idx < cnt; idx++ ) {
2585 args[idx].infile = argv[idx + 7];
2586 args[idx].type = argv[2][0];
2587 args[idx].mgr = mgr;
2588 args[idx].num = num;
2589 args[idx].idx = idx;
2591 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2592 fprintf(stderr, "Error creating thread %d\n", err);
2594 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2598 // wait for termination
2601 for( idx = 0; idx < cnt; idx++ )
2602 pthread_join (threads[idx], NULL);
2604 WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2606 for( idx = 0; idx < cnt; idx++ )
2607 CloseHandle(threads[idx]);
2610 elapsed = getCpuTime(0) - start;
2611 fprintf(stderr, " real %dm%.3fs\n", (int)(elapsed/60), elapsed - (int)(elapsed/60)*60);
2612 elapsed = getCpuTime(1);
2613 fprintf(stderr, " user %dm%.3fs\n", (int)(elapsed/60), elapsed - (int)(elapsed/60)*60);
2614 elapsed = getCpuTime(2);
2615 fprintf(stderr, " sys %dm%.3fs\n", (int)(elapsed/60), elapsed - (int)(elapsed/60)*60);