1 // btree version threads2d sched_yield version
4 // author: karl malbrain, malbrain@cal.berkeley.edu
7 This work, including the source code, documentation
8 and related data, is placed into the public domain.
10 The orginal author is Karl Malbrain.
12 THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY
13 OF ANY KIND, NOT EVEN THE IMPLIED WARRANTY OF
14 MERCHANTABILITY. THE AUTHOR OF THIS SOFTWARE,
15 ASSUMES _NO_ RESPONSIBILITY FOR ANY CONSEQUENCE
16 RESULTING FROM THE USE, MODIFICATION, OR
17 REDISTRIBUTION OF THIS SOFTWARE.
20 // Please see the project home page for documentation
21 // http://code.google.com/p/high-concurrency-btree
23 #define _FILE_OFFSET_BITS 64
24 #define _LARGEFILE64_SOURCE
40 #define WIN32_LEAN_AND_MEAN
52 typedef unsigned long long uid;
55 typedef unsigned long long off64_t;
56 typedef unsigned short ushort;
57 typedef unsigned int uint;
60 #define BT_ro 0x6f72 // ro
61 #define BT_rw 0x7772 // rw
63 #define BT_maxbits 24 // maximum page size in bits
64 #define BT_minbits 9 // minimum page size in bits
65 #define BT_minpage (1 << BT_minbits) // minimum page size
66 #define BT_maxpage (1 << BT_maxbits) // maximum page size
69 There are five lock types for each node in three independent sets:
70 1. (set 1) AccessIntent: Sharable. Going to Read the node. Incompatible with NodeDelete.
71 2. (set 1) NodeDelete: Exclusive. About to release the node. Incompatible with AccessIntent.
72 3. (set 2) ReadLock: Sharable. Read the node. Incompatible with WriteLock.
73 4. (set 2) WriteLock: Exclusive. Modify the node. Incompatible with ReadLock and other WriteLocks.
74 5. (set 3) ParentModification: Exclusive. Change the node's parent keys. Incompatible with another ParentModification.
85 // Define the length of the page and key pointers
89 // Page key slot definition.
91 // If BT_maxbits is 15 or less, you can save 4 bytes
92 // for each key stored by making the first two uints
93 // into ushorts. You can also save 4 bytes by removing
94 // the tod field from the key.
96 // Keys are marked dead, but remain on the page until
97 // it cleanup is called. The fence key (highest key) for
98 // the page is always present, even after cleanup.
101 uint off:BT_maxbits; // page offset for key start
102 uint dead:1; // set for deleted key
103 uint tod; // time-stamp for key
104 unsigned char id[BtId]; // id associated with key
107 // The key structure occupies space at the upper end of
108 // each page. It's a length byte followed by the value
113 unsigned char key[1];
116 // The first part of an index page.
117 // It is immediately followed
118 // by the BtSlot array of keys.
120 typedef struct Page {
121 uint cnt; // count of keys in page
122 uint act; // count of active keys
123 uint min; // next key offset
124 unsigned char bits; // page size in bits
125 unsigned char lvl:7; // level of page
126 unsigned char kill:1; // page is being deleted
127 unsigned char right[BtId]; // page number to right
130 // mode & definition for latch table implementation
137 // latch table lock structure
139 // mode is set for write access
140 // share is count of read accessors
141 // grant write lock when share == 0
149 BtLatch readwr[1]; // read/write page lock
150 BtLatch access[1]; // Access Intent/Page delete
151 BtLatch parent[1]; // Parent modification
154 // The memory mapping hash table buffer manager entry
157 unsigned long long int lru; // number of times accessed
158 uid basepage; // mapped base page number
159 char *map; // mapped memory pointer
160 uint pin; // mapped page pin counter
161 uint slot; // slot index in this array
162 void *hashprev; // previous cache block for the same hash idx
163 void *hashnext; // next cache block for the same hash idx
167 // array of page latch sets, one for each page in map segment
168 BtLatchSet pagelatch[0];
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
183 uint nodecnt; // highest page cache node in use
184 uint nodemax; // highest page cache node allocated
185 uint hashmask; // number of pages in mmap segment
186 uint hashsize; // size of Hash Table
187 uint evicted; // last evicted hash slot
188 ushort *cache; // hash index for memory pool
189 BtLatch *latch; // latches for hash table slots
190 char *nodes; // memory pool page hash nodes
194 BtMgr *mgr; // buffer manager for thread
195 BtPage temp; // temporary frame buffer (memory mapped/file IO)
196 BtPage alloc; // frame buffer for alloc page ( page 0 )
197 BtPage cursor; // cached frame for start/next (never mapped)
198 BtPage frame; // spare frame for the page split (never mapped)
199 BtPage zero; // page frame for zeroes at end of file
200 BtPage page; // current page
201 uid page_no; // current page number
202 uid cursor_page; // current cursor page number
203 unsigned char *mem; // frame, cursor, page memory buffer
204 int err; // last error
218 extern void bt_close (BtDb *bt);
219 extern BtDb *bt_open (BtMgr *mgr);
220 extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod);
221 extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl);
222 extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
223 extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
224 extern uint bt_nextkey (BtDb *bt, uint slot);
227 extern BtMgr *bt_mgr (char *name, uint mode, uint bits, uint cacheblk, uint segsize, uint hashsize);
228 void bt_mgrclose (BtMgr *mgr);
230 // Helper functions to return slot values
232 extern BtKey bt_key (BtDb *bt, uint slot);
233 extern uid bt_uid (BtDb *bt, uint slot);
234 extern uint bt_tod (BtDb *bt, uint slot);
236 // BTree page number constants
240 // Number of levels to create in a new BTree
244 // The page is allocated from low and hi ends.
245 // The key offsets and row-id's are allocated
246 // from the bottom, while the text of the key
247 // is allocated from the top. When the two
248 // areas meet, the page is split into two.
250 // A key consists of a length byte, two bytes of
251 // index number (0 - 65534), and up to 253 bytes
252 // of key value. Duplicate keys are discarded.
253 // Associated with each key is a 48 bit row-id.
255 // The b-tree root is always located at page 1.
256 // The first leaf page of level zero is always
257 // located on page 2.
259 // The b-tree pages are linked with next
260 // pointers to facilitate enumerators,
261 // and provide for concurrency.
263 // When to root page fills, it is split in two and
264 // the tree height is raised by a new root at page
265 // one with two keys.
267 // Deleted keys are marked with a dead bit until
268 // page cleanup The fence key for a node is always
269 // present, even after deletion and cleanup.
271 // Groups of pages called segments from the btree are optionally
272 // cached with memory mapping. A hash table is used to keep
273 // track of the cached segments. This behaviour is controlled
274 // by the cache block size parameter to bt_open.
276 // To achieve maximum concurrency one page is locked at a time
277 // as the tree is traversed to find leaf key in question. The right
278 // page numbers are used in cases where the page is being split,
281 // Page 0 is dedicated to lock for new page extensions,
282 // and chains empty pages together for reuse.
284 // The ParentModification lock on a node is obtained to prevent resplitting
285 // or deleting a node before its fence is posted into its upper level.
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 void bt_mgrclose (BtMgr *mgr)
318 // release mapped pages
320 for( slot = 0; slot < mgr->nodemax; slot++ ) {
321 hash = (BtHash *)(mgr->nodes + slot * (sizeof(BtHash) + (mgr->hashmask + 1) * sizeof(BtLatchSet)));
324 munmap (hash->map, (mgr->hashmask+1) << mgr->page_bits);
327 FlushViewOfFile(hash->map, 0);
328 UnmapViewOfFile(hash->map);
329 CloseHandle(hash->hmap);
340 FlushFileBuffers(mgr->idx);
341 CloseHandle(mgr->idx);
342 GlobalFree (mgr->nodes);
343 GlobalFree (mgr->cache);
344 GlobalFree (mgr->latch);
348 // close and release memory
350 void bt_close (BtDb *bt)
358 VirtualFree (bt->mem, 0, MEM_RELEASE);
363 // open/create new btree buffer manager
365 // call with file_name, BT_openmode, bits in page size (e.g. 16),
366 // size of mapped page cache (e.g. 8192)
368 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint nodemax, uint segsize, uint hashsize)
370 uint lvl, attr, cacheblk, last;
379 SYSTEM_INFO sysinfo[1];
382 // determine sanity of page size and buffer pool
384 if( bits > BT_maxbits )
386 else if( bits < BT_minbits )
390 return NULL; // must have buffer pool
393 mgr = calloc (1, sizeof(BtMgr));
395 switch (mode & 0x7fff)
398 mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
404 mgr->idx = open ((char*)name, O_RDONLY);
409 return free(mgr), NULL;
411 cacheblk = 4096; // minimum mmap segment size for unix
414 mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
415 attr = FILE_ATTRIBUTE_NORMAL;
416 switch (mode & 0x7fff)
419 mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
425 mgr->idx = CreateFile(name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, attr, NULL);
429 if( mgr->idx == INVALID_HANDLE_VALUE )
430 return GlobalFree(mgr), NULL;
432 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
433 GetSystemInfo(sysinfo);
434 cacheblk = sysinfo->dwAllocationGranularity;
438 alloc = malloc (BT_maxpage);
441 // read minimum page size to get root info
443 if( size = lseek (mgr->idx, 0L, 2) ) {
444 if( pread(mgr->idx, alloc, BT_minpage, 0) == BT_minpage )
447 return free(mgr), free(alloc), NULL;
448 } else if( mode == BT_ro )
449 return bt_mgrclose (mgr), NULL;
451 alloc = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
452 size = GetFileSize(mgr->idx, amt);
455 if( !ReadFile(mgr->idx, (char *)alloc, BT_minpage, amt, NULL) )
456 return bt_mgrclose (mgr), NULL;
458 } else if( mode == BT_ro )
459 return bt_mgrclose (mgr), NULL;
462 mgr->page_size = 1 << bits;
463 mgr->page_bits = bits;
465 mgr->nodemax = nodemax;
468 if( cacheblk < mgr->page_size )
469 cacheblk = mgr->page_size;
471 // mask for partial memmaps
473 mgr->hashmask = (cacheblk >> bits) - 1;
475 // see if requested number of pages per memmap is greater
477 if( (1 << segsize) > mgr->hashmask )
478 mgr->hashmask = (1 << segsize) - 1;
482 while( (1 << mgr->seg_bits) <= mgr->hashmask )
485 mgr->hashsize = hashsize;
488 mgr->nodes = calloc (cacheblk, (sizeof(BtHash) + (mgr->hashmask + 1) * sizeof(BtLatchSet)));
489 mgr->cache = calloc (hashsize, sizeof(ushort));
490 mgr->latch = calloc (hashsize, sizeof(BtLatch));
492 mgr->nodes = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cacheblk * (sizeof(BtHash) + (mgr->hashmask + 1) * sizeof(BtLatchSet)));
493 mgr->cache = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
494 mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtLatch));
500 // initializes an empty b-tree with root page and page of leaves
502 memset (alloc, 0, 1 << bits);
503 bt_putid(alloc->right, MIN_lvl+1);
504 alloc->bits = mgr->page_bits;
507 if( write (mgr->idx, alloc, mgr->page_size) < mgr->page_size )
508 return bt_mgrclose (mgr), NULL;
510 if( !WriteFile (mgr->idx, (char *)alloc, mgr->page_size, amt, NULL) )
511 return bt_mgrclose (mgr), NULL;
513 if( *amt < mgr->page_size )
514 return bt_mgrclose (mgr), NULL;
517 memset (alloc, 0, 1 << bits);
518 alloc->bits = mgr->page_bits;
520 for( lvl=MIN_lvl; lvl--; ) {
521 slotptr(alloc, 1)->off = mgr->page_size - 3;
522 bt_putid(slotptr(alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
523 key = keyptr(alloc, 1);
524 key->len = 2; // create stopper key
527 alloc->min = mgr->page_size - 3;
532 if( write (mgr->idx, alloc, mgr->page_size) < mgr->page_size )
533 return bt_mgrclose (mgr), NULL;
535 if( !WriteFile (mgr->idx, (char *)alloc, mgr->page_size, amt, NULL) )
536 return bt_mgrclose (mgr), NULL;
538 if( *amt < mgr->page_size )
539 return bt_mgrclose (mgr), NULL;
543 // create empty page area by writing last page of first
544 // cache area (other pages are zeroed by O/S)
546 if( mgr->hashmask ) {
547 memset(alloc, 0, mgr->page_size);
548 last = mgr->hashmask;
550 while( last < MIN_lvl + 1 )
551 last += mgr->hashmask + 1;
554 pwrite(mgr->idx, alloc, mgr->page_size, last << mgr->page_bits);
556 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
557 if( !WriteFile (mgr->idx, (char *)alloc, mgr->page_size, amt, NULL) )
558 return bt_mgrclose (mgr), NULL;
559 if( *amt < mgr->page_size )
560 return bt_mgrclose (mgr), NULL;
568 VirtualFree (alloc, 0, MEM_RELEASE);
573 // open BTree access method
574 // based on buffer manager
576 BtDb *bt_open (BtMgr *mgr)
578 BtDb *bt = malloc (sizeof(*bt));
580 memset (bt, 0, sizeof(*bt));
583 bt->mem = malloc (3 *mgr->page_size);
585 bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
587 bt->frame = (BtPage)bt->mem;
588 bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
589 bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
593 // compare two keys, returning > 0, = 0, or < 0
594 // as the comparison value
596 int keycmp (BtKey key1, unsigned char *key2, uint len2)
598 uint len1 = key1->len;
601 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
614 // wait until write lock mode is clear
615 // and add 1 to the share count
617 void bt_readlock(BtLatch *latch)
620 // add one to counter, check write bit
623 if( ~__sync_fetch_and_add((int *)latch, Share) & Write )
626 if( ~InterlockedAdd((int *)latch, Share) & Write )
629 // didn't get latch, reset counter by one
632 __sync_fetch_and_add((int *)latch, -Share);
634 InterlockedAdd ((int *)latch, -Share);
646 // wait for other read and write latches to relinquish
648 void bt_writelock(BtLatch *latch)
653 // see if we can get write access
656 prev = __sync_fetch_and_or((int *)latch, Write);
658 prev = InterlockedOr((int *)latch, Write);
664 if( !(prev >> 1) && ours )
677 // try to obtain write lock
679 // return 1 if obtained,
680 // 0 if already write locked
682 int bt_writetry(BtLatch *latch)
687 // see if we can get write access
690 prev = __sync_fetch_and_or((int *)latch, Write);
692 prev = InterlockedOr((int *)latch, Write);
701 if( !(prev >> 1) && ours )
715 void bt_releasewrite(BtLatch *latch)
718 __sync_fetch_and_and((int *)latch, ~Write);
720 InterlockedAnd ((int *)latch, ~Write);
724 // decrement reader count
726 void bt_releaseread(BtLatch *latch)
729 __sync_fetch_and_add((int *)latch, -Share);
731 InterlockedAdd((int *)latch, -Share);
737 // find segment in cache
738 // return NULL if not there
739 // otherwise return node
741 BtHash *bt_findhash(BtDb *bt, uid page_no, uint idx)
746 // compute cache block first page and hash idx
748 if( slot = bt->mgr->cache[idx] )
749 hash = (BtHash *)(bt->mgr->nodes + slot * (sizeof(BtHash) + (bt->mgr->hashmask + 1) * sizeof(BtLatchSet)));
753 page_no &= ~bt->mgr->hashmask;
755 while( hash->basepage != page_no )
756 if( hash = hash->hashnext )
764 // add segment to hash table
766 void bt_linkhash(BtDb *bt, BtHash *hash, uid page_no, int idx)
771 hash->hashprev = hash->hashnext = NULL;
772 hash->basepage = page_no & ~bt->mgr->hashmask;
776 if( slot = bt->mgr->cache[idx] ) {
777 node = (BtHash *)(bt->mgr->nodes + slot * (sizeof(BtHash) + (bt->mgr->hashmask + 1) * sizeof(BtLatchSet)));
778 hash->hashnext = node;
779 node->hashprev = hash;
782 bt->mgr->cache[idx] = hash->slot;
785 // find best segment to evict from buffer pool
787 BtHash *bt_findlru (BtDb *bt, uint slot)
789 unsigned long long int target = ~0LL;
790 BtHash *hash = NULL, *node;
795 node = (BtHash *)(bt->mgr->nodes + slot * (sizeof(BtHash) + (bt->mgr->hashmask + 1) * sizeof(BtLatchSet)));
800 if( node->lru > target )
804 } while( node = node->hashnext );
809 // map new segment to virtual memory
811 BTERR bt_mapsegment(BtDb *bt, BtHash *hash, uid page_no)
813 off64_t off = (page_no & ~bt->mgr->hashmask) << bt->mgr->page_bits;
814 off64_t limit = off + ((bt->mgr->hashmask+1) << bt->mgr->page_bits);
818 flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
819 hash->map = mmap (0, (bt->mgr->hashmask+1) << bt->mgr->page_bits, flag, MAP_SHARED, bt->mgr->idx, off);
820 if( hash->map == MAP_FAILED )
821 return bt->err = BTERR_map;
823 flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
824 hash->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
826 return bt->err = BTERR_map;
828 flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
829 hash->map = MapViewOfFile(hash->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->hashmask+1) << bt->mgr->page_bits);
831 return bt->err = BTERR_map;
836 // find or place requested page in segment-cache
837 // return hash table entry
839 BtHash *bt_hashpage(BtDb *bt, uid page_no)
841 BtHash *hash, *node, *next;
842 uint slot, idx, victim;
845 // lock hash table chain
847 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
848 bt_readlock (&bt->mgr->latch[idx]);
850 // look up in hash table
852 if( hash = bt_findhash(bt, page_no, idx) ) {
854 __sync_fetch_and_add(&hash->pin, 1);
856 InterlockedIncrement (&hash->pin);
858 bt_releaseread (&bt->mgr->latch[idx]);
863 // upgrade to write lock
865 bt_releaseread (&bt->mgr->latch[idx]);
866 bt_writelock (&bt->mgr->latch[idx]);
868 // try to find page in cache with write lock
870 if( hash = bt_findhash(bt, page_no, idx) ) {
872 __sync_fetch_and_add(&hash->pin, 1);
874 InterlockedIncrement (&hash->pin);
876 bt_releasewrite (&bt->mgr->latch[idx]);
881 // allocate a new hash node
882 // and add to hash table
885 slot = __sync_fetch_and_add(&bt->mgr->nodecnt, 1);
887 slot = InterlockedIncrement (&bt->mgr->nodecnt) - 1;
890 if( ++slot < bt->mgr->nodemax ) {
891 hash = (BtHash *)(bt->mgr->nodes + slot * (sizeof(BtHash) + (bt->mgr->hashmask + 1) * sizeof(BtLatchSet)));
894 if( bt_mapsegment(bt, hash, page_no) )
897 bt_linkhash(bt, hash, page_no, idx);
898 bt_releasewrite (&bt->mgr->latch[idx]);
902 // hash table is full
903 // find best cache entry to evict
906 __sync_fetch_and_add(&bt->mgr->nodecnt, -1);
908 InterlockedDecrement (&bt->mgr->nodecnt);
913 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
915 victim = InterlockedIncrement (&bt->mgr->evicted) - 1;
917 victim %= bt->mgr->hashsize;
919 // try to get write lock
920 // skip entry if not obtained
922 if( !bt_writetry (&bt->mgr->latch[victim]) )
925 // if cache entry is empty
926 // or no slots are unpinned
929 if( !(hash = bt_findlru(bt, bt->mgr->cache[victim])) ) {
930 bt_releasewrite (&bt->mgr->latch[victim]);
934 // unlink victim hash node from hash table
936 if( node = hash->hashprev )
937 node->hashnext = hash->hashnext;
938 else if( node = hash->hashnext )
939 bt->mgr->cache[victim] = node->slot;
941 bt->mgr->cache[victim] = 0;
943 if( node = hash->hashnext )
944 node->hashprev = hash->hashprev;
946 // remove old file mapping
948 munmap (hash->map, (bt->mgr->hashmask+1) << bt->mgr->page_bits);
950 FlushViewOfFile(hash->map, 0);
951 UnmapViewOfFile(hash->map);
952 CloseHandle(hash->hmap);
955 bt_releasewrite (&bt->mgr->latch[victim]);
957 // create new file mapping
958 // and link into hash table
960 if( bt_mapsegment(bt, hash, page_no) )
963 bt_linkhash(bt, hash, page_no, idx);
964 bt_releasewrite (&bt->mgr->latch[idx]);
969 // place write, read, or parent lock on requested page_no.
970 // pin to buffer pool
972 BTERR bt_lockpage(BtDb *bt, uid page_no, BtLock mode, BtPage *page)
978 // find/create maping in hash table
980 if( hash = bt_hashpage(bt, page_no) )
981 subpage = (uint)(page_no & bt->mgr->hashmask); // page within mapping
985 set = hash->pagelatch + subpage;
989 bt_readlock (set->readwr);
992 bt_writelock (set->readwr);
995 bt_readlock (set->access);
998 bt_writelock (set->access);
1001 bt_writelock (set->parent);
1004 return bt->err = BTERR_lock;
1008 *page = (BtPage)(hash->map + (subpage << bt->mgr->page_bits));
1013 // remove write, read, or parent lock on requested page_no.
1015 BTERR bt_unlockpage(BtDb *bt, uid page_no, BtLock mode)
1021 // since page is pinned
1022 // it should still be in the buffer pool
1024 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1025 bt_readlock (&bt->mgr->latch[idx]);
1027 if( hash = bt_findhash(bt, page_no, idx) )
1028 subpage = (uint)(page_no & bt->mgr->hashmask);
1030 return bt->err = BTERR_hash;
1032 bt_releaseread (&bt->mgr->latch[idx]);
1033 set = hash->pagelatch + subpage;
1037 bt_releaseread (set->readwr);
1040 bt_releasewrite (set->readwr);
1043 bt_releaseread (set->access);
1046 bt_releasewrite (set->access);
1049 bt_releasewrite (set->parent);
1052 return bt->err = BTERR_lock;
1056 __sync_fetch_and_add(&hash->pin, -1);
1058 InterlockedDecrement (&hash->pin);
1063 // deallocate a deleted page
1064 // place on free chain out of allocator page
1066 BTERR bt_freepage(BtDb *bt, uid page_no)
1068 // obtain delete lock on deleted page
1070 if( bt_lockpage(bt, page_no, BtLockDelete, NULL) )
1073 // obtain write lock on deleted page
1075 if( bt_lockpage(bt, page_no, BtLockWrite, &bt->temp) )
1078 // lock allocation page
1080 if ( bt_lockpage(bt, ALLOC_page, BtLockWrite, &bt->alloc) )
1083 // store chain in second right
1084 bt_putid(bt->temp->right, bt_getid(bt->alloc[1].right));
1085 bt_putid(bt->alloc[1].right, page_no);
1089 if( bt_unlockpage(bt, ALLOC_page, BtLockWrite) )
1092 // remove write lock on deleted node
1094 if( bt_unlockpage(bt, page_no, BtLockWrite) )
1097 // remove delete lock on deleted node
1099 if( bt_unlockpage(bt, page_no, BtLockDelete) )
1105 // allocate a new page and write page into it
1107 uid bt_newpage(BtDb *bt, BtPage page)
1115 if ( bt_lockpage(bt, ALLOC_page, BtLockWrite, &bt->alloc) )
1118 // use empty chain first
1119 // else allocate empty page
1121 if( new_page = bt_getid(bt->alloc[1].right) ) {
1122 if( bt_lockpage (bt, new_page, BtLockWrite, &bt->temp) )
1124 bt_putid(bt->alloc[1].right, bt_getid(bt->temp->right));
1125 if( bt_unlockpage (bt, new_page, BtLockWrite) )
1129 new_page = bt_getid(bt->alloc->right);
1130 bt_putid(bt->alloc->right, new_page+1);
1135 if ( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1136 return bt->err = BTERR_wrt, 0;
1138 // if writing first page of hash block, zero last page in the block
1140 if ( !reuse && bt->mgr->hashmask > 0 && (new_page & bt->mgr->hashmask) == 0 )
1142 // use zero buffer to write zeros
1143 memset(bt->zero, 0, bt->mgr->page_size);
1144 if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->hashmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1145 return bt->err = BTERR_wrt, 0;
1148 // bring new page into page-cache and copy page.
1149 // this will extend the file into the new pages.
1151 if( bt_lockpage(bt, new_page, BtLockWrite, &pmap) )
1154 memcpy(pmap, page, bt->mgr->page_size);
1156 if( bt_unlockpage (bt, new_page, BtLockWrite) )
1161 if ( bt_unlockpage(bt, ALLOC_page, BtLockWrite) )
1167 // find slot in page for given key at a given level
1169 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1171 uint diff, higher = bt->page->cnt, low = 1, slot;
1174 // make stopper key an infinite fence value
1176 if( bt_getid (bt->page->right) )
1181 // low is the next candidate, higher is already
1182 // tested as .ge. the given key, loop ends when they meet
1184 while( diff = higher - low ) {
1185 slot = low + ( diff >> 1 );
1186 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1189 higher = slot, good++;
1192 // return zero if key is on right link page
1194 return good ? higher : 0;
1197 // find and load page at given level for given key
1198 // leave page rd or wr locked as requested
1200 int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, uint lock)
1202 uid page_no = ROOT_page, prevpage = 0;
1203 uint drill = 0xff, slot;
1204 uint mode, prevmode;
1206 // start at root of btree and drill down
1209 // determine lock mode of drill level
1210 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1212 bt->page_no = page_no;
1214 // obtain access lock using lock chaining with Access mode
1216 if( page_no > ROOT_page )
1217 if( bt_lockpage(bt, page_no, BtLockAccess, NULL) )
1221 if( bt_unlockpage(bt, prevpage, prevmode) )
1224 // obtain read lock using lock chaining
1225 // and pin page contents
1227 if( bt_lockpage(bt, page_no, mode, &bt->page) )
1230 if( page_no > ROOT_page )
1231 if( bt_unlockpage(bt, page_no, BtLockAccess) )
1234 // re-read and re-lock root after determining actual level of root
1236 if( bt->page->lvl != drill) {
1237 if ( bt->page_no != ROOT_page )
1238 return bt->err = BTERR_struct, 0;
1240 drill = bt->page->lvl;
1242 if( lock == BtLockWrite && drill == lvl )
1243 if( bt_unlockpage(bt, page_no, mode) )
1249 // find key on page at this level
1250 // and descend to requested level
1252 if( !bt->page->kill && (slot = bt_findslot (bt, key, len)) ) {
1256 while( slotptr(bt->page, slot)->dead )
1257 if( slot++ < bt->page->cnt )
1260 page_no = bt_getid(bt->page->right);
1264 page_no = bt_getid(slotptr(bt->page, slot)->id);
1268 // or slide right into next page
1269 // (slide left from deleted page)
1272 page_no = bt_getid(bt->page->right);
1274 // continue down / right using overlapping locks
1275 // to protect pages being killed or split.
1278 prevpage = bt->page_no;
1282 // return error on end of right chain
1284 bt->err = BTERR_struct;
1285 return 0; // return error
1288 // find and delete key on page by marking delete flag bit
1289 // when page becomes empty, delete it
1291 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl)
1293 unsigned char lowerkey[256], higherkey[256];
1294 uint slot, tod, dirty = 0;
1298 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1299 ptr = keyptr(bt->page, slot);
1303 // if key is found delete it, otherwise ignore request
1305 if( !keycmp (ptr, key, len) )
1306 if( slotptr(bt->page, slot)->dead == 0 )
1307 dirty = slotptr(bt->page,slot)->dead = 1, bt->page->act--;
1309 // return if page is not empty, or it has no right sibling
1311 right = bt_getid(bt->page->right);
1312 page_no = bt->page_no;
1314 if( !right || bt->page->act )
1315 return bt_unlockpage(bt, page_no, BtLockWrite);
1317 // obtain Parent lock over write lock
1319 if( bt_lockpage(bt, page_no, BtLockParent, NULL) )
1322 // cache copy of key to delete
1324 ptr = keyptr(bt->page, bt->page->cnt);
1325 memcpy(lowerkey, ptr, ptr->len + 1);
1327 // lock and map right page
1329 if ( bt_lockpage(bt, right, BtLockWrite, &bt->temp) )
1332 // pull contents of next page into current empty page
1333 memcpy (bt->page, bt->temp, bt->mgr->page_size);
1335 // cache copy of key to update
1336 ptr = keyptr(bt->temp, bt->temp->cnt);
1337 memcpy(higherkey, ptr, ptr->len + 1);
1339 // Mark right page as deleted and point it to left page
1340 // until we can post updates at higher level.
1342 bt_putid(bt->temp->right, page_no);
1346 if( bt_unlockpage(bt, right, BtLockWrite) )
1348 if( bt_unlockpage(bt, page_no, BtLockWrite) )
1351 // delete old lower key to consolidated node
1353 if( bt_deletekey (bt, lowerkey + 1, *lowerkey, lvl + 1) )
1356 // redirect higher key directly to consolidated node
1358 tod = (uint)time(NULL);
1360 if( bt_insertkey (bt, higherkey+1, *higherkey, lvl + 1, page_no, tod) )
1363 // obtain write lock and
1364 // add right block to free chain
1366 if( bt_freepage (bt, right) )
1369 // remove ParentModify lock
1371 if( bt_unlockpage(bt, page_no, BtLockParent) )
1377 // find key in leaf level and return row-id
1379 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1385 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1386 ptr = keyptr(bt->page, slot);
1390 // if key exists, return row-id
1391 // otherwise return 0
1393 if( ptr->len == len && !memcmp (ptr->key, key, len) )
1394 id = bt_getid(slotptr(bt->page,slot)->id);
1398 if ( bt_unlockpage(bt, bt->page_no, BtLockRead) )
1404 void bt_cleanpage(BtDb *bt)
1406 uint nxt = bt->mgr->page_size;
1407 BtPage page = bt->page;
1408 uint cnt = 0, idx = 0;
1409 uint max = page->cnt;
1412 memcpy (bt->frame, page, bt->mgr->page_size);
1414 // skip page info and set rest of page to zero
1415 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1418 // try cleaning up page first
1420 while( cnt++ < max ) {
1421 // always leave fence key in list
1422 if( cnt < max && slotptr(bt->frame,cnt)->dead )
1426 key = keyptr(bt->frame, cnt);
1427 nxt -= key->len + 1;
1428 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1431 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1432 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1434 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1435 slotptr(page, idx)->off = nxt;
1441 // split the root and raise the height of the btree
1443 BTERR bt_splitroot(BtDb *bt, unsigned char *newkey, unsigned char *oldkey, uid page_no2)
1445 uint nxt = bt->mgr->page_size;
1446 BtPage root = bt->page;
1449 // Obtain an empty page to use, and copy the current
1450 // root contents into it
1452 if( !(new_page = bt_newpage(bt, root)) )
1455 // preserve the page info at the bottom
1456 // and set rest to zero
1458 memset(root+1, 0, bt->mgr->page_size - sizeof(*root));
1460 // insert first key on newroot page
1463 memcpy ((unsigned char *)root + nxt, newkey, *newkey + 1);
1464 bt_putid(slotptr(root, 1)->id, new_page);
1465 slotptr(root, 1)->off = nxt;
1467 // insert second key on newroot page
1468 // and increase the root height
1471 memcpy ((unsigned char *)root + nxt, oldkey, *oldkey + 1);
1472 bt_putid(slotptr(root, 2)->id, page_no2);
1473 slotptr(root, 2)->off = nxt;
1475 bt_putid(root->right, 0);
1476 root->min = nxt; // reset lowest used offset and key count
1481 // release root (bt->page)
1483 return bt_unlockpage(bt, bt->page_no, BtLockWrite);
1486 // split already locked full node
1489 BTERR bt_splitpage (BtDb *bt, uint len)
1491 uint cnt = 0, idx = 0, max, nxt = bt->mgr->page_size;
1492 unsigned char oldkey[256], lowerkey[256];
1493 uid page_no = bt->page_no, right;
1494 BtPage page = bt->page;
1495 uint lvl = page->lvl;
1504 // return if enough space now
1506 if( page->min >= (page->cnt + 1) * sizeof(BtSlot) + sizeof(*page) + len + 1)
1507 return bt_unlockpage(bt, page_no, BtLockWrite);
1509 // split higher half of keys to bt->frame
1510 // the last key (fence key) might be dead
1512 tod = (uint)time(NULL);
1514 memset (bt->frame, 0, bt->mgr->page_size);
1515 max = (int)page->cnt;
1519 while( cnt++ < max ) {
1520 key = keyptr(page, cnt);
1521 nxt -= key->len + 1;
1522 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
1523 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
1524 if( !(slotptr(bt->frame, idx)->dead = slotptr(page, cnt)->dead) )
1526 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
1527 slotptr(bt->frame, idx)->off = nxt;
1530 // remember existing fence key for new page to the right
1532 memcpy (oldkey, key, key->len + 1);
1534 bt->frame->bits = bt->mgr->page_bits;
1535 bt->frame->min = nxt;
1536 bt->frame->cnt = idx;
1537 bt->frame->lvl = lvl;
1541 if( page_no > ROOT_page ) {
1542 right = bt_getid (page->right);
1543 bt_putid(bt->frame->right, right);
1546 // get new free page and write frame to it.
1548 if( !(new_page = bt_newpage(bt, bt->frame)) )
1551 // update lower keys to continue in old page
1553 memcpy (bt->frame, page, bt->mgr->page_size);
1554 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1555 nxt = bt->mgr->page_size;
1560 // assemble page of smaller keys
1561 // (they're all active keys)
1563 while( cnt++ < max / 2 ) {
1564 key = keyptr(bt->frame, cnt);
1565 nxt -= key->len + 1;
1566 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1567 memcpy(slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1568 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1569 slotptr(page, idx)->off = nxt;
1573 // remember fence key for old page
1575 memcpy(lowerkey, key, key->len + 1);
1576 bt_putid(page->right, new_page);
1580 // if current page is the root page, split it
1582 if( page_no == ROOT_page )
1583 return bt_splitroot (bt, lowerkey, oldkey, new_page);
1585 // obtain Parent/Write locks
1586 // for left and right node pages
1588 if( bt_lockpage (bt, new_page, BtLockParent, NULL) )
1591 if( bt_lockpage (bt, page_no, BtLockParent, NULL) )
1594 // release wr lock on left page
1596 if( bt_unlockpage (bt, page_no, BtLockWrite) )
1599 // insert new fence for reformulated left block
1601 if( bt_insertkey (bt, lowerkey+1, *lowerkey, lvl + 1, page_no, tod) )
1604 // fix old fence for newly allocated right block page
1606 if( bt_insertkey (bt, oldkey+1, *oldkey, lvl + 1, new_page, tod) )
1609 // release Parent & Write locks
1611 if( bt_unlockpage (bt, new_page, BtLockParent) )
1614 if( bt_unlockpage (bt, page_no, BtLockParent) )
1620 // Insert new key into the btree at requested level.
1621 // Level zero pages are leaf pages and are unlocked at exit.
1622 // Interior pages remain locked.
1624 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod)
1631 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1632 ptr = keyptr(bt->page, slot);
1636 bt->err = BTERR_ovflw;
1640 // if key already exists, update id and return
1644 if( !keycmp (ptr, key, len) ) {
1645 slotptr(page, slot)->dead = 0;
1646 slotptr(page, slot)->tod = tod;
1647 bt_putid(slotptr(page,slot)->id, id);
1648 return bt_unlockpage(bt, bt->page_no, BtLockWrite);
1651 // check if page has enough space
1653 if( page->min >= (page->cnt + 1) * sizeof(BtSlot) + sizeof(*page) + len + 1)
1656 if( bt_splitpage (bt, len) )
1660 // calculate next available slot and copy key into page
1662 page->min -= len + 1; // reset lowest used offset
1663 ((unsigned char *)page)[page->min] = len;
1664 memcpy ((unsigned char *)page + page->min +1, key, len );
1666 for( idx = slot; idx < page->cnt; idx++ )
1667 if( slotptr(page, idx)->dead )
1670 // now insert key into array before slot
1671 // preserving the fence slot
1673 if( idx == page->cnt )
1679 *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
1681 bt_putid(slotptr(page,slot)->id, id);
1682 slotptr(page, slot)->off = page->min;
1683 slotptr(page, slot)->tod = tod;
1684 slotptr(page, slot)->dead = 0;
1686 return bt_unlockpage(bt, bt->page_no, BtLockWrite);
1689 // cache page of keys into cursor and return starting slot for given key
1691 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
1695 // cache page for retrieval
1696 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1697 memcpy (bt->cursor, bt->page, bt->mgr->page_size);
1698 bt->cursor_page = bt->page_no;
1699 if ( bt_unlockpage(bt, bt->page_no, BtLockRead) )
1705 // return next slot for cursor page
1706 // or slide cursor right into next page
1708 uint bt_nextkey (BtDb *bt, uint slot)
1713 right = bt_getid(bt->cursor->right);
1714 while( slot++ < bt->cursor->cnt )
1715 if( slotptr(bt->cursor,slot)->dead )
1717 else if( right || (slot < bt->cursor->cnt))
1725 bt->cursor_page = right;
1727 if( bt_lockpage(bt, right, BtLockRead, &bt->page) )
1730 memcpy (bt->cursor, bt->page, bt->mgr->page_size);
1732 if ( bt_unlockpage(bt, right, BtLockRead) )
1741 BtKey bt_key(BtDb *bt, uint slot)
1743 return keyptr(bt->cursor, slot);
1746 uid bt_uid(BtDb *bt, uint slot)
1748 return bt_getid(slotptr(bt->cursor,slot)->id);
1751 uint bt_tod(BtDb *bt, uint slot)
1753 return slotptr(bt->cursor,slot)->tod;
1765 // standalone program to index file of keys
1766 // then list them onto std-out
1769 void *index_file (void *arg)
1771 uint __stdcall index_file (void *arg)
1774 int line = 0, found = 0;
1775 unsigned char key[256];
1776 ThreadArg *args = arg;
1777 int ch, len = 0, slot;
1783 bt = bt_open (args->mgr);
1786 switch(args->type | 0x20)
1789 fprintf(stderr, "started indexing for %s\n", args->infile);
1790 if( in = fopen (args->infile, "rb") )
1791 while( ch = getc(in), ch != EOF )
1794 if( bt_insertkey (bt, key, len, 0, ++line, *tod) )
1795 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
1798 else if( len < 255 )
1800 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
1804 fprintf(stderr, "started deleting keys for %s\n", args->infile);
1805 if( in = fopen (args->infile, "rb") )
1806 while( ch = getc(in), ch != EOF )
1810 if( bt_deletekey (bt, key, len, 0) )
1811 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
1814 else if( len < 255 )
1816 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
1820 fprintf(stderr, "started finding keys for %s\n", args->infile);
1821 if( in = fopen (args->infile, "rb") )
1822 while( ch = getc(in), ch != EOF )
1826 if( bt_findkey (bt, key, len) )
1829 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
1832 else if( len < 255 )
1834 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
1840 fprintf(stderr, "started reading\n");
1842 if( slot = bt_startkey (bt, key, len) )
1845 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
1847 while( slot = bt_nextkey (bt, slot) ) {
1848 ptr = bt_key(bt, slot);
1849 fwrite (ptr->key, ptr->len, 1, stdout);
1850 fputc ('\n', stdout);
1862 typedef struct timeval timer;
1864 int main (int argc, char **argv)
1866 int idx, cnt, len, slot, err;
1867 int segsize, bits = 16;
1872 time_t start[1], stop[1];
1884 fprintf (stderr, "Usage: %s idx_file Read/Write/Scan/Delete/Find [page_bits mapped_segments seg_bits hash_size src_file1 src_file2 ... ]\n", argv[0]);
1885 fprintf (stderr, " where page_bits is the page size in bits\n");
1886 fprintf (stderr, " mapped_segments is the number of mmap segments in buffer pool\n");
1887 fprintf (stderr, " seg_bits is the size of individual segments in buffer pool in pages in bits\n");
1888 fprintf (stderr, " hash_size is the size of buffer pool hash table\n");
1889 fprintf (stderr, " src_file1 thru src_filen are files of keys separated by newline\n");
1894 gettimeofday(&start, NULL);
1900 bits = atoi(argv[3]);
1903 map = atoi(argv[4]);
1906 fprintf (stderr, "Warning: mapped_pool > 65536 segments\n");
1909 segsize = atoi(argv[5]);
1911 segsize = 4; // 16 pages per mmap segment
1915 threads = malloc (cnt * sizeof(pthread_t));
1917 threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
1919 args = malloc (cnt * sizeof(ThreadArg));
1921 mgr = bt_mgr ((argv[1]), BT_rw, bits, map, segsize, map / 8);
1924 fprintf(stderr, "Index Open Error %s\n", argv[1]);
1930 for( idx = 0; idx < cnt; idx++ ) {
1931 args[idx].infile = argv[idx + 6];
1932 args[idx].type = argv[2][0];
1933 args[idx].mgr = mgr;
1935 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
1936 fprintf(stderr, "Error creating thread %d\n", err);
1938 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
1942 // wait for termination
1945 for( idx = 0; idx < cnt; idx++ )
1946 pthread_join (threads[idx], NULL);
1947 gettimeofday(&stop, NULL);
1948 real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
1950 WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
1952 for( idx = 0; idx < cnt; idx++ )
1953 CloseHandle(threads[idx]);
1956 real_time = 1000 * (*stop - *start);
1958 fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);
1964 fprintf(stderr, "started reading\n");
1966 if( slot = bt_startkey (bt, key, len) )
1969 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
1971 while( slot = bt_nextkey (bt, slot) )
1974 fprintf(stderr, " Total keys read %d\n", cnt);