1 // foster btree version g
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
40 #define WIN32_LEAN_AND_MEAN
53 typedef unsigned long long uid;
56 typedef unsigned long long off64_t;
57 typedef unsigned short ushort;
58 typedef unsigned int uint;
61 #define BT_ro 0x6f72 // ro
62 #define BT_rw 0x7772 // rw
64 #define BT_maxbits 24 // maximum page size in bits
65 #define BT_minbits 9 // minimum page size in bits
66 #define BT_minpage (1 << BT_minbits) // minimum page size
67 #define BT_maxpage (1 << BT_maxbits) // maximum page size
70 There are five lock types for each node in three independent sets:
71 1. (set 1) AccessIntent: Sharable. Going to Read the node. Incompatible with NodeDelete.
72 2. (set 1) NodeDelete: Exclusive. About to release the node. Incompatible with AccessIntent.
73 3. (set 2) ReadLock: Sharable. Read the node. Incompatible with WriteLock.
74 4. (set 2) WriteLock: Exclusive. Modify the node. Incompatible with ReadLock and other WriteLocks.
75 5. (set 3) ParentLock: Exclusive. Have parent adopt/delete maximum foster child from the node.
86 // Define the length of the page and key pointers
90 // Page key slot definition.
92 // If BT_maxbits is 15 or less, you can save 4 bytes
93 // for each key stored by making the first two uints
94 // into ushorts. You can also save 4 bytes by removing
95 // the tod field from the key.
97 // Keys are marked dead, but remain on the page until
98 // it cleanup is called. The fence key (highest key) for
99 // the page is always present, even after cleanup.
102 uint off:BT_maxbits; // page offset for key start
103 uint dead:1; // set for deleted key
104 uint tod; // time-stamp for key
105 unsigned char id[BtId]; // id associated with key
108 // The key structure occupies space at the upper end of
109 // each page. It's a length byte followed by the value
114 unsigned char key[1];
117 // mode & definition for spin latch implementation
126 // mutex locks the other fields
127 // exclusive is set for write access
128 // share is count of read accessors
131 volatile ushort mutex:1;
132 volatile ushort exclusive:1;
133 volatile ushort pending:1;
134 volatile ushort share:13;
137 // The first part of an index page.
138 // It is immediately followed
139 // by the BtSlot array of keys.
141 typedef struct Page {
142 BtSpinLatch readwr[1]; // read/write lock
143 BtSpinLatch access[1]; // access intent lock
144 BtSpinLatch parent[1]; // parent SMO lock
145 uint cnt; // count of keys in page
146 uint act; // count of active keys
147 uint min; // next key offset
148 uint foster; // count of foster children
149 unsigned char bits; // page size in bits
150 unsigned char lvl:6; // level of page
151 unsigned char kill:1; // page is being deleted
152 unsigned char dirty:1; // page needs to be cleaned
153 unsigned char right[BtId]; // page number to right
156 // The memory mapping pool table buffer manager entry
159 unsigned long long int lru; // number of times accessed
160 uid basepage; // mapped base page number
161 char *map; // mapped memory pointer
162 ushort pin; // mapped page pin counter
163 ushort slot; // slot index in this array
164 void *hashprev; // previous pool entry for the same hash idx
165 void *hashnext; // next pool entry for the same hash idx
167 HANDLE hmap; // Windows memory mapping handle
171 // The object structure for Btree access
174 uint page_size; // page size
175 uint page_bits; // page size in bits
176 uint seg_bits; // seg size in pages in bits
177 uint mode; // read-write mode
180 char *pooladvise; // bit maps for pool page advisements
184 ushort poolcnt; // highest page pool node in use
185 ushort poolmax; // highest page pool node allocated
186 ushort poolmask; // total size of pages in mmap segment - 1
187 ushort hashsize; // size of Hash Table for pool entries
188 ushort evicted; // last evicted hash table slot
189 ushort *hash; // hash table of pool entries
190 BtPool *pool; // memory pool page segments
191 BtSpinLatch *latch; // latches for pool hash slots
193 HANDLE halloc, hlatch; // allocation and latch table handles
198 BtMgr *mgr; // buffer manager for thread
199 BtPage temp; // temporary frame buffer (memory mapped/file IO)
200 BtPage alloc; // frame buffer for alloc page ( page 0 )
201 BtPage cursor; // cached frame for start/next (never mapped)
202 BtPage frame; // spare frame for the page split (never mapped)
203 BtPage zero; // page frame for zeroes at end of file
204 BtPage page; // current page
205 uid page_no; // current page number
206 uid cursor_page; // current cursor page number
207 unsigned char *mem; // frame, cursor, page memory buffer
208 int err; // last error
223 extern void bt_close (BtDb *bt);
224 extern BtDb *bt_open (BtMgr *mgr);
225 extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod);
226 extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl);
227 extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
228 extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
229 extern uint bt_nextkey (BtDb *bt, uint slot);
232 extern BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolsize, uint segsize, uint hashsize);
233 void bt_mgrclose (BtMgr *mgr);
235 // Helper functions to return cursor slot values
237 extern BtKey bt_key (BtDb *bt, uint slot);
238 extern uid bt_uid (BtDb *bt, uint slot);
239 extern uint bt_tod (BtDb *bt, uint slot);
241 // BTree page number constants
242 #define ALLOC_page 0 // allocation of new pages
243 #define ROOT_page 1 // root of the btree
244 #define LEAF_page 2 // first page of leaves
246 // Number of levels to create in a new BTree
250 // The page is allocated from low and hi ends.
251 // The key offsets and row-id's are allocated
252 // from the bottom, while the text of the key
253 // is allocated from the top. When the two
254 // areas meet, the page is split into two.
256 // A key consists of a length byte, two bytes of
257 // index number (0 - 65534), and up to 253 bytes
258 // of key value. Duplicate keys are discarded.
259 // Associated with each key is a 48 bit row-id.
261 // The b-tree root is always located at page 1.
262 // The first leaf page of level zero is always
263 // located on page 2.
265 // When to root page fills, it is split in two and
266 // the tree height is raised by a new root at page
267 // one with two keys.
269 // Deleted keys are marked with a dead bit until
270 // page cleanup The fence key for a node is always
271 // present, even after deletion and cleanup.
273 // Groups of pages called segments from the btree are
274 // cached with memory mapping. A hash table is used to keep
275 // track of the cached segments. This behaviour is controlled
276 // by the cache block size parameter to bt_open.
278 // To achieve maximum concurrency one page is locked at a time
279 // as the tree is traversed to find leaf key in question.
281 // An adoption traversal leaves the parent node locked as the
282 // tree is traversed to the level in quesiton.
284 // Page 0 is dedicated to lock for new page extensions,
285 // and chains empty pages together for reuse.
287 // Empty pages are chained together through the ALLOC page and reused.
289 // Access macros to address slot and key values from the page
291 #define slotptr(page, slot) (((BtSlot *)(page+1)) + (slot-1))
292 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
294 void bt_putid(unsigned char *dest, uid id)
299 dest[i] = (unsigned char)id, id >>= 8;
302 uid bt_getid(unsigned char *src)
307 for( i = 0; i < BtId; i++ )
308 id <<= 8, id |= *src++;
313 // wait until write lock mode is clear
314 // and add 1 to the share count
316 void bt_spinreadlock(BtSpinLatch *latch)
322 do prev = __sync_fetch_and_or((ushort *)latch, Mutex);
323 while( prev & Mutex );
325 do prev = _InterlockedOr16((ushort *)latch, Mutex);
326 while( prev & Mutex );
329 // see if exclusive request is pending, or granted
331 if( prev = !(latch->exclusive | latch->pending) )
339 } while( sched_yield(), 1 );
341 } while( SwitchToThread(), 1 );
345 // wait for other read and write latches to relinquish
347 void bt_spinwritelock(BtSpinLatch *latch)
353 do prev = __sync_fetch_and_or((ushort *)latch, (Pending | Mutex));
354 while( prev & Mutex );
356 do prev = _InterlockedOr16((ushort *)latch, (Pending | Mutex));
357 while( prev & Mutex );
359 if( prev = !(latch->share | latch->exclusive) )
360 latch->exclusive = 1, latch->pending = 0;
374 // try to obtain write lock
376 // return 1 if obtained,
379 int bt_spinwritetry(BtSpinLatch *latch)
384 do prev = __sync_fetch_and_or((ushort *)latch, Mutex);
385 while( prev & Mutex );
387 do prev = _InterlockedOr16((ushort *)latch, Mutex);
388 while( prev & Mutex );
390 // take write access if all bits are clear
393 latch->exclusive = 1;
401 void bt_spinreleasewrite(BtSpinLatch *latch)
406 do prev = __sync_fetch_and_or((ushort *)latch, Mutex);
407 while( prev & Mutex );
409 do prev = _InterlockedOr16((ushort *)latch, Mutex);
410 while( prev & Mutex );
413 latch->exclusive = 0;
417 // decrement reader count
419 void bt_spinreleaseread(BtSpinLatch *latch)
424 do prev = __sync_fetch_and_or((ushort *)latch, Mutex);
425 while( prev & Mutex );
427 do prev = _InterlockedOr16((ushort *)latch, Mutex);
428 while( prev & Mutex );
435 void bt_mgrclose (BtMgr *mgr)
440 // release mapped pages
441 // note that slot zero is never used
443 for( slot = 1; slot < mgr->poolmax; slot++ ) {
444 pool = mgr->pool + slot;
447 munmap (pool->map, (mgr->poolmask+1) << mgr->page_bits);
450 FlushViewOfFile(pool->map, 0);
451 UnmapViewOfFile(pool->map);
452 CloseHandle(pool->hmap);
461 free (mgr->pooladvise);
464 FlushFileBuffers(mgr->idx);
465 CloseHandle(mgr->idx);
466 GlobalFree (mgr->pool);
467 GlobalFree (mgr->hash);
472 // close and release memory
474 void bt_close (BtDb *bt)
481 VirtualFree (bt->mem, 0, MEM_RELEASE);
486 // open/create new btree buffer manager
488 // call with file_name, BT_openmode, bits in page size (e.g. 16),
489 // size of mapped page pool (e.g. 8192)
491 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
493 uint lvl, attr, cacheblk, last, slot, idx;
502 SYSTEM_INFO sysinfo[1];
505 // determine sanity of page size and buffer pool
507 if( bits > BT_maxbits )
509 else if( bits < BT_minbits )
513 return NULL; // must have buffer pool
516 mgr = calloc (1, sizeof(BtMgr));
518 switch (mode & 0x7fff)
521 mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
527 mgr->idx = open ((char*)name, O_RDONLY);
532 return free(mgr), NULL;
534 cacheblk = 4096; // minimum mmap segment size for unix
537 mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
538 attr = FILE_ATTRIBUTE_NORMAL;
539 switch (mode & 0x7fff)
542 mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
548 mgr->idx = CreateFile(name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, attr, NULL);
552 if( mgr->idx == INVALID_HANDLE_VALUE )
553 return GlobalFree(mgr), NULL;
555 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
556 GetSystemInfo(sysinfo);
557 cacheblk = sysinfo->dwAllocationGranularity;
561 alloc = malloc (BT_maxpage);
564 // read minimum page size to get root info
566 if( size = lseek (mgr->idx, 0L, 2) ) {
567 if( pread(mgr->idx, alloc, BT_minpage, 0) == BT_minpage )
570 return free(mgr), free(alloc), NULL;
571 } else if( mode == BT_ro )
572 return bt_mgrclose (mgr), NULL;
574 alloc = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
575 size = GetFileSize(mgr->idx, amt);
578 if( !ReadFile(mgr->idx, (char *)alloc, BT_minpage, amt, NULL) )
579 return bt_mgrclose (mgr), NULL;
581 } else if( mode == BT_ro )
582 return bt_mgrclose (mgr), NULL;
585 mgr->page_size = 1 << bits;
586 mgr->page_bits = bits;
588 mgr->poolmax = poolmax;
591 if( cacheblk < mgr->page_size )
592 cacheblk = mgr->page_size;
594 // mask for partial memmaps
596 mgr->poolmask = (cacheblk >> bits) - 1;
598 // see if requested size of pages per memmap is greater
600 if( (1 << segsize) > mgr->poolmask )
601 mgr->poolmask = (1 << segsize) - 1;
605 while( (1 << mgr->seg_bits) <= mgr->poolmask )
608 mgr->hashsize = hashsize;
611 mgr->pool = calloc (poolmax, sizeof(BtPool));
612 mgr->hash = calloc (hashsize, sizeof(ushort));
613 mgr->latch = calloc (hashsize, sizeof(BtSpinLatch));
614 mgr->pooladvise = calloc (poolmax, (mgr->poolmask + 8) / 8);
616 mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * (sizeof(BtPool)));
617 mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
618 mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtSpinLatch));
623 // initializes an empty b-tree with root page and page of leaves
625 memset (alloc, 0, 1 << bits);
626 bt_putid(alloc->right, MIN_lvl+1);
627 alloc->bits = mgr->page_bits;
630 if( write (mgr->idx, alloc, mgr->page_size) < mgr->page_size )
631 return bt_mgrclose (mgr), NULL;
633 if( !WriteFile (mgr->idx, (char *)alloc, mgr->page_size, amt, NULL) )
634 return bt_mgrclose (mgr), NULL;
636 if( *amt < mgr->page_size )
637 return bt_mgrclose (mgr), NULL;
640 memset (alloc, 0, 1 << bits);
641 alloc->bits = mgr->page_bits;
643 for( lvl=MIN_lvl; lvl--; ) {
644 slotptr(alloc, 1)->off = mgr->page_size - 3;
645 bt_putid(slotptr(alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
646 key = keyptr(alloc, 1);
647 key->len = 2; // create stopper key
650 alloc->min = mgr->page_size - 3;
655 if( write (mgr->idx, alloc, mgr->page_size) < mgr->page_size )
656 return bt_mgrclose (mgr), NULL;
658 if( !WriteFile (mgr->idx, (char *)alloc, mgr->page_size, amt, NULL) )
659 return bt_mgrclose (mgr), NULL;
661 if( *amt < mgr->page_size )
662 return bt_mgrclose (mgr), NULL;
666 // create empty page area by writing last page of first
667 // segment area (other pages are zeroed by O/S)
669 if( mgr->poolmask ) {
670 memset(alloc, 0, mgr->page_size);
671 last = mgr->poolmask;
673 while( last < MIN_lvl + 1 )
674 last += mgr->poolmask + 1;
677 pwrite(mgr->idx, alloc, mgr->page_size, last << mgr->page_bits);
679 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
680 if( !WriteFile (mgr->idx, (char *)alloc, mgr->page_size, amt, NULL) )
681 return bt_mgrclose (mgr), NULL;
682 if( *amt < mgr->page_size )
683 return bt_mgrclose (mgr), NULL;
691 VirtualFree (alloc, 0, MEM_RELEASE);
696 // open BTree access method
697 // based on buffer manager
699 BtDb *bt_open (BtMgr *mgr)
701 BtDb *bt = malloc (sizeof(*bt));
703 memset (bt, 0, sizeof(*bt));
706 bt->mem = malloc (3 *mgr->page_size);
708 bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
710 bt->frame = (BtPage)bt->mem;
711 bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
712 bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
716 // compare two keys, returning > 0, = 0, or < 0
717 // as the comparison value
719 int keycmp (BtKey key1, unsigned char *key2, uint len2)
721 uint len1 = key1->len;
724 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
737 // find segment in pool
738 // must be called with hashslot idx locked
739 // return NULL if not there
740 // otherwise return node
742 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
747 // compute start of hash chain in pool
749 if( slot = bt->mgr->hash[idx] )
750 pool = bt->mgr->pool + slot;
754 page_no &= ~bt->mgr->poolmask;
756 while( pool->basepage != page_no )
757 if( pool = pool->hashnext )
765 // add segment to hash table
767 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
772 pool->hashprev = pool->hashnext = NULL;
773 pool->basepage = page_no & ~bt->mgr->poolmask;
776 if( slot = bt->mgr->hash[idx] ) {
777 node = bt->mgr->pool + slot;
778 pool->hashnext = node;
779 node->hashprev = pool;
782 bt->mgr->hash[idx] = pool->slot;
785 // find best segment to evict from buffer pool
787 BtPool *bt_findlru (BtDb *bt, uint hashslot)
789 unsigned long long int target = ~0LL;
790 BtPool *pool = NULL, *node;
795 node = bt->mgr->pool + hashslot;
797 // scan pool entries under hash table slot
802 if( node->lru > target )
806 } while( node = node->hashnext );
811 // map new buffer pool segment to virtual memory
813 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
815 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
816 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
820 flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
821 pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED, bt->mgr->idx, off);
822 if( pool->map == MAP_FAILED )
823 return bt->err = BTERR_map;
824 // clear out madvise issued bits
825 memset (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8) / 8), 0, (bt->mgr->poolmask + 8)/8);
827 flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
828 pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
830 return bt->err = BTERR_map;
832 flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
833 pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
835 return bt->err = BTERR_map;
840 // find or place requested page in segment-pool
841 // return pool table entry, incrementing pin
843 BtPool *bt_pinpage(BtDb *bt, uid page_no)
845 BtPool *pool, *node, *next;
846 uint slot, idx, victim;
848 // lock hash table chain
850 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
851 bt_spinreadlock (&bt->mgr->latch[idx]);
853 // look up in hash table
855 if( pool = bt_findpool(bt, page_no, idx) ) {
857 __sync_fetch_and_add(&pool->pin, 1);
859 _InterlockedIncrement16 (&pool->pin);
861 bt_spinreleaseread (&bt->mgr->latch[idx]);
866 // upgrade to write lock
868 bt_spinreleaseread (&bt->mgr->latch[idx]);
869 bt_spinwritelock (&bt->mgr->latch[idx]);
871 // try to find page in pool with write lock
873 if( pool = bt_findpool(bt, page_no, idx) ) {
875 __sync_fetch_and_add(&pool->pin, 1);
877 _InterlockedIncrement16 (&pool->pin);
879 bt_spinreleasewrite (&bt->mgr->latch[idx]);
884 // allocate a new pool node
885 // and add to hash table
888 slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
890 slot = _InterlockedIncrement16 (&bt->mgr->poolcnt) - 1;
893 if( ++slot < bt->mgr->poolmax ) {
894 pool = bt->mgr->pool + slot;
897 if( bt_mapsegment(bt, pool, page_no) )
900 bt_linkhash(bt, pool, page_no, idx);
902 __sync_fetch_and_add(&pool->pin, 1);
904 _InterlockedIncrement16 (&pool->pin);
906 bt_spinreleasewrite (&bt->mgr->latch[idx]);
910 // pool table is full
911 // find best pool entry to evict
914 __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
916 _InterlockedDecrement16 (&bt->mgr->poolcnt);
921 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
923 victim = _InterlockedIncrement16 (&bt->mgr->evicted) - 1;
925 victim %= bt->mgr->hashsize;
927 // try to get write lock
928 // skip entry if not obtained
930 if( !bt_spinwritetry (&bt->mgr->latch[victim]) )
933 // if cache entry is empty
934 // or no slots are unpinned
937 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
938 bt_spinreleasewrite (&bt->mgr->latch[victim]);
942 // unlink victim pool node from hash table
944 if( node = pool->hashprev )
945 node->hashnext = pool->hashnext;
946 else if( node = pool->hashnext )
947 bt->mgr->hash[victim] = node->slot;
949 bt->mgr->hash[victim] = 0;
951 if( node = pool->hashnext )
952 node->hashprev = pool->hashprev;
954 bt_spinreleasewrite (&bt->mgr->latch[victim]);
956 // remove old file mapping
958 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
960 FlushViewOfFile(pool->map, 0);
961 UnmapViewOfFile(pool->map);
962 CloseHandle(pool->hmap);
966 // create new pool mapping
967 // and link into hash table
969 if( bt_mapsegment(bt, pool, page_no) )
972 bt_linkhash(bt, pool, page_no, idx);
974 __sync_fetch_and_add(&pool->pin, 1);
976 _InterlockedIncrement16 (&pool->pin);
978 bt_spinreleasewrite (&bt->mgr->latch[idx]);
983 // place write, read, or parent lock on requested page_no.
984 // pin to buffer pool and return page pointer
986 BTERR bt_lockpage(BtDb *bt, uid page_no, BtLock mode, BtPage *pageptr)
992 // find/create maping in pool table
993 // and pin our pool slot
995 if( pool = bt_pinpage(bt, page_no) )
996 subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1000 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1004 uint idx = subpage / 8;
1005 uint bit = subpage % 8;
1007 if( ~((bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] >> bit) & 1 ) {
1008 madvise (page, bt->mgr->page_size, MADV_WILLNEED);
1009 (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] |= 1 << bit;
1016 bt_spinreadlock (page->readwr);
1019 bt_spinwritelock (page->readwr);
1022 bt_spinreadlock (page->access);
1025 bt_spinwritelock (page->access);
1028 bt_spinwritelock (page->parent);
1031 return bt->err = BTERR_lock;
1040 // remove write, read, or parent lock on requested page_no.
1042 BTERR bt_unlockpage(BtDb *bt, uid page_no, BtLock mode)
1049 // since page is pinned
1050 // it should still be in the buffer pool
1051 // and is in no danger of being a victim for reuse
1053 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1054 bt_spinreadlock (&bt->mgr->latch[idx]);
1056 if( !(pool = bt_findpool(bt, page_no, idx)) )
1057 return bt->err = BTERR_hash;
1059 bt_spinreleaseread (&bt->mgr->latch[idx]);
1061 subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1062 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1066 bt_spinreleaseread (page->readwr);
1069 bt_spinreleasewrite (page->readwr);
1072 bt_spinreleaseread (page->access);
1075 bt_spinreleasewrite (page->access);
1078 bt_spinreleasewrite (page->parent);
1081 return bt->err = BTERR_lock;
1085 __sync_fetch_and_add(&pool->pin, -1);
1087 _InterlockedDecrement16 (&pool->pin);
1092 // deallocate a deleted page
1093 // place on free chain out of allocator page
1094 // fence key must already be removed from parent
1096 BTERR bt_freepage(BtDb *bt, uid page_no)
1098 // obtain delete lock on deleted page
1100 if( bt_lockpage(bt, page_no, BtLockDelete, NULL) )
1103 // obtain write lock on deleted page
1105 if( bt_lockpage(bt, page_no, BtLockWrite, &bt->temp) )
1108 // lock allocation page
1110 if ( bt_lockpage(bt, ALLOC_page, BtLockWrite, &bt->alloc) )
1113 // store free chain in allocation page second right
1114 bt_putid(bt->temp->right, bt_getid(bt->alloc[1].right));
1115 bt_putid(bt->alloc[1].right, page_no);
1117 // unlock allocation page
1119 if( bt_unlockpage(bt, ALLOC_page, BtLockWrite) )
1122 // remove write lock on deleted node
1124 if( bt_unlockpage(bt, page_no, BtLockWrite) )
1127 // remove delete lock on deleted node
1129 if( bt_unlockpage(bt, page_no, BtLockDelete) )
1135 // allocate a new page and write page into it
1137 uid bt_newpage(BtDb *bt, BtPage page)
1143 // lock allocation page
1145 if ( bt_lockpage(bt, ALLOC_page, BtLockWrite, &bt->alloc) )
1148 // use empty chain first
1149 // else allocate empty page
1151 if( new_page = bt_getid(bt->alloc[1].right) ) {
1152 if( bt_lockpage (bt, new_page, BtLockWrite, &bt->temp) )
1154 bt_putid(bt->alloc[1].right, bt_getid(bt->temp->right));
1155 if( bt_unlockpage (bt, new_page, BtLockWrite) )
1159 new_page = bt_getid(bt->alloc->right);
1160 bt_putid(bt->alloc->right, new_page+1);
1164 memset(bt->zero, 0, 3 * sizeof(BtSpinLatch)); // clear locks
1165 memcpy((char *)bt->zero + 3 * sizeof(BtSpinLatch), (char *)page + 3 * sizeof(BtSpinLatch), bt->mgr->page_size - 3 * sizeof(BtSpinLatch));
1166 if ( pwrite(bt->mgr->idx, bt->zero, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1167 return bt->err = BTERR_wrt, 0;
1169 // if writing first page of pool block, zero last page in the block
1171 if ( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1173 // use zero buffer to write zeros
1174 memset(bt->zero, 0, bt->mgr->page_size);
1175 if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1176 return bt->err = BTERR_wrt, 0;
1179 // bring new page into pool and copy page.
1180 // this will extend the file into the new pages.
1182 if( bt_lockpage(bt, new_page, BtLockWrite, &pmap) )
1185 memcpy(pmap, page, bt->mgr->page_size);
1187 if( bt_unlockpage (bt, new_page, BtLockWrite) )
1190 // unlock allocation latch and return new page no
1192 if ( bt_unlockpage(bt, ALLOC_page, BtLockWrite) )
1198 // find slot in page for given key at a given level
1200 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1202 uint diff, higher = bt->page->cnt, low = 1, slot;
1204 // low is the lowest candidate, higher is already
1205 // tested as .ge. the given key, loop ends when they meet
1207 while( diff = higher - low ) {
1208 slot = low + ( diff >> 1 );
1209 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1218 // find and load page at given level for given key
1219 // leave page rd or wr locked as requested
1221 int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, uint lock)
1223 uid page_no = ROOT_page, prevpage = 0;
1224 uint drill = 0xff, slot;
1225 uint mode, prevmode;
1227 // start at root of btree and drill down
1230 // determine lock mode of drill level
1231 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1233 bt->page_no = page_no;
1235 // obtain access lock using lock chaining with Access mode
1237 if( page_no > ROOT_page )
1238 if( bt_lockpage(bt, page_no, BtLockAccess, NULL) )
1241 // now unlock our (possibly foster) parent
1244 if( bt_unlockpage(bt, prevpage, prevmode) )
1249 // obtain read lock using lock chaining
1250 // and pin page contents
1252 if( bt_lockpage(bt, page_no, mode, &bt->page) )
1255 if( page_no > ROOT_page )
1256 if( bt_unlockpage(bt, page_no, BtLockAccess) )
1259 // re-read and re-lock root after determining actual level of root
1261 if( bt->page_no == ROOT_page )
1262 if( bt->page->lvl != drill) {
1263 drill = bt->page->lvl;
1265 if( lock == BtLockWrite && drill == lvl )
1266 if( bt_unlockpage(bt, page_no, mode) )
1272 prevpage = bt->page_no;
1275 // if page is being deleted,
1276 // move back to preceeding page
1278 if( bt->page->kill ) {
1279 page_no = bt_getid (bt->page->right);
1283 // find key on page at this level
1284 // and descend to requested level
1286 slot = bt_findslot (bt, key, len);
1288 // is this slot a foster child?
1290 if( slot <= bt->page->cnt - bt->page->foster )
1294 while( slotptr(bt->page, slot)->dead )
1295 if( slot++ < bt->page->cnt )
1300 if( slot <= bt->page->cnt - bt->page->foster )
1303 // continue down / right using overlapping locks
1304 // to protect pages being killed or split.
1306 page_no = bt_getid(slotptr(bt->page, slot)->id);
1310 page_no = bt_getid(bt->page->right);
1314 // return error on end of chain
1316 bt->err = BTERR_struct;
1317 return 0; // return error
1320 // find and delete key on page by marking delete flag bit
1321 // when page becomes empty, delete it from the btree
1323 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl)
1325 unsigned char leftkey[256], rightkey[256];
1330 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1331 ptr = keyptr(bt->page, slot);
1335 // if key is found delete it, otherwise ignore request
1337 if( !keycmp (ptr, key, len) )
1338 if( slotptr(bt->page, slot)->dead == 0 ) {
1339 slotptr(bt->page,slot)->dead = 1;
1340 if( slot < bt->page->cnt )
1341 bt->page->dirty = 1;
1345 // return if page is not empty, or it has no right sibling
1347 right = bt_getid(bt->page->right);
1348 page_no = bt->page_no;
1350 if( !right || bt->page->act )
1351 return bt_unlockpage(bt, page_no, BtLockWrite);
1353 // obtain Parent lock over write lock
1355 if( bt_lockpage(bt, page_no, BtLockParent, NULL) )
1358 // cache copy of key to delete
1360 ptr = keyptr(bt->page, bt->page->cnt);
1361 memcpy(leftkey, ptr, ptr->len + 1);
1363 // lock and map right page
1365 if( bt_lockpage(bt, right, BtLockWrite, &bt->temp) )
1368 // pull contents of next page into current empty page
1369 memcpy (bt->page, bt->temp, bt->mgr->page_size);
1371 // cache copy of key to update
1372 ptr = keyptr(bt->temp, bt->temp->cnt);
1373 memcpy(rightkey, ptr, ptr->len + 1);
1375 // Mark right page as deleted and point it to left page
1376 // until we can post updates at higher level.
1378 bt_putid(bt->temp->right, page_no);
1382 if( bt_unlockpage(bt, right, BtLockWrite) )
1384 if( bt_unlockpage(bt, page_no, BtLockWrite) )
1387 // delete old lower key to consolidated node
1389 if( bt_deletekey (bt, leftkey + 1, *leftkey, lvl + 1) )
1392 // redirect higher key directly to consolidated node
1394 if( slot = bt_loadpage (bt, rightkey+1, *rightkey, lvl+1, BtLockWrite) )
1395 ptr = keyptr(bt->page, slot);
1399 // since key already exists, update id
1401 if( keycmp (ptr, rightkey+1, *rightkey) )
1402 return bt->err = BTERR_struct;
1404 slotptr(bt->page, slot)->dead = 0;
1405 bt_putid(slotptr(bt->page,slot)->id, page_no);
1407 if( bt_unlockpage(bt, bt->page_no, BtLockWrite) )
1410 // obtain write lock and
1411 // add right block to free chain
1413 if( bt_freepage (bt, right) )
1416 // remove ParentModify lock
1418 if( bt_unlockpage(bt, page_no, BtLockParent) )
1424 // find key in leaf level and return row-id
1426 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1432 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1433 ptr = keyptr(bt->page, slot);
1437 // if key exists, return row-id
1438 // otherwise return 0
1440 if( ptr->len == len && !memcmp (ptr->key, key, len) )
1441 id = bt_getid(slotptr(bt->page,slot)->id);
1445 if( bt_unlockpage (bt, bt->page_no, BtLockRead) )
1451 // check page for space available,
1452 // clean if necessary and return
1453 // 0 - page needs splitting
1456 uint bt_cleanpage(BtDb *bt, uint amt)
1458 uint nxt = bt->mgr->page_size;
1459 BtPage page = bt->page;
1460 uint cnt = 0, idx = 0;
1461 uint max = page->cnt;
1464 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1467 // skip cleanup if nothing to reclaim
1472 memcpy (bt->frame, page, bt->mgr->page_size);
1474 // skip page info and set rest of page to zero
1476 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1480 // try cleaning up page first
1482 while( cnt++ < max ) {
1483 // always leave fence key and foster children in list
1484 if( cnt < max - page->foster && slotptr(bt->frame,cnt)->dead )
1488 key = keyptr(bt->frame, cnt);
1489 nxt -= key->len + 1;
1490 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1493 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1494 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1496 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1497 slotptr(page, idx)->off = nxt;
1503 // see if page has enough space now, or does it need splitting?
1505 if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1511 // add key to current page
1512 // page must already be writelocked
1514 void bt_addkeytopage (BtDb *bt, uint slot, unsigned char *key, uint len, uid id, uint tod)
1516 BtPage page = bt->page;
1519 // calculate next available slot and copy key into page
1521 page->min -= len + 1;
1522 ((unsigned char *)page)[page->min] = len;
1523 memcpy ((unsigned char *)page + page->min +1, key, len );
1525 for( idx = slot; idx < page->cnt; idx++ )
1526 if( slotptr(page, idx)->dead )
1529 // now insert key into array before slot
1530 // preserving the fence slot
1532 if( idx == page->cnt )
1538 *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
1540 bt_putid(slotptr(page,slot)->id, id);
1541 slotptr(page, slot)->off = page->min;
1542 slotptr(page, slot)->tod = tod;
1543 slotptr(page, slot)->dead = 0;
1546 // split the root and raise the height of the btree
1547 // call with current page locked and page no of foster child
1548 // return with current page (root) unlocked
1550 BTERR bt_splitroot(BtDb *bt, uid right)
1552 uint nxt = bt->mgr->page_size;
1553 unsigned char fencekey[256];
1554 BtPage root = bt->page;
1558 // Obtain an empty page to use, and copy the left page
1559 // contents into it from the root. Strip foster child key.
1560 // (it's the stopper key)
1566 // Save left fence key.
1568 key = keyptr(root, root->cnt);
1569 memcpy (fencekey, key, key->len + 1);
1571 // copy the lower keys into a new left page
1573 if( !(new_page = bt_newpage(bt, root)) )
1576 // preserve the page info at the bottom
1577 // and set rest of the root to zero
1579 memset (root+1, 0, bt->mgr->page_size - sizeof(*root));
1581 // insert left fence key on empty newroot page
1583 nxt -= *fencekey + 1;
1584 memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
1585 bt_putid(slotptr(root, 1)->id, new_page);
1586 slotptr(root, 1)->off = nxt;
1588 // insert stopper key on newroot page
1589 // and increase the root height
1595 memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
1596 bt_putid(slotptr(root, 2)->id, right);
1597 slotptr(root, 2)->off = nxt;
1599 bt_putid(root->right, 0);
1600 root->min = nxt; // reset lowest used offset and key count
1605 // release root (bt->page)
1607 return bt_unlockpage(bt, ROOT_page, BtLockWrite);
1610 // split already locked full node
1611 // in current page variables
1614 BTERR bt_splitpage (BtDb *bt)
1616 uint slot, cnt, idx, max, nxt = bt->mgr->page_size;
1617 unsigned char fencekey[256];
1618 uid page_no = bt->page_no;
1619 BtPage page = bt->page;
1620 uint tod = time(NULL);
1621 uint lvl = page->lvl;
1622 uid new_page, right;
1625 // initialize frame buffer
1627 memset (bt->frame, 0, bt->mgr->page_size);
1628 max = page->cnt - page->foster;
1629 tod = (uint)time(NULL);
1633 // split higher half of keys to bt->frame
1634 // leaving foster children in the left node.
1636 while( cnt++ < max ) {
1637 key = keyptr(page, cnt);
1638 nxt -= key->len + 1;
1639 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
1640 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
1641 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
1642 slotptr(bt->frame, idx)->off = nxt;
1646 // transfer right link node
1648 if( page_no > ROOT_page ) {
1649 right = bt_getid (page->right);
1650 bt_putid(bt->frame->right, right);
1653 bt->frame->bits = bt->mgr->page_bits;
1654 bt->frame->min = nxt;
1655 bt->frame->cnt = idx;
1656 bt->frame->lvl = lvl;
1658 // get new free page and write frame to it.
1660 if( !(new_page = bt_newpage(bt, bt->frame)) )
1663 // remember fence key for new page to add
1666 key = keyptr(bt->frame, idx);
1667 memcpy (fencekey, key, key->len + 1);
1669 // update lower keys and foster children to continue in old page
1671 memcpy (bt->frame, page, bt->mgr->page_size);
1672 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1673 nxt = bt->mgr->page_size;
1678 // assemble page of smaller keys
1679 // to remain in the old page
1681 while( cnt++ < max / 2 ) {
1682 key = keyptr(bt->frame, cnt);
1683 nxt -= key->len + 1;
1684 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1685 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1686 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1687 slotptr(page, idx)->off = nxt;
1691 // insert new foster child at beginning of the current foster children
1693 nxt -= *fencekey + 1;
1694 memcpy ((unsigned char *)page + nxt, fencekey, *fencekey + 1);
1695 bt_putid (slotptr(page,++idx)->id, new_page);
1696 slotptr(page, idx)->tod = tod;
1697 slotptr(page, idx)->off = nxt;
1701 // continue with old foster child keys if any
1703 cnt = bt->frame->cnt - bt->frame->foster;
1705 while( cnt++ < bt->frame->cnt ) {
1706 key = keyptr(bt->frame, cnt);
1707 nxt -= key->len + 1;
1708 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1709 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1710 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1711 slotptr(page, idx)->off = nxt;
1718 // link new right page
1720 bt_putid (page->right, new_page);
1722 // if current page is the root page, split it
1724 if( page_no == ROOT_page )
1725 return bt_splitroot (bt, new_page);
1727 // release wr lock on our page
1729 if( bt_unlockpage (bt, page_no, BtLockWrite) )
1732 // obtain ParentModification lock for current page
1733 // to fix fence key and highest foster child on page
1735 if( bt_lockpage (bt, page_no, BtLockParent, NULL) )
1738 // get our highest foster child key to find in parent node
1740 if( bt_lockpage (bt, page_no, BtLockRead, &page) )
1743 key = keyptr(page, page->cnt);
1744 memcpy (fencekey, key, key->len+1);
1746 if( bt_unlockpage (bt, page_no, BtLockRead) )
1749 // update our parent
1753 slot = bt_loadpage (bt, fencekey + 1, *fencekey, lvl + 1, BtLockWrite);
1758 // check if parent page has enough space for any possible key
1760 if( bt_cleanpage (bt, 256) )
1763 if( bt_splitpage (bt) )
1767 // see if we are still a foster child from another node
1769 if( bt_getid (slotptr(bt->page, slot)->id) != page_no ) {
1770 if( bt_unlockpage (bt, bt->page_no, BtLockWrite) )
1780 // wait until readers from parent get their locks
1783 if( bt_lockpage (bt, page_no, BtLockDelete, NULL) )
1786 // lock our page for writing
1788 if( bt_lockpage (bt, page_no, BtLockWrite, &page) )
1791 // switch parent fence key to foster child
1793 if( slotptr(page, page->cnt)->dead )
1794 slotptr(bt->page, slot)->dead = 1;
1796 bt_putid (slotptr(bt->page, slot)->id, bt_getid(slotptr(page, page->cnt)->id));
1798 // remove highest foster child from our page
1804 key = keyptr(page, page->cnt);
1806 // add our new fence key for foster child to our parent
1808 bt_addkeytopage (bt, slot, key->key, key->len, page_no, tod);
1810 if( bt_unlockpage (bt, bt->page_no, BtLockWrite) )
1813 if( bt_unlockpage (bt, page_no, BtLockDelete) )
1816 if( bt_unlockpage (bt, page_no, BtLockWrite) )
1819 return bt_unlockpage (bt, page_no, BtLockParent);
1822 // Insert new key into the btree at leaf level.
1824 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod)
1831 if( slot = bt_loadpage (bt, key, len, 0, BtLockWrite) )
1832 ptr = keyptr(bt->page, slot);
1836 bt->err = BTERR_ovflw;
1840 // if key already exists, update id and return
1844 if( !keycmp (ptr, key, len) ) {
1845 slotptr(page, slot)->dead = 0;
1846 slotptr(page, slot)->tod = tod;
1847 bt_putid(slotptr(page,slot)->id, id);
1848 return bt_unlockpage(bt, bt->page_no, BtLockWrite);
1851 // check if page has enough space
1853 if( bt_cleanpage (bt, len) )
1856 if( bt_splitpage (bt) )
1860 bt_addkeytopage (bt, slot, key, len, id, tod);
1862 return bt_unlockpage (bt, bt->page_no, BtLockWrite);
1865 // cache page of keys into cursor and return starting slot for given key
1867 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
1871 // cache page for retrieval
1872 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1873 memcpy (bt->cursor, bt->page, bt->mgr->page_size);
1874 bt->cursor_page = bt->page_no;
1875 if ( bt_unlockpage(bt, bt->page_no, BtLockRead) )
1881 // return next slot for cursor page
1882 // or slide cursor right into next page
1884 uint bt_nextkey (BtDb *bt, uint slot)
1890 right = bt_getid(bt->cursor->right);
1891 while( slot++ < bt->cursor->cnt - bt->cursor->foster )
1892 if( slotptr(bt->cursor,slot)->dead )
1894 else if( right || (slot < bt->cursor->cnt - bt->cursor->foster) )
1902 bt->cursor_page = right;
1904 if( bt_lockpage(bt, right, BtLockRead, &page) )
1907 memcpy (bt->cursor, page, bt->mgr->page_size);
1909 if ( bt_unlockpage(bt, right, BtLockRead) )
1918 BtKey bt_key(BtDb *bt, uint slot)
1920 return keyptr(bt->cursor, slot);
1923 uid bt_uid(BtDb *bt, uint slot)
1925 return bt_getid(slotptr(bt->cursor,slot)->id);
1928 uint bt_tod(BtDb *bt, uint slot)
1930 return slotptr(bt->cursor,slot)->tod;
1943 // standalone program to index file of keys
1944 // then list them onto std-out
1947 void *index_file (void *arg)
1949 uint __stdcall index_file (void *arg)
1952 int line = 0, found = 0, cnt = 0;
1953 uid next, page_no = LEAF_page; // start on first page of leaves
1954 unsigned char key[256];
1955 ThreadArg *args = arg;
1956 int ch, len = 0, slot;
1963 bt = bt_open (args->mgr);
1966 switch(args->type | 0x20)
1969 fprintf(stderr, "started indexing for %s\n", args->infile);
1970 if( in = fopen (args->infile, "rb") )
1971 while( ch = getc(in), ch != EOF )
1976 if( args->num == 1 )
1977 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
1979 else if( args->num )
1980 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
1982 if( bt_insertkey (bt, key, len, line, *tod) )
1983 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
1986 else if( len < 255 )
1988 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
1992 fprintf(stderr, "started deleting keys for %s\n", args->infile);
1993 if( in = fopen (args->infile, "rb") )
1994 while( ch = getc(in), ch != EOF )
1998 if( args->num == 1 )
1999 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2001 else if( args->num )
2002 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2004 if( bt_deletekey (bt, key, len, 0) )
2005 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2008 else if( len < 255 )
2010 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2014 fprintf(stderr, "started finding keys for %s\n", args->infile);
2015 if( in = fopen (args->infile, "rb") )
2016 while( ch = getc(in), ch != EOF )
2020 if( args->num == 1 )
2021 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2023 else if( args->num )
2024 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2026 if( bt_findkey (bt, key, len) )
2029 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2032 else if( len < 255 )
2034 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2040 fprintf(stderr, "started reading\n");
2042 if( slot = bt_startkey (bt, key, len) )
2045 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
2047 while( slot = bt_nextkey (bt, slot) ) {
2048 ptr = bt_key(bt, slot);
2049 fwrite (ptr->key, ptr->len, 1, stdout);
2050 fputc ('\n', stdout);
2056 fprintf(stderr, "started reading\n");
2059 bt_lockpage (bt, page_no, BtLockRead, &page);
2061 next = bt_getid (page->right);
2062 bt_unlockpage (bt, page_no, BtLockRead);
2063 } while( page_no = next );
2065 cnt--; // remove stopper key
2066 fprintf(stderr, " Total keys read %d\n", cnt);
2078 typedef struct timeval timer;
2080 int main (int argc, char **argv)
2082 int idx, cnt, len, slot, err;
2083 int segsize, bits = 16;
2088 time_t start[1], stop[1];
2101 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]);
2102 fprintf (stderr, " where page_bits is the page size in bits\n");
2103 fprintf (stderr, " mapped_segments is the number of mmap segments in buffer pool\n");
2104 fprintf (stderr, " seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2105 fprintf (stderr, " line_numbers = 1 to append line numbers to keys\n");
2106 fprintf (stderr, " src_file1 thru src_filen are files of keys separated by newline\n");
2111 gettimeofday(&start, NULL);
2117 bits = atoi(argv[3]);
2120 poolsize = atoi(argv[4]);
2123 fprintf (stderr, "Warning: no mapped_pool\n");
2125 if( poolsize > 65535 )
2126 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2129 segsize = atoi(argv[5]);
2131 segsize = 4; // 16 pages per mmap segment
2134 num = atoi(argv[6]);
2138 threads = malloc (cnt * sizeof(pthread_t));
2140 threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2142 args = malloc (cnt * sizeof(ThreadArg));
2144 mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2147 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2153 for( idx = 0; idx < cnt; idx++ ) {
2154 args[idx].infile = argv[idx + 7];
2155 args[idx].type = argv[2][0];
2156 args[idx].mgr = mgr;
2157 args[idx].num = num;
2158 args[idx].idx = idx;
2160 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2161 fprintf(stderr, "Error creating thread %d\n", err);
2163 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2167 // wait for termination
2170 for( idx = 0; idx < cnt; idx++ )
2171 pthread_join (threads[idx], NULL);
2172 gettimeofday(&stop, NULL);
2173 real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2175 WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2177 for( idx = 0; idx < cnt; idx++ )
2178 CloseHandle(threads[idx]);
2181 real_time = 1000 * (*stop - *start);
2183 fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);