1 // btree version threads2h pthread rw lock version
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
41 #define WIN32_LEAN_AND_MEAN
55 typedef unsigned long long uid;
58 typedef unsigned long long off64_t;
59 typedef unsigned short ushort;
60 typedef unsigned int uint;
63 #define BT_latchtable 128 // number of latch manager slots
65 #define BT_ro 0x6f72 // ro
66 #define BT_rw 0x7772 // rw
68 #define BT_maxbits 24 // maximum page size in bits
69 #define BT_minbits 9 // minimum page size in bits
70 #define BT_minpage (1 << BT_minbits) // minimum page size
71 #define BT_maxpage (1 << BT_maxbits) // maximum page size
74 There are five lock types for each node in three independent sets:
75 1. (set 1) AccessIntent: Sharable. Going to Read the node. Incompatible with NodeDelete.
76 2. (set 1) NodeDelete: Exclusive. About to release the node. Incompatible with AccessIntent.
77 3. (set 2) ReadLock: Sharable. Read the node. Incompatible with WriteLock.
78 4. (set 2) WriteLock: Exclusive. Modify the node. Incompatible with ReadLock and other WriteLocks.
79 5. (set 3) ParentModification: Exclusive. Change the node's parent keys. Incompatible with another ParentModification.
90 // mode & definition for latch implementation
99 // exclusive is set for write access
100 // share is count of read accessors
101 // grant write lock when share == 0
104 volatile ushort mutex:1;
105 volatile ushort exclusive:1;
106 volatile ushort pending:1;
107 volatile ushort share:13;
110 // hash table entries
113 BtSpinLatch latch[1];
114 volatile ushort slot; // Latch table entry at head of chain
117 // latch manager table structure
121 pthread_rwlock_t lock[1];
128 BtLatch readwr[1]; // read/write page lock
129 BtLatch access[1]; // Access Intent/Page delete
130 BtLatch parent[1]; // Posting of fence key in parent
131 BtSpinLatch busy[1]; // slot is being moved between chains
132 volatile ushort next; // next entry in hash table chain
133 volatile ushort prev; // prev entry in hash table chain
134 volatile ushort pin; // number of outstanding locks
135 volatile ushort hash; // hash slot entry is under
136 volatile uid page_no; // latch set page number
139 // Define the length of the page and key pointers
143 // Page key slot definition.
145 // If BT_maxbits is 15 or less, you can save 4 bytes
146 // for each key stored by making the first two uints
147 // into ushorts. You can also save 4 bytes by removing
148 // the tod field from the key.
150 // Keys are marked dead, but remain on the page until
151 // it cleanup is called. The fence key (highest key) for
152 // the page is always present, even after cleanup.
155 uint off:BT_maxbits; // page offset for key start
156 uint dead:1; // set for deleted key
157 uint tod; // time-stamp for key
158 unsigned char id[BtId]; // id associated with key
161 // The key structure occupies space at the upper end of
162 // each page. It's a length byte followed by the value
167 unsigned char key[1];
170 // The first part of an index page.
171 // It is immediately followed
172 // by the BtSlot array of keys.
174 typedef struct BtPage_ {
175 uint cnt; // count of keys in page
176 uint act; // count of active keys
177 uint min; // next key offset
178 unsigned char bits:7; // page size in bits
179 unsigned char free:1; // page is on free list
180 unsigned char lvl:4; // level of page
181 unsigned char kill:1; // page is being killed
182 unsigned char dirty:1; // page has deleted keys
183 unsigned char posted:1; // page fence is posted
184 unsigned char goright:1; // page is being killed, continue to right
185 unsigned char right[BtId]; // page number to right
186 unsigned char fence[256]; // page fence key
189 // The memory mapping pool table buffer manager entry
192 unsigned long long int lru; // number of times accessed
193 uid basepage; // mapped base page number
194 char *map; // mapped memory pointer
195 ushort slot; // slot index in this array
196 ushort pin; // mapped page pin counter
197 void *hashprev; // previous pool entry for the same hash idx
198 void *hashnext; // next pool entry for the same hash idx
200 HANDLE hmap; // Windows memory mapping handle
204 // The loadpage interface object
207 uid page_no; // current page number
208 BtPage page; // current page pointer
209 BtPool *pool; // current page pool
210 BtLatchSet *latch; // current page latch set
213 // structure for latch manager on ALLOC_page
216 struct BtPage_ alloc[2]; // next & free page_nos in right ptr
217 BtSpinLatch lock[1]; // allocation area lite latch
218 ushort latchdeployed; // highest number of latch entries deployed
219 ushort nlatchpage; // number of latch pages at BT_latch
220 ushort latchtotal; // number of page latch entries
221 ushort latchhash; // number of latch hash table slots
222 ushort latchvictim; // next latch entry to examine
223 BtHashEntry table[0]; // the hash table
226 // The object structure for Btree access
229 uint page_size; // page size
230 uint page_bits; // page size in bits
231 uint seg_bits; // seg size in pages in bits
232 uint mode; // read-write mode
238 ushort poolcnt; // highest page pool node in use
239 ushort poolmax; // highest page pool node allocated
240 ushort poolmask; // total number of pages in mmap segment - 1
241 ushort hashsize; // size of Hash Table for pool entries
242 volatile uint evicted; // last evicted hash table slot
243 ushort *hash; // pool index for hash entries
244 BtSpinLatch *latch; // latches for hash table slots
245 BtLatchMgr *latchmgr; // mapped latch page from allocation page
246 BtLatchSet *latchsets; // mapped latch set from latch pages
247 BtPool *pool; // memory pool page segments
249 HANDLE halloc; // allocation and latch table handle
254 BtMgr *mgr; // buffer manager for thread
255 BtPage cursor; // cached frame for start/next (never mapped)
256 BtPage frame; // spare frame for the page split (never mapped)
257 BtPage zero; // page frame for zeroes at end of file
258 uid cursor_page; // current cursor page number
259 unsigned char *mem; // frame, cursor, page memory buffer
260 int found; // last delete or insert was found
261 int err; // last error
275 extern void bt_close (BtDb *bt);
276 extern BtDb *bt_open (BtMgr *mgr);
277 extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod, uint lvl);
278 extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len);
279 extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
280 extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
281 extern uint bt_nextkey (BtDb *bt, uint slot);
283 // internal functions
284 BTERR bt_removepage (BtDb *bt, BtPageSet *set, uint lvl, unsigned char *pagefence);
287 extern BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolsize, uint segsize, uint hashsize);
288 void bt_mgrclose (BtMgr *mgr);
290 // Helper functions to return slot values
292 extern BtKey bt_key (BtDb *bt, uint slot);
293 extern uid bt_uid (BtDb *bt, uint slot);
294 extern uint bt_tod (BtDb *bt, uint slot);
296 // BTree page number constants
297 #define ALLOC_page 0 // allocation & lock manager hash table
298 #define ROOT_page 1 // root of the btree
299 #define LEAF_page 2 // first page of leaves
300 #define LATCH_page 3 // pages for lock manager
302 // Number of levels to create in a new BTree
306 // The page is allocated from low and hi ends.
307 // The key offsets and row-id's are allocated
308 // from the bottom, while the text of the key
309 // is allocated from the top. When the two
310 // areas meet, the page is split into two.
312 // A key consists of a length byte, two bytes of
313 // index number (0 - 65534), and up to 253 bytes
314 // of key value. Duplicate keys are discarded.
315 // Associated with each key is a 48 bit row-id.
317 // The b-tree root is always located at page 1.
318 // The first leaf page of level zero is always
319 // located on page 2.
321 // The b-tree pages are linked with next
322 // pointers to facilitate enumerators,
323 // and provide for concurrency.
325 // When to root page fills, it is split in two and
326 // the tree height is raised by a new root at page
327 // one with two keys.
329 // Deleted keys are marked with a dead bit until
330 // page cleanup The fence key for a node is
331 // present in a special array.
333 // Groups of pages called segments from the btree are optionally
334 // cached with a memory mapped pool. A hash table is used to keep
335 // track of the cached segments. This behaviour is controlled
336 // by the cache block size parameter to bt_open.
338 // To achieve maximum concurrency one page is locked at a time
339 // as the tree is traversed to find leaf key in question. The right
340 // page numbers are used in cases where the page is being split,
343 // Page 0 is dedicated to lock for new page extensions,
344 // and chains empty pages together for reuse.
346 // The ParentModification lock on a node is obtained to serialize posting
347 // or changing the fence key for a node.
349 // Empty pages are chained together through the ALLOC page and reused.
351 // Access macros to address slot and key values from the page.
352 // Page slots use 1 based indexing.
354 #define slotptr(page, slot) (((BtSlot *)(page+1)) + (slot-1))
355 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
357 void bt_putid(unsigned char *dest, uid id)
362 dest[i] = (unsigned char)id, id >>= 8;
365 uid bt_getid(unsigned char *src)
370 for( i = 0; i < BtId; i++ )
371 id <<= 8, id |= *src++;
378 // wait until write lock mode is clear
379 // and add 1 to the share count
381 void bt_spinreadlock(BtSpinLatch *latch)
386 // obtain latch mutex
388 if( __sync_fetch_and_or((ushort *)latch, Mutex) & Mutex )
391 if( prev = _InterlockedOr16((ushort *)latch, Mutex) & Mutex )
394 // see if exclusive request is granted or pending
396 if( prev = !(latch->exclusive | latch->pending) )
398 __sync_fetch_and_add((ushort *)latch, Share);
400 _InterlockedExchangeAdd16 ((ushort *)latch, Share);
404 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
406 _InterlockedAnd16((ushort *)latch, ~Mutex);
412 } while( sched_yield(), 1 );
414 } while( SwitchToThread(), 1 );
418 // wait for other read and write latches to relinquish
420 void bt_spinwritelock(BtSpinLatch *latch)
424 if( __sync_fetch_and_or((ushort *)latch, Mutex | Pending) & Mutex )
427 if( _InterlockedOr16((ushort *)latch, Mutex | Pending) & Mutex )
430 if( !(latch->share | latch->exclusive) ) {
432 __sync_fetch_and_or((ushort *)latch, Write);
433 __sync_fetch_and_and ((ushort *)latch, ~(Mutex | Pending));
435 _InterlockedOr16((ushort *)latch, Write);
436 _InterlockedAnd16((ushort *)latch, ~(Mutex | Pending));
442 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
444 _InterlockedAnd16((ushort *)latch, ~Mutex);
448 } while( sched_yield(), 1 );
450 } while( SwitchToThread(), 1 );
454 // try to obtain write lock
456 // return 1 if obtained,
459 int bt_spinwritetry(BtSpinLatch *latch)
464 if( prev = __sync_fetch_and_or((ushort *)latch, Mutex), prev & Mutex )
467 if( prev = _InterlockedOr16((ushort *)latch, Mutex), prev & Mutex )
470 // take write access if all bits are clear
474 __sync_fetch_and_or ((ushort *)latch, Write);
476 _InterlockedOr16((ushort *)latch, Write);
480 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
482 _InterlockedAnd16((ushort *)latch, ~Mutex);
489 void bt_spinreleasewrite(BtSpinLatch *latch)
492 __sync_fetch_and_and ((ushort *)latch, ~Write);
494 _InterlockedAnd16((ushort *)latch, ~Write);
498 // decrement reader count
500 void bt_spinreleaseread(BtSpinLatch *latch)
503 __sync_fetch_and_add((ushort *)latch, -Share);
505 _InterlockedExchangeAdd16 ((ushort *)latch, -Share);
509 void bt_readlock(BtLatch *latch)
512 pthread_rwlock_rdlock (latch->lock);
514 AcquireSRWLockShared (latch->srw);
518 // wait for other read and write latches to relinquish
520 void bt_writelock(BtLatch *latch)
523 pthread_rwlock_wrlock (latch->lock);
525 AcquireSRWLockExclusive (latch->srw);
529 // try to obtain write lock
531 // return 1 if obtained,
532 // 0 if already write or read locked
534 int bt_writetry(BtLatch *latch)
539 result = !pthread_rwlock_trywrlock (latch->lock);
541 result = TryAcquireSRWLockExclusive (latch->srw);
548 void bt_releasewrite(BtLatch *latch)
551 pthread_rwlock_unlock (latch->lock);
553 ReleaseSRWLockExclusive (latch->srw);
557 // decrement reader count
559 void bt_releaseread(BtLatch *latch)
562 pthread_rwlock_unlock (latch->lock);
564 ReleaseSRWLockShared (latch->srw);
568 void bt_initlockset (BtLatchSet *set)
571 pthread_rwlockattr_t rwattr[1];
573 pthread_rwlockattr_init (rwattr);
574 pthread_rwlockattr_setpshared (rwattr, PTHREAD_PROCESS_SHARED);
576 pthread_rwlock_init (set->readwr->lock, rwattr);
577 pthread_rwlock_init (set->access->lock, rwattr);
578 pthread_rwlock_init (set->parent->lock, rwattr);
579 pthread_rwlockattr_destroy (rwattr);
581 InitializeSRWLock (set->readwr->srw);
582 InitializeSRWLock (set->access->srw);
583 InitializeSRWLock (set->parent->srw);
587 // link latch table entry into latch hash table
589 void bt_latchlink (BtDb *bt, ushort hashidx, ushort victim, uid page_no)
591 BtLatchSet *set = bt->mgr->latchsets + victim;
593 if( set->next = bt->mgr->latchmgr->table[hashidx].slot )
594 bt->mgr->latchsets[set->next].prev = victim;
596 bt->mgr->latchmgr->table[hashidx].slot = victim;
597 set->page_no = page_no;
604 void bt_unpinlatch (BtLatchSet *set)
607 __sync_fetch_and_add(&set->pin, -1);
609 _InterlockedDecrement16 (&set->pin);
613 // find existing latchset or inspire new one
614 // return with latchset pinned
616 BtLatchSet *bt_pinlatch (BtDb *bt, uid page_no)
618 ushort hashidx = page_no % bt->mgr->latchmgr->latchhash;
619 ushort slot, avail = 0, victim, idx;
622 // obtain read lock on hash table entry
624 bt_spinreadlock(bt->mgr->latchmgr->table[hashidx].latch);
626 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
628 set = bt->mgr->latchsets + slot;
629 if( page_no == set->page_no )
631 } while( slot = set->next );
635 __sync_fetch_and_add(&set->pin, 1);
637 _InterlockedIncrement16 (&set->pin);
641 bt_spinreleaseread (bt->mgr->latchmgr->table[hashidx].latch);
646 // try again, this time with write lock
648 bt_spinwritelock(bt->mgr->latchmgr->table[hashidx].latch);
650 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
652 set = bt->mgr->latchsets + slot;
653 if( page_no == set->page_no )
655 if( !set->pin && !avail )
657 } while( slot = set->next );
659 // found our entry, or take over an unpinned one
661 if( slot || (slot = avail) ) {
662 set = bt->mgr->latchsets + slot;
664 __sync_fetch_and_add(&set->pin, 1);
666 _InterlockedIncrement16 (&set->pin);
668 set->page_no = page_no;
669 bt_spinreleasewrite(bt->mgr->latchmgr->table[hashidx].latch);
673 // see if there are any unused entries
675 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, 1) + 1;
677 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchdeployed);
680 if( victim < bt->mgr->latchmgr->latchtotal ) {
681 set = bt->mgr->latchsets + victim;
683 __sync_fetch_and_add(&set->pin, 1);
685 _InterlockedIncrement16 (&set->pin);
687 bt_initlockset (set);
688 bt_latchlink (bt, hashidx, victim, page_no);
689 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
694 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, -1);
696 victim = _InterlockedDecrement16 (&bt->mgr->latchmgr->latchdeployed);
698 // find and reuse previous lock entry
702 victim = __sync_fetch_and_add(&bt->mgr->latchmgr->latchvictim, 1);
704 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchvictim) - 1;
706 // we don't use slot zero
708 if( victim %= bt->mgr->latchmgr->latchtotal )
709 set = bt->mgr->latchsets + victim;
713 // take control of our slot
714 // from other threads
716 if( set->pin || !bt_spinwritetry (set->busy) )
721 // try to get write lock on hash chain
722 // skip entry if not obtained
723 // or has outstanding locks
725 if( !bt_spinwritetry (bt->mgr->latchmgr->table[idx].latch) ) {
726 bt_spinreleasewrite (set->busy);
731 bt_spinreleasewrite (set->busy);
732 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
736 // unlink our available victim from its hash chain
739 bt->mgr->latchsets[set->prev].next = set->next;
741 bt->mgr->latchmgr->table[idx].slot = set->next;
744 bt->mgr->latchsets[set->next].prev = set->prev;
746 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
748 __sync_fetch_and_add(&set->pin, 1);
750 _InterlockedIncrement16 (&set->pin);
752 bt_latchlink (bt, hashidx, victim, page_no);
753 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
754 bt_spinreleasewrite (set->busy);
759 void bt_mgrclose (BtMgr *mgr)
764 // release mapped pages
765 // note that slot zero is never used
767 for( slot = 1; slot < mgr->poolmax; slot++ ) {
768 pool = mgr->pool + slot;
771 munmap (pool->map, (mgr->poolmask+1) << mgr->page_bits);
774 FlushViewOfFile(pool->map, 0);
775 UnmapViewOfFile(pool->map);
776 CloseHandle(pool->hmap);
782 munmap (mgr->latchsets, mgr->latchmgr->nlatchpage * mgr->page_size);
783 munmap (mgr->latchmgr, mgr->page_size);
785 FlushViewOfFile(mgr->latchmgr, 0);
786 UnmapViewOfFile(mgr->latchmgr);
787 CloseHandle(mgr->halloc);
796 FlushFileBuffers(mgr->idx);
797 CloseHandle(mgr->idx);
798 GlobalFree (mgr->pool);
799 GlobalFree (mgr->hash);
800 GlobalFree (mgr->latch);
805 // close and release memory
807 void bt_close (BtDb *bt)
814 VirtualFree (bt->mem, 0, MEM_RELEASE);
819 // open/create new btree buffer manager
821 // call with file_name, BT_openmode, bits in page size (e.g. 16),
822 // size of mapped page pool (e.g. 8192)
824 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
826 uint lvl, attr, cacheblk, last, slot, idx;
827 uint nlatchpage, latchhash;
828 BtLatchMgr *latchmgr;
835 SYSTEM_INFO sysinfo[1];
838 // determine sanity of page size and buffer pool
840 if( bits > BT_maxbits )
842 else if( bits < BT_minbits )
846 return NULL; // must have buffer pool
849 mgr = calloc (1, sizeof(BtMgr));
851 mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
854 return free(mgr), NULL;
856 cacheblk = 4096; // minimum mmap segment size for unix
859 mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
860 attr = FILE_ATTRIBUTE_NORMAL;
861 mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
863 if( mgr->idx == INVALID_HANDLE_VALUE )
864 return GlobalFree(mgr), NULL;
866 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
867 GetSystemInfo(sysinfo);
868 cacheblk = sysinfo->dwAllocationGranularity;
872 latchmgr = malloc (BT_maxpage);
875 // read minimum page size to get root info
877 if( size = lseek (mgr->idx, 0L, 2) ) {
878 if( pread(mgr->idx, latchmgr, BT_minpage, 0) == BT_minpage )
879 bits = latchmgr->alloc->bits;
881 return free(mgr), free(latchmgr), NULL;
882 } else if( mode == BT_ro )
883 return free(latchmgr), bt_mgrclose (mgr), NULL;
885 latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
886 size = GetFileSize(mgr->idx, amt);
889 if( !ReadFile(mgr->idx, (char *)latchmgr, BT_minpage, amt, NULL) )
890 return bt_mgrclose (mgr), NULL;
891 bits = latchmgr->alloc->bits;
892 } else if( mode == BT_ro )
893 return bt_mgrclose (mgr), NULL;
896 mgr->page_size = 1 << bits;
897 mgr->page_bits = bits;
899 mgr->poolmax = poolmax;
902 if( cacheblk < mgr->page_size )
903 cacheblk = mgr->page_size;
905 // mask for partial memmaps
907 mgr->poolmask = (cacheblk >> bits) - 1;
909 // see if requested size of pages per memmap is greater
911 if( (1 << segsize) > mgr->poolmask )
912 mgr->poolmask = (1 << segsize) - 1;
916 while( (1 << mgr->seg_bits) <= mgr->poolmask )
919 mgr->hashsize = hashsize;
922 mgr->pool = calloc (poolmax, sizeof(BtPool));
923 mgr->hash = calloc (hashsize, sizeof(ushort));
924 mgr->latch = calloc (hashsize, sizeof(BtSpinLatch));
926 mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * sizeof(BtPool));
927 mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
928 mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtSpinLatch));
934 // initialize an empty b-tree with latch page, root page, page of leaves
935 // and page(s) of latches
937 memset (latchmgr, 0, 1 << bits);
938 nlatchpage = BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1;
939 bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
940 latchmgr->alloc->bits = mgr->page_bits;
942 latchmgr->nlatchpage = nlatchpage;
943 latchmgr->latchtotal = nlatchpage * (mgr->page_size / sizeof(BtLatchSet));
945 // initialize latch manager
947 latchhash = (mgr->page_size - sizeof(BtLatchMgr)) / sizeof(BtHashEntry);
949 // size of hash table = total number of latchsets
951 if( latchhash > latchmgr->latchtotal )
952 latchhash = latchmgr->latchtotal;
954 latchmgr->latchhash = latchhash;
957 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
958 return bt_mgrclose (mgr), NULL;
960 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
961 return bt_mgrclose (mgr), NULL;
963 if( *amt < mgr->page_size )
964 return bt_mgrclose (mgr), NULL;
967 memset (latchmgr, 0, 1 << bits);
968 latchmgr->alloc->bits = mgr->page_bits;
970 for( lvl=MIN_lvl; lvl--; ) {
971 slotptr(latchmgr->alloc, 1)->off = offsetof(struct BtPage_, fence);
972 bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
973 latchmgr->alloc->fence[0] = 2;
974 latchmgr->alloc->fence[1] = 0xff;
975 latchmgr->alloc->fence[2] = 0xff;
976 latchmgr->alloc->min = mgr->page_size;
977 latchmgr->alloc->lvl = lvl;
978 latchmgr->alloc->cnt = 1;
979 latchmgr->alloc->act = 1;
981 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
982 return bt_mgrclose (mgr), NULL;
984 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
985 return bt_mgrclose (mgr), NULL;
987 if( *amt < mgr->page_size )
988 return bt_mgrclose (mgr), NULL;
992 // clear out latch manager locks
993 // and rest of pages to round out segment
995 memset(latchmgr, 0, mgr->page_size);
998 while( last <= ((MIN_lvl + 1 + nlatchpage) | mgr->poolmask) ) {
1000 pwrite(mgr->idx, latchmgr, mgr->page_size, last << mgr->page_bits);
1002 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
1003 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
1004 return bt_mgrclose (mgr), NULL;
1005 if( *amt < mgr->page_size )
1006 return bt_mgrclose (mgr), NULL;
1013 flag = PROT_READ | PROT_WRITE;
1014 mgr->latchmgr = mmap (0, mgr->page_size, flag, MAP_SHARED, mgr->idx, ALLOC_page * mgr->page_size);
1015 if( mgr->latchmgr == MAP_FAILED )
1016 return bt_mgrclose (mgr), NULL;
1017 mgr->latchsets = (BtLatchSet *)mmap (0, mgr->latchmgr->nlatchpage * mgr->page_size, flag, MAP_SHARED, mgr->idx, LATCH_page * mgr->page_size);
1018 if( mgr->latchsets == MAP_FAILED )
1019 return bt_mgrclose (mgr), NULL;
1021 flag = PAGE_READWRITE;
1022 mgr->halloc = CreateFileMapping(mgr->idx, NULL, flag, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size, NULL);
1024 return bt_mgrclose (mgr), NULL;
1026 flag = FILE_MAP_WRITE;
1027 mgr->latchmgr = MapViewOfFile(mgr->halloc, flag, 0, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size);
1028 if( !mgr->latchmgr )
1029 return GetLastError(), bt_mgrclose (mgr), NULL;
1031 mgr->latchsets = (void *)((char *)mgr->latchmgr + LATCH_page * mgr->page_size);
1037 VirtualFree (latchmgr, 0, MEM_RELEASE);
1042 // open BTree access method
1043 // based on buffer manager
1045 BtDb *bt_open (BtMgr *mgr)
1047 BtDb *bt = malloc (sizeof(*bt));
1049 memset (bt, 0, sizeof(*bt));
1052 bt->mem = malloc (3 *mgr->page_size);
1054 bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
1056 bt->frame = (BtPage)bt->mem;
1057 bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
1058 bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
1060 memset (bt->zero, 0, mgr->page_size);
1064 // compare two keys, returning > 0, = 0, or < 0
1065 // as the comparison value
1067 int keycmp (BtKey key1, unsigned char *key2, uint len2)
1069 uint len1 = key1->len;
1072 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
1085 // find segment in pool
1086 // must be called with hashslot idx locked
1087 // return NULL if not there
1088 // otherwise return node
1090 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
1095 // compute start of hash chain in pool
1097 if( slot = bt->mgr->hash[idx] )
1098 pool = bt->mgr->pool + slot;
1102 page_no &= ~bt->mgr->poolmask;
1104 while( pool->basepage != page_no )
1105 if( pool = pool->hashnext )
1113 // add segment to hash table
1115 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
1120 pool->hashprev = pool->hashnext = NULL;
1121 pool->basepage = page_no & ~bt->mgr->poolmask;
1124 if( slot = bt->mgr->hash[idx] ) {
1125 node = bt->mgr->pool + slot;
1126 pool->hashnext = node;
1127 node->hashprev = pool;
1130 bt->mgr->hash[idx] = pool->slot;
1133 // find best segment to evict from buffer pool
1135 BtPool *bt_findlru (BtDb *bt, uint hashslot)
1137 unsigned long long int target = ~0LL;
1138 BtPool *pool = NULL, *node;
1143 node = bt->mgr->pool + hashslot;
1145 // scan pool entries under hash table slot
1150 if( node->lru > target )
1154 } while( node = node->hashnext );
1159 // map new buffer pool segment to virtual memory
1161 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
1163 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
1164 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
1168 flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
1169 pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED | MAP_POPULATE, bt->mgr->idx, off);
1170 if( pool->map == MAP_FAILED )
1171 return bt->err = BTERR_map;
1173 flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
1174 pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
1176 return bt->err = BTERR_map;
1178 flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
1179 pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1181 return bt->err = BTERR_map;
1186 // calculate page within pool
1188 BtPage bt_page (BtDb *bt, BtPool *pool, uid page_no)
1190 uint subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1193 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1199 void bt_unpinpool (BtPool *pool)
1202 __sync_fetch_and_add(&pool->pin, -1);
1204 _InterlockedDecrement16 (&pool->pin);
1208 // find or place requested page in segment-pool
1209 // return pool table entry, incrementing pin
1211 BtPool *bt_pinpool(BtDb *bt, uid page_no)
1213 BtPool *pool, *node, *next;
1214 uint slot, idx, victim;
1216 // lock hash table chain
1218 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1219 bt_spinreadlock (&bt->mgr->latch[idx]);
1221 // look up in hash table
1223 if( pool = bt_findpool(bt, page_no, idx) ) {
1225 __sync_fetch_and_add(&pool->pin, 1);
1227 _InterlockedIncrement16 (&pool->pin);
1229 bt_spinreleaseread (&bt->mgr->latch[idx]);
1234 // upgrade to write lock
1236 bt_spinreleaseread (&bt->mgr->latch[idx]);
1237 bt_spinwritelock (&bt->mgr->latch[idx]);
1239 // try to find page in pool with write lock
1241 if( pool = bt_findpool(bt, page_no, idx) ) {
1243 __sync_fetch_and_add(&pool->pin, 1);
1245 _InterlockedIncrement16 (&pool->pin);
1247 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1252 // allocate a new pool node
1253 // and add to hash table
1256 slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
1258 slot = _InterlockedIncrement16 (&bt->mgr->poolcnt) - 1;
1261 if( ++slot < bt->mgr->poolmax ) {
1262 pool = bt->mgr->pool + slot;
1265 if( bt_mapsegment(bt, pool, page_no) )
1268 bt_linkhash(bt, pool, page_no, idx);
1270 __sync_fetch_and_add(&pool->pin, 1);
1272 _InterlockedIncrement16 (&pool->pin);
1274 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1278 // pool table is full
1279 // find best pool entry to evict
1282 __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
1284 _InterlockedDecrement16 (&bt->mgr->poolcnt);
1289 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
1291 victim = _InterlockedIncrement (&bt->mgr->evicted) - 1;
1293 victim %= bt->mgr->hashsize;
1295 // try to get write lock
1296 // skip entry if not obtained
1298 if( !bt_spinwritetry (&bt->mgr->latch[victim]) )
1301 // if pool entry is empty
1302 // or any pages are pinned
1305 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
1306 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1310 // unlink victim pool node from hash table
1312 if( node = pool->hashprev )
1313 node->hashnext = pool->hashnext;
1314 else if( node = pool->hashnext )
1315 bt->mgr->hash[victim] = node->slot;
1317 bt->mgr->hash[victim] = 0;
1319 if( node = pool->hashnext )
1320 node->hashprev = pool->hashprev;
1322 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1324 // remove old file mapping
1326 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1328 FlushViewOfFile(pool->map, 0);
1329 UnmapViewOfFile(pool->map);
1330 CloseHandle(pool->hmap);
1334 // create new pool mapping
1335 // and link into hash table
1337 if( bt_mapsegment(bt, pool, page_no) )
1340 bt_linkhash(bt, pool, page_no, idx);
1342 __sync_fetch_and_add(&pool->pin, 1);
1344 _InterlockedIncrement16 (&pool->pin);
1346 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1351 // place write, read, or parent lock on requested page_no.
1353 void bt_lockpage(BtLock mode, BtLatchSet *set)
1357 bt_readlock (set->readwr);
1360 bt_writelock (set->readwr);
1363 bt_readlock (set->access);
1366 bt_writelock (set->access);
1369 bt_writelock (set->parent);
1374 // remove write, read, or parent lock on requested page
1376 void bt_unlockpage(BtLock mode, BtLatchSet *set)
1380 bt_releaseread (set->readwr);
1383 bt_releasewrite (set->readwr);
1386 bt_releaseread (set->access);
1389 bt_releasewrite (set->access);
1392 bt_releasewrite (set->parent);
1397 // allocate a new page and write page into it
1399 uid bt_newpage(BtDb *bt, BtPage page)
1405 // lock allocation page
1407 bt_spinwritelock(bt->mgr->latchmgr->lock);
1409 // use empty chain first
1410 // else allocate empty page
1412 if( new_page = bt_getid(bt->mgr->latchmgr->alloc[1].right) ) {
1413 if( set->pool = bt_pinpool (bt, new_page) )
1414 set->page = bt_page (bt, set->pool, new_page);
1418 bt_putid(bt->mgr->latchmgr->alloc[1].right, bt_getid(set->page->right));
1419 bt_unpinpool (set->pool);
1422 new_page = bt_getid(bt->mgr->latchmgr->alloc->right);
1423 bt_putid(bt->mgr->latchmgr->alloc->right, new_page+1);
1427 if ( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1428 return bt->err = BTERR_wrt, 0;
1430 // if writing first page of pool block, zero last page in the block
1432 if ( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1434 // use zero buffer to write zeros
1435 if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1436 return bt->err = BTERR_wrt, 0;
1439 // bring new page into pool and copy page.
1440 // this will extend the file into the new pages.
1442 if( set->pool = bt_pinpool (bt, new_page) )
1443 set->page = bt_page (bt, set->pool, new_page);
1447 memcpy(set->page, page, bt->mgr->page_size);
1448 bt_unpinpool (set->pool);
1450 // unlock allocation latch and return new page no
1452 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1456 // find slot in page for given key at a given level
1458 int bt_findslot (BtPageSet *set, unsigned char *key, uint len)
1460 uint diff, higher = set->page->cnt, low = 1, slot;
1462 // make stopper key an infinite fence value
1464 if( bt_getid (set->page->right) )
1467 // low is the lowest candidate.
1468 // loop ends when they meet
1470 // higher is already
1471 // tested as .ge. the given key.
1473 while( diff = higher - low ) {
1474 slot = low + ( diff >> 1 );
1475 if( keycmp (keyptr(set->page, slot), key, len) < 0 )
1481 if( higher <= set->page->cnt )
1484 // if leaf page, compare against fence value
1486 // return zero if key is on right link page
1487 // or return slot beyond last key
1489 if( set->page->lvl || keycmp ((BtKey)set->page->fence, key, len) < 0 )
1495 // find and load page at given level for given key
1496 // leave page rd or wr locked as requested
1498 int bt_loadpage (BtDb *bt, BtPageSet *set, unsigned char *key, uint len, uint lvl, uint lock)
1500 uid page_no = ROOT_page, prevpage = 0;
1501 uint drill = 0xff, slot;
1502 BtLatchSet *prevlatch;
1503 uint mode, prevmode;
1506 // start at root of btree and drill down
1509 // determine lock mode of drill level
1510 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1512 set->latch = bt_pinlatch (bt, page_no);
1513 set->page_no = page_no;
1515 // pin page contents
1517 if( set->pool = bt_pinpool (bt, page_no) )
1518 set->page = bt_page (bt, set->pool, page_no);
1522 // obtain access lock using lock chaining with Access mode
1524 if( page_no > ROOT_page )
1525 bt_lockpage(BtLockAccess, set->latch);
1527 // release & unpin parent page
1530 bt_unlockpage(prevmode, prevlatch);
1531 bt_unpinlatch (prevlatch);
1532 bt_unpinpool (prevpool);
1536 // obtain read lock using lock chaining
1538 bt_lockpage(mode, set->latch);
1540 if( page_no > ROOT_page )
1541 bt_unlockpage(BtLockAccess, set->latch);
1543 // re-read and re-lock root after determining actual level of root
1545 if( set->page->lvl != drill) {
1546 if ( set->page_no != ROOT_page )
1547 return bt->err = BTERR_struct, 0;
1549 drill = set->page->lvl;
1551 if( lock == BtLockWrite && drill == lvl ) {
1552 bt_unlockpage(mode, set->latch);
1553 bt_unpinlatch (set->latch);
1554 bt_unpinpool (set->pool);
1559 prevpage = set->page_no;
1560 prevlatch = set->latch;
1561 prevpool = set->pool;
1564 // if page is being deleted and we should continue right
1566 if( set->page->kill && set->page->goright ) {
1567 page_no = bt_getid (set->page->right);
1571 // otherwise, wait for deleted node to clear
1573 if( set->page->kill ) {
1574 bt_unlockpage(mode, set->latch);
1575 bt_unpinlatch (set->latch);
1576 bt_unpinpool (set->pool);
1577 page_no = ROOT_page;
1588 // find key on page at this level
1589 // and descend to requested level
1591 if( slot = bt_findslot (set, key, len) ) {
1595 if( slot > set->page->cnt )
1596 return bt->err = BTERR_struct;
1598 while( slotptr(set->page, slot)->dead )
1599 if( slot++ < set->page->cnt )
1602 return bt->err = BTERR_struct, 0;
1604 page_no = bt_getid(slotptr(set->page, slot)->id);
1609 // or slide right into next page
1611 page_no = bt_getid(set->page->right);
1615 // return error on end of right chain
1617 bt->err = BTERR_struct;
1618 return 0; // return error
1621 // drill down fixing fence values for left sibling tree
1623 // call with set write locked
1624 // return with set unlocked & unpinned.
1626 BTERR bt_fixfences (BtDb *bt, BtPageSet *set, unsigned char *newfence)
1628 unsigned char oldfence[256];
1632 memcpy (oldfence, set->page->fence, 256);
1633 next->page_no = bt_getid(slotptr(set->page, set->page->cnt)->id);
1635 while( !set->page->kill && set->page->lvl ) {
1636 next->latch = bt_pinlatch (bt, next->page_no);
1637 bt_lockpage (BtLockParent, next->latch);
1638 bt_lockpage (BtLockAccess, next->latch);
1639 bt_lockpage (BtLockWrite, next->latch);
1640 bt_unlockpage (BtLockAccess, next->latch);
1642 if( next->pool = bt_pinpool (bt, next->page_no) )
1643 next->page = bt_page (bt, next->pool, next->page_no);
1647 chk = keycmp ((BtKey)next->page->fence, oldfence + 1, *oldfence);
1650 next->page_no = bt_getid (next->page->right);
1651 bt_unlockpage (BtLockWrite, next->latch);
1652 bt_unlockpage (BtLockParent, next->latch);
1653 bt_unpinlatch (next->latch);
1654 bt_unpinpool (next->pool);
1659 return bt->err = BTERR_struct;
1661 if( bt_fixfences (bt, next, newfence) )
1667 memcpy (set->page->fence, newfence, 256);
1669 bt_unlockpage (BtLockWrite, set->latch);
1670 bt_unlockpage (BtLockParent, set->latch);
1671 bt_unpinlatch (set->latch);
1672 bt_unpinpool (set->pool);
1676 // return page to free list
1677 // page must be delete & write locked
1679 void bt_freepage (BtDb *bt, BtPageSet *set)
1681 // lock allocation page
1683 bt_spinwritelock (bt->mgr->latchmgr->lock);
1685 // store chain in second right
1686 bt_putid(set->page->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1687 bt_putid(bt->mgr->latchmgr->alloc[1].right, set->page_no);
1688 set->page->free = 1;
1690 // unlock released page
1692 bt_unlockpage (BtLockDelete, set->latch);
1693 bt_unlockpage (BtLockWrite, set->latch);
1694 bt_unpinlatch (set->latch);
1695 bt_unpinpool (set->pool);
1697 // unlock allocation page
1699 bt_spinreleasewrite (bt->mgr->latchmgr->lock);
1702 // remove the root level by promoting its only child
1703 // call with parent and child pages
1705 BTERR bt_removeroot (BtDb *bt, BtPageSet *root, BtPageSet *child)
1711 child->latch = bt_pinlatch (bt, next);
1712 bt_lockpage (BtLockDelete, child->latch);
1713 bt_lockpage (BtLockWrite, child->latch);
1715 if( child->pool = bt_pinpool (bt, next) )
1716 child->page = bt_page (bt, child->pool, next);
1720 child->page_no = next;
1723 memcpy (root->page, child->page, bt->mgr->page_size);
1724 next = bt_getid (slotptr(child->page, child->page->cnt)->id);
1725 bt_freepage (bt, child);
1726 } while( root->page->lvl > 1 && root->page->cnt == 1 );
1728 bt_unlockpage (BtLockWrite, root->latch);
1729 bt_unpinlatch (root->latch);
1730 bt_unpinpool (root->pool);
1734 // pull right page over ourselves in simple merge
1736 BTERR bt_mergeright (BtDb *bt, BtPageSet *set, BtPageSet *parent, BtPageSet *right, uint slot, uint idx)
1738 // install ourselves as child page
1739 // and delete ourselves from parent
1741 bt_putid (slotptr(parent->page, idx)->id, set->page_no);
1742 slotptr(parent->page, slot)->dead = 1;
1743 parent->page->act--;
1745 // collapse any empty slots
1747 while( idx = parent->page->cnt - 1 )
1748 if( slotptr(parent->page, idx)->dead ) {
1749 *slotptr(parent->page, idx) = *slotptr(parent->page, idx + 1);
1750 memset (slotptr(parent->page, parent->page->cnt--), 0, sizeof(BtSlot));
1754 memcpy (set->page, right->page, bt->mgr->page_size);
1755 bt_unlockpage (BtLockParent, right->latch);
1757 bt_freepage (bt, right);
1759 // do we need to remove a btree level?
1760 // (leave the first page of leaves alone)
1762 if( parent->page_no == ROOT_page && parent->page->cnt == 1 )
1763 if( set->page->lvl )
1764 return bt_removeroot (bt, parent, set);
1766 bt_unlockpage (BtLockWrite, parent->latch);
1767 bt_unlockpage (BtLockDelete, set->latch);
1768 bt_unlockpage (BtLockWrite, set->latch);
1769 bt_unpinlatch (parent->latch);
1770 bt_unpinpool (parent->pool);
1771 bt_unpinlatch (set->latch);
1772 bt_unpinpool (set->pool);
1776 // remove both child and parent from the btree
1777 // from the fence position in the parent
1778 // call with both pages locked for writing
1780 BTERR bt_removeparent (BtDb *bt, BtPageSet *child, BtPageSet *parent, BtPageSet *right, BtPageSet *rparent, uint lvl)
1782 unsigned char pagefence[256];
1785 // pull right sibling over ourselves and unlock
1787 memcpy (child->page, right->page, bt->mgr->page_size);
1789 bt_unlockpage (BtLockWrite, child->latch);
1790 bt_unpinlatch (child->latch);
1791 bt_unpinpool (child->pool);
1793 // install ourselves into right link of old right page
1795 bt_putid (right->page->right, child->page_no);
1796 right->page->goright = 1; // tell bt_loadpage to go right to us
1797 right->page->kill = 1;
1799 bt_unlockpage (BtLockWrite, right->latch);
1801 // remove our slot from our parent
1802 // signal to move right
1804 parent->page->goright = 1; // tell bt_loadpage to go right to rparent
1805 parent->page->kill = 1;
1806 parent->page->act--;
1808 // redirect right page pointer in right parent to us
1810 for( idx = 0; idx++ < rparent->page->cnt; )
1811 if( !slotptr(rparent->page, idx)->dead )
1814 if( bt_getid (slotptr(rparent->page, idx)->id) != right->page_no )
1815 return bt->err = BTERR_struct;
1817 bt_putid (slotptr(rparent->page, idx)->id, child->page_no);
1818 bt_unlockpage (BtLockWrite, rparent->latch);
1819 bt_unpinlatch (rparent->latch);
1820 bt_unpinpool (rparent->pool);
1822 // free the right page
1824 bt_lockpage (BtLockDelete, right->latch);
1825 bt_lockpage (BtLockWrite, right->latch);
1826 bt_freepage (bt, right);
1828 // save parent page fence value
1830 memcpy (pagefence, parent->page->fence, 256);
1831 bt_unlockpage (BtLockWrite, parent->latch);
1833 return bt_removepage (bt, parent, lvl, pagefence);
1836 // remove page from btree
1837 // call with page unlocked
1838 // returns with page on free list
1840 BTERR bt_removepage (BtDb *bt, BtPageSet *set, uint lvl, unsigned char *pagefence)
1842 BtPageSet parent[1], sibling[1], rparent[1];
1843 unsigned char newfence[256];
1847 // load and lock our parent
1850 if( !(slot = bt_loadpage (bt, parent, pagefence+1, *pagefence, lvl+1, BtLockWrite)) )
1853 // do we show up in our parent yet?
1855 if( set->page_no != bt_getid (slotptr (parent->page, slot)->id) ) {
1856 bt_unlockpage (BtLockWrite, parent->latch);
1857 bt_unpinlatch (parent->latch);
1858 bt_unpinpool (parent->pool);
1867 // can we do a simple merge entirely
1868 // between siblings on the parent page?
1870 if( slot < parent->page->cnt ) {
1871 // find our right neighbor
1872 // right must exist because the stopper prevents
1873 // the rightmost page from deleting
1875 for( idx = slot; idx++ < parent->page->cnt; )
1876 if( !slotptr(parent->page, idx)->dead )
1879 sibling->page_no = bt_getid (slotptr (parent->page, idx)->id);
1881 bt_lockpage (BtLockDelete, set->latch);
1882 bt_lockpage (BtLockWrite, set->latch);
1884 // merge right if sibling shows up in
1885 // our parent and is not being killed
1887 if( sibling->page_no == bt_getid (set->page->right) ) {
1888 sibling->latch = bt_pinlatch (bt, sibling->page_no);
1889 bt_lockpage (BtLockParent, sibling->latch);
1890 bt_lockpage (BtLockDelete, sibling->latch);
1891 bt_lockpage (BtLockWrite, sibling->latch);
1893 if( sibling->pool = bt_pinpool (bt, sibling->page_no) )
1894 sibling->page = bt_page (bt, sibling->pool, sibling->page_no);
1898 if( !sibling->page->kill )
1899 return bt_mergeright(bt, set, parent, sibling, slot, idx);
1903 bt_unlockpage (BtLockWrite, sibling->latch);
1904 bt_unlockpage (BtLockParent, sibling->latch);
1905 bt_unlockpage (BtLockDelete, sibling->latch);
1906 bt_unpinlatch (sibling->latch);
1907 bt_unpinpool (sibling->pool);
1910 bt_unlockpage (BtLockDelete, set->latch);
1911 bt_unlockpage (BtLockWrite, set->latch);
1912 bt_unlockpage (BtLockWrite, parent->latch);
1913 bt_unpinlatch (parent->latch);
1914 bt_unpinpool (parent->pool);
1923 // find our left neighbor in our parent page
1925 for( idx = slot; --idx; )
1926 if( !slotptr(parent->page, idx)->dead )
1929 // if no left neighbor, delete ourselves and our parent
1932 bt_lockpage (BtLockAccess, set->latch);
1933 bt_lockpage (BtLockWrite, set->latch);
1934 bt_unlockpage (BtLockAccess, set->latch);
1936 rparent->page_no = bt_getid (parent->page->right);
1937 rparent->latch = bt_pinlatch (bt, rparent->page_no);
1939 bt_lockpage (BtLockAccess, rparent->latch);
1940 bt_lockpage (BtLockWrite, rparent->latch);
1941 bt_unlockpage (BtLockAccess, rparent->latch);
1943 if( rparent->pool = bt_pinpool (bt, rparent->page_no) )
1944 rparent->page = bt_page (bt, rparent->pool, rparent->page_no);
1948 if( !rparent->page->kill ) {
1949 sibling->page_no = bt_getid (set->page->right);
1950 sibling->latch = bt_pinlatch (bt, sibling->page_no);
1952 bt_lockpage (BtLockAccess, sibling->latch);
1953 bt_lockpage (BtLockWrite, sibling->latch);
1954 bt_unlockpage (BtLockAccess, sibling->latch);
1956 if( sibling->pool = bt_pinpool (bt, sibling->page_no) )
1957 sibling->page = bt_page (bt, sibling->pool, sibling->page_no);
1961 if( !sibling->page->kill )
1962 return bt_removeparent (bt, set, parent, sibling, rparent, lvl+1);
1966 bt_unlockpage (BtLockWrite, sibling->latch);
1967 bt_unpinlatch (sibling->latch);
1968 bt_unpinpool (sibling->pool);
1971 bt_unlockpage (BtLockWrite, set->latch);
1972 bt_unlockpage (BtLockWrite, rparent->latch);
1973 bt_unpinlatch (rparent->latch);
1974 bt_unpinpool (rparent->pool);
1976 bt_unlockpage (BtLockWrite, parent->latch);
1977 bt_unpinlatch (parent->latch);
1978 bt_unpinpool (parent->pool);
1987 // redirect parent to our left sibling
1988 // lock and map our left sibling's page
1990 sibling->page_no = bt_getid (slotptr(parent->page, idx)->id);
1991 sibling->latch = bt_pinlatch (bt, sibling->page_no);
1993 // wait our turn on fence key maintenance
1995 bt_lockpage(BtLockParent, sibling->latch);
1996 bt_lockpage(BtLockAccess, sibling->latch);
1997 bt_lockpage(BtLockWrite, sibling->latch);
1998 bt_unlockpage(BtLockAccess, sibling->latch);
2000 if( sibling->pool = bt_pinpool (bt, sibling->page_no) )
2001 sibling->page = bt_page (bt, sibling->pool, sibling->page_no);
2005 // wait until left sibling is in our parent
2007 if( bt_getid (sibling->page->right) != set->page_no ) {
2008 bt_unlockpage (BtLockWrite, parent->latch);
2009 bt_unlockpage (BtLockWrite, sibling->latch);
2010 bt_unlockpage (BtLockParent, sibling->latch);
2011 bt_unpinlatch (parent->latch);
2012 bt_unpinpool (parent->pool);
2013 bt_unpinlatch (sibling->latch);
2014 bt_unpinpool (sibling->pool);
2023 // delete our left sibling from parent
2025 slotptr(parent->page,idx)->dead = 1;
2026 parent->page->dirty = 1;
2027 parent->page->act--;
2029 // redirect our parent slot to our left sibling
2031 bt_putid (slotptr(parent->page, slot)->id, sibling->page_no);
2032 memcpy (sibling->page->right, set->page->right, BtId);
2034 // collapse dead slots from parent
2036 while( idx = parent->page->cnt - 1 )
2037 if( slotptr(parent->page, idx)->dead ) {
2038 *slotptr(parent->page, idx) = *slotptr(parent->page, parent->page->cnt);
2039 memset (slotptr(parent->page, parent->page->cnt--), 0, sizeof(BtSlot));
2043 // free our original page
2045 bt_lockpage (BtLockDelete, set->latch);
2046 bt_lockpage (BtLockWrite, set->latch);
2047 bt_freepage (bt, set);
2049 // go down the left node's fence keys to the leaf level
2050 // and update the fence keys in each page
2052 memcpy (newfence, parent->page->fence, 256);
2054 if( bt_fixfences (bt, sibling, newfence) )
2057 // promote sibling as new root?
2059 if( parent->page_no == ROOT_page && parent->page->cnt == 1 )
2060 if( sibling->page->lvl ) {
2061 sibling->latch = bt_pinlatch (bt, sibling->page_no);
2062 bt_lockpage (BtLockDelete, sibling->latch);
2063 bt_lockpage (BtLockWrite, sibling->latch);
2065 if( sibling->pool = bt_pinpool (bt, sibling->page_no) )
2066 sibling->page = bt_page (bt, sibling->pool, sibling->page_no);
2070 return bt_removeroot (bt, parent, sibling);
2073 bt_unlockpage (BtLockWrite, parent->latch);
2074 bt_unpinlatch (parent->latch);
2075 bt_unpinpool (parent->pool);
2081 // find and delete key on page by marking delete flag bit
2082 // if page becomes empty, delete it from the btree
2084 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len)
2086 unsigned char pagefence[256];
2087 uint slot, idx, found;
2091 if( slot = bt_loadpage (bt, set, key, len, 0, BtLockWrite) )
2092 ptr = keyptr(set->page, slot);
2096 // if key is found delete it, otherwise ignore request
2098 if( found = slot <= set->page->cnt )
2099 if( found = !keycmp (ptr, key, len) )
2100 if( found = slotptr(set->page, slot)->dead == 0 ) {
2101 slotptr(set->page,slot)->dead = 1;
2102 set->page->dirty = 1;
2105 // collapse empty slots
2107 while( idx = set->page->cnt - 1 )
2108 if( slotptr(set->page, idx)->dead ) {
2109 *slotptr(set->page, idx) = *slotptr(set->page, idx + 1);
2110 memset (slotptr(set->page, set->page->cnt--), 0, sizeof(BtSlot));
2115 if( set->page->act ) {
2116 bt_unlockpage(BtLockWrite, set->latch);
2117 bt_unpinlatch (set->latch);
2118 bt_unpinpool (set->pool);
2119 return bt->found = found, 0;
2122 memcpy (pagefence, set->page->fence, 256);
2123 set->page->kill = 1;
2125 bt_unlockpage (BtLockWrite, set->latch);
2127 if( bt_removepage (bt, set, 0, pagefence) )
2134 // find key in leaf level and return row-id
2136 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
2143 if( slot = bt_loadpage (bt, set, key, len, 0, BtLockRead) )
2144 ptr = keyptr(set->page, slot);
2148 // if key exists, return row-id
2149 // otherwise return 0
2151 if( slot <= set->page->cnt )
2152 if( !keycmp (ptr, key, len) )
2153 id = bt_getid(slotptr(set->page,slot)->id);
2155 bt_unlockpage (BtLockRead, set->latch);
2156 bt_unpinlatch (set->latch);
2157 bt_unpinpool (set->pool);
2161 // check page for space available,
2162 // clean if necessary and return
2163 // 0 - page needs splitting
2164 // >0 new slot value
2166 uint bt_cleanpage(BtDb *bt, BtPage page, uint amt, uint slot)
2168 uint nxt = bt->mgr->page_size, off;
2169 uint cnt = 0, idx = 0;
2170 uint max = page->cnt;
2174 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
2177 // skip cleanup if nothing to reclaim
2182 memcpy (bt->frame, page, bt->mgr->page_size);
2184 // skip page info and set rest of page to zero
2186 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
2190 // try cleaning up page first
2191 // by removing deleted keys
2193 while( cnt++ < max ) {
2196 if( slotptr(bt->frame,cnt)->dead )
2199 // if its not the fence key,
2200 // copy the key across
2202 off = slotptr(bt->frame,cnt)->off;
2204 if( off >= sizeof(*page) ) {
2205 key = keyptr(bt->frame, cnt);
2206 off = nxt -= key->len + 1;
2207 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2212 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
2213 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2214 slotptr(page, idx)->off = off;
2221 // see if page has enough space now, or does it need splitting?
2223 if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
2229 // split the root and raise the height of the btree
2231 BTERR bt_splitroot(BtDb *bt, BtPageSet *root, uid page_no2)
2233 uint nxt = bt->mgr->page_size;
2234 unsigned char leftkey[256];
2237 // Obtain an empty page to use, and copy the current
2238 // root contents into it, e.g. lower keys
2240 memcpy (leftkey, root->page->fence, 256);
2241 root->page->posted = 1;
2243 if( !(new_page = bt_newpage(bt, root->page)) )
2246 // preserve the page info at the bottom
2247 // of higher keys and set rest to zero
2249 memset(root->page+1, 0, bt->mgr->page_size - sizeof(*root->page));
2250 memset(root->page->fence, 0, 256);
2251 root->page->fence[0] = 2;
2252 root->page->fence[1] = 0xff;
2253 root->page->fence[2] = 0xff;
2255 // insert lower keys page fence key on newroot page
2257 nxt -= *leftkey + 1;
2258 memcpy ((unsigned char *)root->page + nxt, leftkey, *leftkey + 1);
2259 bt_putid(slotptr(root->page, 1)->id, new_page);
2260 slotptr(root->page, 1)->off = nxt;
2262 // insert stopper key on newroot page
2263 // and increase the root height
2265 bt_putid(slotptr(root->page, 2)->id, page_no2);
2266 slotptr(root->page, 2)->off = offsetof(struct BtPage_, fence);
2268 bt_putid(root->page->right, 0);
2269 root->page->min = nxt; // reset lowest used offset and key count
2270 root->page->cnt = 2;
2271 root->page->act = 2;
2274 // release and unpin root
2276 bt_unlockpage(BtLockWrite, root->latch);
2277 bt_unpinlatch (root->latch);
2278 bt_unpinpool (root->pool);
2282 // split already locked full node
2285 BTERR bt_splitpage (BtDb *bt, BtPageSet *set)
2287 uint cnt = 0, idx = 0, max, nxt = bt->mgr->page_size, off;
2288 unsigned char fencekey[256];
2289 uint lvl = set->page->lvl;
2293 // split higher half of keys to bt->frame
2295 memset (bt->frame, 0, bt->mgr->page_size);
2296 max = set->page->cnt;
2300 while( cnt++ < max ) {
2301 if( !lvl || cnt < max ) {
2302 key = keyptr(set->page, cnt);
2303 off = nxt -= key->len + 1;
2304 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
2306 off = offsetof(struct BtPage_, fence);
2308 memcpy(slotptr(bt->frame,++idx)->id, slotptr(set->page,cnt)->id, BtId);
2309 slotptr(bt->frame, idx)->tod = slotptr(set->page, cnt)->tod;
2310 slotptr(bt->frame, idx)->off = off;
2314 if( set->page_no == ROOT_page )
2315 bt->frame->posted = 1;
2317 memcpy (bt->frame->fence, set->page->fence, 256);
2318 bt->frame->bits = bt->mgr->page_bits;
2319 bt->frame->min = nxt;
2320 bt->frame->cnt = idx;
2321 bt->frame->lvl = lvl;
2325 if( set->page_no > ROOT_page )
2326 memcpy (bt->frame->right, set->page->right, BtId);
2328 // get new free page and write higher keys to it.
2330 if( !(right = bt_newpage(bt, bt->frame)) )
2333 // update lower keys to continue in old page
2335 memcpy (bt->frame, set->page, bt->mgr->page_size);
2336 memset (set->page+1, 0, bt->mgr->page_size - sizeof(*set->page));
2337 nxt = bt->mgr->page_size;
2338 set->page->posted = 0;
2339 set->page->dirty = 0;
2344 // assemble page of smaller keys
2346 while( cnt++ < max / 2 ) {
2347 key = keyptr(bt->frame, cnt);
2349 if( !lvl || cnt < max / 2 ) {
2350 off = nxt -= key->len + 1;
2351 memcpy ((unsigned char *)set->page + nxt, key, key->len + 1);
2353 off = offsetof(struct BtPage_, fence);
2355 memcpy(slotptr(set->page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
2356 slotptr(set->page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2357 slotptr(set->page, idx)->off = off;
2361 // install fence key for smaller key page
2363 memset(set->page->fence, 0, 256);
2364 memcpy(set->page->fence, key, key->len + 1);
2366 bt_putid(set->page->right, right);
2367 set->page->min = nxt;
2368 set->page->cnt = idx;
2370 // if current page is the root page, split it
2372 if( set->page_no == ROOT_page )
2373 return bt_splitroot (bt, set, right);
2375 bt_unlockpage (BtLockWrite, set->latch);
2377 // insert new fences in their parent pages
2380 bt_lockpage (BtLockParent, set->latch);
2381 bt_lockpage (BtLockWrite, set->latch);
2383 memcpy (fencekey, set->page->fence, 256);
2384 right = bt_getid (set->page->right);
2386 if( set->page->posted ) {
2387 bt_unlockpage (BtLockParent, set->latch);
2388 bt_unlockpage (BtLockWrite, set->latch);
2389 bt_unpinlatch (set->latch);
2390 bt_unpinpool (set->pool);
2394 set->page->posted = 1;
2395 bt_unlockpage (BtLockWrite, set->latch);
2397 if( bt_insertkey (bt, fencekey+1, *fencekey, set->page_no, time(NULL), lvl+1) )
2400 bt_unlockpage (BtLockParent, set->latch);
2401 bt_unpinlatch (set->latch);
2402 bt_unpinpool (set->pool);
2404 if( !(set->page_no = right) )
2407 set->latch = bt_pinlatch (bt, right);
2409 if( set->pool = bt_pinpool (bt, right) )
2410 set->page = bt_page (bt, set->pool, right);
2418 // Insert new key into the btree at given level.
2420 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod, uint lvl)
2427 if( slot = bt_loadpage (bt, set, key, len, lvl, BtLockWrite) )
2428 ptr = keyptr(set->page, slot);
2432 bt->err = BTERR_ovflw;
2436 // if key already exists, update id and return
2438 if( slot <= set->page->cnt )
2439 if( !keycmp (ptr, key, len) ) {
2440 if( slotptr(set->page, slot)->dead )
2442 slotptr(set->page, slot)->dead = 0;
2443 slotptr(set->page, slot)->tod = tod;
2444 bt_putid(slotptr(set->page,slot)->id, id);
2445 bt_unlockpage(BtLockWrite, set->latch);
2446 bt_unpinlatch (set->latch);
2447 bt_unpinpool (set->pool);
2451 // check if page has enough space
2453 if( slot = bt_cleanpage (bt, set->page, len, slot) )
2456 if( bt_splitpage (bt, set) )
2460 // calculate next available slot and copy key into page
2462 set->page->min -= len + 1; // reset lowest used offset
2463 ((unsigned char *)set->page)[set->page->min] = len;
2464 memcpy ((unsigned char *)set->page + set->page->min +1, key, len );
2466 for( idx = slot; idx <= set->page->cnt; idx++ )
2467 if( slotptr(set->page, idx)->dead )
2470 // now insert key into array before slot
2472 if( idx > set->page->cnt )
2478 *slotptr(set->page, idx) = *slotptr(set->page, idx -1), idx--;
2480 bt_putid(slotptr(set->page,slot)->id, id);
2481 slotptr(set->page, slot)->off = set->page->min;
2482 slotptr(set->page, slot)->tod = tod;
2483 slotptr(set->page, slot)->dead = 0;
2485 bt_unlockpage (BtLockWrite, set->latch);
2486 bt_unpinlatch (set->latch);
2487 bt_unpinpool (set->pool);
2491 // cache page of keys into cursor and return starting slot for given key
2493 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2498 // cache page for retrieval
2500 if( slot = bt_loadpage (bt, set, key, len, 0, BtLockRead) )
2501 memcpy (bt->cursor, set->page, bt->mgr->page_size);
2505 bt->cursor_page = set->page_no;
2507 bt_unlockpage(BtLockRead, set->latch);
2508 bt_unpinlatch (set->latch);
2509 bt_unpinpool (set->pool);
2513 // return next slot for cursor page
2514 // or slide cursor right into next page
2516 uint bt_nextkey (BtDb *bt, uint slot)
2522 right = bt_getid(bt->cursor->right);
2523 while( slot++ < bt->cursor->cnt )
2524 if( slotptr(bt->cursor,slot)->dead )
2526 else if( right || (slot < bt->cursor->cnt) ) // skip infinite stopper
2534 bt->cursor_page = right;
2536 if( set->pool = bt_pinpool (bt, right) )
2537 set->page = bt_page (bt, set->pool, right);
2541 set->latch = bt_pinlatch (bt, right);
2542 bt_lockpage(BtLockRead, set->latch);
2544 memcpy (bt->cursor, set->page, bt->mgr->page_size);
2546 bt_unlockpage(BtLockRead, set->latch);
2547 bt_unpinlatch (set->latch);
2548 bt_unpinpool (set->pool);
2555 BtKey bt_key(BtDb *bt, uint slot)
2557 return keyptr(bt->cursor, slot);
2560 uid bt_uid(BtDb *bt, uint slot)
2562 return bt_getid(slotptr(bt->cursor,slot)->id);
2565 uint bt_tod(BtDb *bt, uint slot)
2567 return slotptr(bt->cursor,slot)->tod;
2573 void bt_latchaudit (BtDb *bt)
2575 ushort idx, hashidx;
2579 for( idx = 1; idx < bt->mgr->latchmgr->latchdeployed; idx++ ) {
2580 set->latch = bt->mgr->latchsets + idx;
2581 if( set->latch->pin ) {
2582 fprintf(stderr, "latchset %d pinned for page %.6x\n", idx, set->latch->page_no);
2583 set->latch->pin = 0;
2587 for( hashidx = 0; hashidx < bt->mgr->latchmgr->latchhash; hashidx++ ) {
2588 if( idx = bt->mgr->latchmgr->table[hashidx].slot ) do {
2589 set->latch = bt->mgr->latchsets + idx;
2590 if( set->latch->hash != hashidx )
2591 fprintf(stderr, "latchset %d wrong hashidx\n", idx);
2592 if( set->latch->pin )
2593 fprintf(stderr, "latchset %d pinned for page %.8x\n", idx, set->latch->page_no);
2594 } while( idx = set->latch->next );
2597 set->page_no = bt_getid(bt->mgr->latchmgr->alloc[1].right);
2599 while( set->page_no ) {
2600 fprintf(stderr, "free: %.6x\n", (uint)set->page_no);
2602 if( set->pool = bt_pinpool (bt, set->page_no) )
2603 set->page = bt_page (bt, set->pool, set->page_no);
2607 set->page_no = bt_getid(set->page->right);
2608 bt_unpinpool (set->pool);
2620 // standalone program to index file of keys
2621 // then list them onto std-out
2624 void *index_file (void *arg)
2626 uint __stdcall index_file (void *arg)
2629 int line = 0, found = 0, cnt = 0;
2630 uid next, page_no = LEAF_page; // start on first page of leaves
2631 unsigned char key[256];
2632 ThreadArg *args = arg;
2633 int ch, len = 0, slot;
2640 bt = bt_open (args->mgr);
2643 switch(args->type | 0x20)
2646 fprintf(stderr, "started latch mgr audit\n");
2648 fprintf(stderr, "finished latch mgr audit\n");
2652 fprintf(stderr, "started indexing for %s\n", args->infile);
2653 if( in = fopen (args->infile, "rb") )
2654 while( ch = getc(in), ch != EOF )
2659 if( args->num == 1 )
2660 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2662 else if( args->num )
2663 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2665 if( bt_insertkey (bt, key, len, line, *tod, 0) )
2666 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2669 else if( len < 255 )
2671 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
2675 fprintf(stderr, "started deleting keys for %s\n", args->infile);
2676 if( in = fopen (args->infile, "rb") )
2677 while( ch = getc(in), ch != EOF )
2681 if( args->num == 1 )
2682 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2684 else if( args->num )
2685 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2687 if( bt_deletekey (bt, key, len) )
2688 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2691 else if( len < 255 )
2693 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2697 fprintf(stderr, "started finding keys for %s\n", args->infile);
2698 if( in = fopen (args->infile, "rb") )
2699 while( ch = getc(in), ch != EOF )
2703 if( args->num == 1 )
2704 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2706 else if( args->num )
2707 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2709 if( bt_findkey (bt, key, len) )
2712 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2715 else if( len < 255 )
2717 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2721 fprintf(stderr, "started scanning\n");
2723 if( set->pool = bt_pinpool (bt, page_no) )
2724 set->page = bt_page (bt, set->pool, page_no);
2727 set->latch = bt_pinlatch (bt, page_no);
2728 bt_lockpage (BtLockRead, set->latch);
2729 next = bt_getid (set->page->right);
2730 cnt += set->page->act;
2732 for( slot = 0; slot++ < set->page->cnt; )
2733 if( next || slot < set->page->cnt )
2734 if( !slotptr(set->page, slot)->dead ) {
2735 ptr = keyptr(set->page, slot);
2736 fwrite (ptr->key, ptr->len, 1, stdout);
2737 fputc ('\n', stdout);
2740 bt_unlockpage (BtLockRead, set->latch);
2741 bt_unpinlatch (set->latch);
2742 bt_unpinpool (set->pool);
2743 } while( page_no = next );
2745 cnt--; // remove stopper key
2746 fprintf(stderr, " Total keys read %d\n", cnt);
2750 fprintf(stderr, "started counting\n");
2751 next = bt->mgr->latchmgr->nlatchpage + LATCH_page;
2752 page_no = LEAF_page;
2754 while( page_no < bt_getid(bt->mgr->latchmgr->alloc->right) ) {
2755 pread (bt->mgr->idx, bt->frame, bt->mgr->page_size, page_no << bt->mgr->page_bits);
2756 if( !bt->frame->free && !bt->frame->lvl )
2757 cnt += bt->frame->act;
2758 if( page_no > LEAF_page )
2763 cnt--; // remove stopper key
2764 fprintf(stderr, " Total keys read %d\n", cnt);
2776 typedef struct timeval timer;
2778 int main (int argc, char **argv)
2780 int idx, cnt, len, slot, err;
2781 int segsize, bits = 16;
2786 time_t start[1], stop[1];
2799 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]);
2800 fprintf (stderr, " where page_bits is the page size in bits\n");
2801 fprintf (stderr, " mapped_segments is the number of mmap segments in buffer pool\n");
2802 fprintf (stderr, " seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2803 fprintf (stderr, " line_numbers = 1 to append line numbers to keys\n");
2804 fprintf (stderr, " src_file1 thru src_filen are files of keys separated by newline\n");
2809 gettimeofday(&start, NULL);
2815 bits = atoi(argv[3]);
2818 poolsize = atoi(argv[4]);
2821 fprintf (stderr, "Warning: no mapped_pool\n");
2823 if( poolsize > 65535 )
2824 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2827 segsize = atoi(argv[5]);
2829 segsize = 4; // 16 pages per mmap segment
2832 num = atoi(argv[6]);
2836 threads = malloc (cnt * sizeof(pthread_t));
2838 threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2840 args = malloc (cnt * sizeof(ThreadArg));
2842 mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2845 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2851 for( idx = 0; idx < cnt; idx++ ) {
2852 args[idx].infile = argv[idx + 7];
2853 args[idx].type = argv[2][0];
2854 args[idx].mgr = mgr;
2855 args[idx].num = num;
2856 args[idx].idx = idx;
2858 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2859 fprintf(stderr, "Error creating thread %d\n", err);
2861 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2865 // wait for termination
2868 for( idx = 0; idx < cnt; idx++ )
2869 pthread_join (threads[idx], NULL);
2870 gettimeofday(&stop, NULL);
2871 real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2873 WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2875 for( idx = 0; idx < cnt; idx++ )
2876 CloseHandle(threads[idx]);
2879 real_time = 1000 * (*stop - *start);
2881 fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);