2 // with combined latch & pool manager
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
40 #define WIN32_LEAN_AND_MEAN
51 typedef unsigned long long uid;
54 typedef unsigned long long off64_t;
55 typedef unsigned short ushort;
56 typedef unsigned int uint;
59 #define BT_ro 0x6f72 // ro
60 #define BT_rw 0x7772 // rw
61 #define BT_fl 0x6c66 // fl
63 #define BT_maxbits 15 // maximum page size in bits
64 #define BT_minbits 12 // minimum page size in bits
65 #define BT_minpage (1 << BT_minbits) // minimum page size
66 #define BT_maxpage (1 << BT_maxbits) // maximum page size
69 There are five lock types for each node in three independent sets:
70 1. (set 1) AccessIntent: Sharable. Going to Read the node. Incompatible with NodeDelete.
71 2. (set 1) NodeDelete: Exclusive. About to release the node. Incompatible with AccessIntent.
72 3. (set 2) ReadLock: Sharable. Read the node. Incompatible with WriteLock.
73 4. (set 2) WriteLock: Exclusive. Modify the node. Incompatible with ReadLock and other WriteLocks.
74 5. (set 3) ParentModification: Exclusive. Change the node's parent keys. Incompatible with another ParentModification.
85 // definition for latch implementation
87 // exclusive is set for write access
88 // share is count of read accessors
89 // grant write lock when share == 0
91 volatile typedef struct {
92 unsigned char mutex[1];
93 unsigned char exclusive:1;
94 unsigned char pending:1;
98 // Define the length of the page and key pointers
102 // Page key slot definition.
104 // If BT_maxbits is 15 or less, you can save 2 bytes
105 // for each key stored by making the first two uints
106 // into ushorts. You can also save 4 bytes by removing
107 // the tod field from the key.
109 // Keys are marked dead, but remain on the page until
110 // cleanup is called. The fence key (highest key) for
111 // the page is always present, even if dead.
115 uint tod; // time-stamp for key
117 ushort off:BT_maxbits; // page offset for key start
118 ushort dead:1; // set for deleted key
119 unsigned char id[BtId]; // id associated with key
122 // The key structure occupies space at the upper end of
123 // each page. It's a length byte followed by the value
128 unsigned char key[0];
131 // The first part of an index page.
132 // It is immediately followed
133 // by the BtSlot array of keys.
135 typedef struct BtPage_ {
136 uint cnt; // count of keys in page
137 uint act; // count of active keys
138 uint min; // next key offset
139 unsigned char bits:6; // page size in bits
140 unsigned char free:1; // page is on free list
141 unsigned char dirty:1; // page is dirty in cache
142 unsigned char lvl:6; // level of page
143 unsigned char kill:1; // page is being deleted
144 unsigned char clean:1; // page needs cleaning
145 unsigned char right[BtId]; // page number to right
149 struct BtPage_ alloc[2]; // next & free page_nos in right ptr
150 BtSpinLatch lock[1]; // allocation area lite latch
151 uint latchdeployed; // highest number of latch entries deployed
152 uint nlatchpage; // number of latch pages at BT_latch
153 uint latchtotal; // number of page latch entries
154 uint latchhash; // number of latch hash table slots
155 uint latchvictim; // next latch hash entry to examine
158 // latch hash table entries
161 volatile uint slot; // Latch table entry at head of collision chain
162 BtSpinLatch latch[1]; // lock for the collision chain
165 // latch manager table structure
168 volatile uid page_no; // latch set page number on disk
169 BtSpinLatch readwr[1]; // read/write page lock
170 BtSpinLatch access[1]; // Access Intent/Page delete
171 BtSpinLatch parent[1]; // Posting of fence key in parent
172 volatile uint next; // next entry in hash table chain
173 volatile uint prev; // prev entry in hash table chain
174 volatile uint pin; // number of outstanding pins
177 // The object structure for Btree access
179 typedef struct _BtDb {
180 uint page_size; // each page size
181 uint page_bits; // each page size in bits
182 uid page_no; // current page number
183 uid cursor_page; // current cursor page number
185 uint mode; // read-write mode
186 BtPage cursor; // cached frame for start/next (never mapped)
187 BtPage frame; // spare frame for the page split (never mapped)
188 BtPage page; // current mapped page in buffer pool
189 BtLatchSet *latch; // current page latch
190 BtLatchMgr *latchmgr; // mapped latch page from allocation page
191 BtLatchSet *latchsets; // mapped latch set from latch pages
192 unsigned char *pagepool; // cached page pool set
193 BtHashEntry *table; // the hash table
198 HANDLE halloc; // allocation and latch table handle
200 unsigned char *mem; // frame, cursor, memory buffers
201 uint found; // last deletekey found key
219 extern void bt_close (BtDb *bt);
220 extern BtDb *bt_open (char *name, uint mode, uint bits, uint cacheblk);
221 extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod);
222 extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl);
223 extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
224 extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
225 extern uint bt_nextkey (BtDb *bt, uint slot);
227 // internal functions
228 void bt_update (BtDb *bt, BtPage page);
229 BtPage bt_mappage (BtDb *bt, BtLatchSet *latch);
230 // Helper functions to return slot values
232 extern BtKey bt_key (BtDb *bt, uint slot);
233 extern uid bt_uid (BtDb *bt, uint slot);
235 extern uint bt_tod (BtDb *bt, uint slot);
238 // BTree page number constants
244 // Number of levels to create in a new BTree
248 // The page is allocated from low and hi ends.
249 // The key offsets and row-id's are allocated
250 // from the bottom, while the text of the key
251 // is allocated from the top. When the two
252 // areas meet, the page is split into two.
254 // A key consists of a length byte, two bytes of
255 // index number (0 - 65534), and up to 253 bytes
256 // of key value. Duplicate keys are discarded.
257 // Associated with each key is a 48 bit row-id.
259 // The b-tree root is always located at page 1.
260 // The first leaf page of level zero is always
261 // located on page 2.
263 // The b-tree pages are linked with right
264 // pointers to facilitate enumerators,
265 // and provide for concurrency.
267 // When to root page fills, it is split in two and
268 // the tree height is raised by a new root at page
269 // one with two keys.
271 // Deleted keys are marked with a dead bit until
272 // page cleanup The fence key for a node is always
273 // present, even after deletion and cleanup.
275 // Deleted leaf pages are reclaimed on a free list.
276 // The upper levels of the btree are fixed on creation.
278 // To achieve maximum concurrency one page is locked at a time
279 // as the tree is traversed to find leaf key in question. The right
280 // page numbers are used in cases where the page is being split,
283 // Page 0 (ALLOC page) is dedicated to lock for new page extensions,
284 // and chains empty leaf pages together for reuse.
286 // Parent locks are obtained to prevent resplitting or deleting a node
287 // before its fence is posted into its upper level.
289 // A special open mode of BT_fl is provided to safely access files on
290 // WIN32 networks. WIN32 network operations should not use memory mapping.
291 // This WIN32 mode sets FILE_FLAG_NOBUFFERING and FILE_FLAG_WRITETHROUGH
292 // to prevent local caching of network file contents.
294 // Access macros to address slot and key values from the page.
295 // Page slots use 1 based indexing.
297 #define slotptr(page, slot) (((BtSlot *)(page+1)) + (slot-1))
298 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
300 void bt_putid(unsigned char *dest, uid id)
305 dest[i] = (unsigned char)id, id >>= 8;
308 uid bt_getid(unsigned char *src)
313 for( i = 0; i < BtId; i++ )
314 id <<= 8, id |= *src++;
319 BTERR bt_abort (BtDb *bt, BtPage page, uid page_no, BTERR err)
323 fprintf(stderr, "\n Btree2 abort, error %d on page %.8x\n", err, page_no);
324 fprintf(stderr, "level=%d kill=%d free=%d cnt=%x act=%x\n", page->lvl, page->kill, page->free, page->cnt, page->act);
325 ptr = keyptr(page, page->cnt);
326 fprintf(stderr, "fence='%.*s'\n", ptr->len, ptr->key);
327 fprintf(stderr, "right=%.8x\n", bt_getid(page->right));
328 return bt->err = err;
333 // wait until write lock mode is clear
334 // and add 1 to the share count
336 void bt_spinreadlock(BtSpinLatch *latch)
341 // obtain latch mutex
343 if( __sync_lock_test_and_set(latch->mutex, 1) )
346 if( _InterlockedExchange8(latch->mutex, 1) )
349 // see if exclusive request is granted or pending
351 if( prev = !(latch->exclusive | latch->pending) )
357 _InterlockedExchange8(latch->mutex, 0);
364 } while( sched_yield(), 1 );
366 } while( SwitchToThread(), 1 );
370 // wait for other read and write latches to relinquish
372 void bt_spinwritelock(BtSpinLatch *latch)
378 if( __sync_lock_test_and_set(latch->mutex, 1) )
381 if( _InterlockedExchange8(latch->mutex, 1) )
384 if( prev = !(latch->share | latch->exclusive) )
385 latch->exclusive = 1, latch->pending = 0;
391 _InterlockedExchange8(latch->mutex, 0);
396 } while( sched_yield(), 1 );
398 } while( SwitchToThread(), 1 );
402 // try to obtain write lock
404 // return 1 if obtained,
407 int bt_spinwritetry(BtSpinLatch *latch)
412 if( __sync_lock_test_and_set(latch->mutex, 1) )
415 if( _InterlockedExchange8(latch->mutex, 1) )
418 // take write access if all bits are clear
420 if( prev = !(latch->exclusive | latch->share) )
421 latch->exclusive = 1;
426 _InterlockedExchange8(latch->mutex, 0);
433 void bt_spinreleasewrite(BtSpinLatch *latch)
436 while( __sync_lock_test_and_set(latch->mutex, 1) )
439 while( _InterlockedExchange8(latch->mutex, 1) )
442 latch->exclusive = 0;
446 _InterlockedExchange8(latch->mutex, 0);
450 // decrement reader count
452 void bt_spinreleaseread(BtSpinLatch *latch)
455 while( __sync_lock_test_and_set(latch->mutex, 1) )
458 while( _InterlockedExchange8(latch->mutex, 1) )
465 _InterlockedExchange8(latch->mutex, 0);
469 // read page from permanent location in Btree file
471 BTERR bt_readpage (BtDb *bt, BtPage page, uid page_no)
473 off64_t off = page_no << bt->page_bits;
476 if( pread (bt->idx, page, bt->page_size, page_no << bt->page_bits) < bt->page_size )
477 return bt->err = BTERR_read;
482 memset (ovl, 0, sizeof(OVERLAPPED));
484 ovl->OffsetHigh = off >> 32;
486 if( !ReadFile(bt->idx, page, bt->page_size, amt, ovl))
487 return bt->err = BTERR_read;
488 if( *amt < bt->page_size )
489 return bt->err = BTERR_read;
494 // write page to permanent location in Btree file
495 // clear the dirty bit
497 BTERR bt_writepage (BtDb *bt, BtPage page, uid page_no)
499 off64_t off = page_no << bt->page_bits;
504 if( pwrite(bt->idx, page, bt->page_size, off) < bt->page_size )
505 return bt->err = BTERR_wrt;
510 memset (ovl, 0, sizeof(OVERLAPPED));
512 ovl->OffsetHigh = off >> 32;
515 if( !WriteFile(bt->idx, page, bt->page_size, amt, ovl) )
516 return bt->err = BTERR_wrt;
518 if( *amt < bt->page_size )
519 return bt->err = BTERR_wrt;
524 // link latch table entry into head of latch hash table
526 BTERR bt_latchlink (BtDb *bt, uint hashidx, uint slot, uid page_no)
528 BtPage page = (BtPage)(slot * bt->page_size + bt->pagepool);
529 BtLatchSet *latch = bt->latchsets + slot;
531 if( latch->next = bt->table[hashidx].slot )
532 bt->latchsets[latch->next].prev = slot;
534 bt->table[hashidx].slot = slot;
535 latch->page_no = page_no;
539 return bt_readpage (bt, page, page_no);
544 void bt_unpinlatch (BtLatchSet *latch)
547 __sync_fetch_and_add(&latch->pin, -1);
549 _InterlockedDecrement (&latch->pin);
553 // find existing latchset or inspire new one
554 // return with latchset pinned
556 BtLatchSet *bt_pinlatch (BtDb *bt, uid page_no)
558 uint hashidx = page_no % bt->latchmgr->latchhash;
565 // try to find unpinned entry
567 bt_spinwritelock(bt->table[hashidx].latch);
569 if( slot = bt->table[hashidx].slot ) do
571 latch = bt->latchsets + slot;
572 if( page_no == latch->page_no )
574 } while( slot = latch->next );
576 // found our entry, bring to front of hash chain
579 latch = bt->latchsets + slot;
581 __sync_fetch_and_add(&latch->pin, 1);
583 _InterlockedIncrement (&latch->pin);
585 // unlink our entry from its hash chain position
588 bt->latchsets[latch->prev].next = latch->next;
590 bt->table[hashidx].slot = latch->next;
593 bt->latchsets[latch->next].prev = latch->prev;
595 // now link into head of the hash chain
597 if( latch->next = bt->table[hashidx].slot )
598 bt->latchsets[latch->next].prev = slot;
600 bt->table[hashidx].slot = slot;
603 bt_spinreleasewrite(bt->table[hashidx].latch);
607 // see if there are any unused pool entries
609 slot = __sync_fetch_and_add (&bt->latchmgr->latchdeployed, 1) + 1;
611 slot = _InterlockedIncrement (&bt->latchmgr->latchdeployed);
614 if( slot < bt->latchmgr->latchtotal ) {
615 latch = bt->latchsets + slot;
616 if( bt_latchlink (bt, hashidx, slot, page_no) )
618 bt_spinreleasewrite (bt->table[hashidx].latch);
623 __sync_fetch_and_add (&bt->latchmgr->latchdeployed, -1);
625 _InterlockedDecrement (&bt->latchmgr->latchdeployed);
627 // find and reuse previous lru lock entry on victim hash chain
631 idx = __sync_fetch_and_add(&bt->latchmgr->latchvictim, 1);
633 idx = _InterlockedIncrement (&bt->latchmgr->latchvictim) - 1;
635 // try to get write lock on hash chain
636 // skip entry if not obtained
637 // or has outstanding locks
639 idx %= bt->latchmgr->latchhash;
641 if( !bt_spinwritetry (bt->table[idx].latch) )
644 if( slot = bt->table[idx].slot )
646 latch = bt->latchsets + slot;
652 if( !slot || latch->pin ) {
653 bt_spinreleasewrite (bt->table[idx].latch);
657 // update permanent page area in btree
659 page = (BtPage)(slot * bt->page_size + bt->pagepool);
662 if( bt_writepage (bt, page, latch->page_no) )
665 // unlink our available slot from its hash chain
668 bt->latchsets[latch->prev].next = latch->next;
670 bt->table[idx].slot = latch->next;
673 bt->latchsets[latch->next].prev = latch->prev;
675 bt_spinreleasewrite (bt->table[idx].latch);
677 if( bt_latchlink (bt, hashidx, slot, page_no) )
680 bt_spinreleasewrite (bt->table[hashidx].latch);
685 // close and release memory
687 void bt_close (BtDb *bt)
690 munmap (bt->table, bt->latchmgr->nlatchpage * bt->page_size);
691 munmap (bt->latchmgr, bt->page_size);
693 FlushViewOfFile(bt->latchmgr, 0);
694 UnmapViewOfFile(bt->latchmgr);
695 CloseHandle(bt->halloc);
704 VirtualFree (bt->mem, 0, MEM_RELEASE);
705 FlushFileBuffers(bt->idx);
706 CloseHandle(bt->idx);
710 // open/create new btree
712 // call with file_name, BT_openmode, bits in page size (e.g. 16),
713 // size of mapped page pool (e.g. 8192)
715 BtDb *bt_open (char *name, uint mode, uint bits, uint nodemax)
717 uint lvl, attr, last, slot, idx;
718 uint nlatchpage, latchhash;
719 BtLatchMgr *latchmgr;
729 struct flock lock[1];
732 // determine sanity of page size and buffer pool
734 if( bits > BT_maxbits )
736 else if( bits < BT_minbits )
739 if( mode == BT_ro ) {
740 fprintf(stderr, "ReadOnly mode not supported: %s\n", name);
744 bt = calloc (1, sizeof(BtDb));
746 bt->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
748 if( bt->idx == -1 ) {
749 fprintf(stderr, "unable to open %s\n", name);
750 return free(bt), NULL;
753 bt = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtDb));
754 attr = FILE_ATTRIBUTE_NORMAL;
755 bt->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
757 if( bt->idx == INVALID_HANDLE_VALUE ) {
758 fprintf(stderr, "unable to open %s\n", name);
759 return GlobalFree(bt), NULL;
763 memset (lock, 0, sizeof(lock));
764 lock->l_len = sizeof(struct BtPage_);
765 lock->l_type = F_WRLCK;
767 if( fcntl (bt->idx, F_SETLKW, lock) < 0 ) {
768 fprintf(stderr, "unable to lock record zero %s\n", name);
769 return bt_close (bt), NULL;
772 memset (ovl, 0, sizeof(ovl));
774 // use large offsets to
775 // simulate advisory locking
777 ovl->OffsetHigh |= 0x80000000;
779 if( !LockFileEx (bt->idx, LOCKFILE_EXCLUSIVE_LOCK, 0, sizeof(struct BtPage_), 0L, ovl) ) {
780 fprintf(stderr, "unable to lock record zero %s, GetLastError = %d\n", name, GetLastError());
781 return bt_close (bt), NULL;
786 latchmgr = malloc (BT_maxpage);
789 // read minimum page size to get root info
791 if( size = lseek (bt->idx, 0L, 2) ) {
792 if( pread(bt->idx, latchmgr, BT_minpage, 0) == BT_minpage )
793 bits = latchmgr->alloc->bits;
795 fprintf(stderr, "Unable to read page zero\n");
796 return free(bt), free(latchmgr), NULL;
800 latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
801 size = GetFileSize(bt->idx, amt);
804 if( !ReadFile(bt->idx, (char *)latchmgr, BT_minpage, amt, NULL) ) {
805 fprintf(stderr, "Unable to read page zero\n");
806 return bt_close (bt), NULL;
808 bits = latchmgr->alloc->bits;
812 bt->page_size = 1 << bits;
813 bt->page_bits = bits;
818 nlatchpage = latchmgr->nlatchpage;
823 fprintf(stderr, "Buffer pool too small: %d\n", nodemax);
824 return bt_close(bt), NULL;
827 // initialize an empty b-tree with latch page, root page, page of leaves
828 // and page(s) of latches and page pool cache
830 memset (latchmgr, 0, 1 << bits);
831 latchmgr->alloc->bits = bt->page_bits;
833 // calculate number of latch hash table entries
835 nlatchpage = (nodemax/16 * sizeof(BtHashEntry) + bt->page_size - 1) / bt->page_size;
836 latchhash = nlatchpage * bt->page_size / sizeof(BtHashEntry);
838 nlatchpage += nodemax; // size of the buffer pool in pages
839 nlatchpage += (sizeof(BtLatchSet) * nodemax + bt->page_size - 1)/bt->page_size;
841 bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
842 latchmgr->nlatchpage = nlatchpage;
843 latchmgr->latchtotal = nodemax;
844 latchmgr->latchhash = latchhash;
846 if( bt_writepage (bt, latchmgr->alloc, 0) ) {
847 fprintf (stderr, "Unable to create btree page zero\n");
848 return bt_close (bt), NULL;
851 memset (latchmgr, 0, 1 << bits);
852 latchmgr->alloc->bits = bt->page_bits;
854 for( lvl=MIN_lvl; lvl--; ) {
855 last = MIN_lvl - lvl; // page number
856 slotptr(latchmgr->alloc, 1)->off = bt->page_size - 3;
857 bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? last + 1 : 0);
858 key = keyptr(latchmgr->alloc, 1);
859 key->len = 2; // create stopper key
863 latchmgr->alloc->min = bt->page_size - 3;
864 latchmgr->alloc->lvl = lvl;
865 latchmgr->alloc->cnt = 1;
866 latchmgr->alloc->act = 1;
868 if( bt_writepage (bt, latchmgr->alloc, last) ) {
869 fprintf (stderr, "Unable to create btree page %.8x\n", last);
870 return bt_close (bt), NULL;
874 // clear out buffer pool pages
876 memset(latchmgr, 0, bt->page_size);
879 while( ++last < ((MIN_lvl + 1 + nlatchpage) ) )
880 if( bt_writepage (bt, latchmgr->alloc, last) ) {
881 fprintf (stderr, "Unable to write buffer pool page %.8x\n", last);
882 return bt_close (bt), NULL;
888 VirtualFree (latchmgr, 0, MEM_RELEASE);
893 lock->l_type = F_UNLCK;
894 if( fcntl (bt->idx, F_SETLK, lock) < 0 ) {
895 fprintf (stderr, "Unable to unlock page zero\n");
896 return bt_close (bt), NULL;
899 if( !UnlockFileEx (bt->idx, 0, sizeof(struct BtPage_), 0, ovl) ) {
900 fprintf (stderr, "Unable to unlock page zero, GetLastError = %d\n", GetLastError());
901 return bt_close (bt), NULL;
905 flag = PROT_READ | PROT_WRITE;
906 bt->latchmgr = mmap (0, bt->page_size, flag, MAP_SHARED, bt->idx, ALLOC_page * bt->page_size);
907 if( bt->latchmgr == MAP_FAILED ) {
908 fprintf (stderr, "Unable to mmap page zero, errno = %d", errno);
909 return bt_close (bt), NULL;
911 bt->table = (void *)mmap (0, nlatchpage * bt->page_size, flag, MAP_SHARED, bt->idx, LATCH_page * bt->page_size);
912 if( bt->table == MAP_FAILED ) {
913 fprintf (stderr, "Unable to mmap buffer pool, errno = %d", errno);
914 return bt_close (bt), NULL;
917 flag = PAGE_READWRITE;
918 bt->halloc = CreateFileMapping(bt->idx, NULL, flag, 0, (nlatchpage + LATCH_page) * bt->page_size, NULL);
920 fprintf (stderr, "Unable to create file mapping for buffer pool mgr, GetLastError = %d\n", GetLastError());
921 return bt_close (bt), NULL;
924 flag = FILE_MAP_WRITE;
925 bt->latchmgr = MapViewOfFile(bt->halloc, flag, 0, 0, (nlatchpage + LATCH_page) * bt->page_size);
926 if( !bt->latchmgr ) {
927 fprintf (stderr, "Unable to map buffer pool, GetLastError = %d\n", GetLastError());
928 return bt_close (bt), NULL;
931 bt->table = (void *)((char *)bt->latchmgr + LATCH_page * bt->page_size);
933 bt->pagepool = (unsigned char *)bt->table + (nlatchpage - bt->latchmgr->latchtotal) * bt->page_size;
934 bt->latchsets = (BtLatchSet *)(bt->pagepool - bt->latchmgr->latchtotal * sizeof(BtLatchSet));
937 bt->mem = malloc (2 * bt->page_size);
939 bt->mem = VirtualAlloc(NULL, 2 * bt->page_size, MEM_COMMIT, PAGE_READWRITE);
941 bt->frame = (BtPage)bt->mem;
942 bt->cursor = (BtPage)(bt->mem + bt->page_size);
946 // place write, read, or parent lock on requested page_no.
948 void bt_lockpage(BtLock mode, BtLatchSet *latch)
952 bt_spinreadlock (latch->readwr);
955 bt_spinwritelock (latch->readwr);
958 bt_spinreadlock (latch->access);
961 bt_spinwritelock (latch->access);
964 bt_spinwritelock (latch->parent);
969 // remove write, read, or parent lock on requested page
971 void bt_unlockpage(BtLock mode, BtLatchSet *latch)
975 bt_spinreleaseread (latch->readwr);
978 bt_spinreleasewrite (latch->readwr);
981 bt_spinreleaseread (latch->access);
984 bt_spinreleasewrite (latch->access);
987 bt_spinreleasewrite (latch->parent);
992 // allocate a new page and write page into it
994 uid bt_newpage(BtDb *bt, BtPage page)
1000 // lock allocation page
1002 bt_spinwritelock(bt->latchmgr->lock);
1004 // use empty chain first
1005 // else allocate empty page
1007 if( new_page = bt_getid(bt->latchmgr->alloc[1].right) ) {
1008 if( latch = bt_pinlatch (bt, new_page) )
1009 temp = bt_mappage (bt, latch);
1013 bt_putid(bt->latchmgr->alloc[1].right, bt_getid(temp->right));
1014 bt_spinreleasewrite(bt->latchmgr->lock);
1015 memcpy (temp, page, bt->page_size);
1017 bt_update (bt, temp);
1018 bt_unpinlatch (latch);
1021 new_page = bt_getid(bt->latchmgr->alloc->right);
1022 bt_putid(bt->latchmgr->alloc->right, new_page+1);
1023 bt_spinreleasewrite(bt->latchmgr->lock);
1025 if( bt_writepage (bt, page, new_page) )
1029 bt_update (bt, bt->latchmgr->alloc);
1033 // compare two keys, returning > 0, = 0, or < 0
1034 // as the comparison value
1036 int keycmp (BtKey key1, unsigned char *key2, uint len2)
1038 uint len1 = key1->len;
1041 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
1052 // Update current page of btree by
1053 // flushing mapped area to disk backing of cache pool.
1054 // mark page as dirty for rewrite to permanent location
1056 void bt_update (BtDb *bt, BtPage page)
1059 msync (page, bt->page_size, MS_ASYNC);
1061 // FlushViewOfFile (page, bt->page_size);
1066 // map the btree cached page onto current page
1068 BtPage bt_mappage (BtDb *bt, BtLatchSet *latch)
1070 return (BtPage)((latch - bt->latchsets) * bt->page_size + bt->pagepool);
1073 // deallocate a deleted page
1074 // place on free chain out of allocator page
1075 // call with page latched for Writing and Deleting
1077 BTERR bt_freepage(BtDb *bt, uid page_no, BtLatchSet *latch)
1079 BtPage page = bt_mappage (bt, latch);
1081 // lock allocation page
1083 bt_spinwritelock (bt->latchmgr->lock);
1085 // store chain in second right
1086 bt_putid(page->right, bt_getid(bt->latchmgr->alloc[1].right));
1087 bt_putid(bt->latchmgr->alloc[1].right, page_no);
1090 bt_update(bt, page);
1092 // unlock released page
1094 bt_unlockpage (BtLockDelete, latch);
1095 bt_unlockpage (BtLockWrite, latch);
1096 bt_unpinlatch (latch);
1098 // unlock allocation page
1100 bt_spinreleasewrite (bt->latchmgr->lock);
1101 bt_update (bt, bt->latchmgr->alloc);
1105 // find slot in page for given key at a given level
1107 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1109 uint diff, higher = bt->page->cnt, low = 1, slot;
1112 // make stopper key an infinite fence value
1114 if( bt_getid (bt->page->right) )
1119 // low is the lowest candidate, higher is already
1120 // tested as .ge. the given key, loop ends when they meet
1122 while( diff = higher - low ) {
1123 slot = low + ( diff >> 1 );
1124 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1127 higher = slot, good++;
1130 // return zero if key is on right link page
1132 return good ? higher : 0;
1135 // find and load page at given level for given key
1136 // leave page rd or wr locked as requested
1138 int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, uint lock)
1140 uid page_no = ROOT_page, prevpage = 0;
1141 uint drill = 0xff, slot;
1142 BtLatchSet *prevlatch;
1143 uint mode, prevmode;
1145 // start at root of btree and drill down
1148 // determine lock mode of drill level
1149 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1151 if( bt->latch = bt_pinlatch(bt, page_no) )
1152 bt->page_no = page_no;
1156 // obtain access lock using lock chaining
1158 if( page_no > ROOT_page )
1159 bt_lockpage(BtLockAccess, bt->latch);
1162 bt_unlockpage(prevmode, prevlatch);
1163 bt_unpinlatch(prevlatch);
1167 // obtain read lock using lock chaining
1169 bt_lockpage(mode, bt->latch);
1171 if( page_no > ROOT_page )
1172 bt_unlockpage(BtLockAccess, bt->latch);
1174 // map/obtain page contents
1176 bt->page = bt_mappage (bt, bt->latch);
1178 // re-read and re-lock root after determining actual level of root
1180 if( bt->page->lvl != drill) {
1181 if( bt->page_no != ROOT_page )
1182 return bt->err = BTERR_struct, 0;
1184 drill = bt->page->lvl;
1186 if( lock != BtLockRead && drill == lvl ) {
1187 bt_unlockpage(mode, bt->latch);
1188 bt_unpinlatch(bt->latch);
1193 prevpage = bt->page_no;
1194 prevlatch = bt->latch;
1197 // find key on page at this level
1198 // and descend to requested level
1200 if( !bt->page->kill )
1201 if( slot = bt_findslot (bt, key, len) ) {
1205 while( slotptr(bt->page, slot)->dead )
1206 if( slot++ < bt->page->cnt )
1211 page_no = bt_getid(slotptr(bt->page, slot)->id);
1216 // or slide right into next page
1219 page_no = bt_getid(bt->page->right);
1223 // return error on end of right chain
1225 bt->err = BTERR_eof;
1226 return 0; // return error
1229 // a fence key was deleted from a page
1230 // push new fence value upwards
1232 BTERR bt_fixfence (BtDb *bt, uid page_no, uint lvl)
1234 unsigned char leftkey[256], rightkey[256];
1235 BtLatchSet *latch = bt->latch;
1238 // remove deleted key, the old fence value
1240 ptr = keyptr(bt->page, bt->page->cnt);
1241 memcpy(rightkey, ptr, ptr->len + 1);
1243 memset (slotptr(bt->page, bt->page->cnt--), 0, sizeof(BtSlot));
1244 bt->page->clean = 1;
1246 ptr = keyptr(bt->page, bt->page->cnt);
1247 memcpy(leftkey, ptr, ptr->len + 1);
1249 bt_update (bt, bt->page);
1250 bt_lockpage (BtLockParent, latch);
1251 bt_unlockpage (BtLockWrite, latch);
1253 // insert new (now smaller) fence key
1255 if( bt_insertkey (bt, leftkey+1, *leftkey, lvl + 1, page_no, time(NULL)) )
1258 // remove old (larger) fence key
1260 if( bt_deletekey (bt, rightkey+1, *rightkey, lvl + 1) )
1263 bt_unlockpage (BtLockParent, latch);
1264 bt_unpinlatch (latch);
1268 // root has a single child
1269 // collapse a level from the btree
1270 // call with root locked in bt->page
1272 BTERR bt_collapseroot (BtDb *bt, BtPage root)
1279 // find the child entry
1280 // and promote to new root
1283 for( idx = 0; idx++ < root->cnt; )
1284 if( !slotptr(root, idx)->dead )
1287 child = bt_getid (slotptr(root, idx)->id);
1288 if( latch = bt_pinlatch (bt, child) )
1289 temp = bt_mappage (bt, latch);
1293 bt_lockpage (BtLockDelete, latch);
1294 bt_lockpage (BtLockWrite, latch);
1295 memcpy (root, temp, bt->page_size);
1297 bt_update (bt, root);
1299 if( bt_freepage (bt, child, latch) )
1302 } while( root->lvl > 1 && root->act == 1 );
1304 bt_unlockpage (BtLockWrite, bt->latch);
1305 bt_unpinlatch (bt->latch);
1309 // find and delete key on page by marking delete flag bit
1310 // when page becomes empty, delete it
1312 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl)
1314 unsigned char lowerkey[256], higherkey[256];
1315 uint slot, dirty = 0, idx, fence, found;
1316 BtLatchSet *latch, *rlatch;
1321 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1322 ptr = keyptr(bt->page, slot);
1326 // are we deleting a fence slot?
1328 fence = slot == bt->page->cnt;
1330 // if key is found delete it, otherwise ignore request
1332 if( found = !keycmp (ptr, key, len) )
1333 if( found = slotptr(bt->page, slot)->dead == 0 ) {
1334 dirty = slotptr(bt->page,slot)->dead = 1;
1335 bt->page->clean = 1;
1338 // collapse empty slots
1340 while( idx = bt->page->cnt - 1 )
1341 if( slotptr(bt->page, idx)->dead ) {
1342 *slotptr(bt->page, idx) = *slotptr(bt->page, idx + 1);
1343 memset (slotptr(bt->page, bt->page->cnt--), 0, sizeof(BtSlot));
1348 right = bt_getid(bt->page->right);
1349 page_no = bt->page_no;
1354 return bt_abort (bt, bt->page, page_no, BTERR_notfound);
1355 bt_unlockpage(BtLockWrite, latch);
1356 bt_unpinlatch (latch);
1357 return bt->found = found, 0;
1360 // did we delete a fence key in an upper level?
1362 if( lvl && bt->page->act && fence )
1363 if( bt_fixfence (bt, page_no, lvl) )
1366 return bt->found = found, 0;
1368 // is this a collapsed root?
1370 if( lvl > 1 && page_no == ROOT_page && bt->page->act == 1 )
1371 if( bt_collapseroot (bt, bt->page) )
1374 return bt->found = found, 0;
1376 // return if page is not empty
1378 if( bt->page->act ) {
1379 bt_update(bt, bt->page);
1380 bt_unlockpage(BtLockWrite, latch);
1381 bt_unpinlatch (latch);
1382 return bt->found = found, 0;
1385 // cache copy of fence key
1386 // in order to find parent
1388 ptr = keyptr(bt->page, bt->page->cnt);
1389 memcpy(lowerkey, ptr, ptr->len + 1);
1391 // obtain lock on right page
1393 if( rlatch = bt_pinlatch (bt, right) )
1394 temp = bt_mappage (bt, rlatch);
1398 bt_lockpage(BtLockWrite, rlatch);
1401 bt_abort(bt, temp, right, 0);
1402 return bt_abort(bt, bt->page, bt->page_no, BTERR_kill);
1405 // pull contents of next page into current empty page
1407 memcpy (bt->page, temp, bt->page_size);
1409 // cache copy of key to update
1411 ptr = keyptr(temp, temp->cnt);
1412 memcpy(higherkey, ptr, ptr->len + 1);
1414 // Mark right page as deleted and point it to left page
1415 // until we can post updates at higher level.
1417 bt_putid(temp->right, page_no);
1420 bt_update(bt, bt->page);
1421 bt_update(bt, temp);
1423 bt_lockpage(BtLockParent, latch);
1424 bt_unlockpage(BtLockWrite, latch);
1426 bt_lockpage(BtLockParent, rlatch);
1427 bt_unlockpage(BtLockWrite, rlatch);
1429 // redirect higher key directly to consolidated node
1431 if( bt_insertkey (bt, higherkey+1, *higherkey, lvl+1, page_no, time(NULL)) )
1434 // delete old lower key to consolidated node
1436 if( bt_deletekey (bt, lowerkey + 1, *lowerkey, lvl + 1) )
1439 // obtain write & delete lock on deleted node
1440 // add right block to free chain
1442 bt_lockpage(BtLockDelete, rlatch);
1443 bt_lockpage(BtLockWrite, rlatch);
1444 bt_unlockpage(BtLockParent, rlatch);
1446 if( bt_freepage (bt, right, rlatch) )
1449 bt_unlockpage(BtLockParent, latch);
1450 bt_unpinlatch(latch);
1454 // find key in leaf level and return row-id
1456 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1462 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1463 ptr = keyptr(bt->page, slot);
1467 // if key exists, return row-id
1468 // otherwise return 0
1470 if( ptr->len == len && !memcmp (ptr->key, key, len) )
1471 id = bt_getid(slotptr(bt->page,slot)->id);
1475 bt_unlockpage (BtLockRead, bt->latch);
1476 bt_unpinlatch (bt->latch);
1480 // check page for space available,
1481 // clean if necessary and return
1482 // 0 - page needs splitting
1483 // >0 - go ahead with new slot
1485 uint bt_cleanpage(BtDb *bt, uint amt, uint slot)
1487 uint nxt = bt->page_size;
1488 BtPage page = bt->page;
1489 uint cnt = 0, idx = 0;
1490 uint max = page->cnt;
1491 uint newslot = slot;
1495 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1498 // skip cleanup if nothing to reclaim
1503 memcpy (bt->frame, page, bt->page_size);
1505 // skip page info and set rest of page to zero
1507 memset (page+1, 0, bt->page_size - sizeof(*page));
1510 while( cnt++ < max ) {
1513 // always leave fence key in list
1514 if( cnt < max && slotptr(bt->frame,cnt)->dead )
1518 key = keyptr(bt->frame, cnt);
1519 nxt -= key->len + 1;
1520 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1523 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1524 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1527 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1529 slotptr(page, idx)->off = nxt;
1535 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1541 // split the root and raise the height of the btree
1543 BTERR bt_splitroot(BtDb *bt, unsigned char *leftkey, uid page_no2)
1545 uint nxt = bt->page_size;
1546 BtPage root = bt->page;
1549 // Obtain an empty page to use, and copy the current
1550 // root contents into it
1552 if( !(right = bt_newpage(bt, root)) )
1555 // preserve the page info at the bottom
1556 // and set rest to zero
1558 memset(root+1, 0, bt->page_size - sizeof(*root));
1560 // insert first key on newroot page
1562 nxt -= *leftkey + 1;
1563 memcpy ((unsigned char *)root + nxt, leftkey, *leftkey + 1);
1564 bt_putid(slotptr(root, 1)->id, right);
1565 slotptr(root, 1)->off = nxt;
1567 // insert second key on newroot page
1568 // and increase the root height
1571 ((unsigned char *)root)[nxt] = 2;
1572 ((unsigned char *)root)[nxt+1] = 0xff;
1573 ((unsigned char *)root)[nxt+2] = 0xff;
1574 bt_putid(slotptr(root, 2)->id, page_no2);
1575 slotptr(root, 2)->off = nxt;
1577 bt_putid(root->right, 0);
1578 root->min = nxt; // reset lowest used offset and key count
1583 // update and release root (bt->page)
1585 bt_update(bt, root);
1587 bt_unlockpage(BtLockWrite, bt->latch);
1588 bt_unpinlatch(bt->latch);
1592 // split already locked full node
1595 BTERR bt_splitpage (BtDb *bt)
1597 uint cnt = 0, idx = 0, max, nxt = bt->page_size;
1598 unsigned char fencekey[256], rightkey[256];
1599 uid page_no = bt->page_no, right;
1600 BtLatchSet *latch, *rlatch;
1601 BtPage page = bt->page;
1602 uint lvl = page->lvl;
1607 // split higher half of keys to bt->frame
1608 // the last key (fence key) might be dead
1610 memset (bt->frame, 0, bt->page_size);
1615 while( cnt++ < max ) {
1616 key = keyptr(page, cnt);
1617 nxt -= key->len + 1;
1618 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
1619 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
1620 if( !(slotptr(bt->frame, idx)->dead = slotptr(page, cnt)->dead) )
1623 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
1625 slotptr(bt->frame, idx)->off = nxt;
1628 // remember fence key for new right page
1630 memcpy (rightkey, key, key->len + 1);
1632 bt->frame->bits = bt->page_bits;
1633 bt->frame->min = nxt;
1634 bt->frame->cnt = idx;
1635 bt->frame->lvl = lvl;
1639 if( page_no > ROOT_page )
1640 memcpy (bt->frame->right, page->right, BtId);
1642 // get new free page and write frame to it.
1644 if( !(right = bt_newpage(bt, bt->frame)) )
1647 // update lower keys to continue in old page
1649 memcpy (bt->frame, page, bt->page_size);
1650 memset (page+1, 0, bt->page_size - sizeof(*page));
1651 nxt = bt->page_size;
1657 // assemble page of smaller keys
1658 // (they're all active keys)
1660 while( cnt++ < max / 2 ) {
1661 key = keyptr(bt->frame, cnt);
1662 nxt -= key->len + 1;
1663 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1664 memcpy(slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1666 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1668 slotptr(page, idx)->off = nxt;
1672 // remember fence key for smaller page
1674 memcpy (fencekey, key, key->len + 1);
1676 bt_putid(page->right, right);
1680 // if current page is the root page, split it
1682 if( page_no == ROOT_page )
1683 return bt_splitroot (bt, fencekey, right);
1687 if( rlatch = bt_pinlatch (bt, right) )
1688 bt_lockpage (BtLockParent, rlatch);
1692 // update left (containing) node
1694 bt_update(bt, page);
1696 bt_lockpage (BtLockParent, latch);
1697 bt_unlockpage (BtLockWrite, latch);
1699 // insert new fence for reformulated left block
1701 if( bt_insertkey (bt, fencekey+1, *fencekey, lvl+1, page_no, time(NULL)) )
1704 // switch fence for right block of larger keys to new right page
1706 if( bt_insertkey (bt, rightkey+1, *rightkey, lvl+1, right, time(NULL)) )
1709 bt_unlockpage (BtLockParent, latch);
1710 bt_unlockpage (BtLockParent, rlatch);
1712 bt_unpinlatch (rlatch);
1713 bt_unpinlatch (latch);
1717 // Insert new key into the btree at requested level.
1718 // Pages are unlocked at exit.
1720 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod)
1727 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1728 ptr = keyptr(bt->page, slot);
1732 bt->err = BTERR_ovflw;
1736 // if key already exists, update id and return
1740 if( !keycmp (ptr, key, len) ) {
1741 if( slotptr(page, slot)->dead )
1743 slotptr(page, slot)->dead = 0;
1745 slotptr(page, slot)->tod = tod;
1747 bt_putid(slotptr(page,slot)->id, id);
1748 bt_update(bt, bt->page);
1749 bt_unlockpage(BtLockWrite, bt->latch);
1750 bt_unpinlatch (bt->latch);
1754 // check if page has enough space
1756 if( slot = bt_cleanpage (bt, len, slot) )
1759 if( bt_splitpage (bt) )
1763 // calculate next available slot and copy key into page
1765 page->min -= len + 1; // reset lowest used offset
1766 ((unsigned char *)page)[page->min] = len;
1767 memcpy ((unsigned char *)page + page->min +1, key, len );
1769 for( idx = slot; idx < page->cnt; idx++ )
1770 if( slotptr(page, idx)->dead )
1773 // now insert key into array before slot
1774 // preserving the fence slot
1776 if( idx == page->cnt )
1782 *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
1784 bt_putid(slotptr(page,slot)->id, id);
1785 slotptr(page, slot)->off = page->min;
1787 slotptr(page, slot)->tod = tod;
1789 slotptr(page, slot)->dead = 0;
1791 bt_update(bt, bt->page);
1793 bt_unlockpage(BtLockWrite, bt->latch);
1794 bt_unpinlatch(bt->latch);
1798 // cache page of keys into cursor and return starting slot for given key
1800 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
1804 // cache page for retrieval
1806 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1807 memcpy (bt->cursor, bt->page, bt->page_size);
1811 bt_unlockpage(BtLockRead, bt->latch);
1812 bt->cursor_page = bt->page_no;
1813 bt_unpinlatch (bt->latch);
1817 // return next slot for cursor page
1818 // or slide cursor right into next page
1820 uint bt_nextkey (BtDb *bt, uint slot)
1826 right = bt_getid(bt->cursor->right);
1828 while( slot++ < bt->cursor->cnt )
1829 if( slotptr(bt->cursor,slot)->dead )
1831 else if( right || (slot < bt->cursor->cnt))
1839 bt->cursor_page = right;
1841 if( latch = bt_pinlatch (bt, right) )
1842 bt_lockpage(BtLockRead, latch);
1846 bt->page = bt_mappage (bt, latch);
1847 memcpy (bt->cursor, bt->page, bt->page_size);
1848 bt_unlockpage(BtLockRead, latch);
1849 bt_unpinlatch (latch);
1856 BtKey bt_key(BtDb *bt, uint slot)
1858 return keyptr(bt->cursor, slot);
1861 uid bt_uid(BtDb *bt, uint slot)
1863 return bt_getid(slotptr(bt->cursor,slot)->id);
1867 uint bt_tod(BtDb *bt, uint slot)
1869 return slotptr(bt->cursor,slot)->tod;
1875 uint bt_audit (BtDb *bt)
1886 if( *(ushort *)(bt->latchmgr->lock) )
1887 fprintf(stderr, "Alloc page locked\n");
1888 *(ushort *)(bt->latchmgr->lock) = 0;
1890 for( idx = 1; idx <= bt->latchmgr->latchdeployed; idx++ ) {
1891 latch = bt->latchsets + idx;
1892 if( *(ushort *)latch->readwr )
1893 fprintf(stderr, "latchset %d rwlocked for page %.8x\n", idx, latch->page_no);
1894 *(ushort *)latch->readwr = 0;
1896 if( *(ushort *)latch->access )
1897 fprintf(stderr, "latchset %d accesslocked for page %.8x\n", idx, latch->page_no);
1898 *(ushort *)latch->access = 0;
1900 if( *(ushort *)latch->parent )
1901 fprintf(stderr, "latchset %d parentlocked for page %.8x\n", idx, latch->page_no);
1902 *(ushort *)latch->parent = 0;
1905 fprintf(stderr, "latchset %d pinned for page %.8x\n", idx, latch->page_no);
1908 page = (BtPage)(idx * bt->page_size + bt->pagepool);
1911 if( bt_writepage (bt, page, latch->page_no) )
1912 fprintf(stderr, "Page %.8x Write Error\n", latch->page_no);
1915 for( hashidx = 0; hashidx < bt->latchmgr->latchhash; hashidx++ ) {
1916 if( *(ushort *)(bt->table[hashidx].latch) )
1917 fprintf(stderr, "hash entry %d locked\n", hashidx);
1919 *(ushort *)(bt->table[hashidx].latch) = 0;
1921 if( idx = bt->table[hashidx].slot ) do {
1922 latch = bt->latchsets + idx;
1924 fprintf(stderr, "latchset %d pinned for page %.8x\n", idx, latch->page_no);
1925 } while( idx = latch->next );
1928 next = bt->latchmgr->nlatchpage + LATCH_page;
1929 page_no = LEAF_page;
1931 while( page_no < bt_getid(bt->latchmgr->alloc->right) ) {
1932 pread (bt->idx, bt->frame, bt->page_size, page_no << bt->page_bits);
1933 if( !bt->frame->free ) {
1934 for( idx = 0; idx++ < bt->frame->cnt - 1; ) {
1935 ptr = keyptr(bt->frame, idx+1);
1936 if( keycmp (keyptr(bt->frame, idx), ptr->key, ptr->len) >= 0 )
1937 fprintf(stderr, "page %.8x idx %.2x out of order\n", page_no, idx);
1939 if( !bt->frame->lvl )
1940 cnt += bt->frame->act;
1943 if( page_no > LEAF_page )
1954 double getCpuTime(int type)
1957 FILETIME xittime[1];
1958 FILETIME systime[1];
1959 FILETIME usrtime[1];
1960 SYSTEMTIME timeconv[1];
1963 memset (timeconv, 0, sizeof(SYSTEMTIME));
1967 GetSystemTimeAsFileTime (xittime);
1968 FileTimeToSystemTime (xittime, timeconv);
1969 ans = (double)timeconv->wDayOfWeek * 3600 * 24;
1972 GetProcessTimes (GetCurrentProcess(), crtime, xittime, systime, usrtime);
1973 FileTimeToSystemTime (usrtime, timeconv);
1976 GetProcessTimes (GetCurrentProcess(), crtime, xittime, systime, usrtime);
1977 FileTimeToSystemTime (systime, timeconv);
1981 ans += (double)timeconv->wHour * 3600;
1982 ans += (double)timeconv->wMinute * 60;
1983 ans += (double)timeconv->wSecond;
1984 ans += (double)timeconv->wMilliseconds / 1000;
1989 #include <sys/resource.h>
1991 double getCpuTime(int type)
1993 struct rusage used[1];
1994 struct timeval tv[1];
1998 gettimeofday(tv, NULL);
1999 return (double)tv->tv_sec + (double)tv->tv_usec / 1000000;
2002 getrusage(RUSAGE_SELF, used);
2003 return (double)used->ru_utime.tv_sec + (double)used->ru_utime.tv_usec / 1000000;
2006 getrusage(RUSAGE_SELF, used);
2007 return (double)used->ru_stime.tv_sec + (double)used->ru_stime.tv_usec / 1000000;
2014 // standalone program to index file of keys
2015 // then list them onto std-out
2017 int main (int argc, char **argv)
2019 uint slot, line = 0, off = 0, found = 0;
2020 int ch, cnt = 0, bits = 12, idx;
2021 unsigned char key[256];
2034 fprintf (stderr, "Usage: %s idx_file src_file Read/Write/Scan/Delete/Find/Count [page_bits mapped_pool_pages start_line_number]\n", argv[0]);
2035 fprintf (stderr, " page_bits: size of btree page in bits\n");
2036 fprintf (stderr, " mapped_pool_pages: number of pages in buffer pool\n");
2040 start = getCpuTime(0);
2044 bits = atoi(argv[4]);
2047 map = atoi(argv[5]);
2050 off = atoi(argv[6]);
2052 bt = bt_open ((argv[1]), BT_rw, bits, map);
2055 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2059 switch(argv[3][0]| 0x20)
2062 fprintf(stderr, "started audit for %s\n", argv[2]);
2063 cnt = bt_audit (bt);
2064 fprintf(stderr, "finished audit for %s, %d keys\n", argv[2], cnt);
2068 fprintf(stderr, "started indexing for %s\n", argv[2]);
2069 if( argc > 2 && (in = fopen (argv[2], "rb")) )
2070 while( ch = getc(in), ch != EOF )
2074 sprintf((char *)key+len, "%.9d", line + off), len += 9;
2076 if( bt_insertkey (bt, key, len, 0, ++line, *tod) )
2077 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2080 else if( len < 245 )
2082 fprintf(stderr, "finished adding keys for %s, %d \n", argv[2], line);
2086 fprintf(stderr, "started deleting keys for %s\n", argv[2]);
2087 if( argc > 2 && (in = fopen (argv[2], "rb")) )
2088 while( ch = getc(in), ch != EOF )
2092 sprintf((char *)key+len, "%.9d", line + off), len += 9;
2094 if( bt_deletekey (bt, key, len, 0) )
2095 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2098 else if( len < 245 )
2100 fprintf(stderr, "finished deleting keys for %s, %d \n", argv[2], line);
2104 fprintf(stderr, "started finding keys for %s\n", argv[2]);
2105 if( argc > 2 && (in = fopen (argv[2], "rb")) )
2106 while( ch = getc(in), ch != EOF )
2110 sprintf((char *)key+len, "%.9d", line + off), len += 9;
2112 if( bt_findkey (bt, key, len) )
2115 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2118 else if( len < 245 )
2120 fprintf(stderr, "finished search of %d keys for %s, found %d\n", line, argv[2], found);
2124 fprintf(stderr, "started scaning\n");
2125 cnt = len = key[0] = 0;
2127 if( slot = bt_startkey (bt, key, len) )
2130 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
2132 while( slot = bt_nextkey (bt, slot) ) {
2133 ptr = bt_key(bt, slot);
2134 fwrite (ptr->key, ptr->len, 1, stdout);
2135 fputc ('\n', stdout);
2139 fprintf(stderr, " Total keys read %d\n", cnt - 1);
2143 fprintf(stderr, "started counting\n");
2146 next = bt->latchmgr->nlatchpage + LATCH_page;
2147 page_no = LEAF_page;
2149 while( page_no < bt_getid(bt->latchmgr->alloc->right) ) {
2152 if( latch = bt_pinlatch (bt, page_no) )
2153 page = bt_mappage (bt, latch);
2154 if( !page->free && !page->lvl )
2156 if( page_no > LEAF_page )
2159 for( idx = 0; idx++ < page->cnt; ) {
2160 if( slotptr(page, idx)->dead )
2162 ptr = keyptr(page, idx);
2163 if( idx != page->cnt && bt_getid (page->right) ) {
2164 fwrite (ptr->key, ptr->len, 1, stdout);
2165 fputc ('\n', stdout);
2168 bt_unpinlatch (latch);
2172 cnt--; // remove stopper key
2173 fprintf(stderr, " Total keys read %d\n", cnt);
2177 done = getCpuTime(0);
2178 elapsed = (float)(done - start);
2179 fprintf(stderr, " real %dm%.3fs\n", (int)(elapsed/60), elapsed - (int)(elapsed/60)*60);
2180 elapsed = getCpuTime(1);
2181 fprintf(stderr, " user %dm%.3fs\n", (int)(elapsed/60), elapsed - (int)(elapsed/60)*60);
2182 elapsed = getCpuTime(2);
2183 fprintf(stderr, " sys %dm%.3fs\n", (int)(elapsed/60), elapsed - (int)(elapsed/60)*60);