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
975 if ( bt_unlockpage(bt, ALLOC_page, BtLockWrite) )
982 if ( pwrite(bt->idx, page, bt->page_size, new_page << bt->page_bits) < bt->page_size )
983 return bt->err = BTERR_wrt, 0;
985 // if writing first page of hash block, zero last page in the block
987 if ( !reuse && bt->hashmask > 0 && (new_page & bt->hashmask) == 0 )
989 // use temp buffer to write zeros
990 memset(bt->zero, 0, bt->page_size);
991 if ( pwrite(bt->idx,bt->zero, bt->page_size, (new_page | bt->hashmask) << bt->page_bits) < bt->page_size )
992 return bt->err = BTERR_wrt, 0;
995 // bring new page into page-cache and copy page.
996 // this will extend the file into the new pages.
998 if( !(pmap = (char*)bt_hashpage(bt, new_page & ~bt->hashmask)) )
1001 memcpy(pmap+((new_page & bt->hashmask) << bt->page_bits), page, bt->page_size);
1006 if ( bt_unlockpage(bt, ALLOC_page, BtLockWrite) )
1012 // find slot in page for given key at a given level
1014 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1016 uint diff, higher = bt->page->cnt, low = 1, slot;
1019 // make stopper key an infinite fence value
1021 if( bt_getid (bt->page->right) )
1026 // low is the next candidate, higher is already
1027 // tested as .ge. the given key, loop ends when they meet
1029 while( diff = higher - low ) {
1030 slot = low + ( diff >> 1 );
1031 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1034 higher = slot, good++;
1037 // return zero if key is on right link page
1039 return good ? higher : 0;
1042 // find and load page at given level for given key
1043 // leave page rd or wr locked as requested
1045 int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, uint lock)
1047 uid page_no = ROOT_page, prevpage = 0;
1048 uint drill = 0xff, slot;
1049 uint mode, prevmode;
1051 // start at root of btree and drill down
1054 // determine lock mode of drill level
1055 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1057 bt->page_no = page_no;
1059 // obtain access lock using lock chaining
1061 if( page_no > ROOT_page )
1062 if( bt_lockpage(bt, bt->page_no, BtLockAccess) )
1066 if( bt_unlockpage(bt, prevpage, prevmode) )
1069 // obtain read lock using lock chaining
1071 if( bt_lockpage(bt, bt->page_no, mode) )
1074 if( page_no > ROOT_page )
1075 if( bt_unlockpage(bt, bt->page_no, BtLockAccess) )
1078 // map/obtain page contents
1080 if( bt_mappage (bt, &bt->page, page_no) )
1083 // re-read and re-lock root after determining actual level of root
1085 if( bt->page->lvl != drill) {
1086 if ( bt->page_no != ROOT_page )
1087 return bt->err = BTERR_struct, 0;
1089 drill = bt->page->lvl;
1091 if( lock == BtLockWrite && drill == lvl )
1092 if( bt_unlockpage(bt, page_no, mode) )
1098 // find key on page at this level
1099 // and descend to requested level
1101 if( !bt->page->kill && (slot = bt_findslot (bt, key, len)) ) {
1105 while( slotptr(bt->page, slot)->dead )
1106 if( slot++ < bt->page->cnt )
1109 page_no = bt_getid(bt->page->right);
1113 page_no = bt_getid(slotptr(bt->page, slot)->id);
1117 // or slide right into next page
1118 // (slide left from deleted page)
1121 page_no = bt_getid(bt->page->right);
1123 // continue down / right using overlapping locks
1124 // to protect pages being killed or split.
1127 prevpage = bt->page_no;
1131 // return error on end of right chain
1133 bt->err = BTERR_struct;
1134 return 0; // return error
1137 // find and delete key on page by marking delete flag bit
1138 // when page becomes empty, delete it
1140 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl)
1142 unsigned char lowerkey[256], higherkey[256];
1143 uint slot, tod, dirty = 0;
1147 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1148 ptr = keyptr(bt->page, slot);
1152 // if key is found delete it, otherwise ignore request
1154 if( !keycmp (ptr, key, len) )
1155 if( slotptr(bt->page, slot)->dead == 0 )
1156 dirty = slotptr(bt->page,slot)->dead = 1, bt->page->act--;
1158 // return if page is not empty, or it has no right sibling
1160 right = bt_getid(bt->page->right);
1161 page_no = bt->page_no;
1163 if( !right || bt->page->act )
1164 if ( dirty && bt_update(bt, bt->page, page_no) )
1167 return bt_unlockpage(bt, page_no, BtLockWrite);
1169 // obtain Parent lock over write lock
1171 if( bt_lockpage(bt, page_no, BtLockParent) )
1174 // cache copy of key to delete
1176 ptr = keyptr(bt->page, bt->page->cnt);
1177 memcpy(lowerkey, ptr, ptr->len + 1);
1179 // lock and map right page
1181 if ( bt_lockpage(bt, right, BtLockWrite) )
1184 if( bt_mappage (bt, &bt->temp, right) )
1187 // pull contents of next page into current empty page
1188 memcpy (bt->page, bt->temp, bt->page_size);
1190 // cache copy of key to update
1191 ptr = keyptr(bt->temp, bt->temp->cnt);
1192 memcpy(higherkey, ptr, ptr->len + 1);
1194 // Mark right page as deleted and point it to left page
1195 // until we can post updates at higher level.
1197 bt_putid(bt->temp->right, page_no);
1201 if ( bt_update(bt, bt->page, page_no) )
1204 if ( bt_update(bt, bt->temp, right) )
1207 if( bt_unlockpage(bt, right, BtLockWrite) )
1209 if( bt_unlockpage(bt, page_no, BtLockWrite) )
1212 // delete old lower key to consolidated node
1214 if( bt_deletekey (bt, lowerkey + 1, *lowerkey, lvl + 1) )
1217 // redirect higher key directly to consolidated node
1219 tod = (uint)time(NULL);
1221 if( bt_insertkey (bt, higherkey+1, *higherkey, lvl + 1, page_no, tod) )
1224 // obtain write lock and
1225 // add right block to free chain
1227 if( bt_freepage (bt, right) )
1230 // remove ParentModify lock
1232 if( bt_unlockpage(bt, page_no, BtLockParent) )
1238 // find key in leaf level and return row-id
1240 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1246 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1247 ptr = keyptr(bt->page, slot);
1251 // if key exists, return row-id
1252 // otherwise return 0
1254 if( ptr->len == len && !memcmp (ptr->key, key, len) )
1255 id = bt_getid(slotptr(bt->page,slot)->id);
1259 if ( bt_unlockpage(bt, bt->page_no, BtLockRead) )
1265 void bt_cleanpage(BtDb *bt)
1267 uint nxt = bt->page_size;
1268 BtPage page = bt->page;
1269 uint cnt = 0, idx = 0;
1270 uint max = page->cnt;
1273 memcpy (bt->frame, page, bt->page_size);
1275 // skip page info and set rest of page to zero
1276 memset (page+1, 0, bt->page_size - sizeof(*page));
1279 // try cleaning up page first
1281 while( cnt++ < max ) {
1282 // always leave fence key in list
1283 if( cnt < max && slotptr(bt->frame,cnt)->dead )
1287 key = keyptr(bt->frame, cnt);
1288 nxt -= key->len + 1;
1289 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1292 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1293 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1295 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1296 slotptr(page, idx)->off = nxt;
1302 // split the root and raise the height of the btree
1304 BTERR bt_splitroot(BtDb *bt, unsigned char *newkey, unsigned char *oldkey, uid page_no2)
1306 uint nxt = bt->page_size;
1307 BtPage root = bt->page;
1310 // Obtain an empty page to use, and copy the current
1311 // root contents into it
1313 if( !(new_page = bt_newpage(bt, root)) )
1316 // preserve the page info at the bottom
1317 // and set rest to zero
1319 memset(root+1, 0, bt->page_size - sizeof(*root));
1321 // insert first key on newroot page
1324 memcpy ((unsigned char *)root + nxt, newkey, *newkey + 1);
1325 bt_putid(slotptr(root, 1)->id, new_page);
1326 slotptr(root, 1)->off = nxt;
1328 // insert second key on newroot page
1329 // and increase the root height
1332 memcpy ((unsigned char *)root + nxt, oldkey, *oldkey + 1);
1333 bt_putid(slotptr(root, 2)->id, page_no2);
1334 slotptr(root, 2)->off = nxt;
1336 bt_putid(root->right, 0);
1337 root->min = nxt; // reset lowest used offset and key count
1342 // update and release root (bt->page)
1344 if( bt_update(bt, root, bt->page_no) )
1347 return bt_unlockpage(bt, bt->page_no, BtLockWrite);
1350 // split already locked full node
1353 BTERR bt_splitpage (BtDb *bt, uint len)
1355 uint cnt = 0, idx = 0, max, nxt = bt->page_size;
1356 unsigned char oldkey[256], lowerkey[256];
1357 uid page_no = bt->page_no, right;
1358 BtPage page = bt->page;
1359 uint lvl = page->lvl;
1368 // return if enough space now
1370 if( page->min >= (page->cnt + 1) * sizeof(BtSlot) + sizeof(*page) + len + 1)
1372 if ( bt_update(bt, page, page_no) )
1375 return bt_unlockpage(bt, page_no, BtLockWrite);
1378 // split higher half of keys to bt->frame
1379 // the last key (fence key) might be dead
1381 tod = (uint)time(NULL);
1383 memset (bt->frame, 0, bt->page_size);
1384 max = (int)page->cnt;
1388 while( cnt++ < max ) {
1389 key = keyptr(page, cnt);
1390 nxt -= key->len + 1;
1391 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
1392 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
1393 if( !(slotptr(bt->frame, idx)->dead = slotptr(page, cnt)->dead) )
1395 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
1396 slotptr(bt->frame, idx)->off = nxt;
1399 // remember existing fence key for new page to the right
1401 memcpy (oldkey, key, key->len + 1);
1403 bt->frame->bits = bt->page_bits;
1404 bt->frame->min = nxt;
1405 bt->frame->cnt = idx;
1406 bt->frame->lvl = lvl;
1410 if( page_no > ROOT_page ) {
1411 right = bt_getid (page->right);
1412 bt_putid(bt->frame->right, right);
1415 // get new free page and write frame to it.
1417 if( !(new_page = bt_newpage(bt, bt->frame)) )
1420 // update lower keys to continue in old page
1422 memcpy (bt->frame, page, bt->page_size);
1423 memset (page+1, 0, bt->page_size - sizeof(*page));
1424 nxt = bt->page_size;
1429 // assemble page of smaller keys
1430 // (they're all active keys)
1432 while( cnt++ < max / 2 ) {
1433 key = keyptr(bt->frame, cnt);
1434 nxt -= key->len + 1;
1435 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1436 memcpy(slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1437 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1438 slotptr(page, idx)->off = nxt;
1442 // remember fence key for old page
1444 memcpy(lowerkey, key, key->len + 1);
1445 bt_putid(page->right, new_page);
1449 // if current page is the root page, split it
1451 if( page_no == ROOT_page )
1452 return bt_splitroot (bt, lowerkey, oldkey, new_page);
1454 // update left (containing) node
1456 if( bt_update(bt, page, page_no) )
1459 // obtain Parent/Write locks
1460 // for left and right node pages
1462 if( bt_lockpage (bt, new_page, BtLockParent) )
1465 if( bt_lockpage (bt, page_no, BtLockParent) )
1468 // release wr lock on left page
1470 if( bt_unlockpage (bt, page_no, BtLockWrite) )
1473 // insert new fence for reformulated left block
1475 if( bt_insertkey (bt, lowerkey+1, *lowerkey, lvl + 1, page_no, tod) )
1478 // fix old fence for newly allocated right block page
1480 if( bt_insertkey (bt, oldkey+1, *oldkey, lvl + 1, new_page, tod) )
1483 // release Parent & Write locks
1485 if( bt_unlockpage (bt, new_page, BtLockParent) )
1488 if( bt_unlockpage (bt, page_no, BtLockParent) )
1494 // Insert new key into the btree at requested level.
1495 // Level zero pages are leaf pages and are unlocked at exit.
1496 // Interior nodes remain locked.
1498 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod)
1505 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1506 ptr = keyptr(bt->page, slot);
1510 bt->err = BTERR_ovflw;
1514 // if key already exists, update id and return
1518 if( !keycmp (ptr, key, len) ) {
1519 slotptr(page, slot)->dead = 0;
1520 slotptr(page, slot)->tod = tod;
1521 bt_putid(slotptr(page,slot)->id, id);
1522 if ( bt_update(bt, bt->page, bt->page_no) )
1524 return bt_unlockpage(bt, bt->page_no, BtLockWrite);
1527 // check if page has enough space
1529 if( page->min >= (page->cnt + 1) * sizeof(BtSlot) + sizeof(*page) + len + 1)
1532 if( bt_splitpage (bt, len) )
1536 // calculate next available slot and copy key into page
1538 page->min -= len + 1; // reset lowest used offset
1539 ((unsigned char *)page)[page->min] = len;
1540 memcpy ((unsigned char *)page + page->min +1, key, len );
1542 for( idx = slot; idx < page->cnt; idx++ )
1543 if( slotptr(page, idx)->dead )
1546 // now insert key into array before slot
1547 // preserving the fence slot
1549 if( idx == page->cnt )
1555 *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
1557 bt_putid(slotptr(page,slot)->id, id);
1558 slotptr(page, slot)->off = page->min;
1559 slotptr(page, slot)->tod = tod;
1560 slotptr(page, slot)->dead = 0;
1562 if ( bt_update(bt, bt->page, bt->page_no) )
1565 return bt_unlockpage(bt, bt->page_no, BtLockWrite);
1568 // cache page of keys into cursor and return starting slot for given key
1570 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
1574 // cache page for retrieval
1575 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1576 memcpy (bt->cursor, bt->page, bt->page_size);
1577 bt->cursor_page = bt->page_no;
1578 if ( bt_unlockpage(bt, bt->page_no, BtLockRead) )
1584 // return next slot for cursor page
1585 // or slide cursor right into next page
1587 uint bt_nextkey (BtDb *bt, uint slot)
1592 right = bt_getid(bt->cursor->right);
1593 while( slot++ < bt->cursor->cnt )
1594 if( slotptr(bt->cursor,slot)->dead )
1596 else if( right || (slot < bt->cursor->cnt))
1604 bt->cursor_page = right;
1606 if( bt_lockpage(bt, right,BtLockRead) )
1609 if( bt_mappage (bt, &bt->page, right) )
1612 memcpy (bt->cursor, bt->page, bt->page_size);
1613 if ( bt_unlockpage(bt, right, BtLockRead) )
1622 BtKey bt_key(BtDb *bt, uint slot)
1624 return keyptr(bt->cursor, slot);
1627 uid bt_uid(BtDb *bt, uint slot)
1629 return bt_getid(slotptr(bt->cursor,slot)->id);
1632 uint bt_tod(BtDb *bt, uint slot)
1634 return slotptr(bt->cursor,slot)->tod;
1639 // standalone program to index file of keys
1640 // then list them onto std-out
1642 int main (int argc, char **argv)
1644 uint slot, line = 0, off = 0, found = 0;
1645 int dead, ch, cnt = 0, bits = 12;
1646 unsigned char key[256];
1647 clock_t done, start;
1658 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]);
1659 fprintf (stderr, " page_bits: size of btree page in bits\n");
1660 fprintf (stderr, " mapped_pool_segments: size of buffer pool in segments\n");
1661 fprintf (stderr, " pages_per_segment: size of buffer pool segment in pages in bits\n");
1669 bits = atoi(argv[4]);
1672 map = atoi(argv[5]);
1675 fprintf (stderr, "Warning: buffer_pool > 65536 segments\n");
1677 if( map && map < 8 )
1678 fprintf (stderr, "Buffer_pool too small\n");
1681 pgblk = atoi(argv[6]);
1683 if( bits + pgblk > 30 )
1684 fprintf (stderr, "Warning: very large buffer pool segment size\n");
1687 off = atoi(argv[7]);
1689 bt = bt_open ((argv[1]), BT_rw, bits, map, pgblk);
1692 fprintf(stderr, "Index Open Error %s\n", argv[1]);
1696 switch(argv[3][0]| 0x20)
1699 fprintf(stderr, "started indexing for %s\n", argv[2]);
1700 if( argc > 2 && (in = fopen (argv[2], "rb")) )
1701 while( ch = getc(in), ch != EOF )
1705 sprintf((char *)key+len, "%.9d", line + off), len += 9;
1707 if( bt_insertkey (bt, key, len, 0, ++line, *tod) )
1708 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
1711 else if( len < 245 )
1713 fprintf(stderr, "finished adding keys, %d \n", line);
1717 fprintf(stderr, "started deleting keys for %s\n", argv[2]);
1718 if( argc > 2 && (in = fopen (argv[2], "rb")) )
1719 while( ch = getc(in), ch != EOF )
1723 sprintf((char *)key+len, "%.9d", line + off), len += 9;
1725 if( bt_deletekey (bt, key, len, 0) )
1726 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
1729 else if( len < 245 )
1731 fprintf(stderr, "finished deleting keys, %d \n", line);
1735 fprintf(stderr, "started finding keys for %s\n", argv[2]);
1736 if( argc > 2 && (in = fopen (argv[2], "rb")) )
1737 while( ch = getc(in), ch != EOF )
1741 sprintf((char *)key+len, "%.9d", line + off), len += 9;
1743 if( bt_findkey (bt, key, len) )
1746 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
1749 else if( len < 245 )
1751 fprintf(stderr, "finished search of %d keys, found %d\n", line, found);
1761 fprintf(stderr, " Time to complete: %.2f seconds\n", (float)(done - start) / CLOCKS_PER_SEC);
1766 fprintf(stderr, "started reading\n");
1768 if( slot = bt_startkey (bt, key, len) )
1771 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
1773 while( slot = bt_nextkey (bt, slot) )
1775 ptr = bt_key(bt, slot);
1776 fwrite (ptr->key, ptr->len, 1, stdout);
1777 fputc ('\n', stdout);
1780 fprintf(stderr, " Total keys read %d\n", cnt);