1 // btree version threads2i linux futex concurrency version
4 // author: karl malbrain, malbrain@cal.berkeley.edu
7 This work, including the source code, documentation
8 and related data, is placed into the public domain.
10 The orginal author is Karl Malbrain.
12 THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY
13 OF ANY KIND, NOT EVEN THE IMPLIED WARRANTY OF
14 MERCHANTABILITY. THE AUTHOR OF THIS SOFTWARE,
15 ASSUMES _NO_ RESPONSIBILITY FOR ANY CONSEQUENCE
16 RESULTING FROM THE USE, MODIFICATION, OR
17 REDISTRIBUTION OF THIS SOFTWARE.
20 // Please see the project home page for documentation
21 // code.google.com/p/high-concurrency-btree
23 #define _FILE_OFFSET_BITS 64
24 #define _LARGEFILE64_SOURCE
28 #include <linux/futex.h>
43 #define WIN32_LEAN_AND_MEAN
56 typedef unsigned long long uid;
59 typedef unsigned long long off64_t;
60 typedef unsigned short ushort;
61 typedef unsigned int uint;
64 #define BT_ro 0x6f72 // ro
65 #define BT_rw 0x7772 // rw
67 #define BT_maxbits 24 // maximum page size in bits
68 #define BT_minbits 9 // minimum page size in bits
69 #define BT_minpage (1 << BT_minbits) // minimum page size
70 #define BT_maxpage (1 << BT_maxbits) // maximum page size
73 There are five lock types for each node in three independent sets:
74 1. (set 1) AccessIntent: Sharable. Going to Read the node. Incompatible with NodeDelete.
75 2. (set 1) NodeDelete: Exclusive. About to release the node. Incompatible with AccessIntent.
76 3. (set 2) ReadLock: Sharable. Read the node. Incompatible with WriteLock.
77 4. (set 2) WriteLock: Exclusive. Modify the node. Incompatible with ReadLock and other WriteLocks.
78 5. (set 3) ParentModification: Exclusive. Change the node's parent keys. Incompatible with another ParentModification.
89 // mode & definition for latch implementation
92 Mutex = 1 << 0, // the mutex bit
93 Write = 1 << 1, // the writers bit
94 Share = 1 << 2, // reader count
95 PendRd = 1 << 12, // reader contended count
96 PendWr = 1 << 22 // writer contended count
100 QueRd = 1, // reader queue
101 QueWr = 2 // writer queue
104 // share is count of read accessors
105 // grant write lock when share == 0
108 volatile uint mutex:1; // 1 = busy
109 volatile uint write:1; // 1 = exclusive
110 volatile uint share:10; // count of readers holding locks
111 volatile uint readwait:10; // count of readers waiting
112 volatile uint writewait:10; // count of writers waiting
116 BtLatch readwr[1]; // read/write page lock
117 BtLatch access[1]; // Access Intent/Page delete
118 BtLatch parent[1]; // Parent modification
121 // Define the length of the page and key pointers
125 // Page key slot definition.
127 // If BT_maxbits is 15 or less, you can save 4 bytes
128 // for each key stored by making the first two uints
129 // into ushorts. You can also save 4 bytes by removing
130 // the tod field from the key.
132 // Keys are marked dead, but remain on the page until
133 // it cleanup is called. The fence key (highest key) for
134 // the page is always present, even after cleanup.
137 uint off:BT_maxbits; // page offset for key start
138 uint dead:1; // set for deleted key
139 uint tod; // time-stamp for key
140 unsigned char id[BtId]; // id associated with key
143 // The key structure occupies space at the upper end of
144 // each page. It's a length byte followed by the value
149 unsigned char key[1];
152 // The first part of an index page.
153 // It is immediately followed
154 // by the BtSlot array of keys.
156 typedef struct Page {
157 BtLatchSet latch[1]; // Set of three latches
158 uint cnt; // count of keys in page
159 uint act; // count of active keys
160 uint min; // next key offset
161 unsigned char bits; // page size in bits
162 unsigned char lvl:6; // level of page
163 unsigned char kill:1; // page is being deleted
164 unsigned char dirty:1; // page has deleted keys
165 unsigned char right[BtId]; // page number to right
168 // The memory mapping pool table buffer manager entry
171 unsigned long long int lru; // number of times accessed
172 uid basepage; // mapped base page number
173 char *map; // mapped memory pointer
174 uint slot; // slot index in this array
175 volatile uint pin; // mapped page pin counter
176 void *hashprev; // previous pool entry for the same hash idx
177 void *hashnext; // next pool entry for the same hash idx
183 // The object structure for Btree access
186 uint page_size; // page size
187 uint page_bits; // page size in bits
188 uint seg_bits; // seg size in pages in bits
189 uint mode; // read-write mode
191 char *pooladvise; // bit maps for pool page advisements
196 volatile uint poolcnt; // highest page pool node in use
197 volatile uint evicted; // last evicted hash table slot
198 uint poolmax; // highest page pool node allocated
199 uint poolmask; // total size of pages in mmap segment - 1
200 uint hashsize; // size of Hash Table for pool entries
201 ushort *hash; // pool index for hash entries
202 BtLatch *latch; // latches for hash table slots
203 BtPool *pool; // memory pool page segments
207 BtMgr *mgr; // buffer manager for thread
208 BtPage temp; // temporary frame buffer (memory mapped/file IO)
209 BtPage alloc; // frame buffer for alloc page ( mapped to page 0 )
210 BtPage cursor; // cached frame for start/next (never mapped)
211 BtPage frame; // spare frame for the page split (never mapped)
212 BtPage zero; // page of zeroes to extend the file (never mapped)
213 BtPage page; // current page mapped from file
214 uid page_no; // current page number
215 uid cursor_page; // current cursor page number
216 unsigned char *mem; // frame, cursor, page memory buffer
217 int err; // last error
231 extern void bt_close (BtDb *bt);
232 extern BtDb *bt_open (BtMgr *mgr);
233 extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod);
234 extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl);
235 extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
236 extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
237 extern uint bt_nextkey (BtDb *bt, uint slot);
240 extern BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolsize, uint segsize, uint hashsize);
241 void bt_mgrclose (BtMgr *mgr);
243 // Helper functions to return slot values
245 extern BtKey bt_key (BtDb *bt, uint slot);
246 extern uid bt_uid (BtDb *bt, uint slot);
247 extern uint bt_tod (BtDb *bt, uint slot);
249 // BTree page number constants
254 // Number of levels to create in a new BTree
258 // The page is allocated from low and hi ends.
259 // The key offsets and row-id's are allocated
260 // from the bottom, while the text of the key
261 // is allocated from the top. When the two
262 // areas meet, the page is split into two.
264 // A key consists of a length byte, two bytes of
265 // index number (0 - 65534), and up to 253 bytes
266 // of key value. Duplicate keys are discarded.
267 // Associated with each key is a 48 bit row-id.
269 // The b-tree root is always located at page 1.
270 // The first leaf page of level zero is always
271 // located on page 2.
273 // The b-tree pages are linked with next
274 // pointers to facilitate enumerators,
275 // and provide for concurrency.
277 // When to root page fills, it is split in two and
278 // the tree height is raised by a new root at page
279 // one with two keys.
281 // Deleted keys are marked with a dead bit until
282 // page cleanup The fence key for a node is always
283 // present, even after deletion and cleanup.
285 // Groups of pages called segments from the btree are optionally
286 // cached with a memory mapped pool. A hash table is used to keep
287 // track of the cached segments. This behaviour is controlled
288 // by the cache block size parameter to bt_open.
290 // To achieve maximum concurrency one page is locked at a time
291 // as the tree is traversed to find leaf key in question. The right
292 // page numbers are used in cases where the page is being split,
295 // Page 0 is dedicated to lock for new page extensions,
296 // and chains empty pages together for reuse.
298 // The ParentModification lock on a node is obtained to prevent resplitting
299 // or deleting a node before its fence is posted into its upper level.
301 // Empty pages are chained together through the ALLOC page and reused.
303 // Access macros to address slot and key values from the page
305 #define slotptr(page, slot) (((BtSlot *)(page+1)) + (slot-1))
306 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
308 void bt_putid(unsigned char *dest, uid id)
313 dest[i] = (unsigned char)id, id >>= 8;
316 uid bt_getid(unsigned char *src)
321 for( i = 0; i < BtId; i++ )
322 id <<= 8, id |= *src++;
327 void bt_mgrclose (BtMgr *mgr)
332 // release mapped pages
333 // note that slot zero is never used
335 for( slot = 1; slot < mgr->poolmax; slot++ ) {
336 pool = mgr->pool + slot;
339 munmap (pool->map, (mgr->poolmask+1) << mgr->page_bits);
342 FlushViewOfFile(pool->map, 0);
343 UnmapViewOfFile(pool->map);
344 CloseHandle(pool->hmap);
354 free (mgr->pooladvise);
357 FlushFileBuffers(mgr->idx);
358 CloseHandle(mgr->idx);
359 GlobalFree (mgr->pool);
360 GlobalFree (mgr->hash);
361 GlobalFree (mgr->latch);
366 // close and release memory
368 void bt_close (BtDb *bt)
375 VirtualFree (bt->mem, 0, MEM_RELEASE);
380 // open/create new btree buffer manager
382 // call with file_name, BT_openmode, bits in page size (e.g. 16),
383 // size of mapped page pool (e.g. 8192)
385 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
387 uint lvl, attr, cacheblk, last;
396 SYSTEM_INFO sysinfo[1];
399 // determine sanity of page size and buffer pool
401 if( bits > BT_maxbits )
403 else if( bits < BT_minbits )
407 return NULL; // must have buffer pool
410 mgr = calloc (1, sizeof(BtMgr));
412 switch (mode & 0x7fff)
415 mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
421 mgr->idx = open ((char*)name, O_RDONLY);
426 return free(mgr), NULL;
428 cacheblk = 4096; // minimum mmap segment size for unix
431 mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
432 attr = FILE_ATTRIBUTE_NORMAL;
433 switch (mode & 0x7fff)
436 mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
442 mgr->idx = CreateFile(name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, attr, NULL);
446 if( mgr->idx == INVALID_HANDLE_VALUE )
447 return GlobalFree(mgr), NULL;
449 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
450 GetSystemInfo(sysinfo);
451 cacheblk = sysinfo->dwAllocationGranularity;
455 alloc = malloc (BT_maxpage);
458 // read minimum page size to get root info
460 if( size = lseek (mgr->idx, 0L, 2) ) {
461 if( pread(mgr->idx, alloc, BT_minpage, 0) == BT_minpage )
464 return free(mgr), free(alloc), NULL;
465 } else if( mode == BT_ro )
466 return bt_mgrclose (mgr), NULL;
468 alloc = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
469 size = GetFileSize(mgr->idx, amt);
472 if( !ReadFile(mgr->idx, (char *)alloc, BT_minpage, amt, NULL) )
473 return bt_mgrclose (mgr), NULL;
475 } else if( mode == BT_ro )
476 return bt_mgrclose (mgr), NULL;
479 mgr->page_size = 1 << bits;
480 mgr->page_bits = bits;
482 mgr->poolmax = poolmax;
485 if( cacheblk < mgr->page_size )
486 cacheblk = mgr->page_size;
488 // mask for partial memmaps
490 mgr->poolmask = (cacheblk >> bits) - 1;
492 // see if requested size of pages per memmap is greater
494 if( (1 << segsize) > mgr->poolmask )
495 mgr->poolmask = (1 << segsize) - 1;
499 while( (1 << mgr->seg_bits) <= mgr->poolmask )
502 mgr->hashsize = hashsize;
505 mgr->pool = calloc (poolmax, sizeof(BtPool));
506 mgr->hash = calloc (hashsize, sizeof(ushort));
507 mgr->latch = calloc (hashsize, sizeof(BtLatch));
508 mgr->pooladvise = calloc (poolmax, (mgr->poolmask + 8) / 8);
510 mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * sizeof(BtPool));
511 mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
512 mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtLatch));
518 // initializes an empty b-tree with root page and page of leaves
520 memset (alloc, 0, 1 << bits);
521 bt_putid(alloc->right, MIN_lvl+1);
522 alloc->bits = mgr->page_bits;
525 if( write (mgr->idx, alloc, mgr->page_size) < mgr->page_size )
526 return bt_mgrclose (mgr), NULL;
528 if( !WriteFile (mgr->idx, (char *)alloc, mgr->page_size, amt, NULL) )
529 return bt_mgrclose (mgr), NULL;
531 if( *amt < mgr->page_size )
532 return bt_mgrclose (mgr), NULL;
535 memset (alloc, 0, 1 << bits);
536 alloc->bits = mgr->page_bits;
538 for( lvl=MIN_lvl; lvl--; ) {
539 slotptr(alloc, 1)->off = mgr->page_size - 3;
540 bt_putid(slotptr(alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
541 key = keyptr(alloc, 1);
542 key->len = 2; // create stopper key
545 alloc->min = mgr->page_size - 3;
550 if( write (mgr->idx, alloc, mgr->page_size) < mgr->page_size )
551 return bt_mgrclose (mgr), NULL;
553 if( !WriteFile (mgr->idx, (char *)alloc, mgr->page_size, amt, NULL) )
554 return bt_mgrclose (mgr), NULL;
556 if( *amt < mgr->page_size )
557 return bt_mgrclose (mgr), NULL;
561 // create empty page area by writing last page of first
562 // segment area (other pages are zeroed by O/S)
564 if( mgr->poolmask ) {
565 memset(alloc, 0, mgr->page_size);
566 last = mgr->poolmask;
568 while( last < MIN_lvl + 1 )
569 last += mgr->poolmask + 1;
572 pwrite(mgr->idx, alloc, mgr->page_size, last << mgr->page_bits);
574 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
575 if( !WriteFile (mgr->idx, (char *)alloc, mgr->page_size, amt, NULL) )
576 return bt_mgrclose (mgr), NULL;
577 if( *amt < mgr->page_size )
578 return bt_mgrclose (mgr), NULL;
586 VirtualFree (alloc, 0, MEM_RELEASE);
591 // open BTree access method
592 // based on buffer manager
594 BtDb *bt_open (BtMgr *mgr)
596 BtDb *bt = malloc (sizeof(*bt));
598 memset (bt, 0, sizeof(*bt));
601 bt->mem = malloc (3 *mgr->page_size);
603 bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
605 bt->frame = (BtPage)bt->mem;
606 bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
607 bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
609 memset (bt->zero, 0, mgr->page_size);
613 // compare two keys, returning > 0, = 0, or < 0
614 // as the comparison value
616 int keycmp (BtKey key1, unsigned char *key2, uint len2)
618 uint len1 = key1->len;
621 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
634 int sys_futex(void *addr1, int op, int val1, struct timespec *timeout, void *addr2, int val3)
636 return syscall(SYS_futex, addr1, op, val1, timeout, addr2, val3);
639 // wait until write lock mode is clear
640 // and add 1 to the share count
642 void bt_readlock(BtLatch *latch, int private)
647 private = FUTEX_PRIVATE_FLAG;
650 // obtain latch mutex
651 if( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex ) {
656 // wait for writers to clear
657 // increment read waiters and wait
659 if( latch->write || latch->writewait ) {
660 __sync_fetch_and_add ((uint *)latch, PendRd);
661 prev = __sync_fetch_and_and ((uint *)latch, ~Mutex) & ~Mutex;
662 sys_futex( (uint *)latch, FUTEX_WAIT_BITSET | private, prev, NULL, NULL, QueRd );
663 __sync_fetch_and_sub ((uint *)latch, PendRd);
667 // increment reader lock count
668 // and release latch mutex
670 __sync_fetch_and_add ((uint *)latch, Share);
671 __sync_fetch_and_and ((uint *)latch, ~Mutex);
676 // wait for other read and write latches to relinquish
678 void bt_writelock(BtLatch *latch, int private)
683 private = FUTEX_PRIVATE_FLAG;
686 // obtain latch mutex
687 if( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex ) {
692 // wait for write and reader count to clear
694 if( latch->write || latch->share ) {
695 __sync_fetch_and_add ((uint *)latch, PendWr);
696 prev = __sync_fetch_and_and ((uint *)latch, ~Mutex) & ~Mutex;
697 sys_futex( (uint *)latch, FUTEX_WAIT_BITSET | private, prev, NULL, NULL, QueWr );
698 __sync_fetch_and_sub ((uint *)latch, PendWr);
703 // release latch mutex
705 __sync_fetch_and_or ((uint *)latch, Write);
706 __sync_fetch_and_and ((uint *)latch, ~Mutex);
711 // try to obtain write lock
713 // return 1 if obtained,
716 int bt_writetry(BtLatch *latch)
721 // abandon request if not taken
723 if( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex )
726 // see if write mode is available
728 if( !latch->write && !latch->share ) {
729 __sync_fetch_and_or ((uint *)latch, Write);
734 // release latch mutex
736 __sync_fetch_and_and ((uint *)latch, ~Mutex);
742 void bt_releasewrite(BtLatch *latch, int private)
745 private = FUTEX_PRIVATE_FLAG;
747 // obtain latch mutex
749 while( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex )
752 __sync_fetch_and_and ((uint *)latch, ~Write);
756 if( latch->writewait )
757 if( sys_futex( (uint *)latch, FUTEX_WAKE_BITSET | private, 1, NULL, NULL, QueWr ) )
760 if( latch->readwait )
761 sys_futex( (uint *)latch, FUTEX_WAKE_BITSET | private, INT_MAX, NULL, NULL, QueRd );
763 // release latch mutex
766 __sync_fetch_and_and ((uint *)latch, ~Mutex);
769 // decrement reader count
771 void bt_releaseread(BtLatch *latch, int private)
774 private = FUTEX_PRIVATE_FLAG;
776 // obtain latch mutex
778 while( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex )
781 __sync_fetch_and_sub ((uint *)latch, Share);
783 // wake waiting writers
785 if( !latch->share && latch->writewait )
786 sys_futex( (uint *)latch, FUTEX_WAKE_BITSET | private, 1, NULL, NULL, QueWr );
788 // release latch mutex
790 __sync_fetch_and_and ((uint *)latch, ~Mutex);
795 // find segment in pool
796 // must be called with hashslot idx locked
797 // return NULL if not there
798 // otherwise return node
800 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
805 // compute start of hash chain in pool
807 if( slot = bt->mgr->hash[idx] )
808 pool = bt->mgr->pool + slot;
812 page_no &= ~bt->mgr->poolmask;
814 while( pool->basepage != page_no )
815 if( pool = pool->hashnext )
823 // add segment to hash table
825 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
830 pool->hashprev = pool->hashnext = NULL;
831 pool->basepage = page_no & ~bt->mgr->poolmask;
834 if( slot = bt->mgr->hash[idx] ) {
835 node = bt->mgr->pool + slot;
836 pool->hashnext = node;
837 node->hashprev = pool;
840 bt->mgr->hash[idx] = pool->slot;
843 // find best segment to evict from buffer pool
845 BtPool *bt_findlru (BtDb *bt, uint hashslot)
847 unsigned long long int target = ~0LL;
848 BtPool *pool = NULL, *node;
853 node = bt->mgr->pool + hashslot;
855 // scan pool entries under hash table slot
860 if( node->lru > target )
864 } while( node = node->hashnext );
869 // map new buffer pool segment to virtual memory
871 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
873 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
874 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
878 flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
879 pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED, bt->mgr->idx, off);
880 if( pool->map == MAP_FAILED )
881 return bt->err = BTERR_map;
883 // clear out madvise issued bits
884 memset (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8) / 8), 0, (bt->mgr->poolmask + 8)/8);
886 flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
887 pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
889 return bt->err = BTERR_map;
891 flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
892 pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
894 return bt->err = BTERR_map;
899 // find or place requested page in segment-pool
900 // return pool table entry, incrementing pin
902 BtPool *bt_pinpage(BtDb *bt, uid page_no)
904 BtPool *pool, *node, *next;
905 uint slot, idx, victim;
907 // lock hash table chain
909 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
910 bt_readlock (&bt->mgr->latch[idx], 1);
912 // look up in hash table
914 if( pool = bt_findpool(bt, page_no, idx) ) {
916 __sync_fetch_and_add(&pool->pin, 1);
918 _InterlockedIncrement (&pool->pin);
920 bt_releaseread (&bt->mgr->latch[idx], 1);
925 // upgrade to write lock
927 bt_releaseread (&bt->mgr->latch[idx], 1);
928 bt_writelock (&bt->mgr->latch[idx], 1);
930 // try to find page in pool with write lock
932 if( pool = bt_findpool(bt, page_no, idx) ) {
934 __sync_fetch_and_add(&pool->pin, 1);
936 _InterlockedIncrement (&pool->pin);
938 bt_releasewrite (&bt->mgr->latch[idx], 1);
943 // allocate a new pool node
944 // and add to hash table
947 slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
949 slot = _InterlockedIncrement (&bt->mgr->poolcnt) - 1;
952 if( ++slot < bt->mgr->poolmax ) {
953 pool = bt->mgr->pool + slot;
956 if( bt_mapsegment(bt, pool, page_no) )
959 bt_linkhash(bt, pool, page_no, idx);
961 __sync_fetch_and_add(&pool->pin, 1);
963 _InterlockedIncrement (&pool->pin);
965 bt_releasewrite (&bt->mgr->latch[idx], 1);
969 // pool table is full
970 // find best pool entry to evict
973 __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
975 _InterlockedDecrement (&bt->mgr->poolcnt);
980 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
982 victim = _InterlockedIncrement (&bt->mgr->evicted) - 1;
984 victim %= bt->mgr->hashsize;
986 // try to get write lock
987 // skip entry if not obtained
989 if( !bt_writetry (&bt->mgr->latch[victim]) )
992 // if pool entry is empty
993 // or any pages are pinned
996 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
997 bt_releasewrite (&bt->mgr->latch[victim], 1);
1001 // unlink victim pool node from hash table
1003 if( node = pool->hashprev )
1004 node->hashnext = pool->hashnext;
1005 else if( node = pool->hashnext )
1006 bt->mgr->hash[victim] = node->slot;
1008 bt->mgr->hash[victim] = 0;
1010 if( node = pool->hashnext )
1011 node->hashprev = pool->hashprev;
1013 bt_releasewrite (&bt->mgr->latch[victim], 1);
1015 // remove old file mapping
1017 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1019 FlushViewOfFile(pool->map, 0);
1020 UnmapViewOfFile(pool->map);
1021 CloseHandle(pool->hmap);
1025 // create new pool mapping
1026 // and link into hash table
1028 if( bt_mapsegment(bt, pool, page_no) )
1031 bt_linkhash(bt, pool, page_no, idx);
1033 __sync_fetch_and_add(&pool->pin, 1);
1035 _InterlockedIncrement (&pool->pin);
1037 bt_releasewrite (&bt->mgr->latch[idx], 1);
1042 // place write, read, or parent lock on requested page_no.
1043 // pin to buffer pool and return page pointer
1045 BTERR bt_lockpage(BtDb *bt, uid page_no, BtLock mode, BtPage *pageptr)
1051 // find/create maping in pool table
1052 // and pin our pool slot
1054 if( pool = bt_pinpage(bt, page_no) )
1055 subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1059 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1062 uint idx = subpage / 8;
1063 uint bit = subpage % 8;
1065 if( ~((bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] >> bit) & 1 ) {
1066 madvise (page, bt->mgr->page_size, MADV_WILLNEED);
1067 (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] |= 1 << bit;
1074 bt_readlock (page->latch->readwr, 0);
1077 bt_writelock (page->latch->readwr, 0);
1080 bt_readlock (page->latch->access, 0);
1083 bt_writelock (page->latch->access, 0);
1086 bt_writelock (page->latch->parent, 0);
1089 return bt->err = BTERR_lock;
1097 // remove write, read, or parent lock on requested page
1099 BTERR bt_unlockpage(BtDb *bt, uid page_no, BtLock mode)
1105 // since page is pinned
1106 // it should still be in the buffer pool
1107 // and is in no danger of being a victim for reuse
1109 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1110 bt_readlock (&bt->mgr->latch[idx], 1);
1112 if( pool = bt_findpool(bt, page_no, idx) )
1113 subpage = (uint)(page_no & bt->mgr->poolmask);
1115 return bt->err = BTERR_hash;
1117 bt_releaseread (&bt->mgr->latch[idx], 1);
1118 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1122 bt_releaseread (page->latch->readwr, 0);
1125 bt_releasewrite (page->latch->readwr, 0);
1128 bt_releaseread (page->latch->access, 0);
1131 bt_releasewrite (page->latch->access, 0);
1134 bt_releasewrite (page->latch->parent, 0);
1137 return bt->err = BTERR_lock;
1141 __sync_fetch_and_add(&pool->pin, -1);
1143 _InterlockedDecrement (&pool->pin);
1148 // deallocate a deleted page
1149 // place on free chain out of allocator page
1151 BTERR bt_freepage(BtDb *bt, uid page_no)
1153 // obtain delete lock on deleted page
1155 if( bt_lockpage(bt, page_no, BtLockDelete, NULL) )
1158 // obtain write lock on deleted page
1160 if( bt_lockpage(bt, page_no, BtLockWrite, &bt->temp) )
1163 // lock allocation page
1165 if ( bt_lockpage(bt, ALLOC_page, BtLockWrite, &bt->alloc) )
1168 // store chain in second right
1169 bt_putid(bt->temp->right, bt_getid(bt->alloc[1].right));
1170 bt_putid(bt->alloc[1].right, page_no);
1174 if( bt_unlockpage(bt, ALLOC_page, BtLockWrite) )
1177 // remove write lock on deleted node
1179 if( bt_unlockpage(bt, page_no, BtLockWrite) )
1182 // remove delete lock on deleted node
1184 if( bt_unlockpage(bt, page_no, BtLockDelete) )
1190 // allocate a new page and write page into it
1192 uid bt_newpage(BtDb *bt, BtPage page)
1201 if( bt_lockpage(bt, ALLOC_page, BtLockWrite, &bt->alloc) )
1204 // use empty chain first
1205 // else allocate empty page
1207 if( new_page = bt_getid(bt->alloc[1].right) ) {
1208 if( bt_lockpage (bt, new_page, BtLockWrite, &bt->temp) )
1210 bt_putid(bt->alloc[1].right, bt_getid(bt->temp->right));
1211 if( bt_unlockpage (bt, new_page, BtLockWrite) )
1215 new_page = bt_getid(bt->alloc->right);
1216 bt_putid(bt->alloc->right, new_page+1);
1221 // if writing first page of pool block
1222 // expand file thru last page in the block
1224 if( !reuse && (new_page & bt->mgr->poolmask) == 0 )
1225 if( pwrite(bt->mgr->idx, bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1226 return bt->err = BTERR_wrt, 0;
1228 // unlock page allocation page
1230 if( bt_unlockpage(bt, ALLOC_page, BtLockWrite) )
1233 // bring new page into pool and copy page.
1234 // on Windows, this will extend the file into the new page.
1236 if( bt_lockpage(bt, new_page, BtLockWrite, &pmap) )
1239 // copy source page but leave latch area intact
1241 memcpy((char *)pmap + sizeof(BtLatchSet), (char *)page + sizeof(BtLatchSet), bt->mgr->page_size - sizeof(BtLatchSet));
1243 if( bt_unlockpage (bt, new_page, BtLockWrite) )
1249 // find slot in page for given key at a given level
1251 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1253 uint diff, higher = bt->page->cnt, low = 1, slot;
1256 // make stopper key an infinite fence value
1258 if( bt_getid (bt->page->right) )
1263 // low is the next candidate, higher is already
1264 // tested as .ge. the given key, loop ends when they meet
1266 while( diff = higher - low ) {
1267 slot = low + ( diff >> 1 );
1268 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1271 higher = slot, good++;
1274 // return zero if key is on right link page
1276 return good ? higher : 0;
1279 // find and load page at given level for given key
1280 // leave page rd or wr locked as requested
1282 int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, uint lock)
1284 uid page_no = ROOT_page, prevpage = 0;
1285 uint drill = 0xff, slot;
1286 uint mode, prevmode;
1288 // start at root of btree and drill down
1291 // determine lock mode of drill level
1292 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1294 bt->page_no = page_no;
1296 // obtain access lock using lock chaining with Access mode
1298 if( page_no > ROOT_page )
1299 if( bt_lockpage(bt, page_no, BtLockAccess, NULL) )
1303 if( bt_unlockpage(bt, prevpage, prevmode) )
1306 // obtain read lock using lock chaining
1307 // and pin page contents
1309 if( bt_lockpage(bt, page_no, mode, &bt->page) )
1312 if( page_no > ROOT_page )
1313 if( bt_unlockpage(bt, page_no, BtLockAccess) )
1316 // re-read and re-lock root after determining actual level of root
1318 if( bt->page->lvl != drill) {
1319 if ( bt->page_no != ROOT_page )
1320 return bt->err = BTERR_struct, 0;
1322 drill = bt->page->lvl;
1324 if( lock == BtLockWrite && drill == lvl )
1325 if( bt_unlockpage(bt, page_no, mode) )
1331 // find key on page at this level
1332 // and descend to requested level
1334 if( !bt->page->kill && (slot = bt_findslot (bt, key, len)) ) {
1338 while( slotptr(bt->page, slot)->dead )
1339 if( slot++ < bt->page->cnt )
1342 page_no = bt_getid(bt->page->right);
1346 page_no = bt_getid(slotptr(bt->page, slot)->id);
1350 // or slide right into next page
1351 // (slide left from deleted page)
1354 page_no = bt_getid(bt->page->right);
1356 // continue down / right using overlapping locks
1357 // to protect pages being killed or split.
1360 prevpage = bt->page_no;
1364 // return error on end of right chain
1366 bt->err = BTERR_struct;
1367 return 0; // return error
1370 // find and delete key on page by marking delete flag bit
1371 // when page becomes empty, delete it
1373 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl)
1375 unsigned char lowerkey[256], higherkey[256];
1380 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1381 ptr = keyptr(bt->page, slot);
1385 // if key is found delete it, otherwise ignore request
1387 if( !keycmp (ptr, key, len) )
1388 if( slotptr(bt->page, slot)->dead == 0 ) {
1389 slotptr(bt->page,slot)->dead = 1;
1390 if( slot < bt->page->cnt )
1391 bt->page->dirty = 1;
1395 // return if page is not empty, or it has no right sibling
1397 right = bt_getid(bt->page->right);
1398 page_no = bt->page_no;
1400 if( !right || bt->page->act )
1401 return bt_unlockpage(bt, page_no, BtLockWrite);
1403 // obtain Parent lock over write lock
1405 if( bt_lockpage(bt, page_no, BtLockParent, NULL) )
1408 // keep copy of key to delete
1410 ptr = keyptr(bt->page, bt->page->cnt);
1411 memcpy(lowerkey, ptr, ptr->len + 1);
1413 // lock and map right page
1415 if ( bt_lockpage(bt, right, BtLockWrite, &bt->temp) )
1418 // pull contents of next page into current empty page
1419 memcpy((char *)bt->page + sizeof(BtLatchSet), (char *)bt->temp + sizeof(BtLatchSet), bt->mgr->page_size - sizeof(BtLatchSet));
1421 // keep copy of key to update
1422 ptr = keyptr(bt->temp, bt->temp->cnt);
1423 memcpy(higherkey, ptr, ptr->len + 1);
1425 // Mark right page as deleted and point it to left page
1426 // until we can post updates at higher level.
1428 bt_putid(bt->temp->right, page_no);
1432 if( bt_unlockpage(bt, right, BtLockWrite) )
1434 if( bt_unlockpage(bt, page_no, BtLockWrite) )
1437 // delete old lower key to consolidated node
1439 if( bt_deletekey (bt, lowerkey + 1, *lowerkey, lvl + 1) )
1442 // redirect higher key directly to consolidated node
1444 tod = (uint)time(NULL);
1446 if( bt_insertkey (bt, higherkey+1, *higherkey, lvl + 1, page_no, tod) )
1449 // obtain write lock and
1450 // add right block to free chain
1452 if( bt_freepage (bt, right) )
1455 // remove ParentModify lock
1457 if( bt_unlockpage(bt, page_no, BtLockParent) )
1463 // find key in leaf level and return row-id
1465 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1471 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1472 ptr = keyptr(bt->page, slot);
1476 // if key exists, return row-id
1477 // otherwise return 0
1479 if( ptr->len == len && !memcmp (ptr->key, key, len) )
1480 id = bt_getid(slotptr(bt->page,slot)->id);
1484 if ( bt_unlockpage(bt, bt->page_no, BtLockRead) )
1490 // check page for space available,
1491 // clean if necessary and return
1492 // 0 - page needs splitting
1495 uint bt_cleanpage(BtDb *bt, uint amt)
1497 uint nxt = bt->mgr->page_size;
1498 BtPage page = bt->page;
1499 uint cnt = 0, idx = 0;
1500 uint max = page->cnt;
1503 if( page->min >= (page->cnt+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1506 // skip cleanup if nothing to reclaim
1511 memcpy (bt->frame, page, bt->mgr->page_size);
1513 // skip page info and set rest of page to zero
1515 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1519 while( cnt++ < max ) {
1520 // always leave fence key in list
1521 if( cnt < max && slotptr(bt->frame,cnt)->dead )
1525 key = keyptr(bt->frame, cnt);
1526 nxt -= key->len + 1;
1527 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1530 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1531 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1533 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1534 slotptr(page, idx)->off = nxt;
1539 if( page->min >= (page->cnt+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1545 // split the root and raise the height of the btree
1547 BTERR bt_splitroot(BtDb *bt, unsigned char *newkey, unsigned char *oldkey, uid page_no2)
1549 uint nxt = bt->mgr->page_size;
1550 BtPage root = bt->page;
1553 // Obtain an empty page to use, and copy the current
1554 // root contents into it which is the lower half of
1557 if( !(new_page = bt_newpage(bt, root)) )
1560 // preserve the page info at the bottom
1561 // and set rest to zero
1563 memset(root+1, 0, bt->mgr->page_size - sizeof(*root));
1565 // insert first key on newroot page
1568 memcpy ((unsigned char *)root + nxt, newkey, *newkey + 1);
1569 bt_putid(slotptr(root, 1)->id, new_page);
1570 slotptr(root, 1)->off = nxt;
1572 // insert second key on newroot page
1573 // and increase the root height
1576 memcpy ((unsigned char *)root + nxt, oldkey, *oldkey + 1);
1577 bt_putid(slotptr(root, 2)->id, page_no2);
1578 slotptr(root, 2)->off = nxt;
1580 bt_putid(root->right, 0);
1581 root->min = nxt; // reset lowest used offset and key count
1586 // release root (bt->page)
1588 return bt_unlockpage(bt, bt->page_no, BtLockWrite);
1591 // split already locked full node
1594 BTERR bt_splitpage (BtDb *bt)
1596 uint cnt = 0, idx = 0, max, nxt = bt->mgr->page_size;
1597 unsigned char oldkey[256], lowerkey[256];
1598 uid page_no = bt->page_no, right;
1599 BtPage page = bt->page;
1600 uint lvl = page->lvl;
1605 // split higher half of keys to bt->frame
1606 // the last key (fence key) might be dead
1608 tod = (uint)time(NULL);
1610 memset (bt->frame, 0, bt->mgr->page_size);
1611 max = (int)page->cnt;
1615 while( cnt++ < max ) {
1616 key = keyptr(page, cnt);
1617 nxt -= key->len + 1;
1618 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
1619 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
1620 if( !(slotptr(bt->frame, idx)->dead = slotptr(page, cnt)->dead) )
1622 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
1623 slotptr(bt->frame, idx)->off = nxt;
1626 // remember existing fence key for new page to the right
1628 memcpy (oldkey, key, key->len + 1);
1630 bt->frame->bits = bt->mgr->page_bits;
1631 bt->frame->min = nxt;
1632 bt->frame->cnt = idx;
1633 bt->frame->lvl = lvl;
1637 if( page_no > ROOT_page ) {
1638 right = bt_getid (page->right);
1639 bt_putid(bt->frame->right, right);
1642 // get new free page and write frame to it.
1644 if( !(new_page = bt_newpage(bt, bt->frame)) )
1647 // update lower keys to continue in old page
1649 memcpy (bt->frame, page, bt->mgr->page_size);
1650 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1651 nxt = bt->mgr->page_size;
1656 // assemble page of smaller keys
1657 // (they're all active keys)
1659 while( cnt++ < max / 2 ) {
1660 key = keyptr(bt->frame, cnt);
1661 nxt -= key->len + 1;
1662 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1663 memcpy(slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1664 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1665 slotptr(page, idx)->off = nxt;
1669 // remember fence key for old page
1671 memcpy(lowerkey, key, key->len + 1);
1672 bt_putid(page->right, new_page);
1676 // if current page is the root page, split it
1678 if( page_no == ROOT_page )
1679 return bt_splitroot (bt, lowerkey, oldkey, new_page);
1681 // obtain Parent/Write locks
1682 // for left and right node pages
1684 if( bt_lockpage (bt, new_page, BtLockParent, NULL) )
1687 if( bt_lockpage (bt, page_no, BtLockParent, NULL) )
1690 // release wr lock on left page
1692 if( bt_unlockpage (bt, page_no, BtLockWrite) )
1695 // insert new fence for reformulated left block
1697 if( bt_insertkey (bt, lowerkey+1, *lowerkey, lvl + 1, page_no, tod) )
1700 // fix old fence for newly allocated right block page
1702 if( bt_insertkey (bt, oldkey+1, *oldkey, lvl + 1, new_page, tod) )
1705 // release Parent & Write locks
1707 if( bt_unlockpage (bt, new_page, BtLockParent) )
1710 if( bt_unlockpage (bt, page_no, BtLockParent) )
1716 // Insert new key into the btree at requested level.
1717 // Level zero pages are leaf pages and are unlocked at exit.
1718 // Interior pages remain locked.
1720 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod)
1727 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1728 ptr = keyptr(bt->page, slot);
1732 bt->err = BTERR_ovflw;
1736 // if key already exists, update id and return
1740 if( !keycmp (ptr, key, len) ) {
1741 slotptr(page, slot)->dead = 0;
1742 slotptr(page, slot)->tod = tod;
1743 bt_putid(slotptr(page,slot)->id, id);
1744 return bt_unlockpage(bt, bt->page_no, BtLockWrite);
1747 // check if page has enough space
1749 if( bt_cleanpage (bt, len) )
1752 if( bt_splitpage (bt) )
1756 // calculate next available slot and copy key into page
1758 page->min -= len + 1; // reset lowest used offset
1759 ((unsigned char *)page)[page->min] = len;
1760 memcpy ((unsigned char *)page + page->min +1, key, len );
1762 for( idx = slot; idx < page->cnt; idx++ )
1763 if( slotptr(page, idx)->dead )
1766 // now insert key into array before slot
1767 // preserving the fence slot
1769 if( idx == page->cnt )
1775 *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
1777 bt_putid(slotptr(page,slot)->id, id);
1778 slotptr(page, slot)->off = page->min;
1779 slotptr(page, slot)->tod = tod;
1780 slotptr(page, slot)->dead = 0;
1782 return bt_unlockpage(bt, bt->page_no, BtLockWrite);
1785 // cache page of keys into cursor and return starting slot for given key
1787 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
1791 // cache page for retrieval
1792 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1793 memcpy (bt->cursor, bt->page, bt->mgr->page_size);
1794 bt->cursor_page = bt->page_no;
1795 if ( bt_unlockpage(bt, bt->page_no, BtLockRead) )
1801 // return next slot for cursor page
1802 // or slide cursor right into next page
1804 uint bt_nextkey (BtDb *bt, uint slot)
1809 right = bt_getid(bt->cursor->right);
1810 while( slot++ < bt->cursor->cnt )
1811 if( slotptr(bt->cursor,slot)->dead )
1813 else if( right || (slot < bt->cursor->cnt))
1821 bt->cursor_page = right;
1823 if( bt_lockpage(bt, right, BtLockRead, &bt->page) )
1826 memcpy (bt->cursor, bt->page, bt->mgr->page_size);
1828 if ( bt_unlockpage(bt, right, BtLockRead) )
1837 BtKey bt_key(BtDb *bt, uint slot)
1839 return keyptr(bt->cursor, slot);
1842 uid bt_uid(BtDb *bt, uint slot)
1844 return bt_getid(slotptr(bt->cursor,slot)->id);
1847 uint bt_tod(BtDb *bt, uint slot)
1849 return slotptr(bt->cursor,slot)->tod;
1862 // standalone program to index file of keys
1863 // then list them onto std-out
1866 void *index_file (void *arg)
1868 uint __stdcall index_file (void *arg)
1871 int line = 0, found = 0, cnt = 0;
1872 uid next, page_no = LEAF_page; // start on first page of leaves
1873 unsigned char key[256];
1874 ThreadArg *args = arg;
1875 int ch, len = 0, slot;
1882 bt = bt_open (args->mgr);
1885 switch(args->type | 0x20)
1888 fprintf(stderr, "started indexing for %s\n", args->infile);
1889 if( in = fopen (args->infile, "rb") )
1890 while( ch = getc(in), ch != EOF )
1895 if( args->num == 1 )
1896 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
1897 else if( args->num )
1898 sprintf((char *)key+len, "%.9d", line+args->idx * args->num), len += 9;
1900 if( bt_insertkey (bt, key, len, 0, line, *tod) )
1901 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
1904 else if( len < 255 )
1906 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
1910 fprintf(stderr, "started deleting keys for %s\n", args->infile);
1911 if( in = fopen (args->infile, "rb") )
1912 while( ch = getc(in), ch != EOF )
1916 if( args->num == 1 )
1917 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
1918 else if( args->num )
1919 sprintf((char *)key+len, "%.9d", line+args->idx * args->num), len += 9;
1921 if( bt_deletekey (bt, key, len, 0) )
1922 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
1925 else if( len < 255 )
1927 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
1931 fprintf(stderr, "started finding keys for %s\n", args->infile);
1932 if( in = fopen (args->infile, "rb") )
1933 while( ch = getc(in), ch != EOF )
1937 if( args->num == 1 )
1938 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
1939 else if( args->num )
1940 sprintf((char *)key+len, "%.9d", line+args->idx * args->num), len += 9;
1942 if( bt_findkey (bt, key, len) )
1945 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
1948 else if( len < 255 )
1950 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
1956 fprintf(stderr, "started reading\n");
1958 if( slot = bt_startkey (bt, key, len) )
1961 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
1963 while( slot = bt_nextkey (bt, slot) ) {
1964 ptr = bt_key(bt, slot);
1965 fwrite (ptr->key, ptr->len, 1, stdout);
1966 fputc ('\n', stdout);
1972 fprintf(stderr, "started reading\n");
1975 bt_lockpage (bt, page_no, BtLockRead, &page);
1977 next = bt_getid (page->right);
1978 bt_unlockpage (bt, page_no, BtLockRead);
1979 } while( page_no = next );
1981 cnt--; // remove stopper key
1982 fprintf(stderr, " Total keys read %d\n", cnt);
1994 typedef struct timeval timer;
1996 int main (int argc, char **argv)
1998 int idx, cnt, len, slot, err;
1999 int segsize, bits = 16;
2004 time_t start[1], stop[1];
2017 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]);
2018 fprintf (stderr, " where page_bits is the page size in bits\n");
2019 fprintf (stderr, " mapped_segments is the number of mmap segments in buffer pool\n");
2020 fprintf (stderr, " seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2021 fprintf (stderr, " line_numbers set to 1 to append line numbers to input lines\n");
2022 fprintf (stderr, " src_file1 thru src_filen are files of keys separated by newline\n");
2027 gettimeofday(&start, NULL);
2033 bits = atoi(argv[3]);
2036 poolsize = atoi(argv[4]);
2039 fprintf (stderr, "Warning: mapped_pool has no segments\n");
2041 if( poolsize > 65535 )
2042 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2045 segsize = atoi(argv[5]);
2047 segsize = 4; // 16 pages per mmap segment
2050 num = atoi(argv[6]);
2054 threads = malloc (cnt * sizeof(pthread_t));
2056 threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2058 args = malloc (cnt * sizeof(ThreadArg));
2060 mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2063 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2069 for( idx = 0; idx < cnt; idx++ ) {
2070 args[idx].infile = argv[idx + 7];
2071 args[idx].type = argv[2][0];
2072 args[idx].mgr = mgr;
2073 args[idx].num = num;
2074 args[idx].idx = idx;
2076 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2077 fprintf(stderr, "Error creating thread %d\n", err);
2079 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2083 // wait for termination
2086 for( idx = 0; idx < cnt; idx++ )
2087 pthread_join (threads[idx], NULL);
2088 gettimeofday(&stop, NULL);
2089 real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2091 WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2093 for( idx = 0; idx < cnt; idx++ )
2094 CloseHandle(threads[idx]);
2097 real_time = 1000 * (*stop - *start);
2099 fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);