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
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
62 #define BT_fl 0x6c66 // fl
64 #define BT_maxbits 24 // maximum page size in bits
65 #define BT_minbits 9 // minimum page size in bits
66 #define BT_minpage (1 << BT_minbits) // minimum page size
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 2 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
100 uint off:BT_maxbits; // page offset for key start
101 uint dead:1; // set for deleted key
102 uint tod; // time-stamp for key
103 unsigned char id[BtId]; // id associated with key
106 // The key structure occupies space at the upper end of
107 // each page. It's a length byte followed by the value
112 unsigned char key[0];
115 // The first part of an index page.
116 // It is immediately followed
117 // by the BtSlot array of keys.
119 typedef struct BtPage_ {
120 uint cnt; // count of keys in page
121 uint act; // count of active keys
122 uint min; // next key offset
123 unsigned char bits:7; // page size in bits
124 unsigned char free:1; // page is on free list
125 unsigned char lvl:4; // level of page
126 unsigned char kill:1; // page is empty
127 unsigned char dirty:1; // page is dirty
128 unsigned char posted:1; // page fence is posted
129 unsigned char goright:1; // continue to right link
130 unsigned char right[BtId]; // page number to right
131 unsigned char fence[256]; // page fence key
134 // The loadpage interface object
141 // The memory mapping hash table entry
144 BtPage page; // mapped page pointer
145 uid page_no; // mapped page number
146 void *lruprev; // least recently used previous cache block
147 void *lrunext; // lru next cache block
148 void *hashprev; // previous cache block for the same hash idx
149 void *hashnext; // next cache block for the same hash idx
155 // The object structure for Btree access
157 typedef struct _BtDb {
158 uint page_size; // each page size
159 uint page_bits; // each page size in bits
160 uint seg_bits; // segment size in pages in bits
161 uid page_no; // current page number
162 uid cursor_page; // current cursor page number
164 uint mode; // read-write mode
165 uint mapped_io; // use memory mapping
166 BtPage temp; // temporary frame buffer (memory mapped/file IO)
167 BtPage temp2; // temporary frame buffer (memory mapped/file IO)
168 BtPage parent; // current page's parent node (memory mapped/file IO)
169 BtPage alloc; // frame for alloc page (memory mapped/file IO)
170 BtPage cursor; // cached frame for start/next (never mapped)
171 BtPage frame; // spare frame for the page split (never mapped)
172 BtPage zero; // zeroes frame buffer (never mapped)
173 BtPage page; // temporary page (memory mapped/file IO)
179 unsigned char *mem; // frame, cursor, page memory buffer
180 int nodecnt; // highest page cache segment in use
181 int nodemax; // highest page cache segment allocated
182 int hashmask; // number of pages in segments - 1
183 int hashsize; // size of hash table
184 int posted; // last loadpage found posted key
185 int found; // last insert/delete found key
186 BtHash *lrufirst; // lru list head
187 BtHash *lrulast; // lru list tail
188 ushort *cache; // hash table for cached segments
189 BtHash nodes[1]; // segment cache follows
203 extern void bt_close (BtDb *bt);
204 extern BtDb *bt_open (char *name, uint mode, uint bits, uint cacheblk, uint pgblk);
205 extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod);
206 extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len);
207 extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
208 extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
209 extern uint bt_nextkey (BtDb *bt, uint slot);
211 // Internal functions
213 BTERR bt_removepage (BtDb *bt, uid page_no, uint lvl, unsigned char *pagefence);
215 // Helper functions to return slot values
217 extern BtKey bt_key (BtDb *bt, uint slot);
218 extern uid bt_uid (BtDb *bt, uint slot);
219 extern uint bt_tod (BtDb *bt, uint slot);
221 // BTree page number constants
226 // Number of levels to create in a new BTree
230 // The page is allocated from low and hi ends.
231 // The key offsets and row-id's are allocated
232 // from the bottom, while the text of the key
233 // is allocated from the top. When the two
234 // areas meet, the page is split into two.
236 // A key consists of a length byte, two bytes of
237 // index number (0 - 65534), and up to 253 bytes
238 // of key value. Duplicate keys are discarded.
239 // Associated with each key is a 48 bit row-id.
241 // The b-tree root is always located at page 1.
242 // The first leaf page of level zero is always
243 // located on page 2.
245 // The b-tree pages are linked with right
246 // pointers to facilitate enumerators,
247 // and provide for concurrency.
249 // When to root page fills, it is split in two and
250 // the tree height is raised by a new root at page
251 // one with two keys.
253 // Deleted keys are marked with a dead bit until
256 // Groups of pages from the btree are optionally
257 // cached with memory mapping. A hash table is used to keep
258 // track of the cached pages. This behaviour is controlled
259 // by the number of cache blocks parameter and pages per block
262 // To achieve maximum concurrency one page is locked at a time
263 // as the tree is traversed to find leaf key in question. The right
264 // page numbers are used in cases where the page is being split,
267 // Page 0 is dedicated to lock for new page extensions,
268 // and chains empty pages together for reuse.
270 // Parent locks are obtained to prevent resplitting or deleting a node
271 // before its fence is posted into its upper level.
273 // Empty nodes are chained together through the ALLOC page and reused.
275 // A special open mode of BT_fl is provided to safely access files on
276 // WIN32 networks. WIN32 network operations should not use memory mapping.
277 // This WIN32 mode sets FILE_FLAG_NOBUFFERING and FILE_FLAG_WRITETHROUGH
278 // to prevent local caching of network file contents.
280 // Access macros to address slot and key values from the page.
281 // Page slots use 1 based indexing.
283 #define slotptr(page, slot) (((BtSlot *)(page+1)) + (slot-1))
284 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
286 void bt_putid(unsigned char *dest, uid id)
291 dest[i] = (unsigned char)id, id >>= 8;
294 uid bt_getid(unsigned char *src)
299 for( i = 0; i < BtId; i++ )
300 id <<= 8, id |= *src++;
305 // place write, read, or parent lock on requested page_no.
307 BTERR bt_lockpage(BtDb *bt, uid page_no, BtLock mode)
309 off64_t off = page_no << bt->page_bits;
311 int flag = PROT_READ | ( bt->mode == BT_ro ? 0 : PROT_WRITE );
312 struct flock lock[1];
318 if( mode == BtLockRead || mode == BtLockWrite )
319 off += 1 * sizeof(*bt->page); // use second segment
321 if( mode == BtLockParent )
322 off += 2 * sizeof(*bt->page); // use third segment
325 memset (lock, 0, sizeof(lock));
328 lock->l_type = (mode == BtLockDelete || mode == BtLockWrite || mode == BtLockParent) ? F_WRLCK : F_RDLCK;
329 lock->l_len = sizeof(*bt->page);
332 if( fcntl (bt->idx, F_SETLKW, lock) < 0 )
333 return bt->err = BTERR_lock;
337 memset (ovl, 0, sizeof(ovl));
338 ovl->OffsetHigh = (uint)(off >> 32);
339 ovl->Offset = (uint)off;
340 len = sizeof(*bt->page);
342 // use large offsets to
343 // simulate advisory locking
345 ovl->OffsetHigh |= 0x80000000;
347 if( mode == BtLockDelete || mode == BtLockWrite || mode == BtLockParent )
348 flags |= LOCKFILE_EXCLUSIVE_LOCK;
350 if( LockFileEx (bt->idx, flags, 0, len, 0L, ovl) )
353 return bt->err = BTERR_lock;
357 // remove write, read, or parent lock on requested page_no.
359 BTERR bt_unlockpage(BtDb *bt, uid page_no, BtLock mode)
361 off64_t off = page_no << bt->page_bits;
363 struct flock lock[1];
369 if( mode == BtLockRead || mode == BtLockWrite )
370 off += 1 * sizeof(*bt->page); // use second segment
372 if( mode == BtLockParent )
373 off += 2 * sizeof(*bt->page); // use third segment
376 memset (lock, 0, sizeof(lock));
379 lock->l_type = F_UNLCK;
380 lock->l_len = sizeof(*bt->page);
383 if( fcntl (bt->idx, F_SETLK, lock) < 0 )
384 return bt->err = BTERR_lock;
386 memset (ovl, 0, sizeof(ovl));
387 ovl->OffsetHigh = (uint)(off >> 32);
388 ovl->Offset = (uint)off;
389 len = sizeof(*bt->page);
391 // use large offsets to
392 // simulate advisory locking
394 ovl->OffsetHigh |= 0x80000000;
396 if( !UnlockFileEx (bt->idx, 0, len, 0, ovl) )
397 return GetLastError(), bt->err = BTERR_lock;
403 // close and release memory
405 void bt_close (BtDb *bt)
409 // release mapped pages
411 if( hash = bt->lrufirst )
412 do munmap (hash->page, (bt->hashmask+1) << bt->page_bits);
413 while(hash = hash->lrunext);
421 if( hash = bt->lrufirst )
424 FlushViewOfFile(hash->page, 0);
425 UnmapViewOfFile(hash->page);
426 CloseHandle(hash->hmap);
427 } while(hash = hash->lrunext);
430 VirtualFree (bt->mem, 0, MEM_RELEASE);
431 FlushFileBuffers(bt->idx);
432 CloseHandle(bt->idx);
433 GlobalFree (bt->cache);
438 // open/create new btree
439 // call with file_name, BT_openmode, bits in page size (e.g. 16),
440 // size of mapped page cache (e.g. 8192) or zero for no mapping.
442 BtDb *bt_open (char *name, uint mode, uint bits, uint nodemax, uint pgblk)
444 uint lvl, attr, cacheblk, last;
445 BtLock lockmode = BtLockWrite;
452 SYSTEM_INFO sysinfo[1];
456 bt = malloc (sizeof(BtDb) + nodemax * sizeof(BtHash));
457 memset (bt, 0, sizeof(BtDb));
459 switch (mode & 0x7fff)
463 bt->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
468 bt->idx = open ((char*)name, O_RDONLY);
469 lockmode = BtLockRead;
473 return free(bt), NULL;
476 cacheblk = 4096; // page size for unix
481 bt = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtDb) + nodemax * sizeof(BtHash));
482 attr = FILE_ATTRIBUTE_NORMAL;
483 switch (mode & 0x7fff)
486 attr |= FILE_FLAG_WRITE_THROUGH | FILE_FLAG_NO_BUFFERING;
489 bt->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
494 bt->idx = CreateFile(name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, attr, NULL);
495 lockmode = BtLockRead;
498 if( bt->idx == INVALID_HANDLE_VALUE )
499 return GlobalFree(bt), NULL;
501 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
502 GetSystemInfo(sysinfo);
505 cacheblk = sysinfo->dwAllocationGranularity;
510 // determine sanity of page size
512 if( bits > BT_maxbits )
514 else if( bits < BT_minbits )
517 if ( bt_lockpage(bt, ALLOC_page, lockmode) )
518 return bt_close (bt), NULL;
523 // read minimum page size to get root info
525 if( size = lseek (bt->idx, 0L, 2) ) {
526 alloc = malloc (BT_minpage);
527 pread(bt->idx, alloc, BT_minpage, 0);
530 } else if( mode == BT_ro )
531 return bt_close (bt), NULL;
533 size = GetFileSize(bt->idx, amt);
536 alloc = VirtualAlloc(NULL, BT_minpage, MEM_COMMIT, PAGE_READWRITE);
537 if( !ReadFile(bt->idx, (char *)alloc, BT_minpage, amt, NULL) )
538 return bt_close (bt), NULL;
540 VirtualFree (alloc, 0, MEM_RELEASE);
541 } else if( mode == BT_ro )
542 return bt_close (bt), NULL;
545 bt->page_size = 1 << bits;
546 bt->page_bits = bits;
548 bt->nodemax = nodemax;
551 // setup cache mapping
554 if( cacheblk < bt->page_size )
555 cacheblk = bt->page_size;
557 bt->hashsize = nodemax / 8;
558 bt->hashmask = (cacheblk >> bits) - 1;
562 // requested number of pages per memmap segment
565 if( (1 << pgblk) > bt->hashmask )
566 bt->hashmask = (1 << pgblk) - 1;
570 while( (1 << bt->seg_bits) <= bt->hashmask )
574 bt->mem = malloc (8 *bt->page_size);
575 bt->cache = calloc (bt->hashsize, sizeof(ushort));
577 bt->mem = VirtualAlloc(NULL, 8 * bt->page_size, MEM_COMMIT, PAGE_READWRITE);
578 bt->cache = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, bt->hashsize * sizeof(ushort));
580 bt->frame = (BtPage)bt->mem;
581 bt->cursor = (BtPage)(bt->mem + bt->page_size);
582 bt->page = (BtPage)(bt->mem + 2 * bt->page_size);
583 bt->alloc = (BtPage)(bt->mem + 3 * bt->page_size);
584 bt->temp = (BtPage)(bt->mem + 4 * bt->page_size);
585 bt->temp2 = (BtPage)(bt->mem + 5 * bt->page_size);
586 bt->parent = (BtPage)(bt->mem + 6 * bt->page_size);
587 bt->zero = (BtPage)(bt->mem + 7 * bt->page_size);
590 if ( bt_unlockpage(bt, ALLOC_page, lockmode) )
591 return bt_close (bt), NULL;
596 // initializes an empty b-tree with root page and page of leaves
598 memset (bt->alloc, 0, bt->page_size);
599 bt_putid(bt->alloc->right, MIN_lvl+1);
600 bt->alloc->bits = bt->page_bits;
603 if( write (bt->idx, bt->alloc, bt->page_size) < bt->page_size )
604 return bt_close (bt), NULL;
606 if( !WriteFile (bt->idx, (char *)bt->alloc, bt->page_size, amt, NULL) )
607 return bt_close (bt), NULL;
609 if( *amt < bt->page_size )
610 return bt_close (bt), NULL;
613 memset (bt->frame, 0, bt->page_size);
614 bt->frame->bits = bt->page_bits;
615 bt->frame->posted = 1;
617 for( lvl=MIN_lvl; lvl--; ) {
618 slotptr(bt->frame, 1)->off = offsetof(struct BtPage_, fence);
619 bt_putid(slotptr(bt->frame, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
620 bt->frame->fence[0] = 2;
621 bt->frame->fence[1] = 0xff;
622 bt->frame->fence[2] = 0xff;
623 bt->frame->min = bt->page_size;
624 bt->frame->lvl = lvl;
628 if( write (bt->idx, bt->frame, bt->page_size) < bt->page_size )
629 return bt_close (bt), NULL;
631 if( !WriteFile (bt->idx, (char *)bt->frame, bt->page_size, amt, NULL) )
632 return bt_close (bt), NULL;
634 if( *amt < bt->page_size )
635 return bt_close (bt), NULL;
639 // create empty page area by writing last page of first
640 // cache area (other pages are zeroed by O/S)
642 if( bt->mapped_io && bt->hashmask ) {
643 memset(bt->frame, 0, bt->page_size);
646 while( last < MIN_lvl + 1 )
647 last += bt->hashmask + 1;
649 pwrite(bt->idx, bt->frame, bt->page_size, last << bt->page_bits);
651 SetFilePointer (bt->idx, last << bt->page_bits, NULL, FILE_BEGIN);
652 if( !WriteFile (bt->idx, (char *)bt->frame, bt->page_size, amt, NULL) )
653 return bt_close (bt), NULL;
654 if( *amt < bt->page_size )
655 return bt_close (bt), NULL;
659 if( bt_unlockpage(bt, ALLOC_page, lockmode) )
660 return bt_close (bt), NULL;
665 // compare two keys, returning > 0, = 0, or < 0
666 // as the comparison value
668 int keycmp (BtKey key1, unsigned char *key2, uint len2)
670 uint len1 = key1->len;
673 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
684 // Update current page of btree by writing file contents
685 // or flushing mapped area to disk.
687 BTERR bt_update (BtDb *bt, BtPage page, uid page_no)
689 off64_t off = page_no << bt->page_bits;
692 if ( !bt->mapped_io )
693 if ( pwrite(bt->idx, page, bt->page_size, off) != bt->page_size )
694 return bt->err = BTERR_wrt;
697 if ( !bt->mapped_io )
699 SetFilePointer (bt->idx, (long)off, (long*)(&off)+1, FILE_BEGIN);
700 if( !WriteFile (bt->idx, (char *)page, bt->page_size, amt, NULL) )
701 return GetLastError(), bt->err = BTERR_wrt;
703 if( *amt < bt->page_size )
704 return GetLastError(), bt->err = BTERR_wrt;
706 else if ( bt->mode == BT_fl ) {
707 FlushViewOfFile(page, bt->page_size);
708 FlushFileBuffers(bt->idx);
714 // find page in cache
716 BtHash *bt_findhash(BtDb *bt, uid page_no)
721 // compute cache block first page and hash idx
723 page_no &= ~bt->hashmask;
724 idx = (uint)(page_no >> bt->seg_bits) % bt->hashsize;
727 hash = bt->nodes + bt->cache[idx];
731 do if( hash->page_no == page_no )
733 while(hash = hash->hashnext );
738 // add page cache entry to hash index
740 void bt_linkhash(BtDb *bt, BtHash *node, uid page_no)
742 uint idx = (uint)(page_no >> bt->seg_bits) % bt->hashsize;
745 if( bt->cache[idx] ) {
746 node->hashnext = hash = bt->nodes + bt->cache[idx];
747 hash->hashprev = node;
750 node->hashprev = NULL;
751 bt->cache[idx] = (ushort)(node - bt->nodes);
754 // remove cache entry from hash table
756 void bt_unlinkhash(BtDb *bt, BtHash *node)
758 uint idx = (uint)(node->page_no >> bt->seg_bits) % bt->hashsize;
762 if( hash = node->hashprev )
763 hash->hashnext = node->hashnext;
764 else if( hash = node->hashnext )
765 bt->cache[idx] = (ushort)(hash - bt->nodes);
769 if( hash = node->hashnext )
770 hash->hashprev = node->hashprev;
773 // add cache page to lru chain and map pages
775 BtPage bt_linklru(BtDb *bt, BtHash *hash, uid page_no)
778 off64_t off = (page_no & ~bt->hashmask) << bt->page_bits;
779 off64_t limit = off + ((bt->hashmask+1) << bt->page_bits);
782 memset(hash, 0, sizeof(BtHash));
783 hash->page_no = (page_no & ~bt->hashmask);
784 bt_linkhash(bt, hash, page_no);
786 if( node = hash->lrunext = bt->lrufirst )
787 node->lruprev = hash;
794 flag = PROT_READ | ( bt->mode == BT_ro ? 0 : PROT_WRITE );
795 hash->page = (BtPage)mmap (0, (bt->hashmask+1) << bt->page_bits, flag, MAP_SHARED, bt->idx, off);
796 if( hash->page == MAP_FAILED )
797 return bt->err = BTERR_map, (BtPage)NULL;
800 flag = ( bt->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
801 hash->hmap = CreateFileMapping(bt->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
803 return bt->err = BTERR_map, NULL;
805 flag = ( bt->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
806 hash->page = MapViewOfFile(hash->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->hashmask+1) << bt->page_bits);
808 return bt->err = BTERR_map, NULL;
811 return (BtPage)((char*)hash->page + ((uint)(page_no & bt->hashmask) << bt->page_bits));
814 // find or place requested page in page-cache
815 // return memory address where page is located.
817 BtPage bt_hashpage(BtDb *bt, uid page_no)
819 BtHash *hash, *node, *next;
822 // find page in cache and move to top of lru list
824 if( hash = bt_findhash(bt, page_no) ) {
825 page = (BtPage)((char*)hash->page + ((uint)(page_no & bt->hashmask) << bt->page_bits));
826 // swap node in lru list
827 if( node = hash->lruprev ) {
828 if( next = node->lrunext = hash->lrunext )
829 next->lruprev = node;
833 if( next = hash->lrunext = bt->lrufirst )
834 next->lruprev = hash;
836 return bt->err = BTERR_hash, (BtPage)NULL;
838 hash->lruprev = NULL;
844 // map pages and add to cache entry
846 if( bt->nodecnt < bt->nodemax ) {
847 hash = bt->nodes + ++bt->nodecnt;
848 return bt_linklru(bt, hash, page_no);
851 // hash table is already full, replace last lru entry from the cache
853 if( hash = bt->lrulast ) {
854 // unlink from lru list
855 if( node = bt->lrulast = hash->lruprev )
856 node->lrunext = NULL;
858 return bt->err = BTERR_hash, (BtPage)NULL;
861 munmap (hash->page, (bt->hashmask+1) << bt->page_bits);
863 FlushViewOfFile(hash->page, 0);
864 UnmapViewOfFile(hash->page);
865 CloseHandle(hash->hmap);
867 // unlink from hash table
869 bt_unlinkhash(bt, hash);
871 // map and add to cache
873 return bt_linklru(bt, hash, page_no);
876 return bt->err = BTERR_hash, (BtPage)NULL;
879 // map a btree page onto current page
881 BTERR bt_mappage (BtDb *bt, BtPage *page, uid page_no)
883 off64_t off = page_no << bt->page_bits;
888 if( bt->mapped_io ) {
890 *page = bt_hashpage(bt, page_no);
894 if ( pread(bt->idx, *page, bt->page_size, off) < bt->page_size )
895 return bt->err = BTERR_map;
897 SetFilePointer (bt->idx, (long)off, (long*)(&off)+1, FILE_BEGIN);
899 if( !ReadFile(bt->idx, *page, bt->page_size, amt, NULL) )
900 return bt->err = BTERR_map;
902 if( *amt < bt->page_size )
903 return bt->err = BTERR_map;
908 // allocate a new page and write page into it
910 uid bt_newpage(BtDb *bt, BtPage page)
918 if ( bt_lockpage(bt, ALLOC_page, BtLockWrite) )
921 if( bt_mappage (bt, &bt->alloc, ALLOC_page) )
924 // use empty chain first
925 // else allocate empty page
927 if( new_page = bt_getid(bt->alloc[1].right) ) {
928 if( bt_mappage (bt, &bt->temp, new_page) )
929 return 0; // don't unlock on error
930 memcpy(bt->alloc[1].right, bt->temp->right, BtId);
933 new_page = bt_getid(bt->alloc->right);
934 bt_putid(bt->alloc->right, new_page+1);
938 if( bt_update(bt, bt->alloc, ALLOC_page) )
939 return 0; // don't unlock on error
941 if( !bt->mapped_io ) {
942 if( bt_update(bt, page, new_page) )
943 return 0; //don't unlock on error
947 if ( bt_unlockpage(bt, ALLOC_page, BtLockWrite) )
954 if ( pwrite(bt->idx, page, bt->page_size, new_page << bt->page_bits) < bt->page_size )
955 return bt->err = BTERR_wrt, 0;
957 // if writing first page of hash block, zero last page in the block
959 if ( !reuse && bt->hashmask > 0 && (new_page & bt->hashmask) == 0 )
961 // use temp buffer to write zeros
962 memset(bt->zero, 0, bt->page_size);
963 if ( pwrite(bt->idx,bt->zero, bt->page_size, (new_page | bt->hashmask) << bt->page_bits) < bt->page_size )
964 return bt->err = BTERR_wrt, 0;
967 // bring new page into page-cache and copy page.
968 // this will extend the file into the new pages.
970 if( !(pmap = (char*)bt_hashpage(bt, new_page & ~bt->hashmask)) )
973 memcpy(pmap+((new_page & bt->hashmask) << bt->page_bits), page, bt->page_size);
978 if ( bt_unlockpage(bt, ALLOC_page, BtLockWrite) )
984 // find slot in page for given key at a given level
985 // return 0 if beyond fence value
987 int bt_findslot (BtPageSet *set, unsigned char *key, uint len)
989 uint diff, higher = set->page->cnt, low = 1, slot;
991 // make stopper key an infinite fence value
993 if( bt_getid (set->page->right) )
996 // low is the lowest candidate, higher is already
997 // tested as .ge. the given key, loop ends when they meet
999 while( diff = higher - low ) {
1000 slot = low + ( diff >> 1 );
1001 if( keycmp (keyptr(set->page, slot), key, len) < 0 )
1007 if( higher <= set->page->cnt )
1010 // if leaf page, compare against fence value
1012 // return zero if key is on right link page
1013 // or return slot beyond last key
1015 if( set->page->lvl || keycmp ((BtKey)set->page->fence, key, len) < 0 )
1021 // find and load page at given level for given key
1022 // leave page rd or wr locked as requested
1024 int bt_loadpage (BtDb *bt, BtPageSet *set, unsigned char *key, uint len, uint lvl, uint lock)
1026 uid page_no = ROOT_page, prevpage = 0;
1027 uint drill = 0xff, slot;
1028 uint mode, prevmode;
1030 // start at root of btree and drill down
1033 // determine lock mode of drill level
1034 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1036 set->page_no = page_no;
1038 // obtain access lock using lock chaining
1040 if( page_no > ROOT_page )
1041 if( bt_lockpage(bt, page_no, BtLockAccess) )
1045 if( bt_unlockpage(bt, prevpage, prevmode) )
1048 // obtain read lock using lock chaining
1050 if( bt_lockpage(bt, page_no, mode) )
1053 if( page_no > ROOT_page )
1054 if( bt_unlockpage(bt, page_no, BtLockAccess) )
1057 // map/obtain page contents
1059 if( bt_mappage (bt, &set->page, page_no) )
1062 // re-read and re-lock root after determining actual level of root
1064 if( set->page->lvl != drill) {
1065 if ( page_no != ROOT_page )
1066 return bt->err = BTERR_struct, 0;
1068 drill = set->page->lvl;
1070 if( lock == BtLockWrite && drill == lvl )
1071 if( bt_unlockpage(bt, page_no, mode) )
1080 // if page is being deleted and we should continue right
1082 if( set->page->kill && set->page->goright ) {
1083 page_no = bt_getid (set->page->right);
1087 // otherwise, wait for deleted node to clear
1089 if( set->page->kill ) {
1090 if( bt_unlockpage(bt, set->page_no, mode) )
1092 page_no = ROOT_page;
1103 // find key on page at this level
1104 // and descend to requested level
1106 if( slot = bt_findslot (set, key, len) ) {
1110 if( slot > set->page->cnt )
1111 return bt->err = BTERR_struct, 0;
1113 // if drilling down, find next active key
1115 while( slotptr(set->page, slot)->dead )
1116 if( slot++ < set->page->cnt )
1119 return bt->err = BTERR_struct, 0;
1121 page_no = bt_getid(slotptr(set->page, slot)->id);
1126 // or slide right into next page
1127 // (slide left from deleted page)
1129 page_no = bt_getid(set->page->right);
1133 // return error on end of right chain
1135 bt->err = BTERR_struct;
1136 return 0; // return error
1139 // drill down fixing fence values for left sibling tree
1141 // call with set write locked mapped to bt->temp
1142 // return with set unlocked & unpinned.
1144 BTERR bt_fixfences (BtDb *bt, BtPageSet *set, unsigned char *newfence)
1146 unsigned char oldfence[256];
1151 next->page_no = bt_getid(slotptr(set->page, set->page->cnt)->id);
1152 memcpy (oldfence, set->page->fence, 256);
1153 next->page = bt->temp2;
1154 bt->temp2 = bt->temp;
1155 bt->temp = next->page;
1157 while( !set->page->kill && set->page->lvl ) {
1158 if( bt_lockpage (bt, next->page_no, BtLockParent) )
1160 if( bt_lockpage (bt, next->page_no, BtLockAccess) )
1162 if( bt_lockpage (bt, next->page_no, BtLockWrite) )
1164 if( bt_unlockpage (bt, next->page_no, BtLockAccess) )
1167 if( bt_mappage (bt, &next->page, next->page_no) )
1170 chk = keycmp ((BtKey)next->page->fence, oldfence + 1, *oldfence);
1173 right = bt_getid (next->page->right);
1174 if( bt_unlockpage (bt, next->page_no, BtLockWrite) )
1176 if( bt_unlockpage (bt, next->page_no, BtLockParent) )
1178 next->page_no = right;
1183 return bt->err = BTERR_struct;
1185 if( bt_fixfences (bt, next, newfence) )
1191 set->page = bt->temp;
1193 if( bt_mappage (bt, &set->page, set->page_no) )
1196 memcpy (set->page->fence, newfence, 256);
1198 if( bt_update(bt, set->page, set->page_no) )
1200 if( bt_unlockpage (bt, set->page_no, BtLockWrite) )
1202 if( bt_unlockpage (bt, set->page_no, BtLockParent) )
1208 // return page to free list
1209 // page must be delete & write locked
1211 BTERR bt_freepage (BtDb *bt, BtPageSet *set)
1213 // lock & map allocation page
1215 if( bt_lockpage (bt, ALLOC_page, BtLockWrite) )
1218 if( bt_mappage (bt, &bt->alloc, ALLOC_page) )
1221 // store chain in second right
1222 bt_putid(set->page->right, bt_getid(bt->alloc[1].right));
1223 bt_putid(bt->alloc[1].right, set->page_no);
1224 set->page->free = 1;
1226 if( bt_update(bt, bt->alloc, ALLOC_page) )
1228 if( bt_update(bt, set->page, set->page_no) )
1233 if( bt_unlockpage(bt, ALLOC_page, BtLockWrite) )
1236 // remove write lock on deleted node
1238 if( bt_unlockpage(bt, set->page_no, BtLockWrite) )
1241 return bt_unlockpage (bt, set->page_no, BtLockDelete);
1244 // remove the root level by promoting its only child
1246 BTERR bt_removeroot (BtDb *bt, BtPageSet *root, BtPageSet *child)
1252 if( bt_lockpage (bt, next, BtLockDelete) )
1254 if( bt_lockpage (bt, next, BtLockWrite) )
1257 if( bt_mappage (bt, &child->page, next) )
1260 child->page_no = next;
1263 memcpy (root->page, child->page, bt->page_size);
1264 next = bt_getid (slotptr(child->page, child->page->cnt)->id);
1266 if( bt_freepage (bt, child) )
1268 } while( root->page->lvl > 1 && root->page->cnt == 1 );
1270 if( bt_update (bt, root->page, ROOT_page) )
1273 return bt_unlockpage (bt, ROOT_page, BtLockWrite);
1276 // pull right page over ourselves in simple merge
1278 BTERR bt_mergeright (BtDb *bt, BtPageSet *set, BtPageSet *parent, BtPageSet *right, uint slot, uint idx)
1280 // install ourselves as child page
1281 // and delete ourselves from parent
1283 bt_putid (slotptr(parent->page, idx)->id, set->page_no);
1284 slotptr(parent->page, slot)->dead = 1;
1285 parent->page->act--;
1287 // collapse any empty slots
1289 while( idx = parent->page->cnt - 1 )
1290 if( slotptr(parent->page, idx)->dead ) {
1291 *slotptr(parent->page, idx) = *slotptr(parent->page, idx + 1);
1292 memset (slotptr(parent->page, parent->page->cnt--), 0, sizeof(BtSlot));
1296 memcpy (set->page, right->page, bt->page_size);
1298 if( bt_unlockpage (bt, right->page_no, BtLockParent) )
1301 if( bt_freepage (bt, right) )
1304 // do we need to remove a btree level?
1305 // (leave the first page of leaves alone)
1307 if( parent->page_no == ROOT_page && parent->page->cnt == 1 )
1308 if( set->page->lvl )
1309 return bt_removeroot (bt, parent, set);
1311 if( bt_update (bt, parent->page, parent->page_no) )
1314 if( bt_unlockpage (bt, parent->page_no, BtLockWrite) )
1317 if( bt_update (bt, set->page, set->page_no) )
1320 if( bt_unlockpage (bt, set->page_no, BtLockWrite) )
1323 if( bt_unlockpage (bt, set->page_no, BtLockDelete) )
1329 // remove both child and parent from the btree
1330 // from the fence position in the parent
1332 BTERR bt_removeparent (BtDb *bt, BtPageSet *child, BtPageSet *parent, BtPageSet *right, BtPageSet *rparent, uint lvl)
1334 unsigned char pagefence[256];
1337 // pull right sibling over ourselves and unlock
1339 memcpy (child->page, right->page, bt->page_size);
1341 if( bt_update(bt, child->page, child->page_no) )
1344 if( bt_unlockpage (bt, child->page_no, BtLockWrite) )
1347 // install ourselves into right link of old right page
1349 bt_putid (right->page->right, child->page_no);
1350 right->page->goright = 1; // tell bt_loadpage to go right to us
1351 right->page->kill = 1;
1353 if( bt_update(bt, right->page, right->page_no) )
1356 if( bt_unlockpage (bt, right->page_no, BtLockWrite) )
1359 // remove our slot from our parent
1360 // signal to move right
1362 parent->page->goright = 1; // tell bt_findslot to go right to rparent
1363 parent->page->kill = 1;
1364 parent->page->act--;
1366 // redirect right page pointer in right parent to us
1368 for( idx = 0; idx++ < rparent->page->cnt; )
1369 if( !slotptr(rparent->page, idx)->dead )
1372 if( bt_getid (slotptr(rparent->page, idx)->id) != right->page_no )
1373 return bt->err = BTERR_struct;
1375 bt_putid (slotptr(rparent->page, idx)->id, child->page_no);
1377 if( bt_update (bt, rparent->page, rparent->page_no) )
1380 if( bt_unlockpage (bt, rparent->page_no, BtLockWrite) )
1383 // save parent page fence value
1385 memcpy (pagefence, parent->page->fence, 256);
1387 if( bt_update (bt, parent->page, parent->page_no) )
1389 if( bt_unlockpage (bt, parent->page_no, BtLockWrite) )
1392 return bt_removepage (bt, parent->page_no, lvl, pagefence);
1395 // remove page from btree
1396 // call with page unlocked
1397 // returns with page on free list
1399 BTERR bt_removepage (BtDb *bt, uid page_no, uint lvl, unsigned char *pagefence)
1401 BtPageSet parent[1], rparent[1], sibling[1], set[1];
1402 unsigned char newfence[256];
1406 parent->page = bt->parent;
1407 set->page_no = page_no;
1408 set->page = bt->page;
1410 // load and lock our parent
1413 if( !(slot = bt_loadpage (bt, parent, pagefence+1, *pagefence, lvl+1, BtLockWrite)) )
1416 // wait until we are posted in our parent
1418 if( set->page_no != bt_getid (slotptr (parent->page, slot)->id) ) {
1419 if( bt_unlockpage (bt, parent->page_no, BtLockWrite) )
1429 // can we do a simple merge entirely
1430 // between siblings on the parent page?
1432 if( slot < parent->page->cnt ) {
1433 // find our right neighbor
1434 // right must exist because the stopper prevents
1435 // the rightmost page from deleting
1437 for( idx = slot; idx++ < parent->page->cnt; )
1438 if( !slotptr(parent->page, idx)->dead )
1441 sibling->page_no = bt_getid (slotptr (parent->page, idx)->id);
1443 if( bt_lockpage (bt, set->page_no, BtLockDelete) )
1446 if( bt_lockpage (bt, set->page_no, BtLockWrite) )
1449 if( bt_mappage (bt, &set->page, set->page_no) )
1452 // merge right if sibling shows up in
1453 // our parent and is not being killed
1455 if( sibling->page_no == bt_getid (set->page->right) ) {
1456 if( bt_lockpage (bt, sibling->page_no, BtLockParent) )
1459 if( bt_lockpage (bt, sibling->page_no, BtLockDelete) )
1462 if( bt_lockpage (bt, sibling->page_no, BtLockWrite) )
1465 sibling->page = bt->temp;
1467 if( bt_mappage (bt, &sibling->page, sibling->page_no) )
1470 if( !sibling->page->kill )
1471 return bt_mergeright(bt, set, parent, sibling, slot, idx);
1475 if( bt_unlockpage (bt, sibling->page_no, BtLockWrite) )
1479 if( bt_unlockpage (bt, set->page_no, BtLockDelete) )
1482 if( bt_unlockpage (bt, set->page_no, BtLockWrite) )
1485 if( bt_unlockpage (bt, parent->page_no, BtLockWrite) )
1495 // find our left neighbor in our parent page
1497 for( idx = slot; --idx; )
1498 if( !slotptr(parent->page, idx)->dead )
1501 // if no left neighbor, delete ourselves and our parent
1504 if( bt_lockpage (bt, set->page_no, BtLockAccess) )
1507 if( bt_lockpage (bt, set->page_no, BtLockWrite) )
1510 if( bt_unlockpage (bt, set->page_no, BtLockAccess) )
1513 if( bt_mappage (bt, &set->page, set->page_no) )
1516 rparent->page_no = bt_getid (parent->page->right);
1517 rparent->page = bt->temp;
1519 if( bt_lockpage (bt, rparent->page_no, BtLockAccess) )
1522 if( bt_lockpage (bt, rparent->page_no, BtLockWrite) )
1525 if( bt_unlockpage (bt, rparent->page_no, BtLockAccess) )
1528 if( bt_mappage (bt, &rparent->page, rparent->page_no) )
1531 if( !rparent->page->kill ) {
1532 sibling->page_no = bt_getid (set->page->right);
1534 if( bt_lockpage (bt, sibling->page_no, BtLockAccess) )
1537 if( bt_lockpage (bt, sibling->page_no, BtLockWrite) )
1540 if( bt_unlockpage (bt, sibling->page_no, BtLockAccess) )
1543 sibling->page = bt->temp2;
1545 if( bt_mappage (bt, &sibling->page, sibling->page_no) )
1548 if( !sibling->page->kill )
1549 return bt_removeparent (bt, set, parent, sibling, rparent, lvl+1);
1553 if( bt_unlockpage (bt, sibling->page_no, BtLockWrite) )
1557 if( bt_unlockpage (bt, set->page_no, BtLockWrite) )
1560 if( bt_unlockpage (bt, rparent->page_no, BtLockWrite) )
1563 if( bt_unlockpage (bt, parent->page_no, BtLockWrite) )
1573 // redirect parent to our left sibling
1574 // lock and map our left sibling's page
1576 sibling->page_no = bt_getid (slotptr(parent->page, idx)->id);
1577 sibling->page = bt->temp;
1579 // wait our turn on fence key maintenance
1581 if( bt_lockpage(bt, sibling->page_no, BtLockParent) )
1584 if( bt_lockpage(bt, sibling->page_no, BtLockAccess) )
1587 if( bt_lockpage(bt, sibling->page_no, BtLockWrite) )
1590 if( bt_unlockpage(bt, sibling->page_no, BtLockAccess) )
1593 if( bt_mappage (bt, &sibling->page, sibling->page_no) )
1596 // wait until sibling is in our parent
1598 if( bt_getid (sibling->page->right) != set->page_no ) {
1599 if( bt_unlockpage (bt, parent->page_no, BtLockWrite) )
1601 if( bt_unlockpage (bt, sibling->page_no, BtLockWrite) )
1603 if( bt_unlockpage (bt, sibling->page_no, BtLockParent) )
1613 // map page being killed
1615 if( bt_lockpage (bt, set->page_no, BtLockDelete) )
1618 if( bt_lockpage (bt, set->page_no, BtLockWrite) )
1621 if( bt_mappage (bt, &set->page, set->page_no) )
1624 // delete our left sibling from parent
1626 slotptr(parent->page,idx)->dead = 1;
1627 parent->page->dirty = 1;
1628 parent->page->act--;
1630 // redirect our parent slot to our left sibling
1632 bt_putid (slotptr(parent->page, slot)->id, sibling->page_no);
1633 memcpy (sibling->page->right, set->page->right, BtId);
1635 if( bt_update (bt, sibling->page, sibling->page_no) )
1638 // collapse dead slots from parent
1640 while( idx = parent->page->cnt - 1 )
1641 if( slotptr(parent->page, idx)->dead ) {
1642 *slotptr(parent->page, idx) = *slotptr(parent->page, parent->page->cnt);
1643 memset (slotptr(parent->page, parent->page->cnt--), 0, sizeof(BtSlot));
1647 // update parent page
1649 if( bt_update (bt, parent->page, parent->page_no) )
1652 // free our original page
1654 if( bt_freepage (bt, set) )
1657 // go down the left node's fence keys to the leaf level
1658 // and update the fence keys in each page
1660 memcpy (newfence, parent->page->fence, 256);
1662 if( bt_fixfences (bt, sibling, newfence) )
1665 // promote sibling as new root?
1667 if( parent->page_no == ROOT_page && parent->page->cnt == 1 )
1668 if( sibling->page->lvl ) {
1669 if( bt_lockpage (bt, sibling->page_no, BtLockDelete) )
1672 if( bt_lockpage (bt, sibling->page_no, BtLockWrite) )
1675 if( bt_mappage (bt, &sibling->page, set->page_no) )
1678 return bt_removeroot (bt, parent, sibling);
1681 return bt_unlockpage (bt, parent->page_no, BtLockWrite);
1685 // find and delete key on page by marking delete flag bit
1686 // when page becomes empty, delete it
1688 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len)
1690 unsigned char pagefence[256];
1691 uint slot, found, idx;
1695 set->page = bt->page;
1697 if( slot = bt_loadpage (bt, set, key, len, 0, BtLockWrite) )
1698 ptr = keyptr(set->page, slot);
1702 // if key is found delete it, otherwise ignore request
1704 if( found = slot <= set->page->cnt )
1705 if( found = !keycmp (ptr, key, len) )
1706 if( found = slotptr(set->page, slot)->dead == 0 ) {
1707 slotptr(set->page,slot)->dead = 1;
1708 set->page->dirty = 1;
1711 // collapse empty slots
1713 while( idx = set->page->cnt - 1 )
1714 if( slotptr(set->page, idx)->dead ) {
1715 *slotptr(set->page, idx) = *slotptr(set->page, idx + 1);
1716 memset (slotptr(set->page, set->page->cnt--), 0, sizeof(BtSlot));
1721 if( set->page->act ) {
1722 if( bt_update(bt, set->page, set->page_no) )
1725 return bt_unlockpage (bt, set->page_no, BtLockWrite);
1728 // delete page when empty
1730 memcpy (pagefence, set->page->fence, 256);
1731 set->page->kill = 1;
1733 if( bt_update(bt, set->page, set->page_no) )
1736 if( bt_unlockpage(bt, set->page_no, BtLockWrite) )
1739 if( bt_removepage (bt, set->page_no, 0, pagefence) )
1746 // find key in leaf level and return row-id
1748 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1755 set->page = bt->page;
1757 if( slot = bt_loadpage (bt, set, key, len, 0, BtLockRead) )
1758 ptr = keyptr(set->page, slot);
1762 // if key exists, return row-id
1763 // otherwise return 0
1765 if( slot <= set->page->cnt )
1766 if( !keycmp (ptr, key, len) )
1767 id = bt_getid(slotptr(set->page,slot)->id);
1769 if ( bt_unlockpage(bt, set->page_no, BtLockRead) )
1775 // check page for space available,
1776 // clean if necessary and return
1777 // 0 - page needs splitting
1778 // >0 - new slot value
1780 uint bt_cleanpage(BtDb *bt, BtPage page, uint amt, uint slot)
1782 uint nxt = bt->page_size, off;
1783 uint cnt = 0, idx = 0;
1784 uint max = page->cnt;
1788 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1791 // skip cleanup if nothing to reclaim
1796 memcpy (bt->frame, page, bt->page_size);
1798 // skip page info and set rest of page to zero
1800 memset (page+1, 0, bt->page_size - sizeof(*page));
1804 while( cnt++ < max ) {
1807 if( slotptr(bt->frame,cnt)->dead )
1810 off = slotptr(bt->frame,cnt)->off;
1814 if( off >= sizeof(*page) ) {
1815 key = keyptr(bt->frame, cnt);
1816 off = nxt -= key->len + 1;
1817 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1822 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1823 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1824 slotptr(page, idx)->off = off;
1830 if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1836 // split the root and raise the height of the btree
1838 BTERR bt_splitroot(BtDb *bt, BtPageSet *root, uid page_no2)
1840 unsigned char leftkey[256];
1841 uint nxt = bt->page_size;
1844 // Obtain an empty page to use, and copy the current
1845 // root contents into it, e.g. lower keys
1847 memcpy (leftkey, root->page->fence, 256);
1848 root->page->posted = 1;
1850 if( !(new_page = bt_newpage(bt, root->page)) )
1853 // preserve the page info at the bottom
1854 // of higher keys and set rest to zero
1856 memset(root->page+1, 0, bt->page_size - sizeof(*root->page));
1857 memset(root->page->fence, 0, 256);
1858 root->page->fence[0] = 2;
1859 root->page->fence[1] = 0xff;
1860 root->page->fence[2] = 0xff;
1862 // insert new page fence key on newroot page
1864 nxt -= *leftkey + 1;
1865 memcpy ((unsigned char *)root->page + nxt, leftkey, *leftkey + 1);
1866 bt_putid(slotptr(root->page, 1)->id, new_page);
1867 slotptr(root->page, 1)->off = nxt;
1869 // insert stopper key on newroot page
1870 // and increase the root height
1872 bt_putid(slotptr(root->page, 2)->id, page_no2);
1873 slotptr(root->page, 2)->off = offsetof(struct BtPage_, fence);
1875 bt_putid(root->page->right, 0);
1876 root->page->min = nxt; // reset lowest used offset and key count
1877 root->page->cnt = 2;
1878 root->page->act = 2;
1881 // update and release root
1883 if( bt_update(bt, root->page, root->page_no) )
1886 return bt_unlockpage(bt, root->page_no, BtLockWrite);
1889 // split already locked full node
1892 BTERR bt_splitpage (BtDb *bt, BtPageSet *set)
1894 uint cnt = 0, idx = 0, max, nxt = bt->page_size, off;
1895 unsigned char fencekey[256];
1896 uint lvl = set->page->lvl;
1900 // split higher half of keys to bt->frame
1902 memset (bt->frame, 0, bt->page_size);
1903 max = set->page->cnt;
1907 while( cnt++ < max ) {
1908 if( !lvl || cnt < max ) {
1909 key = keyptr(set->page, cnt);
1910 off = nxt -= key->len + 1;
1911 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
1913 off = offsetof(struct BtPage_, fence);
1915 memcpy(slotptr(bt->frame,++idx)->id, slotptr(set->page,cnt)->id, BtId);
1916 slotptr(bt->frame, idx)->tod = slotptr(set->page, cnt)->tod;
1917 slotptr(bt->frame, idx)->off = off;
1921 if( set->page_no == ROOT_page )
1922 bt->frame->posted = 1;
1924 memcpy (bt->frame->fence, set->page->fence, 256);
1925 bt->frame->bits = bt->page_bits;
1926 bt->frame->min = nxt;
1927 bt->frame->cnt = idx;
1928 bt->frame->lvl = lvl;
1932 if( set->page_no > ROOT_page )
1933 memcpy (bt->frame->right, set->page->right, BtId);
1935 // get new free page and write higher keys to it.
1937 if( !(right = bt_newpage(bt, bt->frame)) )
1940 // update lower keys to continue in old page
1942 memcpy (bt->frame, set->page, bt->page_size);
1943 memset (set->page+1, 0, bt->page_size - sizeof(*set->page));
1944 nxt = bt->page_size;
1945 set->page->posted = 0;
1946 set->page->dirty = 0;
1951 // assemble page of smaller keys
1953 while( cnt++ < max / 2 ) {
1954 key = keyptr(bt->frame, cnt);
1956 if( !lvl || cnt < max / 2 ) {
1957 off = nxt -= key->len + 1;
1958 memcpy ((unsigned char *)set->page + nxt, key, key->len + 1);
1960 off = offsetof(struct BtPage_, fence);
1962 memcpy(slotptr(set->page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1963 slotptr(set->page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1964 slotptr(set->page, idx)->off = off;
1968 // install fence key for smaller key page
1970 memset(set->page->fence, 0, 256);
1971 memcpy(set->page->fence, key, key->len + 1);
1973 bt_putid(set->page->right, right);
1974 set->page->min = nxt;
1975 set->page->cnt = idx;
1977 // if current page is the root page, split it
1979 if( set->page_no == ROOT_page )
1980 return bt_splitroot (bt, set, right);
1982 if( bt_update (bt, set->page, set->page_no) )
1985 if( bt_unlockpage (bt, set->page_no, BtLockWrite) )
1988 // insert new fences in their parent pages
1991 if( bt_lockpage (bt, set->page_no, BtLockParent) )
1994 if( bt_lockpage (bt, set->page_no, BtLockWrite) )
1997 if( bt_mappage (bt, &set->page, set->page_no) )
2000 memcpy (fencekey, set->page->fence, 256);
2001 right = bt_getid (set->page->right);
2003 if( set->page->posted ) {
2004 if( bt_unlockpage (bt, set->page_no, BtLockParent) )
2007 return bt_unlockpage (bt, set->page_no, BtLockWrite);
2010 set->page->posted = 1;
2012 if( bt_update (bt, set->page, set->page_no) )
2015 if( bt_unlockpage (bt, set->page_no, BtLockWrite) )
2018 if( bt_insertkey (bt, fencekey+1, *fencekey, lvl+1, set->page_no, time(NULL)) )
2021 if( bt_unlockpage (bt, set->page_no, BtLockParent) )
2024 if( !(set->page_no = right) )
2031 // Insert new key into the btree at requested level.
2033 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod)
2039 set->page = bt->page;
2042 if( slot = bt_loadpage (bt, set, key, len, lvl, BtLockWrite) )
2043 ptr = keyptr(set->page, slot);
2047 bt->err = BTERR_ovflw;
2051 // if key already exists, update id and return
2053 if( slot <= set->page->cnt )
2054 if( !keycmp (ptr, key, len) ) {
2055 if( slotptr(set->page, slot)->dead )
2058 slotptr(set->page, slot)->dead = 0;
2059 slotptr(set->page, slot)->tod = tod;
2060 bt_putid(slotptr(set->page,slot)->id, id);
2062 if ( bt_update(bt, set->page, set->page_no) )
2065 return bt_unlockpage(bt, set->page_no, BtLockWrite);
2068 // check if page has enough space
2070 if( slot = bt_cleanpage (bt, set->page, len, slot) )
2073 if( bt_splitpage (bt, set) )
2077 // calculate next available slot and copy key into page
2079 set->page->min -= len + 1; // reset lowest used offset
2080 ((unsigned char *)set->page)[set->page->min] = len;
2081 memcpy ((unsigned char *)set->page + set->page->min +1, key, len );
2083 for( idx = slot; idx <= set->page->cnt; idx++ )
2084 if( slotptr(set->page, idx)->dead )
2087 // now insert key into array before slot
2089 if( idx > set->page->cnt )
2095 *slotptr(set->page, idx) = *slotptr(set->page, idx -1), idx--;
2097 bt_putid(slotptr(set->page,slot)->id, id);
2098 slotptr(set->page, slot)->off = set->page->min;
2099 slotptr(set->page, slot)->tod = tod;
2100 slotptr(set->page, slot)->dead = 0;
2102 if( bt_update(bt, set->page, set->page_no) )
2105 return bt_unlockpage(bt, set->page_no, BtLockWrite);
2108 // cache page of keys into cursor and return starting slot for given key
2110 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2115 set->page = bt->page;
2117 // cache page for retrieval
2118 if( slot = bt_loadpage (bt, set, key, len, 0, BtLockRead) )
2119 memcpy (bt->cursor, set->page, bt->page_size);
2121 bt->cursor_page = set->page_no;
2123 if ( bt_unlockpage(bt, set->page_no, BtLockRead) )
2129 // return next slot for cursor page
2130 // or slide cursor right into next page
2132 uint bt_nextkey (BtDb *bt, uint slot)
2138 right = bt_getid(bt->cursor->right);
2139 while( slot++ < bt->cursor->cnt )
2140 if( slotptr(bt->cursor,slot)->dead )
2142 else if( right || (slot < bt->cursor->cnt)) // skip infinite stopper
2150 bt->cursor_page = right;
2151 set->page = bt->page;
2153 if( bt_lockpage(bt, right, BtLockRead) )
2156 if( bt_mappage (bt, &set->page, right) )
2159 memcpy (bt->cursor, set->page, bt->page_size);
2161 if( bt_unlockpage(bt, right, BtLockRead) )
2170 BtKey bt_key(BtDb *bt, uint slot)
2172 return keyptr(bt->cursor, slot);
2175 uid bt_uid(BtDb *bt, uint slot)
2177 return bt_getid(slotptr(bt->cursor,slot)->id);
2180 uint bt_tod(BtDb *bt, uint slot)
2182 return slotptr(bt->cursor,slot)->tod;
2187 // standalone program to index file of keys
2188 // then list them onto std-out
2190 int main (int argc, char **argv)
2192 uint slot, line = 0, off = 0, found = 0;
2193 int dead, ch, cnt = 0, bits = 12;
2194 unsigned char key[256];
2195 clock_t done, start;
2206 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]);
2207 fprintf (stderr, " page_bits: size of btree page in bits\n");
2208 fprintf (stderr, " mapped_pool_segments: size of buffer pool in segments\n");
2209 fprintf (stderr, " pages_per_segment: size of buffer pool segment in pages in bits\n");
2217 bits = atoi(argv[4]);
2220 map = atoi(argv[5]);
2223 fprintf (stderr, "Warning: buffer_pool > 65536 segments\n");
2225 if( map && map < 8 )
2226 fprintf (stderr, "Buffer_pool too small\n");
2229 pgblk = atoi(argv[6]);
2231 if( bits + pgblk > 30 )
2232 fprintf (stderr, "Warning: very large buffer pool segment size\n");
2235 off = atoi(argv[7]);
2237 bt = bt_open ((argv[1]), BT_rw, bits, map, pgblk);
2240 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2244 switch(argv[3][0]| 0x20)
2247 fprintf(stderr, "started indexing for %s\n", argv[2]);
2248 if( argc > 2 && (in = fopen (argv[2], "rb")) )
2249 while( ch = getc(in), ch != EOF )
2253 sprintf((char *)key+len, "%.9d", line + off), len += 9;
2255 if( bt_insertkey (bt, key, len, 0, ++line, *tod) )
2256 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2259 else if( len < 245 )
2261 fprintf(stderr, "finished adding keys, %d \n", line);
2265 fprintf(stderr, "started deleting keys for %s\n", argv[2]);
2266 if( argc > 2 && (in = fopen (argv[2], "rb")) )
2267 while( ch = getc(in), ch != EOF )
2271 sprintf((char *)key+len, "%.9d", line + off), len += 9;
2273 if( bt_deletekey (bt, key, len) )
2274 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2277 else if( len < 245 )
2279 fprintf(stderr, "finished deleting keys, %d \n", line);
2283 fprintf(stderr, "started finding keys for %s\n", argv[2]);
2284 if( argc > 2 && (in = fopen (argv[2], "rb")) )
2285 while( ch = getc(in), ch != EOF )
2289 sprintf((char *)key+len, "%.9d", line + off), len += 9;
2291 if( bt_findkey (bt, key, len) )
2294 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2297 else if( len < 245 )
2299 fprintf(stderr, "finished search of %d keys, found %d\n", line, found);
2309 fprintf(stderr, " Time to complete: %.2f seconds\n", (float)(done - start) / CLOCKS_PER_SEC);
2314 fprintf(stderr, "started reading\n");
2316 if( slot = bt_startkey (bt, key, len) )
2319 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
2321 while( slot = bt_nextkey (bt, slot) )
2323 ptr = bt_key(bt, slot);
2324 fwrite (ptr->key, ptr->len, 1, stdout);
2325 fputc ('\n', stdout);
2328 fprintf(stderr, " Total keys read %d\n", cnt);