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 fprintf (stderr, "Unable to read page %.8x errno = %d\n", page_no, errno);
478 return bt->err = BTERR_read;
484 memset (ovl, 0, sizeof(OVERLAPPED));
486 ovl->OffsetHigh = off >> 32;
488 if( !ReadFile(bt->idx, page, bt->page_size, amt, ovl)) {
489 fprintf (stderr, "Unable to read page %.8x GetLastError = %d\n", page_no, GetLastError());
490 return bt->err = BTERR_read;
492 if( *amt < bt->page_size ) {
493 fprintf (stderr, "Unable to read page %.8x GetLastError = %d\n", page_no, GetLastError());
494 return bt->err = BTERR_read;
500 // write page to permanent location in Btree file
501 // clear the dirty bit
503 BTERR bt_writepage (BtDb *bt, BtPage page, uid page_no)
505 off64_t off = page_no << bt->page_bits;
510 if( pwrite(bt->idx, page, bt->page_size, off) < bt->page_size )
511 return bt->err = BTERR_wrt;
516 memset (ovl, 0, sizeof(OVERLAPPED));
518 ovl->OffsetHigh = off >> 32;
521 if( !WriteFile(bt->idx, page, bt->page_size, amt, ovl) )
522 return bt->err = BTERR_wrt;
524 if( *amt < bt->page_size )
525 return bt->err = BTERR_wrt;
530 // link latch table entry into head of latch hash table
532 BTERR bt_latchlink (BtDb *bt, uint hashidx, uint slot, uid page_no)
534 BtPage page = (BtPage)((uid)slot * bt->page_size + bt->pagepool);
535 BtLatchSet *latch = bt->latchsets + slot;
537 if( latch->next = bt->table[hashidx].slot )
538 bt->latchsets[latch->next].prev = slot;
540 bt->table[hashidx].slot = slot;
541 latch->page_no = page_no;
545 return bt_readpage (bt, page, page_no);
550 void bt_unpinlatch (BtLatchSet *latch)
553 __sync_fetch_and_add(&latch->pin, -1);
555 _InterlockedDecrement (&latch->pin);
559 // find existing latchset or inspire new one
560 // return with latchset pinned
562 BtLatchSet *bt_pinlatch (BtDb *bt, uid page_no)
564 uint hashidx = page_no % bt->latchmgr->latchhash;
571 // try to find unpinned entry
573 bt_spinwritelock(bt->table[hashidx].latch);
575 if( slot = bt->table[hashidx].slot ) do
577 latch = bt->latchsets + slot;
578 if( page_no == latch->page_no )
580 } while( slot = latch->next );
582 // found our entry, bring to front of hash chain
585 latch = bt->latchsets + slot;
587 __sync_fetch_and_add(&latch->pin, 1);
589 _InterlockedIncrement (&latch->pin);
591 // unlink our entry from its hash chain position
594 bt->latchsets[latch->prev].next = latch->next;
596 bt->table[hashidx].slot = latch->next;
599 bt->latchsets[latch->next].prev = latch->prev;
601 // now link into head of the hash chain
603 if( latch->next = bt->table[hashidx].slot )
604 bt->latchsets[latch->next].prev = slot;
606 bt->table[hashidx].slot = slot;
609 bt_spinreleasewrite(bt->table[hashidx].latch);
613 // see if there are any unused pool entries
615 slot = __sync_fetch_and_add (&bt->latchmgr->latchdeployed, 1) + 1;
617 slot = _InterlockedIncrement (&bt->latchmgr->latchdeployed);
620 if( slot < bt->latchmgr->latchtotal ) {
621 latch = bt->latchsets + slot;
622 if( bt_latchlink (bt, hashidx, slot, page_no) )
624 bt_spinreleasewrite (bt->table[hashidx].latch);
629 __sync_fetch_and_add (&bt->latchmgr->latchdeployed, -1);
631 _InterlockedDecrement (&bt->latchmgr->latchdeployed);
633 // find and reuse previous lru lock entry on victim hash chain
637 idx = __sync_fetch_and_add(&bt->latchmgr->latchvictim, 1);
639 idx = _InterlockedIncrement (&bt->latchmgr->latchvictim) - 1;
641 // try to get write lock on hash chain
642 // skip entry if not obtained
643 // or has outstanding locks
645 idx %= bt->latchmgr->latchhash;
647 if( !bt_spinwritetry (bt->table[idx].latch) )
650 if( slot = bt->table[idx].slot )
652 latch = bt->latchsets + slot;
658 if( !slot || latch->pin ) {
659 bt_spinreleasewrite (bt->table[idx].latch);
663 // update permanent page area in btree
665 page = (BtPage)((uid)slot * bt->page_size + bt->pagepool);
668 if( bt_writepage (bt, page, latch->page_no) )
671 // unlink our available slot from its hash chain
674 bt->latchsets[latch->prev].next = latch->next;
676 bt->table[idx].slot = latch->next;
679 bt->latchsets[latch->next].prev = latch->prev;
681 bt_spinreleasewrite (bt->table[idx].latch);
683 if( bt_latchlink (bt, hashidx, slot, page_no) )
686 bt_spinreleasewrite (bt->table[hashidx].latch);
691 // close and release memory
693 void bt_close (BtDb *bt)
696 munmap (bt->table, bt->latchmgr->nlatchpage * bt->page_size);
697 munmap (bt->latchmgr, bt->page_size);
699 FlushViewOfFile(bt->latchmgr, 0);
700 UnmapViewOfFile(bt->latchmgr);
701 CloseHandle(bt->halloc);
710 VirtualFree (bt->mem, 0, MEM_RELEASE);
711 FlushFileBuffers(bt->idx);
712 CloseHandle(bt->idx);
716 // open/create new btree
718 // call with file_name, BT_openmode, bits in page size (e.g. 16),
719 // size of mapped page pool (e.g. 8192)
721 BtDb *bt_open (char *name, uint mode, uint bits, uint nodemax)
723 uint lvl, attr, last, slot, idx;
724 uint nlatchpage, latchhash;
725 BtLatchMgr *latchmgr;
735 struct flock lock[1];
738 // determine sanity of page size and buffer pool
740 if( bits > BT_maxbits )
742 else if( bits < BT_minbits )
745 if( mode == BT_ro ) {
746 fprintf(stderr, "ReadOnly mode not supported: %s\n", name);
750 bt = calloc (1, sizeof(BtDb));
752 bt->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
754 if( bt->idx == -1 ) {
755 fprintf(stderr, "unable to open %s\n", name);
756 return free(bt), NULL;
759 bt = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtDb));
760 attr = FILE_ATTRIBUTE_NORMAL;
761 bt->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
763 if( bt->idx == INVALID_HANDLE_VALUE ) {
764 fprintf(stderr, "unable to open %s\n", name);
765 return GlobalFree(bt), NULL;
769 memset (lock, 0, sizeof(lock));
770 lock->l_len = sizeof(struct BtPage_);
771 lock->l_type = F_WRLCK;
773 if( fcntl (bt->idx, F_SETLKW, lock) < 0 ) {
774 fprintf(stderr, "unable to lock record zero %s\n", name);
775 return bt_close (bt), NULL;
778 memset (ovl, 0, sizeof(ovl));
780 // use large offsets to
781 // simulate advisory locking
783 ovl->OffsetHigh |= 0x80000000;
785 if( !LockFileEx (bt->idx, LOCKFILE_EXCLUSIVE_LOCK, 0, sizeof(struct BtPage_), 0L, ovl) ) {
786 fprintf(stderr, "unable to lock record zero %s, GetLastError = %d\n", name, GetLastError());
787 return bt_close (bt), NULL;
792 latchmgr = malloc (BT_maxpage);
795 // read minimum page size to get root info
797 if( size = lseek (bt->idx, 0L, 2) ) {
798 if( pread(bt->idx, latchmgr, BT_minpage, 0) == BT_minpage )
799 bits = latchmgr->alloc->bits;
801 fprintf(stderr, "Unable to read page zero\n");
802 return free(bt), free(latchmgr), NULL;
806 latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
807 size = GetFileSize(bt->idx, amt);
810 if( !ReadFile(bt->idx, (char *)latchmgr, BT_minpage, amt, NULL) ) {
811 fprintf(stderr, "Unable to read page zero\n");
812 return bt_close (bt), NULL;
814 bits = latchmgr->alloc->bits;
818 bt->page_size = 1 << bits;
819 bt->page_bits = bits;
824 nlatchpage = latchmgr->nlatchpage;
829 fprintf(stderr, "Buffer pool too small: %d\n", nodemax);
830 return bt_close(bt), NULL;
833 // initialize an empty b-tree with latch page, root page, page of leaves
834 // and page(s) of latches and page pool cache
836 memset (latchmgr, 0, 1 << bits);
837 latchmgr->alloc->bits = bt->page_bits;
839 // calculate number of latch hash table entries
841 nlatchpage = (nodemax/16 * sizeof(BtHashEntry) + bt->page_size - 1) / bt->page_size;
842 latchhash = nlatchpage * bt->page_size / sizeof(BtHashEntry);
844 nlatchpage += nodemax; // size of the buffer pool in pages
845 nlatchpage += (sizeof(BtLatchSet) * nodemax + bt->page_size - 1)/bt->page_size;
847 bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
848 latchmgr->nlatchpage = nlatchpage;
849 latchmgr->latchtotal = nodemax;
850 latchmgr->latchhash = latchhash;
852 if( bt_writepage (bt, latchmgr->alloc, 0) ) {
853 fprintf (stderr, "Unable to create btree page zero\n");
854 return bt_close (bt), NULL;
857 memset (latchmgr, 0, 1 << bits);
858 latchmgr->alloc->bits = bt->page_bits;
860 for( lvl=MIN_lvl; lvl--; ) {
861 last = MIN_lvl - lvl; // page number
862 slotptr(latchmgr->alloc, 1)->off = bt->page_size - 3;
863 bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? last + 1 : 0);
864 key = keyptr(latchmgr->alloc, 1);
865 key->len = 2; // create stopper key
869 latchmgr->alloc->min = bt->page_size - 3;
870 latchmgr->alloc->lvl = lvl;
871 latchmgr->alloc->cnt = 1;
872 latchmgr->alloc->act = 1;
874 if( bt_writepage (bt, latchmgr->alloc, last) ) {
875 fprintf (stderr, "Unable to create btree page %.8x\n", last);
876 return bt_close (bt), NULL;
880 // clear out buffer pool pages
882 memset(latchmgr, 0, bt->page_size);
885 while( ++last < ((MIN_lvl + 1 + nlatchpage) ) )
886 if( bt_writepage (bt, latchmgr->alloc, last) ) {
887 fprintf (stderr, "Unable to write buffer pool page %.8x\n", last);
888 return bt_close (bt), NULL;
894 VirtualFree (latchmgr, 0, MEM_RELEASE);
899 lock->l_type = F_UNLCK;
900 if( fcntl (bt->idx, F_SETLK, lock) < 0 ) {
901 fprintf (stderr, "Unable to unlock page zero\n");
902 return bt_close (bt), NULL;
905 if( !UnlockFileEx (bt->idx, 0, sizeof(struct BtPage_), 0, ovl) ) {
906 fprintf (stderr, "Unable to unlock page zero, GetLastError = %d\n", GetLastError());
907 return bt_close (bt), NULL;
911 flag = PROT_READ | PROT_WRITE;
912 bt->latchmgr = mmap (0, bt->page_size, flag, MAP_SHARED, bt->idx, ALLOC_page * bt->page_size);
913 if( bt->latchmgr == MAP_FAILED ) {
914 fprintf (stderr, "Unable to mmap page zero, errno = %d", errno);
915 return bt_close (bt), NULL;
917 bt->table = (void *)mmap (0, (uid)nlatchpage * bt->page_size, flag, MAP_SHARED, bt->idx, LATCH_page * bt->page_size);
918 if( bt->table == MAP_FAILED ) {
919 fprintf (stderr, "Unable to mmap buffer pool, errno = %d", errno);
920 return bt_close (bt), NULL;
923 flag = PAGE_READWRITE;
924 bt->halloc = CreateFileMapping(bt->idx, NULL, flag, 0, ((uid)nlatchpage + LATCH_page) * bt->page_size, NULL);
926 fprintf (stderr, "Unable to create file mapping for buffer pool mgr, GetLastError = %d\n", GetLastError());
927 return bt_close (bt), NULL;
930 flag = FILE_MAP_WRITE;
931 bt->latchmgr = MapViewOfFile(bt->halloc, flag, 0, 0, ((uid)nlatchpage + LATCH_page) * bt->page_size);
932 if( !bt->latchmgr ) {
933 fprintf (stderr, "Unable to map buffer pool, GetLastError = %d\n", GetLastError());
934 return bt_close (bt), NULL;
937 bt->table = (void *)((char *)bt->latchmgr + LATCH_page * bt->page_size);
939 bt->pagepool = (unsigned char *)bt->table + (uid)(nlatchpage - bt->latchmgr->latchtotal) * bt->page_size;
940 bt->latchsets = (BtLatchSet *)(bt->pagepool - (uid)bt->latchmgr->latchtotal * sizeof(BtLatchSet));
943 bt->mem = malloc (2 * bt->page_size);
945 bt->mem = VirtualAlloc(NULL, 2 * bt->page_size, MEM_COMMIT, PAGE_READWRITE);
947 bt->frame = (BtPage)bt->mem;
948 bt->cursor = (BtPage)(bt->mem + bt->page_size);
952 // place write, read, or parent lock on requested page_no.
954 void bt_lockpage(BtLock mode, BtLatchSet *latch)
958 bt_spinreadlock (latch->readwr);
961 bt_spinwritelock (latch->readwr);
964 bt_spinreadlock (latch->access);
967 bt_spinwritelock (latch->access);
970 bt_spinwritelock (latch->parent);
975 // remove write, read, or parent lock on requested page
977 void bt_unlockpage(BtLock mode, BtLatchSet *latch)
981 bt_spinreleaseread (latch->readwr);
984 bt_spinreleasewrite (latch->readwr);
987 bt_spinreleaseread (latch->access);
990 bt_spinreleasewrite (latch->access);
993 bt_spinreleasewrite (latch->parent);
998 // allocate a new page and write page into it
1000 uid bt_newpage(BtDb *bt, BtPage page)
1006 // lock allocation page
1008 bt_spinwritelock(bt->latchmgr->lock);
1010 // use empty chain first
1011 // else allocate empty page
1013 if( new_page = bt_getid(bt->latchmgr->alloc[1].right) ) {
1014 if( latch = bt_pinlatch (bt, new_page) )
1015 temp = bt_mappage (bt, latch);
1019 bt_putid(bt->latchmgr->alloc[1].right, bt_getid(temp->right));
1020 bt_spinreleasewrite(bt->latchmgr->lock);
1021 memcpy (temp, page, bt->page_size);
1023 bt_update (bt, temp);
1024 bt_unpinlatch (latch);
1027 new_page = bt_getid(bt->latchmgr->alloc->right);
1028 bt_putid(bt->latchmgr->alloc->right, new_page+1);
1029 bt_spinreleasewrite(bt->latchmgr->lock);
1031 if( bt_writepage (bt, page, new_page) )
1035 bt_update (bt, bt->latchmgr->alloc);
1039 // compare two keys, returning > 0, = 0, or < 0
1040 // as the comparison value
1042 int keycmp (BtKey key1, unsigned char *key2, uint len2)
1044 uint len1 = key1->len;
1047 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
1058 // Update current page of btree by
1059 // flushing mapped area to disk backing of cache pool.
1060 // mark page as dirty for rewrite to permanent location
1062 void bt_update (BtDb *bt, BtPage page)
1065 msync (page, bt->page_size, MS_ASYNC);
1067 // FlushViewOfFile (page, bt->page_size);
1072 // map the btree cached page onto current page
1074 BtPage bt_mappage (BtDb *bt, BtLatchSet *latch)
1076 return (BtPage)((uid)(latch - bt->latchsets) * bt->page_size + bt->pagepool);
1079 // deallocate a deleted page
1080 // place on free chain out of allocator page
1081 // call with page latched for Writing and Deleting
1083 BTERR bt_freepage(BtDb *bt, uid page_no, BtLatchSet *latch)
1085 BtPage page = bt_mappage (bt, latch);
1087 // lock allocation page
1089 bt_spinwritelock (bt->latchmgr->lock);
1091 // store chain in second right
1092 bt_putid(page->right, bt_getid(bt->latchmgr->alloc[1].right));
1093 bt_putid(bt->latchmgr->alloc[1].right, page_no);
1096 bt_update(bt, page);
1098 // unlock released page
1100 bt_unlockpage (BtLockDelete, latch);
1101 bt_unlockpage (BtLockWrite, latch);
1102 bt_unpinlatch (latch);
1104 // unlock allocation page
1106 bt_spinreleasewrite (bt->latchmgr->lock);
1107 bt_update (bt, bt->latchmgr->alloc);
1111 // find slot in page for given key at a given level
1113 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1115 uint diff, higher = bt->page->cnt, low = 1, slot;
1118 // make stopper key an infinite fence value
1120 if( bt_getid (bt->page->right) )
1125 // low is the lowest candidate, higher is already
1126 // tested as .ge. the given key, loop ends when they meet
1128 while( diff = higher - low ) {
1129 slot = low + ( diff >> 1 );
1130 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1133 higher = slot, good++;
1136 // return zero if key is on right link page
1138 return good ? higher : 0;
1141 // find and load page at given level for given key
1142 // leave page rd or wr locked as requested
1144 int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, uint lock)
1146 uid page_no = ROOT_page, prevpage = 0;
1147 uint drill = 0xff, slot;
1148 BtLatchSet *prevlatch;
1149 uint mode, prevmode;
1151 // start at root of btree and drill down
1154 // determine lock mode of drill level
1155 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1157 if( bt->latch = bt_pinlatch(bt, page_no) )
1158 bt->page_no = page_no;
1162 // obtain access lock using lock chaining
1164 if( page_no > ROOT_page )
1165 bt_lockpage(BtLockAccess, bt->latch);
1168 bt_unlockpage(prevmode, prevlatch);
1169 bt_unpinlatch(prevlatch);
1173 // obtain read lock using lock chaining
1175 bt_lockpage(mode, bt->latch);
1177 if( page_no > ROOT_page )
1178 bt_unlockpage(BtLockAccess, bt->latch);
1180 // map/obtain page contents
1182 bt->page = bt_mappage (bt, bt->latch);
1184 // re-read and re-lock root after determining actual level of root
1186 if( bt->page->lvl != drill) {
1187 if( bt->page_no != ROOT_page )
1188 return bt->err = BTERR_struct, 0;
1190 drill = bt->page->lvl;
1192 if( lock != BtLockRead && drill == lvl ) {
1193 bt_unlockpage(mode, bt->latch);
1194 bt_unpinlatch(bt->latch);
1199 prevpage = bt->page_no;
1200 prevlatch = bt->latch;
1203 // find key on page at this level
1204 // and descend to requested level
1206 if( !bt->page->kill )
1207 if( slot = bt_findslot (bt, key, len) ) {
1211 while( slotptr(bt->page, slot)->dead )
1212 if( slot++ < bt->page->cnt )
1217 page_no = bt_getid(slotptr(bt->page, slot)->id);
1222 // or slide right into next page
1225 page_no = bt_getid(bt->page->right);
1229 // return error on end of right chain
1231 bt->err = BTERR_eof;
1232 return 0; // return error
1235 // a fence key was deleted from a page
1236 // push new fence value upwards
1238 BTERR bt_fixfence (BtDb *bt, uid page_no, uint lvl)
1240 unsigned char leftkey[256], rightkey[256];
1241 BtLatchSet *latch = bt->latch;
1244 // remove deleted key, the old fence value
1246 ptr = keyptr(bt->page, bt->page->cnt);
1247 memcpy(rightkey, ptr, ptr->len + 1);
1249 memset (slotptr(bt->page, bt->page->cnt--), 0, sizeof(BtSlot));
1250 bt->page->clean = 1;
1252 ptr = keyptr(bt->page, bt->page->cnt);
1253 memcpy(leftkey, ptr, ptr->len + 1);
1255 bt_update (bt, bt->page);
1256 bt_lockpage (BtLockParent, latch);
1257 bt_unlockpage (BtLockWrite, latch);
1259 // insert new (now smaller) fence key
1261 if( bt_insertkey (bt, leftkey+1, *leftkey, lvl + 1, page_no, time(NULL)) )
1264 // remove old (larger) fence key
1266 if( bt_deletekey (bt, rightkey+1, *rightkey, lvl + 1) )
1269 bt_unlockpage (BtLockParent, latch);
1270 bt_unpinlatch (latch);
1274 // root has a single child
1275 // collapse a level from the btree
1276 // call with root locked in bt->page
1278 BTERR bt_collapseroot (BtDb *bt, BtPage root)
1285 // find the child entry
1286 // and promote to new root
1289 for( idx = 0; idx++ < root->cnt; )
1290 if( !slotptr(root, idx)->dead )
1293 child = bt_getid (slotptr(root, idx)->id);
1294 if( latch = bt_pinlatch (bt, child) )
1295 temp = bt_mappage (bt, latch);
1299 bt_lockpage (BtLockDelete, latch);
1300 bt_lockpage (BtLockWrite, latch);
1301 memcpy (root, temp, bt->page_size);
1303 bt_update (bt, root);
1305 if( bt_freepage (bt, child, latch) )
1308 } while( root->lvl > 1 && root->act == 1 );
1310 bt_unlockpage (BtLockWrite, bt->latch);
1311 bt_unpinlatch (bt->latch);
1315 // find and delete key on page by marking delete flag bit
1316 // when page becomes empty, delete it
1318 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl)
1320 unsigned char lowerkey[256], higherkey[256];
1321 uint slot, dirty = 0, idx, fence, found;
1322 BtLatchSet *latch, *rlatch;
1327 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1328 ptr = keyptr(bt->page, slot);
1332 // are we deleting a fence slot?
1334 fence = slot == bt->page->cnt;
1336 // if key is found delete it, otherwise ignore request
1338 if( found = !keycmp (ptr, key, len) )
1339 if( found = slotptr(bt->page, slot)->dead == 0 ) {
1340 dirty = slotptr(bt->page,slot)->dead = 1;
1341 bt->page->clean = 1;
1344 // collapse empty slots
1346 while( idx = bt->page->cnt - 1 )
1347 if( slotptr(bt->page, idx)->dead ) {
1348 *slotptr(bt->page, idx) = *slotptr(bt->page, idx + 1);
1349 memset (slotptr(bt->page, bt->page->cnt--), 0, sizeof(BtSlot));
1354 right = bt_getid(bt->page->right);
1355 page_no = bt->page_no;
1360 return bt_abort (bt, bt->page, page_no, BTERR_notfound);
1361 bt_unlockpage(BtLockWrite, latch);
1362 bt_unpinlatch (latch);
1363 return bt->found = found, 0;
1366 // did we delete a fence key in an upper level?
1368 if( lvl && bt->page->act && fence )
1369 if( bt_fixfence (bt, page_no, lvl) )
1372 return bt->found = found, 0;
1374 // is this a collapsed root?
1376 if( lvl > 1 && page_no == ROOT_page && bt->page->act == 1 )
1377 if( bt_collapseroot (bt, bt->page) )
1380 return bt->found = found, 0;
1382 // return if page is not empty
1384 if( bt->page->act ) {
1385 bt_update(bt, bt->page);
1386 bt_unlockpage(BtLockWrite, latch);
1387 bt_unpinlatch (latch);
1388 return bt->found = found, 0;
1391 // cache copy of fence key
1392 // in order to find parent
1394 ptr = keyptr(bt->page, bt->page->cnt);
1395 memcpy(lowerkey, ptr, ptr->len + 1);
1397 // obtain lock on right page
1399 if( rlatch = bt_pinlatch (bt, right) )
1400 temp = bt_mappage (bt, rlatch);
1404 bt_lockpage(BtLockWrite, rlatch);
1407 bt_abort(bt, temp, right, 0);
1408 return bt_abort(bt, bt->page, bt->page_no, BTERR_kill);
1411 // pull contents of next page into current empty page
1413 memcpy (bt->page, temp, bt->page_size);
1415 // cache copy of key to update
1417 ptr = keyptr(temp, temp->cnt);
1418 memcpy(higherkey, ptr, ptr->len + 1);
1420 // Mark right page as deleted and point it to left page
1421 // until we can post updates at higher level.
1423 bt_putid(temp->right, page_no);
1426 bt_update(bt, bt->page);
1427 bt_update(bt, temp);
1429 bt_lockpage(BtLockParent, latch);
1430 bt_unlockpage(BtLockWrite, latch);
1432 bt_lockpage(BtLockParent, rlatch);
1433 bt_unlockpage(BtLockWrite, rlatch);
1435 // redirect higher key directly to consolidated node
1437 if( bt_insertkey (bt, higherkey+1, *higherkey, lvl+1, page_no, time(NULL)) )
1440 // delete old lower key to consolidated node
1442 if( bt_deletekey (bt, lowerkey + 1, *lowerkey, lvl + 1) )
1445 // obtain write & delete lock on deleted node
1446 // add right block to free chain
1448 bt_lockpage(BtLockDelete, rlatch);
1449 bt_lockpage(BtLockWrite, rlatch);
1450 bt_unlockpage(BtLockParent, rlatch);
1452 if( bt_freepage (bt, right, rlatch) )
1455 bt_unlockpage(BtLockParent, latch);
1456 bt_unpinlatch(latch);
1460 // find key in leaf level and return row-id
1462 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1468 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1469 ptr = keyptr(bt->page, slot);
1473 // if key exists, return row-id
1474 // otherwise return 0
1476 if( ptr->len == len && !memcmp (ptr->key, key, len) )
1477 id = bt_getid(slotptr(bt->page,slot)->id);
1481 bt_unlockpage (BtLockRead, bt->latch);
1482 bt_unpinlatch (bt->latch);
1486 // check page for space available,
1487 // clean if necessary and return
1488 // 0 - page needs splitting
1489 // >0 - go ahead with new slot
1491 uint bt_cleanpage(BtDb *bt, uint amt, uint slot)
1493 uint nxt = bt->page_size;
1494 BtPage page = bt->page;
1495 uint cnt = 0, idx = 0;
1496 uint max = page->cnt;
1497 uint newslot = slot;
1501 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1504 // skip cleanup if nothing to reclaim
1509 memcpy (bt->frame, page, bt->page_size);
1511 // skip page info and set rest of page to zero
1513 memset (page+1, 0, bt->page_size - sizeof(*page));
1516 while( cnt++ < max ) {
1519 // always leave fence key in list
1520 if( cnt < max && slotptr(bt->frame,cnt)->dead )
1524 key = keyptr(bt->frame, cnt);
1525 nxt -= key->len + 1;
1526 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1529 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1530 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1533 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1535 slotptr(page, idx)->off = nxt;
1541 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1547 // split the root and raise the height of the btree
1549 BTERR bt_splitroot(BtDb *bt, unsigned char *leftkey, uid page_no2)
1551 uint nxt = bt->page_size;
1552 BtPage root = bt->page;
1555 // Obtain an empty page to use, and copy the current
1556 // root contents into it
1558 if( !(right = bt_newpage(bt, root)) )
1561 // preserve the page info at the bottom
1562 // and set rest to zero
1564 memset(root+1, 0, bt->page_size - sizeof(*root));
1566 // insert first key on newroot page
1568 nxt -= *leftkey + 1;
1569 memcpy ((unsigned char *)root + nxt, leftkey, *leftkey + 1);
1570 bt_putid(slotptr(root, 1)->id, right);
1571 slotptr(root, 1)->off = nxt;
1573 // insert second key on newroot page
1574 // and increase the root height
1577 ((unsigned char *)root)[nxt] = 2;
1578 ((unsigned char *)root)[nxt+1] = 0xff;
1579 ((unsigned char *)root)[nxt+2] = 0xff;
1580 bt_putid(slotptr(root, 2)->id, page_no2);
1581 slotptr(root, 2)->off = nxt;
1583 bt_putid(root->right, 0);
1584 root->min = nxt; // reset lowest used offset and key count
1589 // update and release root (bt->page)
1591 bt_update(bt, root);
1593 bt_unlockpage(BtLockWrite, bt->latch);
1594 bt_unpinlatch(bt->latch);
1598 // split already locked full node
1601 BTERR bt_splitpage (BtDb *bt)
1603 uint cnt = 0, idx = 0, max, nxt = bt->page_size;
1604 unsigned char fencekey[256], rightkey[256];
1605 uid page_no = bt->page_no, right;
1606 BtLatchSet *latch, *rlatch;
1607 BtPage page = bt->page;
1608 uint lvl = page->lvl;
1613 // split higher half of keys to bt->frame
1614 // the last key (fence key) might be dead
1616 memset (bt->frame, 0, bt->page_size);
1621 while( cnt++ < max ) {
1622 key = keyptr(page, cnt);
1623 nxt -= key->len + 1;
1624 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
1625 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
1626 if( !(slotptr(bt->frame, idx)->dead = slotptr(page, cnt)->dead) )
1629 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
1631 slotptr(bt->frame, idx)->off = nxt;
1634 // remember fence key for new right page
1636 memcpy (rightkey, key, key->len + 1);
1638 bt->frame->bits = bt->page_bits;
1639 bt->frame->min = nxt;
1640 bt->frame->cnt = idx;
1641 bt->frame->lvl = lvl;
1645 if( page_no > ROOT_page )
1646 memcpy (bt->frame->right, page->right, BtId);
1648 // get new free page and write frame to it.
1650 if( !(right = bt_newpage(bt, bt->frame)) )
1653 // update lower keys to continue in old page
1655 memcpy (bt->frame, page, bt->page_size);
1656 memset (page+1, 0, bt->page_size - sizeof(*page));
1657 nxt = bt->page_size;
1663 // assemble page of smaller keys
1664 // (they're all active keys)
1666 while( cnt++ < max / 2 ) {
1667 key = keyptr(bt->frame, cnt);
1668 nxt -= key->len + 1;
1669 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1670 memcpy(slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1672 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1674 slotptr(page, idx)->off = nxt;
1678 // remember fence key for smaller page
1680 memcpy (fencekey, key, key->len + 1);
1682 bt_putid(page->right, right);
1686 // if current page is the root page, split it
1688 if( page_no == ROOT_page )
1689 return bt_splitroot (bt, fencekey, right);
1693 if( rlatch = bt_pinlatch (bt, right) )
1694 bt_lockpage (BtLockParent, rlatch);
1698 // update left (containing) node
1700 bt_update(bt, page);
1702 bt_lockpage (BtLockParent, latch);
1703 bt_unlockpage (BtLockWrite, latch);
1705 // insert new fence for reformulated left block
1707 if( bt_insertkey (bt, fencekey+1, *fencekey, lvl+1, page_no, time(NULL)) )
1710 // switch fence for right block of larger keys to new right page
1712 if( bt_insertkey (bt, rightkey+1, *rightkey, lvl+1, right, time(NULL)) )
1715 bt_unlockpage (BtLockParent, latch);
1716 bt_unlockpage (BtLockParent, rlatch);
1718 bt_unpinlatch (rlatch);
1719 bt_unpinlatch (latch);
1723 // Insert new key into the btree at requested level.
1724 // Pages are unlocked at exit.
1726 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod)
1733 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1734 ptr = keyptr(bt->page, slot);
1738 bt->err = BTERR_ovflw;
1742 // if key already exists, update id and return
1746 if( !keycmp (ptr, key, len) ) {
1747 if( slotptr(page, slot)->dead )
1749 slotptr(page, slot)->dead = 0;
1751 slotptr(page, slot)->tod = tod;
1753 bt_putid(slotptr(page,slot)->id, id);
1754 bt_update(bt, bt->page);
1755 bt_unlockpage(BtLockWrite, bt->latch);
1756 bt_unpinlatch (bt->latch);
1760 // check if page has enough space
1762 if( slot = bt_cleanpage (bt, len, slot) )
1765 if( bt_splitpage (bt) )
1769 // calculate next available slot and copy key into page
1771 page->min -= len + 1; // reset lowest used offset
1772 ((unsigned char *)page)[page->min] = len;
1773 memcpy ((unsigned char *)page + page->min +1, key, len );
1775 for( idx = slot; idx < page->cnt; idx++ )
1776 if( slotptr(page, idx)->dead )
1779 // now insert key into array before slot
1780 // preserving the fence slot
1782 if( idx == page->cnt )
1788 *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
1790 bt_putid(slotptr(page,slot)->id, id);
1791 slotptr(page, slot)->off = page->min;
1793 slotptr(page, slot)->tod = tod;
1795 slotptr(page, slot)->dead = 0;
1797 bt_update(bt, bt->page);
1799 bt_unlockpage(BtLockWrite, bt->latch);
1800 bt_unpinlatch(bt->latch);
1804 // cache page of keys into cursor and return starting slot for given key
1806 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
1810 // cache page for retrieval
1812 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1813 memcpy (bt->cursor, bt->page, bt->page_size);
1817 bt_unlockpage(BtLockRead, bt->latch);
1818 bt->cursor_page = bt->page_no;
1819 bt_unpinlatch (bt->latch);
1823 // return next slot for cursor page
1824 // or slide cursor right into next page
1826 uint bt_nextkey (BtDb *bt, uint slot)
1832 right = bt_getid(bt->cursor->right);
1834 while( slot++ < bt->cursor->cnt )
1835 if( slotptr(bt->cursor,slot)->dead )
1837 else if( right || (slot < bt->cursor->cnt))
1845 bt->cursor_page = right;
1847 if( latch = bt_pinlatch (bt, right) )
1848 bt_lockpage(BtLockRead, latch);
1852 bt->page = bt_mappage (bt, latch);
1853 memcpy (bt->cursor, bt->page, bt->page_size);
1854 bt_unlockpage(BtLockRead, latch);
1855 bt_unpinlatch (latch);
1862 BtKey bt_key(BtDb *bt, uint slot)
1864 return keyptr(bt->cursor, slot);
1867 uid bt_uid(BtDb *bt, uint slot)
1869 return bt_getid(slotptr(bt->cursor,slot)->id);
1873 uint bt_tod(BtDb *bt, uint slot)
1875 return slotptr(bt->cursor,slot)->tod;
1881 uint bt_audit (BtDb *bt)
1891 if( *(ushort *)(bt->latchmgr->lock) )
1892 fprintf(stderr, "Alloc page locked\n");
1893 *(ushort *)(bt->latchmgr->lock) = 0;
1895 for( idx = 1; idx <= bt->latchmgr->latchdeployed; idx++ ) {
1896 latch = bt->latchsets + idx;
1897 if( *(ushort *)latch->readwr )
1898 fprintf(stderr, "latchset %d rwlocked for page %.8x\n", idx, latch->page_no);
1899 *(ushort *)latch->readwr = 0;
1901 if( *(ushort *)latch->access )
1902 fprintf(stderr, "latchset %d accesslocked for page %.8x\n", idx, latch->page_no);
1903 *(ushort *)latch->access = 0;
1905 if( *(ushort *)latch->parent )
1906 fprintf(stderr, "latchset %d parentlocked for page %.8x\n", idx, latch->page_no);
1907 *(ushort *)latch->parent = 0;
1910 fprintf(stderr, "latchset %d pinned for page %.8x\n", idx, latch->page_no);
1913 page = (BtPage)((uid)idx * bt->page_size + bt->pagepool);
1916 if( bt_writepage (bt, page, latch->page_no) )
1917 fprintf(stderr, "Page %.8x Write Error\n", latch->page_no);
1920 for( hashidx = 0; hashidx < bt->latchmgr->latchhash; hashidx++ ) {
1921 if( *(ushort *)(bt->table[hashidx].latch) )
1922 fprintf(stderr, "hash entry %d locked\n", hashidx);
1924 *(ushort *)(bt->table[hashidx].latch) = 0;
1926 if( idx = bt->table[hashidx].slot ) do {
1927 latch = bt->latchsets + idx;
1929 fprintf(stderr, "latchset %d pinned for page %.8x\n", idx, latch->page_no);
1930 } while( idx = latch->next );
1933 next = bt->latchmgr->nlatchpage + LATCH_page;
1934 page_no = LEAF_page;
1936 while( page_no < bt_getid(bt->latchmgr->alloc->right) ) {
1937 if( bt_readpage (bt, bt->frame, page_no) )
1938 fprintf(stderr, "page %.8x unreadable\n", page_no);
1939 if( !bt->frame->free ) {
1940 for( idx = 0; idx++ < bt->frame->cnt - 1; ) {
1941 ptr = keyptr(bt->frame, idx+1);
1942 if( keycmp (keyptr(bt->frame, idx), ptr->key, ptr->len) >= 0 )
1943 fprintf(stderr, "page %.8x idx %.2x out of order\n", page_no, idx);
1945 if( !bt->frame->lvl )
1946 cnt += bt->frame->act;
1949 if( page_no > LEAF_page )
1957 double getCpuTime(int type)
1960 FILETIME xittime[1];
1961 FILETIME systime[1];
1962 FILETIME usrtime[1];
1963 SYSTEMTIME timeconv[1];
1966 memset (timeconv, 0, sizeof(SYSTEMTIME));
1970 GetSystemTimeAsFileTime (xittime);
1971 FileTimeToSystemTime (xittime, timeconv);
1972 ans = (double)timeconv->wDayOfWeek * 3600 * 24;
1975 GetProcessTimes (GetCurrentProcess(), crtime, xittime, systime, usrtime);
1976 FileTimeToSystemTime (usrtime, timeconv);
1979 GetProcessTimes (GetCurrentProcess(), crtime, xittime, systime, usrtime);
1980 FileTimeToSystemTime (systime, timeconv);
1984 ans += (double)timeconv->wHour * 3600;
1985 ans += (double)timeconv->wMinute * 60;
1986 ans += (double)timeconv->wSecond;
1987 ans += (double)timeconv->wMilliseconds / 1000;
1992 #include <sys/resource.h>
1994 double getCpuTime(int type)
1996 struct rusage used[1];
1997 struct timeval tv[1];
2001 gettimeofday(tv, NULL);
2002 return (double)tv->tv_sec + (double)tv->tv_usec / 1000000;
2005 getrusage(RUSAGE_SELF, used);
2006 return (double)used->ru_utime.tv_sec + (double)used->ru_utime.tv_usec / 1000000;
2009 getrusage(RUSAGE_SELF, used);
2010 return (double)used->ru_stime.tv_sec + (double)used->ru_stime.tv_usec / 1000000;
2017 // standalone program to index file of keys
2018 // then list them onto std-out
2020 int main (int argc, char **argv)
2022 uint slot, line = 0, off = 0, found = 0;
2023 int ch, cnt = 0, bits = 12, idx;
2024 unsigned char key[256];
2037 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]);
2038 fprintf (stderr, " page_bits: size of btree page in bits\n");
2039 fprintf (stderr, " mapped_pool_pages: number of pages in buffer pool\n");
2043 start = getCpuTime(0);
2047 bits = atoi(argv[4]);
2050 map = atoi(argv[5]);
2053 off = atoi(argv[6]);
2055 bt = bt_open ((argv[1]), BT_rw, bits, map);
2058 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2062 switch(argv[3][0]| 0x20)
2065 fprintf(stderr, "started audit for %s\n", argv[2]);
2066 cnt = bt_audit (bt);
2067 fprintf(stderr, "finished audit for %s, %d keys\n", argv[2], cnt);
2071 fprintf(stderr, "started indexing for %s\n", argv[2]);
2072 if( argc > 2 && (in = fopen (argv[2], "rb")) )
2073 while( ch = getc(in), ch != EOF )
2077 sprintf((char *)key+len, "%.9d", line + off), len += 9;
2079 if( bt_insertkey (bt, key, len, 0, ++line, *tod) )
2080 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2083 else if( len < 245 )
2085 fprintf(stderr, "finished adding keys for %s, %d \n", argv[2], line);
2089 fprintf(stderr, "started deleting keys for %s\n", argv[2]);
2090 if( argc > 2 && (in = fopen (argv[2], "rb")) )
2091 while( ch = getc(in), ch != EOF )
2095 sprintf((char *)key+len, "%.9d", line + off), len += 9;
2097 if( bt_deletekey (bt, key, len, 0) )
2098 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2101 else if( len < 245 )
2103 fprintf(stderr, "finished deleting keys for %s, %d \n", argv[2], line);
2107 fprintf(stderr, "started finding keys for %s\n", argv[2]);
2108 if( argc > 2 && (in = fopen (argv[2], "rb")) )
2109 while( ch = getc(in), ch != EOF )
2113 sprintf((char *)key+len, "%.9d", line + off), len += 9;
2115 if( bt_findkey (bt, key, len) )
2118 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2121 else if( len < 245 )
2123 fprintf(stderr, "finished search of %d keys for %s, found %d\n", line, argv[2], found);
2127 fprintf(stderr, "started scaning\n");
2128 cnt = len = key[0] = 0;
2130 if( slot = bt_startkey (bt, key, len) )
2133 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
2135 while( slot = bt_nextkey (bt, slot) ) {
2136 ptr = bt_key(bt, slot);
2137 fwrite (ptr->key, ptr->len, 1, stdout);
2138 fputc ('\n', stdout);
2142 fprintf(stderr, " Total keys read %d\n", cnt - 1);
2146 fprintf(stderr, "started counting\n");
2149 next = bt->latchmgr->nlatchpage + LATCH_page;
2150 page_no = LEAF_page;
2152 while( page_no < bt_getid(bt->latchmgr->alloc->right) ) {
2155 if( latch = bt_pinlatch (bt, page_no) )
2156 page = bt_mappage (bt, latch);
2157 if( !page->free && !page->lvl )
2159 if( page_no > LEAF_page )
2162 for( idx = 0; idx++ < page->cnt; ) {
2163 if( slotptr(page, idx)->dead )
2165 ptr = keyptr(page, idx);
2166 if( idx != page->cnt && bt_getid (page->right) ) {
2167 fwrite (ptr->key, ptr->len, 1, stdout);
2168 fputc ('\n', stdout);
2171 bt_unpinlatch (latch);
2175 cnt--; // remove stopper key
2176 fprintf(stderr, " Total keys read %d\n", cnt);
2180 done = getCpuTime(0);
2181 elapsed = (float)(done - start);
2182 fprintf(stderr, " real %dm%.3fs\n", (int)(elapsed/60), elapsed - (int)(elapsed/60)*60);
2183 elapsed = getCpuTime(1);
2184 fprintf(stderr, " user %dm%.3fs\n", (int)(elapsed/60), elapsed - (int)(elapsed/60)*60);
2185 elapsed = getCpuTime(2);
2186 fprintf(stderr, " sys %dm%.3fs\n", (int)(elapsed/60), elapsed - (int)(elapsed/60)*60);