1 // btree version threads2j linux futex concurrency version
2 // with reworked bt_deletekey
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
29 #include <linux/futex.h>
44 #define WIN32_LEAN_AND_MEAN
58 typedef unsigned long long uid;
61 typedef unsigned long long off64_t;
62 typedef unsigned short ushort;
63 typedef unsigned int uint;
66 #define BT_ro 0x6f72 // ro
67 #define BT_rw 0x7772 // rw
69 #define BT_latchtable 128 // number of latch manager slots
71 #define BT_maxbits 24 // maximum page size in bits
72 #define BT_minbits 9 // minimum page size in bits
73 #define BT_minpage (1 << BT_minbits) // minimum page size
74 #define BT_maxpage (1 << BT_maxbits) // maximum page size
77 There are five lock types for each node in three independent sets:
78 1. (set 1) AccessIntent: Sharable. Going to Read the node. Incompatible with NodeDelete.
79 2. (set 1) NodeDelete: Exclusive. About to release the node. Incompatible with AccessIntent.
80 3. (set 2) ReadLock: Sharable. Read the node. Incompatible with WriteLock.
81 4. (set 2) WriteLock: Exclusive. Modify the node. Incompatible with ReadLock and other WriteLocks.
82 5. (set 3) ParentModification: Exclusive. Change the node's parent keys. Incompatible with another ParentModification.
93 // mode & definition for latch implementation
96 Mutex = 1 << 0, // the mutex bit
97 Write = 1 << 1, // the writers bit
98 Share = 1 << 2, // reader count
99 PendRd = 1 << 12, // reader contended count
100 PendWr = 1 << 22 // writer contended count
104 QueRd = 1, // reader queue
105 QueWr = 2 // writer queue
108 // share is count of read accessors
109 // grant write lock when share == 0
112 volatile uint mutex:1; // 1 = busy
113 volatile uint write:1; // 1 = exclusive
114 volatile uint share:10; // count of readers holding locks
115 volatile uint readwait:10; // count of readers waiting
116 volatile uint writewait:10; // count of writers waiting
119 // Define the length of the page and key pointers
123 // Page key slot definition.
125 // If BT_maxbits is 15 or less, you can save 4 bytes
126 // for each key stored by making the first two uints
127 // into ushorts. You can also save 4 bytes by removing
128 // the tod field from the key.
130 // Keys are marked dead, but remain on the page until
131 // it cleanup is called. The fence key (highest key) for
132 // the page is always present, even after cleanup.
135 uint off:BT_maxbits; // page offset for key start
136 uint dead:1; // set for deleted key
137 uint tod; // time-stamp for key
138 unsigned char id[BtId]; // id associated with key
141 // The key structure occupies space at the upper end of
142 // each page. It's a length byte followed by the value
147 unsigned char key[1];
150 // The first part of an index page.
151 // It is immediately followed
152 // by the BtSlot array of keys.
154 typedef struct BtPage_ {
155 uint cnt; // count of keys in page
156 uint act; // count of active keys
157 uint min; // next key offset
158 unsigned char bits:7; // page size in bits
159 unsigned char free:1; // page is on free list
160 unsigned char lvl:4; // level of page
161 unsigned char kill:1; // page is being deleted
162 unsigned char dirty:1; // page has deleted keys
163 unsigned char posted:1; // page fence has posted
164 unsigned char goright:1; // page is being killed, continue to right
165 unsigned char right[BtId]; // page number to right
166 unsigned char fence[256]; // page fence key
169 // hash table entries
173 volatile ushort slot; // Latch table entry at head of chain
176 // latch manager table structure
179 BtLatch readwr[1]; // read/write page lock
180 BtLatch access[1]; // Access Intent/Page delete
181 BtLatch parent[1]; // adoption of foster children
182 BtLatch busy[1]; // slot is being moved between chains
183 volatile ushort next; // next entry in hash table chain
184 volatile ushort prev; // prev entry in hash table chain
185 volatile ushort pin; // number of outstanding locks
186 volatile ushort hash; // hash slot entry is under
187 volatile uid page_no; // latch set page number
190 // The memory mapping pool table buffer manager entry
193 unsigned long long int lru; // number of times accessed
194 uid basepage; // mapped base page number
195 char *map; // mapped memory pointer
196 ushort slot; // slot index in this array
197 ushort pin; // mapped page pin counter
198 void *hashprev; // previous pool entry for the same hash idx
199 void *hashnext; // next pool entry for the same hash idx
201 HANDLE hmap; // Windows memory mapping handle
205 // The loadpage interface object
208 uid page_no; // current page number
209 BtPage page; // current page pointer
210 BtPool *pool; // current page pool
211 BtLatchSet *latch; // current page latch set
214 // structure for latch manager on ALLOC_page
217 struct BtPage_ alloc[2]; // next & free page_nos in right ptr
218 BtLatch lock[1]; // allocation area lite latch
219 ushort latchdeployed; // highest number of latch entries deployed
220 ushort nlatchpage; // number of latch pages at BT_latch
221 ushort latchtotal; // number of page latch entries
222 ushort latchhash; // number of latch hash table slots
223 ushort latchvictim; // next latch entry to examine
224 BtHashEntry table[0]; // the hash table
227 // The object structure for Btree access
230 uint page_size; // page size
231 uint page_bits; // page size in bits
232 uint seg_bits; // seg size in pages in bits
233 uint mode; // read-write mode
239 ushort poolcnt; // highest page pool node in use
240 ushort poolmax; // highest page pool node allocated
241 ushort poolmask; // total number of pages in mmap segment - 1
242 ushort evicted; // last evicted hash table slot
243 ushort hashsize; // size of Hash Table for pool entries
244 ushort *hash; // pool index for hash entries
245 BtLatch *latch; // latches for pool hash slots
246 BtLatchMgr *latchmgr; // mapped latch page from allocation page
247 BtLatchSet *latchsets; // mapped latch set from latch pages
248 BtPool *pool; // memory pool page segments
250 HANDLE halloc; // allocation and latch table handle
255 BtMgr *mgr; // buffer manager for thread
256 BtPage cursor; // cached frame for start/next (never mapped)
257 BtPage frame; // spare frame for the page split (never mapped)
258 BtPage zero; // page of zeroes to extend the file (never mapped)
259 uid cursor_page; // current cursor page number
260 unsigned char *mem; // frame, cursor, page memory buffer
261 int found; // last delete or insert was found
262 int err; // last error
276 extern void bt_close (BtDb *bt);
277 extern BtDb *bt_open (BtMgr *mgr);
278 extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod, uint lvl);
279 extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len);
280 extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
281 extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
282 extern uint bt_nextkey (BtDb *bt, uint slot);
284 // internal functions
285 BTERR bt_removepage (BtDb *bt, BtPageSet *set, uint lvl, unsigned char *pagefence);
288 extern BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolsize, uint segsize, uint hashsize);
289 void bt_mgrclose (BtMgr *mgr);
291 // Helper functions to return slot values
293 extern BtKey bt_key (BtDb *bt, uint slot);
294 extern uid bt_uid (BtDb *bt, uint slot);
295 extern uint bt_tod (BtDb *bt, uint slot);
297 // BTree page number constants
298 #define ALLOC_page 0 // allocation & lock manager hash table
299 #define ROOT_page 1 // root of the btree
300 #define LEAF_page 2 // first page of leaves
301 #define LATCH_page 3 // pages for lock manager
303 // Number of levels to create in a new BTree
307 // The page is allocated from low and hi ends.
308 // The key offsets and row-id's are allocated
309 // from the bottom, while the text of the key
310 // is allocated from the top. When the two
311 // areas meet, the page is split into two.
313 // A key consists of a length byte, two bytes of
314 // index number (0 - 65534), and up to 253 bytes
315 // of key value. Duplicate keys are discarded.
316 // Associated with each key is a 48 bit row-id.
318 // The b-tree root is always located at page 1.
319 // The first leaf page of level zero is always
320 // located on page 2.
322 // The b-tree pages are linked with next
323 // pointers to facilitate enumerators,
324 // and provide for concurrency.
326 // When to root page fills, it is split in two and
327 // the tree height is raised by a new root at page
328 // one with two keys.
330 // Deleted keys are marked with a dead bit until
331 // page cleanup. The fence key for a node is
332 // present in a special array.
334 // Groups of pages called segments from the btree are optionally
335 // cached with a memory mapped pool. A hash table is used to keep
336 // track of the cached segments. This behaviour is controlled
337 // by the cache block size parameter to bt_open.
339 // To achieve maximum concurrency one page is locked at a time
340 // as the tree is traversed to find leaf key in question. The right
341 // page numbers are used in cases where the page is being split,
344 // Page 0 is dedicated to lock for new page extensions,
345 // and chains empty pages together for reuse.
347 // The ParentModification lock on a node is obtained to serialize posting
348 // or changing the fence key for a node.
350 // Empty pages are chained together through the ALLOC page and reused.
352 // Access macros to address slot and key values from the page
353 // Page slots use 1 based indexing.
355 #define slotptr(page, slot) (((BtSlot *)(page+1)) + (slot-1))
356 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
358 void bt_putid(unsigned char *dest, uid id)
363 dest[i] = (unsigned char)id, id >>= 8;
366 uid bt_getid(unsigned char *src)
371 for( i = 0; i < BtId; i++ )
372 id <<= 8, id |= *src++;
379 int sys_futex(void *addr1, int op, int val1, struct timespec *timeout, void *addr2, int val3)
381 return syscall(SYS_futex, addr1, op, val1, timeout, addr2, val3);
384 // wait until write lock mode is clear
385 // and add 1 to the share count
387 void bt_spinreadlock(BtLatch *latch, int private)
392 private = FUTEX_PRIVATE_FLAG;
395 // obtain latch mutex
396 if( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex ) {
401 // wait for writers to clear
402 // increment read waiters and wait
404 if( latch->write || latch->writewait ) {
405 __sync_fetch_and_add ((uint *)latch, PendRd);
406 prev = __sync_fetch_and_and ((uint *)latch, ~Mutex) & ~Mutex;
407 sys_futex( (uint *)latch, FUTEX_WAIT_BITSET | private, prev, NULL, NULL, QueRd );
408 __sync_fetch_and_sub ((uint *)latch, PendRd);
412 // increment reader lock count
413 // and release latch mutex
415 __sync_fetch_and_add ((uint *)latch, Share);
416 __sync_fetch_and_and ((uint *)latch, ~Mutex);
421 // wait for other read and write latches to relinquish
423 void bt_spinwritelock(BtLatch *latch, int private)
428 private = FUTEX_PRIVATE_FLAG;
431 // obtain latch mutex
432 if( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex ) {
437 // wait for write and reader count to clear
439 if( latch->write || latch->share ) {
440 __sync_fetch_and_add ((uint *)latch, PendWr);
441 prev = __sync_fetch_and_and ((uint *)latch, ~Mutex) & ~Mutex;
442 sys_futex( (uint *)latch, FUTEX_WAIT_BITSET | private, prev, NULL, NULL, QueWr );
443 __sync_fetch_and_sub ((uint *)latch, PendWr);
448 // release latch mutex
450 __sync_fetch_and_or ((uint *)latch, Write);
451 __sync_fetch_and_and ((uint *)latch, ~Mutex);
456 // try to obtain write lock
458 // return 1 if obtained,
461 int bt_spinwritetry(BtLatch *latch)
466 // abandon request if not taken
468 if( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex )
471 // see if write mode is available
473 if( !latch->write && !latch->share ) {
474 __sync_fetch_and_or ((uint *)latch, Write);
479 // release latch mutex
481 __sync_fetch_and_and ((uint *)latch, ~Mutex);
487 void bt_spinreleasewrite(BtLatch *latch, int private)
490 private = FUTEX_PRIVATE_FLAG;
492 // obtain latch mutex
494 while( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex )
497 __sync_fetch_and_and ((uint *)latch, ~Write);
501 if( latch->writewait )
502 if( sys_futex( (uint *)latch, FUTEX_WAKE_BITSET | private, 1, NULL, NULL, QueWr ) )
505 if( latch->readwait )
506 sys_futex( (uint *)latch, FUTEX_WAKE_BITSET | private, INT_MAX, NULL, NULL, QueRd );
508 // release latch mutex
511 __sync_fetch_and_and ((uint *)latch, ~Mutex);
514 // decrement reader count
516 void bt_spinreleaseread(BtLatch *latch, int private)
519 private = FUTEX_PRIVATE_FLAG;
521 // obtain latch mutex
523 while( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex )
526 __sync_fetch_and_sub ((uint *)latch, Share);
528 // wake waiting writers
530 if( !latch->share && latch->writewait )
531 sys_futex( (uint *)latch, FUTEX_WAKE_BITSET | private, 1, NULL, NULL, QueWr );
533 // release latch mutex
535 __sync_fetch_and_and ((uint *)latch, ~Mutex);
538 // link latch table entry into latch hash table
540 void bt_latchlink (BtDb *bt, ushort hashidx, ushort victim, uid page_no)
542 BtLatchSet *set = bt->mgr->latchsets + victim;
544 if( set->next = bt->mgr->latchmgr->table[hashidx].slot )
545 bt->mgr->latchsets[set->next].prev = victim;
547 bt->mgr->latchmgr->table[hashidx].slot = victim;
548 set->page_no = page_no;
555 void bt_unpinlatch (BtLatchSet *set)
558 __sync_fetch_and_add(&set->pin, -1);
560 _InterlockedDecrement16 (&set->pin);
564 // find existing latchset or inspire new one
565 // return with latchset pinned
567 BtLatchSet *bt_pinlatch (BtDb *bt, uid page_no)
569 ushort hashidx = page_no % bt->mgr->latchmgr->latchhash;
570 ushort slot, avail = 0, victim, idx;
573 // obtain read lock on hash table entry
575 bt_spinreadlock(bt->mgr->latchmgr->table[hashidx].latch, 0);
577 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
579 set = bt->mgr->latchsets + slot;
580 if( page_no == set->page_no )
582 } while( slot = set->next );
586 __sync_fetch_and_add(&set->pin, 1);
588 _InterlockedIncrement16 (&set->pin);
592 bt_spinreleaseread (bt->mgr->latchmgr->table[hashidx].latch, 0);
597 // try again, this time with write lock
599 bt_spinwritelock(bt->mgr->latchmgr->table[hashidx].latch, 0);
601 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
603 set = bt->mgr->latchsets + slot;
604 if( page_no == set->page_no )
606 if( !set->pin && !avail )
608 } while( slot = set->next );
610 // found our entry, or take over an unpinned one
612 if( slot || (slot = avail) ) {
613 set = bt->mgr->latchsets + slot;
615 __sync_fetch_and_add(&set->pin, 1);
617 _InterlockedIncrement16 (&set->pin);
619 set->page_no = page_no;
620 bt_spinreleasewrite(bt->mgr->latchmgr->table[hashidx].latch, 0);
624 // see if there are any unused entries
626 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, 1) + 1;
628 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchdeployed);
631 if( victim < bt->mgr->latchmgr->latchtotal ) {
632 set = bt->mgr->latchsets + victim;
634 __sync_fetch_and_add(&set->pin, 1);
636 _InterlockedIncrement16 (&set->pin);
638 bt_latchlink (bt, hashidx, victim, page_no);
639 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch, 0);
644 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, -1);
646 victim = _InterlockedDecrement16 (&bt->mgr->latchmgr->latchdeployed);
648 // find and reuse previous lock entry
652 victim = __sync_fetch_and_add(&bt->mgr->latchmgr->latchvictim, 1);
654 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchvictim) - 1;
656 // we don't use slot zero
658 if( victim %= bt->mgr->latchmgr->latchtotal )
659 set = bt->mgr->latchsets + victim;
663 // take control of our slot
664 // from other threads
666 if( set->pin || !bt_spinwritetry (set->busy) )
671 // try to get write lock on hash chain
672 // skip entry if not obtained
673 // or has outstanding locks
675 if( !bt_spinwritetry (bt->mgr->latchmgr->table[idx].latch) ) {
676 bt_spinreleasewrite (set->busy, 0);
681 bt_spinreleasewrite (set->busy, 0);
682 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch, 0);
686 // unlink our available victim from its hash chain
689 bt->mgr->latchsets[set->prev].next = set->next;
691 bt->mgr->latchmgr->table[idx].slot = set->next;
694 bt->mgr->latchsets[set->next].prev = set->prev;
696 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch, 0);
698 __sync_fetch_and_add(&set->pin, 1);
700 _InterlockedIncrement16 (&set->pin);
702 bt_latchlink (bt, hashidx, victim, page_no);
703 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch, 0);
704 bt_spinreleasewrite (set->busy, 0);
709 void bt_mgrclose (BtMgr *mgr)
714 // release mapped pages
715 // note that slot zero is never used
717 for( slot = 1; slot < mgr->poolmax; slot++ ) {
718 pool = mgr->pool + slot;
721 munmap (pool->map, (mgr->poolmask+1) << mgr->page_bits);
724 FlushViewOfFile(pool->map, 0);
725 UnmapViewOfFile(pool->map);
726 CloseHandle(pool->hmap);
732 munmap (mgr->latchsets, mgr->latchmgr->nlatchpage * mgr->page_size);
733 munmap (mgr->latchmgr, mgr->page_size);
735 FlushViewOfFile(mgr->latchmgr, 0);
736 UnmapViewOfFile(mgr->latchmgr);
737 CloseHandle(mgr->halloc);
746 FlushFileBuffers(mgr->idx);
747 CloseHandle(mgr->idx);
748 GlobalFree (mgr->pool);
749 GlobalFree (mgr->hash);
750 GlobalFree (mgr->latch);
755 // close and release memory
757 void bt_close (BtDb *bt)
764 VirtualFree (bt->mem, 0, MEM_RELEASE);
769 // open/create new btree buffer manager
771 // call with file_name, BT_openmode, bits in page size (e.g. 16),
772 // size of mapped page pool (e.g. 8192)
774 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
776 uint lvl, attr, cacheblk, last, slot, idx;
777 uint nlatchpage, latchhash;
778 BtLatchMgr *latchmgr;
785 SYSTEM_INFO sysinfo[1];
788 // determine sanity of page size and buffer pool
790 if( bits > BT_maxbits )
792 else if( bits < BT_minbits )
796 return NULL; // must have buffer pool
799 mgr = calloc (1, sizeof(BtMgr));
800 mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
803 return free(mgr), NULL;
805 cacheblk = 4096; // minimum mmap segment size for unix
808 mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
809 attr = FILE_ATTRIBUTE_NORMAL;
810 mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
812 if( mgr->idx == INVALID_HANDLE_VALUE )
813 return GlobalFree(mgr), NULL;
815 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
816 GetSystemInfo(sysinfo);
817 cacheblk = sysinfo->dwAllocationGranularity;
821 latchmgr = malloc (BT_maxpage);
824 // read minimum page size to get root info
826 if( size = lseek (mgr->idx, 0L, 2) ) {
827 if( pread(mgr->idx, latchmgr, BT_minpage, 0) == BT_minpage )
828 bits = latchmgr->alloc->bits;
830 return free(mgr), free(latchmgr), NULL;
831 } else if( mode == BT_ro )
832 return free(latchmgr), free (mgr), NULL;
834 latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
835 size = GetFileSize(mgr->idx, amt);
838 if( !ReadFile(mgr->idx, (char *)latchmgr, BT_minpage, amt, NULL) )
839 return bt_mgrclose (mgr), NULL;
840 bits = latchmgr->alloc->bits;
841 } else if( mode == BT_ro )
842 return bt_mgrclose (mgr), NULL;
845 mgr->page_size = 1 << bits;
846 mgr->page_bits = bits;
848 mgr->poolmax = poolmax;
851 if( cacheblk < mgr->page_size )
852 cacheblk = mgr->page_size;
854 // mask for partial memmaps
856 mgr->poolmask = (cacheblk >> bits) - 1;
858 // see if requested size of pages per memmap is greater
860 if( (1 << segsize) > mgr->poolmask )
861 mgr->poolmask = (1 << segsize) - 1;
865 while( (1 << mgr->seg_bits) <= mgr->poolmask )
868 mgr->hashsize = hashsize;
871 mgr->pool = calloc (poolmax, sizeof(BtPool));
872 mgr->hash = calloc (hashsize, sizeof(ushort));
873 mgr->latch = calloc (hashsize, sizeof(BtLatch));
875 mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * sizeof(BtPool));
876 mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
877 mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtLatch));
883 // initialize an empty b-tree with latch page, root page, page of leaves
884 // and page(s) of latches
886 memset (latchmgr, 0, 1 << bits);
887 nlatchpage = BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1;
888 bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
889 latchmgr->alloc->bits = mgr->page_bits;
891 latchmgr->nlatchpage = nlatchpage;
892 latchmgr->latchtotal = nlatchpage * (mgr->page_size / sizeof(BtLatchSet));
894 // initialize latch manager
896 latchhash = (mgr->page_size - sizeof(BtLatchMgr)) / sizeof(BtHashEntry);
898 // size of hash table = total number of latchsets
900 if( latchhash > latchmgr->latchtotal )
901 latchhash = latchmgr->latchtotal;
903 latchmgr->latchhash = latchhash;
906 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
907 return bt_mgrclose (mgr), NULL;
909 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
910 return bt_mgrclose (mgr), NULL;
912 if( *amt < mgr->page_size )
913 return bt_mgrclose (mgr), NULL;
916 memset (latchmgr, 0, 1 << bits);
917 latchmgr->alloc->bits = mgr->page_bits;
919 for( lvl=MIN_lvl; lvl--; ) {
920 slotptr(latchmgr->alloc, 1)->off = offsetof(struct BtPage_, fence);
921 bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
922 latchmgr->alloc->fence[0] = 2; // create stopper key
923 latchmgr->alloc->fence[1] = 0xff;
924 latchmgr->alloc->fence[2] = 0xff;
925 latchmgr->alloc->min = mgr->page_size;
926 latchmgr->alloc->lvl = lvl;
927 latchmgr->alloc->cnt = 1;
928 latchmgr->alloc->act = 1;
930 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
931 return bt_mgrclose (mgr), NULL;
933 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
934 return bt_mgrclose (mgr), NULL;
936 if( *amt < mgr->page_size )
937 return bt_mgrclose (mgr), NULL;
941 // clear out latch manager locks
942 // and rest of pages to round out segment
944 memset(latchmgr, 0, mgr->page_size);
947 while( last <= ((MIN_lvl + 1 + nlatchpage) | mgr->poolmask) ) {
949 pwrite(mgr->idx, latchmgr, mgr->page_size, last << mgr->page_bits);
951 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
952 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
953 return bt_mgrclose (mgr), NULL;
954 if( *amt < mgr->page_size )
955 return bt_mgrclose (mgr), NULL;
962 flag = PROT_READ | PROT_WRITE;
963 mgr->latchmgr = mmap (0, mgr->page_size, flag, MAP_SHARED, mgr->idx, ALLOC_page * mgr->page_size);
964 if( mgr->latchmgr == MAP_FAILED )
965 return bt_mgrclose (mgr), NULL;
966 mgr->latchsets = (BtLatchSet *)mmap (0, mgr->latchmgr->nlatchpage * mgr->page_size, flag, MAP_SHARED, mgr->idx, LATCH_page * mgr->page_size);
967 if( mgr->latchsets == MAP_FAILED )
968 return bt_mgrclose (mgr), NULL;
970 flag = PAGE_READWRITE;
971 mgr->halloc = CreateFileMapping(mgr->idx, NULL, flag, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size, NULL);
973 return bt_mgrclose (mgr), NULL;
975 flag = FILE_MAP_WRITE;
976 mgr->latchmgr = MapViewOfFile(mgr->halloc, flag, 0, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size);
978 return GetLastError(), bt_mgrclose (mgr), NULL;
980 mgr->latchsets = (void *)((char *)mgr->latchmgr + LATCH_page * mgr->page_size);
986 VirtualFree (latchmgr, 0, MEM_RELEASE);
991 // open BTree access method
992 // based on buffer manager
994 BtDb *bt_open (BtMgr *mgr)
996 BtDb *bt = malloc (sizeof(*bt));
998 memset (bt, 0, sizeof(*bt));
1001 bt->mem = malloc (3 *mgr->page_size);
1003 bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
1005 bt->frame = (BtPage)bt->mem;
1006 bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
1007 bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
1009 memset (bt->zero, 0, mgr->page_size);
1013 // compare two keys, returning > 0, = 0, or < 0
1014 // as the comparison value
1016 int keycmp (BtKey key1, unsigned char *key2, uint len2)
1018 uint len1 = key1->len;
1021 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
1034 // find segment in pool
1035 // must be called with hashslot idx locked
1036 // return NULL if not there
1037 // otherwise return node
1039 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
1044 // compute start of hash chain in pool
1046 if( slot = bt->mgr->hash[idx] )
1047 pool = bt->mgr->pool + slot;
1051 page_no &= ~bt->mgr->poolmask;
1053 while( pool->basepage != page_no )
1054 if( pool = pool->hashnext )
1062 // add segment to hash table
1064 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
1069 pool->hashprev = pool->hashnext = NULL;
1070 pool->basepage = page_no & ~bt->mgr->poolmask;
1073 if( slot = bt->mgr->hash[idx] ) {
1074 node = bt->mgr->pool + slot;
1075 pool->hashnext = node;
1076 node->hashprev = pool;
1079 bt->mgr->hash[idx] = pool->slot;
1082 // find best segment to evict from buffer pool
1084 BtPool *bt_findlru (BtDb *bt, uint hashslot)
1086 unsigned long long int target = ~0LL;
1087 BtPool *pool = NULL, *node;
1092 node = bt->mgr->pool + hashslot;
1094 // scan pool entries under hash table slot
1099 if( node->lru > target )
1103 } while( node = node->hashnext );
1108 // map new buffer pool segment to virtual memory
1110 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
1112 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
1113 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
1117 flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
1118 pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED | MAP_POPULATE, bt->mgr->idx, off);
1119 if( pool->map == MAP_FAILED )
1120 return bt->err = BTERR_map;
1123 flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
1124 pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
1126 return bt->err = BTERR_map;
1128 flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
1129 pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1131 return bt->err = BTERR_map;
1136 // calculate page within pool
1138 BtPage bt_page (BtDb *bt, BtPool *pool, uid page_no)
1140 uint subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1143 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1149 void bt_unpinpool (BtPool *pool)
1152 __sync_fetch_and_add(&pool->pin, -1);
1154 _InterlockedDecrement16 (&pool->pin);
1158 // find or place requested page in segment-pool
1159 // return pool table entry, incrementing pin
1161 BtPool *bt_pinpool(BtDb *bt, uid page_no)
1163 BtPool *pool, *node, *next;
1164 uint slot, idx, victim;
1166 // lock hash table chain
1168 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1169 bt_spinreadlock (&bt->mgr->latch[idx], 1);
1171 // look up in hash table
1173 if( pool = bt_findpool(bt, page_no, idx) ) {
1175 __sync_fetch_and_add(&pool->pin, 1);
1177 _InterlockedIncrement16 (&pool->pin);
1179 bt_spinreleaseread (&bt->mgr->latch[idx], 1);
1184 // upgrade to write lock
1186 bt_spinreleaseread (&bt->mgr->latch[idx], 1);
1187 bt_spinwritelock (&bt->mgr->latch[idx], 1);
1189 // try to find page in pool with write lock
1191 if( pool = bt_findpool(bt, page_no, idx) ) {
1193 __sync_fetch_and_add(&pool->pin, 1);
1195 _InterlockedIncrement16 (&pool->pin);
1197 bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
1202 // allocate a new pool node
1203 // and add to hash table
1206 slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
1208 slot = _InterlockedIncrement16 (&bt->mgr->poolcnt) - 1;
1211 if( ++slot < bt->mgr->poolmax ) {
1212 pool = bt->mgr->pool + slot;
1215 if( bt_mapsegment(bt, pool, page_no) )
1218 bt_linkhash(bt, pool, page_no, idx);
1220 __sync_fetch_and_add(&pool->pin, 1);
1222 _InterlockedIncrement16 (&pool->pin);
1224 bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
1228 // pool table is full
1229 // find best pool entry to evict
1232 __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
1234 _InterlockedDecrement16 (&bt->mgr->poolcnt);
1239 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
1241 victim = _InterlockedIncrement16 (&bt->mgr->evicted) - 1;
1243 victim %= bt->mgr->hashsize;
1245 // try to get write lock
1246 // skip entry if not obtained
1248 if( !bt_spinwritetry (&bt->mgr->latch[victim]) )
1251 // if pool entry is empty
1252 // or any pages are pinned
1255 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
1256 bt_spinreleasewrite (&bt->mgr->latch[victim], 1);
1260 // unlink victim pool node from hash table
1262 if( node = pool->hashprev )
1263 node->hashnext = pool->hashnext;
1264 else if( node = pool->hashnext )
1265 bt->mgr->hash[victim] = node->slot;
1267 bt->mgr->hash[victim] = 0;
1269 if( node = pool->hashnext )
1270 node->hashprev = pool->hashprev;
1272 bt_spinreleasewrite (&bt->mgr->latch[victim], 1);
1274 // remove old file mapping
1276 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1278 FlushViewOfFile(pool->map, 0);
1279 UnmapViewOfFile(pool->map);
1280 CloseHandle(pool->hmap);
1284 // create new pool mapping
1285 // and link into hash table
1287 if( bt_mapsegment(bt, pool, page_no) )
1290 bt_linkhash(bt, pool, page_no, idx);
1292 __sync_fetch_and_add(&pool->pin, 1);
1294 _InterlockedIncrement16 (&pool->pin);
1296 bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
1301 // place write, read, or parent lock on requested page_no.
1303 void bt_lockpage(BtLock mode, BtLatchSet *set)
1307 bt_spinreadlock (set->readwr, 0);
1310 bt_spinwritelock (set->readwr, 0);
1313 bt_spinreadlock (set->access, 0);
1316 bt_spinwritelock (set->access, 0);
1319 bt_spinwritelock (set->parent, 0);
1324 // remove write, read, or parent lock on requested page
1326 void bt_unlockpage(BtLock mode, BtLatchSet *set)
1330 bt_spinreleaseread (set->readwr, 0);
1333 bt_spinreleasewrite (set->readwr, 0);
1336 bt_spinreleaseread (set->access, 0);
1339 bt_spinreleasewrite (set->access, 0);
1342 bt_spinreleasewrite (set->parent, 0);
1347 // allocate a new page and write page into it
1349 uid bt_newpage(BtDb *bt, BtPage page)
1355 // lock allocation page
1357 bt_spinwritelock(bt->mgr->latchmgr->lock, 0);
1359 // use empty chain first
1360 // else allocate empty page
1362 if( new_page = bt_getid(bt->mgr->latchmgr->alloc[1].right) ) {
1363 if( set->pool = bt_pinpool (bt, new_page) )
1364 set->page = bt_page (bt, set->pool, new_page);
1368 bt_putid(bt->mgr->latchmgr->alloc[1].right, bt_getid(set->page->right));
1369 bt_unpinpool (set->pool);
1372 new_page = bt_getid(bt->mgr->latchmgr->alloc->right);
1373 bt_putid(bt->mgr->latchmgr->alloc->right, new_page+1);
1377 if ( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1378 return bt->err = BTERR_wrt, 0;
1380 // if writing first page of pool block, zero last page in the block
1382 if ( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1384 // use zero buffer to write zeros
1385 if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1386 return bt->err = BTERR_wrt, 0;
1389 // bring new page into pool and copy page.
1390 // this will extend the file into the new pages.
1392 if( set->pool = bt_pinpool (bt, new_page) )
1393 set->page = bt_page (bt, set->pool, new_page);
1397 memcpy(set->page, page, bt->mgr->page_size);
1398 bt_unpinpool (set->pool);
1400 // unlock allocation latch and return new page no
1402 bt_spinreleasewrite(bt->mgr->latchmgr->lock, 0);
1406 // find slot in page for given key at a given level
1408 int bt_findslot (BtPageSet *set, unsigned char *key, uint len)
1410 uint diff, higher = set->page->cnt, low = 1, slot;
1412 // make stopper key an infinite fence value
1414 if( bt_getid (set->page->right) )
1417 // low is the lowest candidate.
1418 // loop ends when they meet
1420 // higher is already
1421 // tested as .ge. the given key.
1423 while( diff = higher - low ) {
1424 slot = low + ( diff >> 1 );
1425 if( keycmp (keyptr(set->page, slot), key, len) < 0 )
1431 if( higher <= set->page->cnt )
1434 // if leaf page, compare against fence value
1436 // return zero if key is on right link page
1437 // or return slot beyond last key
1439 if( set->page->lvl || keycmp ((BtKey)set->page->fence, key, len) < 0 )
1445 // find and load page at given level for given key
1446 // leave page rd or wr locked as requested
1448 int bt_loadpage (BtDb *bt, BtPageSet *set, unsigned char *key, uint len, uint lvl, uint lock)
1450 uid page_no = ROOT_page, prevpage = 0;
1451 uint drill = 0xff, slot;
1452 BtLatchSet *prevlatch;
1453 uint mode, prevmode;
1456 // start at root of btree and drill down
1459 // determine lock mode of drill level
1460 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1462 set->latch = bt_pinlatch (bt, page_no);
1463 set->page_no = page_no;
1465 // pin page contents
1467 if( set->pool = bt_pinpool (bt, page_no) )
1468 set->page = bt_page (bt, set->pool, page_no);
1472 // obtain access lock using lock chaining with Access mode
1474 if( page_no > ROOT_page )
1475 bt_lockpage(BtLockAccess, set->latch);
1477 // release & unpin parent page
1480 bt_unlockpage(prevmode, prevlatch);
1481 bt_unpinlatch (prevlatch);
1482 bt_unpinpool (prevpool);
1486 // obtain read lock using lock chaining
1488 bt_lockpage(mode, set->latch);
1490 if( page_no > ROOT_page )
1491 bt_unlockpage(BtLockAccess, set->latch);
1493 // re-read and re-lock root after determining actual level of root
1495 if( set->page->lvl != drill) {
1496 if ( set->page_no != ROOT_page )
1497 return bt->err = BTERR_struct, 0;
1499 drill = set->page->lvl;
1501 if( lock == BtLockWrite && drill == lvl ) {
1502 bt_unlockpage(mode, set->latch);
1503 bt_unpinlatch (set->latch);
1504 bt_unpinpool (set->pool);
1509 prevpage = set->page_no;
1510 prevlatch = set->latch;
1511 prevpool = set->pool;
1514 // if page is being deleted and we should continue right
1516 if( set->page->kill && set->page->goright ) {
1517 page_no = bt_getid (set->page->right);
1521 // otherwise, wait for deleted node to clear
1523 if( set->page->kill ) {
1524 bt_unlockpage(mode, set->latch);
1525 bt_unpinlatch (set->latch);
1526 bt_unpinpool (set->pool);
1527 page_no = ROOT_page;
1538 // find key on page at this level
1539 // and descend to requested level
1541 if( slot = bt_findslot (set, key, len) ) {
1545 if( slot > set->page->cnt )
1546 return bt->err = BTERR_struct;
1548 while( slotptr(set->page, slot)->dead )
1549 if( slot++ < set->page->cnt )
1552 return bt->err = BTERR_struct, 0;
1554 page_no = bt_getid(slotptr(set->page, slot)->id);
1559 // or slide right into next page
1561 page_no = bt_getid(set->page->right);
1565 // return error on end of right chain
1567 bt->err = BTERR_struct;
1568 return 0; // return error
1571 // drill down fixing fence values for left sibling tree
1573 // call with set write locked
1574 // return with set unlocked & unpinned.
1576 BTERR bt_fixfences (BtDb *bt, BtPageSet *set, unsigned char *newfence)
1578 unsigned char oldfence[256];
1582 memcpy (oldfence, set->page->fence, 256);
1583 next->page_no = bt_getid(slotptr(set->page, set->page->cnt)->id);
1585 while( !set->page->kill && set->page->lvl ) {
1586 next->latch = bt_pinlatch (bt, next->page_no);
1587 bt_lockpage (BtLockParent, next->latch);
1588 bt_lockpage (BtLockAccess, next->latch);
1589 bt_lockpage (BtLockWrite, next->latch);
1590 bt_unlockpage (BtLockAccess, next->latch);
1592 if( next->pool = bt_pinpool (bt, next->page_no) )
1593 next->page = bt_page (bt, next->pool, next->page_no);
1597 chk = keycmp ((BtKey)next->page->fence, oldfence + 1, *oldfence);
1600 next->page_no = bt_getid (next->page->right);
1601 bt_unlockpage (BtLockWrite, next->latch);
1602 bt_unlockpage (BtLockParent, next->latch);
1603 bt_unpinlatch (next->latch);
1604 bt_unpinpool (next->pool);
1609 return bt->err = BTERR_struct;
1611 if( bt_fixfences (bt, next, newfence) )
1617 memcpy (set->page->fence, newfence, 256);
1619 bt_unlockpage (BtLockWrite, set->latch);
1620 bt_unlockpage (BtLockParent, set->latch);
1621 bt_unpinlatch (set->latch);
1622 bt_unpinpool (set->pool);
1626 // return page to free list
1627 // page must be delete & write locked
1629 void bt_freepage (BtDb *bt, BtPageSet *set)
1631 // lock allocation page
1633 bt_spinwritelock (bt->mgr->latchmgr->lock, 0);
1635 // store chain in second right
1636 bt_putid(set->page->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1637 bt_putid(bt->mgr->latchmgr->alloc[1].right, set->page_no);
1638 set->page->free = 1;
1640 // unlock released page
1642 bt_unlockpage (BtLockDelete, set->latch);
1643 bt_unlockpage (BtLockWrite, set->latch);
1644 bt_unpinlatch (set->latch);
1645 bt_unpinpool (set->pool);
1647 // unlock allocation page
1649 bt_spinreleasewrite (bt->mgr->latchmgr->lock, 0);
1652 // remove the root level by promoting its only child
1653 // call with parent and child pages
1655 BTERR bt_removeroot (BtDb *bt, BtPageSet *root, BtPageSet *child)
1661 child->latch = bt_pinlatch (bt, next);
1662 bt_lockpage (BtLockDelete, child->latch);
1663 bt_lockpage (BtLockWrite, child->latch);
1665 if( child->pool = bt_pinpool (bt, next) )
1666 child->page = bt_page (bt, child->pool, next);
1670 child->page_no = next;
1673 memcpy (root->page, child->page, bt->mgr->page_size);
1674 next = bt_getid (slotptr(child->page, child->page->cnt)->id);
1675 bt_freepage (bt, child);
1676 } while( root->page->lvl > 1 && root->page->cnt == 1 );
1678 bt_unlockpage (BtLockWrite, root->latch);
1679 bt_unpinlatch (root->latch);
1680 bt_unpinpool (root->pool);
1684 // pull right page over ourselves in simple merge
1686 BTERR bt_mergeright (BtDb *bt, BtPageSet *set, BtPageSet *parent, BtPageSet *right, uint slot, uint idx)
1688 // install ourselves as child page
1689 // and delete ourselves from parent
1691 bt_putid (slotptr(parent->page, idx)->id, set->page_no);
1692 slotptr(parent->page, slot)->dead = 1;
1693 parent->page->act--;
1695 // collapse any empty slots
1697 while( idx = parent->page->cnt - 1 )
1698 if( slotptr(parent->page, idx)->dead ) {
1699 *slotptr(parent->page, idx) = *slotptr(parent->page, idx + 1);
1700 memset (slotptr(parent->page, parent->page->cnt--), 0, sizeof(BtSlot));
1704 memcpy (set->page, right->page, bt->mgr->page_size);
1705 bt_unlockpage (BtLockParent, right->latch);
1707 bt_freepage (bt, right);
1709 // do we need to remove a btree level?
1710 // (leave the first page of leaves alone)
1712 if( parent->page_no == ROOT_page && parent->page->cnt == 1 )
1713 if( set->page->lvl )
1714 return bt_removeroot (bt, parent, set);
1716 bt_unlockpage (BtLockWrite, parent->latch);
1717 bt_unlockpage (BtLockDelete, set->latch);
1718 bt_unlockpage (BtLockWrite, set->latch);
1719 bt_unpinlatch (parent->latch);
1720 bt_unpinpool (parent->pool);
1721 bt_unpinlatch (set->latch);
1722 bt_unpinpool (set->pool);
1726 // remove both child and parent from the btree
1727 // from the fence position in the parent
1728 // call with both pages locked for writing
1730 BTERR bt_removeparent (BtDb *bt, BtPageSet *child, BtPageSet *parent, BtPageSet *right, BtPageSet *rparent, uint lvl)
1732 unsigned char pagefence[256];
1735 // pull right sibling over ourselves and unlock
1737 memcpy (child->page, right->page, bt->mgr->page_size);
1739 bt_unlockpage (BtLockWrite, child->latch);
1740 bt_unpinlatch (child->latch);
1741 bt_unpinpool (child->pool);
1743 // install ourselves into right link of old right page
1745 bt_putid (right->page->right, child->page_no);
1746 right->page->goright = 1; // tell bt_loadpage to go right to us
1747 right->page->kill = 1;
1749 bt_unlockpage (BtLockWrite, right->latch);
1751 // remove our slot from our parent
1752 // signal to move right
1754 parent->page->goright = 1; // tell bt_loadpage to go right to rparent
1755 parent->page->kill = 1;
1756 parent->page->act--;
1758 // redirect right page pointer in right parent to us
1760 for( idx = 0; idx++ < rparent->page->cnt; )
1761 if( !slotptr(rparent->page, idx)->dead )
1764 if( bt_getid (slotptr(rparent->page, idx)->id) != right->page_no )
1765 return bt->err = BTERR_struct;
1767 bt_putid (slotptr(rparent->page, idx)->id, child->page_no);
1768 bt_unlockpage (BtLockWrite, rparent->latch);
1769 bt_unpinlatch (rparent->latch);
1770 bt_unpinpool (rparent->pool);
1772 // free the right page
1774 bt_lockpage (BtLockDelete, right->latch);
1775 bt_lockpage (BtLockWrite, right->latch);
1776 bt_freepage (bt, right);
1778 // save parent page fence value
1780 memcpy (pagefence, parent->page->fence, 256);
1781 bt_unlockpage (BtLockWrite, parent->latch);
1783 return bt_removepage (bt, parent, lvl, pagefence);
1786 // remove page from btree
1787 // call with page unlocked
1788 // returns with page on free list
1790 BTERR bt_removepage (BtDb *bt, BtPageSet *set, uint lvl, unsigned char *pagefence)
1792 BtPageSet parent[1], sibling[1], rparent[1];
1793 unsigned char newfence[256];
1797 // load and lock our parent
1800 if( !(slot = bt_loadpage (bt, parent, pagefence+1, *pagefence, lvl+1, BtLockWrite)) )
1803 // do we show up in our parent yet?
1805 if( set->page_no != bt_getid (slotptr (parent->page, slot)->id) ) {
1806 bt_unlockpage (BtLockWrite, parent->latch);
1807 bt_unpinlatch (parent->latch);
1808 bt_unpinpool (parent->pool);
1817 // can we do a simple merge entirely
1818 // between siblings on the parent page?
1820 if( slot < parent->page->cnt ) {
1821 // find our right neighbor
1822 // right must exist because the stopper prevents
1823 // the rightmost page from deleting
1825 for( idx = slot; idx++ < parent->page->cnt; )
1826 if( !slotptr(parent->page, idx)->dead )
1829 sibling->page_no = bt_getid (slotptr (parent->page, idx)->id);
1831 bt_lockpage (BtLockDelete, set->latch);
1832 bt_lockpage (BtLockWrite, set->latch);
1834 // merge right if sibling shows up in
1835 // our parent and is not being killed
1837 if( sibling->page_no == bt_getid (set->page->right) ) {
1838 sibling->latch = bt_pinlatch (bt, sibling->page_no);
1839 bt_lockpage (BtLockParent, sibling->latch);
1840 bt_lockpage (BtLockDelete, sibling->latch);
1841 bt_lockpage (BtLockWrite, sibling->latch);
1843 if( sibling->pool = bt_pinpool (bt, sibling->page_no) )
1844 sibling->page = bt_page (bt, sibling->pool, sibling->page_no);
1848 if( !sibling->page->kill )
1849 return bt_mergeright(bt, set, parent, sibling, slot, idx);
1853 bt_unlockpage (BtLockWrite, sibling->latch);
1854 bt_unlockpage (BtLockParent, sibling->latch);
1855 bt_unlockpage (BtLockDelete, sibling->latch);
1856 bt_unpinlatch (sibling->latch);
1857 bt_unpinpool (sibling->pool);
1860 bt_unlockpage (BtLockDelete, set->latch);
1861 bt_unlockpage (BtLockWrite, set->latch);
1862 bt_unlockpage (BtLockWrite, parent->latch);
1863 bt_unpinlatch (parent->latch);
1864 bt_unpinpool (parent->pool);
1873 // find our left neighbor in our parent page
1875 for( idx = slot; --idx; )
1876 if( !slotptr(parent->page, idx)->dead )
1879 // if no left neighbor, delete ourselves and our parent
1882 bt_lockpage (BtLockAccess, set->latch);
1883 bt_lockpage (BtLockWrite, set->latch);
1884 bt_unlockpage (BtLockAccess, set->latch);
1886 rparent->page_no = bt_getid (parent->page->right);
1887 rparent->latch = bt_pinlatch (bt, rparent->page_no);
1889 bt_lockpage (BtLockAccess, rparent->latch);
1890 bt_lockpage (BtLockWrite, rparent->latch);
1891 bt_unlockpage (BtLockAccess, rparent->latch);
1893 if( rparent->pool = bt_pinpool (bt, rparent->page_no) )
1894 rparent->page = bt_page (bt, rparent->pool, rparent->page_no);
1898 if( !rparent->page->kill ) {
1899 sibling->page_no = bt_getid (set->page->right);
1900 sibling->latch = bt_pinlatch (bt, sibling->page_no);
1902 bt_lockpage (BtLockAccess, sibling->latch);
1903 bt_lockpage (BtLockWrite, sibling->latch);
1904 bt_unlockpage (BtLockAccess, sibling->latch);
1906 if( sibling->pool = bt_pinpool (bt, sibling->page_no) )
1907 sibling->page = bt_page (bt, sibling->pool, sibling->page_no);
1911 if( !sibling->page->kill )
1912 return bt_removeparent (bt, set, parent, sibling, rparent, lvl+1);
1916 bt_unlockpage (BtLockWrite, sibling->latch);
1917 bt_unpinlatch (sibling->latch);
1918 bt_unpinpool (sibling->pool);
1921 bt_unlockpage (BtLockWrite, set->latch);
1922 bt_unlockpage (BtLockWrite, rparent->latch);
1923 bt_unpinlatch (rparent->latch);
1924 bt_unpinpool (rparent->pool);
1926 bt_unlockpage (BtLockWrite, parent->latch);
1927 bt_unpinlatch (parent->latch);
1928 bt_unpinpool (parent->pool);
1937 // redirect parent to our left sibling
1938 // lock and map our left sibling's page
1940 sibling->page_no = bt_getid (slotptr(parent->page, idx)->id);
1941 sibling->latch = bt_pinlatch (bt, sibling->page_no);
1943 // wait our turn on fence key maintenance
1945 bt_lockpage(BtLockParent, sibling->latch);
1946 bt_lockpage(BtLockAccess, sibling->latch);
1947 bt_lockpage(BtLockWrite, sibling->latch);
1948 bt_unlockpage(BtLockAccess, sibling->latch);
1950 if( sibling->pool = bt_pinpool (bt, sibling->page_no) )
1951 sibling->page = bt_page (bt, sibling->pool, sibling->page_no);
1955 // wait until left sibling is in our parent
1957 if( bt_getid (sibling->page->right) != set->page_no ) {
1958 bt_unlockpage (BtLockWrite, parent->latch);
1959 bt_unlockpage (BtLockWrite, sibling->latch);
1960 bt_unlockpage (BtLockParent, sibling->latch);
1961 bt_unpinlatch (parent->latch);
1962 bt_unpinpool (parent->pool);
1963 bt_unpinlatch (sibling->latch);
1964 bt_unpinpool (sibling->pool);
1973 // delete our left sibling from parent
1975 slotptr(parent->page,idx)->dead = 1;
1976 parent->page->dirty = 1;
1977 parent->page->act--;
1979 // redirect our parent slot to our left sibling
1981 bt_putid (slotptr(parent->page, slot)->id, sibling->page_no);
1982 memcpy (sibling->page->right, set->page->right, BtId);
1984 // collapse dead slots from parent
1986 while( idx = parent->page->cnt - 1 )
1987 if( slotptr(parent->page, idx)->dead ) {
1988 *slotptr(parent->page, idx) = *slotptr(parent->page, parent->page->cnt);
1989 memset (slotptr(parent->page, parent->page->cnt--), 0, sizeof(BtSlot));
1993 // free our original page
1995 bt_lockpage (BtLockDelete, set->latch);
1996 bt_lockpage (BtLockWrite, set->latch);
1997 bt_freepage (bt, set);
1999 // go down the left node's fence keys to the leaf level
2000 // and update the fence keys in each page
2002 memcpy (newfence, parent->page->fence, 256);
2004 if( bt_fixfences (bt, sibling, newfence) )
2007 // promote sibling as new root?
2009 if( parent->page_no == ROOT_page && parent->page->cnt == 1 )
2010 if( sibling->page->lvl ) {
2011 sibling->latch = bt_pinlatch (bt, sibling->page_no);
2012 bt_lockpage (BtLockDelete, sibling->latch);
2013 bt_lockpage (BtLockWrite, sibling->latch);
2015 if( sibling->pool = bt_pinpool (bt, sibling->page_no) )
2016 sibling->page = bt_page (bt, sibling->pool, sibling->page_no);
2020 return bt_removeroot (bt, parent, sibling);
2023 bt_unlockpage (BtLockWrite, parent->latch);
2024 bt_unpinlatch (parent->latch);
2025 bt_unpinpool (parent->pool);
2031 // find and delete key on page by marking delete flag bit
2032 // if page becomes empty, delete it from the btree
2034 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len)
2036 unsigned char pagefence[256];
2037 uint slot, idx, found;
2041 if( slot = bt_loadpage (bt, set, key, len, 0, BtLockWrite) )
2042 ptr = keyptr(set->page, slot);
2046 // if key is found delete it, otherwise ignore request
2048 if( found = slot <= set->page->cnt )
2049 if( found = !keycmp (ptr, key, len) )
2050 if( found = slotptr(set->page, slot)->dead == 0 ) {
2051 slotptr(set->page,slot)->dead = 1;
2052 set->page->dirty = 1;
2055 // collapse empty slots
2057 while( idx = set->page->cnt - 1 )
2058 if( slotptr(set->page, idx)->dead ) {
2059 *slotptr(set->page, idx) = *slotptr(set->page, idx + 1);
2060 memset (slotptr(set->page, set->page->cnt--), 0, sizeof(BtSlot));
2065 if( set->page->act ) {
2066 bt_unlockpage(BtLockWrite, set->latch);
2067 bt_unpinlatch (set->latch);
2068 bt_unpinpool (set->pool);
2069 return bt->found = found, 0;
2072 memcpy (pagefence, set->page->fence, 256);
2073 set->page->kill = 1;
2075 bt_unlockpage (BtLockWrite, set->latch);
2077 if( bt_removepage (bt, set, 0, pagefence) )
2084 // find key in leaf level and return row-id
2086 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
2093 if( slot = bt_loadpage (bt, set, key, len, 0, BtLockRead) )
2094 ptr = keyptr(set->page, slot);
2098 // if key exists, return row-id
2099 // otherwise return 0
2101 if( slot <= set->page->cnt )
2102 if( !keycmp (ptr, key, len) )
2103 id = bt_getid(slotptr(set->page,slot)->id);
2105 bt_unlockpage (BtLockRead, set->latch);
2106 bt_unpinlatch (set->latch);
2107 bt_unpinpool (set->pool);
2111 // check page for space available,
2112 // clean if necessary and return
2113 // 0 - page needs splitting
2114 // >0 new slot value
2116 uint bt_cleanpage(BtDb *bt, BtPage page, uint amt, uint slot)
2118 uint nxt = bt->mgr->page_size, off;
2119 uint cnt = 0, idx = 0;
2120 uint max = page->cnt;
2124 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
2127 // skip cleanup if nothing to reclaim
2132 memcpy (bt->frame, page, bt->mgr->page_size);
2134 // skip page info and set rest of page to zero
2136 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
2140 // try cleaning up page first
2141 // by removing deleted keys
2143 while( cnt++ < max ) {
2146 if( slotptr(bt->frame,cnt)->dead )
2149 // if its not the fence key,
2150 // copy the key across
2152 off = slotptr(bt->frame,cnt)->off;
2154 if( off >= sizeof(*page) ) {
2155 key = keyptr(bt->frame, cnt);
2156 off = nxt -= key->len + 1;
2157 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2162 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
2163 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2164 slotptr(page, idx)->off = off;
2171 // see if page has enough space now, or does it need splitting?
2173 if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
2179 // split the root and raise the height of the btree
2181 BTERR bt_splitroot(BtDb *bt, BtPageSet *root, uid page_no2)
2183 uint nxt = bt->mgr->page_size;
2184 unsigned char leftkey[256];
2187 // Obtain an empty page to use, and copy the current
2188 // root contents into it, e.g. lower keys
2190 memcpy (leftkey, root->page->fence, 256);
2191 root->page->posted = 1;
2193 if( !(new_page = bt_newpage(bt, root->page)) )
2196 // preserve the page info at the bottom
2197 // of higher keys and set rest to zero
2199 memset(root->page+1, 0, bt->mgr->page_size - sizeof(*root->page));
2200 memset(root->page->fence, 0, 256);
2201 root->page->fence[0] = 2;
2202 root->page->fence[1] = 0xff;
2203 root->page->fence[2] = 0xff;
2205 // insert lower keys page fence key on newroot page
2207 nxt -= *leftkey + 1;
2208 memcpy ((unsigned char *)root->page + nxt, leftkey, *leftkey + 1);
2209 bt_putid(slotptr(root->page, 1)->id, new_page);
2210 slotptr(root->page, 1)->off = nxt;
2212 // insert stopper key on newroot page
2213 // and increase the root height
2215 bt_putid(slotptr(root->page, 2)->id, page_no2);
2216 slotptr(root->page, 2)->off = offsetof(struct BtPage_, fence);
2218 bt_putid(root->page->right, 0);
2219 root->page->min = nxt; // reset lowest used offset and key count
2220 root->page->cnt = 2;
2221 root->page->act = 2;
2224 // release and unpin root
2226 bt_unlockpage(BtLockWrite, root->latch);
2227 bt_unpinlatch (root->latch);
2228 bt_unpinpool (root->pool);
2232 // split already locked full node
2235 BTERR bt_splitpage (BtDb *bt, BtPageSet *set)
2237 uint cnt = 0, idx = 0, max, nxt = bt->mgr->page_size, off;
2238 unsigned char fencekey[256];
2239 uint lvl = set->page->lvl;
2243 // split higher half of keys to bt->frame
2245 memset (bt->frame, 0, bt->mgr->page_size);
2246 max = set->page->cnt;
2250 while( cnt++ < max ) {
2251 if( !lvl || cnt < max ) {
2252 key = keyptr(set->page, cnt);
2253 off = nxt -= key->len + 1;
2254 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
2256 off = offsetof(struct BtPage_, fence);
2258 memcpy(slotptr(bt->frame,++idx)->id, slotptr(set->page,cnt)->id, BtId);
2259 slotptr(bt->frame, idx)->tod = slotptr(set->page, cnt)->tod;
2260 slotptr(bt->frame, idx)->off = off;
2264 if( set->page_no == ROOT_page )
2265 bt->frame->posted = 1;
2267 memcpy (bt->frame->fence, set->page->fence, 256);
2268 bt->frame->bits = bt->mgr->page_bits;
2269 bt->frame->min = nxt;
2270 bt->frame->cnt = idx;
2271 bt->frame->lvl = lvl;
2275 if( set->page_no > ROOT_page )
2276 memcpy (bt->frame->right, set->page->right, BtId);
2278 // get new free page and write higher keys to it.
2280 if( !(right = bt_newpage(bt, bt->frame)) )
2283 // update lower keys to continue in old page
2285 memcpy (bt->frame, set->page, bt->mgr->page_size);
2286 memset (set->page+1, 0, bt->mgr->page_size - sizeof(*set->page));
2287 nxt = bt->mgr->page_size;
2288 set->page->posted = 0;
2289 set->page->dirty = 0;
2294 // assemble page of smaller keys
2296 while( cnt++ < max / 2 ) {
2297 key = keyptr(bt->frame, cnt);
2299 if( !lvl || cnt < max / 2 ) {
2300 off = nxt -= key->len + 1;
2301 memcpy ((unsigned char *)set->page + nxt, key, key->len + 1);
2303 off = offsetof(struct BtPage_, fence);
2305 memcpy(slotptr(set->page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
2306 slotptr(set->page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2307 slotptr(set->page, idx)->off = off;
2311 // install fence key for smaller key page
2313 memset(set->page->fence, 0, 256);
2314 memcpy(set->page->fence, key, key->len + 1);
2316 bt_putid(set->page->right, right);
2317 set->page->min = nxt;
2318 set->page->cnt = idx;
2320 // if current page is the root page, split it
2322 if( set->page_no == ROOT_page )
2323 return bt_splitroot (bt, set, right);
2325 bt_unlockpage (BtLockWrite, set->latch);
2327 // insert new fences in their parent pages
2330 bt_lockpage (BtLockParent, set->latch);
2331 bt_lockpage (BtLockWrite, set->latch);
2333 memcpy (fencekey, set->page->fence, 256);
2334 right = bt_getid (set->page->right);
2336 if( set->page->posted ) {
2337 bt_unlockpage (BtLockParent, set->latch);
2338 bt_unlockpage (BtLockWrite, set->latch);
2339 bt_unpinlatch (set->latch);
2340 bt_unpinpool (set->pool);
2344 set->page->posted = 1;
2345 bt_unlockpage (BtLockWrite, set->latch);
2347 if( bt_insertkey (bt, fencekey+1, *fencekey, set->page_no, time(NULL), lvl+1) )
2350 bt_unlockpage (BtLockParent, set->latch);
2351 bt_unpinlatch (set->latch);
2352 bt_unpinpool (set->pool);
2354 if( !(set->page_no = right) )
2357 set->latch = bt_pinlatch (bt, right);
2359 if( set->pool = bt_pinpool (bt, right) )
2360 set->page = bt_page (bt, set->pool, right);
2368 // Insert new key into the btree at given level.
2370 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod, uint lvl)
2377 if( slot = bt_loadpage (bt, set, key, len, lvl, BtLockWrite) )
2378 ptr = keyptr(set->page, slot);
2382 bt->err = BTERR_ovflw;
2386 // if key already exists, update id and return
2388 if( slot <= set->page->cnt )
2389 if( !keycmp (ptr, key, len) ) {
2390 if( slotptr(set->page, slot)->dead )
2392 slotptr(set->page, slot)->dead = 0;
2393 slotptr(set->page, slot)->tod = tod;
2394 bt_putid(slotptr(set->page,slot)->id, id);
2395 bt_unlockpage(BtLockWrite, set->latch);
2396 bt_unpinlatch (set->latch);
2397 bt_unpinpool (set->pool);
2401 // check if page has enough space
2403 if( slot = bt_cleanpage (bt, set->page, len, slot) )
2406 if( bt_splitpage (bt, set) )
2410 // calculate next available slot and copy key into page
2412 set->page->min -= len + 1; // reset lowest used offset
2413 ((unsigned char *)set->page)[set->page->min] = len;
2414 memcpy ((unsigned char *)set->page + set->page->min +1, key, len );
2416 for( idx = slot; idx <= set->page->cnt; idx++ )
2417 if( slotptr(set->page, idx)->dead )
2420 // now insert key into array before slot
2422 if( idx > set->page->cnt )
2428 *slotptr(set->page, idx) = *slotptr(set->page, idx -1), idx--;
2430 bt_putid(slotptr(set->page,slot)->id, id);
2431 slotptr(set->page, slot)->off = set->page->min;
2432 slotptr(set->page, slot)->tod = tod;
2433 slotptr(set->page, slot)->dead = 0;
2435 bt_unlockpage (BtLockWrite, set->latch);
2436 bt_unpinlatch (set->latch);
2437 bt_unpinpool (set->pool);
2441 // cache page of keys into cursor and return starting slot for given key
2443 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2448 // cache page for retrieval
2450 if( slot = bt_loadpage (bt, set, key, len, 0, BtLockRead) )
2451 memcpy (bt->cursor, set->page, bt->mgr->page_size);
2455 bt->cursor_page = set->page_no;
2457 bt_unlockpage(BtLockRead, set->latch);
2458 bt_unpinlatch (set->latch);
2459 bt_unpinpool (set->pool);
2463 // return next slot for cursor page
2464 // or slide cursor right into next page
2466 uint bt_nextkey (BtDb *bt, uint slot)
2472 right = bt_getid(bt->cursor->right);
2473 while( slot++ < bt->cursor->cnt )
2474 if( slotptr(bt->cursor,slot)->dead )
2476 else if( right || (slot < bt->cursor->cnt) ) // skip infinite stopper
2484 bt->cursor_page = right;
2486 if( set->pool = bt_pinpool (bt, right) )
2487 set->page = bt_page (bt, set->pool, right);
2491 set->latch = bt_pinlatch (bt, right);
2492 bt_lockpage(BtLockRead, set->latch);
2494 memcpy (bt->cursor, set->page, bt->mgr->page_size);
2496 bt_unlockpage(BtLockRead, set->latch);
2497 bt_unpinlatch (set->latch);
2498 bt_unpinpool (set->pool);
2505 BtKey bt_key(BtDb *bt, uint slot)
2507 return keyptr(bt->cursor, slot);
2510 uid bt_uid(BtDb *bt, uint slot)
2512 return bt_getid(slotptr(bt->cursor,slot)->id);
2515 uint bt_tod(BtDb *bt, uint slot)
2517 return slotptr(bt->cursor,slot)->tod;
2523 void bt_latchaudit (BtDb *bt)
2525 ushort idx, hashidx;
2532 for( idx = 1; idx < bt->mgr->latchmgr->latchdeployed; idx++ ) {
2533 latch = bt->mgr->latchsets + idx;
2534 if( *(uint *)latch->readwr ) {
2535 fprintf(stderr, "latchset %d r/w locked for page %.8x\n", idx, latch->page_no);
2536 *(uint *)latch->readwr = 0;
2538 if( *(uint *)latch->access ) {
2539 fprintf(stderr, "latchset %d access locked for page %.8x\n", idx, latch->page_no);
2540 *(uint *)latch->access = 0;
2542 if( *(uint *)latch->parent ) {
2543 fprintf(stderr, "latchset %d parent locked for page %.8x\n", idx, latch->page_no);
2544 *(uint *)latch->parent = 0;
2546 if( *(uint *)latch->busy ) {
2547 fprintf(stderr, "latchset %d busy locked for page %.8x\n", idx, latch->page_no);
2548 *(uint *)latch->parent = 0;
2551 fprintf(stderr, "latchset %d pinned for page %.8x\n", idx, latch->page_no);
2556 for( hashidx = 0; hashidx < bt->mgr->latchmgr->latchhash; hashidx++ ) {
2557 if( idx = bt->mgr->latchmgr->table[hashidx].slot ) do {
2558 latch = bt->mgr->latchsets + idx;
2559 if( latch->hash != hashidx ) {
2560 fprintf(stderr, "latchset %d wrong hashidx\n", idx);
2561 latch->hash = hashidx;
2563 } while( idx = latch->next );
2566 page_no = bt_getid(bt->mgr->latchmgr->alloc[1].right);
2569 fprintf(stderr, "free: %.6x\n", (uint)page_no);
2571 if( pool = bt_pinpool (bt, page_no) )
2572 page = bt_page (bt, pool, page_no);
2576 page_no = bt_getid(page->right);
2577 bt_unpinpool (pool);
2589 // standalone program to index file of keys
2590 // then list them onto std-out
2593 void *index_file (void *arg)
2595 uint __stdcall index_file (void *arg)
2598 int line = 0, found = 0, cnt = 0;
2599 uid next, page_no = LEAF_page; // start on first page of leaves
2600 unsigned char key[256];
2601 ThreadArg *args = arg;
2602 int ch, len = 0, slot;
2609 bt = bt_open (args->mgr);
2612 switch(args->type | 0x20)
2615 fprintf(stderr, "started latch mgr audit\n");
2617 fprintf(stderr, "finished latch mgr audit\n");
2621 fprintf(stderr, "started indexing for %s\n", args->infile);
2622 if( in = fopen (args->infile, "rb") )
2623 while( ch = getc(in), ch != EOF )
2628 if( args->num == 1 )
2629 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2631 else if( args->num )
2632 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2634 if( bt_insertkey (bt, key, len, line, *tod, 0) )
2635 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2638 else if( len < 255 )
2640 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
2644 fprintf(stderr, "started deleting keys for %s\n", args->infile);
2645 if( in = fopen (args->infile, "rb") )
2646 while( ch = getc(in), ch != EOF )
2650 if( args->num == 1 )
2651 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2653 else if( args->num )
2654 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2656 if( bt_deletekey (bt, key, len) )
2657 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2660 else if( len < 255 )
2662 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2666 fprintf(stderr, "started finding keys for %s\n", args->infile);
2667 if( in = fopen (args->infile, "rb") )
2668 while( ch = getc(in), ch != EOF )
2672 if( args->num == 1 )
2673 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2675 else if( args->num )
2676 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2678 if( bt_findkey (bt, key, len) )
2681 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2684 else if( len < 255 )
2686 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2690 fprintf(stderr, "started scanning\n");
2692 if( set->pool = bt_pinpool (bt, page_no) )
2693 set->page = bt_page (bt, set->pool, page_no);
2696 set->latch = bt_pinlatch (bt, page_no);
2697 bt_lockpage (BtLockRead, set->latch);
2698 next = bt_getid (set->page->right);
2699 cnt += set->page->act;
2701 for( slot = 0; slot++ < set->page->cnt; )
2702 if( next || slot < set->page->cnt )
2703 if( !slotptr(set->page, slot)->dead ) {
2704 ptr = keyptr(set->page, slot);
2705 fwrite (ptr->key, ptr->len, 1, stdout);
2706 fputc ('\n', stdout);
2709 bt_unlockpage (BtLockRead, set->latch);
2710 bt_unpinlatch (set->latch);
2711 bt_unpinpool (set->pool);
2712 } while( page_no = next );
2714 cnt--; // remove stopper key
2715 fprintf(stderr, " Total keys read %d\n", cnt);
2719 fprintf(stderr, "started counting\n");
2720 next = bt->mgr->latchmgr->nlatchpage + LATCH_page;
2721 page_no = LEAF_page;
2723 while( page_no < bt_getid(bt->mgr->latchmgr->alloc->right) ) {
2724 pread (bt->mgr->idx, bt->frame, bt->mgr->page_size, page_no << bt->mgr->page_bits);
2725 if( !bt->frame->free && !bt->frame->lvl )
2726 cnt += bt->frame->act;
2727 if( page_no > LEAF_page )
2732 cnt--; // remove stopper key
2733 fprintf(stderr, " Total keys read %d\n", cnt);
2745 typedef struct timeval timer;
2747 int main (int argc, char **argv)
2749 int idx, cnt, len, slot, err;
2750 int segsize, bits = 16;
2755 time_t start[1], stop[1];
2768 fprintf (stderr, "Usage: %s idx_file Read/Write/Scan/Delete/Find [page_bits mapped_segments seg_bits line_numbers src_file1 src_file2 ... ]\n", argv[0]);
2769 fprintf (stderr, " where page_bits is the page size in bits\n");
2770 fprintf (stderr, " mapped_segments is the number of mmap segments in buffer pool\n");
2771 fprintf (stderr, " seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2772 fprintf (stderr, " line_numbers = 1 to append line numbers to keys\n");
2773 fprintf (stderr, " src_file1 thru src_filen are files of keys separated by newline\n");
2778 gettimeofday(&start, NULL);
2784 bits = atoi(argv[3]);
2787 poolsize = atoi(argv[4]);
2790 fprintf (stderr, "Warning: no mapped_pool\n");
2792 if( poolsize > 65535 )
2793 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2796 segsize = atoi(argv[5]);
2798 segsize = 4; // 16 pages per mmap segment
2801 num = atoi(argv[6]);
2805 threads = malloc (cnt * sizeof(pthread_t));
2807 threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2809 args = malloc (cnt * sizeof(ThreadArg));
2811 mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2814 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2820 for( idx = 0; idx < cnt; idx++ ) {
2821 args[idx].infile = argv[idx + 7];
2822 args[idx].type = argv[2][0];
2823 args[idx].mgr = mgr;
2824 args[idx].num = num;
2825 args[idx].idx = idx;
2827 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2828 fprintf(stderr, "Error creating thread %d\n", err);
2830 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2834 // wait for termination
2837 for( idx = 0; idx < cnt; idx++ )
2838 pthread_join (threads[idx], NULL);
2839 gettimeofday(&stop, NULL);
2840 real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2842 WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2844 for( idx = 0; idx < cnt; idx++ )
2845 CloseHandle(threads[idx]);
2848 real_time = 1000 * (*stop - *start);
2850 fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);