2 // with reworked bt_deletekey code
5 // author: karl malbrain, malbrain@cal.berkeley.edu
8 This work, including the source code, documentation
9 and related data, is placed into the public domain.
11 The orginal author is Karl Malbrain.
13 THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY
14 OF ANY KIND, NOT EVEN THE IMPLIED WARRANTY OF
15 MERCHANTABILITY. THE AUTHOR OF THIS SOFTWARE,
16 ASSUMES _NO_ RESPONSIBILITY FOR ANY CONSEQUENCE
17 RESULTING FROM THE USE, MODIFICATION, OR
18 REDISTRIBUTION OF THIS SOFTWARE.
21 // Please see the project home page for documentation
22 // code.google.com/p/high-concurrency-btree
24 #define _FILE_OFFSET_BITS 64
25 #define _LARGEFILE64_SOURCE
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_latchtable 128 // number of latch manager slots
61 #define BT_ro 0x6f72 // ro
62 #define BT_rw 0x7772 // rw
63 #define BT_fl 0x6c66 // fl
65 #define BT_maxbits 24 // maximum page size in bits
66 #define BT_minbits 9 // minimum page size in bits
67 #define BT_minpage (1 << BT_minbits) // minimum page size
68 #define BT_maxpage (1 << BT_maxbits) // maximum page size
71 There are five lock types for each node in three independent sets:
72 1. (set 1) AccessIntent: Sharable. Going to Read the node. Incompatible with NodeDelete.
73 2. (set 1) NodeDelete: Exclusive. About to release the node. Incompatible with AccessIntent.
74 3. (set 2) ReadLock: Sharable. Read the node. Incompatible with WriteLock.
75 4. (set 2) WriteLock: Exclusive. Modify the node. Incompatible with ReadLock and other WriteLocks.
76 5. (set 3) ParentModification: Exclusive. Change the node's parent keys. Incompatible with another ParentModification.
87 // definition for latch implementation
89 // exclusive is set for write access
90 // share is count of read accessors
91 // grant write lock when share == 0
93 volatile typedef struct {
94 unsigned char mutex[1];
95 unsigned char exclusive:1;
96 unsigned char pending:1;
100 // hash table entries
103 BtSpinLatch latch[1];
104 volatile ushort slot; // Latch table entry at head of chain
107 // latch manager table structure
110 BtSpinLatch readwr[1]; // read/write page lock
111 BtSpinLatch access[1]; // Access Intent/Page delete
112 BtSpinLatch parent[1]; // Posting of fence key in parent
113 BtSpinLatch busy[1]; // slot is being moved between chains
114 volatile ushort next; // next entry in hash table chain
115 volatile ushort prev; // prev entry in hash table chain
116 volatile ushort pin; // number of outstanding locks
117 volatile ushort hash; // hash slot entry is under
118 volatile uid page_no; // latch set page number
121 // Define the length of the page and key pointers
125 // Page key slot definition.
127 // If BT_maxbits is 15 or less, you can save 2 bytes
128 // for each key stored by making the first two uints
129 // into ushorts. You can also save 4 bytes by removing
130 // the tod field from the key.
132 // Keys are marked dead, but remain on the page until
133 // cleanup is called. The fence key (highest key) for
134 // the page is always present, even if dead.
137 uint off:BT_maxbits; // page offset for key start
138 uint dead:1; // set for deleted key
139 uint tod; // time-stamp for key
140 unsigned char id[BtId]; // id associated with key
143 // The key structure occupies space at the upper end of
144 // each page. It's a length byte followed by the value
149 unsigned char key[0];
152 // The first part of an index page.
153 // It is immediately followed
154 // by the BtSlot array of keys.
156 typedef struct BtPage_ {
157 uint cnt; // count of keys in page
158 uint act; // count of active keys
159 uint min; // next key offset
160 unsigned char bits:7; // page size in bits
161 unsigned char free:1; // page is on free list
162 unsigned char lvl:6; // level of page
163 unsigned char kill:1; // page is being deleted
164 unsigned char dirty:1; // page is dirty
165 unsigned char right[BtId]; // page number to right
168 // The memory mapping hash table entry
171 BtPage page; // mapped page pointer
172 uid page_no; // mapped page number
173 void *lruprev; // least recently used previous cache block
174 void *lrunext; // lru next cache block
175 void *hashprev; // previous cache block for the same hash idx
176 void *hashnext; // next cache block for the same hash idx
183 struct BtPage_ alloc[2]; // next & free page_nos in right ptr
184 BtSpinLatch lock[1]; // allocation area lite latch
185 ushort latchdeployed; // highest number of latch entries deployed
186 ushort nlatchpage; // number of latch pages at BT_latch
187 ushort latchtotal; // number of page latch entries
188 ushort latchhash; // number of latch hash table slots
189 ushort latchvictim; // next latch entry to examine
190 BtHashEntry table[0]; // the hash table
193 // The object structure for Btree access
195 typedef struct _BtDb {
196 uint page_size; // each page size
197 uint page_bits; // each page size in bits
198 uint seg_bits; // segment size in pages in bits
199 uid page_no; // current page number
200 uid cursor_page; // current cursor page number
202 uint mode; // read-write mode
203 uint mapped_io; // use memory mapping
204 BtPage temp; // temporary frame buffer (memory mapped/file IO)
205 BtPage alloc; // frame buffer for alloc page ( page 0 )
206 BtPage cursor; // cached frame for start/next (never mapped)
207 BtPage frame; // spare frame for the page split (never mapped)
208 BtPage zero; // zeroes frame buffer (never mapped)
209 BtPage page; // current page
210 BtLatchSet *latch; // current page latch
211 BtLatchMgr *latchmgr; // mapped latch page from allocation page
212 BtLatchSet *latchsets; // mapped latch set from latch pages
217 HANDLE halloc; // allocation and latch table handle
219 unsigned char *mem; // frame, cursor, page memory buffer
220 int nodecnt; // highest page cache segment in use
221 int nodemax; // highest page cache segment allocated
222 int hashmask; // number of pages in segments - 1
223 int hashsize; // size of hash table
224 int found; // last deletekey found key
225 BtHash *lrufirst; // lru list head
226 BtHash *lrulast; // lru list tail
227 ushort *cache; // hash table for cached segments
228 BtHash *nodes; // segment cache
245 extern void bt_close (BtDb *bt);
246 extern BtDb *bt_open (char *name, uint mode, uint bits, uint cacheblk, uint pgblk, uint hashsize);
247 extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod);
248 extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl);
249 extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
250 extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
251 extern uint bt_nextkey (BtDb *bt, uint slot);
253 // internal functions
254 BTERR bt_update (BtDb *bt, BtPage page, uid page_no);
255 BTERR bt_mappage (BtDb *bt, BtPage *page, uid page_no);
256 // Helper functions to return slot values
258 extern BtKey bt_key (BtDb *bt, uint slot);
259 extern uid bt_uid (BtDb *bt, uint slot);
260 extern uint bt_tod (BtDb *bt, uint slot);
262 // BTree page number constants
268 // Number of levels to create in a new BTree
272 // The page is allocated from low and hi ends.
273 // The key offsets and row-id's are allocated
274 // from the bottom, while the text of the key
275 // is allocated from the top. When the two
276 // areas meet, the page is split into two.
278 // A key consists of a length byte, two bytes of
279 // index number (0 - 65534), and up to 253 bytes
280 // of key value. Duplicate keys are discarded.
281 // Associated with each key is a 48 bit row-id.
283 // The b-tree root is always located at page 1.
284 // The first leaf page of level zero is always
285 // located on page 2.
287 // The b-tree pages are linked with right
288 // pointers to facilitate enumerators,
289 // and provide for concurrency.
291 // When to root page fills, it is split in two and
292 // the tree height is raised by a new root at page
293 // one with two keys.
295 // Deleted keys are marked with a dead bit until
296 // page cleanup The fence key for a node is always
297 // present, even after deletion and cleanup.
299 // Deleted leaf pages are reclaimed on a free list.
300 // The upper levels of the btree are fixed on creation.
302 // Groups of pages from the btree are optionally
303 // cached with memory mapping. A hash table is used to keep
304 // track of the cached pages. This behaviour is controlled
305 // by the number of cache blocks parameter and pages per block
308 // To achieve maximum concurrency one page is locked at a time
309 // as the tree is traversed to find leaf key in question. The right
310 // page numbers are used in cases where the page is being split,
313 // Page 0 (ALLOC page) is dedicated to lock for new page extensions,
314 // and chains empty leaf pages together for reuse.
316 // Parent locks are obtained to prevent resplitting or deleting a node
317 // before its fence is posted into its upper level.
319 // A special open mode of BT_fl is provided to safely access files on
320 // WIN32 networks. WIN32 network operations should not use memory mapping.
321 // This WIN32 mode sets FILE_FLAG_NOBUFFERING and FILE_FLAG_WRITETHROUGH
322 // to prevent local caching of network file contents.
324 // Access macros to address slot and key values from the page.
325 // Page slots use 1 based indexing.
327 #define slotptr(page, slot) (((BtSlot *)(page+1)) + (slot-1))
328 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
330 void bt_putid(unsigned char *dest, uid id)
335 dest[i] = (unsigned char)id, id >>= 8;
338 uid bt_getid(unsigned char *src)
343 for( i = 0; i < BtId; i++ )
344 id <<= 8, id |= *src++;
349 BTERR bt_abort (BtDb *bt, BtPage page, uid page_no, BTERR err)
353 fprintf(stderr, "\n Btree2 abort, error %d on page %.8x\n", err, page_no);
354 fprintf(stderr, "level=%d kill=%d free=%d cnt=%x act=%x\n", page->lvl, page->kill, page->free, page->cnt, page->act);
355 ptr = keyptr(page, page->cnt);
356 fprintf(stderr, "fence='%.*s'\n", ptr->len, ptr->key);
357 fprintf(stderr, "right=%.8x\n", bt_getid(page->right));
358 return bt->err = err;
363 // wait until write lock mode is clear
364 // and add 1 to the share count
366 void bt_spinreadlock(BtSpinLatch *latch)
371 // obtain latch mutex
373 if( __sync_lock_test_and_set(latch->mutex, 1) )
376 if( _InterlockedExchange8(latch->mutex, 1) )
379 // see if exclusive request is granted or pending
381 if( prev = !(latch->exclusive | latch->pending) )
387 _InterlockedExchange8(latch->mutex, 0);
394 } while( sched_yield(), 1 );
396 } while( SwitchToThread(), 1 );
400 // wait for other read and write latches to relinquish
402 void bt_spinwritelock(BtSpinLatch *latch)
408 if( __sync_lock_test_and_set(latch->mutex, 1) )
411 if( _InterlockedExchange8(latch->mutex, 1) )
414 if( prev = !(latch->share | latch->exclusive) )
415 latch->exclusive = 1, latch->pending = 0;
421 _InterlockedExchange8(latch->mutex, 0);
426 } while( sched_yield(), 1 );
428 } while( SwitchToThread(), 1 );
432 // try to obtain write lock
434 // return 1 if obtained,
437 int bt_spinwritetry(BtSpinLatch *latch)
442 if( __sync_lock_test_and_set(latch->mutex, 1) )
445 if( _InterlockedExchange8(latch->mutex, 1) )
448 // take write access if all bits are clear
450 if( prev = !(latch->exclusive | latch->share) )
451 latch->exclusive = 1;
456 _InterlockedExchange8(latch->mutex, 0);
463 void bt_spinreleasewrite(BtSpinLatch *latch)
466 while( __sync_lock_test_and_set(latch->mutex, 1) )
469 while( _InterlockedExchange8(latch->mutex, 1) )
472 latch->exclusive = 0;
476 _InterlockedExchange8(latch->mutex, 0);
480 // decrement reader count
482 void bt_spinreleaseread(BtSpinLatch *latch)
485 while( __sync_lock_test_and_set(latch->mutex, 1) )
488 while( _InterlockedExchange8(latch->mutex, 1) )
495 _InterlockedExchange8(latch->mutex, 0);
499 // link latch table entry into latch hash table
501 void bt_latchlink (BtDb *bt, ushort hashidx, ushort victim, uid page_no)
503 BtLatchSet *latch = bt->latchsets + victim;
505 if( latch->next = bt->latchmgr->table[hashidx].slot )
506 bt->latchsets[latch->next].prev = victim;
508 bt->latchmgr->table[hashidx].slot = victim;
509 latch->page_no = page_no;
510 latch->hash = hashidx;
516 void bt_unpinlatch (BtLatchSet *latch)
519 __sync_fetch_and_add(&latch->pin, -1);
521 _InterlockedDecrement16 (&latch->pin);
525 // find existing latchset or inspire new one
526 // return with latchset pinned
528 BtLatchSet *bt_pinlatch (BtDb *bt, uid page_no)
530 ushort hashidx = page_no % bt->latchmgr->latchhash;
531 ushort slot, avail = 0, victim, idx;
534 // obtain read lock on hash table entry
536 bt_spinreadlock(bt->latchmgr->table[hashidx].latch);
538 if( slot = bt->latchmgr->table[hashidx].slot ) do
540 latch = bt->latchsets + slot;
541 if( page_no == latch->page_no )
543 } while( slot = latch->next );
547 __sync_fetch_and_add(&latch->pin, 1);
549 _InterlockedIncrement16 (&latch->pin);
553 bt_spinreleaseread (bt->latchmgr->table[hashidx].latch);
558 // try again, this time with write lock
560 bt_spinwritelock(bt->latchmgr->table[hashidx].latch);
562 if( slot = bt->latchmgr->table[hashidx].slot ) do
564 latch = bt->latchsets + slot;
565 if( page_no == latch->page_no )
567 if( !latch->pin && !avail )
569 } while( slot = latch->next );
571 // found our entry, or take over an unpinned one
573 if( slot || (slot = avail) ) {
574 latch = bt->latchsets + slot;
576 __sync_fetch_and_add(&latch->pin, 1);
578 _InterlockedIncrement16 (&latch->pin);
580 latch->page_no = page_no;
581 bt_spinreleasewrite(bt->latchmgr->table[hashidx].latch);
585 // see if there are any unused entries
587 victim = __sync_fetch_and_add (&bt->latchmgr->latchdeployed, 1) + 1;
589 victim = _InterlockedIncrement16 (&bt->latchmgr->latchdeployed);
592 if( victim < bt->latchmgr->latchtotal ) {
593 latch = bt->latchsets + victim;
595 __sync_fetch_and_add(&latch->pin, 1);
597 _InterlockedIncrement16 (&latch->pin);
599 bt_latchlink (bt, hashidx, victim, page_no);
600 bt_spinreleasewrite (bt->latchmgr->table[hashidx].latch);
605 victim = __sync_fetch_and_add (&bt->latchmgr->latchdeployed, -1);
607 victim = _InterlockedDecrement16 (&bt->latchmgr->latchdeployed);
609 // find and reuse previous lock entry
613 victim = __sync_fetch_and_add(&bt->latchmgr->latchvictim, 1);
615 victim = _InterlockedIncrement16 (&bt->latchmgr->latchvictim) - 1;
617 // we don't use slot zero
619 if( victim %= bt->latchmgr->latchtotal )
620 latch = bt->latchsets + victim;
624 // take control of our slot
625 // from other threads
627 if( latch->pin || !bt_spinwritetry (latch->busy) )
632 // try to get write lock on hash chain
633 // skip entry if not obtained
634 // or has outstanding locks
636 if( !bt_spinwritetry (bt->latchmgr->table[idx].latch) ) {
637 bt_spinreleasewrite (latch->busy);
642 bt_spinreleasewrite (latch->busy);
643 bt_spinreleasewrite (bt->latchmgr->table[idx].latch);
647 // unlink our available victim from its hash chain
650 bt->latchsets[latch->prev].next = latch->next;
652 bt->latchmgr->table[idx].slot = latch->next;
655 bt->latchsets[latch->next].prev = latch->prev;
657 bt_spinreleasewrite (bt->latchmgr->table[idx].latch);
659 __sync_fetch_and_add(&latch->pin, 1);
661 _InterlockedIncrement16 (&latch->pin);
663 bt_latchlink (bt, hashidx, victim, page_no);
664 bt_spinreleasewrite (bt->latchmgr->table[hashidx].latch);
665 bt_spinreleasewrite (latch->busy);
670 // close and release memory
672 void bt_close (BtDb *bt)
676 munmap (bt->latchsets, bt->latchmgr->nlatchpage * bt->page_size);
677 munmap (bt->latchmgr, bt->page_size);
679 FlushViewOfFile(bt->latchmgr, 0);
680 UnmapViewOfFile(bt->latchmgr);
681 CloseHandle(bt->halloc);
684 // release mapped pages
686 if( hash = bt->lrufirst )
687 do munmap (hash->page, (bt->hashmask+1) << bt->page_bits);
688 while(hash = hash->lrunext);
696 if( hash = bt->lrufirst )
699 FlushViewOfFile(hash->page, 0);
700 UnmapViewOfFile(hash->page);
701 CloseHandle(hash->hmap);
702 } while(hash = hash->lrunext);
705 VirtualFree (bt->mem, 0, MEM_RELEASE);
706 FlushFileBuffers(bt->idx);
707 CloseHandle(bt->idx);
708 GlobalFree (bt->cache);
712 // open/create new btree
714 // call with file_name, BT_openmode, bits in page size (e.g. 16),
715 // size of mapped page pool (e.g. 8192)
717 BtDb *bt_open (char *name, uint mode, uint bits, uint nodemax, uint segsize, uint hashsize)
719 uint lvl, attr, cacheblk, last, slot, idx;
720 uint nlatchpage, latchhash;
721 BtLatchMgr *latchmgr;
729 SYSTEM_INFO sysinfo[1];
732 struct flock lock[1];
735 // determine sanity of page size and buffer pool
737 if( bits > BT_maxbits )
739 else if( bits < BT_minbits )
743 bt = calloc (1, sizeof(BtDb));
745 bt->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
748 return free(bt), NULL;
750 cacheblk = 4096; // minimum mmap segment size for unix
753 bt = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtDb));
754 attr = FILE_ATTRIBUTE_NORMAL;
755 bt->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
757 if( bt->idx == INVALID_HANDLE_VALUE )
758 return GlobalFree(bt), NULL;
760 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
761 GetSystemInfo(sysinfo);
762 cacheblk = sysinfo->dwAllocationGranularity;
766 memset (lock, 0, sizeof(lock));
768 lock->l_type = F_WRLCK;
769 lock->l_len = sizeof(struct BtPage_);
772 if( fcntl (bt->idx, F_SETLKW, lock) < 0 )
773 return bt_close (bt), NULL;
775 memset (ovl, 0, sizeof(ovl));
776 len = sizeof(struct BtPage_);
778 // use large offsets to
779 // simulate advisory locking
781 ovl->OffsetHigh |= 0x80000000;
783 if( mode == BtLockDelete || mode == BtLockWrite || mode == BtLockParent )
784 flags |= LOCKFILE_EXCLUSIVE_LOCK;
786 if( LockFileEx (bt->idx, flags, 0, len, 0L, ovl) )
787 return bt_close (bt), NULL;
790 latchmgr = malloc (BT_maxpage);
793 // read minimum page size to get root info
795 if( size = lseek (bt->idx, 0L, 2) ) {
796 if( pread(bt->idx, latchmgr, BT_minpage, 0) == BT_minpage )
797 bits = latchmgr->alloc->bits;
799 return free(bt), free(latchmgr), NULL;
800 } else if( mode == BT_ro )
801 return free(latchmgr), bt_close (bt), NULL;
803 latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
804 size = GetFileSize(bt->idx, amt);
807 if( !ReadFile(bt->idx, (char *)latchmgr, BT_minpage, amt, NULL) )
808 return bt_close (bt), NULL;
809 bits = latchmgr->alloc->bits;
810 } else if( mode == BT_ro )
811 return bt_close (bt), NULL;
814 bt->page_size = 1 << bits;
815 bt->page_bits = bits;
819 if( cacheblk < bt->page_size )
820 cacheblk = bt->page_size;
822 // mask for partial memmaps
824 bt->hashmask = (cacheblk >> bits) - 1;
826 // see if requested size of pages per memmap is greater
828 if( (1 << segsize) > bt->hashmask )
829 bt->hashmask = (1 << segsize) - 1;
833 while( (1 << bt->seg_bits) <= bt->hashmask )
836 bt->hashsize = hashsize;
838 if( bt->nodemax = nodemax ) {
840 bt->nodes = calloc (nodemax, sizeof(BtHash));
841 bt->cache = calloc (hashsize, sizeof(ushort));
843 bt->nodes = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, nodemax * sizeof(BtHash));
844 bt->cache = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
853 // initialize an empty b-tree with latch page, root page, page of leaves
854 // and page(s) of latches
856 memset (latchmgr, 0, 1 << bits);
857 nlatchpage = BT_latchtable / (bt->page_size / sizeof(BtLatchSet)) + 1;
858 bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
859 latchmgr->alloc->bits = bt->page_bits;
861 latchmgr->nlatchpage = nlatchpage;
862 latchmgr->latchtotal = nlatchpage * (bt->page_size / sizeof(BtLatchSet));
864 // initialize latch manager
866 latchhash = (bt->page_size - sizeof(BtLatchMgr)) / sizeof(BtHashEntry);
868 // size of hash table = total number of latchsets
870 if( latchhash > latchmgr->latchtotal )
871 latchhash = latchmgr->latchtotal;
873 latchmgr->latchhash = latchhash;
876 if( write (bt->idx, latchmgr, bt->page_size) < bt->page_size )
877 return bt_close (bt), NULL;
879 if( !WriteFile (bt->idx, (char *)latchmgr, bt->page_size, amt, NULL) )
880 return bt_close (bt), NULL;
882 if( *amt < bt->page_size )
883 return bt_close (bt), NULL;
886 memset (latchmgr, 0, 1 << bits);
887 latchmgr->alloc->bits = bt->page_bits;
889 for( lvl=MIN_lvl; lvl--; ) {
890 slotptr(latchmgr->alloc, 1)->off = bt->page_size - 3;
891 bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
892 key = keyptr(latchmgr->alloc, 1);
893 key->len = 2; // create stopper key
896 latchmgr->alloc->min = bt->page_size - 3;
897 latchmgr->alloc->lvl = lvl;
898 latchmgr->alloc->cnt = 1;
899 latchmgr->alloc->act = 1;
901 if( write (bt->idx, latchmgr, bt->page_size) < bt->page_size )
902 return bt_close (bt), NULL;
904 if( !WriteFile (bt->idx, (char *)latchmgr, bt->page_size, amt, NULL) )
905 return bt_close (bt), NULL;
907 if( *amt < bt->page_size )
908 return bt_close (bt), NULL;
912 // clear out latch manager locks
913 // and rest of pages to round out segment
915 memset(latchmgr, 0, bt->page_size);
918 while( last <= ((MIN_lvl + 1 + nlatchpage) | bt->hashmask) ) {
920 pwrite(bt->idx, latchmgr, bt->page_size, last << bt->page_bits);
922 SetFilePointer (bt->idx, last << bt->page_bits, NULL, FILE_BEGIN);
923 if( !WriteFile (bt->idx, (char *)latchmgr, bt->page_size, amt, NULL) )
924 return bt_close (bt), NULL;
925 if( *amt < bt->page_size )
926 return bt_close (bt), NULL;
933 lock->l_type = F_UNLCK;
934 if( fcntl (bt->idx, F_SETLK, lock) < 0 )
935 return bt_close (bt), NULL;
937 if( !UnlockFileEx (bt->idx, 0, sizeof(struct BtPage_), 0, ovl) )
938 return bt_close (bt), NULL;
941 flag = PROT_READ | PROT_WRITE;
942 bt->latchmgr = mmap (0, bt->page_size, flag, MAP_SHARED, bt->idx, ALLOC_page * bt->page_size);
943 if( bt->latchmgr == MAP_FAILED )
944 return bt_close (bt), NULL;
945 bt->latchsets = (BtLatchSet *)mmap (0, bt->latchmgr->nlatchpage * bt->page_size, flag, MAP_SHARED, bt->idx, LATCH_page * bt->page_size);
946 if( bt->latchsets == MAP_FAILED )
947 return bt_close (bt), NULL;
949 flag = PAGE_READWRITE;
950 bt->halloc = CreateFileMapping(bt->idx, NULL, flag, 0, (BT_latchtable / (bt->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * bt->page_size, NULL);
952 return bt_close (bt), NULL;
954 flag = FILE_MAP_WRITE;
955 bt->latchmgr = MapViewOfFile(bt->halloc, flag, 0, 0, (BT_latchtable / (bt->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * bt->page_size);
957 return GetLastError(), bt_close (bt), NULL;
959 bt->latchsets = (void *)((char *)bt->latchmgr + LATCH_page * bt->page_size);
965 VirtualFree (latchmgr, 0, MEM_RELEASE);
969 bt->mem = malloc (6 * bt->page_size);
971 bt->mem = VirtualAlloc(NULL, 6 * bt->page_size, MEM_COMMIT, PAGE_READWRITE);
973 bt->frame = (BtPage)bt->mem;
974 bt->cursor = (BtPage)(bt->mem + bt->page_size);
975 bt->page = (BtPage)(bt->mem + 2 * bt->page_size);
976 bt->alloc = (BtPage)(bt->mem + 3 * bt->page_size);
977 bt->temp = (BtPage)(bt->mem + 4 * bt->page_size);
978 bt->zero = (BtPage)(bt->mem + 5 * bt->page_size);
980 memset (bt->zero, 0, bt->page_size);
984 // place write, read, or parent lock on requested page_no.
986 void bt_lockpage(BtLock mode, BtLatchSet *latch)
990 bt_spinreadlock (latch->readwr);
993 bt_spinwritelock (latch->readwr);
996 bt_spinreadlock (latch->access);
999 bt_spinwritelock (latch->access);
1002 bt_spinwritelock (latch->parent);
1007 // remove write, read, or parent lock on requested page
1009 void bt_unlockpage(BtLock mode, BtLatchSet *latch)
1013 bt_spinreleaseread (latch->readwr);
1016 bt_spinreleasewrite (latch->readwr);
1019 bt_spinreleaseread (latch->access);
1022 bt_spinreleasewrite (latch->access);
1025 bt_spinreleasewrite (latch->parent);
1030 // allocate a new page and write page into it
1032 uid bt_newpage(BtDb *bt, BtPage page)
1037 // lock allocation page
1039 bt_spinwritelock(bt->latchmgr->lock);
1041 // use empty chain first
1042 // else allocate empty page
1044 if( new_page = bt_getid(bt->latchmgr->alloc[1].right) ) {
1045 if( bt_mappage (bt, &bt->temp, new_page) )
1047 bt_putid(bt->latchmgr->alloc[1].right, bt_getid(bt->temp->right));
1050 new_page = bt_getid(bt->latchmgr->alloc->right);
1051 bt_putid(bt->latchmgr->alloc->right, new_page+1);
1055 bt_spinreleasewrite(bt->latchmgr->lock);
1057 if( !bt->mapped_io )
1058 if( bt_update(bt, page, new_page) )
1059 return 0; //don't unlock on error
1064 if( pwrite(bt->idx, page, bt->page_size, new_page << bt->page_bits) < bt->page_size )
1065 return bt->err = BTERR_wrt, 0;
1067 // if writing first page of pool block, zero last page in the block
1069 if( !reuse && bt->hashmask > 0 && (new_page & bt->hashmask) == 0 )
1071 // use zero buffer to write zeros
1072 if( pwrite(bt->idx,bt->zero, bt->page_size, (new_page | bt->hashmask) << bt->page_bits) < bt->page_size )
1073 return bt->err = BTERR_wrt, 0;
1076 // bring new page into pool and copy page.
1077 // this will extend the file into the new pages.
1079 if( bt_mappage (bt, &bt->temp, new_page) )
1082 memcpy(bt->temp, page, bt->page_size);
1087 // compare two keys, returning > 0, = 0, or < 0
1088 // as the comparison value
1090 int keycmp (BtKey key1, unsigned char *key2, uint len2)
1092 uint len1 = key1->len;
1095 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
1106 // Update current page of btree by writing file contents
1107 // or flushing mapped area to disk.
1109 BTERR bt_update (BtDb *bt, BtPage page, uid page_no)
1111 off64_t off = page_no << bt->page_bits;
1114 if( !bt->mapped_io )
1115 if( pwrite(bt->idx, page, bt->page_size, off) != bt->page_size )
1116 return bt->err = BTERR_wrt;
1119 if( !bt->mapped_io )
1121 SetFilePointer (bt->idx, (long)off, (long*)(&off)+1, FILE_BEGIN);
1122 if( !WriteFile (bt->idx, (char *)page, bt->page_size, amt, NULL) )
1123 return GetLastError(), bt->err = BTERR_wrt;
1125 if( *amt < bt->page_size )
1126 return GetLastError(), bt->err = BTERR_wrt;
1128 else if( bt->mode == BT_fl ) {
1129 FlushViewOfFile(page, bt->page_size);
1130 FlushFileBuffers(bt->idx);
1136 // find page in cache
1138 BtHash *bt_findhash(BtDb *bt, uid page_no)
1143 // compute cache block first page and hash idx
1145 page_no &= ~bt->hashmask;
1146 idx = (uint)(page_no >> bt->seg_bits) % bt->hashsize;
1148 if( bt->cache[idx] )
1149 hash = bt->nodes + bt->cache[idx];
1153 do if( hash->page_no == page_no )
1155 while(hash = hash->hashnext );
1160 // add page cache entry to hash index
1162 void bt_linkhash(BtDb *bt, BtHash *node, uid page_no)
1164 uint idx = (uint)(page_no >> bt->seg_bits) % bt->hashsize;
1167 if( bt->cache[idx] ) {
1168 node->hashnext = hash = bt->nodes + bt->cache[idx];
1169 hash->hashprev = node;
1172 node->hashprev = NULL;
1173 bt->cache[idx] = (ushort)(node - bt->nodes);
1176 // remove cache entry from hash table
1178 void bt_unlinkhash(BtDb *bt, BtHash *node)
1180 uint idx = (uint)(node->page_no >> bt->seg_bits) % bt->hashsize;
1184 if( hash = node->hashprev )
1185 hash->hashnext = node->hashnext;
1186 else if( hash = node->hashnext )
1187 bt->cache[idx] = (ushort)(hash - bt->nodes);
1191 if( hash = node->hashnext )
1192 hash->hashprev = node->hashprev;
1195 // add cache page to lru chain and map pages
1197 BtPage bt_linklru(BtDb *bt, BtHash *hash, uid page_no)
1200 off64_t off = (page_no & ~bt->hashmask) << bt->page_bits;
1201 off64_t limit = off + ((bt->hashmask+1) << bt->page_bits);
1204 memset(hash, 0, sizeof(BtHash));
1205 hash->page_no = (page_no & ~bt->hashmask);
1206 bt_linkhash(bt, hash, page_no);
1208 if( node = hash->lrunext = bt->lrufirst )
1209 node->lruprev = hash;
1213 bt->lrufirst = hash;
1216 flag = PROT_READ | ( bt->mode == BT_ro ? 0 : PROT_WRITE );
1217 hash->page = (BtPage)mmap (0, (bt->hashmask+1) << bt->page_bits, flag, MAP_SHARED, bt->idx, off);
1218 if( hash->page == MAP_FAILED )
1219 return bt->err = BTERR_map, (BtPage)NULL;
1222 flag = ( bt->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
1223 hash->hmap = CreateFileMapping(bt->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
1225 return bt->err = BTERR_map, NULL;
1227 flag = ( bt->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
1228 hash->page = MapViewOfFile(hash->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->hashmask+1) << bt->page_bits);
1230 return bt->err = BTERR_map, NULL;
1233 return (BtPage)((char*)hash->page + ((uint)(page_no & bt->hashmask) << bt->page_bits));
1236 // find or place requested page in page-cache
1237 // return memory address where page is located.
1239 BtPage bt_hashpage(BtDb *bt, uid page_no)
1241 BtHash *hash, *node, *next;
1244 // find page in cache and move to top of lru list
1246 if( hash = bt_findhash(bt, page_no) ) {
1247 page = (BtPage)((char*)hash->page + ((uint)(page_no & bt->hashmask) << bt->page_bits));
1248 // swap node in lru list
1249 if( node = hash->lruprev ) {
1250 if( next = node->lrunext = hash->lrunext )
1251 next->lruprev = node;
1255 if( next = hash->lrunext = bt->lrufirst )
1256 next->lruprev = hash;
1258 return bt->err = BTERR_hash, (BtPage)NULL;
1260 hash->lruprev = NULL;
1261 bt->lrufirst = hash;
1266 // map pages and add to cache entry
1268 if( bt->nodecnt < bt->nodemax ) {
1269 hash = bt->nodes + ++bt->nodecnt;
1270 return bt_linklru(bt, hash, page_no);
1273 // hash table is already full, replace last lru entry from the cache
1275 if( hash = bt->lrulast ) {
1276 // unlink from lru list
1277 if( node = bt->lrulast = hash->lruprev )
1278 node->lrunext = NULL;
1280 return bt->err = BTERR_hash, (BtPage)NULL;
1283 munmap (hash->page, (bt->hashmask+1) << bt->page_bits);
1285 FlushViewOfFile(hash->page, 0);
1286 UnmapViewOfFile(hash->page);
1287 CloseHandle(hash->hmap);
1289 // unlink from hash table
1291 bt_unlinkhash(bt, hash);
1293 // map and add to cache
1295 return bt_linklru(bt, hash, page_no);
1298 return bt->err = BTERR_hash, (BtPage)NULL;
1301 // map a btree page onto current page
1303 BTERR bt_mappage (BtDb *bt, BtPage *page, uid page_no)
1305 off64_t off = page_no << bt->page_bits;
1310 if( bt->mapped_io ) {
1312 *page = bt_hashpage(bt, page_no);
1316 if( pread(bt->idx, *page, bt->page_size, off) < bt->page_size )
1317 return bt->err = BTERR_map;
1319 SetFilePointer (bt->idx, (long)off, (long*)(&off)+1, FILE_BEGIN);
1321 if( !ReadFile(bt->idx, *page, bt->page_size, amt, NULL) )
1322 return bt->err = BTERR_map;
1324 if( *amt < bt->page_size )
1325 return bt->err = BTERR_map;
1330 // deallocate a deleted page
1331 // place on free chain out of allocator page
1332 // call with page latched for Writing and Deleting
1334 BTERR bt_freepage(BtDb *bt, uid page_no, BtPage page, BtLatchSet *latch)
1336 if( bt_mappage (bt, &page, page_no) )
1339 // lock allocation page
1341 bt_spinwritelock (bt->latchmgr->lock);
1343 // store chain in second right
1344 bt_putid(page->right, bt_getid(bt->latchmgr->alloc[1].right));
1345 bt_putid(bt->latchmgr->alloc[1].right, page_no);
1348 if( bt_update(bt, page, page_no) )
1351 // unlock released page
1353 bt_unlockpage (BtLockDelete, latch);
1354 bt_unlockpage (BtLockWrite, latch);
1355 bt_unpinlatch (latch);
1357 // unlock allocation page
1359 bt_spinreleasewrite (bt->latchmgr->lock);
1363 // find slot in page for given key at a given level
1365 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1367 uint diff, higher = bt->page->cnt, low = 1, slot;
1370 // make stopper key an infinite fence value
1372 if( bt_getid (bt->page->right) )
1377 // low is the lowest candidate, higher is already
1378 // tested as .ge. the given key, loop ends when they meet
1380 while( diff = higher - low ) {
1381 slot = low + ( diff >> 1 );
1382 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1385 higher = slot, good++;
1388 // return zero if key is on right link page
1390 return good ? higher : 0;
1393 // find and load page at given level for given key
1394 // leave page rd or wr locked as requested
1396 int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, uint lock)
1398 uid page_no = ROOT_page, prevpage = 0;
1399 uint drill = 0xff, slot;
1400 BtLatchSet *prevlatch;
1401 uint mode, prevmode;
1403 // start at root of btree and drill down
1406 // determine lock mode of drill level
1407 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1409 bt->latch = bt_pinlatch(bt, page_no);
1410 bt->page_no = page_no;
1412 // obtain access lock using lock chaining
1414 if( page_no > ROOT_page )
1415 bt_lockpage(BtLockAccess, bt->latch);
1418 bt_unlockpage(prevmode, prevlatch);
1419 bt_unpinlatch(prevlatch);
1423 // obtain read lock using lock chaining
1425 bt_lockpage(mode, bt->latch);
1427 if( page_no > ROOT_page )
1428 bt_unlockpage(BtLockAccess, bt->latch);
1430 // map/obtain page contents
1432 if( bt_mappage (bt, &bt->page, page_no) )
1435 // re-read and re-lock root after determining actual level of root
1437 if( bt->page->lvl != drill) {
1438 if( bt->page_no != ROOT_page )
1439 return bt->err = BTERR_struct, 0;
1441 drill = bt->page->lvl;
1443 if( lock != BtLockRead && drill == lvl ) {
1444 bt_unlockpage(mode, bt->latch);
1445 bt_unpinlatch(bt->latch);
1450 prevpage = bt->page_no;
1451 prevlatch = bt->latch;
1454 // find key on page at this level
1455 // and descend to requested level
1457 if( !bt->page->kill )
1458 if( slot = bt_findslot (bt, key, len) ) {
1462 while( slotptr(bt->page, slot)->dead )
1463 if( slot++ < bt->page->cnt )
1468 page_no = bt_getid(slotptr(bt->page, slot)->id);
1473 // or slide right into next page
1476 page_no = bt_getid(bt->page->right);
1480 // return error on end of right chain
1482 bt->err = BTERR_eof;
1483 return 0; // return error
1486 // a fence key was deleted from a page
1487 // push new fence value upwards
1489 BTERR bt_fixfence (BtDb *bt, uid page_no, uint lvl)
1491 unsigned char leftkey[256], rightkey[256];
1492 BtLatchSet *latch = bt->latch;
1495 // remove deleted key, the old fence value
1497 ptr = keyptr(bt->page, bt->page->cnt);
1498 memcpy(rightkey, ptr, ptr->len + 1);
1500 memset (slotptr(bt->page, bt->page->cnt--), 0, sizeof(BtSlot));
1501 bt->page->dirty = 1;
1503 ptr = keyptr(bt->page, bt->page->cnt);
1504 memcpy(leftkey, ptr, ptr->len + 1);
1506 if( bt_update (bt, bt->page, page_no) )
1509 bt_lockpage (BtLockParent, latch);
1510 bt_unlockpage (BtLockWrite, latch);
1512 // insert new (now smaller) fence key
1514 if( bt_insertkey (bt, leftkey+1, *leftkey, lvl + 1, page_no, time(NULL)) )
1517 // remove old (larger) fence key
1519 if( bt_deletekey (bt, rightkey+1, *rightkey, lvl + 1) )
1522 bt_unlockpage (BtLockParent, latch);
1523 bt_unpinlatch (latch);
1527 // root has a single child
1528 // collapse a level from the btree
1529 // call with root locked in bt->page
1531 BTERR bt_collapseroot (BtDb *bt, BtPage root)
1537 // find the child entry
1538 // and promote to new root
1541 for( idx = 0; idx++ < root->cnt; )
1542 if( !slotptr(root, idx)->dead )
1545 child = bt_getid (slotptr(root, idx)->id);
1546 latch = bt_pinlatch (bt, child);
1548 bt_lockpage (BtLockDelete, latch);
1549 bt_lockpage (BtLockWrite, latch);
1551 if( bt_mappage (bt, &bt->temp, child) )
1554 memcpy (root, bt->temp, bt->page_size);
1556 if( bt_update (bt, root, ROOT_page) )
1559 if( bt_freepage (bt, child, bt->temp, latch) )
1562 } while( root->lvl > 1 && root->act == 1 );
1564 bt_unlockpage (BtLockWrite, bt->latch);
1565 bt_unpinlatch (bt->latch);
1569 // find and delete key on page by marking delete flag bit
1570 // when page becomes empty, delete it
1572 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl)
1574 unsigned char lowerkey[256], higherkey[256];
1575 uint slot, dirty = 0, idx, fence, found;
1576 BtLatchSet *latch, *rlatch;
1580 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1581 ptr = keyptr(bt->page, slot);
1585 // are we deleting a fence slot?
1587 fence = slot == bt->page->cnt;
1589 // if key is found delete it, otherwise ignore request
1591 if( found = !keycmp (ptr, key, len) )
1592 if( found = slotptr(bt->page, slot)->dead == 0 ) {
1593 dirty = slotptr(bt->page,slot)->dead = 1;
1594 bt->page->dirty = 1;
1597 // collapse empty slots
1599 while( idx = bt->page->cnt - 1 )
1600 if( slotptr(bt->page, idx)->dead ) {
1601 *slotptr(bt->page, idx) = *slotptr(bt->page, idx + 1);
1602 memset (slotptr(bt->page, bt->page->cnt--), 0, sizeof(BtSlot));
1607 right = bt_getid(bt->page->right);
1608 page_no = bt->page_no;
1613 return bt_abort (bt, bt->page, page_no, BTERR_notfound);
1614 bt_unlockpage(BtLockWrite, latch);
1615 bt_unpinlatch (latch);
1616 return bt->found = found, 0;
1619 // did we delete a fence key in an upper level?
1621 if( lvl && bt->page->act && fence )
1622 if( bt_fixfence (bt, page_no, lvl) )
1625 return bt->found = found, 0;
1627 // is this a collapsed root?
1629 if( lvl > 1 && page_no == ROOT_page && bt->page->act == 1 )
1630 if( bt_collapseroot (bt, bt->page) )
1633 return bt->found = found, 0;
1635 // return if page is not empty
1637 if( bt->page->act ) {
1638 if( bt_update(bt, bt->page, page_no) )
1640 bt_unlockpage(BtLockWrite, latch);
1641 bt_unpinlatch (latch);
1642 return bt->found = found, 0;
1645 // cache copy of fence key
1646 // in order to find parent
1648 ptr = keyptr(bt->page, bt->page->cnt);
1649 memcpy(lowerkey, ptr, ptr->len + 1);
1651 // obtain lock on right page
1653 rlatch = bt_pinlatch (bt, right);
1654 bt_lockpage(BtLockWrite, rlatch);
1656 if( bt_mappage (bt, &bt->temp, right) )
1659 if( bt->temp->kill ) {
1660 bt_abort(bt, bt->temp, right, 0);
1661 return bt_abort(bt, bt->page, bt->page_no, BTERR_kill);
1664 // pull contents of next page into current empty page
1666 memcpy (bt->page, bt->temp, bt->page_size);
1668 // cache copy of key to update
1670 ptr = keyptr(bt->temp, bt->temp->cnt);
1671 memcpy(higherkey, ptr, ptr->len + 1);
1673 // Mark right page as deleted and point it to left page
1674 // until we can post updates at higher level.
1676 bt_putid(bt->temp->right, page_no);
1679 if( bt_update(bt, bt->page, page_no) )
1682 if( bt_update(bt, bt->temp, right) )
1685 bt_lockpage(BtLockParent, latch);
1686 bt_unlockpage(BtLockWrite, latch);
1688 bt_lockpage(BtLockParent, rlatch);
1689 bt_unlockpage(BtLockWrite, rlatch);
1691 // redirect higher key directly to consolidated node
1693 if( bt_insertkey (bt, higherkey+1, *higherkey, lvl+1, page_no, time(NULL)) )
1696 // delete old lower key to consolidated node
1698 if( bt_deletekey (bt, lowerkey + 1, *lowerkey, lvl + 1) )
1701 // obtain write & delete lock on deleted node
1702 // add right block to free chain
1704 bt_lockpage(BtLockDelete, rlatch);
1705 bt_lockpage(BtLockWrite, rlatch);
1706 bt_unlockpage(BtLockParent, rlatch);
1708 if( bt_freepage (bt, right, bt->temp, rlatch) )
1711 bt_unlockpage(BtLockParent, latch);
1712 bt_unpinlatch(latch);
1716 // find key in leaf level and return row-id
1718 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1724 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1725 ptr = keyptr(bt->page, slot);
1729 // if key exists, return row-id
1730 // otherwise return 0
1732 if( ptr->len == len && !memcmp (ptr->key, key, len) )
1733 id = bt_getid(slotptr(bt->page,slot)->id);
1737 bt_unlockpage (BtLockRead, bt->latch);
1738 bt_unpinlatch (bt->latch);
1742 // check page for space available,
1743 // clean if necessary and return
1744 // 0 - page needs splitting
1745 // >0 - go ahead with new slot
1747 uint bt_cleanpage(BtDb *bt, uint amt, uint slot)
1749 uint nxt = bt->page_size;
1750 BtPage page = bt->page;
1751 uint cnt = 0, idx = 0;
1752 uint max = page->cnt;
1753 uint newslot = slot;
1757 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1760 // skip cleanup if nothing to reclaim
1765 memcpy (bt->frame, page, bt->page_size);
1767 // skip page info and set rest of page to zero
1769 memset (page+1, 0, bt->page_size - sizeof(*page));
1772 while( cnt++ < max ) {
1775 // always leave fence key in list
1776 if( cnt < max && slotptr(bt->frame,cnt)->dead )
1780 key = keyptr(bt->frame, cnt);
1781 nxt -= key->len + 1;
1782 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1785 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1786 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1788 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1789 slotptr(page, idx)->off = nxt;
1795 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1801 // split the root and raise the height of the btree
1803 BTERR bt_splitroot(BtDb *bt, unsigned char *leftkey, uid page_no2)
1805 uint nxt = bt->page_size;
1806 BtPage root = bt->page;
1809 // Obtain an empty page to use, and copy the current
1810 // root contents into it
1812 if( !(right = bt_newpage(bt, root)) )
1815 // preserve the page info at the bottom
1816 // and set rest to zero
1818 memset(root+1, 0, bt->page_size - sizeof(*root));
1820 // insert first key on newroot page
1822 nxt -= *leftkey + 1;
1823 memcpy ((unsigned char *)root + nxt, leftkey, *leftkey + 1);
1824 bt_putid(slotptr(root, 1)->id, right);
1825 slotptr(root, 1)->off = nxt;
1827 // insert second key on newroot page
1828 // and increase the root height
1831 ((unsigned char *)root)[nxt] = 2;
1832 ((unsigned char *)root)[nxt+1] = 0xff;
1833 ((unsigned char *)root)[nxt+2] = 0xff;
1834 bt_putid(slotptr(root, 2)->id, page_no2);
1835 slotptr(root, 2)->off = nxt;
1837 bt_putid(root->right, 0);
1838 root->min = nxt; // reset lowest used offset and key count
1843 // update and release root (bt->page)
1845 if( bt_update(bt, root, bt->page_no) )
1848 bt_unlockpage(BtLockWrite, bt->latch);
1849 bt_unpinlatch(bt->latch);
1853 // split already locked full node
1856 BTERR bt_splitpage (BtDb *bt)
1858 uint cnt = 0, idx = 0, max, nxt = bt->page_size;
1859 unsigned char fencekey[256], rightkey[256];
1860 uid page_no = bt->page_no, right;
1861 BtLatchSet *latch, *rlatch;
1862 BtPage page = bt->page;
1863 uint lvl = page->lvl;
1868 // split higher half of keys to bt->frame
1869 // the last key (fence key) might be dead
1871 memset (bt->frame, 0, bt->page_size);
1876 while( cnt++ < max ) {
1877 key = keyptr(page, cnt);
1878 nxt -= key->len + 1;
1879 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
1880 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
1881 if( !(slotptr(bt->frame, idx)->dead = slotptr(page, cnt)->dead) )
1883 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
1884 slotptr(bt->frame, idx)->off = nxt;
1887 // remember fence key for new right page
1889 memcpy (rightkey, key, key->len + 1);
1891 bt->frame->bits = bt->page_bits;
1892 bt->frame->min = nxt;
1893 bt->frame->cnt = idx;
1894 bt->frame->lvl = lvl;
1898 if( page_no > ROOT_page )
1899 memcpy (bt->frame->right, page->right, BtId);
1901 // get new free page and write frame to it.
1903 if( !(right = bt_newpage(bt, bt->frame)) )
1906 // update lower keys to continue in old page
1908 memcpy (bt->frame, page, bt->page_size);
1909 memset (page+1, 0, bt->page_size - sizeof(*page));
1910 nxt = bt->page_size;
1916 // assemble page of smaller keys
1917 // (they're all active keys)
1919 while( cnt++ < max / 2 ) {
1920 key = keyptr(bt->frame, cnt);
1921 nxt -= key->len + 1;
1922 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1923 memcpy(slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1924 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1925 slotptr(page, idx)->off = nxt;
1929 // remember fence key for smaller page
1931 memcpy (fencekey, key, key->len + 1);
1933 bt_putid(page->right, right);
1937 // if current page is the root page, split it
1939 if( page_no == ROOT_page )
1940 return bt_splitroot (bt, fencekey, right);
1944 rlatch = bt_pinlatch (bt, right);
1945 bt_lockpage (BtLockParent, rlatch);
1947 // update left (containing) node
1949 if( bt_update(bt, page, page_no) )
1952 bt_lockpage (BtLockParent, latch);
1953 bt_unlockpage (BtLockWrite, latch);
1955 // insert new fence for reformulated left block
1957 if( bt_insertkey (bt, fencekey+1, *fencekey, lvl+1, page_no, time(NULL)) )
1960 // switch fence for right block of larger keys to new right page
1962 if( bt_insertkey (bt, rightkey+1, *rightkey, lvl+1, right, time(NULL)) )
1965 bt_unlockpage (BtLockParent, latch);
1966 bt_unlockpage (BtLockParent, rlatch);
1968 bt_unpinlatch (rlatch);
1969 bt_unpinlatch (latch);
1973 // Insert new key into the btree at requested level.
1974 // Pages are unlocked at exit.
1976 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod)
1983 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1984 ptr = keyptr(bt->page, slot);
1988 bt->err = BTERR_ovflw;
1992 // if key already exists, update id and return
1996 if( !keycmp (ptr, key, len) ) {
1997 if( slotptr(page, slot)->dead )
1999 slotptr(page, slot)->dead = 0;
2000 slotptr(page, slot)->tod = tod;
2001 bt_putid(slotptr(page,slot)->id, id);
2002 if( bt_update(bt, bt->page, bt->page_no) )
2004 bt_unlockpage(BtLockWrite, bt->latch);
2005 bt_unpinlatch (bt->latch);
2009 // check if page has enough space
2011 if( slot = bt_cleanpage (bt, len, slot) )
2014 if( bt_splitpage (bt) )
2018 // calculate next available slot and copy key into page
2020 page->min -= len + 1; // reset lowest used offset
2021 ((unsigned char *)page)[page->min] = len;
2022 memcpy ((unsigned char *)page + page->min +1, key, len );
2024 for( idx = slot; idx < page->cnt; idx++ )
2025 if( slotptr(page, idx)->dead )
2028 // now insert key into array before slot
2029 // preserving the fence slot
2031 if( idx == page->cnt )
2037 *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
2039 bt_putid(slotptr(page,slot)->id, id);
2040 slotptr(page, slot)->off = page->min;
2041 slotptr(page, slot)->tod = tod;
2042 slotptr(page, slot)->dead = 0;
2044 if( bt_update(bt, bt->page, bt->page_no) )
2047 bt_unlockpage(BtLockWrite, bt->latch);
2048 bt_unpinlatch(bt->latch);
2052 // cache page of keys into cursor and return starting slot for given key
2054 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2058 // cache page for retrieval
2060 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
2061 memcpy (bt->cursor, bt->page, bt->page_size);
2065 bt_unlockpage(BtLockRead, bt->latch);
2066 bt->cursor_page = bt->page_no;
2067 bt_unpinlatch (bt->latch);
2071 // return next slot for cursor page
2072 // or slide cursor right into next page
2074 uint bt_nextkey (BtDb *bt, uint slot)
2080 right = bt_getid(bt->cursor->right);
2082 while( slot++ < bt->cursor->cnt )
2083 if( slotptr(bt->cursor,slot)->dead )
2085 else if( right || (slot < bt->cursor->cnt))
2093 bt->cursor_page = right;
2094 latch = bt_pinlatch (bt, right);
2095 bt_lockpage(BtLockRead, latch);
2097 if( bt_mappage (bt, &bt->page, right) )
2100 memcpy (bt->cursor, bt->page, bt->page_size);
2101 bt_unlockpage(BtLockRead, latch);
2102 bt_unpinlatch (latch);
2109 BtKey bt_key(BtDb *bt, uint slot)
2111 return keyptr(bt->cursor, slot);
2114 uid bt_uid(BtDb *bt, uint slot)
2116 return bt_getid(slotptr(bt->cursor,slot)->id);
2119 uint bt_tod(BtDb *bt, uint slot)
2121 return slotptr(bt->cursor,slot)->tod;
2127 uint bt_audit (BtDb *bt)
2129 ushort idx, hashidx;
2136 if( *(ushort *)(bt->latchmgr->lock) )
2137 fprintf(stderr, "Alloc page locked\n");
2138 *(ushort *)(bt->latchmgr->lock) = 0;
2140 for( idx = 1; idx <= bt->latchmgr->latchdeployed; idx++ ) {
2141 latch = bt->latchsets + idx;
2142 if( *(ushort *)latch->readwr )
2143 fprintf(stderr, "latchset %d rwlocked for page %.8x\n", idx, latch->page_no);
2144 *(ushort *)latch->readwr = 0;
2146 if( *(ushort *)latch->access )
2147 fprintf(stderr, "latchset %d accesslocked for page %.8x\n", idx, latch->page_no);
2148 *(ushort *)latch->access = 0;
2150 if( *(ushort *)latch->parent )
2151 fprintf(stderr, "latchset %d parentlocked for page %.8x\n", idx, latch->page_no);
2152 *(ushort *)latch->parent = 0;
2155 fprintf(stderr, "latchset %d pinned for page %.8x\n", idx, latch->page_no);
2160 for( hashidx = 0; hashidx < bt->latchmgr->latchhash; hashidx++ ) {
2161 if( *(ushort *)(bt->latchmgr->table[hashidx].latch) )
2162 fprintf(stderr, "hash entry %d locked\n", hashidx);
2164 *(ushort *)(bt->latchmgr->table[hashidx].latch) = 0;
2166 if( idx = bt->latchmgr->table[hashidx].slot ) do {
2167 latch = bt->latchsets + idx;
2168 if( *(ushort *)latch->busy )
2169 fprintf(stderr, "latchset %d busylocked for page %.8x\n", idx, latch->page_no);
2170 *(ushort *)latch->busy = 0;
2171 if( latch->hash != hashidx )
2172 fprintf(stderr, "latchset %d wrong hashidx\n", idx);
2174 fprintf(stderr, "latchset %d pinned for page %.8x\n", idx, latch->page_no);
2175 } while( idx = latch->next );
2178 next = bt->latchmgr->nlatchpage + LATCH_page;
2179 page_no = LEAF_page;
2181 while( page_no < bt_getid(bt->latchmgr->alloc->right) ) {
2182 pread (bt->idx, bt->frame, bt->page_size, page_no << bt->page_bits);
2183 if( !bt->frame->free ) {
2184 for( idx = 0; idx++ < bt->frame->cnt - 1; ) {
2185 ptr = keyptr(bt->frame, idx+1);
2186 if( keycmp (keyptr(bt->frame, idx), ptr->key, ptr->len) >= 0 )
2187 fprintf(stderr, "page %.8x idx %.2x out of order\n", page_no, idx);
2189 if( !bt->frame->lvl )
2190 cnt += bt->frame->act;
2193 if( page_no > LEAF_page )
2202 double getCpuTime(int type)
2205 FILETIME xittime[1];
2206 FILETIME systime[1];
2207 FILETIME usrtime[1];
2208 SYSTEMTIME timeconv[1];
2211 memset (timeconv, 0, sizeof(SYSTEMTIME));
2215 GetSystemTimeAsFileTime (xittime);
2216 FileTimeToSystemTime (xittime, timeconv);
2217 ans = (double)timeconv->wDayOfWeek * 3600 * 24;
2220 GetProcessTimes (GetCurrentProcess(), crtime, xittime, systime, usrtime);
2221 FileTimeToSystemTime (usrtime, timeconv);
2224 GetProcessTimes (GetCurrentProcess(), crtime, xittime, systime, usrtime);
2225 FileTimeToSystemTime (systime, timeconv);
2229 ans += (double)timeconv->wHour * 3600;
2230 ans += (double)timeconv->wMinute * 60;
2231 ans += (double)timeconv->wSecond;
2232 ans += (double)timeconv->wMilliseconds / 1000;
2237 #include <sys/resource.h>
2239 double getCpuTime(int type)
2241 struct rusage used[1];
2242 struct timeval tv[1];
2246 gettimeofday(tv, NULL);
2247 return (double)tv->tv_sec + (double)tv->tv_usec / 1000000;
2250 getrusage(RUSAGE_SELF, used);
2251 return (double)used->ru_utime.tv_sec + (double)used->ru_utime.tv_usec / 1000000;
2254 getrusage(RUSAGE_SELF, used);
2255 return (double)used->ru_stime.tv_sec + (double)used->ru_stime.tv_usec / 1000000;
2262 // standalone program to index file of keys
2263 // then list them onto std-out
2265 int main (int argc, char **argv)
2267 uint slot, line = 0, off = 0, found = 0;
2268 int ch, cnt = 0, bits = 12;
2269 unsigned char key[256];
2283 fprintf (stderr, "Usage: %s idx_file src_file Read/Write/Scan/Delete/Find [page_bits mapped_pool_segments pages_per_segment start_line_number]\n", argv[0]);
2284 fprintf (stderr, " page_bits: size of btree page in bits\n");
2285 fprintf (stderr, " mapped_pool_segments: size of buffer pool in segments\n");
2286 fprintf (stderr, " pages_per_segment: size of buffer pool segment in pages in bits\n");
2290 start = getCpuTime(0);
2294 bits = atoi(argv[4]);
2297 map = atoi(argv[5]);
2300 fprintf (stderr, "Warning: buffer_pool > 65536 segments\n");
2302 if( map && map < 8 )
2303 fprintf (stderr, "Buffer_pool too small\n");
2306 pgblk = atoi(argv[6]);
2308 if( bits + pgblk > 30 )
2309 fprintf (stderr, "Warning: very large buffer pool segment size\n");
2312 off = atoi(argv[7]);
2314 bt = bt_open ((argv[1]), BT_rw, bits, map, pgblk, map / 8);
2317 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2321 switch(argv[3][0]| 0x20)
2324 fprintf(stderr, "started audit for %s\n", argv[2]);
2325 cnt = bt_audit (bt);
2326 fprintf(stderr, "finished audit for %s, %d keys\n", argv[2], cnt);
2330 fprintf(stderr, "started indexing for %s\n", argv[2]);
2331 if( argc > 2 && (in = fopen (argv[2], "rb")) )
2332 while( ch = getc(in), ch != EOF )
2336 sprintf((char *)key+len, "%.9d", line + off), len += 9;
2338 if( bt_insertkey (bt, key, len, 0, ++line, *tod) )
2339 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2342 else if( len < 245 )
2344 fprintf(stderr, "finished adding keys for %s, %d \n", argv[2], line);
2348 fprintf(stderr, "started deleting keys for %s\n", argv[2]);
2349 if( argc > 2 && (in = fopen (argv[2], "rb")) )
2350 while( ch = getc(in), ch != EOF )
2354 sprintf((char *)key+len, "%.9d", line + off), len += 9;
2356 if( bt_deletekey (bt, key, len, 0) )
2357 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2360 else if( len < 245 )
2362 fprintf(stderr, "finished deleting keys for %s, %d \n", argv[2], line);
2366 fprintf(stderr, "started finding keys for %s\n", argv[2]);
2367 if( argc > 2 && (in = fopen (argv[2], "rb")) )
2368 while( ch = getc(in), ch != EOF )
2372 sprintf((char *)key+len, "%.9d", line + off), len += 9;
2374 if( bt_findkey (bt, key, len) )
2377 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2380 else if( len < 245 )
2382 fprintf(stderr, "finished search of %d keys for %s, found %d\n", line, argv[2], found);
2386 fprintf(stderr, "started scaning\n");
2387 cnt = len = key[0] = 0;
2389 if( slot = bt_startkey (bt, key, len) )
2392 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
2394 while( slot = bt_nextkey (bt, slot) ) {
2395 ptr = bt_key(bt, slot);
2396 fwrite (ptr->key, ptr->len, 1, stdout);
2397 fputc ('\n', stdout);
2401 fprintf(stderr, " Total keys read %d\n", cnt - 1);
2405 fprintf(stderr, "started counting\n");
2407 next = bt->latchmgr->nlatchpage + LATCH_page;
2408 page_no = LEAF_page;
2411 while( page_no < bt_getid(bt->latchmgr->alloc->right) ) {
2412 uid off = page_no << bt->page_bits;
2414 pread (bt->idx, bt->frame, bt->page_size, off);
2418 SetFilePointer (bt->idx, (long)off, (long*)(&off)+1, FILE_BEGIN);
2420 if( !ReadFile(bt->idx, bt->frame, bt->page_size, amt, NULL))
2421 fprintf (stderr, "unable to read page %.8x", page_no);
2423 if( *amt < bt->page_size )
2424 fprintf (stderr, "unable to read page %.8x", page_no);
2426 if( !bt->frame->free && !bt->frame->lvl )
2427 cnt += bt->frame->act;
2428 if( page_no > LEAF_page )
2433 cnt--; // remove stopper key
2434 fprintf(stderr, " Total keys read %d\n", cnt);
2438 done = getCpuTime(0);
2439 elapsed = (float)(done - start);
2440 fprintf(stderr, " real %dm%.3fs\n", (int)(elapsed/60), elapsed - (int)(elapsed/60)*60);
2441 elapsed = getCpuTime(1);
2442 fprintf(stderr, " user %dm%.3fs\n", (int)(elapsed/60), elapsed - (int)(elapsed/60)*60);
2443 elapsed = getCpuTime(2);
2444 fprintf(stderr, " sys %dm%.3fs\n", (int)(elapsed/60), elapsed - (int)(elapsed/60)*60);