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
51 typedef unsigned long long uid;
54 typedef unsigned long long off64_t;
55 typedef unsigned short ushort;
56 typedef unsigned int uint;
59 #define BT_ro 0x6f72 // ro
60 #define BT_rw 0x7772 // rw
61 #define BT_fl 0x6c66 // fl
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
68 There are five lock types for each node in three independent sets:
69 1. (set 1) AccessIntent: Sharable. Going to Read the node. Incompatible with NodeDelete.
70 2. (set 1) NodeDelete: Exclusive. About to release the node. Incompatible with AccessIntent.
71 3. (set 2) ReadLock: Sharable. Read the node. Incompatible with WriteLock.
72 4. (set 2) WriteLock: Exclusive. Modify the node. Incompatible with ReadLock and other WriteLocks.
73 5. (set 3) ParentModification: Exclusive. Change the node's parent keys. Incompatible with another ParentModification.
84 // Define the length of the page and key pointers
88 // Page key slot definition.
90 // If BT_maxbits is 15 or less, you can save 2 bytes
91 // for each key stored by making the first two uints
92 // into ushorts. You can also save 4 bytes by removing
93 // the tod field from the key.
95 // Keys are marked dead, but remain on the page until
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.
118 typedef struct BtPage_ {
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:4; // level of page
125 unsigned char kill:1; // page is empty
126 unsigned char dirty:1; // page is dirty
127 unsigned char posted:1; // page fence is posted
128 unsigned char goright:1; // continue to right link
129 unsigned char right[BtId]; // page number to right
130 unsigned char fence[256]; // page fence key
133 // The loadpage interface object
140 // The memory mapping hash table entry
143 BtPage page; // mapped page pointer
144 uid page_no; // mapped page number
145 void *lruprev; // least recently used previous cache block
146 void *lrunext; // lru next cache block
147 void *hashprev; // previous cache block for the same hash idx
148 void *hashnext; // next cache block for the same hash idx
154 // The object structure for Btree access
156 typedef struct _BtDb {
157 uint page_size; // each page size
158 uint page_bits; // each page size in bits
159 uint seg_bits; // segment size in pages in bits
160 uid page_no; // current page number
161 uid cursor_page; // current cursor page number
163 uint mode; // read-write mode
164 uint mapped_io; // use memory mapping
165 BtPage temp; // temporary frame buffer (memory mapped/file IO)
166 BtPage temp2; // temporary frame buffer (memory mapped/file IO)
167 BtPage parent; // current page's parent node (memory mapped/file IO)
168 BtPage alloc; // frame for alloc page (memory mapped/file IO)
169 BtPage cursor; // cached frame for start/next (never mapped)
170 BtPage frame; // spare frame for the page split (never mapped)
171 BtPage zero; // zeroes frame buffer (never mapped)
172 BtPage page; // temporary page (memory mapped/file IO)
178 unsigned char *mem; // frame, cursor, page memory buffer
179 int nodecnt; // highest page cache segment in use
180 int nodemax; // highest page cache segment allocated
181 int hashmask; // number of pages in segments - 1
182 int hashsize; // size of hash table
183 int posted; // last loadpage found posted key
184 int found; // last insert/delete found key
185 BtHash *lrufirst; // lru list head
186 BtHash *lrulast; // lru list tail
187 ushort *cache; // hash table for cached segments
188 BtHash nodes[1]; // segment cache follows
202 extern void bt_close (BtDb *bt);
203 extern BtDb *bt_open (char *name, uint mode, uint bits, uint cacheblk, uint pgblk);
204 extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod);
205 extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len);
206 extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
207 extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
208 extern uint bt_nextkey (BtDb *bt, uint slot);
210 // Internal functions
212 BTERR bt_removepage (BtDb *bt, uid page_no, uint lvl, unsigned char *pagefence);
214 // Helper functions to return slot values
216 extern BtKey bt_key (BtDb *bt, uint slot);
217 extern uid bt_uid (BtDb *bt, uint slot);
218 extern uint bt_tod (BtDb *bt, uint slot);
220 // BTree page number constants
225 // Number of levels to create in a new BTree
229 // The page is allocated from low and hi ends.
230 // The key offsets and row-id's are allocated
231 // from the bottom, while the text of the key
232 // is allocated from the top. When the two
233 // areas meet, the page is split into two.
235 // A key consists of a length byte, two bytes of
236 // index number (0 - 65534), and up to 253 bytes
237 // of key value. Duplicate keys are discarded.
238 // Associated with each key is a 48 bit row-id.
240 // The b-tree root is always located at page 1.
241 // The first leaf page of level zero is always
242 // located on page 2.
244 // The b-tree pages are linked with right
245 // pointers to facilitate enumerators,
246 // and provide for concurrency.
248 // When to root page fills, it is split in two and
249 // the tree height is raised by a new root at page
250 // one with two keys.
252 // Deleted keys are marked with a dead bit until
255 // Groups of pages from the btree are optionally
256 // cached with memory mapping. A hash table is used to keep
257 // track of the cached pages. This behaviour is controlled
258 // by the number of cache blocks parameter and pages per block
261 // To achieve maximum concurrency one page is locked at a time
262 // as the tree is traversed to find leaf key in question. The right
263 // page numbers are used in cases where the page is being split,
266 // Page 0 is dedicated to lock for new page extensions,
267 // and chains empty pages together for reuse.
269 // Parent locks are obtained to prevent resplitting or deleting a node
270 // before its fence is posted into its upper level.
272 // Empty nodes are chained together through the ALLOC page and reused.
274 // A special open mode of BT_fl is provided to safely access files on
275 // WIN32 networks. WIN32 network operations should not use memory mapping.
276 // This WIN32 mode sets FILE_FLAG_NOBUFFERING and FILE_FLAG_WRITETHROUGH
277 // to prevent local caching of network file contents.
279 // Access macros to address slot and key values from the page.
280 // Page slots use 1 based indexing.
282 #define slotptr(page, slot) (((BtSlot *)(page+1)) + (slot-1))
283 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
285 void bt_putid(unsigned char *dest, uid id)
290 dest[i] = (unsigned char)id, id >>= 8;
293 uid bt_getid(unsigned char *src)
298 for( i = 0; i < BtId; i++ )
299 id <<= 8, id |= *src++;
304 // place write, read, or parent lock on requested page_no.
306 BTERR bt_lockpage(BtDb *bt, uid page_no, BtLock mode)
308 off64_t off = page_no << bt->page_bits;
310 int flag = PROT_READ | ( bt->mode == BT_ro ? 0 : PROT_WRITE );
311 struct flock lock[1];
317 if( mode == BtLockRead || mode == BtLockWrite )
318 off += 1 * sizeof(*bt->page); // use second segment
320 if( mode == BtLockParent )
321 off += 2 * sizeof(*bt->page); // use third segment
324 memset (lock, 0, sizeof(lock));
327 lock->l_type = (mode == BtLockDelete || mode == BtLockWrite || mode == BtLockParent) ? F_WRLCK : F_RDLCK;
328 lock->l_len = sizeof(*bt->page);
331 if( fcntl (bt->idx, F_SETLKW, lock) < 0 )
332 return bt->err = BTERR_lock;
336 memset (ovl, 0, sizeof(ovl));
337 ovl->OffsetHigh = (uint)(off >> 32);
338 ovl->Offset = (uint)off;
339 len = sizeof(*bt->page);
341 // use large offsets to
342 // simulate advisory locking
344 ovl->OffsetHigh |= 0x80000000;
346 if( mode == BtLockDelete || mode == BtLockWrite || mode == BtLockParent )
347 flags |= LOCKFILE_EXCLUSIVE_LOCK;
349 if( LockFileEx (bt->idx, flags, 0, len, 0L, ovl) )
352 return bt->err = BTERR_lock;
356 // remove write, read, or parent lock on requested page_no.
358 BTERR bt_unlockpage(BtDb *bt, uid page_no, BtLock mode)
360 off64_t off = page_no << bt->page_bits;
362 struct flock lock[1];
368 if( mode == BtLockRead || mode == BtLockWrite )
369 off += 1 * sizeof(*bt->page); // use second segment
371 if( mode == BtLockParent )
372 off += 2 * sizeof(*bt->page); // use third segment
375 memset (lock, 0, sizeof(lock));
378 lock->l_type = F_UNLCK;
379 lock->l_len = sizeof(*bt->page);
382 if( fcntl (bt->idx, F_SETLK, lock) < 0 )
383 return bt->err = BTERR_lock;
385 memset (ovl, 0, sizeof(ovl));
386 ovl->OffsetHigh = (uint)(off >> 32);
387 ovl->Offset = (uint)off;
388 len = sizeof(*bt->page);
390 // use large offsets to
391 // simulate advisory locking
393 ovl->OffsetHigh |= 0x80000000;
395 if( !UnlockFileEx (bt->idx, 0, len, 0, ovl) )
396 return GetLastError(), bt->err = BTERR_lock;
402 // close and release memory
404 void bt_close (BtDb *bt)
408 // release mapped pages
410 if( hash = bt->lrufirst )
411 do munmap (hash->page, (bt->hashmask+1) << bt->page_bits);
412 while(hash = hash->lrunext);
420 if( hash = bt->lrufirst )
423 FlushViewOfFile(hash->page, 0);
424 UnmapViewOfFile(hash->page);
425 CloseHandle(hash->hmap);
426 } while(hash = hash->lrunext);
429 VirtualFree (bt->mem, 0, MEM_RELEASE);
430 FlushFileBuffers(bt->idx);
431 CloseHandle(bt->idx);
432 GlobalFree (bt->cache);
437 // open/create new btree
438 // call with file_name, BT_openmode, bits in page size (e.g. 16),
439 // size of mapped page cache (e.g. 8192) or zero for no mapping.
441 BtDb *bt_open (char *name, uint mode, uint bits, uint nodemax, uint pgblk)
443 uint lvl, attr, cacheblk, last;
444 BtLock lockmode = BtLockWrite;
451 SYSTEM_INFO sysinfo[1];
455 bt = malloc (sizeof(BtDb) + nodemax * sizeof(BtHash));
456 memset (bt, 0, sizeof(BtDb));
458 switch (mode & 0x7fff)
462 bt->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
467 bt->idx = open ((char*)name, O_RDONLY);
468 lockmode = BtLockRead;
472 return free(bt), NULL;
475 cacheblk = 4096; // page size for unix
480 bt = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtDb) + nodemax * sizeof(BtHash));
481 attr = FILE_ATTRIBUTE_NORMAL;
482 switch (mode & 0x7fff)
485 attr |= FILE_FLAG_WRITE_THROUGH | FILE_FLAG_NO_BUFFERING;
488 bt->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
493 bt->idx = CreateFile(name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, attr, NULL);
494 lockmode = BtLockRead;
497 if( bt->idx == INVALID_HANDLE_VALUE )
498 return GlobalFree(bt), NULL;
500 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
501 GetSystemInfo(sysinfo);
504 cacheblk = sysinfo->dwAllocationGranularity;
509 // determine sanity of page size
511 if( bits > BT_maxbits )
513 else if( bits < BT_minbits )
516 if ( bt_lockpage(bt, ALLOC_page, lockmode) )
517 return bt_close (bt), NULL;
522 // read minimum page size to get root info
524 if( size = lseek (bt->idx, 0L, 2) ) {
525 alloc = malloc (BT_minpage);
526 pread(bt->idx, alloc, BT_minpage, 0);
529 } else if( mode == BT_ro )
530 return bt_close (bt), NULL;
532 size = GetFileSize(bt->idx, amt);
535 alloc = VirtualAlloc(NULL, BT_minpage, MEM_COMMIT, PAGE_READWRITE);
536 if( !ReadFile(bt->idx, (char *)alloc, BT_minpage, amt, NULL) )
537 return bt_close (bt), NULL;
539 VirtualFree (alloc, 0, MEM_RELEASE);
540 } else if( mode == BT_ro )
541 return bt_close (bt), NULL;
544 bt->page_size = 1 << bits;
545 bt->page_bits = bits;
547 bt->nodemax = nodemax;
550 // setup cache mapping
553 if( cacheblk < bt->page_size )
554 cacheblk = bt->page_size;
556 bt->hashsize = nodemax / 8;
557 bt->hashmask = (cacheblk >> bits) - 1;
561 // requested number of pages per memmap segment
564 if( (1 << pgblk) > bt->hashmask )
565 bt->hashmask = (1 << pgblk) - 1;
569 while( (1 << bt->seg_bits) <= bt->hashmask )
573 bt->mem = malloc (8 *bt->page_size);
574 bt->cache = calloc (bt->hashsize, sizeof(ushort));
576 bt->mem = VirtualAlloc(NULL, 8 * bt->page_size, MEM_COMMIT, PAGE_READWRITE);
577 bt->cache = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, bt->hashsize * sizeof(ushort));
579 bt->frame = (BtPage)bt->mem;
580 bt->cursor = (BtPage)(bt->mem + bt->page_size);
581 bt->page = (BtPage)(bt->mem + 2 * bt->page_size);
582 bt->alloc = (BtPage)(bt->mem + 3 * bt->page_size);
583 bt->temp = (BtPage)(bt->mem + 4 * bt->page_size);
584 bt->temp2 = (BtPage)(bt->mem + 5 * bt->page_size);
585 bt->parent = (BtPage)(bt->mem + 6 * bt->page_size);
586 bt->zero = (BtPage)(bt->mem + 7 * bt->page_size);
589 if ( bt_unlockpage(bt, ALLOC_page, lockmode) )
590 return bt_close (bt), NULL;
595 // initializes an empty b-tree with root page and page of leaves
597 memset (bt->alloc, 0, bt->page_size);
598 bt_putid(bt->alloc->right, MIN_lvl+1);
599 bt->alloc->bits = bt->page_bits;
602 if( write (bt->idx, bt->alloc, bt->page_size) < bt->page_size )
603 return bt_close (bt), NULL;
605 if( !WriteFile (bt->idx, (char *)bt->alloc, bt->page_size, amt, NULL) )
606 return bt_close (bt), NULL;
608 if( *amt < bt->page_size )
609 return bt_close (bt), NULL;
612 memset (bt->frame, 0, bt->page_size);
613 bt->frame->bits = bt->page_bits;
614 bt->frame->posted = 1;
616 for( lvl=MIN_lvl; lvl--; ) {
617 slotptr(bt->frame, 1)->off = offsetof(struct BtPage_, fence);
618 bt_putid(slotptr(bt->frame, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
619 bt->frame->fence[0] = 2;
620 bt->frame->fence[1] = 0xff;
621 bt->frame->fence[2] = 0xff;
622 bt->frame->min = bt->page_size;
623 bt->frame->lvl = lvl;
627 if( write (bt->idx, bt->frame, bt->page_size) < bt->page_size )
628 return bt_close (bt), NULL;
630 if( !WriteFile (bt->idx, (char *)bt->frame, bt->page_size, amt, NULL) )
631 return bt_close (bt), NULL;
633 if( *amt < bt->page_size )
634 return bt_close (bt), NULL;
638 // create empty page area by writing last page of first
639 // cache area (other pages are zeroed by O/S)
641 if( bt->mapped_io && bt->hashmask ) {
642 memset(bt->frame, 0, bt->page_size);
645 while( last < MIN_lvl + 1 )
646 last += bt->hashmask + 1;
648 pwrite(bt->idx, bt->frame, bt->page_size, last << bt->page_bits);
650 SetFilePointer (bt->idx, last << bt->page_bits, NULL, FILE_BEGIN);
651 if( !WriteFile (bt->idx, (char *)bt->frame, bt->page_size, amt, NULL) )
652 return bt_close (bt), NULL;
653 if( *amt < bt->page_size )
654 return bt_close (bt), NULL;
658 if( bt_unlockpage(bt, ALLOC_page, lockmode) )
659 return bt_close (bt), NULL;
664 // compare two keys, returning > 0, = 0, or < 0
665 // as the comparison value
667 int keycmp (BtKey key1, unsigned char *key2, uint len2)
669 uint len1 = key1->len;
672 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
683 // Update current page of btree by writing file contents
684 // or flushing mapped area to disk.
686 BTERR bt_update (BtDb *bt, BtPage page, uid page_no)
688 off64_t off = page_no << bt->page_bits;
691 if ( !bt->mapped_io )
692 if ( pwrite(bt->idx, page, bt->page_size, off) != bt->page_size )
693 return bt->err = BTERR_wrt;
696 if ( !bt->mapped_io )
698 SetFilePointer (bt->idx, (long)off, (long*)(&off)+1, FILE_BEGIN);
699 if( !WriteFile (bt->idx, (char *)page, bt->page_size, amt, NULL) )
700 return GetLastError(), bt->err = BTERR_wrt;
702 if( *amt < bt->page_size )
703 return GetLastError(), bt->err = BTERR_wrt;
705 else if ( bt->mode == BT_fl ) {
706 FlushViewOfFile(page, bt->page_size);
707 FlushFileBuffers(bt->idx);
713 // find page in cache
715 BtHash *bt_findhash(BtDb *bt, uid page_no)
720 // compute cache block first page and hash idx
722 page_no &= ~bt->hashmask;
723 idx = (uint)(page_no >> bt->seg_bits) % bt->hashsize;
726 hash = bt->nodes + bt->cache[idx];
730 do if( hash->page_no == page_no )
732 while(hash = hash->hashnext );
737 // add page cache entry to hash index
739 void bt_linkhash(BtDb *bt, BtHash *node, uid page_no)
741 uint idx = (uint)(page_no >> bt->seg_bits) % bt->hashsize;
744 if( bt->cache[idx] ) {
745 node->hashnext = hash = bt->nodes + bt->cache[idx];
746 hash->hashprev = node;
749 node->hashprev = NULL;
750 bt->cache[idx] = (ushort)(node - bt->nodes);
753 // remove cache entry from hash table
755 void bt_unlinkhash(BtDb *bt, BtHash *node)
757 uint idx = (uint)(node->page_no >> bt->seg_bits) % bt->hashsize;
761 if( hash = node->hashprev )
762 hash->hashnext = node->hashnext;
763 else if( hash = node->hashnext )
764 bt->cache[idx] = (ushort)(hash - bt->nodes);
768 if( hash = node->hashnext )
769 hash->hashprev = node->hashprev;
772 // add cache page to lru chain and map pages
774 BtPage bt_linklru(BtDb *bt, BtHash *hash, uid page_no)
777 off64_t off = (page_no & ~bt->hashmask) << bt->page_bits;
778 off64_t limit = off + ((bt->hashmask+1) << bt->page_bits);
781 memset(hash, 0, sizeof(BtHash));
782 hash->page_no = (page_no & ~bt->hashmask);
783 bt_linkhash(bt, hash, page_no);
785 if( node = hash->lrunext = bt->lrufirst )
786 node->lruprev = hash;
793 flag = PROT_READ | ( bt->mode == BT_ro ? 0 : PROT_WRITE );
794 hash->page = (BtPage)mmap (0, (bt->hashmask+1) << bt->page_bits, flag, MAP_SHARED, bt->idx, off);
795 if( hash->page == MAP_FAILED )
796 return bt->err = BTERR_map, (BtPage)NULL;
799 flag = ( bt->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
800 hash->hmap = CreateFileMapping(bt->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
802 return bt->err = BTERR_map, NULL;
804 flag = ( bt->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
805 hash->page = MapViewOfFile(hash->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->hashmask+1) << bt->page_bits);
807 return bt->err = BTERR_map, NULL;
810 return (BtPage)((char*)hash->page + ((uint)(page_no & bt->hashmask) << bt->page_bits));
813 // find or place requested page in page-cache
814 // return memory address where page is located.
816 BtPage bt_hashpage(BtDb *bt, uid page_no)
818 BtHash *hash, *node, *next;
821 // find page in cache and move to top of lru list
823 if( hash = bt_findhash(bt, page_no) ) {
824 page = (BtPage)((char*)hash->page + ((uint)(page_no & bt->hashmask) << bt->page_bits));
825 // swap node in lru list
826 if( node = hash->lruprev ) {
827 if( next = node->lrunext = hash->lrunext )
828 next->lruprev = node;
832 if( next = hash->lrunext = bt->lrufirst )
833 next->lruprev = hash;
835 return bt->err = BTERR_hash, (BtPage)NULL;
837 hash->lruprev = NULL;
843 // map pages and add to cache entry
845 if( bt->nodecnt < bt->nodemax ) {
846 hash = bt->nodes + ++bt->nodecnt;
847 return bt_linklru(bt, hash, page_no);
850 // hash table is already full, replace last lru entry from the cache
852 if( hash = bt->lrulast ) {
853 // unlink from lru list
854 if( node = bt->lrulast = hash->lruprev )
855 node->lrunext = NULL;
857 return bt->err = BTERR_hash, (BtPage)NULL;
860 munmap (hash->page, (bt->hashmask+1) << bt->page_bits);
862 FlushViewOfFile(hash->page, 0);
863 UnmapViewOfFile(hash->page);
864 CloseHandle(hash->hmap);
866 // unlink from hash table
868 bt_unlinkhash(bt, hash);
870 // map and add to cache
872 return bt_linklru(bt, hash, page_no);
875 return bt->err = BTERR_hash, (BtPage)NULL;
878 // map a btree page onto current page
880 BTERR bt_mappage (BtDb *bt, BtPage *page, uid page_no)
882 off64_t off = page_no << bt->page_bits;
887 if( bt->mapped_io ) {
889 *page = bt_hashpage(bt, page_no);
893 if ( pread(bt->idx, *page, bt->page_size, off) < bt->page_size )
894 return bt->err = BTERR_map;
896 SetFilePointer (bt->idx, (long)off, (long*)(&off)+1, FILE_BEGIN);
898 if( !ReadFile(bt->idx, *page, bt->page_size, amt, NULL) )
899 return bt->err = BTERR_map;
901 if( *amt < bt->page_size )
902 return bt->err = BTERR_map;
907 // allocate a new page and write page into it
909 uid bt_newpage(BtDb *bt, BtPage page)
917 if ( bt_lockpage(bt, ALLOC_page, BtLockWrite) )
920 if( bt_mappage (bt, &bt->alloc, ALLOC_page) )
923 // use empty chain first
924 // else allocate empty page
926 if( new_page = bt_getid(bt->alloc[1].right) ) {
927 if( bt_mappage (bt, &bt->temp, new_page) )
928 return 0; // don't unlock on error
929 memcpy(bt->alloc[1].right, bt->temp->right, BtId);
932 new_page = bt_getid(bt->alloc->right);
933 bt_putid(bt->alloc->right, new_page+1);
937 if( bt_update(bt, bt->alloc, ALLOC_page) )
938 return 0; // don't unlock on error
940 if( !bt->mapped_io ) {
941 if( bt_update(bt, page, new_page) )
942 return 0; //don't unlock on error
946 if ( bt_unlockpage(bt, ALLOC_page, BtLockWrite) )
953 if ( pwrite(bt->idx, page, bt->page_size, new_page << bt->page_bits) < bt->page_size )
954 return bt->err = BTERR_wrt, 0;
956 // if writing first page of hash block, zero last page in the block
958 if ( !reuse && bt->hashmask > 0 && (new_page & bt->hashmask) == 0 )
960 // use temp buffer to write zeros
961 memset(bt->zero, 0, bt->page_size);
962 if ( pwrite(bt->idx,bt->zero, bt->page_size, (new_page | bt->hashmask) << bt->page_bits) < bt->page_size )
963 return bt->err = BTERR_wrt, 0;
966 // bring new page into page-cache and copy page.
967 // this will extend the file into the new pages.
969 if( !(pmap = (char*)bt_hashpage(bt, new_page & ~bt->hashmask)) )
972 memcpy(pmap+((new_page & bt->hashmask) << bt->page_bits), page, bt->page_size);
977 if ( bt_unlockpage(bt, ALLOC_page, BtLockWrite) )
983 // find slot in page for given key at a given level
984 // return 0 if beyond fence value
986 int bt_findslot (BtPageSet *set, unsigned char *key, uint len)
988 uint diff, higher = set->page->cnt, low = 1, slot;
990 // make stopper key an infinite fence value
992 if( bt_getid (set->page->right) )
995 // low is the lowest candidate, higher is already
996 // tested as .ge. the given key, loop ends when they meet
998 while( diff = higher - low ) {
999 slot = low + ( diff >> 1 );
1000 if( keycmp (keyptr(set->page, slot), key, len) < 0 )
1006 if( higher <= set->page->cnt )
1009 // if leaf page, compare against fence value
1011 // return zero if key is on right link page
1012 // or return slot beyond last key
1014 if( set->page->lvl || keycmp ((BtKey)set->page->fence, key, len) < 0 )
1020 // find and load page at given level for given key
1021 // leave page rd or wr locked as requested
1023 int bt_loadpage (BtDb *bt, BtPageSet *set, unsigned char *key, uint len, uint lvl, uint lock)
1025 uid page_no = ROOT_page, prevpage = 0;
1026 uint drill = 0xff, slot;
1027 uint mode, prevmode;
1029 // start at root of btree and drill down
1032 // determine lock mode of drill level
1033 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1035 set->page_no = page_no;
1037 // obtain access lock using lock chaining
1039 if( page_no > ROOT_page )
1040 if( bt_lockpage(bt, page_no, BtLockAccess) )
1044 if( bt_unlockpage(bt, prevpage, prevmode) )
1047 // obtain read lock using lock chaining
1049 if( bt_lockpage(bt, page_no, mode) )
1052 if( page_no > ROOT_page )
1053 if( bt_unlockpage(bt, page_no, BtLockAccess) )
1056 // map/obtain page contents
1058 if( bt_mappage (bt, &set->page, page_no) )
1061 // re-read and re-lock root after determining actual level of root
1063 if( set->page->lvl != drill) {
1064 if ( page_no != ROOT_page )
1065 return bt->err = BTERR_struct, 0;
1067 drill = set->page->lvl;
1069 if( lock == BtLockWrite && drill == lvl )
1070 if( bt_unlockpage(bt, page_no, mode) )
1079 // if page is being deleted and we should continue right
1081 if( set->page->kill && set->page->goright ) {
1082 page_no = bt_getid (set->page->right);
1086 // otherwise, wait for deleted node to clear
1088 if( set->page->kill ) {
1089 if( bt_unlockpage(bt, set->page_no, mode) )
1091 page_no = ROOT_page;
1102 // find key on page at this level
1103 // and descend to requested level
1105 if( slot = bt_findslot (set, key, len) ) {
1109 if( slot > set->page->cnt )
1110 return bt->err = BTERR_struct, 0;
1112 // if drilling down, find next active key
1114 while( slotptr(set->page, slot)->dead )
1115 if( slot++ < set->page->cnt )
1118 return bt->err = BTERR_struct, 0;
1120 page_no = bt_getid(slotptr(set->page, slot)->id);
1125 // or slide right into next page
1126 // (slide left from deleted page)
1128 page_no = bt_getid(set->page->right);
1132 // return error on end of right chain
1134 bt->err = BTERR_struct;
1135 return 0; // return error
1138 // drill down fixing fence values for left sibling tree
1140 // call with set write locked mapped to bt->temp
1141 // return with set unlocked & unpinned.
1143 BTERR bt_fixfences (BtDb *bt, BtPageSet *set, unsigned char *newfence)
1145 unsigned char oldfence[256];
1150 next->page_no = bt_getid(slotptr(set->page, set->page->cnt)->id);
1151 memcpy (oldfence, set->page->fence, 256);
1152 next->page = bt->temp2;
1153 bt->temp2 = bt->temp;
1154 bt->temp = next->page;
1156 while( !set->page->kill && set->page->lvl ) {
1157 if( bt_lockpage (bt, next->page_no, BtLockParent) )
1159 if( bt_lockpage (bt, next->page_no, BtLockAccess) )
1161 if( bt_lockpage (bt, next->page_no, BtLockWrite) )
1163 if( bt_unlockpage (bt, next->page_no, BtLockAccess) )
1166 if( bt_mappage (bt, &next->page, next->page_no) )
1169 chk = keycmp ((BtKey)next->page->fence, oldfence + 1, *oldfence);
1172 right = bt_getid (next->page->right);
1173 if( bt_unlockpage (bt, next->page_no, BtLockWrite) )
1175 if( bt_unlockpage (bt, next->page_no, BtLockParent) )
1177 next->page_no = right;
1182 return bt->err = BTERR_struct;
1184 if( bt_fixfences (bt, next, newfence) )
1190 set->page = bt->temp;
1192 if( bt_mappage (bt, &set->page, set->page_no) )
1195 memcpy (set->page->fence, newfence, 256);
1197 if( bt_update(bt, set->page, set->page_no) )
1199 if( bt_unlockpage (bt, set->page_no, BtLockWrite) )
1201 if( bt_unlockpage (bt, set->page_no, BtLockParent) )
1207 // return page to free list
1208 // page must be delete & write locked
1210 BTERR bt_freepage (BtDb *bt, BtPageSet *set)
1212 // lock & map allocation page
1214 if( bt_lockpage (bt, ALLOC_page, BtLockWrite) )
1217 if( bt_mappage (bt, &bt->alloc, ALLOC_page) )
1220 // store chain in second right
1221 bt_putid(set->page->right, bt_getid(bt->alloc[1].right));
1222 bt_putid(bt->alloc[1].right, set->page_no);
1223 set->page->free = 1;
1225 if( bt_update(bt, bt->alloc, ALLOC_page) )
1227 if( bt_update(bt, set->page, set->page_no) )
1232 if( bt_unlockpage(bt, ALLOC_page, BtLockWrite) )
1235 // remove write lock on deleted node
1237 if( bt_unlockpage(bt, set->page_no, BtLockWrite) )
1240 return bt_unlockpage (bt, set->page_no, BtLockDelete);
1243 // remove the root level by promoting its only child
1245 BTERR bt_removeroot (BtDb *bt, BtPageSet *root, BtPageSet *child)
1251 if( bt_lockpage (bt, next, BtLockDelete) )
1253 if( bt_lockpage (bt, next, BtLockWrite) )
1256 if( bt_mappage (bt, &child->page, next) )
1259 child->page_no = next;
1262 memcpy (root->page, child->page, bt->page_size);
1263 next = bt_getid (slotptr(child->page, child->page->cnt)->id);
1265 if( bt_freepage (bt, child) )
1267 } while( root->page->lvl > 1 && root->page->cnt == 1 );
1269 if( bt_update (bt, root->page, ROOT_page) )
1272 return bt_unlockpage (bt, ROOT_page, BtLockWrite);
1275 // pull right page over ourselves in simple merge
1277 BTERR bt_mergeright (BtDb *bt, BtPageSet *set, BtPageSet *parent, BtPageSet *right, uint slot, uint idx)
1279 // install ourselves as child page
1280 // and delete ourselves from parent
1282 bt_putid (slotptr(parent->page, idx)->id, set->page_no);
1283 slotptr(parent->page, slot)->dead = 1;
1284 parent->page->act--;
1286 // collapse any empty slots
1288 while( idx = parent->page->cnt - 1 )
1289 if( slotptr(parent->page, idx)->dead ) {
1290 *slotptr(parent->page, idx) = *slotptr(parent->page, idx + 1);
1291 memset (slotptr(parent->page, parent->page->cnt--), 0, sizeof(BtSlot));
1295 memcpy (set->page, right->page, bt->page_size);
1297 if( bt_unlockpage (bt, right->page_no, BtLockParent) )
1300 if( bt_freepage (bt, right) )
1303 // do we need to remove a btree level?
1304 // (leave the first page of leaves alone)
1306 if( parent->page_no == ROOT_page && parent->page->cnt == 1 )
1307 if( set->page->lvl )
1308 return bt_removeroot (bt, parent, set);
1310 if( bt_update (bt, parent->page, parent->page_no) )
1313 if( bt_unlockpage (bt, parent->page_no, BtLockWrite) )
1316 if( bt_update (bt, set->page, set->page_no) )
1319 if( bt_unlockpage (bt, set->page_no, BtLockWrite) )
1322 if( bt_unlockpage (bt, set->page_no, BtLockDelete) )
1328 // remove both child and parent from the btree
1329 // from the fence position in the parent
1331 BTERR bt_removeparent (BtDb *bt, BtPageSet *child, BtPageSet *parent, BtPageSet *right, BtPageSet *rparent, uint lvl)
1333 unsigned char pagefence[256];
1336 // pull right sibling over ourselves and unlock
1338 memcpy (child->page, right->page, bt->page_size);
1340 if( bt_update(bt, child->page, child->page_no) )
1343 if( bt_unlockpage (bt, child->page_no, BtLockWrite) )
1346 // install ourselves into right link of old right page
1348 bt_putid (right->page->right, child->page_no);
1349 right->page->goright = 1; // tell bt_loadpage to go right to us
1350 right->page->kill = 1;
1352 if( bt_update(bt, right->page, right->page_no) )
1355 if( bt_unlockpage (bt, right->page_no, BtLockWrite) )
1358 // remove our slot from our parent
1359 // signal to move right
1361 parent->page->goright = 1; // tell bt_findslot to go right to rparent
1362 parent->page->kill = 1;
1363 parent->page->act--;
1365 // redirect right page pointer in right parent to us
1367 for( idx = 0; idx++ < rparent->page->cnt; )
1368 if( !slotptr(rparent->page, idx)->dead )
1371 if( bt_getid (slotptr(rparent->page, idx)->id) != right->page_no )
1372 return bt->err = BTERR_struct;
1374 bt_putid (slotptr(rparent->page, idx)->id, child->page_no);
1376 if( bt_update (bt, rparent->page, rparent->page_no) )
1379 if( bt_unlockpage (bt, rparent->page_no, BtLockWrite) )
1382 // save parent page fence value
1384 memcpy (pagefence, parent->page->fence, 256);
1386 if( bt_update (bt, parent->page, parent->page_no) )
1388 if( bt_unlockpage (bt, parent->page_no, BtLockWrite) )
1391 return bt_removepage (bt, parent->page_no, lvl, pagefence);
1394 // remove page from btree
1395 // call with page unlocked
1396 // returns with page on free list
1398 BTERR bt_removepage (BtDb *bt, uid page_no, uint lvl, unsigned char *pagefence)
1400 BtPageSet parent[1], rparent[1], sibling[1], set[1];
1401 unsigned char newfence[256];
1405 parent->page = bt->parent;
1406 set->page_no = page_no;
1407 set->page = bt->page;
1409 // load and lock our parent
1412 if( !(slot = bt_loadpage (bt, parent, pagefence+1, *pagefence, lvl+1, BtLockWrite)) )
1415 // wait until we are posted in our parent
1417 if( set->page_no != bt_getid (slotptr (parent->page, slot)->id) ) {
1418 if( bt_unlockpage (bt, parent->page_no, BtLockWrite) )
1428 // can we do a simple merge entirely
1429 // between siblings on the parent page?
1431 if( slot < parent->page->cnt ) {
1432 // find our right neighbor
1433 // right must exist because the stopper prevents
1434 // the rightmost page from deleting
1436 for( idx = slot; idx++ < parent->page->cnt; )
1437 if( !slotptr(parent->page, idx)->dead )
1440 sibling->page_no = bt_getid (slotptr (parent->page, idx)->id);
1442 if( bt_lockpage (bt, set->page_no, BtLockDelete) )
1445 if( bt_lockpage (bt, set->page_no, BtLockWrite) )
1448 if( bt_mappage (bt, &set->page, set->page_no) )
1451 // merge right if sibling shows up in
1452 // our parent and is not being killed
1454 if( sibling->page_no == bt_getid (set->page->right) ) {
1455 if( bt_lockpage (bt, sibling->page_no, BtLockParent) )
1458 if( bt_lockpage (bt, sibling->page_no, BtLockDelete) )
1461 if( bt_lockpage (bt, sibling->page_no, BtLockWrite) )
1464 sibling->page = bt->temp;
1466 if( bt_mappage (bt, &sibling->page, sibling->page_no) )
1469 if( !sibling->page->kill )
1470 return bt_mergeright(bt, set, parent, sibling, slot, idx);
1474 if( bt_unlockpage (bt, sibling->page_no, BtLockWrite) )
1478 if( bt_unlockpage (bt, set->page_no, BtLockDelete) )
1481 if( bt_unlockpage (bt, set->page_no, BtLockWrite) )
1484 if( bt_unlockpage (bt, parent->page_no, BtLockWrite) )
1494 // find our left neighbor in our parent page
1496 for( idx = slot; --idx; )
1497 if( !slotptr(parent->page, idx)->dead )
1500 // if no left neighbor, delete ourselves and our parent
1503 if( bt_lockpage (bt, set->page_no, BtLockAccess) )
1506 if( bt_lockpage (bt, set->page_no, BtLockWrite) )
1509 if( bt_unlockpage (bt, set->page_no, BtLockAccess) )
1512 if( bt_mappage (bt, &set->page, set->page_no) )
1515 rparent->page_no = bt_getid (parent->page->right);
1516 rparent->page = bt->temp;
1518 if( bt_lockpage (bt, rparent->page_no, BtLockAccess) )
1521 if( bt_lockpage (bt, rparent->page_no, BtLockWrite) )
1524 if( bt_unlockpage (bt, rparent->page_no, BtLockAccess) )
1527 if( bt_mappage (bt, &rparent->page, rparent->page_no) )
1530 if( !rparent->page->kill ) {
1531 sibling->page_no = bt_getid (set->page->right);
1533 if( bt_lockpage (bt, sibling->page_no, BtLockAccess) )
1536 if( bt_lockpage (bt, sibling->page_no, BtLockWrite) )
1539 if( bt_unlockpage (bt, sibling->page_no, BtLockAccess) )
1542 sibling->page = bt->temp2;
1544 if( bt_mappage (bt, &sibling->page, sibling->page_no) )
1547 if( !sibling->page->kill )
1548 return bt_removeparent (bt, set, parent, sibling, rparent, lvl+1);
1552 if( bt_unlockpage (bt, sibling->page_no, BtLockWrite) )
1556 if( bt_unlockpage (bt, set->page_no, BtLockWrite) )
1559 if( bt_unlockpage (bt, rparent->page_no, BtLockWrite) )
1562 if( bt_unlockpage (bt, parent->page_no, BtLockWrite) )
1572 // redirect parent to our left sibling
1573 // lock and map our left sibling's page
1575 sibling->page_no = bt_getid (slotptr(parent->page, idx)->id);
1576 sibling->page = bt->temp;
1578 // wait our turn on fence key maintenance
1580 if( bt_lockpage(bt, sibling->page_no, BtLockParent) )
1583 if( bt_lockpage(bt, sibling->page_no, BtLockAccess) )
1586 if( bt_lockpage(bt, sibling->page_no, BtLockWrite) )
1589 if( bt_unlockpage(bt, sibling->page_no, BtLockAccess) )
1592 if( bt_mappage (bt, &sibling->page, sibling->page_no) )
1595 // wait until sibling is in our parent
1597 if( bt_getid (sibling->page->right) != set->page_no ) {
1598 if( bt_unlockpage (bt, parent->page_no, BtLockWrite) )
1600 if( bt_unlockpage (bt, sibling->page_no, BtLockWrite) )
1602 if( bt_unlockpage (bt, sibling->page_no, BtLockParent) )
1612 // map page being killed
1614 if( bt_lockpage (bt, set->page_no, BtLockDelete) )
1617 if( bt_lockpage (bt, set->page_no, BtLockWrite) )
1620 if( bt_mappage (bt, &set->page, set->page_no) )
1623 // delete our left sibling from parent
1625 slotptr(parent->page,idx)->dead = 1;
1626 parent->page->dirty = 1;
1627 parent->page->act--;
1629 // redirect our parent slot to our left sibling
1631 bt_putid (slotptr(parent->page, slot)->id, sibling->page_no);
1632 memcpy (sibling->page->right, set->page->right, BtId);
1634 if( bt_update (bt, sibling->page, sibling->page_no) )
1637 // collapse dead slots from parent
1639 while( idx = parent->page->cnt - 1 )
1640 if( slotptr(parent->page, idx)->dead ) {
1641 *slotptr(parent->page, idx) = *slotptr(parent->page, parent->page->cnt);
1642 memset (slotptr(parent->page, parent->page->cnt--), 0, sizeof(BtSlot));
1646 // update parent page
1648 if( bt_update (bt, parent->page, parent->page_no) )
1651 // free our original page
1653 if( bt_freepage (bt, set) )
1656 // go down the left node's fence keys to the leaf level
1657 // and update the fence keys in each page
1659 memcpy (newfence, parent->page->fence, 256);
1661 if( bt_fixfences (bt, sibling, newfence) )
1664 // promote sibling as new root?
1666 if( parent->page_no == ROOT_page && parent->page->cnt == 1 )
1667 if( sibling->page->lvl ) {
1668 if( bt_lockpage (bt, sibling->page_no, BtLockDelete) )
1671 if( bt_lockpage (bt, sibling->page_no, BtLockWrite) )
1674 if( bt_mappage (bt, &sibling->page, set->page_no) )
1677 return bt_removeroot (bt, parent, sibling);
1680 return bt_unlockpage (bt, parent->page_no, BtLockWrite);
1684 // find and delete key on page by marking delete flag bit
1685 // when page becomes empty, delete it
1687 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len)
1689 unsigned char pagefence[256];
1690 uint slot, found, idx;
1694 set->page = bt->page;
1696 if( slot = bt_loadpage (bt, set, key, len, 0, BtLockWrite) )
1697 ptr = keyptr(set->page, slot);
1701 // if key is found delete it, otherwise ignore request
1703 if( found = slot <= set->page->cnt )
1704 if( found = !keycmp (ptr, key, len) )
1705 if( found = slotptr(set->page, slot)->dead == 0 ) {
1706 slotptr(set->page,slot)->dead = 1;
1707 set->page->dirty = 1;
1710 // collapse empty slots
1712 while( idx = set->page->cnt - 1 )
1713 if( slotptr(set->page, idx)->dead ) {
1714 *slotptr(set->page, idx) = *slotptr(set->page, idx + 1);
1715 memset (slotptr(set->page, set->page->cnt--), 0, sizeof(BtSlot));
1720 if( set->page->act ) {
1721 if( bt_update(bt, set->page, set->page_no) )
1724 return bt_unlockpage (bt, set->page_no, BtLockWrite);
1727 // delete page when empty
1729 memcpy (pagefence, set->page->fence, 256);
1730 set->page->kill = 1;
1732 if( bt_update(bt, set->page, set->page_no) )
1735 if( bt_unlockpage(bt, set->page_no, BtLockWrite) )
1738 if( bt_removepage (bt, set->page_no, 0, pagefence) )
1745 // find key in leaf level and return row-id
1747 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1754 set->page = bt->page;
1756 if( slot = bt_loadpage (bt, set, key, len, 0, BtLockRead) )
1757 ptr = keyptr(set->page, slot);
1761 // if key exists, return row-id
1762 // otherwise return 0
1764 if( slot <= set->page->cnt )
1765 if( !keycmp (ptr, key, len) )
1766 id = bt_getid(slotptr(set->page,slot)->id);
1768 if ( bt_unlockpage(bt, set->page_no, BtLockRead) )
1774 // check page for space available,
1775 // clean if necessary and return
1776 // 0 - page needs splitting
1777 // >0 - new slot value
1779 uint bt_cleanpage(BtDb *bt, BtPage page, uint amt, uint slot)
1781 uint nxt = bt->page_size, off;
1782 uint cnt = 0, idx = 0;
1783 uint max = page->cnt;
1787 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1790 // skip cleanup if nothing to reclaim
1795 memcpy (bt->frame, page, bt->page_size);
1797 // skip page info and set rest of page to zero
1799 memset (page+1, 0, bt->page_size - sizeof(*page));
1803 while( cnt++ < max ) {
1806 if( slotptr(bt->frame,cnt)->dead )
1809 off = slotptr(bt->frame,cnt)->off;
1813 if( off >= sizeof(*page) ) {
1814 key = keyptr(bt->frame, cnt);
1815 off = nxt -= key->len + 1;
1816 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1821 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1822 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1823 slotptr(page, idx)->off = off;
1829 if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1835 // split the root and raise the height of the btree
1837 BTERR bt_splitroot(BtDb *bt, BtPageSet *root, uid page_no2)
1839 unsigned char leftkey[256];
1840 uint nxt = bt->page_size;
1843 // Obtain an empty page to use, and copy the current
1844 // root contents into it, e.g. lower keys
1846 memcpy (leftkey, root->page->fence, 256);
1847 root->page->posted = 1;
1849 if( !(new_page = bt_newpage(bt, root->page)) )
1852 // preserve the page info at the bottom
1853 // of higher keys and set rest to zero
1855 memset(root->page+1, 0, bt->page_size - sizeof(*root->page));
1856 memset(root->page->fence, 0, 256);
1857 root->page->fence[0] = 2;
1858 root->page->fence[1] = 0xff;
1859 root->page->fence[2] = 0xff;
1861 // insert new page fence key on newroot page
1863 nxt -= *leftkey + 1;
1864 memcpy ((unsigned char *)root->page + nxt, leftkey, *leftkey + 1);
1865 bt_putid(slotptr(root->page, 1)->id, new_page);
1866 slotptr(root->page, 1)->off = nxt;
1868 // insert stopper key on newroot page
1869 // and increase the root height
1871 bt_putid(slotptr(root->page, 2)->id, page_no2);
1872 slotptr(root->page, 2)->off = offsetof(struct BtPage_, fence);
1874 bt_putid(root->page->right, 0);
1875 root->page->min = nxt; // reset lowest used offset and key count
1876 root->page->cnt = 2;
1877 root->page->act = 2;
1880 // update and release root
1882 if( bt_update(bt, root->page, root->page_no) )
1885 return bt_unlockpage(bt, root->page_no, BtLockWrite);
1888 // split already locked full node
1891 BTERR bt_splitpage (BtDb *bt, BtPageSet *set)
1893 uint cnt = 0, idx = 0, max, nxt = bt->page_size, off;
1894 unsigned char fencekey[256];
1895 uint lvl = set->page->lvl;
1899 // split higher half of keys to bt->frame
1901 memset (bt->frame, 0, bt->page_size);
1902 max = set->page->cnt;
1906 while( cnt++ < max ) {
1907 if( !lvl || cnt < max ) {
1908 key = keyptr(set->page, cnt);
1909 off = nxt -= key->len + 1;
1910 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
1912 off = offsetof(struct BtPage_, fence);
1914 memcpy(slotptr(bt->frame,++idx)->id, slotptr(set->page,cnt)->id, BtId);
1915 slotptr(bt->frame, idx)->tod = slotptr(set->page, cnt)->tod;
1916 slotptr(bt->frame, idx)->off = off;
1920 if( set->page_no == ROOT_page )
1921 bt->frame->posted = 1;
1923 memcpy (bt->frame->fence, set->page->fence, 256);
1924 bt->frame->bits = bt->page_bits;
1925 bt->frame->min = nxt;
1926 bt->frame->cnt = idx;
1927 bt->frame->lvl = lvl;
1931 if( set->page_no > ROOT_page )
1932 memcpy (bt->frame->right, set->page->right, BtId);
1934 // get new free page and write higher keys to it.
1936 if( !(right = bt_newpage(bt, bt->frame)) )
1939 // update lower keys to continue in old page
1941 memcpy (bt->frame, set->page, bt->page_size);
1942 memset (set->page+1, 0, bt->page_size - sizeof(*set->page));
1943 nxt = bt->page_size;
1944 set->page->posted = 0;
1945 set->page->dirty = 0;
1950 // assemble page of smaller keys
1952 while( cnt++ < max / 2 ) {
1953 key = keyptr(bt->frame, cnt);
1955 if( !lvl || cnt < max / 2 ) {
1956 off = nxt -= key->len + 1;
1957 memcpy ((unsigned char *)set->page + nxt, key, key->len + 1);
1959 off = offsetof(struct BtPage_, fence);
1961 memcpy(slotptr(set->page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1962 slotptr(set->page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1963 slotptr(set->page, idx)->off = off;
1967 // install fence key for smaller key page
1969 memset(set->page->fence, 0, 256);
1970 memcpy(set->page->fence, key, key->len + 1);
1972 bt_putid(set->page->right, right);
1973 set->page->min = nxt;
1974 set->page->cnt = idx;
1976 // if current page is the root page, split it
1978 if( set->page_no == ROOT_page )
1979 return bt_splitroot (bt, set, right);
1981 if( bt_update (bt, set->page, set->page_no) )
1984 if( bt_unlockpage (bt, set->page_no, BtLockWrite) )
1987 // insert new fences in their parent pages
1990 if( bt_lockpage (bt, set->page_no, BtLockParent) )
1993 if( bt_lockpage (bt, set->page_no, BtLockWrite) )
1996 if( bt_mappage (bt, &set->page, set->page_no) )
1999 memcpy (fencekey, set->page->fence, 256);
2000 right = bt_getid (set->page->right);
2002 if( set->page->posted ) {
2003 if( bt_unlockpage (bt, set->page_no, BtLockParent) )
2006 return bt_unlockpage (bt, set->page_no, BtLockWrite);
2009 set->page->posted = 1;
2011 if( bt_update (bt, set->page, set->page_no) )
2014 if( bt_unlockpage (bt, set->page_no, BtLockWrite) )
2017 if( bt_insertkey (bt, fencekey+1, *fencekey, lvl+1, set->page_no, time(NULL)) )
2020 if( bt_unlockpage (bt, set->page_no, BtLockParent) )
2023 if( !(set->page_no = right) )
2030 // Insert new key into the btree at requested level.
2032 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod)
2038 set->page = bt->page;
2041 if( slot = bt_loadpage (bt, set, key, len, lvl, BtLockWrite) )
2042 ptr = keyptr(set->page, slot);
2046 bt->err = BTERR_ovflw;
2050 // if key already exists, update id and return
2052 if( slot <= set->page->cnt )
2053 if( !keycmp (ptr, key, len) ) {
2054 if( slotptr(set->page, slot)->dead )
2057 slotptr(set->page, slot)->dead = 0;
2058 slotptr(set->page, slot)->tod = tod;
2059 bt_putid(slotptr(set->page,slot)->id, id);
2061 if ( bt_update(bt, set->page, set->page_no) )
2064 return bt_unlockpage(bt, set->page_no, BtLockWrite);
2067 // check if page has enough space
2069 if( slot = bt_cleanpage (bt, set->page, len, slot) )
2072 if( bt_splitpage (bt, set) )
2076 // calculate next available slot and copy key into page
2078 set->page->min -= len + 1; // reset lowest used offset
2079 ((unsigned char *)set->page)[set->page->min] = len;
2080 memcpy ((unsigned char *)set->page + set->page->min +1, key, len );
2082 for( idx = slot; idx <= set->page->cnt; idx++ )
2083 if( slotptr(set->page, idx)->dead )
2086 // now insert key into array before slot
2088 if( idx > set->page->cnt )
2094 *slotptr(set->page, idx) = *slotptr(set->page, idx -1), idx--;
2096 bt_putid(slotptr(set->page,slot)->id, id);
2097 slotptr(set->page, slot)->off = set->page->min;
2098 slotptr(set->page, slot)->tod = tod;
2099 slotptr(set->page, slot)->dead = 0;
2101 if( bt_update(bt, set->page, set->page_no) )
2104 return bt_unlockpage(bt, set->page_no, BtLockWrite);
2107 // cache page of keys into cursor and return starting slot for given key
2109 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2114 set->page = bt->page;
2116 // cache page for retrieval
2117 if( slot = bt_loadpage (bt, set, key, len, 0, BtLockRead) )
2118 memcpy (bt->cursor, set->page, bt->page_size);
2120 bt->cursor_page = set->page_no;
2122 if ( bt_unlockpage(bt, set->page_no, BtLockRead) )
2128 // return next slot for cursor page
2129 // or slide cursor right into next page
2131 uint bt_nextkey (BtDb *bt, uint slot)
2137 right = bt_getid(bt->cursor->right);
2138 while( slot++ < bt->cursor->cnt )
2139 if( slotptr(bt->cursor,slot)->dead )
2141 else if( right || (slot < bt->cursor->cnt)) // skip infinite stopper
2149 bt->cursor_page = right;
2150 set->page = bt->page;
2152 if( bt_lockpage(bt, right, BtLockRead) )
2155 if( bt_mappage (bt, &set->page, right) )
2158 memcpy (bt->cursor, set->page, bt->page_size);
2160 if( bt_unlockpage(bt, right, BtLockRead) )
2169 BtKey bt_key(BtDb *bt, uint slot)
2171 return keyptr(bt->cursor, slot);
2174 uid bt_uid(BtDb *bt, uint slot)
2176 return bt_getid(slotptr(bt->cursor,slot)->id);
2179 uint bt_tod(BtDb *bt, uint slot)
2181 return slotptr(bt->cursor,slot)->tod;
2186 // standalone program to index file of keys
2187 // then list them onto std-out
2189 int main (int argc, char **argv)
2191 uint slot, line = 0, off = 0, found = 0;
2192 int dead, ch, cnt = 0, bits = 12;
2193 unsigned char key[256];
2194 clock_t done, start;
2205 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]);
2206 fprintf (stderr, " page_bits: size of btree page in bits\n");
2207 fprintf (stderr, " mapped_pool_segments: size of buffer pool in segments\n");
2208 fprintf (stderr, " pages_per_segment: size of buffer pool segment in pages in bits\n");
2216 bits = atoi(argv[4]);
2219 map = atoi(argv[5]);
2222 fprintf (stderr, "Warning: buffer_pool > 65536 segments\n");
2224 if( map && map < 8 )
2225 fprintf (stderr, "Buffer_pool too small\n");
2228 pgblk = atoi(argv[6]);
2230 if( bits + pgblk > 30 )
2231 fprintf (stderr, "Warning: very large buffer pool segment size\n");
2234 off = atoi(argv[7]);
2236 bt = bt_open ((argv[1]), BT_rw, bits, map, pgblk);
2239 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2243 switch(argv[3][0]| 0x20)
2246 fprintf(stderr, "started indexing for %s\n", argv[2]);
2247 if( argc > 2 && (in = fopen (argv[2], "rb")) )
2248 while( ch = getc(in), ch != EOF )
2252 sprintf((char *)key+len, "%.9d", line + off), len += 9;
2254 if( bt_insertkey (bt, key, len, 0, ++line, *tod) )
2255 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2258 else if( len < 245 )
2260 fprintf(stderr, "finished adding keys, %d \n", line);
2264 fprintf(stderr, "started deleting keys for %s\n", argv[2]);
2265 if( argc > 2 && (in = fopen (argv[2], "rb")) )
2266 while( ch = getc(in), ch != EOF )
2270 sprintf((char *)key+len, "%.9d", line + off), len += 9;
2272 if( bt_deletekey (bt, key, len) )
2273 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2276 else if( len < 245 )
2278 fprintf(stderr, "finished deleting keys, %d \n", line);
2282 fprintf(stderr, "started finding keys for %s\n", argv[2]);
2283 if( argc > 2 && (in = fopen (argv[2], "rb")) )
2284 while( ch = getc(in), ch != EOF )
2288 sprintf((char *)key+len, "%.9d", line + off), len += 9;
2290 if( bt_findkey (bt, key, len) )
2293 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2296 else if( len < 245 )
2298 fprintf(stderr, "finished search of %d keys, found %d\n", line, found);
2308 fprintf(stderr, " Time to complete: %.2f seconds\n", (float)(done - start) / CLOCKS_PER_SEC);
2313 fprintf(stderr, "started reading\n");
2315 if( slot = bt_startkey (bt, key, len) )
2318 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
2320 while( slot = bt_nextkey (bt, slot) )
2322 ptr = bt_key(bt, slot);
2323 fwrite (ptr->key, ptr->len, 1, stdout);
2324 fputc ('\n', stdout);
2327 fprintf(stderr, " Total keys read %d\n", cnt);