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
52 typedef unsigned long long uid;
55 typedef unsigned long long off64_t;
56 typedef unsigned short ushort;
57 typedef unsigned int uint;
60 #define BT_ro 0x6f72 // ro
61 #define BT_rw 0x7772 // rw
62 #define BT_fl 0x6c66 // fl
64 #define BT_maxbits 15 // maximum page size in bits
65 #define BT_minbits 12 // minimum page size in bits
66 #define BT_minpage (1 << BT_minbits) // minimum page size
67 #define BT_maxpage (1 << BT_maxbits) // maximum page size
69 // BTree page number constants
75 // Number of levels to create in a new BTree
81 There are five lock types for each node in three independent sets:
82 1. (set 1) AccessIntent: Sharable. Going to Read the node. Incompatible with NodeDelete.
83 2. (set 1) NodeDelete: Exclusive. About to release the node. Incompatible with AccessIntent.
84 3. (set 2) ReadLock: Sharable. Read the node. Incompatible with WriteLock.
85 4. (set 2) WriteLock: Exclusive. Modify the node. Incompatible with ReadLock and other WriteLocks.
86 5. (set 3) ParentModification: Exclusive. Change the node's parent keys. Incompatible with another ParentModification.
97 // definition for latch implementation
99 // exclusive is set for write access
100 // share is count of read accessors
101 // grant write lock when share == 0
103 volatile typedef struct {
104 unsigned char mutex[1];
105 unsigned char exclusive:1;
106 unsigned char pending:1;
110 // Define the length of the page and key pointers
114 // Page key slot definition.
116 // If BT_maxbits is 15 or less, you can save 2 bytes
117 // for each key stored by making the first two uints
118 // into ushorts. You can also save 4 bytes by removing
119 // the tod field from the key.
121 // Keys are marked dead, but remain on the page until
122 // cleanup is called. The fence key (highest key) for
123 // the page is always present, even if dead.
127 uint tod; // time-stamp for key
129 ushort off:BT_maxbits; // page offset for key start
130 ushort dead:1; // set for deleted key
131 unsigned char id[BtId]; // id associated with key
134 // The key structure occupies space at the upper end of
135 // each page. It's a length byte followed by the value
140 unsigned char key[0];
143 // The first part of an index page.
144 // It is immediately followed
145 // by the BtSlot array of keys.
147 typedef struct BtPage_ {
148 uint cnt; // count of keys in page
149 uint act; // count of active keys
150 uint min; // next key offset
151 unsigned char bits:6; // page size in bits
152 unsigned char free:1; // page is on free list
153 unsigned char dirty:1; // page is dirty in cache
154 unsigned char lvl:6; // level of page
155 unsigned char kill:1; // page is being deleted
156 unsigned char clean:1; // page needs cleaning
157 unsigned char right[BtId]; // page number to right
161 struct BtPage_ alloc[2]; // next & free page_nos in right ptr
162 BtSpinLatch lock[1]; // allocation area lite latch
163 volatile uint latchdeployed;// highest number of latch entries deployed
164 volatile uint nlatchpage; // number of latch pages at BT_latch
165 volatile uint latchtotal; // number of page latch entries
166 volatile uint latchhash; // number of latch hash table slots
167 volatile uint latchvictim; // next latch hash entry to examine
168 volatile uint safelevel; // safe page level in cache
169 volatile uint cache[MAX_lvl];// cache census counts by btree level
172 // latch hash table entries
175 volatile uint slot; // Latch table entry at head of collision chain
176 BtSpinLatch latch[1]; // lock for the collision chain
179 // latch manager table structure
182 volatile uid page_no; // latch set page number on disk
183 BtSpinLatch readwr[1]; // read/write page lock
184 BtSpinLatch access[1]; // Access Intent/Page delete
185 BtSpinLatch parent[1]; // Posting of fence key in parent
186 volatile ushort pin; // number of pins/level/clock bits
187 volatile uint next; // next entry in hash table chain
188 volatile uint prev; // prev entry in hash table chain
191 #define CLOCK_mask 0xe000
192 #define CLOCK_unit 0x2000
193 #define PIN_mask 0x07ff
194 #define LVL_mask 0x1800
197 // The object structure for Btree access
199 typedef struct _BtDb {
200 uint page_size; // each page size
201 uint page_bits; // each page size in bits
202 uid page_no; // current page number
203 uid cursor_page; // current cursor page number
205 uint mode; // read-write mode
206 BtPage cursor; // cached frame for start/next (never mapped)
207 BtPage frame; // spare frame for the page split (never mapped)
208 BtPage page; // current mapped page in buffer pool
209 BtLatchSet *latch; // current page latch
210 BtLatchMgr *latchmgr; // mapped latch page from allocation page
211 BtLatchSet *latchsets; // mapped latch set from latch pages
212 unsigned char *pagepool; // cached page pool set
213 BtHashEntry *table; // the hash table
218 HANDLE halloc; // allocation and latch table handle
220 unsigned char *mem; // frame, cursor, memory buffers
221 uint found; // last deletekey found key
239 extern void bt_close (BtDb *bt);
240 extern BtDb *bt_open (char *name, uint mode, uint bits, uint cacheblk);
241 extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod);
242 extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl);
243 extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
244 extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
245 extern uint bt_nextkey (BtDb *bt, uint slot);
247 // internal functions
248 void bt_update (BtDb *bt, BtPage page);
249 BtPage bt_mappage (BtDb *bt, BtLatchSet *latch);
250 // Helper functions to return slot values
252 extern BtKey bt_key (BtDb *bt, uint slot);
253 extern uid bt_uid (BtDb *bt, uint slot);
255 extern uint bt_tod (BtDb *bt, uint slot);
258 // The page is allocated from low and hi ends.
259 // The key offsets and row-id's are allocated
260 // from the bottom, while the text of the key
261 // is allocated from the top. When the two
262 // areas meet, the page is split into two.
264 // A key consists of a length byte, two bytes of
265 // index number (0 - 65534), and up to 253 bytes
266 // of key value. Duplicate keys are discarded.
267 // Associated with each key is a 48 bit row-id.
269 // The b-tree root is always located at page 1.
270 // The first leaf page of level zero is always
271 // located on page 2.
273 // The b-tree pages are linked with right
274 // pointers to facilitate enumerators,
275 // and provide for concurrency.
277 // When to root page fills, it is split in two and
278 // the tree height is raised by a new root at page
279 // one with two keys.
281 // Deleted keys are marked with a dead bit until
282 // page cleanup The fence key for a node is always
283 // present, even after deletion and cleanup.
285 // Deleted leaf pages are reclaimed on a free list.
286 // The upper levels of the btree are fixed on creation.
288 // To achieve maximum concurrency one page is locked at a time
289 // as the tree is traversed to find leaf key in question. The right
290 // page numbers are used in cases where the page is being split,
293 // Page 0 (ALLOC page) is dedicated to lock for new page extensions,
294 // and chains empty leaf pages together for reuse.
296 // Parent locks are obtained to prevent resplitting or deleting a node
297 // before its fence is posted into its upper level.
299 // A special open mode of BT_fl is provided to safely access files on
300 // WIN32 networks. WIN32 network operations should not use memory mapping.
301 // This WIN32 mode sets FILE_FLAG_NOBUFFERING and FILE_FLAG_WRITETHROUGH
302 // to prevent local caching of network file contents.
304 // Access macros to address slot and key values from the page.
305 // Page slots use 1 based indexing.
307 #define slotptr(page, slot) (((BtSlot *)(page+1)) + (slot-1))
308 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
310 void bt_putid(unsigned char *dest, uid id)
315 dest[i] = (unsigned char)id, id >>= 8;
318 uid bt_getid(unsigned char *src)
323 for( i = 0; i < BtId; i++ )
324 id <<= 8, id |= *src++;
329 BTERR bt_abort (BtDb *bt, BtPage page, uid page_no, BTERR err)
333 fprintf(stderr, "\n Btree2 abort, error %d on page %.8x\n", err, page_no);
334 fprintf(stderr, "level=%d kill=%d free=%d cnt=%x act=%x\n", page->lvl, page->kill, page->free, page->cnt, page->act);
335 ptr = keyptr(page, page->cnt);
336 fprintf(stderr, "fence='%.*s'\n", ptr->len, ptr->key);
337 fprintf(stderr, "right=%.8x\n", bt_getid(page->right));
338 return bt->err = err;
343 // wait until write lock mode is clear
344 // and add 1 to the share count
346 void bt_spinreadlock(BtSpinLatch *latch)
351 // obtain latch mutex
353 if( __sync_lock_test_and_set(latch->mutex, 1) )
356 if( _InterlockedExchange8(latch->mutex, 1) )
359 // see if exclusive request is granted or pending
361 if( prev = !(latch->exclusive | latch->pending) )
367 _InterlockedExchange8(latch->mutex, 0);
374 } while( sched_yield(), 1 );
376 } while( SwitchToThread(), 1 );
380 // wait for other read and write latches to relinquish
382 void bt_spinwritelock(BtSpinLatch *latch)
388 if( __sync_lock_test_and_set(latch->mutex, 1) )
391 if( _InterlockedExchange8(latch->mutex, 1) )
394 if( prev = !(latch->share | latch->exclusive) )
395 latch->exclusive = 1, latch->pending = 0;
401 _InterlockedExchange8(latch->mutex, 0);
406 } while( sched_yield(), 1 );
408 } while( SwitchToThread(), 1 );
412 // try to obtain write lock
414 // return 1 if obtained,
417 int bt_spinwritetry(BtSpinLatch *latch)
422 if( __sync_lock_test_and_set(latch->mutex, 1) )
425 if( _InterlockedExchange8(latch->mutex, 1) )
428 // take write access if all bits are clear
430 if( prev = !(latch->exclusive | latch->share) )
431 latch->exclusive = 1;
436 _InterlockedExchange8(latch->mutex, 0);
443 void bt_spinreleasewrite(BtSpinLatch *latch)
446 while( __sync_lock_test_and_set(latch->mutex, 1) )
449 while( _InterlockedExchange8(latch->mutex, 1) )
452 latch->exclusive = 0;
456 _InterlockedExchange8(latch->mutex, 0);
460 // decrement reader count
462 void bt_spinreleaseread(BtSpinLatch *latch)
465 while( __sync_lock_test_and_set(latch->mutex, 1) )
468 while( _InterlockedExchange8(latch->mutex, 1) )
475 _InterlockedExchange8(latch->mutex, 0);
479 // read page from permanent location in Btree file
481 BTERR bt_readpage (BtDb *bt, BtPage page, uid page_no)
483 off64_t off = page_no << bt->page_bits;
486 if( pread (bt->idx, page, bt->page_size, page_no << bt->page_bits) < bt->page_size ) {
487 fprintf (stderr, "Unable to read page %.8x errno = %d\n", page_no, errno);
488 return bt->err = BTERR_read;
494 memset (ovl, 0, sizeof(OVERLAPPED));
496 ovl->OffsetHigh = off >> 32;
498 if( !ReadFile(bt->idx, page, bt->page_size, amt, ovl)) {
499 fprintf (stderr, "Unable to read page %.8x GetLastError = %d\n", page_no, GetLastError());
500 return bt->err = BTERR_read;
502 if( *amt < bt->page_size ) {
503 fprintf (stderr, "Unable to read page %.8x GetLastError = %d\n", page_no, GetLastError());
504 return bt->err = BTERR_read;
510 // write page to permanent location in Btree file
511 // clear the dirty bit
513 BTERR bt_writepage (BtDb *bt, BtPage page, uid page_no)
515 off64_t off = page_no << bt->page_bits;
520 if( pwrite(bt->idx, page, bt->page_size, off) < bt->page_size )
521 return bt->err = BTERR_wrt;
526 memset (ovl, 0, sizeof(OVERLAPPED));
528 ovl->OffsetHigh = off >> 32;
531 if( !WriteFile(bt->idx, page, bt->page_size, amt, ovl) )
532 return bt->err = BTERR_wrt;
534 if( *amt < bt->page_size )
535 return bt->err = BTERR_wrt;
540 // link latch table entry into head of latch hash table
542 BTERR bt_latchlink (BtDb *bt, uint hashidx, uint slot, uid page_no)
544 BtPage page = (BtPage)((uid)slot * bt->page_size + bt->pagepool);
545 BtLatchSet *latch = bt->latchsets + slot;
548 if( latch->next = bt->table[hashidx].slot )
549 bt->latchsets[latch->next].prev = slot;
551 bt->table[hashidx].slot = slot;
552 latch->page_no = page_no;
556 if( bt_readpage (bt, page, page_no) )
559 lvl = page->lvl << LVL_shift;
562 latch->pin |= lvl; // store lvl
563 latch->pin |= lvl << 3; // initialize clock
566 __sync_fetch_and_add (&bt->latchmgr->cache[page->lvl], 1);
568 _InterlockedAdd(&bt->latchmgr->cache[page->lvl], 1);
575 void bt_unpinlatch (BtLatchSet *latch)
578 __sync_fetch_and_add(&latch->pin, -1);
580 _InterlockedDecrement16 (&latch->pin);
584 // find existing latchset or inspire new one
585 // return with latchset pinned
587 BtLatchSet *bt_pinlatch (BtDb *bt, uid page_no)
589 uint hashidx = page_no % bt->latchmgr->latchhash;
597 // try to find our entry
599 bt_spinwritelock(bt->table[hashidx].latch);
601 if( slot = bt->table[hashidx].slot ) do
603 latch = bt->latchsets + slot;
604 if( page_no == latch->page_no )
606 } while( slot = latch->next );
612 latch = bt->latchsets + slot;
613 lvl = (latch->pin & LVL_mask) >> LVL_shift;
614 lvl *= CLOCK_unit * 2;
617 __sync_fetch_and_add(&latch->pin, 1);
618 __sync_fetch_and_or(&latch->pin, lvl);
620 _InterlockedIncrement16 (&latch->pin);
621 _InterlockedOr16 (&latch->pin, lvl);
623 bt_spinreleasewrite(bt->table[hashidx].latch);
627 // see if there are any unused pool entries
629 slot = __sync_fetch_and_add (&bt->latchmgr->latchdeployed, 1) + 1;
631 slot = _InterlockedIncrement (&bt->latchmgr->latchdeployed);
634 if( slot < bt->latchmgr->latchtotal ) {
635 latch = bt->latchsets + slot;
636 if( bt_latchlink (bt, hashidx, slot, page_no) )
638 bt_spinreleasewrite (bt->table[hashidx].latch);
643 __sync_fetch_and_add (&bt->latchmgr->latchdeployed, -1);
645 _InterlockedDecrement (&bt->latchmgr->latchdeployed);
647 // find and reuse previous entry on victim
651 slot = __sync_fetch_and_add(&bt->latchmgr->latchvictim, 1);
653 slot = _InterlockedIncrement (&bt->latchmgr->latchvictim) - 1;
655 // try to get write lock on hash chain
656 // skip entry if not obtained
657 // or has outstanding pins
659 slot %= bt->latchmgr->latchtotal;
661 // on slot wraparound, check census
662 // count and increment safe level
664 cnt = bt->latchmgr->cache[bt->latchmgr->safelevel];
667 if( cnt < bt->latchmgr->latchtotal / 10 )
669 __sync_fetch_and_add(&bt->latchmgr->safelevel, 1);
671 _InterlockedIncrement (&bt->latchmgr->safelevel);
676 latch = bt->latchsets + slot;
677 idx = latch->page_no % bt->latchmgr->latchhash;
678 lvl = (latch->pin & LVL_mask) >> LVL_shift;
680 // see if we are evicting this level yet
682 if( lvl > bt->latchmgr->safelevel )
685 if( !bt_spinwritetry (bt->table[idx].latch) )
688 if( latch->pin & ~LVL_mask ) {
689 if( latch->pin & CLOCK_mask )
691 __sync_fetch_and_add(&latch->pin, -CLOCK_unit);
693 _InterlockedExchangeAdd16 (&latch->pin, -CLOCK_unit);
695 bt_spinreleasewrite (bt->table[idx].latch);
699 // update permanent page area in btree
701 page = (BtPage)((uid)slot * bt->page_size + bt->pagepool);
703 posix_fadvise (bt->idx, page_no << bt->page_bits, bt->page_size, POSIX_FADV_WILLNEED);
704 __sync_fetch_and_add (&bt->latchmgr->cache[page->lvl], -1);
706 _InterlockedAdd(&bt->latchmgr->cache[page->lvl], -1);
709 if( bt_writepage (bt, page, latch->page_no) )
712 // unlink our available slot from its hash chain
715 bt->latchsets[latch->prev].next = latch->next;
717 bt->table[idx].slot = latch->next;
720 bt->latchsets[latch->next].prev = latch->prev;
722 bt_spinreleasewrite (bt->table[idx].latch);
724 if( bt_latchlink (bt, hashidx, slot, page_no) )
727 bt_spinreleasewrite (bt->table[hashidx].latch);
732 // close and release memory
734 void bt_close (BtDb *bt)
737 munmap (bt->table, bt->latchmgr->nlatchpage * bt->page_size);
738 munmap (bt->latchmgr, bt->page_size);
740 FlushViewOfFile(bt->latchmgr, 0);
741 UnmapViewOfFile(bt->latchmgr);
742 CloseHandle(bt->halloc);
751 VirtualFree (bt->mem, 0, MEM_RELEASE);
752 FlushFileBuffers(bt->idx);
753 CloseHandle(bt->idx);
757 // open/create new btree
759 // call with file_name, BT_openmode, bits in page size (e.g. 16),
760 // size of mapped page pool (e.g. 8192)
762 BtDb *bt_open (char *name, uint mode, uint bits, uint nodemax)
764 uint lvl, attr, last, slot, idx;
765 uint nlatchpage, latchhash;
766 BtLatchMgr *latchmgr;
776 struct flock lock[1];
779 // determine sanity of page size and buffer pool
781 if( bits > BT_maxbits )
783 else if( bits < BT_minbits )
786 if( mode == BT_ro ) {
787 fprintf(stderr, "ReadOnly mode not supported: %s\n", name);
791 bt = calloc (1, sizeof(BtDb));
793 bt->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
794 posix_fadvise( bt->idx, 0, 0, POSIX_FADV_RANDOM);
796 if( bt->idx == -1 ) {
797 fprintf(stderr, "unable to open %s\n", name);
798 return free(bt), NULL;
801 bt = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtDb));
802 attr = FILE_ATTRIBUTE_NORMAL;
803 bt->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
805 if( bt->idx == INVALID_HANDLE_VALUE ) {
806 fprintf(stderr, "unable to open %s\n", name);
807 return GlobalFree(bt), NULL;
811 memset (lock, 0, sizeof(lock));
812 lock->l_len = sizeof(struct BtPage_);
813 lock->l_type = F_WRLCK;
815 if( fcntl (bt->idx, F_SETLKW, lock) < 0 ) {
816 fprintf(stderr, "unable to lock record zero %s\n", name);
817 return bt_close (bt), NULL;
820 memset (ovl, 0, sizeof(ovl));
822 // use large offsets to
823 // simulate advisory locking
825 ovl->OffsetHigh |= 0x80000000;
827 if( !LockFileEx (bt->idx, LOCKFILE_EXCLUSIVE_LOCK, 0, sizeof(struct BtPage_), 0L, ovl) ) {
828 fprintf(stderr, "unable to lock record zero %s, GetLastError = %d\n", name, GetLastError());
829 return bt_close (bt), NULL;
834 latchmgr = valloc (BT_maxpage);
837 // read minimum page size to get root info
839 if( size = lseek (bt->idx, 0L, 2) ) {
840 if( pread(bt->idx, latchmgr, BT_minpage, 0) == BT_minpage )
841 bits = latchmgr->alloc->bits;
843 fprintf(stderr, "Unable to read page zero\n");
844 return free(bt), free(latchmgr), NULL;
848 latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
849 size = GetFileSize(bt->idx, amt);
852 if( !ReadFile(bt->idx, (char *)latchmgr, BT_minpage, amt, NULL) ) {
853 fprintf(stderr, "Unable to read page zero\n");
854 return bt_close (bt), NULL;
856 bits = latchmgr->alloc->bits;
860 bt->page_size = 1 << bits;
861 bt->page_bits = bits;
866 nlatchpage = latchmgr->nlatchpage;
871 fprintf(stderr, "Buffer pool too small: %d\n", nodemax);
872 return bt_close(bt), NULL;
875 // initialize an empty b-tree with latch page, root page, page of leaves
876 // and page(s) of latches and page pool cache
878 memset (latchmgr, 0, 1 << bits);
879 latchmgr->alloc->bits = bt->page_bits;
881 // calculate number of latch hash table entries
883 nlatchpage = (nodemax/16 * sizeof(BtHashEntry) + bt->page_size - 1) / bt->page_size;
884 latchhash = nlatchpage * bt->page_size / sizeof(BtHashEntry);
886 nlatchpage += nodemax; // size of the buffer pool in pages
887 nlatchpage += (sizeof(BtLatchSet) * nodemax + bt->page_size - 1)/bt->page_size;
889 bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
890 latchmgr->nlatchpage = nlatchpage;
891 latchmgr->latchtotal = nodemax;
892 latchmgr->latchhash = latchhash;
894 if( bt_writepage (bt, latchmgr->alloc, 0) ) {
895 fprintf (stderr, "Unable to create btree page zero\n");
896 return bt_close (bt), NULL;
899 memset (latchmgr, 0, 1 << bits);
900 latchmgr->alloc->bits = bt->page_bits;
902 for( lvl=MIN_lvl; lvl--; ) {
903 last = MIN_lvl - lvl; // page number
904 slotptr(latchmgr->alloc, 1)->off = bt->page_size - 3;
905 bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? last + 1 : 0);
906 key = keyptr(latchmgr->alloc, 1);
907 key->len = 2; // create stopper key
911 latchmgr->alloc->min = bt->page_size - 3;
912 latchmgr->alloc->lvl = lvl;
913 latchmgr->alloc->cnt = 1;
914 latchmgr->alloc->act = 1;
916 if( bt_writepage (bt, latchmgr->alloc, last) ) {
917 fprintf (stderr, "Unable to create btree page %.8x\n", last);
918 return bt_close (bt), NULL;
922 // clear out buffer pool pages
924 memset(latchmgr, 0, bt->page_size);
925 last = MIN_lvl + nlatchpage;
927 if( bt_writepage (bt, latchmgr->alloc, last) ) {
928 fprintf (stderr, "Unable to write buffer pool page %.8x\n", last);
929 return bt_close (bt), NULL;
935 VirtualFree (latchmgr, 0, MEM_RELEASE);
940 lock->l_type = F_UNLCK;
941 if( fcntl (bt->idx, F_SETLK, lock) < 0 ) {
942 fprintf (stderr, "Unable to unlock page zero\n");
943 return bt_close (bt), NULL;
946 if( !UnlockFileEx (bt->idx, 0, sizeof(struct BtPage_), 0, ovl) ) {
947 fprintf (stderr, "Unable to unlock page zero, GetLastError = %d\n", GetLastError());
948 return bt_close (bt), NULL;
952 flag = PROT_READ | PROT_WRITE;
953 bt->latchmgr = mmap (0, bt->page_size, flag, MAP_SHARED, bt->idx, ALLOC_page * bt->page_size);
954 if( bt->latchmgr == MAP_FAILED ) {
955 fprintf (stderr, "Unable to mmap page zero, errno = %d", errno);
956 return bt_close (bt), NULL;
958 bt->table = (void *)mmap (0, (uid)nlatchpage * bt->page_size, flag, MAP_SHARED, bt->idx, LATCH_page * bt->page_size);
959 if( bt->table == MAP_FAILED ) {
960 fprintf (stderr, "Unable to mmap buffer pool, errno = %d", errno);
961 return bt_close (bt), NULL;
963 madvise (bt->table, (uid)nlatchpage << bt->page_bits, MADV_RANDOM | MADV_WILLNEED);
965 flag = PAGE_READWRITE;
966 bt->halloc = CreateFileMapping(bt->idx, NULL, flag, 0, ((uid)nlatchpage + LATCH_page) * bt->page_size, NULL);
968 fprintf (stderr, "Unable to create file mapping for buffer pool mgr, GetLastError = %d\n", GetLastError());
969 return bt_close (bt), NULL;
972 flag = FILE_MAP_WRITE;
973 bt->latchmgr = MapViewOfFile(bt->halloc, flag, 0, 0, ((uid)nlatchpage + LATCH_page) * bt->page_size);
974 if( !bt->latchmgr ) {
975 fprintf (stderr, "Unable to map buffer pool, GetLastError = %d\n", GetLastError());
976 return bt_close (bt), NULL;
979 bt->table = (void *)((char *)bt->latchmgr + LATCH_page * bt->page_size);
981 bt->pagepool = (unsigned char *)bt->table + (uid)(nlatchpage - bt->latchmgr->latchtotal) * bt->page_size;
982 bt->latchsets = (BtLatchSet *)(bt->pagepool - (uid)bt->latchmgr->latchtotal * sizeof(BtLatchSet));
985 bt->mem = valloc (2 * bt->page_size);
987 bt->mem = VirtualAlloc(NULL, 2 * bt->page_size, MEM_COMMIT, PAGE_READWRITE);
989 bt->frame = (BtPage)bt->mem;
990 bt->cursor = (BtPage)(bt->mem + bt->page_size);
994 // place write, read, or parent lock on requested page_no.
996 void bt_lockpage(BtLock mode, BtLatchSet *latch)
1000 bt_spinreadlock (latch->readwr);
1003 bt_spinwritelock (latch->readwr);
1006 bt_spinreadlock (latch->access);
1009 bt_spinwritelock (latch->access);
1012 bt_spinwritelock (latch->parent);
1017 // remove write, read, or parent lock on requested page
1019 void bt_unlockpage(BtLock mode, BtLatchSet *latch)
1023 bt_spinreleaseread (latch->readwr);
1026 bt_spinreleasewrite (latch->readwr);
1029 bt_spinreleaseread (latch->access);
1032 bt_spinreleasewrite (latch->access);
1035 bt_spinreleasewrite (latch->parent);
1040 // allocate a new page and write page into it
1042 uid bt_newpage(BtDb *bt, BtPage page)
1048 // lock allocation page
1050 bt_spinwritelock(bt->latchmgr->lock);
1052 // use empty chain first
1053 // else allocate empty page
1055 if( new_page = bt_getid(bt->latchmgr->alloc[1].right) ) {
1056 if( latch = bt_pinlatch (bt, new_page) )
1057 temp = bt_mappage (bt, latch);
1061 bt_putid(bt->latchmgr->alloc[1].right, bt_getid(temp->right));
1062 bt_spinreleasewrite(bt->latchmgr->lock);
1063 memcpy (temp, page, bt->page_size);
1065 bt_update (bt, temp);
1066 bt_unpinlatch (latch);
1069 new_page = bt_getid(bt->latchmgr->alloc->right);
1070 bt_putid(bt->latchmgr->alloc->right, new_page+1);
1071 bt_spinreleasewrite(bt->latchmgr->lock);
1073 if( bt_writepage (bt, page, new_page) )
1077 bt_update (bt, bt->latchmgr->alloc);
1081 // compare two keys, returning > 0, = 0, or < 0
1082 // as the comparison value
1084 int keycmp (BtKey key1, unsigned char *key2, uint len2)
1086 uint len1 = key1->len;
1089 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
1100 // Update current page of btree by
1101 // flushing mapped area to disk backing of cache pool.
1102 // mark page as dirty for rewrite to permanent location
1104 void bt_update (BtDb *bt, BtPage page)
1107 msync (page, bt->page_size, MS_ASYNC);
1109 // FlushViewOfFile (page, bt->page_size);
1114 // map the btree cached page onto current page
1116 BtPage bt_mappage (BtDb *bt, BtLatchSet *latch)
1118 return (BtPage)((uid)(latch - bt->latchsets) * bt->page_size + bt->pagepool);
1121 // deallocate a deleted page
1122 // place on free chain out of allocator page
1123 // call with page latched for Writing and Deleting
1125 BTERR bt_freepage(BtDb *bt, uid page_no, BtLatchSet *latch)
1127 BtPage page = bt_mappage (bt, latch);
1129 // lock allocation page
1131 bt_spinwritelock (bt->latchmgr->lock);
1133 // store chain in second right
1134 bt_putid(page->right, bt_getid(bt->latchmgr->alloc[1].right));
1135 bt_putid(bt->latchmgr->alloc[1].right, page_no);
1138 bt_update(bt, page);
1140 // unlock released page
1142 bt_unlockpage (BtLockDelete, latch);
1143 bt_unlockpage (BtLockWrite, latch);
1144 bt_unpinlatch (latch);
1146 // unlock allocation page
1148 bt_spinreleasewrite (bt->latchmgr->lock);
1149 bt_update (bt, bt->latchmgr->alloc);
1153 // find slot in page for given key at a given level
1155 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1157 uint diff, higher = bt->page->cnt, low = 1, slot;
1160 // make stopper key an infinite fence value
1162 if( bt_getid (bt->page->right) )
1167 // low is the lowest candidate, higher is already
1168 // tested as .ge. the given key, loop ends when they meet
1170 while( diff = higher - low ) {
1171 slot = low + ( diff >> 1 );
1172 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1175 higher = slot, good++;
1178 // return zero if key is on right link page
1180 return good ? higher : 0;
1183 // find and load page at given level for given key
1184 // leave page rd or wr locked as requested
1186 int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, uint lock)
1188 uid page_no = ROOT_page, prevpage = 0;
1189 uint drill = 0xff, slot;
1190 BtLatchSet *prevlatch;
1191 uint mode, prevmode;
1193 // start at root of btree and drill down
1196 // determine lock mode of drill level
1197 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1199 if( bt->latch = bt_pinlatch(bt, page_no) )
1200 bt->page_no = page_no;
1204 // obtain access lock using lock chaining
1206 if( page_no > ROOT_page )
1207 bt_lockpage(BtLockAccess, bt->latch);
1210 bt_unlockpage(prevmode, prevlatch);
1211 bt_unpinlatch(prevlatch);
1215 // obtain read lock using lock chaining
1217 bt_lockpage(mode, bt->latch);
1219 if( page_no > ROOT_page )
1220 bt_unlockpage(BtLockAccess, bt->latch);
1222 // map/obtain page contents
1224 bt->page = bt_mappage (bt, bt->latch);
1226 // re-read and re-lock root after determining actual level of root
1228 if( bt->page->lvl != drill) {
1229 if( bt->page_no != ROOT_page )
1230 return bt->err = BTERR_struct, 0;
1232 drill = bt->page->lvl;
1234 if( lock != BtLockRead && drill == lvl ) {
1235 bt_unlockpage(mode, bt->latch);
1236 bt_unpinlatch(bt->latch);
1241 prevpage = bt->page_no;
1242 prevlatch = bt->latch;
1245 // find key on page at this level
1246 // and descend to requested level
1248 if( !bt->page->kill )
1249 if( slot = bt_findslot (bt, key, len) ) {
1253 while( slotptr(bt->page, slot)->dead )
1254 if( slot++ < bt->page->cnt )
1259 page_no = bt_getid(slotptr(bt->page, slot)->id);
1264 // or slide right into next page
1267 page_no = bt_getid(bt->page->right);
1271 // return error on end of right chain
1273 bt->err = BTERR_eof;
1274 return 0; // return error
1277 // a fence key was deleted from a page
1278 // push new fence value upwards
1280 BTERR bt_fixfence (BtDb *bt, uid page_no, uint lvl)
1282 unsigned char leftkey[256], rightkey[256];
1283 BtLatchSet *latch = bt->latch;
1286 // remove deleted key, the old fence value
1288 ptr = keyptr(bt->page, bt->page->cnt);
1289 memcpy(rightkey, ptr, ptr->len + 1);
1291 memset (slotptr(bt->page, bt->page->cnt--), 0, sizeof(BtSlot));
1292 bt->page->clean = 1;
1294 ptr = keyptr(bt->page, bt->page->cnt);
1295 memcpy(leftkey, ptr, ptr->len + 1);
1297 bt_update (bt, bt->page);
1298 bt_lockpage (BtLockParent, latch);
1299 bt_unlockpage (BtLockWrite, latch);
1301 // insert new (now smaller) fence key
1303 if( bt_insertkey (bt, leftkey+1, *leftkey, lvl + 1, page_no, time(NULL)) )
1306 // remove old (larger) fence key
1308 if( bt_deletekey (bt, rightkey+1, *rightkey, lvl + 1) )
1311 bt_unlockpage (BtLockParent, latch);
1312 bt_unpinlatch (latch);
1316 // root has a single child
1317 // collapse a level from the btree
1318 // call with root locked in bt->page
1320 BTERR bt_collapseroot (BtDb *bt, BtPage root)
1327 // find the child entry
1328 // and promote to new root
1331 for( idx = 0; idx++ < root->cnt; )
1332 if( !slotptr(root, idx)->dead )
1335 child = bt_getid (slotptr(root, idx)->id);
1336 if( latch = bt_pinlatch (bt, child) )
1337 temp = bt_mappage (bt, latch);
1341 bt_lockpage (BtLockDelete, latch);
1342 bt_lockpage (BtLockWrite, latch);
1343 memcpy (root, temp, bt->page_size);
1345 bt_update (bt, root);
1347 if( bt_freepage (bt, child, latch) )
1350 } while( root->lvl > 1 && root->act == 1 );
1352 bt_unlockpage (BtLockWrite, bt->latch);
1353 bt_unpinlatch (bt->latch);
1357 // find and delete key on page by marking delete flag bit
1358 // when page becomes empty, delete it
1360 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl)
1362 unsigned char lowerkey[256], higherkey[256];
1363 uint slot, dirty = 0, idx, fence, found;
1364 BtLatchSet *latch, *rlatch;
1369 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1370 ptr = keyptr(bt->page, slot);
1374 // are we deleting a fence slot?
1376 fence = slot == bt->page->cnt;
1378 // if key is found delete it, otherwise ignore request
1380 if( found = !keycmp (ptr, key, len) )
1381 if( found = slotptr(bt->page, slot)->dead == 0 ) {
1382 dirty = slotptr(bt->page,slot)->dead = 1;
1383 bt->page->clean = 1;
1386 // collapse empty slots
1388 while( idx = bt->page->cnt - 1 )
1389 if( slotptr(bt->page, idx)->dead ) {
1390 *slotptr(bt->page, idx) = *slotptr(bt->page, idx + 1);
1391 memset (slotptr(bt->page, bt->page->cnt--), 0, sizeof(BtSlot));
1396 right = bt_getid(bt->page->right);
1397 page_no = bt->page_no;
1402 return bt_abort (bt, bt->page, page_no, BTERR_notfound);
1403 bt_unlockpage(BtLockWrite, latch);
1404 bt_unpinlatch (latch);
1405 return bt->found = found, 0;
1408 // did we delete a fence key in an upper level?
1410 if( lvl && bt->page->act && fence )
1411 if( bt_fixfence (bt, page_no, lvl) )
1414 return bt->found = found, 0;
1416 // is this a collapsed root?
1418 if( lvl > 1 && page_no == ROOT_page && bt->page->act == 1 )
1419 if( bt_collapseroot (bt, bt->page) )
1422 return bt->found = found, 0;
1424 // return if page is not empty
1426 if( bt->page->act ) {
1427 bt_update(bt, bt->page);
1428 bt_unlockpage(BtLockWrite, latch);
1429 bt_unpinlatch (latch);
1430 return bt->found = found, 0;
1433 // cache copy of fence key
1434 // in order to find parent
1436 ptr = keyptr(bt->page, bt->page->cnt);
1437 memcpy(lowerkey, ptr, ptr->len + 1);
1439 // obtain lock on right page
1441 if( rlatch = bt_pinlatch (bt, right) )
1442 temp = bt_mappage (bt, rlatch);
1446 bt_lockpage(BtLockWrite, rlatch);
1449 bt_abort(bt, temp, right, 0);
1450 return bt_abort(bt, bt->page, bt->page_no, BTERR_kill);
1453 // pull contents of next page into current empty page
1455 memcpy (bt->page, temp, bt->page_size);
1457 // cache copy of key to update
1459 ptr = keyptr(temp, temp->cnt);
1460 memcpy(higherkey, ptr, ptr->len + 1);
1462 // Mark right page as deleted and point it to left page
1463 // until we can post updates at higher level.
1465 bt_putid(temp->right, page_no);
1468 bt_update(bt, bt->page);
1469 bt_update(bt, temp);
1471 bt_lockpage(BtLockParent, latch);
1472 bt_unlockpage(BtLockWrite, latch);
1474 bt_lockpage(BtLockParent, rlatch);
1475 bt_unlockpage(BtLockWrite, rlatch);
1477 // redirect higher key directly to consolidated node
1479 if( bt_insertkey (bt, higherkey+1, *higherkey, lvl+1, page_no, time(NULL)) )
1482 // delete old lower key to consolidated node
1484 if( bt_deletekey (bt, lowerkey + 1, *lowerkey, lvl + 1) )
1487 // obtain write & delete lock on deleted node
1488 // add right block to free chain
1490 bt_lockpage(BtLockDelete, rlatch);
1491 bt_lockpage(BtLockWrite, rlatch);
1492 bt_unlockpage(BtLockParent, rlatch);
1494 if( bt_freepage (bt, right, rlatch) )
1497 bt_unlockpage(BtLockParent, latch);
1498 bt_unpinlatch(latch);
1502 // find key in leaf level and return row-id
1504 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1510 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1511 ptr = keyptr(bt->page, slot);
1515 // if key exists, return row-id
1516 // otherwise return 0
1518 if( ptr->len == len && !memcmp (ptr->key, key, len) )
1519 id = bt_getid(slotptr(bt->page,slot)->id);
1523 bt_unlockpage (BtLockRead, bt->latch);
1524 bt_unpinlatch (bt->latch);
1528 // check page for space available,
1529 // clean if necessary and return
1530 // 0 - page needs splitting
1531 // >0 - go ahead with new slot
1533 uint bt_cleanpage(BtDb *bt, uint amt, uint slot)
1535 uint nxt = bt->page_size;
1536 BtPage page = bt->page;
1537 uint cnt = 0, idx = 0;
1538 uint max = page->cnt;
1539 uint newslot = slot;
1543 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1546 // skip cleanup if nothing to reclaim
1551 memcpy (bt->frame, page, bt->page_size);
1553 // skip page info and set rest of page to zero
1555 memset (page+1, 0, bt->page_size - sizeof(*page));
1558 while( cnt++ < max ) {
1561 // always leave fence key in list
1562 if( cnt < max && slotptr(bt->frame,cnt)->dead )
1566 key = keyptr(bt->frame, cnt);
1567 nxt -= key->len + 1;
1568 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1571 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1572 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1575 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1577 slotptr(page, idx)->off = nxt;
1583 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1589 // split the root and raise the height of the btree
1591 BTERR bt_splitroot(BtDb *bt, unsigned char *leftkey, uid page_no2)
1593 uint nxt = bt->page_size;
1594 BtPage root = bt->page;
1597 // Obtain an empty page to use, and copy the current
1598 // root contents into it
1600 if( !(right = bt_newpage(bt, root)) )
1603 // preserve the page info at the bottom
1604 // and set rest to zero
1606 memset(root+1, 0, bt->page_size - sizeof(*root));
1608 // insert first key on newroot page
1610 nxt -= *leftkey + 1;
1611 memcpy ((unsigned char *)root + nxt, leftkey, *leftkey + 1);
1612 bt_putid(slotptr(root, 1)->id, right);
1613 slotptr(root, 1)->off = nxt;
1615 // insert second key on newroot page
1616 // and increase the root height
1619 ((unsigned char *)root)[nxt] = 2;
1620 ((unsigned char *)root)[nxt+1] = 0xff;
1621 ((unsigned char *)root)[nxt+2] = 0xff;
1622 bt_putid(slotptr(root, 2)->id, page_no2);
1623 slotptr(root, 2)->off = nxt;
1625 bt_putid(root->right, 0);
1626 root->min = nxt; // reset lowest used offset and key count
1631 // update and release root (bt->page)
1633 bt_update(bt, root);
1635 bt_unlockpage(BtLockWrite, bt->latch);
1636 bt_unpinlatch(bt->latch);
1640 // split already locked full node
1643 BTERR bt_splitpage (BtDb *bt)
1645 uint cnt = 0, idx = 0, max, nxt = bt->page_size;
1646 unsigned char fencekey[256], rightkey[256];
1647 uid page_no = bt->page_no, right;
1648 BtLatchSet *latch, *rlatch;
1649 BtPage page = bt->page;
1650 uint lvl = page->lvl;
1655 // split higher half of keys to bt->frame
1656 // the last key (fence key) might be dead
1658 memset (bt->frame, 0, bt->page_size);
1663 while( cnt++ < max ) {
1664 key = keyptr(page, cnt);
1665 nxt -= key->len + 1;
1666 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
1667 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
1668 if( !(slotptr(bt->frame, idx)->dead = slotptr(page, cnt)->dead) )
1671 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
1673 slotptr(bt->frame, idx)->off = nxt;
1676 // remember fence key for new right page
1678 memcpy (rightkey, key, key->len + 1);
1680 bt->frame->bits = bt->page_bits;
1681 bt->frame->min = nxt;
1682 bt->frame->cnt = idx;
1683 bt->frame->lvl = lvl;
1687 if( page_no > ROOT_page )
1688 memcpy (bt->frame->right, page->right, BtId);
1690 // get new free page and write frame to it.
1692 if( !(right = bt_newpage(bt, bt->frame)) )
1695 // update lower keys to continue in old page
1697 memcpy (bt->frame, page, bt->page_size);
1698 memset (page+1, 0, bt->page_size - sizeof(*page));
1699 nxt = bt->page_size;
1705 // assemble page of smaller keys
1706 // (they're all active keys)
1708 while( cnt++ < max / 2 ) {
1709 key = keyptr(bt->frame, cnt);
1710 nxt -= key->len + 1;
1711 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1712 memcpy(slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1714 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1716 slotptr(page, idx)->off = nxt;
1720 // remember fence key for smaller page
1722 memcpy (fencekey, key, key->len + 1);
1724 bt_putid(page->right, right);
1728 // if current page is the root page, split it
1730 if( page_no == ROOT_page )
1731 return bt_splitroot (bt, fencekey, right);
1735 if( rlatch = bt_pinlatch (bt, right) )
1736 bt_lockpage (BtLockParent, rlatch);
1740 // update left (containing) node
1742 bt_update(bt, page);
1744 bt_lockpage (BtLockParent, latch);
1745 bt_unlockpage (BtLockWrite, latch);
1747 // insert new fence for reformulated left block
1749 if( bt_insertkey (bt, fencekey+1, *fencekey, lvl+1, page_no, time(NULL)) )
1752 // switch fence for right block of larger keys to new right page
1754 if( bt_insertkey (bt, rightkey+1, *rightkey, lvl+1, right, time(NULL)) )
1757 bt_unlockpage (BtLockParent, latch);
1758 bt_unlockpage (BtLockParent, rlatch);
1760 bt_unpinlatch (rlatch);
1761 bt_unpinlatch (latch);
1765 // Insert new key into the btree at requested level.
1766 // Pages are unlocked at exit.
1768 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod)
1775 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1776 ptr = keyptr(bt->page, slot);
1780 bt->err = BTERR_ovflw;
1784 // if key already exists, update id and return
1788 if( !keycmp (ptr, key, len) ) {
1789 if( slotptr(page, slot)->dead )
1791 slotptr(page, slot)->dead = 0;
1793 slotptr(page, slot)->tod = tod;
1795 bt_putid(slotptr(page,slot)->id, id);
1796 bt_update(bt, bt->page);
1797 bt_unlockpage(BtLockWrite, bt->latch);
1798 bt_unpinlatch (bt->latch);
1802 // check if page has enough space
1804 if( slot = bt_cleanpage (bt, len, slot) )
1807 if( bt_splitpage (bt) )
1811 // calculate next available slot and copy key into page
1813 page->min -= len + 1; // reset lowest used offset
1814 ((unsigned char *)page)[page->min] = len;
1815 memcpy ((unsigned char *)page + page->min +1, key, len );
1817 for( idx = slot; idx < page->cnt; idx++ )
1818 if( slotptr(page, idx)->dead )
1821 // now insert key into array before slot
1822 // preserving the fence slot
1824 if( idx == page->cnt )
1830 *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
1832 bt_putid(slotptr(page,slot)->id, id);
1833 slotptr(page, slot)->off = page->min;
1835 slotptr(page, slot)->tod = tod;
1837 slotptr(page, slot)->dead = 0;
1839 bt_update(bt, bt->page);
1841 bt_unlockpage(BtLockWrite, bt->latch);
1842 bt_unpinlatch(bt->latch);
1846 // cache page of keys into cursor and return starting slot for given key
1848 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
1852 // cache page for retrieval
1854 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1855 memcpy (bt->cursor, bt->page, bt->page_size);
1859 bt_unlockpage(BtLockRead, bt->latch);
1860 bt->cursor_page = bt->page_no;
1861 bt_unpinlatch (bt->latch);
1865 // return next slot for cursor page
1866 // or slide cursor right into next page
1868 uint bt_nextkey (BtDb *bt, uint slot)
1874 right = bt_getid(bt->cursor->right);
1876 while( slot++ < bt->cursor->cnt )
1877 if( slotptr(bt->cursor,slot)->dead )
1879 else if( right || (slot < bt->cursor->cnt))
1887 bt->cursor_page = right;
1889 if( latch = bt_pinlatch (bt, right) )
1890 bt_lockpage(BtLockRead, latch);
1894 bt->page = bt_mappage (bt, latch);
1895 memcpy (bt->cursor, bt->page, bt->page_size);
1896 bt_unlockpage(BtLockRead, latch);
1897 bt_unpinlatch (latch);
1904 BtKey bt_key(BtDb *bt, uint slot)
1906 return keyptr(bt->cursor, slot);
1909 uid bt_uid(BtDb *bt, uint slot)
1911 return bt_getid(slotptr(bt->cursor,slot)->id);
1915 uint bt_tod(BtDb *bt, uint slot)
1917 return slotptr(bt->cursor,slot)->tod;
1923 uint bt_audit (BtDb *bt)
1935 posix_fadvise( bt->idx, 0, 0, POSIX_FADV_SEQUENTIAL);
1937 if( *(ushort *)(bt->latchmgr->lock) )
1938 fprintf(stderr, "Alloc page locked\n");
1939 *(ushort *)(bt->latchmgr->lock) = 0;
1941 memset (blks, 0, sizeof(blks));
1943 for( idx = 1; idx <= bt->latchmgr->latchdeployed; idx++ ) {
1944 latch = bt->latchsets + idx;
1945 if( *(ushort *)latch->readwr )
1946 fprintf(stderr, "latchset %d rwlocked for page %.8x\n", idx, latch->page_no);
1947 *(ushort *)latch->readwr = 0;
1949 if( *(ushort *)latch->access )
1950 fprintf(stderr, "latchset %d accesslocked for page %.8x\n", idx, latch->page_no);
1951 *(ushort *)latch->access = 0;
1953 if( *(ushort *)latch->parent )
1954 fprintf(stderr, "latchset %d parentlocked for page %.8x\n", idx, latch->page_no);
1955 *(ushort *)latch->parent = 0;
1957 if( latch->pin & PIN_mask ) {
1958 fprintf(stderr, "latchset %d pinned for page %.8x\n", idx, latch->page_no);
1961 page = (BtPage)((uid)idx * bt->page_size + bt->pagepool);
1965 if( bt_writepage (bt, page, latch->page_no) )
1966 fprintf(stderr, "Page %.8x Write Error\n", latch->page_no);
1969 for( idx = 0; blks[idx]; idx++ )
1970 fprintf(stderr, "cache: %d lvl %d blocks\n", blks[idx], idx);
1972 for( hashidx = 0; hashidx < bt->latchmgr->latchhash; hashidx++ ) {
1973 if( *(ushort *)(bt->table[hashidx].latch) )
1974 fprintf(stderr, "hash entry %d locked\n", hashidx);
1976 *(ushort *)(bt->table[hashidx].latch) = 0;
1979 memset (blks, 0, sizeof(blks));
1981 next = bt->latchmgr->nlatchpage + LATCH_page;
1982 page_no = LEAF_page;
1984 while( page_no < bt_getid(bt->latchmgr->alloc->right) ) {
1985 if( bt_readpage (bt, bt->frame, page_no) )
1986 fprintf(stderr, "page %.8x unreadable\n", page_no);
1987 if( !bt->frame->free ) {
1988 for( idx = 0; idx++ < bt->frame->cnt - 1; ) {
1989 ptr = keyptr(bt->frame, idx+1);
1990 if( keycmp (keyptr(bt->frame, idx), ptr->key, ptr->len) >= 0 )
1991 fprintf(stderr, "page %.8x idx %.2x out of order\n", page_no, idx);
1993 if( !bt->frame->lvl )
1994 cnt += bt->frame->act;
1995 blks[bt->frame->lvl]++;
1998 if( page_no > LEAF_page )
2003 for( idx = 0; blks[idx]; idx++ )
2004 fprintf(stderr, "btree: %d lvl %d blocks\n", blks[idx], idx);
2010 double getCpuTime(int type)
2013 FILETIME xittime[1];
2014 FILETIME systime[1];
2015 FILETIME usrtime[1];
2016 SYSTEMTIME timeconv[1];
2019 memset (timeconv, 0, sizeof(SYSTEMTIME));
2023 GetSystemTimeAsFileTime (xittime);
2024 FileTimeToSystemTime (xittime, timeconv);
2025 ans = (double)timeconv->wDayOfWeek * 3600 * 24;
2028 GetProcessTimes (GetCurrentProcess(), crtime, xittime, systime, usrtime);
2029 FileTimeToSystemTime (usrtime, timeconv);
2032 GetProcessTimes (GetCurrentProcess(), crtime, xittime, systime, usrtime);
2033 FileTimeToSystemTime (systime, timeconv);
2037 ans += (double)timeconv->wHour * 3600;
2038 ans += (double)timeconv->wMinute * 60;
2039 ans += (double)timeconv->wSecond;
2040 ans += (double)timeconv->wMilliseconds / 1000;
2045 #include <sys/resource.h>
2047 double getCpuTime(int type)
2049 struct rusage used[1];
2050 struct timeval tv[1];
2054 gettimeofday(tv, NULL);
2055 return (double)tv->tv_sec + (double)tv->tv_usec / 1000000;
2058 getrusage(RUSAGE_SELF, used);
2059 return (double)used->ru_utime.tv_sec + (double)used->ru_utime.tv_usec / 1000000;
2062 getrusage(RUSAGE_SELF, used);
2063 return (double)used->ru_stime.tv_sec + (double)used->ru_stime.tv_usec / 1000000;
2070 // standalone program to index file of keys
2071 // then list them onto std-out
2073 int main (int argc, char **argv)
2075 uint slot, line = 0, off = 0, found = 0;
2076 int ch, cnt = 0, bits = 12, idx;
2077 unsigned char key[256];
2092 _setmode (1, _O_BINARY);
2095 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]);
2096 fprintf (stderr, " page_bits: size of btree page in bits\n");
2097 fprintf (stderr, " mapped_pool_pages: number of pages in buffer pool\n");
2101 start = getCpuTime(0);
2105 bits = atoi(argv[4]);
2108 map = atoi(argv[5]);
2111 off = atoi(argv[6]);
2113 bt = bt_open ((argv[1]), BT_rw, bits, map);
2116 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2120 switch(argv[3][0]| 0x20)
2122 case 'p': // display page
2123 if( latch = bt_pinlatch (bt, off) )
2124 page = bt_mappage (bt, latch);
2126 fprintf(stderr, "unable to read page %.8x\n", off);
2128 write (1, page, bt->page_size);
2131 case 'a': // buffer pool audit
2132 fprintf(stderr, "started audit for %s\n", argv[1]);
2133 cnt = bt_audit (bt);
2134 fprintf(stderr, "finished audit for %s, %d keys\n", argv[1], cnt);
2137 case 'w': // write keys
2138 fprintf(stderr, "started indexing for %s\n", argv[2]);
2139 if( argc > 2 && (in = fopen (argv[2], "rb")) ) {
2141 posix_fadvise( fileno(in), 0, 0, POSIX_FADV_NOREUSE);
2143 while( ch = getc(in), ch != EOF )
2147 sprintf((char *)key+len, "%.9d", line + off), len += 9;
2149 if( bt_insertkey (bt, key, len, 0, ++line, *tod) )
2150 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2153 else if( len < 245 )
2156 fprintf(stderr, "finished adding keys for %s, %d \n", argv[2], line);
2159 case 'd': // delete keys
2160 fprintf(stderr, "started deleting keys for %s\n", argv[2]);
2161 if( argc > 2 && (in = fopen (argv[2], "rb")) ) {
2163 posix_fadvise( fileno(in), 0, 0, POSIX_FADV_NOREUSE);
2165 while( ch = getc(in), ch != EOF )
2169 sprintf((char *)key+len, "%.9d", line + off), len += 9;
2171 if( bt_deletekey (bt, key, len, 0) )
2172 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2175 else if( len < 245 )
2178 fprintf(stderr, "finished deleting keys for %s, %d \n", argv[2], line);
2181 case 'f': // find keys
2182 fprintf(stderr, "started finding keys for %s\n", argv[2]);
2183 if( argc > 2 && (in = fopen (argv[2], "rb")) ) {
2185 posix_fadvise( fileno(in), 0, 0, POSIX_FADV_NOREUSE);
2187 while( ch = getc(in), ch != EOF )
2191 sprintf((char *)key+len, "%.9d", line + off), len += 9;
2193 if( bt_findkey (bt, key, len) )
2196 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2199 else if( len < 245 )
2202 fprintf(stderr, "finished search of %d keys for %s, found %d\n", line, argv[2], found);
2205 case 's': // scan and print keys
2206 fprintf(stderr, "started scaning\n");
2207 cnt = len = key[0] = 0;
2209 if( slot = bt_startkey (bt, key, len) )
2212 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
2214 while( slot = bt_nextkey (bt, slot) ) {
2215 ptr = bt_key(bt, slot);
2216 fwrite (ptr->key, ptr->len, 1, stdout);
2217 fputc ('\n', stdout);
2221 fprintf(stderr, " Total keys read %d\n", cnt - 1);
2224 case 'c': // count keys
2225 fprintf(stderr, "started counting\n");
2228 next = bt->latchmgr->nlatchpage + LATCH_page;
2229 page_no = LEAF_page;
2231 while( page_no < bt_getid(bt->latchmgr->alloc->right) ) {
2232 if( latch = bt_pinlatch (bt, page_no) )
2233 page = bt_mappage (bt, latch);
2234 if( !page->free && !page->lvl )
2236 if( page_no > LEAF_page )
2239 for( idx = 0; idx++ < page->cnt; ) {
2240 if( slotptr(page, idx)->dead )
2242 ptr = keyptr(page, idx);
2243 if( idx != page->cnt && bt_getid (page->right) ) {
2244 fwrite (ptr->key, ptr->len, 1, stdout);
2245 fputc ('\n', stdout);
2248 bt_unpinlatch (latch);
2252 cnt--; // remove stopper key
2253 fprintf(stderr, " Total keys read %d\n", cnt);
2257 done = getCpuTime(0);
2258 elapsed = (float)(done - start);
2259 fprintf(stderr, " real %dm%.3fs\n", (int)(elapsed/60), elapsed - (int)(elapsed/60)*60);
2260 elapsed = getCpuTime(1);
2261 fprintf(stderr, " user %dm%.3fs\n", (int)(elapsed/60), elapsed - (int)(elapsed/60)*60);
2262 elapsed = getCpuTime(2);
2263 fprintf(stderr, " sys %dm%.3fs\n", (int)(elapsed/60), elapsed - (int)(elapsed/60)*60);