1 // btree version threads2i sched_yield 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
120 BtSpinLatch readwr[1]; // read/write page lock
121 BtSpinLatch access[1]; // Access Intent/Page delete
122 BtSpinLatch parent[1]; // Posting of fence key in parent
123 BtSpinLatch busy[1]; // slot is being moved between chains
124 volatile ushort next; // next entry in hash table chain
125 volatile ushort prev; // prev entry in hash table chain
126 volatile ushort pin; // number of outstanding locks
127 volatile ushort hash; // hash slot entry is under
128 volatile uid page_no; // latch set page number
131 // Define the length of the page and key pointers
135 // Page key slot definition.
137 // If BT_maxbits is 15 or less, you can save 4 bytes
138 // for each key stored by making the first two uints
139 // into ushorts. You can also save 4 bytes by removing
140 // the tod field from the key.
142 // Keys are marked dead, but remain on the page until
143 // it cleanup is called. The fence key (highest key) for
144 // the page is always present, even after cleanup.
147 uint off:BT_maxbits; // page offset for key start
148 uint dead:1; // set for deleted key
149 uint tod; // time-stamp for key
150 unsigned char id[BtId]; // id associated with key
153 // The key structure occupies space at the upper end of
154 // each page. It's a length byte followed by the value
159 unsigned char key[1];
162 // The first part of an index page.
163 // It is immediately followed
164 // by the BtSlot array of keys.
166 typedef struct BtPage_ {
167 uint cnt; // count of keys in page
168 uint act; // count of active keys
169 uint min; // next key offset
170 unsigned char bits:7; // page size in bits
171 unsigned char free:1; // page is on free chain
172 unsigned char lvl:4; // level of page
173 unsigned char kill:1; // page is being deleted
174 unsigned char dirty:1; // page has deleted keys
175 unsigned char posted:1; // page fence is posted
176 unsigned char goright:1; // page is being deleted, go right
177 unsigned char right[BtId]; // page number to right
178 unsigned char fence[256]; // page fence key
181 // The memory mapping pool table buffer manager entry
184 unsigned long long int lru; // number of times accessed
185 uid basepage; // mapped base page number
186 char *map; // mapped memory pointer
187 ushort slot; // slot index in this array
188 ushort pin; // mapped page pin counter
189 void *hashprev; // previous pool entry for the same hash idx
190 void *hashnext; // next pool entry for the same hash idx
192 HANDLE hmap; // Windows memory mapping handle
196 // The loadpage interface object
199 uid page_no; // current page number
200 BtPage page; // current page pointer
201 BtPool *pool; // current page pool
202 BtLatchSet *latch; // current page latch set
205 // structure for latch manager on ALLOC_page
208 struct BtPage_ alloc[2]; // next & free page_nos in right ptr
209 BtSpinLatch lock[1]; // allocation area lite latch
210 ushort latchdeployed; // highest number of latch entries deployed
211 ushort nlatchpage; // number of latch pages at BT_latch
212 ushort latchtotal; // number of page latch entries
213 ushort latchhash; // number of latch hash table slots
214 ushort latchvictim; // next latch entry to examine
215 BtHashEntry table[0]; // the hash table
218 // The object structure for Btree access
221 uint page_size; // page size
222 uint page_bits; // page size in bits
223 uint seg_bits; // seg size in pages in bits
224 uint mode; // read-write mode
230 ushort poolcnt; // highest page pool node in use
231 ushort poolmax; // highest page pool node allocated
232 ushort poolmask; // total number of pages in mmap segment - 1
233 ushort hashsize; // size of Hash Table for pool entries
234 volatile uint evicted; // last evicted hash table slot
235 ushort *hash; // pool index for hash entries
236 BtSpinLatch *latch; // latches for hash table slots
237 BtLatchMgr *latchmgr; // mapped latch page from allocation page
238 BtLatchSet *latchsets; // mapped latch set from latch pages
239 BtPool *pool; // memory pool page segments
241 HANDLE halloc; // allocation and latch table handle
246 BtMgr *mgr; // buffer manager for thread
247 BtPage cursor; // cached frame for start/next (never mapped)
248 BtPage frame; // spare frame for the page split (never mapped)
249 BtPage zero; // page frame for zeroes at end of file
250 uid cursor_page; // current cursor page number
251 unsigned char *mem; // frame, cursor, page memory buffer
252 int found; // last delete or insert was found
253 int err; // last error
267 extern void bt_close (BtDb *bt);
268 extern BtDb *bt_open (BtMgr *mgr);
269 extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod, uint lvl);
270 extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len);
271 extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
272 extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
273 extern uint bt_nextkey (BtDb *bt, uint slot);
275 // internal functions
276 BTERR bt_removepage (BtDb *bt, BtPageSet *set, uint lvl, unsigned char *pagefence);
279 extern BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolsize, uint segsize, uint hashsize);
280 void bt_mgrclose (BtMgr *mgr);
282 // Helper functions to return slot values
284 extern BtKey bt_key (BtDb *bt, uint slot);
285 extern uid bt_uid (BtDb *bt, uint slot);
286 extern uint bt_tod (BtDb *bt, uint slot);
288 // BTree page number constants
289 #define ALLOC_page 0 // allocation & lock manager hash table
290 #define ROOT_page 1 // root of the btree
291 #define LEAF_page 2 // first page of leaves
292 #define LATCH_page 3 // pages for lock manager
294 // Number of levels to create in a new BTree
298 // The page is allocated from low and hi ends.
299 // The key offsets and row-id's are allocated
300 // from the bottom, while the text of the key
301 // is allocated from the top. When the two
302 // areas meet, the page is split into two.
304 // A key consists of a length byte, two bytes of
305 // index number (0 - 65534), and up to 253 bytes
306 // of key value. Duplicate keys are discarded.
307 // Associated with each key is a 48 bit row-id.
309 // The b-tree root is always located at page 1.
310 // The first leaf page of level zero is always
311 // located on page 2.
313 // The b-tree pages are linked with next
314 // pointers to facilitate enumerators,
315 // and provide for concurrency.
317 // When to root page fills, it is split in two and
318 // the tree height is raised by a new root at page
319 // one with two keys.
321 // Deleted keys are marked with a dead bit until
322 // page cleanup. The fence key for a node is
323 // present in a special array
325 // Groups of pages called segments from the btree are optionally
326 // cached with a memory mapped pool. A hash table is used to keep
327 // track of the cached segments. This behaviour is controlled
328 // by the cache block size parameter to bt_open.
330 // To achieve maximum concurrency one page is locked at a time
331 // as the tree is traversed to find leaf key in question. The right
332 // page numbers are used in cases where the page is being split,
335 // Page 0 is dedicated to lock for new page extensions,
336 // and chains empty pages together for reuse.
338 // The ParentModification lock on a node is obtained to serialize posting
339 // or changing the fence key for a node.
341 // Empty pages are chained together through the ALLOC page and reused.
343 // Access macros to address slot and key values from the page
344 // Page slots use 1 based indexing.
346 #define slotptr(page, slot) (((BtSlot *)(page+1)) + (slot-1))
347 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
349 void bt_putid(unsigned char *dest, uid id)
354 dest[i] = (unsigned char)id, id >>= 8;
357 uid bt_getid(unsigned char *src)
362 for( i = 0; i < BtId; i++ )
363 id <<= 8, id |= *src++;
370 // wait until write lock mode is clear
371 // and add 1 to the share count
373 void bt_spinreadlock(BtSpinLatch *latch)
378 // obtain latch mutex
380 if( __sync_fetch_and_or((ushort *)latch, Mutex) & Mutex )
383 if( prev = _InterlockedOr16((ushort *)latch, Mutex) & Mutex )
386 // see if exclusive request is granted or pending
388 if( prev = !(latch->exclusive | latch->pending) )
390 __sync_fetch_and_add((ushort *)latch, Share);
392 _InterlockedExchangeAdd16 ((ushort *)latch, Share);
396 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
398 _InterlockedAnd16((ushort *)latch, ~Mutex);
404 } while( sched_yield(), 1 );
406 } while( SwitchToThread(), 1 );
410 // wait for other read and write latches to relinquish
412 void bt_spinwritelock(BtSpinLatch *latch)
416 if( __sync_fetch_and_or((ushort *)latch, Mutex | Pending) & Mutex )
419 if( _InterlockedOr16((ushort *)latch, Mutex | Pending) & Mutex )
422 if( !(latch->share | latch->exclusive) ) {
424 __sync_fetch_and_or((ushort *)latch, Write);
425 __sync_fetch_and_and ((ushort *)latch, ~(Mutex | Pending));
427 _InterlockedOr16((ushort *)latch, Write);
428 _InterlockedAnd16((ushort *)latch, ~(Mutex | Pending));
434 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
436 _InterlockedAnd16((ushort *)latch, ~Mutex);
440 } while( sched_yield(), 1 );
442 } while( SwitchToThread(), 1 );
446 // try to obtain write lock
448 // return 1 if obtained,
451 int bt_spinwritetry(BtSpinLatch *latch)
456 if( prev = __sync_fetch_and_or((ushort *)latch, Mutex), prev & Mutex )
459 if( prev = _InterlockedOr16((ushort *)latch, Mutex), prev & Mutex )
462 // take write access if all bits are clear
466 __sync_fetch_and_or ((ushort *)latch, Write);
468 _InterlockedOr16((ushort *)latch, Write);
472 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
474 _InterlockedAnd16((ushort *)latch, ~Mutex);
481 void bt_spinreleasewrite(BtSpinLatch *latch)
484 __sync_fetch_and_and ((ushort *)latch, ~Write);
486 _InterlockedAnd16((ushort *)latch, ~Write);
490 // decrement reader count
492 void bt_spinreleaseread(BtSpinLatch *latch)
495 __sync_fetch_and_add((ushort *)latch, -Share);
497 _InterlockedExchangeAdd16 ((ushort *)latch, -Share);
501 // link latch table entry into latch hash table
503 void bt_latchlink (BtDb *bt, ushort hashidx, ushort victim, uid page_no)
505 BtLatchSet *set = bt->mgr->latchsets + victim;
507 if( set->next = bt->mgr->latchmgr->table[hashidx].slot )
508 bt->mgr->latchsets[set->next].prev = victim;
510 bt->mgr->latchmgr->table[hashidx].slot = victim;
511 set->page_no = page_no;
518 void bt_unpinlatch (BtLatchSet *set)
521 __sync_fetch_and_add(&set->pin, -1);
523 _InterlockedDecrement16 (&set->pin);
527 // find existing latchset or inspire new one
528 // return with latchset pinned
530 BtLatchSet *bt_pinlatch (BtDb *bt, uid page_no)
532 ushort hashidx = page_no % bt->mgr->latchmgr->latchhash;
533 ushort slot, avail = 0, victim, idx;
536 // obtain read lock on hash table entry
538 bt_spinreadlock(bt->mgr->latchmgr->table[hashidx].latch);
540 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
542 set = bt->mgr->latchsets + slot;
543 if( page_no == set->page_no )
545 } while( slot = set->next );
549 __sync_fetch_and_add(&set->pin, 1);
551 _InterlockedIncrement16 (&set->pin);
555 bt_spinreleaseread (bt->mgr->latchmgr->table[hashidx].latch);
560 // try again, this time with write lock
562 bt_spinwritelock(bt->mgr->latchmgr->table[hashidx].latch);
564 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
566 set = bt->mgr->latchsets + slot;
567 if( page_no == set->page_no )
569 if( !set->pin && !avail )
571 } while( slot = set->next );
573 // found our entry, or take over an unpinned one
575 if( slot || (slot = avail) ) {
576 set = bt->mgr->latchsets + slot;
578 __sync_fetch_and_add(&set->pin, 1);
580 _InterlockedIncrement16 (&set->pin);
582 set->page_no = page_no;
583 bt_spinreleasewrite(bt->mgr->latchmgr->table[hashidx].latch);
587 // see if there are any unused entries
589 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, 1) + 1;
591 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchdeployed);
594 if( victim < bt->mgr->latchmgr->latchtotal ) {
595 set = bt->mgr->latchsets + victim;
597 __sync_fetch_and_add(&set->pin, 1);
599 _InterlockedIncrement16 (&set->pin);
601 bt_latchlink (bt, hashidx, victim, page_no);
602 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
607 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, -1);
609 victim = _InterlockedDecrement16 (&bt->mgr->latchmgr->latchdeployed);
611 // find and reuse previous lock entry
615 victim = __sync_fetch_and_add(&bt->mgr->latchmgr->latchvictim, 1);
617 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchvictim) - 1;
619 // we don't use slot zero
621 if( victim %= bt->mgr->latchmgr->latchtotal )
622 set = bt->mgr->latchsets + victim;
626 // take control of our slot
627 // from other threads
629 if( set->pin || !bt_spinwritetry (set->busy) )
634 // try to get write lock on hash chain
635 // skip entry if not obtained
636 // or has outstanding locks
638 if( !bt_spinwritetry (bt->mgr->latchmgr->table[idx].latch) ) {
639 bt_spinreleasewrite (set->busy);
644 bt_spinreleasewrite (set->busy);
645 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
649 // unlink our available victim from its hash chain
652 bt->mgr->latchsets[set->prev].next = set->next;
654 bt->mgr->latchmgr->table[idx].slot = set->next;
657 bt->mgr->latchsets[set->next].prev = set->prev;
659 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
661 __sync_fetch_and_add(&set->pin, 1);
663 _InterlockedIncrement16 (&set->pin);
665 bt_latchlink (bt, hashidx, victim, page_no);
666 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
667 bt_spinreleasewrite (set->busy);
672 void bt_mgrclose (BtMgr *mgr)
677 // release mapped pages
678 // note that slot zero is never used
680 for( slot = 1; slot < mgr->poolmax; slot++ ) {
681 pool = mgr->pool + slot;
684 munmap (pool->map, (mgr->poolmask+1) << mgr->page_bits);
687 FlushViewOfFile(pool->map, 0);
688 UnmapViewOfFile(pool->map);
689 CloseHandle(pool->hmap);
695 munmap (mgr->latchsets, mgr->latchmgr->nlatchpage * mgr->page_size);
696 munmap (mgr->latchmgr, mgr->page_size);
698 FlushViewOfFile(mgr->latchmgr, 0);
699 UnmapViewOfFile(mgr->latchmgr);
700 CloseHandle(mgr->halloc);
709 FlushFileBuffers(mgr->idx);
710 CloseHandle(mgr->idx);
711 GlobalFree (mgr->pool);
712 GlobalFree (mgr->hash);
713 GlobalFree (mgr->latch);
718 // close and release memory
720 void bt_close (BtDb *bt)
727 VirtualFree (bt->mem, 0, MEM_RELEASE);
732 // open/create new btree buffer manager
734 // call with file_name, BT_openmode, bits in page size (e.g. 16),
735 // size of mapped page pool (e.g. 8192)
737 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
739 uint lvl, attr, cacheblk, last, slot, idx;
740 uint nlatchpage, latchhash;
741 BtLatchMgr *latchmgr;
749 SYSTEM_INFO sysinfo[1];
752 // determine sanity of page size and buffer pool
754 if( bits > BT_maxbits )
756 else if( bits < BT_minbits )
760 return NULL; // must have buffer pool
763 mgr = calloc (1, sizeof(BtMgr));
765 mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
768 return free(mgr), NULL;
770 cacheblk = 4096; // minimum mmap segment size for unix
773 mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
774 attr = FILE_ATTRIBUTE_NORMAL;
775 mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
777 if( mgr->idx == INVALID_HANDLE_VALUE )
778 return GlobalFree(mgr), NULL;
780 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
781 GetSystemInfo(sysinfo);
782 cacheblk = sysinfo->dwAllocationGranularity;
786 latchmgr = malloc (BT_maxpage);
789 // read minimum page size to get root info
791 if( size = lseek (mgr->idx, 0L, 2) ) {
792 if( pread(mgr->idx, latchmgr, BT_minpage, 0) == BT_minpage )
793 bits = latchmgr->alloc->bits;
795 return free(mgr), free(latchmgr), NULL;
796 } else if( mode == BT_ro )
797 return free(latchmgr), bt_mgrclose (mgr), NULL;
799 latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
800 size = GetFileSize(mgr->idx, amt);
803 if( !ReadFile(mgr->idx, (char *)latchmgr, BT_minpage, amt, NULL) )
804 return bt_mgrclose (mgr), NULL;
805 bits = latchmgr->alloc->bits;
806 } else if( mode == BT_ro )
807 return bt_mgrclose (mgr), NULL;
810 mgr->page_size = 1 << bits;
811 mgr->page_bits = bits;
813 mgr->poolmax = poolmax;
816 if( cacheblk < mgr->page_size )
817 cacheblk = mgr->page_size;
819 // mask for partial memmaps
821 mgr->poolmask = (cacheblk >> bits) - 1;
823 // see if requested size of pages per memmap is greater
825 if( (1 << segsize) > mgr->poolmask )
826 mgr->poolmask = (1 << segsize) - 1;
830 while( (1 << mgr->seg_bits) <= mgr->poolmask )
833 mgr->hashsize = hashsize;
836 mgr->pool = calloc (poolmax, sizeof(BtPool));
837 mgr->hash = calloc (hashsize, sizeof(ushort));
838 mgr->latch = calloc (hashsize, sizeof(BtSpinLatch));
840 mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * sizeof(BtPool));
841 mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
842 mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtSpinLatch));
848 // initialize an empty b-tree with latch page, root page, page of leaves
849 // and page(s) of latches
851 memset (latchmgr, 0, 1 << bits);
852 nlatchpage = BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1;
853 bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
854 latchmgr->alloc->bits = mgr->page_bits;
856 latchmgr->nlatchpage = nlatchpage;
857 latchmgr->latchtotal = nlatchpage * (mgr->page_size / sizeof(BtLatchSet));
859 // initialize latch manager
861 latchhash = (mgr->page_size - sizeof(BtLatchMgr)) / sizeof(BtHashEntry);
863 // size of hash table = total number of latchsets
865 if( latchhash > latchmgr->latchtotal )
866 latchhash = latchmgr->latchtotal;
868 latchmgr->latchhash = latchhash;
871 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
872 return bt_mgrclose (mgr), NULL;
874 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
875 return bt_mgrclose (mgr), NULL;
877 if( *amt < mgr->page_size )
878 return bt_mgrclose (mgr), NULL;
881 memset (latchmgr, 0, 1 << bits);
882 latchmgr->alloc->bits = mgr->page_bits;
884 for( lvl=MIN_lvl; lvl--; ) {
885 slotptr(latchmgr->alloc, 1)->off = offsetof(struct BtPage_, fence);
886 bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
887 latchmgr->alloc->fence[0] = 2; // create stopper key
888 latchmgr->alloc->fence[1] = 0xff;
889 latchmgr->alloc->fence[2] = 0xff;
890 latchmgr->alloc->min = mgr->page_size;
891 latchmgr->alloc->lvl = lvl;
892 latchmgr->alloc->cnt = 1;
893 latchmgr->alloc->act = 1;
895 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
896 return bt_mgrclose (mgr), NULL;
898 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
899 return bt_mgrclose (mgr), NULL;
901 if( *amt < mgr->page_size )
902 return bt_mgrclose (mgr), NULL;
906 // clear out latch manager locks
907 // and rest of pages to round out segment
909 memset(latchmgr, 0, mgr->page_size);
912 while( last <= ((MIN_lvl + 1 + nlatchpage) | mgr->poolmask) ) {
914 pwrite(mgr->idx, latchmgr, mgr->page_size, last << mgr->page_bits);
916 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
917 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
918 return bt_mgrclose (mgr), NULL;
919 if( *amt < mgr->page_size )
920 return bt_mgrclose (mgr), NULL;
927 flag = PROT_READ | PROT_WRITE;
928 mgr->latchmgr = mmap (0, mgr->page_size, flag, MAP_SHARED, mgr->idx, ALLOC_page * mgr->page_size);
929 if( mgr->latchmgr == MAP_FAILED )
930 return bt_mgrclose (mgr), NULL;
931 mgr->latchsets = (BtLatchSet *)mmap (0, mgr->latchmgr->nlatchpage * mgr->page_size, flag, MAP_SHARED, mgr->idx, LATCH_page * mgr->page_size);
932 if( mgr->latchsets == MAP_FAILED )
933 return bt_mgrclose (mgr), NULL;
935 flag = PAGE_READWRITE;
936 mgr->halloc = CreateFileMapping(mgr->idx, NULL, flag, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size, NULL);
938 return bt_mgrclose (mgr), NULL;
940 flag = FILE_MAP_WRITE;
941 mgr->latchmgr = MapViewOfFile(mgr->halloc, flag, 0, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size);
943 return GetLastError(), bt_mgrclose (mgr), NULL;
945 mgr->latchsets = (void *)((char *)mgr->latchmgr + LATCH_page * mgr->page_size);
951 VirtualFree (latchmgr, 0, MEM_RELEASE);
956 // open BTree access method
957 // based on buffer manager
959 BtDb *bt_open (BtMgr *mgr)
961 BtDb *bt = malloc (sizeof(*bt));
963 memset (bt, 0, sizeof(*bt));
966 bt->mem = malloc (3 *mgr->page_size);
968 bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
970 bt->frame = (BtPage)bt->mem;
971 bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
972 bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
974 memset (bt->zero, 0, mgr->page_size);
978 // compare two keys, returning > 0, = 0, or < 0
979 // as the comparison value
981 int keycmp (BtKey key1, unsigned char *key2, uint len2)
983 uint len1 = key1->len;
986 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
999 // find segment in pool
1000 // must be called with hashslot idx locked
1001 // return NULL if not there
1002 // otherwise return node
1004 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
1009 // compute start of hash chain in pool
1011 if( slot = bt->mgr->hash[idx] )
1012 pool = bt->mgr->pool + slot;
1016 page_no &= ~bt->mgr->poolmask;
1018 while( pool->basepage != page_no )
1019 if( pool = pool->hashnext )
1027 // add segment to hash table
1029 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
1034 pool->hashprev = pool->hashnext = NULL;
1035 pool->basepage = page_no & ~bt->mgr->poolmask;
1038 if( slot = bt->mgr->hash[idx] ) {
1039 node = bt->mgr->pool + slot;
1040 pool->hashnext = node;
1041 node->hashprev = pool;
1044 bt->mgr->hash[idx] = pool->slot;
1047 // find best segment to evict from buffer pool
1049 BtPool *bt_findlru (BtDb *bt, uint hashslot)
1051 unsigned long long int target = ~0LL;
1052 BtPool *pool = NULL, *node;
1057 node = bt->mgr->pool + hashslot;
1059 // scan pool entries under hash table slot
1064 if( node->lru > target )
1068 } while( node = node->hashnext );
1073 // map new buffer pool segment to virtual memory
1075 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
1077 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
1078 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
1082 flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
1083 pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED | MAP_POPULATE, bt->mgr->idx, off);
1084 if( pool->map == MAP_FAILED )
1085 return bt->err = BTERR_map;
1088 flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
1089 pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
1091 return bt->err = BTERR_map;
1093 flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
1094 pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1096 return bt->err = BTERR_map;
1101 // calculate page within pool
1103 BtPage bt_page (BtDb *bt, BtPool *pool, uid page_no)
1105 uint subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1108 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1114 void bt_unpinpool (BtPool *pool)
1117 __sync_fetch_and_add(&pool->pin, -1);
1119 _InterlockedDecrement16 (&pool->pin);
1123 // find or place requested page in segment-pool
1124 // return pool table entry, incrementing pin
1126 BtPool *bt_pinpool(BtDb *bt, uid page_no)
1128 BtPool *pool, *node, *next;
1129 uint slot, idx, victim;
1131 // lock hash table chain
1133 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1134 bt_spinreadlock (&bt->mgr->latch[idx]);
1136 // look up in hash table
1138 if( pool = bt_findpool(bt, page_no, idx) ) {
1140 __sync_fetch_and_add(&pool->pin, 1);
1142 _InterlockedIncrement16 (&pool->pin);
1144 bt_spinreleaseread (&bt->mgr->latch[idx]);
1149 // upgrade to write lock
1151 bt_spinreleaseread (&bt->mgr->latch[idx]);
1152 bt_spinwritelock (&bt->mgr->latch[idx]);
1154 // try to find page in pool with write lock
1156 if( pool = bt_findpool(bt, page_no, idx) ) {
1158 __sync_fetch_and_add(&pool->pin, 1);
1160 _InterlockedIncrement16 (&pool->pin);
1162 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1167 // allocate a new pool node
1168 // and add to hash table
1171 slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
1173 slot = _InterlockedIncrement16 (&bt->mgr->poolcnt) - 1;
1176 if( ++slot < bt->mgr->poolmax ) {
1177 pool = bt->mgr->pool + slot;
1180 if( bt_mapsegment(bt, pool, page_no) )
1183 bt_linkhash(bt, pool, page_no, idx);
1185 __sync_fetch_and_add(&pool->pin, 1);
1187 _InterlockedIncrement16 (&pool->pin);
1189 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1193 // pool table is full
1194 // find best pool entry to evict
1197 __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
1199 _InterlockedDecrement16 (&bt->mgr->poolcnt);
1204 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
1206 victim = _InterlockedIncrement (&bt->mgr->evicted) - 1;
1208 victim %= bt->mgr->hashsize;
1210 // try to get write lock
1211 // skip entry if not obtained
1213 if( !bt_spinwritetry (&bt->mgr->latch[victim]) )
1216 // if pool entry is empty
1217 // or any pages are pinned
1220 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
1221 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1225 // unlink victim pool node from hash table
1227 if( node = pool->hashprev )
1228 node->hashnext = pool->hashnext;
1229 else if( node = pool->hashnext )
1230 bt->mgr->hash[victim] = node->slot;
1232 bt->mgr->hash[victim] = 0;
1234 if( node = pool->hashnext )
1235 node->hashprev = pool->hashprev;
1237 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1239 // remove old file mapping
1241 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1243 FlushViewOfFile(pool->map, 0);
1244 UnmapViewOfFile(pool->map);
1245 CloseHandle(pool->hmap);
1249 // create new pool mapping
1250 // and link into hash table
1252 if( bt_mapsegment(bt, pool, page_no) )
1255 bt_linkhash(bt, pool, page_no, idx);
1257 __sync_fetch_and_add(&pool->pin, 1);
1259 _InterlockedIncrement16 (&pool->pin);
1261 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1266 // place write, read, or parent lock on requested page_no.
1268 void bt_lockpage(BtLock mode, BtLatchSet *set)
1272 bt_spinreadlock (set->readwr);
1275 bt_spinwritelock (set->readwr);
1278 bt_spinreadlock (set->access);
1281 bt_spinwritelock (set->access);
1284 bt_spinwritelock (set->parent);
1289 // remove write, read, or parent lock on requested page
1291 void bt_unlockpage(BtLock mode, BtLatchSet *set)
1295 bt_spinreleaseread (set->readwr);
1298 bt_spinreleasewrite (set->readwr);
1301 bt_spinreleaseread (set->access);
1304 bt_spinreleasewrite (set->access);
1307 bt_spinreleasewrite (set->parent);
1312 // allocate a new page and write page into it
1314 uid bt_newpage(BtDb *bt, BtPage page)
1320 // lock allocation page
1322 bt_spinwritelock(bt->mgr->latchmgr->lock);
1324 // use empty chain first
1325 // else allocate empty page
1327 if( new_page = bt_getid(bt->mgr->latchmgr->alloc[1].right) ) {
1328 if( set->pool = bt_pinpool (bt, new_page) )
1329 set->page = bt_page (bt, set->pool, new_page);
1333 bt_putid(bt->mgr->latchmgr->alloc[1].right, bt_getid(set->page->right));
1334 bt_unpinpool (set->pool);
1337 new_page = bt_getid(bt->mgr->latchmgr->alloc->right);
1338 bt_putid(bt->mgr->latchmgr->alloc->right, new_page+1);
1342 if ( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1343 return bt->err = BTERR_wrt, 0;
1345 // if writing first page of pool block, zero last page in the block
1347 if ( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1349 // use zero buffer to write zeros
1350 if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1351 return bt->err = BTERR_wrt, 0;
1354 // bring new page into pool and copy page.
1355 // this will extend the file into the new pages.
1357 if( set->pool = bt_pinpool (bt, new_page) )
1358 set->page = bt_page (bt, set->pool, new_page);
1362 memcpy(set->page, page, bt->mgr->page_size);
1363 bt_unpinpool (set->pool);
1365 // unlock allocation latch and return new page no
1367 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1371 // find slot in page for given key at a given level
1373 int bt_findslot (BtPageSet *set, unsigned char *key, uint len)
1375 uint diff, higher = set->page->cnt, low = 1, slot;
1377 // make stopper key an infinite fence value
1379 if( bt_getid (set->page->right) )
1382 // low is the lowest candidate.
1383 // loop ends when they meet
1385 // higher is already
1386 // tested as .ge. the given key.
1388 while( diff = higher - low ) {
1389 slot = low + ( diff >> 1 );
1390 if( keycmp (keyptr(set->page, slot), key, len) < 0 )
1396 if( higher <= set->page->cnt )
1399 // if leaf page, compare against fence value
1401 // return zero if key is on right link page
1402 // or return slot beyond last key
1404 if( set->page->lvl || keycmp ((BtKey)set->page->fence, key, len) < 0 )
1410 // find and load page at given level for given key
1411 // leave page rd or wr locked as requested
1413 int bt_loadpage (BtDb *bt, BtPageSet *set, unsigned char *key, uint len, uint lvl, uint lock)
1415 uid page_no = ROOT_page, prevpage = 0;
1416 uint drill = 0xff, slot;
1417 BtLatchSet *prevlatch;
1418 uint mode, prevmode;
1421 // start at root of btree and drill down
1424 // determine lock mode of drill level
1425 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1427 set->latch = bt_pinlatch (bt, page_no);
1428 set->page_no = page_no;
1430 // pin page contents
1432 if( set->pool = bt_pinpool (bt, page_no) )
1433 set->page = bt_page (bt, set->pool, page_no);
1437 // obtain access lock using lock chaining with Access mode
1439 if( page_no > ROOT_page )
1440 bt_lockpage(BtLockAccess, set->latch);
1442 // release & unpin parent page
1445 bt_unlockpage(prevmode, prevlatch);
1446 bt_unpinlatch (prevlatch);
1447 bt_unpinpool (prevpool);
1451 // obtain read lock using lock chaining
1453 bt_lockpage(mode, set->latch);
1455 if( page_no > ROOT_page )
1456 bt_unlockpage(BtLockAccess, set->latch);
1458 // re-read and re-lock root after determining actual level of root
1460 if( set->page->lvl != drill) {
1461 if ( set->page_no != ROOT_page )
1462 return bt->err = BTERR_struct, 0;
1464 drill = set->page->lvl;
1466 if( lock == BtLockWrite && drill == lvl ) {
1467 bt_unlockpage(mode, set->latch);
1468 bt_unpinlatch (set->latch);
1469 bt_unpinpool (set->pool);
1474 prevpage = set->page_no;
1475 prevlatch = set->latch;
1476 prevpool = set->pool;
1479 // if page is being deleted and we should continue right
1481 if( set->page->kill && set->page->goright ) {
1482 page_no = bt_getid (set->page->right);
1486 // otherwise, wait for deleted node to clear
1488 if( set->page->kill ) {
1489 bt_unlockpage(mode, set->latch);
1490 bt_unpinlatch (set->latch);
1491 bt_unpinpool (set->pool);
1492 page_no = ROOT_page;
1503 // find key on page at this level
1504 // and descend to requested level
1506 if( slot = bt_findslot (set, key, len) ) {
1510 if( slot > set->page->cnt )
1511 return bt->err = BTERR_struct;
1513 while( slotptr(set->page, slot)->dead )
1514 if( slot++ < set->page->cnt )
1517 return bt->err = BTERR_struct, 0;
1519 page_no = bt_getid(slotptr(set->page, slot)->id);
1524 // or slide right into next page
1526 page_no = bt_getid(set->page->right);
1530 // return error on end of right chain
1532 bt->err = BTERR_struct;
1533 return 0; // return error
1536 // drill down fixing fence values for left sibling tree
1538 // call with set write locked
1539 // return with set unlocked & unpinned.
1541 BTERR bt_fixfences (BtDb *bt, BtPageSet *set, unsigned char *newfence)
1543 unsigned char oldfence[256];
1547 memcpy (oldfence, set->page->fence, 256);
1548 next->page_no = bt_getid(slotptr(set->page, set->page->cnt)->id);
1550 while( !set->page->kill && set->page->lvl ) {
1551 next->latch = bt_pinlatch (bt, next->page_no);
1552 bt_lockpage (BtLockParent, next->latch);
1553 bt_lockpage (BtLockAccess, next->latch);
1554 bt_lockpage (BtLockWrite, next->latch);
1555 bt_unlockpage (BtLockAccess, next->latch);
1557 if( next->pool = bt_pinpool (bt, next->page_no) )
1558 next->page = bt_page (bt, next->pool, next->page_no);
1562 chk = keycmp ((BtKey)next->page->fence, oldfence + 1, *oldfence);
1565 next->page_no = bt_getid (next->page->right);
1566 bt_unlockpage (BtLockWrite, next->latch);
1567 bt_unlockpage (BtLockParent, next->latch);
1568 bt_unpinlatch (next->latch);
1569 bt_unpinpool (next->pool);
1574 return bt->err = BTERR_struct;
1576 if( bt_fixfences (bt, next, newfence) )
1582 memcpy (set->page->fence, newfence, 256);
1584 bt_unlockpage (BtLockWrite, set->latch);
1585 bt_unlockpage (BtLockParent, set->latch);
1586 bt_unpinlatch (set->latch);
1587 bt_unpinpool (set->pool);
1591 // return page to free list
1592 // page must be delete & write locked
1594 void bt_freepage (BtDb *bt, BtPageSet *set)
1596 // lock allocation page
1598 bt_spinwritelock (bt->mgr->latchmgr->lock);
1600 // store chain in second right
1601 bt_putid(set->page->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1602 bt_putid(bt->mgr->latchmgr->alloc[1].right, set->page_no);
1603 set->page->free = 1;
1605 // unlock released page
1607 bt_unlockpage (BtLockDelete, set->latch);
1608 bt_unlockpage (BtLockWrite, set->latch);
1609 bt_unpinlatch (set->latch);
1610 bt_unpinpool (set->pool);
1612 // unlock allocation page
1614 bt_spinreleasewrite (bt->mgr->latchmgr->lock);
1617 // remove the root level by promoting its only child
1618 // call with parent and child pages
1620 BTERR bt_removeroot (BtDb *bt, BtPageSet *root, BtPageSet *child)
1626 child->latch = bt_pinlatch (bt, next);
1627 bt_lockpage (BtLockDelete, child->latch);
1628 bt_lockpage (BtLockWrite, child->latch);
1630 if( child->pool = bt_pinpool (bt, next) )
1631 child->page = bt_page (bt, child->pool, next);
1635 child->page_no = next;
1638 memcpy (root->page, child->page, bt->mgr->page_size);
1639 next = bt_getid (slotptr(child->page, child->page->cnt)->id);
1640 bt_freepage (bt, child);
1641 } while( root->page->lvl > 1 && root->page->cnt == 1 );
1643 bt_unlockpage (BtLockWrite, root->latch);
1644 bt_unpinlatch (root->latch);
1645 bt_unpinpool (root->pool);
1649 // pull right page over ourselves in simple merge
1651 BTERR bt_mergeright (BtDb *bt, BtPageSet *set, BtPageSet *parent, BtPageSet *right, uint slot, uint idx)
1653 // install ourselves as child page
1654 // and delete ourselves from parent
1656 bt_putid (slotptr(parent->page, idx)->id, set->page_no);
1657 slotptr(parent->page, slot)->dead = 1;
1658 parent->page->act--;
1660 // collapse any empty slots
1662 while( idx = parent->page->cnt - 1 )
1663 if( slotptr(parent->page, idx)->dead ) {
1664 *slotptr(parent->page, idx) = *slotptr(parent->page, idx + 1);
1665 memset (slotptr(parent->page, parent->page->cnt--), 0, sizeof(BtSlot));
1669 memcpy (set->page, right->page, bt->mgr->page_size);
1670 bt_unlockpage (BtLockParent, right->latch);
1672 bt_freepage (bt, right);
1674 // do we need to remove a btree level?
1675 // (leave the first page of leaves alone)
1677 if( parent->page_no == ROOT_page && parent->page->cnt == 1 )
1678 if( set->page->lvl )
1679 return bt_removeroot (bt, parent, set);
1681 bt_unlockpage (BtLockWrite, parent->latch);
1682 bt_unlockpage (BtLockDelete, set->latch);
1683 bt_unlockpage (BtLockWrite, set->latch);
1684 bt_unpinlatch (parent->latch);
1685 bt_unpinpool (parent->pool);
1686 bt_unpinlatch (set->latch);
1687 bt_unpinpool (set->pool);
1691 // remove both child and parent from the btree
1692 // from the fence position in the parent
1693 // call with both pages locked for writing
1695 BTERR bt_removeparent (BtDb *bt, BtPageSet *child, BtPageSet *parent, BtPageSet *right, BtPageSet *rparent, uint lvl)
1697 unsigned char pagefence[256];
1700 // pull right sibling over ourselves and unlock
1702 memcpy (child->page, right->page, bt->mgr->page_size);
1704 bt_unlockpage (BtLockWrite, child->latch);
1705 bt_unpinlatch (child->latch);
1706 bt_unpinpool (child->pool);
1708 // install ourselves into right link of old right page
1710 bt_putid (right->page->right, child->page_no);
1711 right->page->goright = 1; // tell bt_loadpage to go right to us
1712 right->page->kill = 1;
1714 bt_unlockpage (BtLockWrite, right->latch);
1716 // remove our slot from our parent
1717 // signal to move right
1719 parent->page->goright = 1; // tell bt_loadpage to go right to rparent
1720 parent->page->kill = 1;
1721 parent->page->act--;
1723 // redirect right page pointer in right parent to us
1725 for( idx = 0; idx++ < rparent->page->cnt; )
1726 if( !slotptr(rparent->page, idx)->dead )
1729 if( bt_getid (slotptr(rparent->page, idx)->id) != right->page_no )
1730 return bt->err = BTERR_struct;
1732 bt_putid (slotptr(rparent->page, idx)->id, child->page_no);
1733 bt_unlockpage (BtLockWrite, rparent->latch);
1734 bt_unpinlatch (rparent->latch);
1735 bt_unpinpool (rparent->pool);
1737 // free the right page
1739 bt_lockpage (BtLockDelete, right->latch);
1740 bt_lockpage (BtLockWrite, right->latch);
1741 bt_freepage (bt, right);
1743 // save parent page fence value
1745 memcpy (pagefence, parent->page->fence, 256);
1746 bt_unlockpage (BtLockWrite, parent->latch);
1748 return bt_removepage (bt, parent, lvl, pagefence);
1751 // remove page from btree
1752 // call with page unlocked
1753 // returns with page on free list
1755 BTERR bt_removepage (BtDb *bt, BtPageSet *set, uint lvl, unsigned char *pagefence)
1757 BtPageSet parent[1], sibling[1], rparent[1];
1758 unsigned char newfence[256];
1762 // load and lock our parent
1765 if( !(slot = bt_loadpage (bt, parent, pagefence+1, *pagefence, lvl+1, BtLockWrite)) )
1768 // do we show up in our parent yet?
1770 if( set->page_no != bt_getid (slotptr (parent->page, slot)->id) ) {
1771 bt_unlockpage (BtLockWrite, parent->latch);
1772 bt_unpinlatch (parent->latch);
1773 bt_unpinpool (parent->pool);
1782 // can we do a simple merge entirely
1783 // between siblings on the parent page?
1785 if( slot < parent->page->cnt ) {
1786 // find our right neighbor
1787 // right must exist because the stopper prevents
1788 // the rightmost page from deleting
1790 for( idx = slot; idx++ < parent->page->cnt; )
1791 if( !slotptr(parent->page, idx)->dead )
1794 sibling->page_no = bt_getid (slotptr (parent->page, idx)->id);
1796 bt_lockpage (BtLockDelete, set->latch);
1797 bt_lockpage (BtLockWrite, set->latch);
1799 // merge right if sibling shows up in
1800 // our parent and is not being killed
1802 if( sibling->page_no == bt_getid (set->page->right) ) {
1803 sibling->latch = bt_pinlatch (bt, sibling->page_no);
1804 bt_lockpage (BtLockParent, sibling->latch);
1805 bt_lockpage (BtLockDelete, sibling->latch);
1806 bt_lockpage (BtLockWrite, sibling->latch);
1808 if( sibling->pool = bt_pinpool (bt, sibling->page_no) )
1809 sibling->page = bt_page (bt, sibling->pool, sibling->page_no);
1813 if( !sibling->page->kill )
1814 return bt_mergeright(bt, set, parent, sibling, slot, idx);
1818 bt_unlockpage (BtLockWrite, sibling->latch);
1819 bt_unlockpage (BtLockParent, sibling->latch);
1820 bt_unlockpage (BtLockDelete, sibling->latch);
1821 bt_unpinlatch (sibling->latch);
1822 bt_unpinpool (sibling->pool);
1825 bt_unlockpage (BtLockDelete, set->latch);
1826 bt_unlockpage (BtLockWrite, set->latch);
1827 bt_unlockpage (BtLockWrite, parent->latch);
1828 bt_unpinlatch (parent->latch);
1829 bt_unpinpool (parent->pool);
1838 // find our left neighbor in our parent page
1840 for( idx = slot; --idx; )
1841 if( !slotptr(parent->page, idx)->dead )
1844 // if no left neighbor, delete ourselves and our parent
1847 bt_lockpage (BtLockAccess, set->latch);
1848 bt_lockpage (BtLockWrite, set->latch);
1849 bt_unlockpage (BtLockAccess, set->latch);
1851 rparent->page_no = bt_getid (parent->page->right);
1852 rparent->latch = bt_pinlatch (bt, rparent->page_no);
1854 bt_lockpage (BtLockAccess, rparent->latch);
1855 bt_lockpage (BtLockWrite, rparent->latch);
1856 bt_unlockpage (BtLockAccess, rparent->latch);
1858 if( rparent->pool = bt_pinpool (bt, rparent->page_no) )
1859 rparent->page = bt_page (bt, rparent->pool, rparent->page_no);
1863 if( !rparent->page->kill ) {
1864 sibling->page_no = bt_getid (set->page->right);
1865 sibling->latch = bt_pinlatch (bt, sibling->page_no);
1867 bt_lockpage (BtLockAccess, sibling->latch);
1868 bt_lockpage (BtLockWrite, sibling->latch);
1869 bt_unlockpage (BtLockAccess, sibling->latch);
1871 if( sibling->pool = bt_pinpool (bt, sibling->page_no) )
1872 sibling->page = bt_page (bt, sibling->pool, sibling->page_no);
1876 if( !sibling->page->kill )
1877 return bt_removeparent (bt, set, parent, sibling, rparent, lvl+1);
1881 bt_unlockpage (BtLockWrite, sibling->latch);
1882 bt_unpinlatch (sibling->latch);
1883 bt_unpinpool (sibling->pool);
1886 bt_unlockpage (BtLockWrite, set->latch);
1887 bt_unlockpage (BtLockWrite, rparent->latch);
1888 bt_unpinlatch (rparent->latch);
1889 bt_unpinpool (rparent->pool);
1891 bt_unlockpage (BtLockWrite, parent->latch);
1892 bt_unpinlatch (parent->latch);
1893 bt_unpinpool (parent->pool);
1902 // redirect parent to our left sibling
1903 // lock and map our left sibling's page
1905 sibling->page_no = bt_getid (slotptr(parent->page, idx)->id);
1906 sibling->latch = bt_pinlatch (bt, sibling->page_no);
1908 // wait our turn on fence key maintenance
1910 bt_lockpage(BtLockParent, sibling->latch);
1911 bt_lockpage(BtLockAccess, sibling->latch);
1912 bt_lockpage(BtLockWrite, sibling->latch);
1913 bt_unlockpage(BtLockAccess, sibling->latch);
1915 if( sibling->pool = bt_pinpool (bt, sibling->page_no) )
1916 sibling->page = bt_page (bt, sibling->pool, sibling->page_no);
1920 // wait until left sibling is in our parent
1922 if( bt_getid (sibling->page->right) != set->page_no ) {
1923 bt_unlockpage (BtLockWrite, parent->latch);
1924 bt_unlockpage (BtLockWrite, sibling->latch);
1925 bt_unlockpage (BtLockParent, sibling->latch);
1926 bt_unpinlatch (parent->latch);
1927 bt_unpinpool (parent->pool);
1928 bt_unpinlatch (sibling->latch);
1929 bt_unpinpool (sibling->pool);
1938 // delete our left sibling from parent
1940 slotptr(parent->page,idx)->dead = 1;
1941 parent->page->dirty = 1;
1942 parent->page->act--;
1944 // redirect our parent slot to our left sibling
1946 bt_putid (slotptr(parent->page, slot)->id, sibling->page_no);
1947 memcpy (sibling->page->right, set->page->right, BtId);
1949 // collapse dead slots from parent
1951 while( idx = parent->page->cnt - 1 )
1952 if( slotptr(parent->page, idx)->dead ) {
1953 *slotptr(parent->page, idx) = *slotptr(parent->page, parent->page->cnt);
1954 memset (slotptr(parent->page, parent->page->cnt--), 0, sizeof(BtSlot));
1958 // free our original page
1960 bt_lockpage (BtLockDelete, set->latch);
1961 bt_lockpage (BtLockWrite, set->latch);
1962 bt_freepage (bt, set);
1964 // go down the left node's fence keys to the leaf level
1965 // and update the fence keys in each page
1967 memcpy (newfence, parent->page->fence, 256);
1969 if( bt_fixfences (bt, sibling, newfence) )
1972 // promote sibling as new root?
1974 if( parent->page_no == ROOT_page && parent->page->cnt == 1 )
1975 if( sibling->page->lvl ) {
1976 sibling->latch = bt_pinlatch (bt, sibling->page_no);
1977 bt_lockpage (BtLockDelete, sibling->latch);
1978 bt_lockpage (BtLockWrite, sibling->latch);
1980 if( sibling->pool = bt_pinpool (bt, sibling->page_no) )
1981 sibling->page = bt_page (bt, sibling->pool, sibling->page_no);
1985 return bt_removeroot (bt, parent, sibling);
1988 bt_unlockpage (BtLockWrite, parent->latch);
1989 bt_unpinlatch (parent->latch);
1990 bt_unpinpool (parent->pool);
1996 // find and delete key on page by marking delete flag bit
1997 // if page becomes empty, delete it from the btree
1999 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len)
2001 unsigned char pagefence[256];
2002 uint slot, idx, found;
2006 if( slot = bt_loadpage (bt, set, key, len, 0, BtLockWrite) )
2007 ptr = keyptr(set->page, slot);
2011 // if key is found delete it, otherwise ignore request
2013 if( found = slot <= set->page->cnt )
2014 if( found = !keycmp (ptr, key, len) )
2015 if( found = slotptr(set->page, slot)->dead == 0 ) {
2016 slotptr(set->page,slot)->dead = 1;
2017 set->page->dirty = 1;
2020 // collapse empty slots
2022 while( idx = set->page->cnt - 1 )
2023 if( slotptr(set->page, idx)->dead ) {
2024 *slotptr(set->page, idx) = *slotptr(set->page, idx + 1);
2025 memset (slotptr(set->page, set->page->cnt--), 0, sizeof(BtSlot));
2030 if( set->page->act ) {
2031 bt_unlockpage(BtLockWrite, set->latch);
2032 bt_unpinlatch (set->latch);
2033 bt_unpinpool (set->pool);
2034 return bt->found = found, 0;
2037 memcpy (pagefence, set->page->fence, 256);
2038 set->page->kill = 1;
2040 bt_unlockpage (BtLockWrite, set->latch);
2042 if( bt_removepage (bt, set, 0, pagefence) )
2049 // find key in leaf level and return row-id
2051 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
2058 if( slot = bt_loadpage (bt, set, key, len, 0, BtLockRead) )
2059 ptr = keyptr(set->page, slot);
2063 // if key exists, return row-id
2064 // otherwise return 0
2066 if( slot <= set->page->cnt )
2067 if( !keycmp (ptr, key, len) )
2068 id = bt_getid(slotptr(set->page,slot)->id);
2070 bt_unlockpage (BtLockRead, set->latch);
2071 bt_unpinlatch (set->latch);
2072 bt_unpinpool (set->pool);
2076 // check page for space available,
2077 // clean if necessary and return
2078 // 0 - page needs splitting
2079 // >0 new slot value
2081 uint bt_cleanpage(BtDb *bt, BtPage page, uint amt, uint slot)
2083 uint nxt = bt->mgr->page_size, off;
2084 uint cnt = 0, idx = 0;
2085 uint max = page->cnt;
2089 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
2092 // skip cleanup if nothing to reclaim
2097 memcpy (bt->frame, page, bt->mgr->page_size);
2099 // skip page info and set rest of page to zero
2101 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
2105 // try cleaning up page first
2106 // by removing deleted keys
2108 while( cnt++ < max ) {
2111 if( slotptr(bt->frame,cnt)->dead )
2114 // if its not the fence key,
2115 // copy the key across
2117 off = slotptr(bt->frame,cnt)->off;
2119 if( off >= sizeof(*page) ) {
2120 key = keyptr(bt->frame, cnt);
2121 off = nxt -= key->len + 1;
2122 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2127 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
2128 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2129 slotptr(page, idx)->off = off;
2136 // see if page has enough space now, or does it need splitting?
2138 if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
2144 // split the root and raise the height of the btree
2146 BTERR bt_splitroot(BtDb *bt, BtPageSet *root, uid page_no2)
2148 uint nxt = bt->mgr->page_size;
2149 unsigned char leftkey[256];
2152 // Obtain an empty page to use, and copy the current
2153 // root contents into it, e.g. lower keys
2155 memcpy (leftkey, root->page->fence, 256);
2156 root->page->posted = 1;
2158 if( !(new_page = bt_newpage(bt, root->page)) )
2161 // preserve the page info at the bottom
2162 // of higher keys and set rest to zero
2164 memset(root->page+1, 0, bt->mgr->page_size - sizeof(*root->page));
2165 memset(root->page->fence, 0, 256);
2166 root->page->fence[0] = 2;
2167 root->page->fence[1] = 0xff;
2168 root->page->fence[2] = 0xff;
2170 // insert lower keys page fence key on newroot page
2172 nxt -= *leftkey + 1;
2173 memcpy ((unsigned char *)root->page + nxt, leftkey, *leftkey + 1);
2174 bt_putid(slotptr(root->page, 1)->id, new_page);
2175 slotptr(root->page, 1)->off = nxt;
2177 // insert stopper key on newroot page
2178 // and increase the root height
2180 bt_putid(slotptr(root->page, 2)->id, page_no2);
2181 slotptr(root->page, 2)->off = offsetof(struct BtPage_, fence);
2183 bt_putid(root->page->right, 0);
2184 root->page->min = nxt; // reset lowest used offset and key count
2185 root->page->cnt = 2;
2186 root->page->act = 2;
2189 // release and unpin root
2191 bt_unlockpage(BtLockWrite, root->latch);
2192 bt_unpinlatch (root->latch);
2193 bt_unpinpool (root->pool);
2197 // split already locked full node
2200 BTERR bt_splitpage (BtDb *bt, BtPageSet *set)
2202 uint cnt = 0, idx = 0, max, nxt = bt->mgr->page_size, off;
2203 unsigned char fencekey[256];
2204 uint lvl = set->page->lvl;
2208 // split higher half of keys to bt->frame
2210 memset (bt->frame, 0, bt->mgr->page_size);
2211 max = set->page->cnt;
2215 while( cnt++ < max ) {
2216 if( !lvl || cnt < max ) {
2217 key = keyptr(set->page, cnt);
2218 off = nxt -= key->len + 1;
2219 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
2221 off = offsetof(struct BtPage_, fence);
2223 memcpy(slotptr(bt->frame,++idx)->id, slotptr(set->page,cnt)->id, BtId);
2224 slotptr(bt->frame, idx)->tod = slotptr(set->page, cnt)->tod;
2225 slotptr(bt->frame, idx)->off = off;
2229 if( set->page_no == ROOT_page )
2230 bt->frame->posted = 1;
2232 memcpy (bt->frame->fence, set->page->fence, 256);
2233 bt->frame->bits = bt->mgr->page_bits;
2234 bt->frame->min = nxt;
2235 bt->frame->cnt = idx;
2236 bt->frame->lvl = lvl;
2240 if( set->page_no > ROOT_page )
2241 memcpy (bt->frame->right, set->page->right, BtId);
2243 // get new free page and write higher keys to it.
2245 if( !(right = bt_newpage(bt, bt->frame)) )
2248 // update lower keys to continue in old page
2250 memcpy (bt->frame, set->page, bt->mgr->page_size);
2251 memset (set->page+1, 0, bt->mgr->page_size - sizeof(*set->page));
2252 nxt = bt->mgr->page_size;
2253 set->page->posted = 0;
2254 set->page->dirty = 0;
2259 // assemble page of smaller keys
2261 while( cnt++ < max / 2 ) {
2262 key = keyptr(bt->frame, cnt);
2264 if( !lvl || cnt < max / 2 ) {
2265 off = nxt -= key->len + 1;
2266 memcpy ((unsigned char *)set->page + nxt, key, key->len + 1);
2268 off = offsetof(struct BtPage_, fence);
2270 memcpy(slotptr(set->page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
2271 slotptr(set->page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2272 slotptr(set->page, idx)->off = off;
2276 // install fence key for smaller key page
2278 memset(set->page->fence, 0, 256);
2279 memcpy(set->page->fence, key, key->len + 1);
2281 bt_putid(set->page->right, right);
2282 set->page->min = nxt;
2283 set->page->cnt = idx;
2285 // if current page is the root page, split it
2287 if( set->page_no == ROOT_page )
2288 return bt_splitroot (bt, set, right);
2290 bt_unlockpage (BtLockWrite, set->latch);
2292 // insert new fences in their parent pages
2295 bt_lockpage (BtLockParent, set->latch);
2296 bt_lockpage (BtLockWrite, set->latch);
2298 memcpy (fencekey, set->page->fence, 256);
2299 right = bt_getid (set->page->right);
2301 if( set->page->posted ) {
2302 bt_unlockpage (BtLockParent, set->latch);
2303 bt_unlockpage (BtLockWrite, set->latch);
2304 bt_unpinlatch (set->latch);
2305 bt_unpinpool (set->pool);
2309 set->page->posted = 1;
2310 bt_unlockpage (BtLockWrite, set->latch);
2312 if( bt_insertkey (bt, fencekey+1, *fencekey, set->page_no, time(NULL), lvl+1) )
2315 bt_unlockpage (BtLockParent, set->latch);
2316 bt_unpinlatch (set->latch);
2317 bt_unpinpool (set->pool);
2319 if( !(set->page_no = right) )
2322 set->latch = bt_pinlatch (bt, right);
2324 if( set->pool = bt_pinpool (bt, right) )
2325 set->page = bt_page (bt, set->pool, right);
2333 // Insert new key into the btree at given level.
2335 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod, uint lvl)
2342 if( slot = bt_loadpage (bt, set, key, len, lvl, BtLockWrite) )
2343 ptr = keyptr(set->page, slot);
2347 bt->err = BTERR_ovflw;
2351 // if key already exists, update id and return
2353 if( slot <= set->page->cnt )
2354 if( !keycmp (ptr, key, len) ) {
2355 if( slotptr(set->page, slot)->dead )
2357 slotptr(set->page, slot)->dead = 0;
2358 slotptr(set->page, slot)->tod = tod;
2359 bt_putid(slotptr(set->page,slot)->id, id);
2360 bt_unlockpage(BtLockWrite, set->latch);
2361 bt_unpinlatch (set->latch);
2362 bt_unpinpool (set->pool);
2366 // check if page has enough space
2368 if( slot = bt_cleanpage (bt, set->page, len, slot) )
2371 if( bt_splitpage (bt, set) )
2375 // calculate next available slot and copy key into page
2377 set->page->min -= len + 1; // reset lowest used offset
2378 ((unsigned char *)set->page)[set->page->min] = len;
2379 memcpy ((unsigned char *)set->page + set->page->min +1, key, len );
2381 for( idx = slot; idx <= set->page->cnt; idx++ )
2382 if( slotptr(set->page, idx)->dead )
2385 // now insert key into array before slot
2387 if( idx > set->page->cnt )
2393 *slotptr(set->page, idx) = *slotptr(set->page, idx -1), idx--;
2395 bt_putid(slotptr(set->page,slot)->id, id);
2396 slotptr(set->page, slot)->off = set->page->min;
2397 slotptr(set->page, slot)->tod = tod;
2398 slotptr(set->page, slot)->dead = 0;
2400 bt_unlockpage (BtLockWrite, set->latch);
2401 bt_unpinlatch (set->latch);
2402 bt_unpinpool (set->pool);
2406 // cache page of keys into cursor and return starting slot for given key
2408 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2413 // cache page for retrieval
2415 if( slot = bt_loadpage (bt, set, key, len, 0, BtLockRead) )
2416 memcpy (bt->cursor, set->page, bt->mgr->page_size);
2420 bt->cursor_page = set->page_no;
2422 bt_unlockpage(BtLockRead, set->latch);
2423 bt_unpinlatch (set->latch);
2424 bt_unpinpool (set->pool);
2428 // return next slot for cursor page
2429 // or slide cursor right into next page
2431 uint bt_nextkey (BtDb *bt, uint slot)
2437 right = bt_getid(bt->cursor->right);
2438 while( slot++ < bt->cursor->cnt )
2439 if( slotptr(bt->cursor,slot)->dead )
2441 else if( right || (slot < bt->cursor->cnt) ) // skip infinite stopper
2449 bt->cursor_page = right;
2451 if( set->pool = bt_pinpool (bt, right) )
2452 set->page = bt_page (bt, set->pool, right);
2456 set->latch = bt_pinlatch (bt, right);
2457 bt_lockpage(BtLockRead, set->latch);
2459 memcpy (bt->cursor, set->page, bt->mgr->page_size);
2461 bt_unlockpage(BtLockRead, set->latch);
2462 bt_unpinlatch (set->latch);
2463 bt_unpinpool (set->pool);
2470 BtKey bt_key(BtDb *bt, uint slot)
2472 return keyptr(bt->cursor, slot);
2475 uid bt_uid(BtDb *bt, uint slot)
2477 return bt_getid(slotptr(bt->cursor,slot)->id);
2480 uint bt_tod(BtDb *bt, uint slot)
2482 return slotptr(bt->cursor,slot)->tod;
2488 void bt_latchaudit (BtDb *bt)
2490 ushort idx, hashidx;
2497 for( idx = 1; idx < bt->mgr->latchmgr->latchdeployed; idx++ ) {
2498 latch = bt->mgr->latchsets + idx;
2499 if( *(ushort *)latch->readwr ) {
2500 fprintf(stderr, "latchset %d r/w locked for page %.8x\n", idx, latch->page_no);
2501 *(ushort *)latch->readwr = 0;
2503 if( *(ushort *)latch->access ) {
2504 fprintf(stderr, "latchset %d access locked for page %.8x\n", idx, latch->page_no);
2505 *(ushort *)latch->access = 0;
2507 if( *(ushort *)latch->parent ) {
2508 fprintf(stderr, "latchset %d parent locked for page %.8x\n", idx, latch->page_no);
2509 *(ushort *)latch->parent = 0;
2511 if( *(ushort *)latch->busy ) {
2512 fprintf(stderr, "latchset %d busy locked for page %.8x\n", idx, latch->page_no);
2513 *(ushort *)latch->parent = 0;
2516 fprintf(stderr, "latchset %d pinned for page %.8x\n", idx, latch->page_no);
2521 for( hashidx = 0; hashidx < bt->mgr->latchmgr->latchhash; hashidx++ ) {
2522 if( idx = bt->mgr->latchmgr->table[hashidx].slot ) do {
2523 latch = bt->mgr->latchsets + idx;
2524 if( latch->hash != hashidx ) {
2525 fprintf(stderr, "latchset %d wrong hashidx\n", idx);
2526 latch->hash = hashidx;
2528 } while( idx = latch->next );
2531 page_no = bt_getid(bt->mgr->latchmgr->alloc[1].right);
2534 fprintf(stderr, "free: %.6x\n", (uint)page_no);
2536 if( pool = bt_pinpool (bt, page_no) )
2537 page = bt_page (bt, pool, page_no);
2541 page_no = bt_getid(page->right);
2542 bt_unpinpool (pool);
2554 // standalone program to index file of keys
2555 // then list them onto std-out
2558 void *index_file (void *arg)
2560 uint __stdcall index_file (void *arg)
2563 int line = 0, found = 0, cnt = 0;
2564 uid next, page_no = LEAF_page; // start on first page of leaves
2565 unsigned char key[256];
2566 ThreadArg *args = arg;
2567 int ch, len = 0, slot;
2574 bt = bt_open (args->mgr);
2577 switch(args->type | 0x20)
2580 fprintf(stderr, "started latch mgr audit\n");
2582 fprintf(stderr, "finished latch mgr audit\n");
2586 fprintf(stderr, "started indexing for %s\n", args->infile);
2587 if( in = fopen (args->infile, "rb") )
2588 while( ch = getc(in), ch != EOF )
2593 if( args->num == 1 )
2594 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2596 else if( args->num )
2597 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2599 if( bt_insertkey (bt, key, len, line, *tod, 0) )
2600 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2603 else if( len < 255 )
2605 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
2609 fprintf(stderr, "started deleting keys for %s\n", args->infile);
2610 if( in = fopen (args->infile, "rb") )
2611 while( ch = getc(in), ch != EOF )
2615 if( args->num == 1 )
2616 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2618 else if( args->num )
2619 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2621 if( bt_deletekey (bt, key, len) )
2622 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2625 else if( len < 255 )
2627 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2631 fprintf(stderr, "started finding keys for %s\n", args->infile);
2632 if( in = fopen (args->infile, "rb") )
2633 while( ch = getc(in), ch != EOF )
2637 if( args->num == 1 )
2638 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2640 else if( args->num )
2641 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2643 if( bt_findkey (bt, key, len) )
2646 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2649 else if( len < 255 )
2651 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2655 fprintf(stderr, "started scanning\n");
2657 if( set->pool = bt_pinpool (bt, page_no) )
2658 set->page = bt_page (bt, set->pool, page_no);
2661 set->latch = bt_pinlatch (bt, page_no);
2662 bt_lockpage (BtLockRead, set->latch);
2663 next = bt_getid (set->page->right);
2664 cnt += set->page->act;
2666 for( slot = 0; slot++ < set->page->cnt; )
2667 if( next || slot < set->page->cnt )
2668 if( !slotptr(set->page, slot)->dead ) {
2669 ptr = keyptr(set->page, slot);
2670 fwrite (ptr->key, ptr->len, 1, stdout);
2671 fputc ('\n', stdout);
2674 bt_unlockpage (BtLockRead, set->latch);
2675 bt_unpinlatch (set->latch);
2676 bt_unpinpool (set->pool);
2677 } while( page_no = next );
2679 cnt--; // remove stopper key
2680 fprintf(stderr, " Total keys read %d\n", cnt);
2684 fprintf(stderr, "started counting\n");
2685 next = bt->mgr->latchmgr->nlatchpage + LATCH_page;
2686 page_no = LEAF_page;
2688 while( page_no < bt_getid(bt->mgr->latchmgr->alloc->right) ) {
2689 pread (bt->mgr->idx, bt->frame, bt->mgr->page_size, page_no << bt->mgr->page_bits);
2690 if( !bt->frame->free && !bt->frame->lvl )
2691 cnt += bt->frame->act;
2692 if( page_no > LEAF_page )
2697 cnt--; // remove stopper key
2698 fprintf(stderr, " Total keys read %d\n", cnt);
2710 typedef struct timeval timer;
2712 int main (int argc, char **argv)
2714 int idx, cnt, len, slot, err;
2715 int segsize, bits = 16;
2720 time_t start[1], stop[1];
2733 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]);
2734 fprintf (stderr, " where page_bits is the page size in bits\n");
2735 fprintf (stderr, " mapped_segments is the number of mmap segments in buffer pool\n");
2736 fprintf (stderr, " seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2737 fprintf (stderr, " line_numbers = 1 to append line numbers to keys\n");
2738 fprintf (stderr, " src_file1 thru src_filen are files of keys separated by newline\n");
2743 gettimeofday(&start, NULL);
2749 bits = atoi(argv[3]);
2752 poolsize = atoi(argv[4]);
2755 fprintf (stderr, "Warning: no mapped_pool\n");
2757 if( poolsize > 65535 )
2758 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2761 segsize = atoi(argv[5]);
2763 segsize = 4; // 16 pages per mmap segment
2766 num = atoi(argv[6]);
2770 threads = malloc (cnt * sizeof(pthread_t));
2772 threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2774 args = malloc (cnt * sizeof(ThreadArg));
2776 mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2779 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2785 for( idx = 0; idx < cnt; idx++ ) {
2786 args[idx].infile = argv[idx + 7];
2787 args[idx].type = argv[2][0];
2788 args[idx].mgr = mgr;
2789 args[idx].num = num;
2790 args[idx].idx = idx;
2792 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2793 fprintf(stderr, "Error creating thread %d\n", err);
2795 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2799 // wait for termination
2802 for( idx = 0; idx < cnt; idx++ )
2803 pthread_join (threads[idx], NULL);
2804 gettimeofday(&stop, NULL);
2805 real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2807 WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2809 for( idx = 0; idx < cnt; idx++ )
2810 CloseHandle(threads[idx]);
2813 real_time = 1000 * (*stop - *start);
2815 fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);