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
39 #define WIN32_LEAN_AND_MEAN
50 typedef unsigned long long uid;
53 typedef unsigned long long off64_t;
54 typedef unsigned short ushort;
55 typedef unsigned int uint;
58 #define BT_ro 0x6f72 // ro
59 #define BT_rw 0x7772 // rw
60 #define BT_fl 0x6c66 // fl
62 #define BT_maxbits 24 // maximum page size in bits
63 #define BT_minbits 9 // minimum page size in bits
64 #define BT_minpage (1 << BT_minbits) // minimum page size
67 There are five lock types for each node in three independent sets:
68 1. (set 1) AccessIntent: Sharable. Going to Read the node. Incompatible with NodeDelete.
69 2. (set 1) NodeDelete: Exclusive. About to release the node. Incompatible with AccessIntent.
70 3. (set 2) ReadLock: Sharable. Read the node. Incompatible with WriteLock.
71 4. (set 2) WriteLock: Exclusive. Modify the node. Incompatible with ReadLock and other WriteLocks.
72 5. (set 3) ParentModification: Exclusive. Change the node's parent keys. Incompatible with another ParentModification.
83 // Define the length of the page and key pointers
87 // Page key slot definition.
89 // If BT_maxbits is 15 or less, you can save 2 bytes
90 // for each key stored by making the first two uints
91 // into ushorts. You can also save 4 bytes by removing
92 // the tod field from the key.
94 // Keys are marked dead, but remain on the page until
95 // cleanup is called. The fence key (highest key) for
96 // the page is always present, even if dead.
99 uint off:BT_maxbits; // page offset for key start
100 uint dead:1; // set for deleted key
101 uint tod; // time-stamp for key
102 unsigned char id[BtId]; // id associated with key
105 // The key structure occupies space at the upper end of
106 // each page. It's a length byte followed by the value
111 unsigned char key[0];
114 // The first part of an index page.
115 // It is immediately followed
116 // by the BtSlot array of keys.
119 uint cnt; // count of keys in page
120 uint act; // count of active keys
121 uint min; // next key offset
122 unsigned char bits:7; // page size in bits
123 unsigned char free:1; // page is on free list
124 unsigned char lvl:7; // level of page
125 unsigned char dirty:1; // page is dirty
126 unsigned char right[BtId]; // page number to right
129 // The memory mapping hash table entry
132 BtPage page; // mapped page pointer
133 uid page_no; // mapped page number
134 void *lruprev; // least recently used previous cache block
135 void *lrunext; // lru next cache block
136 void *hashprev; // previous cache block for the same hash idx
137 void *hashnext; // next cache block for the same hash idx
143 // The object structure for Btree access
145 typedef struct _BtDb {
146 uint page_size; // each page size
147 uint page_bits; // each page size in bits
148 uint seg_bits; // segment size in pages in bits
149 uid page_no; // current page number
150 uid cursor_page; // current cursor page number
152 uint mode; // read-write mode
153 uint mapped_io; // use memory mapping
154 BtPage temp; // temporary frame buffer (memory mapped/file IO)
155 BtPage alloc; // frame buffer for alloc page ( page 0 )
156 BtPage cursor; // cached frame for start/next (never mapped)
157 BtPage frame; // spare frame for the page split (never mapped)
158 BtPage zero; // zeroes frame buffer (never mapped)
159 BtPage page; // current page
165 unsigned char *mem; // frame, cursor, page memory buffer
166 int nodecnt; // highest page cache segment in use
167 int nodemax; // highest page cache segment allocated
168 int hashmask; // number of pages in segments - 1
169 int hashsize; // size of hash table
170 int found; // last deletekey found key
171 int fence; // last load page used fence position
172 BtHash *lrufirst; // lru list head
173 BtHash *lrulast; // lru list tail
174 ushort *cache; // hash table for cached segments
175 BtHash nodes[1]; // segment cache follows
189 extern void bt_close (BtDb *bt);
190 extern BtDb *bt_open (char *name, uint mode, uint bits, uint cacheblk, uint pgblk);
191 extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod);
192 extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl);
193 extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
194 extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
195 extern uint bt_nextkey (BtDb *bt, uint slot);
197 // Helper functions to return slot values
199 extern BtKey bt_key (BtDb *bt, uint slot);
200 extern uid bt_uid (BtDb *bt, uint slot);
201 extern uint bt_tod (BtDb *bt, uint slot);
203 // BTree page number constants
208 // Number of levels to create in a new BTree
212 // The page is allocated from low and hi ends.
213 // The key offsets and row-id's are allocated
214 // from the bottom, while the text of the key
215 // is allocated from the top. When the two
216 // areas meet, the page is split into two.
218 // A key consists of a length byte, two bytes of
219 // index number (0 - 65534), and up to 253 bytes
220 // of key value. Duplicate keys are discarded.
221 // Associated with each key is a 48 bit row-id.
223 // The b-tree root is always located at page 1.
224 // The first leaf page of level zero is always
225 // located on page 2.
227 // The b-tree pages are linked with right
228 // pointers to facilitate enumerators,
229 // and provide for concurrency.
231 // When to root page fills, it is split in two and
232 // the tree height is raised by a new root at page
233 // one with two keys.
235 // Deleted keys are marked with a dead bit until
236 // page cleanup The fence key for a node is always
237 // present, even after deletion and cleanup.
239 // Deleted leaf pages are reclaimed on a free list.
240 // The upper levels of the btree are fixed on creation.
242 // Groups of pages from the btree are optionally
243 // cached with memory mapping. A hash table is used to keep
244 // track of the cached pages. This behaviour is controlled
245 // by the number of cache blocks parameter and pages per block
248 // To achieve maximum concurrency one page is locked at a time
249 // as the tree is traversed to find leaf key in question. The right
250 // page numbers are used in cases where the page is being split,
253 // Page 0 (ALLOC page) is dedicated to lock for new page extensions,
254 // and chains empty leaf pages together for reuse.
256 // Parent locks are obtained to prevent resplitting or deleting a node
257 // before its fence is posted into its upper level.
259 // A special open mode of BT_fl is provided to safely access files on
260 // WIN32 networks. WIN32 network operations should not use memory mapping.
261 // This WIN32 mode sets FILE_FLAG_NOBUFFERING and FILE_FLAG_WRITETHROUGH
262 // to prevent local caching of network file contents.
264 // Access macros to address slot and key values from the page.
265 // Page slots use 1 based indexing.
267 #define slotptr(page, slot) (((BtSlot *)(page+1)) + (slot-1))
268 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
270 void bt_putid(unsigned char *dest, uid id)
275 dest[i] = (unsigned char)id, id >>= 8;
278 uid bt_getid(unsigned char *src)
283 for( i = 0; i < BtId; i++ )
284 id <<= 8, id |= *src++;
289 // place write, read, or parent lock on requested page_no.
291 BTERR bt_lockpage(BtDb *bt, uid page_no, BtLock mode)
293 off64_t off = page_no << bt->page_bits;
295 int flag = PROT_READ | ( bt->mode == BT_ro ? 0 : PROT_WRITE );
296 struct flock lock[1];
302 if( mode == BtLockRead || mode == BtLockWrite )
303 off += sizeof(*bt->page); // use second segment
305 if( mode == BtLockParent )
306 off += 2 * sizeof(*bt->page); // use third segment
309 memset (lock, 0, sizeof(lock));
312 lock->l_type = (mode == BtLockDelete || mode == BtLockWrite || mode == BtLockParent) ? F_WRLCK : F_RDLCK;
313 lock->l_len = sizeof(*bt->page);
316 if( fcntl (bt->idx, F_SETLKW, lock) < 0 )
317 return bt->err = BTERR_lock;
321 memset (ovl, 0, sizeof(ovl));
322 ovl->OffsetHigh = (uint)(off >> 32);
323 ovl->Offset = (uint)off;
324 len = sizeof(*bt->page);
326 // use large offsets to
327 // simulate advisory locking
329 ovl->OffsetHigh |= 0x80000000;
331 if( mode == BtLockDelete || mode == BtLockWrite || mode == BtLockParent )
332 flags |= LOCKFILE_EXCLUSIVE_LOCK;
334 if( LockFileEx (bt->idx, flags, 0, len, 0L, ovl) )
337 return bt->err = BTERR_lock;
341 // remove write, read, or parent lock on requested page_no.
343 BTERR bt_unlockpage(BtDb *bt, uid page_no, BtLock mode)
345 off64_t off = page_no << bt->page_bits;
347 struct flock lock[1];
353 if( mode == BtLockRead || mode == BtLockWrite )
354 off += sizeof(*bt->page); // use second segment
356 if( mode == BtLockParent )
357 off += 2 * sizeof(*bt->page); // use third segment
360 memset (lock, 0, sizeof(lock));
363 lock->l_type = F_UNLCK;
364 lock->l_len = sizeof(*bt->page);
367 if( fcntl (bt->idx, F_SETLK, lock) < 0 )
368 return bt->err = BTERR_lock;
370 memset (ovl, 0, sizeof(ovl));
371 ovl->OffsetHigh = (uint)(off >> 32);
372 ovl->Offset = (uint)off;
373 len = sizeof(*bt->page);
375 // use large offsets to
376 // simulate advisory locking
378 ovl->OffsetHigh |= 0x80000000;
380 if( !UnlockFileEx (bt->idx, 0, len, 0, ovl) )
381 return GetLastError(), bt->err = BTERR_lock;
387 // close and release memory
389 void bt_close (BtDb *bt)
393 // release mapped pages
395 if( hash = bt->lrufirst )
396 do munmap (hash->page, (bt->hashmask+1) << bt->page_bits);
397 while(hash = hash->lrunext);
405 if( hash = bt->lrufirst )
408 FlushViewOfFile(hash->page, 0);
409 UnmapViewOfFile(hash->page);
410 CloseHandle(hash->hmap);
411 } while(hash = hash->lrunext);
414 VirtualFree (bt->mem, 0, MEM_RELEASE);
415 FlushFileBuffers(bt->idx);
416 CloseHandle(bt->idx);
417 GlobalFree (bt->cache);
422 // open/create new btree
423 // call with file_name, BT_openmode, bits in page size (e.g. 16),
424 // size of mapped page cache (e.g. 8192) or zero for no mapping.
426 BtDb *bt_open (char *name, uint mode, uint bits, uint nodemax, uint pgblk)
428 uint lvl, attr, cacheblk, last;
429 BtLock lockmode = BtLockWrite;
437 SYSTEM_INFO sysinfo[1];
441 bt = malloc (sizeof(BtDb) + nodemax * sizeof(BtHash));
442 memset (bt, 0, sizeof(BtDb));
444 switch (mode & 0x7fff)
448 bt->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
453 bt->idx = open ((char*)name, O_RDONLY);
454 lockmode = BtLockRead;
458 return free(bt), NULL;
461 cacheblk = 4096; // page size for unix
466 bt = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtDb) + nodemax * sizeof(BtHash));
467 attr = FILE_ATTRIBUTE_NORMAL;
468 switch (mode & 0x7fff)
471 attr |= FILE_FLAG_WRITE_THROUGH | FILE_FLAG_NO_BUFFERING;
474 bt->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
479 bt->idx = CreateFile(name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, attr, NULL);
480 lockmode = BtLockRead;
483 if( bt->idx == INVALID_HANDLE_VALUE )
484 return GlobalFree(bt), NULL;
486 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
487 GetSystemInfo(sysinfo);
490 cacheblk = sysinfo->dwAllocationGranularity;
495 // determine sanity of page size
497 if( bits > BT_maxbits )
499 else if( bits < BT_minbits )
502 if ( bt_lockpage(bt, ALLOC_page, lockmode) )
503 return bt_close (bt), NULL;
508 // read minimum page size to get root info
510 if( size = lseek (bt->idx, 0L, 2) ) {
511 alloc = malloc (BT_minpage);
512 pread(bt->idx, alloc, BT_minpage, 0);
515 } else if( mode == BT_ro )
516 return bt_close (bt), NULL;
518 size = GetFileSize(bt->idx, amt);
521 alloc = VirtualAlloc(NULL, BT_minpage, MEM_COMMIT, PAGE_READWRITE);
522 if( !ReadFile(bt->idx, (char *)alloc, BT_minpage, amt, NULL) )
523 return bt_close (bt), NULL;
525 VirtualFree (alloc, 0, MEM_RELEASE);
526 } else if( mode == BT_ro )
527 return bt_close (bt), NULL;
530 bt->page_size = 1 << bits;
531 bt->page_bits = bits;
533 bt->nodemax = nodemax;
536 // setup cache mapping
539 if( cacheblk < bt->page_size )
540 cacheblk = bt->page_size;
542 bt->hashsize = nodemax / 8;
543 bt->hashmask = (cacheblk >> bits) - 1;
547 // requested number of pages per memmap segment
550 if( (1 << pgblk) > bt->hashmask )
551 bt->hashmask = (1 << pgblk) - 1;
555 while( (1 << bt->seg_bits) <= bt->hashmask )
559 bt->mem = malloc (6 *bt->page_size);
560 bt->cache = calloc (bt->hashsize, sizeof(ushort));
562 bt->mem = VirtualAlloc(NULL, 6 * bt->page_size, MEM_COMMIT, PAGE_READWRITE);
563 bt->cache = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, bt->hashsize * sizeof(ushort));
565 bt->frame = (BtPage)bt->mem;
566 bt->cursor = (BtPage)(bt->mem + bt->page_size);
567 bt->page = (BtPage)(bt->mem + 2 * bt->page_size);
568 bt->alloc = (BtPage)(bt->mem + 3 * bt->page_size);
569 bt->temp = (BtPage)(bt->mem + 4 * bt->page_size);
570 bt->zero = (BtPage)(bt->mem + 5 * bt->page_size);
573 if ( bt_unlockpage(bt, ALLOC_page, lockmode) )
574 return bt_close (bt), NULL;
579 // initializes an empty b-tree with root page and page of leaves
581 memset (bt->alloc, 0, bt->page_size);
582 bt_putid(bt->alloc->right, MIN_lvl+1);
583 bt->alloc->bits = bt->page_bits;
586 if( write (bt->idx, bt->alloc, bt->page_size) < bt->page_size )
587 return bt_close (bt), NULL;
589 if( !WriteFile (bt->idx, (char *)bt->alloc, bt->page_size, amt, NULL) )
590 return bt_close (bt), NULL;
592 if( *amt < bt->page_size )
593 return bt_close (bt), NULL;
596 memset (bt->frame, 0, bt->page_size);
597 bt->frame->bits = bt->page_bits;
599 for( lvl=MIN_lvl; lvl--; ) {
600 slotptr(bt->frame, 1)->off = bt->page_size - 3;
601 bt_putid(slotptr(bt->frame, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
602 key = keyptr(bt->frame, 1);
603 key->len = 2; // create stopper key
606 bt->frame->min = bt->page_size - 3;
607 bt->frame->lvl = lvl;
611 if( write (bt->idx, bt->frame, bt->page_size) < bt->page_size )
612 return bt_close (bt), NULL;
614 if( !WriteFile (bt->idx, (char *)bt->frame, bt->page_size, amt, NULL) )
615 return bt_close (bt), NULL;
617 if( *amt < bt->page_size )
618 return bt_close (bt), NULL;
622 // create empty page area by writing last page of first
623 // cache area (other pages are zeroed by O/S)
625 if( bt->mapped_io && bt->hashmask ) {
626 memset(bt->frame, 0, bt->page_size);
629 while( last < MIN_lvl + 1 )
630 last += bt->hashmask + 1;
632 pwrite(bt->idx, bt->frame, bt->page_size, last << bt->page_bits);
634 SetFilePointer (bt->idx, last << bt->page_bits, NULL, FILE_BEGIN);
635 if( !WriteFile (bt->idx, (char *)bt->frame, bt->page_size, amt, NULL) )
636 return bt_close (bt), NULL;
637 if( *amt < bt->page_size )
638 return bt_close (bt), NULL;
642 if( bt_unlockpage(bt, ALLOC_page, lockmode) )
643 return bt_close (bt), NULL;
648 // compare two keys, returning > 0, = 0, or < 0
649 // as the comparison value
651 int keycmp (BtKey key1, unsigned char *key2, uint len2)
653 uint len1 = key1->len;
656 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
667 // Update current page of btree by writing file contents
668 // or flushing mapped area to disk.
670 BTERR bt_update (BtDb *bt, BtPage page, uid page_no)
672 off64_t off = page_no << bt->page_bits;
675 if ( !bt->mapped_io )
676 if ( pwrite(bt->idx, page, bt->page_size, off) != bt->page_size )
677 return bt->err = BTERR_wrt;
680 if ( !bt->mapped_io )
682 SetFilePointer (bt->idx, (long)off, (long*)(&off)+1, FILE_BEGIN);
683 if( !WriteFile (bt->idx, (char *)page, bt->page_size, amt, NULL) )
684 return GetLastError(), bt->err = BTERR_wrt;
686 if( *amt < bt->page_size )
687 return GetLastError(), bt->err = BTERR_wrt;
689 else if ( bt->mode == BT_fl ) {
690 FlushViewOfFile(page, bt->page_size);
691 FlushFileBuffers(bt->idx);
697 // find page in cache
699 BtHash *bt_findhash(BtDb *bt, uid page_no)
704 // compute cache block first page and hash idx
706 page_no &= ~bt->hashmask;
707 idx = (uint)(page_no >> bt->seg_bits) % bt->hashsize;
710 hash = bt->nodes + bt->cache[idx];
714 do if( hash->page_no == page_no )
716 while(hash = hash->hashnext );
721 // add page cache entry to hash index
723 void bt_linkhash(BtDb *bt, BtHash *node, uid page_no)
725 uint idx = (uint)(page_no >> bt->seg_bits) % bt->hashsize;
728 if( bt->cache[idx] ) {
729 node->hashnext = hash = bt->nodes + bt->cache[idx];
730 hash->hashprev = node;
733 node->hashprev = NULL;
734 bt->cache[idx] = (ushort)(node - bt->nodes);
737 // remove cache entry from hash table
739 void bt_unlinkhash(BtDb *bt, BtHash *node)
741 uint idx = (uint)(node->page_no >> bt->seg_bits) % bt->hashsize;
745 if( hash = node->hashprev )
746 hash->hashnext = node->hashnext;
747 else if( hash = node->hashnext )
748 bt->cache[idx] = (ushort)(hash - bt->nodes);
752 if( hash = node->hashnext )
753 hash->hashprev = node->hashprev;
756 // add cache page to lru chain and map pages
758 BtPage bt_linklru(BtDb *bt, BtHash *hash, uid page_no)
761 off64_t off = (page_no & ~bt->hashmask) << bt->page_bits;
762 off64_t limit = off + ((bt->hashmask+1) << bt->page_bits);
765 memset(hash, 0, sizeof(BtHash));
766 hash->page_no = (page_no & ~bt->hashmask);
767 bt_linkhash(bt, hash, page_no);
769 if( node = hash->lrunext = bt->lrufirst )
770 node->lruprev = hash;
777 flag = PROT_READ | ( bt->mode == BT_ro ? 0 : PROT_WRITE );
778 hash->page = (BtPage)mmap (0, (bt->hashmask+1) << bt->page_bits, flag, MAP_SHARED, bt->idx, off);
779 if( hash->page == MAP_FAILED )
780 return bt->err = BTERR_map, (BtPage)NULL;
783 flag = ( bt->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
784 hash->hmap = CreateFileMapping(bt->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
786 return bt->err = BTERR_map, NULL;
788 flag = ( bt->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
789 hash->page = MapViewOfFile(hash->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->hashmask+1) << bt->page_bits);
791 return bt->err = BTERR_map, NULL;
794 return (BtPage)((char*)hash->page + ((uint)(page_no & bt->hashmask) << bt->page_bits));
797 // find or place requested page in page-cache
798 // return memory address where page is located.
800 BtPage bt_hashpage(BtDb *bt, uid page_no)
802 BtHash *hash, *node, *next;
805 // find page in cache and move to top of lru list
807 if( hash = bt_findhash(bt, page_no) ) {
808 page = (BtPage)((char*)hash->page + ((uint)(page_no & bt->hashmask) << bt->page_bits));
809 // swap node in lru list
810 if( node = hash->lruprev ) {
811 if( next = node->lrunext = hash->lrunext )
812 next->lruprev = node;
816 if( next = hash->lrunext = bt->lrufirst )
817 next->lruprev = hash;
819 return bt->err = BTERR_hash, (BtPage)NULL;
821 hash->lruprev = NULL;
827 // map pages and add to cache entry
829 if( bt->nodecnt < bt->nodemax ) {
830 hash = bt->nodes + ++bt->nodecnt;
831 return bt_linklru(bt, hash, page_no);
834 // hash table is already full, replace last lru entry from the cache
836 if( hash = bt->lrulast ) {
837 // unlink from lru list
838 if( node = bt->lrulast = hash->lruprev )
839 node->lrunext = NULL;
841 return bt->err = BTERR_hash, (BtPage)NULL;
844 munmap (hash->page, (bt->hashmask+1) << bt->page_bits);
846 FlushViewOfFile(hash->page, 0);
847 UnmapViewOfFile(hash->page);
848 CloseHandle(hash->hmap);
850 // unlink from hash table
852 bt_unlinkhash(bt, hash);
854 // map and add to cache
856 return bt_linklru(bt, hash, page_no);
859 return bt->err = BTERR_hash, (BtPage)NULL;
862 // map a btree page onto current page
864 BTERR bt_mappage (BtDb *bt, BtPage *page, uid page_no)
866 off64_t off = page_no << bt->page_bits;
871 if( bt->mapped_io ) {
873 *page = bt_hashpage(bt, page_no);
877 if ( pread(bt->idx, *page, bt->page_size, off) < bt->page_size )
878 return bt->err = BTERR_map;
880 SetFilePointer (bt->idx, (long)off, (long*)(&off)+1, FILE_BEGIN);
882 if( !ReadFile(bt->idx, *page, bt->page_size, amt, NULL) )
883 return bt->err = BTERR_map;
885 if( *amt < bt->page_size )
886 return bt->err = BTERR_map;
891 // deallocate a deleted page
892 // place on free chain out of allocator page
894 BTERR bt_freepage(BtDb *bt, uid page_no)
896 // obtain delete lock on deleted node
898 if( bt_lockpage(bt, page_no, BtLockDelete) )
901 // obtain write lock on deleted node
903 if( bt_lockpage(bt, page_no, BtLockWrite) )
906 if( bt_mappage (bt, &bt->temp, page_no) )
909 // lock allocation page
911 if ( bt_lockpage(bt, ALLOC_page, BtLockWrite) )
914 if( bt_mappage (bt, &bt->alloc, ALLOC_page) )
917 // store chain in second right
918 bt_putid(bt->temp->right, bt_getid(bt->alloc[1].right));
919 bt_putid(bt->alloc[1].right, page_no);
922 if( bt_update(bt, bt->alloc, ALLOC_page) )
924 if( bt_update(bt, bt->temp, page_no) )
929 if( bt_unlockpage(bt, ALLOC_page, BtLockWrite) )
932 // remove write lock on deleted node
934 if( bt_unlockpage(bt, page_no, BtLockWrite) )
937 // remove delete lock on deleted node
939 if( bt_unlockpage(bt, page_no, BtLockDelete) )
945 // allocate a new page and write page into it
947 uid bt_newpage(BtDb *bt, BtPage page)
955 if ( bt_lockpage(bt, ALLOC_page, BtLockWrite) )
958 if( bt_mappage (bt, &bt->alloc, ALLOC_page) )
961 // use empty chain first
962 // else allocate empty page
964 if( new_page = bt_getid(bt->alloc[1].right) ) {
965 if( bt_mappage (bt, &bt->temp, new_page) )
966 return 0; // don't unlock on error
967 bt_putid(bt->alloc[1].right, bt_getid(bt->temp->right));
970 new_page = bt_getid(bt->alloc->right);
971 bt_putid(bt->alloc->right, new_page+1);
975 if( bt_update(bt, bt->alloc, ALLOC_page) )
976 return 0; // don't unlock on error
978 if( !bt->mapped_io ) {
979 if( bt_update(bt, page, new_page) )
980 return 0; //don't unlock on error
984 if ( bt_unlockpage(bt, ALLOC_page, BtLockWrite) )
991 if ( pwrite(bt->idx, page, bt->page_size, new_page << bt->page_bits) < bt->page_size )
992 return bt->err = BTERR_wrt, 0;
994 // if writing first page of hash block, zero last page in the block
996 if ( !reuse && bt->hashmask > 0 && (new_page & bt->hashmask) == 0 )
998 // use temp buffer to write zeros
999 memset(bt->zero, 0, bt->page_size);
1000 if ( pwrite(bt->idx,bt->zero, bt->page_size, (new_page | bt->hashmask) << bt->page_bits) < bt->page_size )
1001 return bt->err = BTERR_wrt, 0;
1004 // bring new page into page-cache and copy page.
1005 // this will extend the file into the new pages.
1007 if( !(pmap = (char*)bt_hashpage(bt, new_page & ~bt->hashmask)) )
1010 memcpy(pmap+((new_page & bt->hashmask) << bt->page_bits), page, bt->page_size);
1015 if ( bt_unlockpage(bt, ALLOC_page, BtLockWrite) )
1021 // find slot in page for given key at a given level
1023 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1025 uint diff, higher = bt->page->cnt, low = 1, slot;
1028 // make stopper key an infinite fence value
1030 if( bt_getid (bt->page->right) )
1035 // low is the next candidate, higher is already
1036 // tested as .ge. the given key, loop ends when they meet
1038 while( diff = higher - low ) {
1039 slot = low + ( diff >> 1 );
1040 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1043 higher = slot, good++;
1046 // return zero if key is on right link page
1048 return good ? higher : 0;
1051 // find and load page at given level for given key
1052 // leave page rd or wr locked as requested
1054 int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, uint lock)
1056 uid page_no = ROOT_page, prevpage = 0;
1057 uint drill = 0xff, slot;
1058 uint mode, prevmode;
1060 // start at root of btree and drill down
1063 // determine lock mode of drill level
1064 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1066 bt->page_no = page_no;
1068 // obtain access lock using lock chaining
1070 if( page_no > ROOT_page )
1071 if( bt_lockpage(bt, bt->page_no, BtLockAccess) )
1075 if( bt_unlockpage(bt, prevpage, prevmode) )
1078 // obtain read lock using lock chaining
1080 if( bt_lockpage(bt, bt->page_no, mode) )
1083 if( page_no > ROOT_page )
1084 if( bt_unlockpage(bt, bt->page_no, BtLockAccess) )
1087 // map/obtain page contents
1089 if( bt_mappage (bt, &bt->page, page_no) )
1092 // re-read and re-lock root after determining actual level of root
1094 if( bt->page->lvl != drill) {
1095 if ( bt->page_no != ROOT_page )
1096 return bt->err = BTERR_struct, 0;
1098 drill = bt->page->lvl;
1100 if( lock == BtLockWrite && drill == lvl )
1101 if( bt_unlockpage(bt, page_no, mode) )
1107 prevpage = bt->page_no;
1110 // find key on page at this level
1111 // and descend to requested level
1113 if( slot = bt_findslot (bt, key, len) ) {
1117 while( slotptr(bt->page, slot)->dead )
1118 if( slot++ < bt->page->cnt )
1123 // if the page has no active slots,
1124 // move right otherwise drill down
1126 if( slot <= bt->page->cnt ) {
1127 page_no = bt_getid(slotptr(bt->page, slot)->id);
1128 bt->fence = slot == bt->page->cnt;
1134 // or slide right into next page
1136 page_no = bt_getid(bt->page->right);
1140 // return error on end of right chain
1142 bt->err = BTERR_struct;
1143 return 0; // return error
1146 // find and delete key on page by marking delete flag bit
1147 // when page becomes empty, delete it
1149 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl)
1151 unsigned char lowerkey[256], higherkey[256];
1152 uint slot, tod, dirty = 0;
1156 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1157 ptr = keyptr(bt->page, slot);
1161 // if key is found delete it, otherwise ignore request
1163 if( !keycmp (ptr, key, len) )
1164 if( slotptr(bt->page, slot)->dead == 0 ) {
1165 dirty = slotptr(bt->page,slot)->dead = 1;
1166 if( slot < bt->page->cnt )
1167 bt->page->dirty = 1;
1171 // return if page is not empty, or
1172 // if non-leaf level or fence key
1174 right = bt_getid(bt->page->right);
1175 page_no = bt->page_no;
1177 if( lvl || bt->page->act || bt->fence )
1178 if ( dirty && bt_update(bt, bt->page, page_no) )
1181 return bt_unlockpage(bt, page_no, BtLockWrite);
1183 // obtain Parent lock over write lock
1185 if( bt_lockpage(bt, page_no, BtLockParent) )
1188 // cache copy of fence key
1189 // in order to find parent
1191 ptr = keyptr(bt->page, bt->page->cnt);
1192 memcpy(lowerkey, ptr, ptr->len + 1);
1194 // lock and map right page
1196 if ( bt_lockpage(bt, right, BtLockWrite) )
1199 if( bt_mappage (bt, &bt->temp, right) )
1202 // pull contents of next page into current empty page
1204 memcpy (bt->page, bt->temp, bt->page_size);
1206 // cache copy of key to update
1208 ptr = keyptr(bt->temp, bt->temp->cnt);
1209 memcpy(higherkey, ptr, ptr->len + 1);
1211 // Mark right page as deleted and point it to left page
1212 // until we can post updates at higher level.
1214 bt_putid(bt->temp->right, page_no);
1217 if( bt_update(bt, bt->page, page_no) )
1220 if( bt_update(bt, bt->temp, right) )
1223 if( bt_unlockpage(bt, right, BtLockWrite) )
1226 if( bt_unlockpage(bt, page_no, BtLockWrite) )
1229 // delete old lower key to consolidated node
1231 if( bt_deletekey (bt, lowerkey + 1, *lowerkey, lvl + 1) )
1234 // redirect higher key directly to consolidated node
1236 tod = (uint)time(NULL);
1238 if( bt_insertkey (bt, higherkey+1, *higherkey, lvl + 1, page_no, tod) )
1241 // obtain write lock and
1242 // add right block to free chain
1244 if( bt_freepage (bt, right) )
1247 // remove ParentModify lock
1249 if( bt_unlockpage(bt, page_no, BtLockParent) )
1255 // find key in leaf level and return row-id
1257 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1263 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1264 ptr = keyptr(bt->page, slot);
1268 // if key exists, return row-id
1269 // otherwise return 0
1271 if( ptr->len == len && !memcmp (ptr->key, key, len) )
1272 id = bt_getid(slotptr(bt->page,slot)->id);
1276 if ( bt_unlockpage(bt, bt->page_no, BtLockRead) )
1282 // check page for space available,
1283 // clean if necessary and return
1284 // 0 - page needs splitting
1285 // >0 - go ahead with new slot
1287 uint bt_cleanpage(BtDb *bt, uint amt, uint slot)
1289 uint nxt = bt->page_size;
1290 BtPage page = bt->page;
1291 uint cnt = 0, idx = 0;
1292 uint max = page->cnt;
1293 uint newslot = slot;
1297 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1300 // skip cleanup if nothing to reclaim
1305 memcpy (bt->frame, page, bt->page_size);
1307 // skip page info and set rest of page to zero
1309 memset (page+1, 0, bt->page_size - sizeof(*page));
1312 while( cnt++ < max ) {
1315 // always leave fence key in list
1316 if( cnt < max && slotptr(bt->frame,cnt)->dead )
1320 key = keyptr(bt->frame, cnt);
1321 nxt -= key->len + 1;
1322 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1325 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1326 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1328 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1329 slotptr(page, idx)->off = nxt;
1335 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1341 // split the root and raise the height of the btree
1343 BTERR bt_splitroot(BtDb *bt, unsigned char *newkey, unsigned char *oldkey, uid page_no2)
1345 uint nxt = bt->page_size;
1346 BtPage root = bt->page;
1349 // Obtain an empty page to use, and copy the current
1350 // root contents into it
1352 if( !(new_page = bt_newpage(bt, root)) )
1355 // preserve the page info at the bottom
1356 // and set rest to zero
1358 memset(root+1, 0, bt->page_size - sizeof(*root));
1360 // insert first key on newroot page
1363 memcpy ((unsigned char *)root + nxt, newkey, *newkey + 1);
1364 bt_putid(slotptr(root, 1)->id, new_page);
1365 slotptr(root, 1)->off = nxt;
1367 // insert second key on newroot page
1368 // and increase the root height
1371 memcpy ((unsigned char *)root + nxt, oldkey, *oldkey + 1);
1372 bt_putid(slotptr(root, 2)->id, page_no2);
1373 slotptr(root, 2)->off = nxt;
1375 bt_putid(root->right, 0);
1376 root->min = nxt; // reset lowest used offset and key count
1381 // update and release root (bt->page)
1383 if( bt_update(bt, root, bt->page_no) )
1386 return bt_unlockpage(bt, bt->page_no, BtLockWrite);
1389 // split already locked full node
1392 BTERR bt_splitpage (BtDb *bt)
1394 uint cnt = 0, idx = 0, max, nxt = bt->page_size;
1395 unsigned char oldkey[256], lowerkey[256];
1396 uid page_no = bt->page_no, right;
1397 BtPage page = bt->page;
1398 uint lvl = page->lvl;
1403 // split higher half of keys to bt->frame
1404 // the last key (fence key) might be dead
1406 tod = (uint)time(NULL);
1408 memset (bt->frame, 0, bt->page_size);
1409 max = (int)page->cnt;
1413 while( cnt++ < max ) {
1414 key = keyptr(page, cnt);
1415 nxt -= key->len + 1;
1416 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
1417 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
1418 if( !(slotptr(bt->frame, idx)->dead = slotptr(page, cnt)->dead) )
1420 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
1421 slotptr(bt->frame, idx)->off = nxt;
1424 // remember existing fence key for new page to the right
1426 memcpy (oldkey, key, key->len + 1);
1428 bt->frame->bits = bt->page_bits;
1429 bt->frame->min = nxt;
1430 bt->frame->cnt = idx;
1431 bt->frame->lvl = lvl;
1435 if( page_no > ROOT_page ) {
1436 right = bt_getid (page->right);
1437 bt_putid(bt->frame->right, right);
1440 // get new free page and write frame to it.
1442 if( !(new_page = bt_newpage(bt, bt->frame)) )
1445 // update lower keys to continue in old page
1447 memcpy (bt->frame, page, bt->page_size);
1448 memset (page+1, 0, bt->page_size - sizeof(*page));
1449 nxt = bt->page_size;
1454 // assemble page of smaller keys
1455 // (they're all active keys)
1457 while( cnt++ < max / 2 ) {
1458 key = keyptr(bt->frame, cnt);
1459 nxt -= key->len + 1;
1460 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1461 memcpy(slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1462 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1463 slotptr(page, idx)->off = nxt;
1467 // remember fence key for old page
1469 memcpy(lowerkey, key, key->len + 1);
1470 bt_putid(page->right, new_page);
1474 // if current page is the root page, split it
1476 if( page_no == ROOT_page )
1477 return bt_splitroot (bt, lowerkey, oldkey, new_page);
1479 // update left (containing) node
1481 if( bt_update(bt, page, page_no) )
1484 // obtain Parent/Write locks
1485 // for left and right node pages
1487 if( bt_lockpage (bt, new_page, BtLockParent) )
1490 if( bt_lockpage (bt, page_no, BtLockParent) )
1493 // release wr lock on left page
1495 if( bt_unlockpage (bt, page_no, BtLockWrite) )
1498 // insert new fence for reformulated left block
1500 if( bt_insertkey (bt, lowerkey+1, *lowerkey, lvl + 1, page_no, tod) )
1503 // fix old fence for newly allocated right block page
1505 if( bt_insertkey (bt, oldkey+1, *oldkey, lvl + 1, new_page, tod) )
1508 // release Parent & Write locks
1510 if( bt_unlockpage (bt, new_page, BtLockParent) )
1513 if( bt_unlockpage (bt, page_no, BtLockParent) )
1519 // Insert new key into the btree at requested level.
1520 // Level zero pages are leaf pages and are unlocked at exit.
1521 // Interior nodes remain locked.
1523 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod)
1530 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1531 ptr = keyptr(bt->page, slot);
1535 bt->err = BTERR_ovflw;
1539 // if key already exists, update id and return
1543 if( !keycmp (ptr, key, len) ) {
1544 slotptr(page, slot)->dead = 0;
1545 slotptr(page, slot)->tod = tod;
1546 bt_putid(slotptr(page,slot)->id, id);
1547 if ( bt_update(bt, bt->page, bt->page_no) )
1549 return bt_unlockpage(bt, bt->page_no, BtLockWrite);
1552 // check if page has enough space
1554 if( slot = bt_cleanpage (bt, len, slot) )
1557 if( bt_splitpage (bt) )
1561 // calculate next available slot and copy key into page
1563 page->min -= len + 1; // reset lowest used offset
1564 ((unsigned char *)page)[page->min] = len;
1565 memcpy ((unsigned char *)page + page->min +1, key, len );
1567 for( idx = slot; idx < page->cnt; idx++ )
1568 if( slotptr(page, idx)->dead )
1571 // now insert key into array before slot
1572 // preserving the fence slot
1574 if( idx == page->cnt )
1580 *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
1582 bt_putid(slotptr(page,slot)->id, id);
1583 slotptr(page, slot)->off = page->min;
1584 slotptr(page, slot)->tod = tod;
1585 slotptr(page, slot)->dead = 0;
1587 if ( bt_update(bt, bt->page, bt->page_no) )
1590 return bt_unlockpage(bt, bt->page_no, BtLockWrite);
1593 // cache page of keys into cursor and return starting slot for given key
1595 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
1599 // cache page for retrieval
1600 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1601 memcpy (bt->cursor, bt->page, bt->page_size);
1602 bt->cursor_page = bt->page_no;
1603 if ( bt_unlockpage(bt, bt->page_no, BtLockRead) )
1609 // return next slot for cursor page
1610 // or slide cursor right into next page
1612 uint bt_nextkey (BtDb *bt, uint slot)
1617 right = bt_getid(bt->cursor->right);
1618 while( slot++ < bt->cursor->cnt )
1619 if( slotptr(bt->cursor,slot)->dead )
1621 else if( right || (slot < bt->cursor->cnt))
1629 bt->cursor_page = right;
1631 if( bt_lockpage(bt, right,BtLockRead) )
1634 if( bt_mappage (bt, &bt->page, right) )
1637 memcpy (bt->cursor, bt->page, bt->page_size);
1638 if ( bt_unlockpage(bt, right, BtLockRead) )
1647 BtKey bt_key(BtDb *bt, uint slot)
1649 return keyptr(bt->cursor, slot);
1652 uid bt_uid(BtDb *bt, uint slot)
1654 return bt_getid(slotptr(bt->cursor,slot)->id);
1657 uint bt_tod(BtDb *bt, uint slot)
1659 return slotptr(bt->cursor,slot)->tod;
1664 // standalone program to index file of keys
1665 // then list them onto std-out
1667 int main (int argc, char **argv)
1669 uint slot, line = 0, off = 0, found = 0;
1670 int dead, ch, cnt = 0, bits = 12;
1671 unsigned char key[256];
1672 clock_t done, start;
1683 fprintf (stderr, "Usage: %s idx_file src_file Read/Write/Scan/Delete/Find [page_bits mapped_pool_segments pages_per_segment start_line_number]\n", argv[0]);
1684 fprintf (stderr, " page_bits: size of btree page in bits\n");
1685 fprintf (stderr, " mapped_pool_segments: size of buffer pool in segments\n");
1686 fprintf (stderr, " pages_per_segment: size of buffer pool segment in pages in bits\n");
1694 bits = atoi(argv[4]);
1697 map = atoi(argv[5]);
1700 fprintf (stderr, "Warning: buffer_pool > 65536 segments\n");
1702 if( map && map < 8 )
1703 fprintf (stderr, "Buffer_pool too small\n");
1706 pgblk = atoi(argv[6]);
1708 if( bits + pgblk > 30 )
1709 fprintf (stderr, "Warning: very large buffer pool segment size\n");
1712 off = atoi(argv[7]);
1714 bt = bt_open ((argv[1]), BT_rw, bits, map, pgblk);
1717 fprintf(stderr, "Index Open Error %s\n", argv[1]);
1721 switch(argv[3][0]| 0x20)
1724 fprintf(stderr, "started indexing for %s\n", argv[2]);
1725 if( argc > 2 && (in = fopen (argv[2], "rb")) )
1726 while( ch = getc(in), ch != EOF )
1730 sprintf((char *)key+len, "%.9d", line + off), len += 9;
1732 if( bt_insertkey (bt, key, len, 0, ++line, *tod) )
1733 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
1736 else if( len < 245 )
1738 fprintf(stderr, "finished adding keys, %d \n", line);
1742 fprintf(stderr, "started deleting keys for %s\n", argv[2]);
1743 if( argc > 2 && (in = fopen (argv[2], "rb")) )
1744 while( ch = getc(in), ch != EOF )
1748 sprintf((char *)key+len, "%.9d", line + off), len += 9;
1750 if( bt_deletekey (bt, key, len, 0) )
1751 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
1754 else if( len < 245 )
1756 fprintf(stderr, "finished deleting keys, %d \n", line);
1760 fprintf(stderr, "started finding keys for %s\n", argv[2]);
1761 if( argc > 2 && (in = fopen (argv[2], "rb")) )
1762 while( ch = getc(in), ch != EOF )
1766 sprintf((char *)key+len, "%.9d", line + off), len += 9;
1768 if( bt_findkey (bt, key, len) )
1771 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
1774 else if( len < 245 )
1776 fprintf(stderr, "finished search of %d keys, found %d\n", line, found);
1786 fprintf(stderr, " Time to complete: %.2f seconds\n", (float)(done - start) / CLOCKS_PER_SEC);
1791 fprintf(stderr, "started reading\n");
1793 if( slot = bt_startkey (bt, key, len) )
1796 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
1798 while( slot = bt_nextkey (bt, slot) )
1800 ptr = bt_key(bt, slot);
1801 fwrite (ptr->key, ptr->len, 1, stdout);
1802 fputc ('\n', stdout);
1805 fprintf(stderr, " Total keys read %d\n", cnt);