4 // author: karl malbrain, malbrain@cal.berkeley.edu
7 This work, including the source code, documentation
8 and related data, is placed into the public domain.
10 The orginal author is Karl Malbrain.
12 THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY
13 OF ANY KIND, NOT EVEN THE IMPLIED WARRANTY OF
14 MERCHANTABILITY. THE AUTHOR OF THIS SOFTWARE,
15 ASSUMES _NO_ RESPONSIBILITY FOR ANY CONSEQUENCE
16 RESULTING FROM THE USE, MODIFICATION, OR
17 REDISTRIBUTION OF THIS SOFTWARE.
20 // Please see the project home page for documentation
21 // code.google.com/p/high-concurrency-btree
23 #define _FILE_OFFSET_BITS 64
24 #define _LARGEFILE64_SOURCE
39 #define WIN32_LEAN_AND_MEAN
50 typedef unsigned long long uid;
53 typedef unsigned long long off64_t;
54 typedef unsigned short ushort;
55 typedef unsigned int uint;
58 #define BT_ro 0x6f72 // ro
59 #define BT_rw 0x7772 // rw
60 #define BT_fl 0x6c66 // fl
62 #define BT_maxbits 24 // maximum page size in bits
63 #define BT_minbits 9 // minimum page size in bits
64 #define BT_minpage (1 << BT_minbits) // minimum page size
67 There are five lock types for each node in three independent sets:
68 1. (set 1) AccessIntent: Sharable. Going to Read the node. Incompatible with NodeDelete.
69 2. (set 1) NodeDelete: Exclusive. About to release the node. Incompatible with AccessIntent.
70 3. (set 2) ReadLock: Sharable. Read the node. Incompatible with WriteLock.
71 4. (set 2) WriteLock: Exclusive. Modify the node. Incompatible with ReadLock and other WriteLocks.
72 5. (set 3) ParentModification: Exclusive. Change the node's parent keys. Incompatible with another ParentModification.
83 // Define the length of the page and key pointers
87 // Page key slot definition.
89 // If BT_maxbits is 15 or less, you can save 2 bytes
90 // for each key stored by making the first two uints
91 // into ushorts. You can also save 4 bytes by removing
92 // the tod field from the key.
94 // Keys are marked dead, but remain on the page until
95 // cleanup is called. The fence key (highest key) for
96 // the page is always present, even if dead.
99 uint off:BT_maxbits; // page offset for key start
100 uint dead:1; // set for deleted key
101 uint tod; // time-stamp for key
102 unsigned char id[BtId]; // id associated with key
105 // The key structure occupies space at the upper end of
106 // each page. It's a length byte followed by the value
111 unsigned char key[0];
114 // The first part of an index page.
115 // It is immediately followed
116 // by the BtSlot array of keys.
119 uint cnt; // count of keys in page
120 uint act; // count of active keys
121 uint min; // next key offset
122 unsigned char bits; // page size in bits
123 unsigned char lvl:7; // level of page
124 unsigned char kill:1; // page is being deleted
125 unsigned char right[BtId]; // page number to right
128 // The memory mapping hash table entry
131 BtPage page; // mapped page pointer
132 uid page_no; // mapped page number
133 void *lruprev; // least recently used previous cache block
134 void *lrunext; // lru next cache block
135 void *hashprev; // previous cache block for the same hash idx
136 void *hashnext; // next cache block for the same hash idx
142 // The object structure for Btree access
144 typedef struct _BtDb {
145 uint page_size; // each page size
146 uint page_bits; // each page size in bits
147 uint seg_bits; // segment size in pages in bits
148 uid page_no; // current page number
149 uid cursor_page; // current cursor page number
151 uint mode; // read-write mode
152 uint mapped_io; // use memory mapping
153 BtPage temp; // temporary frame buffer (memory mapped/file IO)
154 BtPage alloc; // frame buffer for alloc page ( page 0 )
155 BtPage cursor; // cached frame for start/next (never mapped)
156 BtPage frame; // spare frame for the page split (never mapped)
157 BtPage zero; // zeroes frame buffer (never mapped)
158 BtPage page; // current page
164 unsigned char *mem; // frame, cursor, page memory buffer
165 int nodecnt; // highest page cache segment in use
166 int nodemax; // highest page cache segment allocated
167 int hashmask; // number of pages in segments - 1
168 int hashsize; // size of hash table
169 BtHash *lrufirst; // lru list head
170 BtHash *lrulast; // lru list tail
171 ushort *cache; // hash table for cached segments
172 BtHash nodes[1]; // segment cache follows
186 extern void bt_close (BtDb *bt);
187 extern BtDb *bt_open (char *name, uint mode, uint bits, uint cacheblk, uint pgblk);
188 extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod);
189 extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl);
190 extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
191 extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
192 extern uint bt_nextkey (BtDb *bt, uint slot);
194 // Helper functions to return slot values
196 extern BtKey bt_key (BtDb *bt, uint slot);
197 extern uid bt_uid (BtDb *bt, uint slot);
198 extern uint bt_tod (BtDb *bt, uint slot);
200 // BTree page number constants
204 // Number of levels to create in a new BTree
208 // The page is allocated from low and hi ends.
209 // The key offsets and row-id's are allocated
210 // from the bottom, while the text of the key
211 // is allocated from the top. When the two
212 // areas meet, the page is split into two.
214 // A key consists of a length byte, two bytes of
215 // index number (0 - 65534), and up to 253 bytes
216 // of key value. Duplicate keys are discarded.
217 // Associated with each key is a 48 bit row-id.
219 // The b-tree root is always located at page 1.
220 // The first leaf page of level zero is always
221 // located on page 2.
223 // The b-tree pages are linked with right
224 // pointers to facilitate enumerators,
225 // and provide for concurrency.
227 // When to root page fills, it is split in two and
228 // the tree height is raised by a new root at page
229 // one with two keys.
231 // Deleted keys are marked with a dead bit until
232 // page cleanup The fence key for a node is always
233 // present, even after deletion and cleanup.
235 // Groups of pages from the btree are optionally
236 // cached with memory mapping. A hash table is used to keep
237 // track of the cached pages. This behaviour is controlled
238 // by the number of cache blocks parameter and pages per block
241 // To achieve maximum concurrency one page is locked at a time
242 // as the tree is traversed to find leaf key in question. The right
243 // page numbers are used in cases where the page is being split,
246 // Page 0 is dedicated to lock for new page extensions,
247 // and chains empty pages together for reuse.
249 // Parent locks are obtained to prevent resplitting or deleting a node
250 // before its fence is posted into its upper level.
252 // Empty nodes are chained together through the ALLOC page and reused.
254 // A special open mode of BT_fl is provided to safely access files on
255 // WIN32 networks. WIN32 network operations should not use memory mapping.
256 // This WIN32 mode sets FILE_FLAG_NOBUFFERING and FILE_FLAG_WRITETHROUGH
257 // to prevent local caching of network file contents.
259 // Access macros to address slot and key values from the page.
260 // Page slots use 1 based indexing.
262 #define slotptr(page, slot) (((BtSlot *)(page+1)) + (slot-1))
263 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
265 void bt_putid(unsigned char *dest, uid id)
270 dest[i] = (unsigned char)id, id >>= 8;
273 uid bt_getid(unsigned char *src)
278 for( i = 0; i < BtId; i++ )
279 id <<= 8, id |= *src++;
284 // place write, read, or parent lock on requested page_no.
286 BTERR bt_lockpage(BtDb *bt, uid page_no, BtLock mode)
288 off64_t off = page_no << bt->page_bits;
290 int flag = PROT_READ | ( bt->mode == BT_ro ? 0 : PROT_WRITE );
291 struct flock lock[1];
297 if( mode == BtLockRead || mode == BtLockWrite )
298 off += sizeof(*bt->page); // use second segment
300 if( mode == BtLockParent )
301 off += 2 * sizeof(*bt->page); // use third segment
304 memset (lock, 0, sizeof(lock));
307 lock->l_type = (mode == BtLockDelete || mode == BtLockWrite || mode == BtLockParent) ? F_WRLCK : F_RDLCK;
308 lock->l_len = sizeof(*bt->page);
311 if( fcntl (bt->idx, F_SETLKW, lock) < 0 )
312 return bt->err = BTERR_lock;
316 memset (ovl, 0, sizeof(ovl));
317 ovl->OffsetHigh = (uint)(off >> 32);
318 ovl->Offset = (uint)off;
319 len = sizeof(*bt->page);
321 // use large offsets to
322 // simulate advisory locking
324 ovl->OffsetHigh |= 0x80000000;
326 if( mode == BtLockDelete || mode == BtLockWrite || mode == BtLockParent )
327 flags |= LOCKFILE_EXCLUSIVE_LOCK;
329 if( LockFileEx (bt->idx, flags, 0, len, 0L, ovl) )
332 return bt->err = BTERR_lock;
336 // remove write, read, or parent lock on requested page_no.
338 BTERR bt_unlockpage(BtDb *bt, uid page_no, BtLock mode)
340 off64_t off = page_no << bt->page_bits;
342 struct flock lock[1];
348 if( mode == BtLockRead || mode == BtLockWrite )
349 off += sizeof(*bt->page); // use second segment
351 if( mode == BtLockParent )
352 off += 2 * sizeof(*bt->page); // use third segment
355 memset (lock, 0, sizeof(lock));
358 lock->l_type = F_UNLCK;
359 lock->l_len = sizeof(*bt->page);
362 if( fcntl (bt->idx, F_SETLK, lock) < 0 )
363 return bt->err = BTERR_lock;
365 memset (ovl, 0, sizeof(ovl));
366 ovl->OffsetHigh = (uint)(off >> 32);
367 ovl->Offset = (uint)off;
368 len = sizeof(*bt->page);
370 // use large offsets to
371 // simulate advisory locking
373 ovl->OffsetHigh |= 0x80000000;
375 if( !UnlockFileEx (bt->idx, 0, len, 0, ovl) )
376 return GetLastError(), bt->err = BTERR_lock;
382 // close and release memory
384 void bt_close (BtDb *bt)
388 // release mapped pages
390 if( hash = bt->lrufirst )
391 do munmap (hash->page, (bt->hashmask+1) << bt->page_bits);
392 while(hash = hash->lrunext);
400 if( hash = bt->lrufirst )
403 FlushViewOfFile(hash->page, 0);
404 UnmapViewOfFile(hash->page);
405 CloseHandle(hash->hmap);
406 } while(hash = hash->lrunext);
409 VirtualFree (bt->mem, 0, MEM_RELEASE);
410 FlushFileBuffers(bt->idx);
411 CloseHandle(bt->idx);
412 GlobalFree (bt->cache);
417 // open/create new btree
418 // call with file_name, BT_openmode, bits in page size (e.g. 16),
419 // size of mapped page cache (e.g. 8192) or zero for no mapping.
421 BtDb *bt_open (char *name, uint mode, uint bits, uint nodemax, uint pgblk)
423 uint lvl, attr, cacheblk, last;
424 BtLock lockmode = BtLockWrite;
432 SYSTEM_INFO sysinfo[1];
436 bt = malloc (sizeof(BtDb) + nodemax * sizeof(BtHash));
437 memset (bt, 0, sizeof(BtDb));
439 switch (mode & 0x7fff)
443 bt->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
448 bt->idx = open ((char*)name, O_RDONLY);
449 lockmode = BtLockRead;
453 return free(bt), NULL;
456 cacheblk = 4096; // page size for unix
461 bt = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtDb) + nodemax * sizeof(BtHash));
462 attr = FILE_ATTRIBUTE_NORMAL;
463 switch (mode & 0x7fff)
466 attr |= FILE_FLAG_WRITE_THROUGH | FILE_FLAG_NO_BUFFERING;
469 bt->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
474 bt->idx = CreateFile(name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, attr, NULL);
475 lockmode = BtLockRead;
478 if( bt->idx == INVALID_HANDLE_VALUE )
479 return GlobalFree(bt), NULL;
481 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
482 GetSystemInfo(sysinfo);
485 cacheblk = sysinfo->dwAllocationGranularity;
490 // determine sanity of page size
492 if( bits > BT_maxbits )
494 else if( bits < BT_minbits )
497 if ( bt_lockpage(bt, ALLOC_page, lockmode) )
498 return bt_close (bt), NULL;
503 // read minimum page size to get root info
505 if( size = lseek (bt->idx, 0L, 2) ) {
506 alloc = malloc (BT_minpage);
507 pread(bt->idx, alloc, BT_minpage, 0);
510 } else if( mode == BT_ro )
511 return bt_close (bt), NULL;
513 size = GetFileSize(bt->idx, amt);
516 alloc = VirtualAlloc(NULL, BT_minpage, MEM_COMMIT, PAGE_READWRITE);
517 if( !ReadFile(bt->idx, (char *)alloc, BT_minpage, amt, NULL) )
518 return bt_close (bt), NULL;
520 VirtualFree (alloc, 0, MEM_RELEASE);
521 } else if( mode == BT_ro )
522 return bt_close (bt), NULL;
525 bt->page_size = 1 << bits;
526 bt->page_bits = bits;
528 bt->nodemax = nodemax;
531 // setup cache mapping
534 if( cacheblk < bt->page_size )
535 cacheblk = bt->page_size;
537 bt->hashsize = nodemax / 8;
538 bt->hashmask = (cacheblk >> bits) - 1;
542 // requested number of pages per memmap segment
545 if( (1 << pgblk) > bt->hashmask )
546 bt->hashmask = (1 << pgblk) - 1;
550 while( (1 << bt->seg_bits) <= bt->hashmask )
554 bt->mem = malloc (6 *bt->page_size);
555 bt->cache = calloc (bt->hashsize, sizeof(ushort));
557 bt->mem = VirtualAlloc(NULL, 6 * bt->page_size, MEM_COMMIT, PAGE_READWRITE);
558 bt->cache = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, bt->hashsize * sizeof(ushort));
560 bt->frame = (BtPage)bt->mem;
561 bt->cursor = (BtPage)(bt->mem + bt->page_size);
562 bt->page = (BtPage)(bt->mem + 2 * bt->page_size);
563 bt->alloc = (BtPage)(bt->mem + 3 * bt->page_size);
564 bt->temp = (BtPage)(bt->mem + 4 * bt->page_size);
565 bt->zero = (BtPage)(bt->mem + 5 * bt->page_size);
568 if ( bt_unlockpage(bt, ALLOC_page, lockmode) )
569 return bt_close (bt), NULL;
574 // initializes an empty b-tree with root page and page of leaves
576 memset (bt->alloc, 0, bt->page_size);
577 bt_putid(bt->alloc->right, MIN_lvl+1);
578 bt->alloc->bits = bt->page_bits;
581 if( write (bt->idx, bt->alloc, bt->page_size) < bt->page_size )
582 return bt_close (bt), NULL;
584 if( !WriteFile (bt->idx, (char *)bt->alloc, bt->page_size, amt, NULL) )
585 return bt_close (bt), NULL;
587 if( *amt < bt->page_size )
588 return bt_close (bt), NULL;
591 memset (bt->frame, 0, bt->page_size);
592 bt->frame->bits = bt->page_bits;
594 for( lvl=MIN_lvl; lvl--; ) {
595 slotptr(bt->frame, 1)->off = bt->page_size - 3;
596 bt_putid(slotptr(bt->frame, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
597 key = keyptr(bt->frame, 1);
598 key->len = 2; // create stopper key
601 bt->frame->min = bt->page_size - 3;
602 bt->frame->lvl = lvl;
606 if( write (bt->idx, bt->frame, bt->page_size) < bt->page_size )
607 return bt_close (bt), NULL;
609 if( !WriteFile (bt->idx, (char *)bt->frame, bt->page_size, amt, NULL) )
610 return bt_close (bt), NULL;
612 if( *amt < bt->page_size )
613 return bt_close (bt), NULL;
617 // create empty page area by writing last page of first
618 // cache area (other pages are zeroed by O/S)
620 if( bt->mapped_io && bt->hashmask ) {
621 memset(bt->frame, 0, bt->page_size);
624 while( last < MIN_lvl + 1 )
625 last += bt->hashmask + 1;
627 pwrite(bt->idx, bt->frame, bt->page_size, last << bt->page_bits);
629 SetFilePointer (bt->idx, last << bt->page_bits, NULL, FILE_BEGIN);
630 if( !WriteFile (bt->idx, (char *)bt->frame, bt->page_size, amt, NULL) )
631 return bt_close (bt), NULL;
632 if( *amt < bt->page_size )
633 return bt_close (bt), NULL;
637 if( bt_unlockpage(bt, ALLOC_page, lockmode) )
638 return bt_close (bt), NULL;
643 // compare two keys, returning > 0, = 0, or < 0
644 // as the comparison value
646 int keycmp (BtKey key1, unsigned char *key2, uint len2)
648 uint len1 = key1->len;
651 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
662 // Update current page of btree by writing file contents
663 // or flushing mapped area to disk.
665 BTERR bt_update (BtDb *bt, BtPage page, uid page_no)
667 off64_t off = page_no << bt->page_bits;
670 if ( !bt->mapped_io )
671 if ( pwrite(bt->idx, page, bt->page_size, off) != bt->page_size )
672 return bt->err = BTERR_wrt;
675 if ( !bt->mapped_io )
677 SetFilePointer (bt->idx, (long)off, (long*)(&off)+1, FILE_BEGIN);
678 if( !WriteFile (bt->idx, (char *)page, bt->page_size, amt, NULL) )
679 return GetLastError(), bt->err = BTERR_wrt;
681 if( *amt < bt->page_size )
682 return GetLastError(), bt->err = BTERR_wrt;
684 else if ( bt->mode == BT_fl ) {
685 FlushViewOfFile(page, bt->page_size);
686 FlushFileBuffers(bt->idx);
692 // find page in cache
694 BtHash *bt_findhash(BtDb *bt, uid page_no)
699 // compute cache block first page and hash idx
701 page_no &= ~bt->hashmask;
702 idx = (uint)(page_no >> bt->seg_bits) % bt->hashsize;
705 hash = bt->nodes + bt->cache[idx];
709 do if( hash->page_no == page_no )
711 while(hash = hash->hashnext );
716 // add page cache entry to hash index
718 void bt_linkhash(BtDb *bt, BtHash *node, uid page_no)
720 uint idx = (uint)(page_no >> bt->seg_bits) % bt->hashsize;
723 if( bt->cache[idx] ) {
724 node->hashnext = hash = bt->nodes + bt->cache[idx];
725 hash->hashprev = node;
728 node->hashprev = NULL;
729 bt->cache[idx] = (ushort)(node - bt->nodes);
732 // remove cache entry from hash table
734 void bt_unlinkhash(BtDb *bt, BtHash *node)
736 uint idx = (uint)(node->page_no >> bt->seg_bits) % bt->hashsize;
740 if( hash = node->hashprev )
741 hash->hashnext = node->hashnext;
742 else if( hash = node->hashnext )
743 bt->cache[idx] = (ushort)(hash - bt->nodes);
747 if( hash = node->hashnext )
748 hash->hashprev = node->hashprev;
751 // add cache page to lru chain and map pages
753 BtPage bt_linklru(BtDb *bt, BtHash *hash, uid page_no)
756 off64_t off = (page_no & ~bt->hashmask) << bt->page_bits;
757 off64_t limit = off + ((bt->hashmask+1) << bt->page_bits);
760 memset(hash, 0, sizeof(BtHash));
761 hash->page_no = (page_no & ~bt->hashmask);
762 bt_linkhash(bt, hash, page_no);
764 if( node = hash->lrunext = bt->lrufirst )
765 node->lruprev = hash;
772 flag = PROT_READ | ( bt->mode == BT_ro ? 0 : PROT_WRITE );
773 hash->page = (BtPage)mmap (0, (bt->hashmask+1) << bt->page_bits, flag, MAP_SHARED, bt->idx, off);
774 if( hash->page == MAP_FAILED )
775 return bt->err = BTERR_map, (BtPage)NULL;
778 flag = ( bt->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
779 hash->hmap = CreateFileMapping(bt->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
781 return bt->err = BTERR_map, NULL;
783 flag = ( bt->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
784 hash->page = MapViewOfFile(hash->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->hashmask+1) << bt->page_bits);
786 return bt->err = BTERR_map, NULL;
789 return (BtPage)((char*)hash->page + ((uint)(page_no & bt->hashmask) << bt->page_bits));
792 // find or place requested page in page-cache
793 // return memory address where page is located.
795 BtPage bt_hashpage(BtDb *bt, uid page_no)
797 BtHash *hash, *node, *next;
800 // find page in cache and move to top of lru list
802 if( hash = bt_findhash(bt, page_no) ) {
803 page = (BtPage)((char*)hash->page + ((uint)(page_no & bt->hashmask) << bt->page_bits));
804 // swap node in lru list
805 if( node = hash->lruprev ) {
806 if( next = node->lrunext = hash->lrunext )
807 next->lruprev = node;
811 if( next = hash->lrunext = bt->lrufirst )
812 next->lruprev = hash;
814 return bt->err = BTERR_hash, (BtPage)NULL;
816 hash->lruprev = NULL;
822 // map pages and add to cache entry
824 if( bt->nodecnt < bt->nodemax ) {
825 hash = bt->nodes + ++bt->nodecnt;
826 return bt_linklru(bt, hash, page_no);
829 // hash table is already full, replace last lru entry from the cache
831 if( hash = bt->lrulast ) {
832 // unlink from lru list
833 if( node = bt->lrulast = hash->lruprev )
834 node->lrunext = NULL;
836 return bt->err = BTERR_hash, (BtPage)NULL;
839 munmap (hash->page, (bt->hashmask+1) << bt->page_bits);
841 FlushViewOfFile(hash->page, 0);
842 UnmapViewOfFile(hash->page);
843 CloseHandle(hash->hmap);
845 // unlink from hash table
847 bt_unlinkhash(bt, hash);
849 // map and add to cache
851 return bt_linklru(bt, hash, page_no);
854 return bt->err = BTERR_hash, (BtPage)NULL;
857 // map a btree page onto current page
859 BTERR bt_mappage (BtDb *bt, BtPage *page, uid page_no)
861 off64_t off = page_no << bt->page_bits;
866 if( bt->mapped_io ) {
868 *page = bt_hashpage(bt, page_no);
872 if ( pread(bt->idx, *page, bt->page_size, off) < bt->page_size )
873 return bt->err = BTERR_map;
875 SetFilePointer (bt->idx, (long)off, (long*)(&off)+1, FILE_BEGIN);
877 if( !ReadFile(bt->idx, *page, bt->page_size, amt, NULL) )
878 return bt->err = BTERR_map;
880 if( *amt < bt->page_size )
881 return bt->err = BTERR_map;
886 // deallocate a deleted page
887 // place on free chain out of allocator page
889 BTERR bt_freepage(BtDb *bt, uid page_no)
891 // obtain delete lock on deleted node
893 if( bt_lockpage(bt, page_no, BtLockDelete) )
896 // obtain write lock on deleted node
898 if( bt_lockpage(bt, page_no, BtLockWrite) )
901 if( bt_mappage (bt, &bt->temp, page_no) )
904 // lock allocation page
906 if ( bt_lockpage(bt, ALLOC_page, BtLockWrite) )
909 if( bt_mappage (bt, &bt->alloc, ALLOC_page) )
912 // store chain in second right
913 bt_putid(bt->temp->right, bt_getid(bt->alloc[1].right));
914 bt_putid(bt->alloc[1].right, page_no);
916 if( bt_update(bt, bt->alloc, ALLOC_page) )
918 if( bt_update(bt, bt->temp, page_no) )
923 if( bt_unlockpage(bt, ALLOC_page, BtLockWrite) )
926 // remove write lock on deleted node
928 if( bt_unlockpage(bt, page_no, BtLockWrite) )
931 // remove delete lock on deleted node
933 if( bt_unlockpage(bt, page_no, BtLockDelete) )
939 // allocate a new page and write page into it
941 uid bt_newpage(BtDb *bt, BtPage page)
949 if ( bt_lockpage(bt, ALLOC_page, BtLockWrite) )
952 if( bt_mappage (bt, &bt->alloc, ALLOC_page) )
955 // use empty chain first
956 // else allocate empty page
958 if( new_page = bt_getid(bt->alloc[1].right) ) {
959 if( bt_mappage (bt, &bt->temp, new_page) )
960 return 0; // don't unlock on error
961 bt_putid(bt->alloc[1].right, bt_getid(bt->temp->right));
964 new_page = bt_getid(bt->alloc->right);
965 bt_putid(bt->alloc->right, new_page+1);
969 if( bt_update(bt, bt->alloc, ALLOC_page) )
970 return 0; // don't unlock on error
972 if( !bt->mapped_io ) {
973 if( bt_update(bt, page, new_page) )
974 return 0; //don't unlock on error
978 if ( bt_unlockpage(bt, ALLOC_page, BtLockWrite) )
985 if ( pwrite(bt->idx, page, bt->page_size, new_page << bt->page_bits) < bt->page_size )
986 return bt->err = BTERR_wrt, 0;
988 // if writing first page of hash block, zero last page in the block
990 if ( !reuse && bt->hashmask > 0 && (new_page & bt->hashmask) == 0 )
992 // use temp buffer to write zeros
993 memset(bt->zero, 0, bt->page_size);
994 if ( pwrite(bt->idx,bt->zero, bt->page_size, (new_page | bt->hashmask) << bt->page_bits) < bt->page_size )
995 return bt->err = BTERR_wrt, 0;
998 // bring new page into page-cache and copy page.
999 // this will extend the file into the new pages.
1001 if( !(pmap = (char*)bt_hashpage(bt, new_page & ~bt->hashmask)) )
1004 memcpy(pmap+((new_page & bt->hashmask) << bt->page_bits), page, bt->page_size);
1009 if ( bt_unlockpage(bt, ALLOC_page, BtLockWrite) )
1015 // find slot in page for given key at a given level
1017 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1019 uint diff, higher = bt->page->cnt, low = 1, slot;
1022 // make stopper key an infinite fence value
1024 if( bt_getid (bt->page->right) )
1029 // low is the next candidate, higher is already
1030 // tested as .ge. the given key, loop ends when they meet
1032 while( diff = higher - low ) {
1033 slot = low + ( diff >> 1 );
1034 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1037 higher = slot, good++;
1040 // return zero if key is on right link page
1042 return good ? higher : 0;
1045 // find and load page at given level for given key
1046 // leave page rd or wr locked as requested
1048 int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, uint lock)
1050 uid page_no = ROOT_page, prevpage = 0;
1051 uint drill = 0xff, slot;
1052 uint mode, prevmode;
1054 // start at root of btree and drill down
1057 // determine lock mode of drill level
1058 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1060 bt->page_no = page_no;
1062 // obtain access lock using lock chaining
1064 if( page_no > ROOT_page )
1065 if( bt_lockpage(bt, bt->page_no, BtLockAccess) )
1069 if( bt_unlockpage(bt, prevpage, prevmode) )
1072 // obtain read lock using lock chaining
1074 if( bt_lockpage(bt, bt->page_no, mode) )
1077 if( page_no > ROOT_page )
1078 if( bt_unlockpage(bt, bt->page_no, BtLockAccess) )
1081 // map/obtain page contents
1083 if( bt_mappage (bt, &bt->page, page_no) )
1086 // re-read and re-lock root after determining actual level of root
1088 if( bt->page->lvl != drill) {
1089 if ( bt->page_no != ROOT_page )
1090 return bt->err = BTERR_struct, 0;
1092 drill = bt->page->lvl;
1094 if( lock == BtLockWrite && drill == lvl )
1095 if( bt_unlockpage(bt, page_no, mode) )
1101 // find key on page at this level
1102 // and descend to requested level
1104 if( !bt->page->kill && (slot = bt_findslot (bt, key, len)) ) {
1108 while( slotptr(bt->page, slot)->dead )
1109 if( slot++ < bt->page->cnt )
1112 page_no = bt_getid(bt->page->right);
1116 page_no = bt_getid(slotptr(bt->page, slot)->id);
1120 // or slide right into next page
1121 // (slide left from deleted page)
1124 page_no = bt_getid(bt->page->right);
1126 // continue down / right using overlapping locks
1127 // to protect pages being killed or split.
1130 prevpage = bt->page_no;
1134 // return error on end of right chain
1136 bt->err = BTERR_struct;
1137 return 0; // return error
1140 // find and delete key on page by marking delete flag bit
1141 // when page becomes empty, delete it
1143 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl)
1145 unsigned char lowerkey[256], higherkey[256];
1146 uint slot, tod, dirty = 0;
1150 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1151 ptr = keyptr(bt->page, slot);
1155 // if key is found delete it, otherwise ignore request
1157 if( !keycmp (ptr, key, len) )
1158 if( slotptr(bt->page, slot)->dead == 0 )
1159 dirty = slotptr(bt->page,slot)->dead = 1, bt->page->act--;
1161 // return if page is not empty, or it has no right sibling
1163 right = bt_getid(bt->page->right);
1164 page_no = bt->page_no;
1166 if( !right || bt->page->act )
1167 if ( dirty && bt_update(bt, bt->page, page_no) )
1170 return bt_unlockpage(bt, page_no, BtLockWrite);
1172 // obtain Parent lock over write lock
1174 if( bt_lockpage(bt, page_no, BtLockParent) )
1177 // cache copy of key to delete
1179 ptr = keyptr(bt->page, bt->page->cnt);
1180 memcpy(lowerkey, ptr, ptr->len + 1);
1182 // lock and map right page
1184 if ( bt_lockpage(bt, right, BtLockWrite) )
1187 if( bt_mappage (bt, &bt->temp, right) )
1190 // pull contents of next page into current empty page
1191 memcpy (bt->page, bt->temp, bt->page_size);
1193 // cache copy of key to update
1194 ptr = keyptr(bt->temp, bt->temp->cnt);
1195 memcpy(higherkey, ptr, ptr->len + 1);
1197 // Mark right page as deleted and point it to left page
1198 // until we can post updates at higher level.
1200 bt_putid(bt->temp->right, page_no);
1204 if ( bt_update(bt, bt->page, page_no) )
1207 if ( bt_update(bt, bt->temp, right) )
1210 if( bt_unlockpage(bt, right, BtLockWrite) )
1212 if( bt_unlockpage(bt, page_no, BtLockWrite) )
1215 // delete old lower key to consolidated node
1217 if( bt_deletekey (bt, lowerkey + 1, *lowerkey, lvl + 1) )
1220 // redirect higher key directly to consolidated node
1222 tod = (uint)time(NULL);
1224 if( bt_insertkey (bt, higherkey+1, *higherkey, lvl + 1, page_no, tod) )
1227 // obtain write lock and
1228 // add right block to free chain
1230 if( bt_freepage (bt, right) )
1233 // remove ParentModify lock
1235 if( bt_unlockpage(bt, page_no, BtLockParent) )
1241 // find key in leaf level and return row-id
1243 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1249 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1250 ptr = keyptr(bt->page, slot);
1254 // if key exists, return row-id
1255 // otherwise return 0
1257 if( ptr->len == len && !memcmp (ptr->key, key, len) )
1258 id = bt_getid(slotptr(bt->page,slot)->id);
1262 if ( bt_unlockpage(bt, bt->page_no, BtLockRead) )
1268 void bt_cleanpage(BtDb *bt)
1270 uint nxt = bt->page_size;
1271 BtPage page = bt->page;
1272 uint cnt = 0, idx = 0;
1273 uint max = page->cnt;
1276 memcpy (bt->frame, page, bt->page_size);
1278 // skip page info and set rest of page to zero
1279 memset (page+1, 0, bt->page_size - sizeof(*page));
1282 // try cleaning up page first
1284 while( cnt++ < max ) {
1285 // always leave fence key in list
1286 if( cnt < max && slotptr(bt->frame,cnt)->dead )
1290 key = keyptr(bt->frame, cnt);
1291 nxt -= key->len + 1;
1292 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1295 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1296 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1298 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1299 slotptr(page, idx)->off = nxt;
1305 // split the root and raise the height of the btree
1307 BTERR bt_splitroot(BtDb *bt, unsigned char *newkey, unsigned char *oldkey, uid page_no2)
1309 uint nxt = bt->page_size;
1310 BtPage root = bt->page;
1313 // Obtain an empty page to use, and copy the current
1314 // root contents into it
1316 if( !(new_page = bt_newpage(bt, root)) )
1319 // preserve the page info at the bottom
1320 // and set rest to zero
1322 memset(root+1, 0, bt->page_size - sizeof(*root));
1324 // insert first key on newroot page
1327 memcpy ((unsigned char *)root + nxt, newkey, *newkey + 1);
1328 bt_putid(slotptr(root, 1)->id, new_page);
1329 slotptr(root, 1)->off = nxt;
1331 // insert second key on newroot page
1332 // and increase the root height
1335 memcpy ((unsigned char *)root + nxt, oldkey, *oldkey + 1);
1336 bt_putid(slotptr(root, 2)->id, page_no2);
1337 slotptr(root, 2)->off = nxt;
1339 bt_putid(root->right, 0);
1340 root->min = nxt; // reset lowest used offset and key count
1345 // update and release root (bt->page)
1347 if( bt_update(bt, root, bt->page_no) )
1350 return bt_unlockpage(bt, bt->page_no, BtLockWrite);
1353 // split already locked full node
1356 BTERR bt_splitpage (BtDb *bt, uint len)
1358 uint cnt = 0, idx = 0, max, nxt = bt->page_size;
1359 unsigned char oldkey[256], lowerkey[256];
1360 uid page_no = bt->page_no, right;
1361 BtPage page = bt->page;
1362 uint lvl = page->lvl;
1371 // return if enough space now
1373 if( page->min >= (page->cnt + 1) * sizeof(BtSlot) + sizeof(*page) + len + 1)
1375 if ( bt_update(bt, page, page_no) )
1378 return bt_unlockpage(bt, page_no, BtLockWrite);
1381 // split higher half of keys to bt->frame
1382 // the last key (fence key) might be dead
1384 tod = (uint)time(NULL);
1386 memset (bt->frame, 0, bt->page_size);
1387 max = (int)page->cnt;
1391 while( cnt++ < max ) {
1392 key = keyptr(page, cnt);
1393 nxt -= key->len + 1;
1394 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
1395 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
1396 if( !(slotptr(bt->frame, idx)->dead = slotptr(page, cnt)->dead) )
1398 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
1399 slotptr(bt->frame, idx)->off = nxt;
1402 // remember existing fence key for new page to the right
1404 memcpy (oldkey, key, key->len + 1);
1406 bt->frame->bits = bt->page_bits;
1407 bt->frame->min = nxt;
1408 bt->frame->cnt = idx;
1409 bt->frame->lvl = lvl;
1413 if( page_no > ROOT_page ) {
1414 right = bt_getid (page->right);
1415 bt_putid(bt->frame->right, right);
1418 // get new free page and write frame to it.
1420 if( !(new_page = bt_newpage(bt, bt->frame)) )
1423 // update lower keys to continue in old page
1425 memcpy (bt->frame, page, bt->page_size);
1426 memset (page+1, 0, bt->page_size - sizeof(*page));
1427 nxt = bt->page_size;
1432 // assemble page of smaller keys
1433 // (they're all active keys)
1435 while( cnt++ < max / 2 ) {
1436 key = keyptr(bt->frame, cnt);
1437 nxt -= key->len + 1;
1438 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1439 memcpy(slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1440 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1441 slotptr(page, idx)->off = nxt;
1445 // remember fence key for old page
1447 memcpy(lowerkey, key, key->len + 1);
1448 bt_putid(page->right, new_page);
1452 // if current page is the root page, split it
1454 if( page_no == ROOT_page )
1455 return bt_splitroot (bt, lowerkey, oldkey, new_page);
1457 // update left (containing) node
1459 if( bt_update(bt, page, page_no) )
1462 // obtain Parent/Write locks
1463 // for left and right node pages
1465 if( bt_lockpage (bt, new_page, BtLockParent) )
1468 if( bt_lockpage (bt, page_no, BtLockParent) )
1471 // release wr lock on left page
1473 if( bt_unlockpage (bt, page_no, BtLockWrite) )
1476 // insert new fence for reformulated left block
1478 if( bt_insertkey (bt, lowerkey+1, *lowerkey, lvl + 1, page_no, tod) )
1481 // fix old fence for newly allocated right block page
1483 if( bt_insertkey (bt, oldkey+1, *oldkey, lvl + 1, new_page, tod) )
1486 // release Parent & Write locks
1488 if( bt_unlockpage (bt, new_page, BtLockParent) )
1491 if( bt_unlockpage (bt, page_no, BtLockParent) )
1497 // Insert new key into the btree at requested level.
1498 // Level zero pages are leaf pages and are unlocked at exit.
1499 // Interior nodes remain locked.
1501 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod)
1508 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1509 ptr = keyptr(bt->page, slot);
1513 bt->err = BTERR_ovflw;
1517 // if key already exists, update id and return
1521 if( !keycmp (ptr, key, len) ) {
1522 slotptr(page, slot)->dead = 0;
1523 slotptr(page, slot)->tod = tod;
1524 bt_putid(slotptr(page,slot)->id, id);
1525 if ( bt_update(bt, bt->page, bt->page_no) )
1527 return bt_unlockpage(bt, bt->page_no, BtLockWrite);
1530 // check if page has enough space
1532 if( page->min >= (page->cnt + 1) * sizeof(BtSlot) + sizeof(*page) + len + 1)
1535 if( bt_splitpage (bt, len) )
1539 // calculate next available slot and copy key into page
1541 page->min -= len + 1; // reset lowest used offset
1542 ((unsigned char *)page)[page->min] = len;
1543 memcpy ((unsigned char *)page + page->min +1, key, len );
1545 for( idx = slot; idx < page->cnt; idx++ )
1546 if( slotptr(page, idx)->dead )
1549 // now insert key into array before slot
1550 // preserving the fence slot
1552 if( idx == page->cnt )
1558 *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
1560 bt_putid(slotptr(page,slot)->id, id);
1561 slotptr(page, slot)->off = page->min;
1562 slotptr(page, slot)->tod = tod;
1563 slotptr(page, slot)->dead = 0;
1565 if ( bt_update(bt, bt->page, bt->page_no) )
1568 return bt_unlockpage(bt, bt->page_no, BtLockWrite);
1571 // cache page of keys into cursor and return starting slot for given key
1573 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
1577 // cache page for retrieval
1578 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1579 memcpy (bt->cursor, bt->page, bt->page_size);
1580 bt->cursor_page = bt->page_no;
1581 if ( bt_unlockpage(bt, bt->page_no, BtLockRead) )
1587 // return next slot for cursor page
1588 // or slide cursor right into next page
1590 uint bt_nextkey (BtDb *bt, uint slot)
1595 right = bt_getid(bt->cursor->right);
1596 while( slot++ < bt->cursor->cnt )
1597 if( slotptr(bt->cursor,slot)->dead )
1599 else if( right || (slot < bt->cursor->cnt))
1607 bt->cursor_page = right;
1609 if( bt_lockpage(bt, right,BtLockRead) )
1612 if( bt_mappage (bt, &bt->page, right) )
1615 memcpy (bt->cursor, bt->page, bt->page_size);
1616 if ( bt_unlockpage(bt, right, BtLockRead) )
1625 BtKey bt_key(BtDb *bt, uint slot)
1627 return keyptr(bt->cursor, slot);
1630 uid bt_uid(BtDb *bt, uint slot)
1632 return bt_getid(slotptr(bt->cursor,slot)->id);
1635 uint bt_tod(BtDb *bt, uint slot)
1637 return slotptr(bt->cursor,slot)->tod;
1642 // standalone program to index file of keys
1643 // then list them onto std-out
1645 int main (int argc, char **argv)
1647 uint slot, line = 0, off = 0, found = 0;
1648 int dead, ch, cnt = 0, bits = 12;
1649 unsigned char key[256];
1650 clock_t done, start;
1661 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]);
1662 fprintf (stderr, " page_bits: size of btree page in bits\n");
1663 fprintf (stderr, " mapped_pool_segments: size of buffer pool in segments\n");
1664 fprintf (stderr, " pages_per_segment: size of buffer pool segment in pages in bits\n");
1672 bits = atoi(argv[4]);
1675 map = atoi(argv[5]);
1678 fprintf (stderr, "Warning: buffer_pool > 65536 segments\n");
1680 if( map && map < 8 )
1681 fprintf (stderr, "Buffer_pool too small\n");
1684 pgblk = atoi(argv[6]);
1686 if( bits + pgblk > 30 )
1687 fprintf (stderr, "Warning: very large buffer pool segment size\n");
1690 off = atoi(argv[7]);
1692 bt = bt_open ((argv[1]), BT_rw, bits, map, pgblk);
1695 fprintf(stderr, "Index Open Error %s\n", argv[1]);
1699 switch(argv[3][0]| 0x20)
1702 fprintf(stderr, "started indexing for %s\n", argv[2]);
1703 if( argc > 2 && (in = fopen (argv[2], "rb")) )
1704 while( ch = getc(in), ch != EOF )
1708 sprintf((char *)key+len, "%.9d", line + off), len += 9;
1710 if( bt_insertkey (bt, key, len, 0, ++line, *tod) )
1711 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
1714 else if( len < 245 )
1716 fprintf(stderr, "finished adding keys, %d \n", line);
1720 fprintf(stderr, "started deleting keys for %s\n", argv[2]);
1721 if( argc > 2 && (in = fopen (argv[2], "rb")) )
1722 while( ch = getc(in), ch != EOF )
1726 sprintf((char *)key+len, "%.9d", line + off), len += 9;
1728 if( bt_deletekey (bt, key, len, 0) )
1729 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
1732 else if( len < 245 )
1734 fprintf(stderr, "finished deleting keys, %d \n", line);
1738 fprintf(stderr, "started finding keys for %s\n", argv[2]);
1739 if( argc > 2 && (in = fopen (argv[2], "rb")) )
1740 while( ch = getc(in), ch != EOF )
1744 sprintf((char *)key+len, "%.9d", line + off), len += 9;
1746 if( bt_findkey (bt, key, len) )
1749 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
1752 else if( len < 245 )
1754 fprintf(stderr, "finished search of %d keys, found %d\n", line, found);
1764 fprintf(stderr, " Time to complete: %.2f seconds\n", (float)(done - start) / CLOCKS_PER_SEC);
1769 fprintf(stderr, "started reading\n");
1771 if( slot = bt_startkey (bt, key, len) )
1774 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
1776 while( slot = bt_nextkey (bt, slot) )
1778 ptr = bt_key(bt, slot);
1779 fwrite (ptr->key, ptr->len, 1, stdout);
1780 fputc ('\n', stdout);
1783 fprintf(stderr, " Total keys read %d\n", cnt);