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 ushort foster; // count of foster children
146 uint cnt; // count of keys in page
147 uint act; // count of active keys
148 uint min; // next key offset
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 volatile 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 volatile ushort poolcnt; // highest page pool node in use
185 volatile ushort evicted; // last evicted hash table slot
186 ushort poolmax; // highest page pool node allocated
187 ushort poolmask; // total size of pages in mmap segment - 1
188 ushort hashsize; // size of Hash Table for pool entries
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 while( __sync_fetch_and_or((ushort *)latch, Mutex) & Mutex )
325 while( _InterlockedOr16((ushort *)latch, Mutex) & Mutex )
328 // see if exclusive request is granted or pending
330 if( prev = !(latch->exclusive | latch->pending) )
332 __sync_fetch_and_add((ushort *)latch, Share);
334 _InterlockedExchangeAdd16 ((ushort *)latch, Share);
338 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
340 _InterlockedAnd16((ushort *)latch, ~Mutex);
346 } while( sched_yield(), 1 );
348 } while( SwitchToThread(), 1 );
352 // wait for other read and write latches to relinquish
354 void bt_spinwritelock(BtSpinLatch *latch)
360 while( __sync_fetch_and_or((ushort *)latch, Mutex | Pending) & Mutex )
363 while( _InterlockedOr16((ushort *)latch, Mutex | Pending) & Mutex )
366 if( prev = !(latch->share | latch->exclusive) )
368 __sync_fetch_and_or((ushort *)latch, Write);
370 _InterlockedOr16((ushort *)latch, Write);
374 __sync_fetch_and_and ((ushort *)latch, ~(Mutex | Pending));
376 _InterlockedAnd16((ushort *)latch, ~(Mutex | Pending));
389 // try to obtain write lock
391 // return 1 if obtained,
394 int bt_spinwritetry(BtSpinLatch *latch)
399 if( prev = __sync_fetch_and_or((ushort *)latch, Mutex), prev & Mutex )
402 if( prev = _InterlockedOr16((ushort *)latch, Mutex), prev & Mutex )
405 // take write access if all bits are clear
409 __sync_fetch_and_or ((ushort *)latch, Write);
411 _InterlockedOr16((ushort *)latch, Write);
418 void bt_spinreleasewrite(BtSpinLatch *latch)
421 __sync_fetch_and_and ((ushort *)latch, ~Write);
423 _InterlockedAnd16((ushort *)latch, ~Write);
427 // decrement reader count
429 void bt_spinreleaseread(BtSpinLatch *latch)
432 __sync_fetch_and_add((ushort *)latch, -Share);
434 _InterlockedExchangeAdd16 ((ushort *)latch, -Share);
438 void bt_mgrclose (BtMgr *mgr)
443 // release mapped pages
444 // note that slot zero is never used
446 for( slot = 1; slot < mgr->poolmax; slot++ ) {
447 pool = mgr->pool + slot;
450 munmap (pool->map, (mgr->poolmask+1) << mgr->page_bits);
453 FlushViewOfFile(pool->map, 0);
454 UnmapViewOfFile(pool->map);
455 CloseHandle(pool->hmap);
464 free (mgr->pooladvise);
467 FlushFileBuffers(mgr->idx);
468 CloseHandle(mgr->idx);
469 GlobalFree (mgr->pool);
470 GlobalFree (mgr->hash);
475 // close and release memory
477 void bt_close (BtDb *bt)
484 VirtualFree (bt->mem, 0, MEM_RELEASE);
489 // open/create new btree buffer manager
491 // call with file_name, BT_openmode, bits in page size (e.g. 16),
492 // size of mapped page pool (e.g. 8192)
494 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
496 uint lvl, attr, cacheblk, last, slot, idx;
505 SYSTEM_INFO sysinfo[1];
508 // determine sanity of page size and buffer pool
510 if( bits > BT_maxbits )
512 else if( bits < BT_minbits )
516 return NULL; // must have buffer pool
519 mgr = calloc (1, sizeof(BtMgr));
521 switch (mode & 0x7fff)
524 mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
530 mgr->idx = open ((char*)name, O_RDONLY);
535 return free(mgr), NULL;
537 cacheblk = 4096; // minimum mmap segment size for unix
540 mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
541 attr = FILE_ATTRIBUTE_NORMAL;
542 switch (mode & 0x7fff)
545 mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
551 mgr->idx = CreateFile(name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, attr, NULL);
555 if( mgr->idx == INVALID_HANDLE_VALUE )
556 return GlobalFree(mgr), NULL;
558 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
559 GetSystemInfo(sysinfo);
560 cacheblk = sysinfo->dwAllocationGranularity;
564 alloc = malloc (BT_maxpage);
567 // read minimum page size to get root info
569 if( size = lseek (mgr->idx, 0L, 2) ) {
570 if( pread(mgr->idx, alloc, BT_minpage, 0) == BT_minpage )
573 return free(mgr), free(alloc), NULL;
574 } else if( mode == BT_ro )
575 return bt_mgrclose (mgr), NULL;
577 alloc = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
578 size = GetFileSize(mgr->idx, amt);
581 if( !ReadFile(mgr->idx, (char *)alloc, BT_minpage, amt, NULL) )
582 return bt_mgrclose (mgr), NULL;
584 } else if( mode == BT_ro )
585 return bt_mgrclose (mgr), NULL;
588 mgr->page_size = 1 << bits;
589 mgr->page_bits = bits;
591 mgr->poolmax = poolmax;
594 if( cacheblk < mgr->page_size )
595 cacheblk = mgr->page_size;
597 // mask for partial memmaps
599 mgr->poolmask = (cacheblk >> bits) - 1;
601 // see if requested size of pages per memmap is greater
603 if( (1 << segsize) > mgr->poolmask )
604 mgr->poolmask = (1 << segsize) - 1;
608 while( (1 << mgr->seg_bits) <= mgr->poolmask )
611 mgr->hashsize = hashsize;
614 mgr->pool = calloc (poolmax, sizeof(BtPool));
615 mgr->hash = calloc (hashsize, sizeof(ushort));
616 mgr->latch = calloc (hashsize, sizeof(BtSpinLatch));
617 mgr->pooladvise = calloc (poolmax, (mgr->poolmask + 8) / 8);
619 mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * (sizeof(BtPool)));
620 mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
621 mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtSpinLatch));
626 // initializes an empty b-tree with root page and page of leaves
628 memset (alloc, 0, 1 << bits);
629 bt_putid(alloc->right, MIN_lvl+1);
630 alloc->bits = mgr->page_bits;
633 if( write (mgr->idx, alloc, mgr->page_size) < mgr->page_size )
634 return bt_mgrclose (mgr), NULL;
636 if( !WriteFile (mgr->idx, (char *)alloc, mgr->page_size, amt, NULL) )
637 return bt_mgrclose (mgr), NULL;
639 if( *amt < mgr->page_size )
640 return bt_mgrclose (mgr), NULL;
643 memset (alloc, 0, 1 << bits);
644 alloc->bits = mgr->page_bits;
646 for( lvl=MIN_lvl; lvl--; ) {
647 slotptr(alloc, 1)->off = mgr->page_size - 3;
648 bt_putid(slotptr(alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
649 key = keyptr(alloc, 1);
650 key->len = 2; // create stopper key
653 alloc->min = mgr->page_size - 3;
658 if( write (mgr->idx, alloc, mgr->page_size) < mgr->page_size )
659 return bt_mgrclose (mgr), NULL;
661 if( !WriteFile (mgr->idx, (char *)alloc, mgr->page_size, amt, NULL) )
662 return bt_mgrclose (mgr), NULL;
664 if( *amt < mgr->page_size )
665 return bt_mgrclose (mgr), NULL;
669 // create empty page area by writing last page of first
670 // segment area (other pages are zeroed by O/S)
672 if( mgr->poolmask ) {
673 memset(alloc, 0, mgr->page_size);
674 last = mgr->poolmask;
676 while( last < MIN_lvl + 1 )
677 last += mgr->poolmask + 1;
680 pwrite(mgr->idx, alloc, mgr->page_size, last << mgr->page_bits);
682 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
683 if( !WriteFile (mgr->idx, (char *)alloc, mgr->page_size, amt, NULL) )
684 return bt_mgrclose (mgr), NULL;
685 if( *amt < mgr->page_size )
686 return bt_mgrclose (mgr), NULL;
694 VirtualFree (alloc, 0, MEM_RELEASE);
699 // open BTree access method
700 // based on buffer manager
702 BtDb *bt_open (BtMgr *mgr)
704 BtDb *bt = malloc (sizeof(*bt));
706 memset (bt, 0, sizeof(*bt));
709 bt->mem = malloc (3 *mgr->page_size);
711 bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
713 bt->frame = (BtPage)bt->mem;
714 bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
715 bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
719 // compare two keys, returning > 0, = 0, or < 0
720 // as the comparison value
722 int keycmp (BtKey key1, unsigned char *key2, uint len2)
724 uint len1 = key1->len;
727 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
740 // find segment in pool
741 // must be called with hashslot idx locked
742 // return NULL if not there
743 // otherwise return node
745 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
750 // compute start of hash chain in pool
752 if( slot = bt->mgr->hash[idx] )
753 pool = bt->mgr->pool + slot;
757 page_no &= ~bt->mgr->poolmask;
759 while( pool->basepage != page_no )
760 if( pool = pool->hashnext )
768 // add segment to hash table
770 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
775 pool->hashprev = pool->hashnext = NULL;
776 pool->basepage = page_no & ~bt->mgr->poolmask;
779 if( slot = bt->mgr->hash[idx] ) {
780 node = bt->mgr->pool + slot;
781 pool->hashnext = node;
782 node->hashprev = pool;
785 bt->mgr->hash[idx] = pool->slot;
788 // find best segment to evict from buffer pool
790 BtPool *bt_findlru (BtDb *bt, uint hashslot)
792 unsigned long long int target = ~0LL;
793 BtPool *pool = NULL, *node;
798 node = bt->mgr->pool + hashslot;
800 // scan pool entries under hash table slot
805 if( node->lru > target )
809 } while( node = node->hashnext );
814 // map new buffer pool segment to virtual memory
816 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
818 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
819 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
823 flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
824 pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED, bt->mgr->idx, off);
825 if( pool->map == MAP_FAILED )
826 return bt->err = BTERR_map;
827 // clear out madvise issued bits
828 memset (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8) / 8), 0, (bt->mgr->poolmask + 8)/8);
830 flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
831 pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
833 return bt->err = BTERR_map;
835 flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
836 pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
838 return bt->err = BTERR_map;
843 // find or place requested page in segment-pool
844 // return pool table entry, incrementing pin
846 BtPool *bt_pinpage(BtDb *bt, uid page_no)
848 BtPool *pool, *node, *next;
849 uint slot, idx, victim;
851 // lock hash table chain
853 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
854 bt_spinreadlock (&bt->mgr->latch[idx]);
856 // look up in hash table
858 if( pool = bt_findpool(bt, page_no, idx) ) {
860 __sync_fetch_and_add(&pool->pin, 1);
862 _InterlockedIncrement16 (&pool->pin);
864 bt_spinreleaseread (&bt->mgr->latch[idx]);
869 // upgrade to write lock
871 bt_spinreleaseread (&bt->mgr->latch[idx]);
872 bt_spinwritelock (&bt->mgr->latch[idx]);
874 // try to find page in pool with write lock
876 if( pool = bt_findpool(bt, page_no, idx) ) {
878 __sync_fetch_and_add(&pool->pin, 1);
880 _InterlockedIncrement16 (&pool->pin);
882 bt_spinreleasewrite (&bt->mgr->latch[idx]);
887 // allocate a new pool node
888 // and add to hash table
891 slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
893 slot = _InterlockedIncrement16 (&bt->mgr->poolcnt) - 1;
896 if( ++slot < bt->mgr->poolmax ) {
897 pool = bt->mgr->pool + slot;
900 if( bt_mapsegment(bt, pool, page_no) )
903 bt_linkhash(bt, pool, page_no, idx);
905 __sync_fetch_and_add(&pool->pin, 1);
907 _InterlockedIncrement16 (&pool->pin);
909 bt_spinreleasewrite (&bt->mgr->latch[idx]);
913 // pool table is full
914 // find best pool entry to evict
917 __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
919 _InterlockedDecrement16 (&bt->mgr->poolcnt);
924 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
926 victim = _InterlockedIncrement16 (&bt->mgr->evicted) - 1;
928 victim %= bt->mgr->hashsize;
930 // try to get write lock
931 // skip entry if not obtained
933 if( !bt_spinwritetry (&bt->mgr->latch[victim]) )
936 // if cache entry is empty
937 // or no slots are unpinned
940 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
941 bt_spinreleasewrite (&bt->mgr->latch[victim]);
945 // unlink victim pool node from hash table
947 if( node = pool->hashprev )
948 node->hashnext = pool->hashnext;
949 else if( node = pool->hashnext )
950 bt->mgr->hash[victim] = node->slot;
952 bt->mgr->hash[victim] = 0;
954 if( node = pool->hashnext )
955 node->hashprev = pool->hashprev;
957 bt_spinreleasewrite (&bt->mgr->latch[victim]);
959 // remove old file mapping
961 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
963 FlushViewOfFile(pool->map, 0);
964 UnmapViewOfFile(pool->map);
965 CloseHandle(pool->hmap);
969 // create new pool mapping
970 // and link into hash table
972 if( bt_mapsegment(bt, pool, page_no) )
975 bt_linkhash(bt, pool, page_no, idx);
977 __sync_fetch_and_add(&pool->pin, 1);
979 _InterlockedIncrement16 (&pool->pin);
981 bt_spinreleasewrite (&bt->mgr->latch[idx]);
986 // place write, read, or parent lock on requested page_no.
987 // pin to buffer pool and return page pointer
989 BTERR bt_lockpage(BtDb *bt, uid page_no, BtLock mode, BtPage *pageptr)
995 // find/create maping in pool table
996 // and pin our pool slot
998 if( pool = bt_pinpage(bt, page_no) )
999 subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1003 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1007 uint idx = subpage / 8;
1008 uint bit = subpage % 8;
1010 if( ~((bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] >> bit) & 1 ) {
1011 madvise (page, bt->mgr->page_size, MADV_WILLNEED);
1012 (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] |= 1 << bit;
1019 bt_spinreadlock (page->readwr);
1022 bt_spinwritelock (page->readwr);
1025 bt_spinreadlock (page->access);
1028 bt_spinwritelock (page->access);
1031 bt_spinwritelock (page->parent);
1034 return bt->err = BTERR_lock;
1043 // remove write, read, or parent lock on requested page_no.
1045 BTERR bt_unlockpage(BtDb *bt, uid page_no, BtLock mode)
1052 // since page is pinned
1053 // it should still be in the buffer pool
1054 // and is in no danger of being a victim for reuse
1056 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1057 bt_spinreadlock (&bt->mgr->latch[idx]);
1059 if( !(pool = bt_findpool(bt, page_no, idx)) )
1060 return bt->err = BTERR_hash;
1062 bt_spinreleaseread (&bt->mgr->latch[idx]);
1064 subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1065 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1069 bt_spinreleaseread (page->readwr);
1072 bt_spinreleasewrite (page->readwr);
1075 bt_spinreleaseread (page->access);
1078 bt_spinreleasewrite (page->access);
1081 bt_spinreleasewrite (page->parent);
1084 return bt->err = BTERR_lock;
1088 __sync_fetch_and_add(&pool->pin, -1);
1090 _InterlockedDecrement16 (&pool->pin);
1095 // deallocate a deleted page
1096 // place on free chain out of allocator page
1097 // fence key must already be removed from parent
1099 BTERR bt_freepage(BtDb *bt, uid page_no)
1101 // obtain delete lock on deleted page
1103 if( bt_lockpage(bt, page_no, BtLockDelete, NULL) )
1106 // obtain write lock on deleted page
1108 if( bt_lockpage(bt, page_no, BtLockWrite, &bt->temp) )
1111 // lock allocation page
1113 if ( bt_lockpage(bt, ALLOC_page, BtLockWrite, &bt->alloc) )
1116 // store free chain in allocation page second right
1117 bt_putid(bt->temp->right, bt_getid(bt->alloc[1].right));
1118 bt_putid(bt->alloc[1].right, page_no);
1120 // unlock allocation page
1122 if( bt_unlockpage(bt, ALLOC_page, BtLockWrite) )
1125 // remove write lock on deleted node
1127 if( bt_unlockpage(bt, page_no, BtLockWrite) )
1130 // remove delete lock on deleted node
1132 if( bt_unlockpage(bt, page_no, BtLockDelete) )
1138 // allocate a new page and write page into it
1140 uid bt_newpage(BtDb *bt, BtPage page)
1149 if( bt_lockpage(bt, ALLOC_page, BtLockWrite, &bt->alloc) )
1152 // use empty chain first
1153 // else allocate empty page
1155 if( new_page = bt_getid(bt->alloc[1].right) ) {
1156 if( bt_lockpage (bt, new_page, BtLockWrite, &bt->temp) )
1158 bt_putid(bt->alloc[1].right, bt_getid(bt->temp->right));
1159 if( bt_unlockpage (bt, new_page, BtLockWrite) )
1163 new_page = bt_getid(bt->alloc->right);
1164 bt_putid(bt->alloc->right, new_page+1);
1169 memset(bt->zero, 0, 3 * sizeof(BtSpinLatch)); // clear locks
1170 memcpy((char *)bt->zero + 3 * sizeof(BtSpinLatch), (char *)page + 3 * sizeof(BtSpinLatch), bt->mgr->page_size - 3 * sizeof(BtSpinLatch));
1171 if ( pwrite(bt->mgr->idx, bt->zero, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1172 return bt->err = BTERR_wrt, 0;
1174 // if writing first page of pool block, zero last page in the block
1176 if ( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1178 // use zero buffer to write zeros
1179 memset(bt->zero, 0, bt->mgr->page_size);
1180 if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1181 return bt->err = BTERR_wrt, 0;
1184 // bring new page into pool and copy page.
1185 // this will extend the file into the new pages.
1187 if( bt_lockpage(bt, new_page, BtLockWrite, &pmap) )
1190 // copy source page, but leave latch area intact
1192 memcpy((char *)pmap + 3 * sizeof(BtSpinLatch), (char *)page + 3 * sizeof(BtSpinLatch), bt->mgr->page_size - 3 * sizeof(BtSpinLatch));
1194 if( bt_unlockpage (bt, new_page, BtLockWrite) )
1197 // unlock allocation latch and return new page no
1199 if ( bt_unlockpage(bt, ALLOC_page, BtLockWrite) )
1205 // find slot in page for given key at a given level
1207 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1209 uint diff, higher = bt->page->cnt, low = 1, slot;
1211 // low is the lowest candidate, higher is already
1212 // tested as .ge. the given key, loop ends when they meet
1214 while( diff = higher - low ) {
1215 slot = low + ( diff >> 1 );
1216 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1225 // find and load page at given level for given key
1226 // leave page rd or wr locked as requested
1228 int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, uint lock)
1230 uid page_no = ROOT_page, prevpage = 0;
1231 uint drill = 0xff, slot;
1232 uint mode, prevmode;
1234 // start at root of btree and drill down
1237 // determine lock mode of drill level
1238 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1240 bt->page_no = page_no;
1242 // obtain access lock using lock chaining with Access mode
1244 if( page_no > ROOT_page )
1245 if( bt_lockpage(bt, page_no, BtLockAccess, NULL) )
1248 // now unlock our (possibly foster) parent
1251 if( bt_unlockpage(bt, prevpage, prevmode) )
1256 // obtain read lock using lock chaining
1257 // and pin page contents
1259 if( bt_lockpage(bt, page_no, mode, &bt->page) )
1262 if( page_no > ROOT_page )
1263 if( bt_unlockpage(bt, page_no, BtLockAccess) )
1266 // re-read and re-lock root after determining actual level of root
1268 if( bt->page_no == ROOT_page )
1269 if( bt->page->lvl != drill) {
1270 drill = bt->page->lvl;
1272 if( lock == BtLockWrite && drill == lvl )
1273 if( bt_unlockpage(bt, page_no, mode) )
1279 prevpage = bt->page_no;
1282 // if page is being deleted,
1283 // move back to preceeding page
1285 if( bt->page->kill ) {
1286 page_no = bt_getid (bt->page->right);
1290 // find key on page at this level
1291 // and descend to requested level
1293 slot = bt_findslot (bt, key, len);
1295 // is this slot a foster child?
1297 if( slot <= bt->page->cnt - bt->page->foster )
1301 while( slotptr(bt->page, slot)->dead )
1302 if( slot++ < bt->page->cnt )
1307 if( slot <= bt->page->cnt - bt->page->foster )
1310 // continue down / right using overlapping locks
1311 // to protect pages being killed or split.
1313 page_no = bt_getid(slotptr(bt->page, slot)->id);
1317 page_no = bt_getid(bt->page->right);
1321 // return error on end of chain
1323 bt->err = BTERR_struct;
1324 return 0; // return error
1327 // find and delete key on page by marking delete flag bit
1328 // when page becomes empty, delete it from the btree
1330 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl)
1332 unsigned char leftkey[256], rightkey[256];
1337 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1338 ptr = keyptr(bt->page, slot);
1342 // if key is found delete it, otherwise ignore request
1344 if( !keycmp (ptr, key, len) )
1345 if( slotptr(bt->page, slot)->dead == 0 ) {
1346 slotptr(bt->page,slot)->dead = 1;
1347 if( slot < bt->page->cnt )
1348 bt->page->dirty = 1;
1352 // return if page is not empty, or it has no right sibling
1354 right = bt_getid(bt->page->right);
1355 page_no = bt->page_no;
1357 if( !right || bt->page->act )
1358 return bt_unlockpage(bt, page_no, BtLockWrite);
1360 // obtain Parent lock over write lock
1362 if( bt_lockpage(bt, page_no, BtLockParent, NULL) )
1365 // cache copy of key to delete
1367 ptr = keyptr(bt->page, bt->page->cnt);
1368 memcpy(leftkey, ptr, ptr->len + 1);
1370 // lock and map right page
1372 if( bt_lockpage(bt, right, BtLockWrite, &bt->temp) )
1375 // pull contents of next page into current empty page
1376 memcpy (bt->page, bt->temp, bt->mgr->page_size);
1378 // cache copy of key to update
1379 ptr = keyptr(bt->temp, bt->temp->cnt);
1380 memcpy(rightkey, ptr, ptr->len + 1);
1382 // Mark right page as deleted and point it to left page
1383 // until we can post updates at higher level.
1385 bt_putid(bt->temp->right, page_no);
1389 if( bt_unlockpage(bt, right, BtLockWrite) )
1391 if( bt_unlockpage(bt, page_no, BtLockWrite) )
1394 // delete old lower key to consolidated node
1396 if( bt_deletekey (bt, leftkey + 1, *leftkey, lvl + 1) )
1399 // redirect higher key directly to consolidated node
1401 if( slot = bt_loadpage (bt, rightkey+1, *rightkey, lvl+1, BtLockWrite) )
1402 ptr = keyptr(bt->page, slot);
1406 // since key already exists, update id
1408 if( keycmp (ptr, rightkey+1, *rightkey) )
1409 return bt->err = BTERR_struct;
1411 slotptr(bt->page, slot)->dead = 0;
1412 bt_putid(slotptr(bt->page,slot)->id, page_no);
1414 if( bt_unlockpage(bt, bt->page_no, BtLockWrite) )
1417 // obtain write lock and
1418 // add right block to free chain
1420 if( bt_freepage (bt, right) )
1423 // remove ParentModify lock
1425 if( bt_unlockpage(bt, page_no, BtLockParent) )
1431 // find key in leaf level and return row-id
1433 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1439 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1440 ptr = keyptr(bt->page, slot);
1444 // if key exists, return row-id
1445 // otherwise return 0
1447 if( ptr->len == len && !memcmp (ptr->key, key, len) )
1448 id = bt_getid(slotptr(bt->page,slot)->id);
1452 if( bt_unlockpage (bt, bt->page_no, BtLockRead) )
1458 // check page for space available,
1459 // clean if necessary and return
1460 // 0 - page needs splitting
1463 uint bt_cleanpage(BtDb *bt, uint amt)
1465 uint nxt = bt->mgr->page_size;
1466 BtPage page = bt->page;
1467 uint cnt = 0, idx = 0;
1468 uint max = page->cnt;
1471 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1474 // skip cleanup if nothing to reclaim
1479 memcpy (bt->frame, page, bt->mgr->page_size);
1481 // skip page info and set rest of page to zero
1483 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1487 // try cleaning up page first
1489 while( cnt++ < max ) {
1490 // always leave fence key and foster children in list
1491 if( cnt < max - page->foster && slotptr(bt->frame,cnt)->dead )
1495 key = keyptr(bt->frame, cnt);
1496 nxt -= key->len + 1;
1497 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1500 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1501 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1503 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1504 slotptr(page, idx)->off = nxt;
1510 // see if page has enough space now, or does it need splitting?
1512 if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1518 // add key to current page
1519 // page must already be writelocked
1521 void bt_addkeytopage (BtDb *bt, uint slot, unsigned char *key, uint len, uid id, uint tod)
1523 BtPage page = bt->page;
1526 // calculate next available slot and copy key into page
1528 page->min -= len + 1;
1529 ((unsigned char *)page)[page->min] = len;
1530 memcpy ((unsigned char *)page + page->min +1, key, len );
1532 for( idx = slot; idx < page->cnt; idx++ )
1533 if( slotptr(page, idx)->dead )
1536 // now insert key into array before slot
1537 // preserving the fence slot
1539 if( idx == page->cnt )
1545 *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
1547 bt_putid(slotptr(page,slot)->id, id);
1548 slotptr(page, slot)->off = page->min;
1549 slotptr(page, slot)->tod = tod;
1550 slotptr(page, slot)->dead = 0;
1553 // split the root and raise the height of the btree
1554 // call with current page locked and page no of foster child
1555 // return with current page (root) unlocked
1557 BTERR bt_splitroot(BtDb *bt, uid right)
1559 uint nxt = bt->mgr->page_size;
1560 unsigned char fencekey[256];
1561 BtPage root = bt->page;
1565 // Obtain an empty page to use, and copy the left page
1566 // contents into it from the root. Strip foster child key.
1567 // (it's the stopper key)
1573 // Save left fence key.
1575 key = keyptr(root, root->cnt);
1576 memcpy (fencekey, key, key->len + 1);
1578 // copy the lower keys into a new left page
1580 if( !(new_page = bt_newpage(bt, root)) )
1583 // preserve the page info at the bottom
1584 // and set rest of the root to zero
1586 memset (root+1, 0, bt->mgr->page_size - sizeof(*root));
1588 // insert left fence key on empty newroot page
1590 nxt -= *fencekey + 1;
1591 memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
1592 bt_putid(slotptr(root, 1)->id, new_page);
1593 slotptr(root, 1)->off = nxt;
1595 // insert stopper key on newroot page
1596 // and increase the root height
1602 memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
1603 bt_putid(slotptr(root, 2)->id, right);
1604 slotptr(root, 2)->off = nxt;
1606 bt_putid(root->right, 0);
1607 root->min = nxt; // reset lowest used offset and key count
1612 // release root (bt->page)
1614 return bt_unlockpage(bt, ROOT_page, BtLockWrite);
1617 // split already locked full node
1618 // in current page variables
1621 BTERR bt_splitpage (BtDb *bt)
1623 uint slot, cnt, idx, max, nxt = bt->mgr->page_size;
1624 unsigned char fencekey[256];
1625 uid page_no = bt->page_no;
1626 BtPage page = bt->page;
1627 uint tod = time(NULL);
1628 uint lvl = page->lvl;
1629 uid new_page, right;
1632 // initialize frame buffer
1634 memset (bt->frame, 0, bt->mgr->page_size);
1635 max = page->cnt - page->foster;
1636 tod = (uint)time(NULL);
1640 // split higher half of keys to bt->frame
1641 // leaving foster children in the left node.
1643 while( cnt++ < max ) {
1644 key = keyptr(page, cnt);
1645 nxt -= key->len + 1;
1646 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
1647 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
1648 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
1649 slotptr(bt->frame, idx)->off = nxt;
1653 // transfer right link node
1655 if( page_no > ROOT_page ) {
1656 right = bt_getid (page->right);
1657 bt_putid(bt->frame->right, right);
1660 bt->frame->bits = bt->mgr->page_bits;
1661 bt->frame->min = nxt;
1662 bt->frame->cnt = idx;
1663 bt->frame->lvl = lvl;
1665 // get new free page and write frame to it.
1667 if( !(new_page = bt_newpage(bt, bt->frame)) )
1670 // remember fence key for new page to add
1673 key = keyptr(bt->frame, idx);
1674 memcpy (fencekey, key, key->len + 1);
1676 // update lower keys and foster children to continue in old page
1678 memcpy (bt->frame, page, bt->mgr->page_size);
1679 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1680 nxt = bt->mgr->page_size;
1685 // assemble page of smaller keys
1686 // to remain in the old page
1688 while( cnt++ < max / 2 ) {
1689 key = keyptr(bt->frame, cnt);
1690 nxt -= key->len + 1;
1691 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1692 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1693 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1694 slotptr(page, idx)->off = nxt;
1698 // insert new foster child at beginning of the current foster children
1700 nxt -= *fencekey + 1;
1701 memcpy ((unsigned char *)page + nxt, fencekey, *fencekey + 1);
1702 bt_putid (slotptr(page,++idx)->id, new_page);
1703 slotptr(page, idx)->tod = tod;
1704 slotptr(page, idx)->off = nxt;
1708 // continue with old foster child keys if any
1710 cnt = bt->frame->cnt - bt->frame->foster;
1712 while( cnt++ < bt->frame->cnt ) {
1713 key = keyptr(bt->frame, cnt);
1714 nxt -= key->len + 1;
1715 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1716 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1717 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1718 slotptr(page, idx)->off = nxt;
1725 // link new right page
1727 bt_putid (page->right, new_page);
1729 // if current page is the root page, split it
1731 if( page_no == ROOT_page )
1732 return bt_splitroot (bt, new_page);
1734 // release wr lock on our page
1736 if( bt_unlockpage (bt, page_no, BtLockWrite) )
1739 // obtain ParentModification lock for current page
1740 // to fix fence key and highest foster child on page
1742 if( bt_lockpage (bt, page_no, BtLockParent, NULL) )
1745 // get our highest foster child key to find in parent node
1747 if( bt_lockpage (bt, page_no, BtLockRead, &page) )
1750 key = keyptr(page, page->cnt);
1751 memcpy (fencekey, key, key->len+1);
1753 if( bt_unlockpage (bt, page_no, BtLockRead) )
1756 // update our parent
1760 slot = bt_loadpage (bt, fencekey + 1, *fencekey, lvl + 1, BtLockWrite);
1765 // check if parent page has enough space for any possible key
1767 if( bt_cleanpage (bt, 256) )
1770 if( bt_splitpage (bt) )
1774 // see if we are still a foster child from another node
1776 if( bt_getid (slotptr(bt->page, slot)->id) != page_no ) {
1777 if( bt_unlockpage (bt, bt->page_no, BtLockWrite) )
1787 // wait until readers from parent get their locks
1790 if( bt_lockpage (bt, page_no, BtLockDelete, NULL) )
1793 // lock our page for writing
1795 if( bt_lockpage (bt, page_no, BtLockWrite, &page) )
1798 // switch parent fence key to foster child
1800 if( slotptr(page, page->cnt)->dead )
1801 slotptr(bt->page, slot)->dead = 1;
1803 bt_putid (slotptr(bt->page, slot)->id, bt_getid(slotptr(page, page->cnt)->id));
1805 // remove highest foster child from our page
1811 key = keyptr(page, page->cnt);
1813 // add our new fence key for foster child to our parent
1815 bt_addkeytopage (bt, slot, key->key, key->len, page_no, tod);
1817 if( bt_unlockpage (bt, bt->page_no, BtLockWrite) )
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 bt_addkeytopage (bt, slot, key, len, id, tod);
1869 return bt_unlockpage (bt, bt->page_no, BtLockWrite);
1872 // cache page of keys into cursor and return starting slot for given key
1874 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
1878 // cache page for retrieval
1879 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1880 memcpy (bt->cursor, bt->page, bt->mgr->page_size);
1881 bt->cursor_page = bt->page_no;
1882 if ( bt_unlockpage(bt, bt->page_no, BtLockRead) )
1888 // return next slot for cursor page
1889 // or slide cursor right into next page
1891 uint bt_nextkey (BtDb *bt, uint slot)
1897 right = bt_getid(bt->cursor->right);
1898 while( slot++ < bt->cursor->cnt - bt->cursor->foster )
1899 if( slotptr(bt->cursor,slot)->dead )
1901 else if( right || (slot < bt->cursor->cnt - bt->cursor->foster) )
1909 bt->cursor_page = right;
1911 if( bt_lockpage(bt, right, BtLockRead, &page) )
1914 memcpy (bt->cursor, page, bt->mgr->page_size);
1916 if ( bt_unlockpage(bt, right, BtLockRead) )
1925 BtKey bt_key(BtDb *bt, uint slot)
1927 return keyptr(bt->cursor, slot);
1930 uid bt_uid(BtDb *bt, uint slot)
1932 return bt_getid(slotptr(bt->cursor,slot)->id);
1935 uint bt_tod(BtDb *bt, uint slot)
1937 return slotptr(bt->cursor,slot)->tod;
1950 // standalone program to index file of keys
1951 // then list them onto std-out
1954 void *index_file (void *arg)
1956 uint __stdcall index_file (void *arg)
1959 int line = 0, found = 0, cnt = 0;
1960 uid next, page_no = LEAF_page; // start on first page of leaves
1961 unsigned char key[256];
1962 ThreadArg *args = arg;
1963 int ch, len = 0, slot;
1970 bt = bt_open (args->mgr);
1973 switch(args->type | 0x20)
1976 fprintf(stderr, "started indexing for %s\n", args->infile);
1977 if( in = fopen (args->infile, "rb") )
1978 while( ch = getc(in), ch != EOF )
1983 if( args->num == 1 )
1984 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
1986 else if( args->num )
1987 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
1989 if( bt_insertkey (bt, key, len, line, *tod) )
1990 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
1993 else if( len < 255 )
1995 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
1999 fprintf(stderr, "started deleting keys for %s\n", args->infile);
2000 if( in = fopen (args->infile, "rb") )
2001 while( ch = getc(in), ch != EOF )
2005 if( args->num == 1 )
2006 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2008 else if( args->num )
2009 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2011 if( bt_deletekey (bt, key, len, 0) )
2012 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2015 else if( len < 255 )
2017 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2021 fprintf(stderr, "started finding keys for %s\n", args->infile);
2022 if( in = fopen (args->infile, "rb") )
2023 while( ch = getc(in), ch != EOF )
2027 if( args->num == 1 )
2028 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2030 else if( args->num )
2031 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2033 if( bt_findkey (bt, key, len) )
2036 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2039 else if( len < 255 )
2041 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2047 fprintf(stderr, "started reading\n");
2049 if( slot = bt_startkey (bt, key, len) )
2052 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
2054 while( slot = bt_nextkey (bt, slot) ) {
2055 ptr = bt_key(bt, slot);
2056 fwrite (ptr->key, ptr->len, 1, stdout);
2057 fputc ('\n', stdout);
2063 fprintf(stderr, "started reading\n");
2066 bt_lockpage (bt, page_no, BtLockRead, &page);
2068 next = bt_getid (page->right);
2069 bt_unlockpage (bt, page_no, BtLockRead);
2070 } while( page_no = next );
2072 cnt--; // remove stopper key
2073 fprintf(stderr, " Total keys read %d\n", cnt);
2085 typedef struct timeval timer;
2087 int main (int argc, char **argv)
2089 int idx, cnt, len, slot, err;
2090 int segsize, bits = 16;
2095 time_t start[1], stop[1];
2108 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]);
2109 fprintf (stderr, " where page_bits is the page size in bits\n");
2110 fprintf (stderr, " mapped_segments is the number of mmap segments in buffer pool\n");
2111 fprintf (stderr, " seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2112 fprintf (stderr, " line_numbers = 1 to append line numbers to keys\n");
2113 fprintf (stderr, " src_file1 thru src_filen are files of keys separated by newline\n");
2118 gettimeofday(&start, NULL);
2124 bits = atoi(argv[3]);
2127 poolsize = atoi(argv[4]);
2130 fprintf (stderr, "Warning: no mapped_pool\n");
2132 if( poolsize > 65535 )
2133 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2136 segsize = atoi(argv[5]);
2138 segsize = 4; // 16 pages per mmap segment
2141 num = atoi(argv[6]);
2145 threads = malloc (cnt * sizeof(pthread_t));
2147 threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2149 args = malloc (cnt * sizeof(ThreadArg));
2151 mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2154 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2160 for( idx = 0; idx < cnt; idx++ ) {
2161 args[idx].infile = argv[idx + 7];
2162 args[idx].type = argv[2][0];
2163 args[idx].mgr = mgr;
2164 args[idx].num = num;
2165 args[idx].idx = idx;
2167 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2168 fprintf(stderr, "Error creating thread %d\n", err);
2170 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2174 // wait for termination
2177 for( idx = 0; idx < cnt; idx++ )
2178 pthread_join (threads[idx], NULL);
2179 gettimeofday(&stop, NULL);
2180 real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2182 WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2184 for( idx = 0; idx < cnt; idx++ )
2185 CloseHandle(threads[idx]);
2188 real_time = 1000 * (*stop - *start);
2190 fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);