1 // foster btree version b
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 // The first part of an index page.
118 // It is immediately followed
119 // by the BtSlot array of keys.
121 typedef struct Page {
122 uint cnt; // count of keys in page
123 uint act; // count of active keys
124 uint min; // next key offset
125 uint foster; // count of foster children
126 unsigned char bits; // page size in bits
127 unsigned char lvl:6; // level of page
128 unsigned char kill:1; // page is being deleted
129 unsigned char dirty:1; // page needs to be cleaned
130 unsigned char right[BtId]; // page number to right
133 // mode & definition for latch table implementation
141 // latch table lock structure
143 // exclusive is set for write access
144 // share is count of read accessors
145 // grant write lock when share == 0
148 volatile uint exclusive:1;
149 volatile uint request:1;
150 volatile uint share:30;
154 BtLatch readwr[1]; // read/write page lock
155 BtLatch access[1]; // Access Intent/Page delete
156 BtLatch parent[1]; // adoption of foster children
159 // The memory mapping pool table buffer manager entry
162 unsigned long long int lru; // number of times accessed
163 uid basepage; // mapped base page number
164 char *map; // mapped memory pointer
165 uint pin; // mapped page pin counter
166 uint slot; // slot index in this array
167 void *hashprev; // previous pool entry for the same hash idx
168 void *hashnext; // next pool entry for the same hash idx
172 // array of page latch sets, one for each page in map segment
173 BtLatchSet pagelatch[0];
176 // The object structure for Btree access
179 uint page_size; // page size
180 uint page_bits; // page size in bits
181 uint seg_bits; // seg size in pages in bits
182 uint mode; // read-write mode
185 char *pooladvise; // bit maps for pool page advisements
189 uint poolcnt; // highest page pool node in use
190 uint poolmax; // highest page pool node allocated
191 uint poolmask; // total size of pages in mmap segment - 1
192 uint hashsize; // size of Hash Table for pool entries
193 volatile uint evicted; // last evicted hash table slot
194 ushort *hash; // hash table of pool entries
195 BtLatch *latch; // latches for hash table slots
196 char *nodes; // memory pool page segments
200 BtMgr *mgr; // buffer manager for thread
201 BtPage temp; // temporary frame buffer (memory mapped/file IO)
202 BtPage alloc; // frame buffer for alloc page ( page 0 )
203 BtPage cursor; // cached frame for start/next (never mapped)
204 BtPage frame; // spare frame for the page split (never mapped)
205 BtPage zero; // page frame for zeroes at end of file
206 BtPage page; // current page
207 uid page_no; // current page number
208 uid cursor_page; // current cursor page number
209 unsigned char *mem; // frame, cursor, page memory buffer
210 int err; // last error
224 extern void bt_close (BtDb *bt);
225 extern BtDb *bt_open (BtMgr *mgr);
226 extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod);
227 extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl);
228 extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
229 extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
230 extern uint bt_nextkey (BtDb *bt, uint slot);
233 bt_mgr (char *name, uint mode, uint bits, uint poolsize, uint segsize, uint hashsize);
234 void bt_mgrclose (BtMgr *mgr);
236 // Helper functions to return cursor slot values
238 extern BtKey bt_key (BtDb *bt, uint slot);
239 extern uid bt_uid (BtDb *bt, uint slot);
240 extern uint bt_tod (BtDb *bt, uint slot);
242 // BTree page number constants
247 // Number of levels to create in a new BTree
251 // The page is allocated from low and hi ends.
252 // The key offsets and row-id's are allocated
253 // from the bottom, while the text of the key
254 // is allocated from the top. When the two
255 // areas meet, the page is split into two.
257 // A key consists of a length byte, two bytes of
258 // index number (0 - 65534), and up to 253 bytes
259 // of key value. Duplicate keys are discarded.
260 // Associated with each key is a 48 bit row-id.
262 // The b-tree root is always located at page 1.
263 // The first leaf page of level zero is always
264 // located on page 2.
266 // When to root page fills, it is split in two and
267 // the tree height is raised by a new root at page
268 // one with two keys.
270 // Deleted keys are marked with a dead bit until
271 // page cleanup The fence key for a node is always
272 // present, even after deletion and cleanup.
274 // Groups of pages called segments from the btree are
275 // cached with memory mapping. A hash table is used to keep
276 // track of the cached segments. This behaviour is controlled
277 // by the cache block size parameter to bt_open.
279 // To achieve maximum concurrency one page is locked at a time
280 // as the tree is traversed to find leaf key in question.
282 // An adoption traversal leaves the parent node locked as the
283 // tree is traversed to the level in quesiton.
285 // Page 0 is dedicated to lock for new page extensions,
286 // and chains empty pages together for reuse.
288 // Empty pages are chained together through the ALLOC page and reused.
290 // Access macros to address slot and key values from the page
292 #define slotptr(page, slot) (((BtSlot *)(page+1)) + (slot-1))
293 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
295 void bt_putid(unsigned char *dest, uid id)
300 dest[i] = (unsigned char)id, id >>= 8;
303 uid bt_getid(unsigned char *src)
308 for( i = 0; i < BtId; i++ )
309 id <<= 8, id |= *src++;
314 void bt_mgrclose (BtMgr *mgr)
319 // release mapped pages
320 // note that slot zero is never used
322 for( slot = 1; slot < mgr->poolmax; slot++ ) {
323 pool = (BtPool *)(mgr->nodes + slot * (sizeof(BtPool) + (mgr->poolmask + 1) * sizeof(BtLatchSet)));
326 munmap (pool->map, (mgr->poolmask+1) << mgr->page_bits);
329 FlushViewOfFile(pool->map, 0);
330 UnmapViewOfFile(pool->map);
331 CloseHandle(pool->hmap);
341 free (mgr->pooladvise);
344 FlushFileBuffers(mgr->idx);
345 CloseHandle(mgr->idx);
346 GlobalFree (mgr->nodes);
347 GlobalFree (mgr->hash);
348 GlobalFree (mgr->latch);
353 // close and release memory
355 void bt_close (BtDb *bt)
362 VirtualFree (bt->mem, 0, MEM_RELEASE);
367 // open/create new btree buffer manager
369 // call with file_name, BT_openmode, bits in page size (e.g. 16),
370 // size of mapped page pool (e.g. 8192)
372 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
374 uint lvl, attr, cacheblk, last;
383 SYSTEM_INFO sysinfo[1];
386 // determine sanity of page size and buffer pool
388 if( bits > BT_maxbits )
390 else if( bits < BT_minbits )
394 return NULL; // must have buffer pool
397 mgr = calloc (1, sizeof(BtMgr));
399 switch (mode & 0x7fff)
402 mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
408 mgr->idx = open ((char*)name, O_RDONLY);
413 return free(mgr), NULL;
415 cacheblk = 4096; // minimum mmap segment size for unix
418 mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
419 attr = FILE_ATTRIBUTE_NORMAL;
420 switch (mode & 0x7fff)
423 mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
429 mgr->idx = CreateFile(name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, attr, NULL);
433 if( mgr->idx == INVALID_HANDLE_VALUE )
434 return GlobalFree(mgr), NULL;
436 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
437 GetSystemInfo(sysinfo);
438 cacheblk = sysinfo->dwAllocationGranularity;
442 alloc = malloc (BT_maxpage);
445 // read minimum page size to get root info
447 if( size = lseek (mgr->idx, 0L, 2) ) {
448 if( pread(mgr->idx, alloc, BT_minpage, 0) == BT_minpage )
451 return free(mgr), free(alloc), NULL;
452 } else if( mode == BT_ro )
453 return bt_mgrclose (mgr), NULL;
455 alloc = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
456 size = GetFileSize(mgr->idx, amt);
459 if( !ReadFile(mgr->idx, (char *)alloc, BT_minpage, amt, NULL) )
460 return bt_mgrclose (mgr), NULL;
462 } else if( mode == BT_ro )
463 return bt_mgrclose (mgr), NULL;
466 mgr->page_size = 1 << bits;
467 mgr->page_bits = bits;
469 mgr->poolmax = poolmax;
472 if( cacheblk < mgr->page_size )
473 cacheblk = mgr->page_size;
475 // mask for partial memmaps
477 mgr->poolmask = (cacheblk >> bits) - 1;
479 // see if requested size of pages per memmap is greater
481 if( (1 << segsize) > mgr->poolmask )
482 mgr->poolmask = (1 << segsize) - 1;
486 while( (1 << mgr->seg_bits) <= mgr->poolmask )
489 mgr->hashsize = hashsize;
492 mgr->nodes = calloc (poolmax, (sizeof(BtPool) + (mgr->poolmask + 1) * sizeof(BtLatchSet)));
493 mgr->hash = calloc (hashsize, sizeof(ushort));
494 mgr->latch = calloc (hashsize, sizeof(BtLatch));
495 mgr->pooladvise = calloc (poolmax, (mgr->poolmask + 1) / 8);
497 mgr->nodes = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * (sizeof(BtPool) + (mgr->poolmask + 1) * sizeof(BtLatchSet)));
498 mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
499 mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtLatch));
505 // initializes an empty b-tree with root page and page of leaves
507 memset (alloc, 0, 1 << bits);
508 bt_putid(alloc->right, MIN_lvl+1);
509 alloc->bits = mgr->page_bits;
512 if( write (mgr->idx, alloc, mgr->page_size) < mgr->page_size )
513 return bt_mgrclose (mgr), NULL;
515 if( !WriteFile (mgr->idx, (char *)alloc, mgr->page_size, amt, NULL) )
516 return bt_mgrclose (mgr), NULL;
518 if( *amt < mgr->page_size )
519 return bt_mgrclose (mgr), NULL;
522 memset (alloc, 0, 1 << bits);
523 alloc->bits = mgr->page_bits;
525 for( lvl=MIN_lvl; lvl--; ) {
526 slotptr(alloc, 1)->off = mgr->page_size - 3;
527 bt_putid(slotptr(alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
528 key = keyptr(alloc, 1);
529 key->len = 2; // create stopper key
532 alloc->min = mgr->page_size - 3;
537 if( write (mgr->idx, alloc, mgr->page_size) < mgr->page_size )
538 return bt_mgrclose (mgr), NULL;
540 if( !WriteFile (mgr->idx, (char *)alloc, mgr->page_size, amt, NULL) )
541 return bt_mgrclose (mgr), NULL;
543 if( *amt < mgr->page_size )
544 return bt_mgrclose (mgr), NULL;
548 // create empty page area by writing last page of first
549 // segment area (other pages are zeroed by O/S)
551 if( mgr->poolmask ) {
552 memset(alloc, 0, mgr->page_size);
553 last = mgr->poolmask;
555 while( last < MIN_lvl + 1 )
556 last += mgr->poolmask + 1;
559 pwrite(mgr->idx, alloc, mgr->page_size, last << mgr->page_bits);
561 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
562 if( !WriteFile (mgr->idx, (char *)alloc, mgr->page_size, amt, NULL) )
563 return bt_mgrclose (mgr), NULL;
564 if( *amt < mgr->page_size )
565 return bt_mgrclose (mgr), NULL;
573 VirtualFree (alloc, 0, MEM_RELEASE);
578 // open BTree access method
579 // based on buffer manager
581 BtDb *bt_open (BtMgr *mgr)
583 BtDb *bt = malloc (sizeof(*bt));
585 memset (bt, 0, sizeof(*bt));
588 bt->mem = malloc (3 *mgr->page_size);
590 bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
592 bt->frame = (BtPage)bt->mem;
593 bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
594 bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
598 // compare two keys, returning > 0, = 0, or < 0
599 // as the comparison value
601 int keycmp (BtKey key1, unsigned char *key2, uint len2)
603 uint len1 = key1->len;
606 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
619 // wait until write lock mode is clear
620 // and add 1 to the share count
622 void bt_readlock(BtLatch *latch)
625 // see if exclusive request is pending, or granted
627 if( !(volatile int)latch->request && !(volatile int)latch->exclusive ) {
628 // add one to counter, check write bit
630 if( ~__sync_fetch_and_add((volatile int *)latch, Share) & Write )
633 if( ~_InterlockedExchangeAdd((volatile int *)latch, Share) & Write )
636 // didn't get latch, reduce counter by one
639 __sync_fetch_and_add((volatile int *)latch, -Share);
641 _InterlockedExchangeAdd ((volatile int *)latch, -Share);
654 // wait for other read and write latches to relinquish
656 void bt_writelock(BtLatch *latch)
661 // set exclusive access pending
664 __sync_fetch_and_or((int *)latch, Pending);
666 _InterlockedOr((int *)latch, Pending);
669 // see if we can get write access
672 prev = __sync_fetch_and_or((volatile int *)latch, Write);
674 prev = _InterlockedOr((volatile int *)latch, Write);
677 // did we get exclusive access?
678 // if so, clear write pending
680 if( !(prev & ~Pending) ) {
682 __sync_fetch_and_and((volatile int *)latch, ~Pending);
684 _InterlockedAnd((volatile int *)latch, ~Pending);
689 // reset our Write mode if it was clear before
691 if( !(prev & Write) ) {
693 __sync_fetch_and_and((volatile int *)latch, ~Write);
695 _InterlockedAnd((volatile int *)latch, ~Write);
709 // try to obtain write lock
711 // return 1 if obtained,
712 // 0 if already write locked
714 int bt_writetry(BtLatch *latch)
718 // see if we can get write access
721 prev = __sync_fetch_and_or((volatile int *)latch, Write);
723 prev = _InterlockedOr((volatile int *)latch, Write);
726 // did we get exclusive access?
729 if( !(prev & ~Pending) )
732 // reset our Write mode if it was clear before
734 if( !(prev & Write) ) {
736 __sync_fetch_and_and((volatile int *)latch, ~Write);
738 _InterlockedAnd((volatile int *)latch, ~Write);
746 void bt_releasewrite(BtLatch *latch)
749 __sync_fetch_and_and((int *)latch, ~Write);
751 _InterlockedAnd ((int *)latch, ~Write);
755 // decrement reader count
757 void bt_releaseread(BtLatch *latch)
760 __sync_fetch_and_add((int *)latch, -Share);
762 _InterlockedExchangeAdd((int *)latch, -Share);
768 // find segment in pool
769 // must be called with hashslot idx locked
770 // return NULL if not there
771 // otherwise return node
773 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
778 // compute start of hash chain in pool
780 if( slot = bt->mgr->hash[idx] )
781 pool = (BtPool *)(bt->mgr->nodes + slot * (sizeof(BtPool) + (bt->mgr->poolmask + 1) * sizeof(BtLatchSet)));
785 page_no &= ~bt->mgr->poolmask;
787 while( pool->basepage != page_no )
788 if( pool = pool->hashnext )
796 // add segment to hash table
798 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
803 pool->hashprev = pool->hashnext = NULL;
804 pool->basepage = page_no & ~bt->mgr->poolmask;
807 if( slot = bt->mgr->hash[idx] ) {
808 node = (BtPool *)(bt->mgr->nodes + slot * (sizeof(BtPool) + (bt->mgr->poolmask + 1) * sizeof(BtLatchSet)));
809 pool->hashnext = node;
810 node->hashprev = pool;
813 bt->mgr->hash[idx] = pool->slot;
816 // find best segment to evict from buffer pool
818 BtPool *bt_findlru (BtDb *bt, uint hashslot)
820 unsigned long long int target = ~0LL;
821 BtPool *pool = NULL, *node;
826 node = (BtPool *)(bt->mgr->nodes + hashslot * (sizeof(BtPool) + (bt->mgr->poolmask + 1) * sizeof(BtLatchSet)));
828 // scan pool entries under hash table slot
833 if( node->lru > target )
837 } while( node = node->hashnext );
842 // map new buffer pool segment to virtual memory
844 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
846 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
847 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
851 flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
852 pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED, bt->mgr->idx, off);
853 if( pool->map == MAP_FAILED )
854 return bt->err = BTERR_map;
855 // clear out madvise issued bits
856 memset (bt->mgr->pooladvise + pool->slot * (bt->mgr->poolmask + 1) / 8, 0, (bt->mgr->poolmask + 1)/8);
858 flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
859 pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
861 return bt->err = BTERR_map;
863 flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
864 pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
866 return bt->err = BTERR_map;
871 // find or place requested page in segment-pool
872 // return pool table entry, incrementing pin
874 BtPool *bt_pinpage(BtDb *bt, uid page_no)
876 BtPool *pool, *node, *next;
877 uint slot, idx, victim;
880 // lock hash table chain
882 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
883 bt_readlock (&bt->mgr->latch[idx]);
885 // look up in hash table
887 if( pool = bt_findpool(bt, page_no, idx) ) {
889 __sync_fetch_and_add(&pool->pin, 1);
891 _InterlockedIncrement (&pool->pin);
893 bt_releaseread (&bt->mgr->latch[idx]);
898 // upgrade to write lock
900 bt_releaseread (&bt->mgr->latch[idx]);
901 bt_writelock (&bt->mgr->latch[idx]);
903 // try to find page in pool with write lock
905 if( pool = bt_findpool(bt, page_no, idx) ) {
907 __sync_fetch_and_add(&pool->pin, 1);
909 _InterlockedIncrement (&pool->pin);
911 bt_releasewrite (&bt->mgr->latch[idx]);
916 // allocate a new pool node
917 // and add to hash table
920 slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
922 slot = _InterlockedIncrement (&bt->mgr->poolcnt) - 1;
925 if( ++slot < bt->mgr->poolmax ) {
926 pool = (BtPool *)(bt->mgr->nodes + slot * (sizeof(BtPool) + (bt->mgr->poolmask + 1) * sizeof(BtLatchSet)));
929 if( bt_mapsegment(bt, pool, page_no) )
932 bt_linkhash(bt, pool, page_no, idx);
934 __sync_fetch_and_add(&pool->pin, 1);
936 _InterlockedIncrement (&pool->pin);
938 bt_releasewrite (&bt->mgr->latch[idx]);
942 // pool table is full
943 // find best pool entry to evict
946 __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
948 _InterlockedDecrement (&bt->mgr->poolcnt);
953 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
955 victim = _InterlockedIncrement (&bt->mgr->evicted) - 1;
957 victim %= bt->mgr->hashsize;
959 // try to get write lock
960 // skip entry if not obtained
962 if( !bt_writetry (&bt->mgr->latch[victim]) )
965 // if cache entry is empty
966 // or no slots are unpinned
969 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
970 bt_releasewrite (&bt->mgr->latch[victim]);
974 // unlink victim pool node from hash table
976 if( node = pool->hashprev )
977 node->hashnext = pool->hashnext;
978 else if( node = pool->hashnext )
979 bt->mgr->hash[victim] = node->slot;
981 bt->mgr->hash[victim] = 0;
983 if( node = pool->hashnext )
984 node->hashprev = pool->hashprev;
986 bt_releasewrite (&bt->mgr->latch[victim]);
988 // remove old file mapping
990 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
992 FlushViewOfFile(pool->map, 0);
993 UnmapViewOfFile(pool->map);
994 CloseHandle(pool->hmap);
998 // create new pool mapping
999 // and link into hash table
1001 if( bt_mapsegment(bt, pool, page_no) )
1004 bt_linkhash(bt, pool, page_no, idx);
1006 __sync_fetch_and_add(&pool->pin, 1);
1008 _InterlockedIncrement (&pool->pin);
1010 bt_releasewrite (&bt->mgr->latch[idx]);
1015 // place write, read, or parent lock on requested page_no.
1016 // pin to buffer pool and return page pointer
1018 BTERR bt_lockpage(BtDb *bt, uid page_no, BtLock mode, BtPage *pageptr)
1025 // find/create maping in pool table
1026 // and pin our pool slot
1028 if( pool = bt_pinpage(bt, page_no) )
1029 subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1033 set = pool->pagelatch + subpage;
1034 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1037 uint idx = subpage / 8;
1038 uint bit = subpage % 8;
1040 if( !((bt->mgr->pooladvise + pool->slot * (bt->mgr->poolmask + 1)/8)[idx] >> bit) & 1 ) {
1041 madvise (page, bt->mgr->page_size, MADV_WILLNEED);
1042 (bt->mgr->pooladvise + pool->slot * (bt->mgr->poolmask + 1)/8)[idx] |= 1 << bit;
1049 bt_readlock (set->readwr);
1052 bt_writelock (set->readwr);
1055 bt_readlock (set->access);
1058 bt_writelock (set->access);
1061 bt_writelock (set->parent);
1064 return bt->err = BTERR_lock;
1073 // remove write, read, or parent lock on requested page_no.
1075 BTERR bt_unlockpage(BtDb *bt, uid page_no, BtLock mode)
1081 // since page is pinned
1082 // it should still be in the buffer pool
1083 // and is in no danger of being a victim for reuse
1085 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1086 bt_readlock (&bt->mgr->latch[idx]);
1088 if( pool = bt_findpool(bt, page_no, idx) )
1089 subpage = (uint)(page_no & bt->mgr->poolmask);
1091 return bt->err = BTERR_hash;
1093 bt_releaseread (&bt->mgr->latch[idx]);
1094 set = pool->pagelatch + subpage;
1098 bt_releaseread (set->readwr);
1101 bt_releasewrite (set->readwr);
1104 bt_releaseread (set->access);
1107 bt_releasewrite (set->access);
1110 bt_releasewrite (set->parent);
1113 return bt->err = BTERR_lock;
1117 __sync_fetch_and_add(&pool->pin, -1);
1119 _InterlockedDecrement (&pool->pin);
1124 // deallocate a deleted page
1125 // place on free chain out of allocator page
1127 BTERR bt_freepage(BtDb *bt, uid page_no)
1129 // obtain delete lock on deleted page
1131 if( bt_lockpage(bt, page_no, BtLockDelete, NULL) )
1134 // obtain write lock on deleted page
1136 if( bt_lockpage(bt, page_no, BtLockWrite, &bt->temp) )
1139 // lock allocation page
1141 if ( bt_lockpage(bt, ALLOC_page, BtLockWrite, &bt->alloc) )
1144 // store chain in second right
1145 bt_putid(bt->temp->right, bt_getid(bt->alloc[1].right));
1146 bt_putid(bt->alloc[1].right, page_no);
1150 if( bt_unlockpage(bt, ALLOC_page, BtLockWrite) )
1153 // remove write lock on deleted node
1155 if( bt_unlockpage(bt, page_no, BtLockWrite) )
1158 // remove delete lock on deleted node
1160 if( bt_unlockpage(bt, page_no, BtLockDelete) )
1166 // allocate a new page and write page into it
1168 uid bt_newpage(BtDb *bt, BtPage page)
1176 if ( bt_lockpage(bt, ALLOC_page, BtLockWrite, &bt->alloc) )
1179 // use empty chain first
1180 // else allocate empty page
1182 if( new_page = bt_getid(bt->alloc[1].right) ) {
1183 if( bt_lockpage (bt, new_page, BtLockWrite, &bt->temp) )
1185 bt_putid(bt->alloc[1].right, bt_getid(bt->temp->right));
1186 if( bt_unlockpage (bt, new_page, BtLockWrite) )
1190 new_page = bt_getid(bt->alloc->right);
1191 bt_putid(bt->alloc->right, new_page+1);
1195 if ( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1196 return bt->err = BTERR_wrt, 0;
1198 // if writing first page of pool block, zero last page in the block
1200 if ( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1202 // use zero buffer to write zeros
1203 memset(bt->zero, 0, bt->mgr->page_size);
1204 if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1205 return bt->err = BTERR_wrt, 0;
1208 // bring new page into pool and copy page.
1209 // this will extend the file into the new pages.
1211 if( bt_lockpage(bt, new_page, BtLockWrite, &pmap) )
1214 memcpy(pmap, page, bt->mgr->page_size);
1216 if( bt_unlockpage (bt, new_page, BtLockWrite) )
1221 if ( bt_unlockpage(bt, ALLOC_page, BtLockWrite) )
1227 // find slot in page for given key at a given level
1229 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1231 uint diff, higher = bt->page->cnt, low = 1, slot;
1233 // low is the lowest candidate, higher is already
1234 // tested as .ge. the given key, loop ends when they meet
1236 while( diff = higher - low ) {
1237 slot = low + ( diff >> 1 );
1238 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1247 // find and load page at given level for given key
1248 // leave page rd or wr locked as requested
1250 int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, uint lock)
1252 uid page_no = ROOT_page, prevpage = 0;
1253 uint drill = 0xff, slot;
1254 uint mode, prevmode;
1256 // start at root of btree and drill down
1259 // determine lock mode of drill level
1260 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1262 bt->page_no = page_no;
1264 // obtain access lock using lock chaining with Access mode
1266 if( page_no > ROOT_page )
1267 if( bt_lockpage(bt, page_no, BtLockAccess, NULL) )
1271 if( bt_unlockpage(bt, prevpage, prevmode) )
1274 // obtain read lock using lock chaining
1275 // and pin page contents
1277 if( bt_lockpage(bt, page_no, mode, &bt->page) )
1280 if( page_no > ROOT_page )
1281 if( bt_unlockpage(bt, page_no, BtLockAccess) )
1284 // re-read and re-lock root after determining actual level of root
1286 if( bt->page_no == ROOT_page )
1287 if( bt->page->lvl != drill) {
1288 drill = bt->page->lvl;
1290 if( lock == BtLockWrite && drill == lvl )
1291 if( bt_unlockpage(bt, page_no, mode) )
1297 // if page is being deleted,
1298 // move back to preceeding page
1300 if( bt->page->kill ) {
1301 page_no = bt_getid (bt->page->right);
1305 // find key on page at this level
1306 // and descend to requested level
1308 slot = bt_findslot (bt, key, len);
1310 // is this slot a foster child?
1312 if( slot <= bt->page->cnt - bt->page->foster )
1318 while( slotptr(bt->page, slot)->dead )
1319 if( slot++ < bt->page->cnt )
1322 return bt->err = BTERR_struct, 0;
1324 // continue down / right using overlapping locks
1325 // to protect pages being killed or split.
1328 prevpage = bt->page_no;
1329 page_no = bt_getid(slotptr(bt->page, slot)->id);
1332 // return error on end of chain
1334 bt->err = BTERR_struct;
1335 return 0; // return error
1338 // find and delete key on page by marking delete flag bit
1339 // when page becomes empty, delete it from the btree
1341 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl)
1343 unsigned char leftkey[256], rightkey[256];
1348 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1349 ptr = keyptr(bt->page, slot);
1353 // if key is found delete it, otherwise ignore request
1355 if( !keycmp (ptr, key, len) )
1356 if( slotptr(bt->page, slot)->dead == 0 ) {
1357 slotptr(bt->page,slot)->dead = 1;
1358 if( slot < bt->page->cnt )
1359 bt->page->dirty = 1;
1363 // return if page is not empty, or it has no right sibling
1365 right = bt_getid(bt->page->right);
1366 page_no = bt->page_no;
1368 if( !right || bt->page->act )
1369 return bt_unlockpage(bt, page_no, BtLockWrite);
1371 // obtain Parent lock over write lock
1373 if( bt_lockpage(bt, page_no, BtLockParent, NULL) )
1376 // cache copy of key to delete
1378 ptr = keyptr(bt->page, bt->page->cnt);
1379 memcpy(leftkey, ptr, ptr->len + 1);
1381 // lock and map right page
1383 if ( bt_lockpage(bt, right, BtLockWrite, &bt->temp) )
1386 // pull contents of next page into current empty page
1387 memcpy (bt->page, bt->temp, bt->mgr->page_size);
1389 // cache copy of key to update
1390 ptr = keyptr(bt->temp, bt->temp->cnt);
1391 memcpy(rightkey, ptr, ptr->len + 1);
1393 // Mark right page as deleted and point it to left page
1394 // until we can post updates at higher level.
1396 bt_putid(bt->temp->right, page_no);
1400 if( bt_unlockpage(bt, right, BtLockWrite) )
1402 if( bt_unlockpage(bt, page_no, BtLockWrite) )
1405 // delete old lower key to consolidated node
1407 if( bt_deletekey (bt, leftkey + 1, *leftkey, lvl + 1) )
1410 // redirect higher key directly to consolidated node
1412 if( slot = bt_loadpage (bt, rightkey+1, *rightkey, lvl+1, BtLockWrite) )
1413 ptr = keyptr(bt->page, slot);
1417 // since key already exists, update id
1419 if( keycmp (ptr, rightkey+1, *rightkey) )
1420 return bt->err = BTERR_struct;
1422 slotptr(bt->page, slot)->dead = 0;
1423 bt_putid(slotptr(bt->page,slot)->id, page_no);
1424 bt_unlockpage(bt, bt->page_no, BtLockWrite);
1426 // obtain write lock and
1427 // add right block to free chain
1429 if( bt_freepage (bt, right) )
1432 // remove ParentModify lock
1434 if( bt_unlockpage(bt, page_no, BtLockParent) )
1440 // find key in leaf level and return row-id
1442 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1448 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1449 ptr = keyptr(bt->page, slot);
1453 // if key exists, return row-id
1454 // otherwise return 0
1456 if( ptr->len == len && !memcmp (ptr->key, key, len) )
1457 id = bt_getid(slotptr(bt->page,slot)->id);
1461 if ( bt_unlockpage(bt, bt->page_no, BtLockRead) )
1467 // check page for space available,
1468 // clean if necessary and return
1469 // 0 - page needs splitting
1472 uint bt_cleanpage(BtDb *bt, uint amt)
1474 uint nxt = bt->mgr->page_size;
1475 BtPage page = bt->page;
1476 uint cnt = 0, idx = 0;
1477 uint max = page->cnt;
1480 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1483 // skip cleanup if nothing to reclaim
1488 memcpy (bt->frame, page, bt->mgr->page_size);
1490 // skip page info and set rest of page to zero
1492 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1496 // try cleaning up page first
1498 while( cnt++ < max ) {
1499 // always leave fence key and foster children in list
1500 if( cnt < max - page->foster && slotptr(bt->frame,cnt)->dead )
1504 key = keyptr(bt->frame, cnt);
1505 nxt -= key->len + 1;
1506 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1509 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1510 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1512 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1513 slotptr(page, idx)->off = nxt;
1519 // see if page has enough space now, or does it need splitting?
1521 if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1528 // return with page unlocked
1530 BTERR bt_addkeytopage (BtDb *bt, uint slot, unsigned char *key, uint len, uid id, uint tod)
1532 BtPage page = bt->page;
1535 // calculate next available slot and copy key into page
1537 page->min -= len + 1;
1538 ((unsigned char *)page)[page->min] = len;
1539 memcpy ((unsigned char *)page + page->min +1, key, len );
1541 for( idx = slot; idx < page->cnt; idx++ )
1542 if( slotptr(page, idx)->dead )
1545 // now insert key into array before slot
1546 // preserving the fence slot
1548 if( idx == page->cnt )
1554 *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
1556 bt_putid(slotptr(page,slot)->id, id);
1557 slotptr(page, slot)->off = page->min;
1558 slotptr(page, slot)->tod = tod;
1559 slotptr(page, slot)->dead = 0;
1561 return bt_unlockpage(bt, bt->page_no, BtLockWrite);
1564 // split the root and raise the height of the btree
1566 BTERR bt_splitroot(BtDb *bt, uid right)
1568 uint nxt = bt->mgr->page_size;
1569 unsigned char fencekey[256];
1570 BtPage root = bt->page;
1574 // Obtain an empty page to use, and copy the left page
1575 // contents into it from the root. Strip foster child key.
1576 // (it's the stopper key)
1582 // Save left fence key.
1584 key = keyptr(root, root->cnt);
1585 memcpy (fencekey, key, key->len + 1);
1587 // copy the lower keys into a new left page
1589 if( !(new_page = bt_newpage(bt, root)) )
1592 // preserve the page info at the bottom
1593 // and set rest of the root to zero
1595 memset (root+1, 0, bt->mgr->page_size - sizeof(*root));
1597 // insert left fence key on empty newroot page
1599 nxt -= *fencekey + 1;
1600 memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
1601 bt_putid(slotptr(root, 1)->id, new_page);
1602 slotptr(root, 1)->off = nxt;
1604 // insert stopper key on newroot page
1605 // and increase the root height
1611 memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
1612 bt_putid(slotptr(root, 2)->id, right);
1613 slotptr(root, 2)->off = nxt;
1615 bt_putid(root->right, 0);
1616 root->min = nxt; // reset lowest used offset and key count
1621 // release root (bt->page)
1623 return bt_unlockpage(bt, bt->page_no, BtLockWrite);
1626 // split already locked full node
1629 BTERR bt_splitpage (BtDb *bt)
1631 uint slot, cnt, idx, max, nxt = bt->mgr->page_size;
1632 unsigned char fencekey[256];
1633 uid page_no = bt->page_no;
1634 BtPage page = bt->page;
1635 uint tod = time(NULL);
1636 uint lvl = page->lvl;
1637 uid new_page, right;
1640 // initialize frame buffer
1642 memset (bt->frame, 0, bt->mgr->page_size);
1643 max = page->cnt - page->foster;
1644 tod = (uint)time(NULL);
1648 // split higher half of keys to bt->frame
1649 // leaving foster children in the left node.
1651 while( cnt++ < max ) {
1652 key = keyptr(page, cnt);
1653 nxt -= key->len + 1;
1654 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
1655 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
1656 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
1657 slotptr(bt->frame, idx)->off = nxt;
1661 // transfer right link node
1663 if( page_no > ROOT_page ) {
1664 right = bt_getid (page->right);
1665 bt_putid(bt->frame->right, right);
1668 bt->frame->bits = bt->mgr->page_bits;
1669 bt->frame->min = nxt;
1670 bt->frame->cnt = idx;
1671 bt->frame->lvl = lvl;
1673 // get new free page and write frame to it.
1675 if( !(new_page = bt_newpage(bt, bt->frame)) )
1678 // remember fence key for new page to add
1681 key = keyptr(bt->frame, idx);
1682 memcpy (fencekey, key, key->len + 1);
1684 // update lower keys and foster children to continue in old page
1686 memcpy (bt->frame, page, bt->mgr->page_size);
1687 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1688 nxt = bt->mgr->page_size;
1693 // assemble page of smaller keys
1694 // to remain in the old page
1696 while( cnt++ < max / 2 ) {
1697 key = keyptr(bt->frame, cnt);
1698 nxt -= key->len + 1;
1699 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1700 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1701 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1702 slotptr(page, idx)->off = nxt;
1706 // insert new foster child at beginning of the current foster children
1708 nxt -= *fencekey + 1;
1709 memcpy ((unsigned char *)page + nxt, fencekey, *fencekey + 1);
1710 bt_putid (slotptr(page,++idx)->id, new_page);
1711 slotptr(page, idx)->tod = tod;
1712 slotptr(page, idx)->off = nxt;
1716 // continue with old foster child keys if any
1718 cnt = bt->frame->cnt - bt->frame->foster;
1720 while( cnt++ < bt->frame->cnt ) {
1721 key = keyptr(bt->frame, cnt);
1722 nxt -= key->len + 1;
1723 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1724 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1725 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1726 slotptr(page, idx)->off = nxt;
1733 // link new right page
1735 bt_putid (page->right, new_page);
1737 // if current page is the root page, split it
1739 if( page_no == ROOT_page )
1740 return bt_splitroot (bt, new_page);
1742 // release wr lock on page
1744 if( bt_unlockpage (bt, page_no, BtLockWrite) )
1747 // obtain ParentModification lock for current page
1748 // to fix fence key and highest foster child on page
1750 if( bt_lockpage (bt, page_no, BtLockParent, NULL) )
1753 // get our highest foster child key to find in parent node
1755 if( bt_lockpage (bt, page_no, BtLockRead, &page) )
1758 key = keyptr(page, page->cnt);
1759 memcpy (fencekey, key, key->len+1);
1761 if( bt_unlockpage (bt, page_no, BtLockRead) )
1767 slot = bt_loadpage (bt, fencekey + 1, *fencekey, lvl + 1, BtLockWrite);
1772 // check if parent page has enough space for any possible key
1774 if( bt_cleanpage (bt, 256) )
1777 if( bt_splitpage (bt) )
1781 // see if we are still a foster child from another node
1783 if( bt_getid (slotptr(bt->page, slot)->id) != page_no ) {
1784 bt_unlockpage (bt, bt->page_no, BtLockWrite);
1793 // wait until readers from parent get their locks
1795 if( bt_lockpage (bt, page_no, BtLockDelete, NULL) )
1798 if( bt_lockpage (bt, page_no, BtLockWrite, &page) )
1801 // switch parent fence key to foster child
1803 if( slotptr(page, page->cnt)->dead )
1804 slotptr(bt->page, slot)->dead = 1;
1806 bt_putid (slotptr(bt->page, slot)->id, bt_getid(slotptr(page, page->cnt)->id));
1808 // remove highest foster child from our page
1809 // add our new fence key to parent
1815 key = keyptr(page, page->cnt);
1817 if( bt_addkeytopage (bt, slot, key->key, key->len, page_no, tod) )
1820 if( bt_unlockpage (bt, page_no, BtLockDelete) )
1823 if( bt_unlockpage (bt, page_no, BtLockWrite) )
1826 return bt_unlockpage (bt, page_no, BtLockParent);
1829 // Insert new key into the btree at leaf level.
1831 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod)
1838 if( slot = bt_loadpage (bt, key, len, 0, BtLockWrite) )
1839 ptr = keyptr(bt->page, slot);
1843 bt->err = BTERR_ovflw;
1847 // if key already exists, update id and return
1851 if( !keycmp (ptr, key, len) ) {
1852 slotptr(page, slot)->dead = 0;
1853 slotptr(page, slot)->tod = tod;
1854 bt_putid(slotptr(page,slot)->id, id);
1855 return bt_unlockpage(bt, bt->page_no, BtLockWrite);
1858 // check if page has enough space
1860 if( bt_cleanpage (bt, len) )
1863 if( bt_splitpage (bt) )
1867 return bt_addkeytopage (bt, slot, key, len, id, tod);
1870 // cache page of keys into cursor and return starting slot for given key
1872 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
1876 // cache page for retrieval
1877 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1878 memcpy (bt->cursor, bt->page, bt->mgr->page_size);
1879 bt->cursor_page = bt->page_no;
1880 if ( bt_unlockpage(bt, bt->page_no, BtLockRead) )
1886 // return next slot for cursor page
1887 // or slide cursor right into next page
1889 uint bt_nextkey (BtDb *bt, uint slot)
1895 right = bt_getid(bt->cursor->right);
1896 while( slot++ < bt->cursor->cnt - bt->cursor->foster )
1897 if( slotptr(bt->cursor,slot)->dead )
1899 else if( right || (slot < bt->cursor->cnt - bt->cursor->foster) )
1907 bt->cursor_page = right;
1909 if( bt_lockpage(bt, right, BtLockRead, &page) )
1912 memcpy (bt->cursor, page, bt->mgr->page_size);
1914 if ( bt_unlockpage(bt, right, BtLockRead) )
1923 BtKey bt_key(BtDb *bt, uint slot)
1925 return keyptr(bt->cursor, slot);
1928 uid bt_uid(BtDb *bt, uint slot)
1930 return bt_getid(slotptr(bt->cursor,slot)->id);
1933 uint bt_tod(BtDb *bt, uint slot)
1935 return slotptr(bt->cursor,slot)->tod;
1948 // standalone program to index file of keys
1949 // then list them onto std-out
1952 void *index_file (void *arg)
1954 uint __stdcall index_file (void *arg)
1957 int line = 0, found = 0, cnt = 0;
1958 uid next, page_no = LEAF_page; // start on first page of leaves
1959 unsigned char key[256];
1960 ThreadArg *args = arg;
1961 int ch, len = 0, slot;
1968 bt = bt_open (args->mgr);
1971 switch(args->type | 0x20)
1974 fprintf(stderr, "started indexing for %s\n", args->infile);
1975 if( in = fopen (args->infile, "rb") )
1976 while( ch = getc(in), ch != EOF )
1981 if( args->num == 1 )
1982 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
1984 else if( args->num )
1985 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
1987 if( bt_insertkey (bt, key, len, line, *tod) )
1988 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
1991 else if( len < 255 )
1993 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
1997 fprintf(stderr, "started deleting keys for %s\n", args->infile);
1998 if( in = fopen (args->infile, "rb") )
1999 while( ch = getc(in), ch != EOF )
2003 if( args->num == 1 )
2004 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2006 else if( args->num )
2007 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2009 if( bt_deletekey (bt, key, len, 0) )
2010 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2013 else if( len < 255 )
2015 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2019 fprintf(stderr, "started finding keys for %s\n", args->infile);
2020 if( in = fopen (args->infile, "rb") )
2021 while( ch = getc(in), ch != EOF )
2025 if( args->num == 1 )
2026 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2028 else if( args->num )
2029 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2031 if( bt_findkey (bt, key, len) )
2034 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2037 else if( len < 255 )
2039 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2045 fprintf(stderr, "started reading\n");
2047 if( slot = bt_startkey (bt, key, len) )
2050 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
2052 while( slot = bt_nextkey (bt, slot) ) {
2053 ptr = bt_key(bt, slot);
2054 fwrite (ptr->key, ptr->len, 1, stdout);
2055 fputc ('\n', stdout);
2061 fprintf(stderr, "started reading\n");
2064 bt_lockpage (bt, page_no, BtLockRead, &page);
2066 next = bt_getid (page->right);
2067 bt_unlockpage (bt, page_no, BtLockRead);
2068 } while( page_no = next );
2070 cnt--; // remove stopper key
2071 fprintf(stderr, " Total keys read %d\n", cnt);
2083 typedef struct timeval timer;
2085 int main (int argc, char **argv)
2087 int idx, cnt, len, slot, err;
2088 int segsize, bits = 16;
2093 time_t start[1], stop[1];
2106 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]);
2107 fprintf (stderr, " where page_bits is the page size in bits\n");
2108 fprintf (stderr, " mapped_segments is the number of mmap segments in buffer pool\n");
2109 fprintf (stderr, " seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2110 fprintf (stderr, " line_numbers = 1 to append line numbers to keys\n");
2111 fprintf (stderr, " src_file1 thru src_filen are files of keys separated by newline\n");
2116 gettimeofday(&start, NULL);
2122 bits = atoi(argv[3]);
2125 poolsize = atoi(argv[4]);
2128 fprintf (stderr, "Warning: no mapped_pool\n");
2130 if( poolsize > 65535 )
2131 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2134 segsize = atoi(argv[5]);
2136 segsize = 4; // 16 pages per mmap segment
2139 num = atoi(argv[6]);
2143 threads = malloc (cnt * sizeof(pthread_t));
2145 threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2147 args = malloc (cnt * sizeof(ThreadArg));
2149 mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2152 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2158 for( idx = 0; idx < cnt; idx++ ) {
2159 args[idx].infile = argv[idx + 7];
2160 args[idx].type = argv[2][0];
2161 args[idx].mgr = mgr;
2162 args[idx].num = num;
2163 args[idx].idx = idx;
2165 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2166 fprintf(stderr, "Error creating thread %d\n", err);
2168 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2172 // wait for termination
2175 for( idx = 0; idx < cnt; idx++ )
2176 pthread_join (threads[idx], NULL);
2177 gettimeofday(&stop, NULL);
2178 real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2180 WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2182 for( idx = 0; idx < cnt; idx++ )
2183 CloseHandle(threads[idx]);
2186 real_time = 1000 * (*stop - *start);
2188 fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);