1 // foster btree version e2
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
53 typedef unsigned long long uid;
56 typedef unsigned long long off64_t;
57 typedef unsigned short ushort;
58 typedef unsigned int uint;
61 #define BT_ro 0x6f72 // ro
62 #define BT_rw 0x7772 // rw
64 #define BT_latchtable 128 // number of latch manager slots
66 #define BT_maxbits 24 // maximum page size in bits
67 #define BT_minbits 9 // minimum page size in bits
68 #define BT_minpage (1 << BT_minbits) // minimum page size
69 #define BT_maxpage (1 << BT_maxbits) // maximum page size
72 There are five lock types for each node in three independent sets:
73 1. (set 1) AccessIntent: Sharable. Going to Read the node. Incompatible with NodeDelete.
74 2. (set 1) NodeDelete: Exclusive. About to release the node. Incompatible with AccessIntent.
75 3. (set 2) ReadLock: Sharable. Read the node. Incompatible with WriteLock.
76 4. (set 2) WriteLock: Exclusive. Modify the node. Incompatible with ReadLock and other WriteLocks.
77 5. (set 3) ParentLock: Exclusive. Have parent adopt/delete maximum foster child from the node.
88 // Define the length of the page and key pointers
92 // Page key slot definition.
94 // If BT_maxbits is 15 or less, you can save 4 bytes
95 // for each key stored by making the first two uints
96 // into ushorts. You can also save 4 bytes by removing
97 // the tod field from the key.
99 // Keys are marked dead, but remain on the page until
100 // cleanup is called. The fence key (highest key) for
101 // the page is always present, even after cleanup.
104 uint off:BT_maxbits; // page offset for key start
105 uint dead:1; // set for deleted key
106 uint tod; // time-stamp for key
107 unsigned char id[BtId]; // id associated with key
110 // The key structure occupies space at the upper end of
111 // each page. It's a length byte followed by the value
116 unsigned char key[1];
119 // The first part of an index page.
120 // It is immediately followed
121 // by the BtSlot array of keys.
123 typedef struct Page {
124 volatile uint cnt; // count of keys in page
125 volatile uint act; // count of active keys
126 volatile uint min; // next key offset
127 volatile uint foster; // count of foster children
128 unsigned char bits; // page size in bits
129 unsigned char lvl:7; // level of page
130 unsigned char dirty:1; // page needs to be cleaned
131 unsigned char right[BtId]; // page number to right
134 // mode & definition for hash latch implementation
143 // mutex locks the other fields
144 // exclusive is set for write access
145 // share is count of read accessors
148 volatile ushort mutex:1;
149 volatile ushort exclusive:1;
150 volatile ushort pending:1;
151 volatile ushort share:13;
154 // hash table entries
157 BtSpinLatch latch[1];
158 volatile ushort slot; // Latch table entry at head of chain
161 // latch manager table structure
165 pthread_rwlock_t lock[1];
172 BtLatch readwr[1]; // read/write page lock
173 BtLatch access[1]; // Access Intent/Page delete
174 BtLatch parent[1]; // adoption of foster children
175 BtSpinLatch busy[1]; // slot is being moved between chains
176 volatile ushort next; // next entry in hash table chain
177 volatile ushort prev; // prev entry in hash table chain
178 volatile ushort pin; // number of outstanding locks
179 volatile ushort hash; // hash slot entry is under
180 volatile uid page_no; // latch set page number
183 // The memory mapping pool table buffer manager entry
186 unsigned long long int lru; // number of times accessed
187 uid basepage; // mapped base page number
188 char *map; // mapped memory pointer
189 ushort pin; // mapped page pin counter
190 ushort slot; // slot index in this array
191 void *hashprev; // previous pool entry for the same hash idx
192 void *hashnext; // next pool entry for the same hash idx
194 HANDLE hmap; // Windows memory mapping handle
198 // structure for latch manager on ALLOC_page
201 struct Page alloc[2]; // next & free page_nos in right ptr
202 BtSpinLatch lock[1]; // allocation area lite latch
203 ushort latchdeployed; // highest number of latch entries deployed
204 ushort nlatchpage; // number of latch pages at BT_latch
205 ushort latchtotal; // number of page latch entries
206 ushort latchhash; // number of latch hash table slots
207 ushort latchvictim; // next latch entry to examine
208 BtHashEntry table[0]; // the hash table
211 // The object structure for Btree access
214 uint page_size; // page size
215 uint page_bits; // page size in bits
216 uint seg_bits; // seg size in pages in bits
217 uint mode; // read-write mode
220 char *pooladvise; // bit maps for pool page advisements
224 ushort poolcnt; // highest page pool node in use
225 ushort poolmax; // highest page pool node allocated
226 ushort poolmask; // total number of pages in mmap segment - 1
227 ushort hashsize; // size of Hash Table for pool entries
228 ushort evicted; // last evicted hash table slot
229 ushort *hash; // hash table of pool entries
230 BtPool *pool; // memory pool page segments
231 BtSpinLatch *latch; // latches for pool hash slots
232 BtLatchMgr *latchmgr; // mapped latch page from allocation page
233 BtLatchSet *latchsets; // mapped latch set from latch pages
235 HANDLE halloc; // allocation and latch table handle
240 BtMgr *mgr; // buffer manager for thread
241 BtPage cursor; // cached frame for start/next (never mapped)
242 BtPage frame; // spare frame for the page split (never mapped)
243 BtPage zero; // page frame for zeroes at end of file
244 BtPage page; // current page
245 uid page_no; // current page number
246 uid cursor_page; // current cursor page number
247 BtLatchSet *set; // current page latch set
248 BtPool *pool; // current page pool
249 unsigned char *mem; // frame, cursor, page memory buffer
250 int found; // last delete was found
251 int err; // last error
266 extern void bt_close (BtDb *bt);
267 extern BtDb *bt_open (BtMgr *mgr);
268 extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod, uint lvl);
269 extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len);
270 extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
271 extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
272 extern uint bt_nextkey (BtDb *bt, uint slot);
275 extern BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolsize, uint segsize, uint hashsize);
276 void bt_mgrclose (BtMgr *mgr);
278 // Helper functions to return cursor slot values
280 extern BtKey bt_key (BtDb *bt, uint slot);
281 extern uid bt_uid (BtDb *bt, uint slot);
282 extern uint bt_tod (BtDb *bt, uint slot);
284 // BTree page number constants
285 #define ALLOC_page 0 // allocation & lock manager hash table
286 #define ROOT_page 1 // root of the btree
287 #define LEAF_page 2 // first page of leaves
288 #define LATCH_page 3 // pages for lock manager
290 // Number of levels to create in a new BTree
294 // The page is allocated from low and hi ends.
295 // The key offsets and row-id's are allocated
296 // from the bottom, while the text of the key
297 // is allocated from the top. When the two
298 // areas meet, the page is split into two.
300 // A key consists of a length byte, two bytes of
301 // index number (0 - 65534), and up to 253 bytes
302 // of key value. Duplicate keys are discarded.
303 // Associated with each key is a 48 bit row-id.
305 // The b-tree root is always located at page 1.
306 // The first leaf page of level zero is always
307 // located on page 2.
309 // When to root page fills, it is split in two and
310 // the tree height is raised by a new root at page
311 // one with two keys.
313 // Deleted keys are marked with a dead bit until
314 // page cleanup The fence key for a node is always
315 // present, even after deletion and cleanup.
317 // Groups of pages called segments from the btree are
318 // cached with memory mapping. A hash table is used to keep
319 // track of the cached segments. This behaviour is controlled
320 // by the cache block size parameter to bt_open.
322 // To achieve maximum concurrency one page is locked at a time
323 // as the tree is traversed to find leaf key in question.
325 // An adoption traversal leaves the parent node locked as the
326 // tree is traversed to the level in quesiton.
328 // Page 0 is dedicated to lock for new page extensions,
329 // and chains empty pages together for reuse.
331 // Empty pages are chained together through the ALLOC page and reused.
333 // Access macros to address slot and key values from the page
335 #define slotptr(page, slot) (((BtSlot *)(page+1)) + (slot-1))
336 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
338 void bt_putid(unsigned char *dest, uid id)
343 dest[i] = (unsigned char)id, id >>= 8;
346 uid bt_getid(unsigned char *src)
351 for( i = 0; i < BtId; i++ )
352 id <<= 8, id |= *src++;
357 // wait until write lock mode is clear
358 // and add 1 to the share count
360 void bt_spinreadlock(BtSpinLatch *latch)
366 while( __sync_fetch_and_or((ushort *)latch, Mutex) & Mutex )
369 while( _InterlockedOr16((ushort *)latch, Mutex) & Mutex )
373 // see if exclusive request is granted or pending
375 if( prev = !(latch->exclusive | latch->pending) )
377 __sync_fetch_and_add((ushort *)latch, Share);
379 _InterlockedExchangeAdd16 ((ushort *)latch, Share);
383 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
385 _InterlockedAnd16((ushort *)latch, ~Mutex);
390 } while( sched_yield(), 1 );
392 } while( SwitchToThread(), 1 );
396 // wait for other read and write latches to relinquish
398 void bt_spinwritelock(BtSpinLatch *latch)
402 while( __sync_fetch_and_or((ushort *)latch, Mutex | Pending) & Mutex )
405 while( _InterlockedOr16((ushort *)latch, Mutex | Pending) & Mutex )
408 if( !(latch->share | latch->exclusive) ) {
410 __sync_fetch_and_or((ushort *)latch, Write);
411 __sync_fetch_and_and ((ushort *)latch, ~(Mutex | Pending));
413 _InterlockedOr16((ushort *)latch, Write);
414 _InterlockedAnd16((ushort *)latch, ~(Mutex | Pending));
420 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
422 _InterlockedAnd16((ushort *)latch, ~Mutex);
432 // try to obtain write lock
434 // return 1 if obtained,
437 int bt_spinwritetry(BtSpinLatch *latch)
442 if( prev = __sync_fetch_and_or((ushort *)latch, Mutex), prev & Mutex )
445 if( prev = _InterlockedOr16((ushort *)latch, Mutex), prev & Mutex )
448 // take write access if all bits are clear
452 __sync_fetch_and_or ((ushort *)latch, Write);
454 _InterlockedOr16((ushort *)latch, Write);
458 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
460 _InterlockedAnd16((ushort *)latch, ~Mutex);
467 void bt_spinreleasewrite(BtSpinLatch *latch)
470 __sync_fetch_and_and ((ushort *)latch, ~Write);
472 _InterlockedAnd16((ushort *)latch, ~Write);
476 // decrement reader count
478 void bt_spinreleaseread(BtSpinLatch *latch)
481 __sync_fetch_and_add((ushort *)latch, -Share);
483 _InterlockedExchangeAdd16 ((ushort *)latch, -Share);
487 void bt_initlockset (BtLatchSet *set, int reuse)
490 pthread_rwlockattr_t rwattr[1];
493 pthread_rwlock_destroy (set->readwr->lock);
494 pthread_rwlock_destroy (set->access->lock);
495 pthread_rwlock_destroy (set->parent->lock);
498 pthread_rwlockattr_init (rwattr);
499 pthread_rwlockattr_setkind_np (rwattr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
500 pthread_rwlockattr_setpshared (rwattr, PTHREAD_PROCESS_SHARED);
502 pthread_rwlock_init (set->readwr->lock, rwattr);
503 pthread_rwlock_init (set->access->lock, rwattr);
504 pthread_rwlock_init (set->parent->lock, rwattr);
505 pthread_rwlockattr_destroy (rwattr);
507 InitializeSRWLock (set->readwr->srw);
508 InitializeSRWLock (set->access->srw);
509 InitializeSRWLock (set->parent->srw);
513 // link latch table entry into latch hash table
515 void bt_latchlink (BtDb *bt, ushort hashidx, ushort victim, uid page_no)
517 BtLatchSet *set = bt->mgr->latchsets + victim;
519 if( set->next = bt->mgr->latchmgr->table[hashidx].slot )
520 bt->mgr->latchsets[set->next].prev = victim;
522 bt->mgr->latchmgr->table[hashidx].slot = victim;
523 set->page_no = page_no;
528 void bt_unpinlatch (BtLatchSet *set)
531 __sync_fetch_and_add(&set->pin, -1);
533 _InterlockedDecrement16 (&set->pin);
537 // find existing latchset or inspire new one
538 // return with latchset pinned
540 BtLatchSet *bt_pinlatch (BtDb *bt, uid page_no)
542 ushort hashidx = page_no % bt->mgr->latchmgr->latchhash;
543 ushort slot, avail = 0, victim, idx;
546 // obtain read lock on hash table entry
548 bt_spinreadlock(bt->mgr->latchmgr->table[hashidx].latch);
550 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
552 set = bt->mgr->latchsets + slot;
553 if( page_no == set->page_no )
555 } while( slot = set->next );
559 __sync_fetch_and_add(&set->pin, 1);
561 _InterlockedIncrement16 (&set->pin);
565 bt_spinreleaseread (bt->mgr->latchmgr->table[hashidx].latch);
570 // try again, this time with write lock
572 bt_spinwritelock(bt->mgr->latchmgr->table[hashidx].latch);
574 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
576 set = bt->mgr->latchsets + slot;
577 if( page_no == set->page_no )
579 if( !set->pin && !avail )
581 } while( slot = set->next );
583 // found our entry, or take over an unpinned one
585 if( slot || (slot = avail) ) {
586 set = bt->mgr->latchsets + slot;
588 __sync_fetch_and_add(&set->pin, 1);
590 _InterlockedIncrement16 (&set->pin);
592 set->page_no = page_no;
593 bt_spinreleasewrite(bt->mgr->latchmgr->table[hashidx].latch);
597 // see if there are any unused entries
599 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, 1) + 1;
601 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchdeployed);
604 if( victim < bt->mgr->latchmgr->latchtotal ) {
605 set = bt->mgr->latchsets + victim;
607 __sync_fetch_and_add(&set->pin, 1);
609 _InterlockedIncrement16 (&set->pin);
611 bt_initlockset (set, 0);
612 bt_latchlink (bt, hashidx, victim, page_no);
613 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
618 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, -1);
620 victim = _InterlockedDecrement16 (&bt->mgr->latchmgr->latchdeployed);
622 // find and reuse previous lock entry
626 victim = __sync_fetch_and_add(&bt->mgr->latchmgr->latchvictim, 1);
628 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchvictim) - 1;
630 // we don't use slot zero
632 if( victim %= bt->mgr->latchmgr->latchtotal )
633 set = bt->mgr->latchsets + victim;
637 // take control of our slot
638 // from other threads
640 if( set->pin || !bt_spinwritetry (set->busy) )
645 // try to get write lock on hash chain
646 // skip entry if not obtained
647 // or has outstanding locks
649 if( !bt_spinwritetry (bt->mgr->latchmgr->table[idx].latch) ) {
650 bt_spinreleasewrite (set->busy);
655 bt_spinreleasewrite (set->busy);
656 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
660 // unlink our available victim from its hash chain
663 bt->mgr->latchsets[set->prev].next = set->next;
665 bt->mgr->latchmgr->table[idx].slot = set->next;
668 bt->mgr->latchsets[set->next].prev = set->prev;
670 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
672 __sync_fetch_and_add(&set->pin, 1);
674 _InterlockedIncrement16 (&set->pin);
676 bt_initlockset (set, 1);
677 bt_latchlink (bt, hashidx, victim, page_no);
678 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
679 bt_spinreleasewrite (set->busy);
684 void bt_mgrclose (BtMgr *mgr)
689 // release mapped pages
690 // note that slot zero is never used
692 for( slot = 1; slot < mgr->poolmax; slot++ ) {
693 pool = mgr->pool + slot;
696 munmap (pool->map, (mgr->poolmask+1) << mgr->page_bits);
699 FlushViewOfFile(pool->map, 0);
700 UnmapViewOfFile(pool->map);
701 CloseHandle(pool->hmap);
707 munmap (mgr->latchsets, mgr->latchmgr->nlatchpage * mgr->page_size);
708 munmap (mgr->latchmgr, mgr->page_size);
710 FlushViewOfFile(mgr->latchmgr, 0);
711 UnmapViewOfFile(mgr->latchmgr);
712 CloseHandle(mgr->halloc);
719 free (mgr->pooladvise);
722 FlushFileBuffers(mgr->idx);
723 CloseHandle(mgr->idx);
724 GlobalFree (mgr->pool);
725 GlobalFree (mgr->hash);
726 GlobalFree (mgr->latch);
731 // close and release memory
733 void bt_close (BtDb *bt)
740 VirtualFree (bt->mem, 0, MEM_RELEASE);
745 // open/create new btree buffer manager
747 // call with file_name, BT_openmode, bits in page size (e.g. 16),
748 // size of mapped page pool (e.g. 8192)
750 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
752 uint lvl, attr, cacheblk, last, slot, idx;
753 uint nlatchpage, latchhash;
754 BtLatchMgr *latchmgr;
762 SYSTEM_INFO sysinfo[1];
765 // determine sanity of page size and buffer pool
767 if( bits > BT_maxbits )
769 else if( bits < BT_minbits )
773 return NULL; // must have buffer pool
776 mgr = calloc (1, sizeof(BtMgr));
778 mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
781 return free(mgr), NULL;
783 cacheblk = 4096; // minimum mmap segment size for unix
786 mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
787 attr = FILE_ATTRIBUTE_NORMAL;
788 mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
790 if( mgr->idx == INVALID_HANDLE_VALUE )
791 return GlobalFree(mgr), NULL;
793 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
794 GetSystemInfo(sysinfo);
795 cacheblk = sysinfo->dwAllocationGranularity;
799 latchmgr = malloc (BT_maxpage);
802 // read minimum page size to get root info
804 if( size = lseek (mgr->idx, 0L, 2) ) {
805 if( pread(mgr->idx, latchmgr, BT_minpage, 0) == BT_minpage )
806 bits = latchmgr->alloc->bits;
808 return free(mgr), free(latchmgr), NULL;
809 } else if( mode == BT_ro )
810 return free(latchmgr), free (mgr), NULL;
812 latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
813 size = GetFileSize(mgr->idx, amt);
816 if( !ReadFile(mgr->idx, (char *)latchmgr, BT_minpage, amt, NULL) )
817 return bt_mgrclose (mgr), NULL;
818 bits = latchmgr->alloc->bits;
819 } else if( mode == BT_ro )
820 return bt_mgrclose (mgr), NULL;
823 mgr->page_size = 1 << bits;
824 mgr->page_bits = bits;
826 mgr->poolmax = poolmax;
829 if( cacheblk < mgr->page_size )
830 cacheblk = mgr->page_size;
832 // mask for partial memmaps
834 mgr->poolmask = (cacheblk >> bits) - 1;
836 // see if requested size of pages per memmap is greater
838 if( (1 << segsize) > mgr->poolmask )
839 mgr->poolmask = (1 << segsize) - 1;
843 while( (1 << mgr->seg_bits) <= mgr->poolmask )
846 mgr->hashsize = hashsize;
849 mgr->pool = calloc (poolmax, sizeof(BtPool));
850 mgr->hash = calloc (hashsize, sizeof(ushort));
851 mgr->latch = calloc (hashsize, sizeof(BtSpinLatch));
852 mgr->pooladvise = calloc (poolmax, (mgr->poolmask + 8) / 8);
854 mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * sizeof(BtPool));
855 mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
856 mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtSpinLatch));
862 // initialize an empty b-tree with latch page, root page, page of leaves
863 // and page(s) of latches
865 memset (latchmgr, 0, 1 << bits);
866 nlatchpage = BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1;
867 bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
868 latchmgr->alloc->bits = mgr->page_bits;
870 latchmgr->nlatchpage = nlatchpage;
871 latchmgr->latchtotal = nlatchpage * (mgr->page_size / sizeof(BtLatchSet));
873 // initialize latch manager
875 latchhash = (mgr->page_size - sizeof(BtLatchMgr)) / sizeof(BtHashEntry);
877 // size of hash table = total number of latchsets
879 if( latchhash > latchmgr->latchtotal )
880 latchhash = latchmgr->latchtotal;
882 latchmgr->latchhash = latchhash;
885 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
886 return free(latchmgr), bt_mgrclose (mgr), NULL;
888 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
889 return bt_mgrclose (mgr), NULL;
891 if( *amt < mgr->page_size )
892 return bt_mgrclose (mgr), NULL;
895 memset (latchmgr, 0, 1 << bits);
896 latchmgr->alloc->bits = mgr->page_bits;
898 for( lvl=MIN_lvl; lvl--; ) {
899 slotptr(latchmgr->alloc, 1)->off = mgr->page_size - 3;
900 bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
901 key = keyptr(latchmgr->alloc, 1);
902 key->len = 2; // create stopper key
905 latchmgr->alloc->min = mgr->page_size - 3;
906 latchmgr->alloc->lvl = lvl;
907 latchmgr->alloc->cnt = 1;
908 latchmgr->alloc->act = 1;
910 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
911 return bt_mgrclose (mgr), NULL;
913 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
914 return bt_mgrclose (mgr), NULL;
916 if( *amt < mgr->page_size )
917 return bt_mgrclose (mgr), NULL;
921 // clear out latch manager locks
922 // and rest of pages to round out segment
924 memset(latchmgr, 0, mgr->page_size);
927 while( last <= ((MIN_lvl + 1 + nlatchpage) | mgr->poolmask) ) {
929 pwrite(mgr->idx, latchmgr, mgr->page_size, last << mgr->page_bits);
931 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
932 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
933 return bt_mgrclose (mgr), NULL;
934 if( *amt < mgr->page_size )
935 return bt_mgrclose (mgr), NULL;
942 flag = PROT_READ | PROT_WRITE;
943 mgr->latchmgr = mmap (0, mgr->page_size, flag, MAP_SHARED, mgr->idx, ALLOC_page * mgr->page_size);
944 if( mgr->latchmgr == MAP_FAILED )
945 return bt_mgrclose (mgr), NULL;
946 mgr->latchsets = (BtLatchSet *)mmap (0, mgr->latchmgr->nlatchpage * mgr->page_size, flag, MAP_SHARED, mgr->idx, LATCH_page * mgr->page_size);
947 if( mgr->latchsets == MAP_FAILED )
948 return bt_mgrclose (mgr), NULL;
950 flag = PAGE_READWRITE;
951 mgr->halloc = CreateFileMapping(mgr->idx, NULL, flag, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size, NULL);
953 return bt_mgrclose (mgr), NULL;
955 flag = FILE_MAP_WRITE;
956 mgr->latchmgr = MapViewOfFile(mgr->halloc, flag, 0, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size);
958 return GetLastError(), bt_mgrclose (mgr), NULL;
960 mgr->latchsets = (void *)((char *)mgr->latchmgr + LATCH_page * mgr->page_size);
966 VirtualFree (latchmgr, 0, MEM_RELEASE);
971 // open BTree access method
972 // based on buffer manager
974 BtDb *bt_open (BtMgr *mgr)
976 BtDb *bt = malloc (sizeof(*bt));
978 memset (bt, 0, sizeof(*bt));
981 bt->mem = malloc (3 *mgr->page_size);
983 bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
985 bt->frame = (BtPage)bt->mem;
986 bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
987 bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
989 memset(bt->zero, 0, mgr->page_size);
993 // compare two keys, returning > 0, = 0, or < 0
994 // as the comparison value
996 int keycmp (BtKey key1, unsigned char *key2, uint len2)
998 uint len1 = key1->len;
1001 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
1014 void bt_readlock(BtLatch *latch)
1017 pthread_rwlock_rdlock (latch->lock);
1019 AcquireSRWLockShared (latch->srw);
1023 // wait for other read and write latches to relinquish
1025 void bt_writelock(BtLatch *latch)
1028 pthread_rwlock_wrlock (latch->lock);
1030 AcquireSRWLockExclusive (latch->srw);
1034 // try to obtain write lock
1036 // return 1 if obtained,
1037 // 0 if already write or read locked
1039 int bt_writetry(BtLatch *latch)
1044 result = !pthread_rwlock_trywrlock (latch->lock);
1046 result = TryAcquireSRWLockExclusive (latch->srw);
1053 void bt_releasewrite(BtLatch *latch)
1056 pthread_rwlock_unlock (latch->lock);
1058 ReleaseSRWLockExclusive (latch->srw);
1062 // decrement reader count
1064 void bt_releaseread(BtLatch *latch)
1067 pthread_rwlock_unlock (latch->lock);
1069 ReleaseSRWLockShared (latch->srw);
1075 // find segment in pool
1076 // must be called with hashslot idx locked
1077 // return NULL if not there
1078 // otherwise return node
1080 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
1085 // compute start of hash chain in pool
1087 if( slot = bt->mgr->hash[idx] )
1088 pool = bt->mgr->pool + slot;
1092 page_no &= ~bt->mgr->poolmask;
1094 while( pool->basepage != page_no )
1095 if( pool = pool->hashnext )
1103 // add segment to hash table
1105 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
1110 pool->hashprev = pool->hashnext = NULL;
1111 pool->basepage = page_no & ~bt->mgr->poolmask;
1114 if( slot = bt->mgr->hash[idx] ) {
1115 node = bt->mgr->pool + slot;
1116 pool->hashnext = node;
1117 node->hashprev = pool;
1120 bt->mgr->hash[idx] = pool->slot;
1123 // find best segment to evict from buffer pool
1125 BtPool *bt_findlru (BtDb *bt, uint hashslot)
1127 unsigned long long int target = ~0LL;
1128 BtPool *pool = NULL, *node;
1133 node = bt->mgr->pool + hashslot;
1135 // scan pool entries under hash table slot
1140 if( node->lru > target )
1144 } while( node = node->hashnext );
1149 // map new buffer pool segment to virtual memory
1151 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
1153 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
1154 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
1158 flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
1159 pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED, bt->mgr->idx, off);
1160 if( pool->map == MAP_FAILED )
1161 return bt->err = BTERR_map;
1162 // clear out madvise issued bits
1163 memset (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8) / 8), 0, (bt->mgr->poolmask + 8)/8);
1165 flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
1166 pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
1168 return bt->err = BTERR_map;
1170 flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
1171 pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1173 return bt->err = BTERR_map;
1178 // calculate page within pool
1180 BtPage bt_page (BtDb *bt, BtPool *pool, uid page_no)
1182 uint subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1185 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1188 uint idx = subpage / 8;
1189 uint bit = subpage % 8;
1191 if( ~((bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] >> bit) & 1 ) {
1192 madvise (page, bt->mgr->page_size, MADV_WILLNEED);
1193 (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] |= 1 << bit;
1202 void bt_unpinpool (BtPool *pool)
1205 __sync_fetch_and_add(&pool->pin, -1);
1207 _InterlockedDecrement16 (&pool->pin);
1211 // find or place requested page in segment-pool
1212 // return pool table entry, incrementing pin
1214 BtPool *bt_pinpool(BtDb *bt, uid page_no)
1216 BtPool *pool, *node, *next;
1217 uint slot, idx, victim;
1220 // lock hash table chain
1222 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1223 bt_spinreadlock (&bt->mgr->latch[idx]);
1225 // look up in hash table
1227 if( pool = bt_findpool(bt, page_no, idx) ) {
1229 __sync_fetch_and_add(&pool->pin, 1);
1231 _InterlockedIncrement16 (&pool->pin);
1233 bt_spinreleaseread (&bt->mgr->latch[idx]);
1238 // upgrade to write lock
1240 bt_spinreleaseread (&bt->mgr->latch[idx]);
1241 bt_spinwritelock (&bt->mgr->latch[idx]);
1243 // try to find page in pool with write lock
1245 if( pool = bt_findpool(bt, page_no, idx) ) {
1247 __sync_fetch_and_add(&pool->pin, 1);
1249 _InterlockedIncrement16 (&pool->pin);
1251 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1256 // allocate a new pool node
1257 // and add to hash table
1260 slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
1262 slot = _InterlockedIncrement16 (&bt->mgr->poolcnt) - 1;
1265 if( ++slot < bt->mgr->poolmax ) {
1266 pool = bt->mgr->pool + slot;
1269 if( bt_mapsegment(bt, pool, page_no) )
1272 bt_linkhash(bt, pool, page_no, idx);
1274 __sync_fetch_and_add(&pool->pin, 1);
1276 _InterlockedIncrement16 (&pool->pin);
1278 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1282 // pool table is full
1283 // find best pool entry to evict
1286 __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
1288 _InterlockedDecrement16 (&bt->mgr->poolcnt);
1293 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
1295 victim = _InterlockedIncrement16 (&bt->mgr->evicted) - 1;
1297 victim %= bt->mgr->hashsize;
1299 // try to get write lock
1300 // skip entry if not obtained
1302 if( !bt_spinwritetry (&bt->mgr->latch[victim]) )
1305 // if cache entry is empty
1306 // or no slots are unpinned
1309 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
1310 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1314 // unlink victim pool node from hash table
1316 if( node = pool->hashprev )
1317 node->hashnext = pool->hashnext;
1318 else if( node = pool->hashnext )
1319 bt->mgr->hash[victim] = node->slot;
1321 bt->mgr->hash[victim] = 0;
1323 if( node = pool->hashnext )
1324 node->hashprev = pool->hashprev;
1326 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1328 // remove old file mapping
1330 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1332 FlushViewOfFile(pool->map, 0);
1333 UnmapViewOfFile(pool->map);
1334 CloseHandle(pool->hmap);
1338 // create new pool mapping
1339 // and link into hash table
1341 if( bt_mapsegment(bt, pool, page_no) )
1344 bt_linkhash(bt, pool, page_no, idx);
1346 __sync_fetch_and_add(&pool->pin, 1);
1348 _InterlockedIncrement16 (&pool->pin);
1350 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1355 // place write, read, or parent lock on requested page_no.
1356 // pin to buffer pool and return latchset pointer
1358 void bt_lockpage(BtLock mode, BtLatchSet *set)
1362 bt_readlock (set->readwr);
1365 bt_writelock (set->readwr);
1368 bt_readlock (set->access);
1371 bt_writelock (set->access);
1374 bt_writelock (set->parent);
1379 // remove write, read, or parent lock on requested page_no.
1381 void bt_unlockpage(BtLock mode, BtLatchSet *set)
1385 bt_releaseread (set->readwr);
1388 bt_releasewrite (set->readwr);
1391 bt_releaseread (set->access);
1394 bt_releasewrite (set->access);
1397 bt_releasewrite (set->parent);
1402 // allocate a new page and write page into it
1404 uid bt_newpage(BtDb *bt, BtPage page)
1412 // lock allocation page
1414 bt_spinwritelock(bt->mgr->latchmgr->lock);
1416 // use empty chain first
1417 // else allocate empty page
1419 if( new_page = bt_getid(bt->mgr->latchmgr->alloc[1].right) ) {
1420 if( pool = bt_pinpool (bt, new_page) )
1421 pmap = bt_page (bt, pool, new_page);
1424 bt_putid(bt->mgr->latchmgr->alloc[1].right, bt_getid(pmap->right));
1425 bt_unpinpool (pool);
1428 new_page = bt_getid(bt->mgr->latchmgr->alloc->right);
1429 bt_putid(bt->mgr->latchmgr->alloc->right, new_page+1);
1433 // if writing first page of pool block, zero last page in the block
1435 if ( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1437 // use zero buffer to write zeros
1438 if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1439 return bt->err = BTERR_wrt, 0;
1442 // unlock allocation latch
1444 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1446 if ( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1447 return bt->err = BTERR_wrt, 0;
1450 // unlock allocation latch
1452 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1454 // bring new page into pool and copy page.
1455 // this will extend the file into the new pages.
1456 // NB -- no latch required
1458 if( pool = bt_pinpool (bt, new_page) )
1459 pmap = bt_page (bt, pool, new_page);
1463 memcpy(pmap, page, bt->mgr->page_size);
1464 bt_unpinpool (pool);
1469 // find slot in page for given key at a given level
1471 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1473 uint diff, higher = bt->page->cnt, low = 1, slot;
1475 // low is the lowest candidate, higher is already
1476 // tested as .ge. the given key, loop ends when they meet
1478 while( diff = higher - low ) {
1479 slot = low + ( diff >> 1 );
1480 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1489 // find and load page at given level for given key
1490 // leave page rd or wr locked as requested
1492 int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, BtLock lock)
1494 uid page_no = ROOT_page, prevpage = 0;
1495 BtLatchSet *set, *prevset;
1496 uint drill = 0xff, slot;
1497 uint mode, prevmode;
1500 // start at root of btree and drill down
1503 // determine lock mode of drill level
1504 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1506 // obtain latch set for this page
1508 bt->set = bt_pinlatch (bt, page_no);
1509 bt->page_no = page_no;
1511 // pin page contents
1513 if( bt->pool = bt_pinpool (bt, page_no) )
1514 bt->page = bt_page (bt, bt->pool, page_no);
1518 // obtain access lock using lock chaining with Access mode
1520 if( page_no > ROOT_page )
1521 bt_lockpage(BtLockAccess, bt->set);
1523 // now unlock and unpin our (possibly foster) parent
1526 bt_unlockpage(prevmode, prevset);
1527 bt_unpinlatch (prevset);
1528 bt_unpinpool (prevpool);
1532 // obtain read lock using lock chaining
1534 bt_lockpage(mode, bt->set);
1536 if( page_no > ROOT_page )
1537 bt_unlockpage(BtLockAccess, bt->set);
1539 // re-read and re-lock root after determining actual level of root
1541 if( page_no == ROOT_page )
1542 if( bt->page->lvl != drill) {
1543 drill = bt->page->lvl;
1545 if( lock == BtLockWrite && drill == lvl ) {
1546 bt_unlockpage(mode, bt->set);
1547 bt_unpinlatch (bt->set);
1548 bt_unpinpool (bt->pool);
1553 prevpage = bt->page_no;
1554 prevpool = bt->pool;
1558 // find key on page at this level
1559 // and either descend to requested level
1560 // or return key slot
1562 slot = bt_findslot (bt, key, len);
1564 // is this slot < foster child area
1565 // on the requested level?
1567 // if so, return actual slot even if dead
1569 if( slot <= bt->page->cnt - bt->page->foster )
1573 // find next active slot
1575 // note: foster children are never dead
1576 // nor fence keys for interiour nodes
1578 while( slotptr(bt->page, slot)->dead )
1579 if( slot++ < bt->page->cnt )
1582 return bt->err = BTERR_struct, 0; // last key shouldn't be deleted
1584 // is this slot < foster child area
1585 // if so, drill to next level
1587 if( slot <= bt->page->cnt - bt->page->foster )
1590 // continue right onto foster child
1591 // or down to next level.
1593 page_no = bt_getid(slotptr(bt->page, slot)->id);
1597 // return error on end of chain
1599 bt->err = BTERR_struct;
1600 return 0; // return error
1603 // find and delete key on page by marking delete flag bit
1604 // when leaf page becomes empty, delete it from the btree
1606 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len)
1608 unsigned char leftkey[256];
1609 BtLatchSet *rset, *set;
1610 BtPool *pool, *rpool;
1616 if( slot = bt_loadpage (bt, key, len, 0, BtLockWrite) )
1617 ptr = keyptr(bt->page, slot);
1621 // if key is found delete it, otherwise ignore request
1622 // note that fence keys of interiour nodes are not deleted.
1624 if( bt->found = !keycmp (ptr, key, len) )
1625 if( bt->found = slotptr(bt->page, slot)->dead == 0 ) {
1626 slotptr(bt->page,slot)->dead = 1;
1627 if( slot < bt->page->cnt )
1628 bt->page->dirty = 1;
1632 page_no = bt->page_no;
1637 // return if page is not empty or not found
1639 if( page->act || !bt->found ) {
1640 bt_unlockpage(BtLockWrite, set);
1641 bt_unpinlatch (set);
1642 bt_unpinpool (pool);
1646 // cache copy of fence key of empty node
1648 ptr = keyptr(page, page->cnt);
1649 memcpy(leftkey, ptr, ptr->len + 1);
1651 // release write lock on empty node
1652 // obtain Parent lock
1654 bt_unlockpage(BtLockWrite, set);
1655 bt_lockpage(BtLockParent, set);
1657 // load and lock parent to see
1658 // if delete of empty node is OK
1659 // ie, not a fence key of parent
1662 if( slot = bt_loadpage (bt, leftkey+1, *leftkey, 1, BtLockWrite) )
1663 ptr = keyptr(bt->page, slot);
1667 // does parent level contain our fence key yet?
1668 // and is it free of foster children?
1670 if( !bt->page->foster )
1671 if( !keycmp (ptr, leftkey+1, *leftkey) )
1674 bt_unlockpage(BtLockWrite, bt->set);
1675 bt_unpinlatch (bt->set);
1676 bt_unpinpool (bt->pool);
1684 // find our left fence key
1686 while( slotptr(bt->page, slot)->dead )
1687 if( slot++ < bt->page->cnt )
1690 return bt->err = BTERR_struct; // last key shouldn't be deleted
1692 // now we have both parent and child
1694 bt_lockpage(BtLockDelete, set);
1695 bt_lockpage(BtLockWrite, set);
1697 // return if page has no right sibling within parent
1698 // or if empty node is no longer empty
1700 if( page->act || slot == bt->page->cnt ) {
1702 bt_unlockpage(BtLockWrite, bt->set);
1703 bt_unpinlatch (bt->set);
1704 bt_unpinpool (bt->pool);
1706 bt_unlockpage(BtLockParent, set);
1707 bt_unlockpage(BtLockDelete, set);
1708 bt_unlockpage(BtLockWrite, set);
1709 bt_unpinlatch (set);
1710 bt_unpinpool (pool);
1714 // lock and map our right page
1715 // note that it cannot be our foster child
1716 // since the our node is empty
1718 right = bt_getid(page->right);
1720 if( rpool = bt_pinpool (bt, right) )
1721 rpage = bt_page (bt, rpool, right);
1725 rset = bt_pinlatch (bt, right);
1726 bt_lockpage(BtLockWrite, rset);
1727 bt_lockpage(BtLockDelete, rset);
1729 // pull contents of right page into empty page
1731 memcpy (page, rpage, bt->mgr->page_size);
1733 // delete left parent slot for old empty page
1734 // and redirect right parent slot to it
1737 bt->page->dirty = 1;
1738 slotptr(bt->page, slot)->dead = 1;
1740 while( slot++ < bt->page->cnt )
1741 if( !slotptr(bt->page, slot)->dead )
1744 bt_putid(slotptr(bt->page,slot)->id, page_no);
1746 // release parent level lock
1747 // and our empty node lock
1749 bt_unlockpage(BtLockWrite, set);
1750 bt_unlockpage(BtLockWrite, bt->set);
1751 bt_unpinlatch (bt->set);
1752 bt_unpinpool (bt->pool);
1754 // add killed right block to free chain
1757 bt_spinwritelock(bt->mgr->latchmgr->lock);
1759 // store free chain in allocation page second right
1760 bt_putid(rpage->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1761 bt_putid(bt->mgr->latchmgr->alloc[1].right, right);
1763 // unlock latch mgr and right page
1765 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1767 bt_unlockpage(BtLockWrite, rset);
1768 bt_unlockpage(BtLockDelete, rset);
1769 bt_unpinlatch (rset);
1770 bt_unpinpool (rpool);
1772 // remove ParentModify lock
1774 bt_unlockpage(BtLockParent, set);
1775 bt_unlockpage(BtLockDelete, set);
1776 bt_unpinlatch (set);
1777 bt_unpinpool (pool);
1781 // find key in leaf level and return row-id
1783 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1789 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1790 ptr = keyptr(bt->page, slot);
1794 // if key exists, return row-id
1795 // otherwise return 0
1797 if( slot <= bt->page->cnt && !keycmp (ptr, key, len) )
1798 id = bt_getid(slotptr(bt->page,slot)->id);
1802 bt_unlockpage (BtLockRead, bt->set);
1803 bt_unpinlatch (bt->set);
1804 bt_unpinpool (bt->pool);
1808 // check page for space available,
1809 // clean if necessary and return
1810 // 0 - page needs splitting
1811 // >0 new slot value
1813 uint bt_cleanpage(BtDb *bt, uint amt, uint slot)
1815 uint nxt = bt->mgr->page_size;
1816 BtPage page = bt->page;
1817 uint cnt = 0, idx = 0;
1818 uint max = page->cnt;
1822 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1825 // skip cleanup if nothing to reclaim
1830 memcpy (bt->frame, page, bt->mgr->page_size);
1832 // skip page info and set rest of page to zero
1834 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1838 // try cleaning up page first
1840 // always leave fence key in the array
1841 // otherwise, remove deleted key
1843 // note: foster children are never dead
1844 // nor are fence keys for interiour nodes
1846 while( cnt++ < max ) {
1849 else if( cnt < max && slotptr(bt->frame,cnt)->dead )
1854 key = keyptr(bt->frame, cnt);
1855 nxt -= key->len + 1;
1856 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1859 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1860 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1862 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1863 slotptr(page, idx)->off = nxt;
1869 // see if page has enough space now, or does it need splitting?
1871 if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1877 // add key to current page
1878 // page must already be writelocked
1880 void bt_addkeytopage (BtDb *bt, uint slot, unsigned char *key, uint len, uid id, uint tod)
1882 BtPage page = bt->page;
1885 // find next available dead slot and copy key onto page
1886 // note that foster children on the page are never dead
1888 // look for next hole, but stay back from the fence key
1890 for( idx = slot; idx < page->cnt; idx++ )
1891 if( slotptr(page, idx)->dead )
1894 if( idx == page->cnt )
1899 // now insert key into array before slot
1902 *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
1904 page->min -= len + 1;
1905 ((unsigned char *)page)[page->min] = len;
1906 memcpy ((unsigned char *)page + page->min +1, key, len );
1908 bt_putid(slotptr(page,slot)->id, id);
1909 slotptr(page, slot)->off = page->min;
1910 slotptr(page, slot)->tod = tod;
1911 slotptr(page, slot)->dead = 0;
1914 // split the root and raise the height of the btree
1915 // call with current page locked and page no of foster child
1916 // return with current page (root) unlocked
1918 BTERR bt_splitroot(BtDb *bt, uid right)
1920 uint nxt = bt->mgr->page_size;
1921 unsigned char fencekey[256];
1922 BtPage root = bt->page;
1926 // Obtain an empty page to use, and copy the left page
1927 // contents into it from the root. Strip foster child key.
1928 // (it's the stopper key)
1930 memset (slotptr(root, root->cnt), 0, sizeof(BtSlot));
1936 // Save left fence key.
1938 key = keyptr(root, root->cnt);
1939 memcpy (fencekey, key, key->len + 1);
1941 // copy the lower keys into a new left page
1943 if( !(new_page = bt_newpage(bt, root)) )
1946 // preserve the page info at the bottom
1947 // and set rest of the root to zero
1949 memset (root+1, 0, bt->mgr->page_size - sizeof(*root));
1951 // insert left fence key on empty newroot page
1953 nxt -= *fencekey + 1;
1954 memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
1955 bt_putid(slotptr(root, 1)->id, new_page);
1956 slotptr(root, 1)->off = nxt;
1958 // insert stopper key on newroot page
1959 // and increase the root height
1965 memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
1966 bt_putid(slotptr(root, 2)->id, right);
1967 slotptr(root, 2)->off = nxt;
1969 bt_putid(root->right, 0);
1970 root->min = nxt; // reset lowest used offset and key count
1975 // release and unpin root (bt->page)
1977 bt_unlockpage(BtLockWrite, bt->set);
1978 bt_unpinlatch (bt->set);
1979 bt_unpinpool (bt->pool);
1983 // split already locked full node
1984 // in current page variables
1985 // return unlocked and unpinned.
1987 BTERR bt_splitpage (BtDb *bt)
1989 uint slot, cnt, idx, max, nxt = bt->mgr->page_size;
1990 unsigned char fencekey[256];
1991 uid page_no = bt->page_no;
1992 BtLatchSet *set = bt->set;
1993 BtPool *pool = bt->pool;
1994 BtPage page = bt->page;
1995 uint tod = time(NULL);
1996 uint lvl = page->lvl;
1997 uid new_page, right;
2000 // initialize frame buffer for right node
2002 memset (bt->frame, 0, bt->mgr->page_size);
2003 max = page->cnt - page->foster;
2004 tod = (uint)time(NULL);
2008 // split higher half of keys to bt->frame
2009 // leaving old foster children in the left node,
2010 // and adding a new foster child there.
2012 while( cnt++ < max ) {
2013 key = keyptr(page, cnt);
2014 nxt -= key->len + 1;
2015 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
2016 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
2017 if( !(slotptr(bt->frame, idx)->dead = slotptr(page, cnt)->dead) )
2019 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
2020 slotptr(bt->frame, idx)->off = nxt;
2023 // transfer right link node to new right node
2025 if( page_no > ROOT_page ) {
2026 right = bt_getid (page->right);
2027 bt_putid(bt->frame->right, right);
2030 bt->frame->bits = bt->mgr->page_bits;
2031 bt->frame->min = nxt;
2032 bt->frame->cnt = idx;
2033 bt->frame->lvl = lvl;
2035 // get new free page and write right frame to it.
2037 if( !(new_page = bt_newpage(bt, bt->frame)) )
2040 // remember fence key for new right page to add
2041 // as foster child to the left node
2043 key = keyptr(bt->frame, idx);
2044 memcpy (fencekey, key, key->len + 1);
2046 // update lower keys and foster children to continue in old page
2048 memcpy (bt->frame, page, bt->mgr->page_size);
2049 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
2050 nxt = bt->mgr->page_size;
2056 // assemble page of smaller keys
2057 // to remain in the old page
2059 while( cnt++ < max / 2 ) {
2060 key = keyptr(bt->frame, cnt);
2061 nxt -= key->len + 1;
2062 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2063 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
2064 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
2066 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2067 slotptr(page, idx)->off = nxt;
2070 // insert new foster child for right page in queue
2071 // before any of the current foster children
2073 nxt -= *fencekey + 1;
2074 memcpy ((unsigned char *)page + nxt, fencekey, *fencekey + 1);
2076 bt_putid (slotptr(page,++idx)->id, new_page);
2077 slotptr(page, idx)->tod = tod;
2078 slotptr(page, idx)->off = nxt;
2082 // continue with old foster child keys
2083 // note that none will be dead
2085 cnt = bt->frame->cnt - bt->frame->foster;
2087 while( cnt++ < bt->frame->cnt ) {
2088 key = keyptr(bt->frame, cnt);
2089 nxt -= key->len + 1;
2090 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2091 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
2092 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2093 slotptr(page, idx)->off = nxt;
2100 // link new right page
2102 bt_putid (page->right, new_page);
2104 // if current page is the root page, split it
2106 if( page_no == ROOT_page )
2107 return bt_splitroot (bt, new_page);
2109 // release wr lock on our page
2111 bt_unlockpage (BtLockWrite, set);
2113 // obtain ParentModification lock for current page
2114 // to fix new fence key and oldest foster child on page
2116 bt_lockpage (BtLockParent, set);
2118 // get our new fence key to insert in parent node
2120 bt_lockpage (BtLockRead, set);
2122 key = keyptr(page, page->cnt-1);
2123 memcpy (fencekey, key, key->len+1);
2125 bt_unlockpage (BtLockRead, set);
2127 if( bt_insertkey (bt, fencekey + 1, *fencekey, page_no, tod, lvl + 1) )
2130 // lock our page for writing
2132 bt_lockpage (BtLockRead, set);
2134 // switch old parent key from us to our oldest foster child
2136 key = keyptr(page, page->cnt);
2137 memcpy (fencekey, key, key->len+1);
2139 new_page = bt_getid (slotptr(page, page->cnt)->id);
2140 bt_unlockpage (BtLockRead, set);
2142 if( bt_insertkey (bt, fencekey + 1, *fencekey, new_page, tod, lvl + 1) )
2145 // now that it has its own parent pointer,
2146 // remove oldest foster child from our page
2148 bt_lockpage (BtLockWrite, set);
2149 memset (slotptr(page, page->cnt), 0, sizeof(BtSlot));
2157 bt_unlockpage (BtLockWrite, set);
2158 bt_unlockpage (BtLockParent, set);
2159 bt_unpinlatch (set);
2160 bt_unpinpool (pool);
2164 // Insert new key into the btree at leaf level.
2166 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod, uint lvl)
2173 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
2174 ptr = keyptr(bt->page, slot);
2178 bt->err = BTERR_ovflw;
2182 // if key already exists, update id and return
2186 if( !keycmp (ptr, key, len) ) {
2187 if( slotptr(page, slot)->dead )
2189 slotptr(page, slot)->dead = 0;
2190 slotptr(page, slot)->tod = tod;
2191 bt_putid(slotptr(page,slot)->id, id);
2192 bt_unlockpage(BtLockWrite, bt->set);
2193 bt_unpinlatch (bt->set);
2194 bt_unpinpool (bt->pool);
2198 // check if page has enough space
2200 if( slot = bt_cleanpage (bt, len, slot) )
2203 if( bt_splitpage (bt) )
2207 bt_addkeytopage (bt, slot, key, len, id, tod);
2209 bt_unlockpage (BtLockWrite, bt->set);
2210 bt_unpinlatch (bt->set);
2211 bt_unpinpool (bt->pool);
2215 // cache page of keys into cursor and return starting slot for given key
2217 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2221 // cache page for retrieval
2222 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
2223 memcpy (bt->cursor, bt->page, bt->mgr->page_size);
2225 bt->cursor_page = bt->page_no;
2227 bt_unlockpage(BtLockRead, bt->set);
2228 bt_unpinlatch (bt->set);
2229 bt_unpinpool (bt->pool);
2233 // return next slot for cursor page
2234 // or slide cursor right into next page
2236 uint bt_nextkey (BtDb *bt, uint slot)
2244 right = bt_getid(bt->cursor->right);
2245 while( slot++ < bt->cursor->cnt - bt->cursor->foster )
2246 if( slotptr(bt->cursor,slot)->dead )
2248 else if( right || (slot < bt->cursor->cnt - bt->cursor->foster) )
2256 bt->cursor_page = right;
2257 if( pool = bt_pinpool (bt, right) )
2258 page = bt_page (bt, pool, right);
2262 set = bt_pinlatch (bt, right);
2263 bt_lockpage(BtLockRead, set);
2265 memcpy (bt->cursor, page, bt->mgr->page_size);
2267 bt_unlockpage(BtLockRead, set);
2268 bt_unpinlatch (set);
2269 bt_unpinpool (pool);
2276 BtKey bt_key(BtDb *bt, uint slot)
2278 return keyptr(bt->cursor, slot);
2281 uid bt_uid(BtDb *bt, uint slot)
2283 return bt_getid(slotptr(bt->cursor,slot)->id);
2286 uint bt_tod(BtDb *bt, uint slot)
2288 return slotptr(bt->cursor,slot)->tod;
2301 // standalone program to index file of keys
2302 // then list them onto std-out
2305 void *index_file (void *arg)
2307 uint __stdcall index_file (void *arg)
2310 int line = 0, found = 0, cnt = 0;
2311 uid next, page_no = LEAF_page; // start on first page of leaves
2312 unsigned char key[256];
2313 ThreadArg *args = arg;
2314 int ch, len = 0, slot;
2323 bt = bt_open (args->mgr);
2326 switch(args->type | 0x20)
2329 fprintf(stderr, "started indexing for %s\n", args->infile);
2330 if( in = fopen (args->infile, "rb") )
2331 while( ch = getc(in), ch != EOF )
2336 if( args->num == 1 )
2337 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2339 else if( args->num )
2340 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2342 if( bt_insertkey (bt, key, len, line, *tod, 0) )
2343 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2346 else if( len < 255 )
2348 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
2352 fprintf(stderr, "started deleting keys for %s\n", args->infile);
2353 if( in = fopen (args->infile, "rb") )
2354 while( ch = getc(in), ch != EOF )
2358 if( args->num == 1 )
2359 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2361 else if( args->num )
2362 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2364 if( bt_deletekey (bt, key, len) )
2365 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2368 else if( len < 255 )
2370 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2374 fprintf(stderr, "started finding keys for %s\n", args->infile);
2375 if( in = fopen (args->infile, "rb") )
2376 while( ch = getc(in), ch != EOF )
2380 if( args->num == 1 )
2381 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2383 else if( args->num )
2384 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2386 if( bt_findkey (bt, key, len) )
2389 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2392 else if( len < 255 )
2394 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2400 fprintf(stderr, "started reading\n");
2402 if( slot = bt_startkey (bt, key, len) )
2405 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
2407 while( slot = bt_nextkey (bt, slot) ) {
2408 ptr = bt_key(bt, slot);
2409 fwrite (ptr->key, ptr->len, 1, stdout);
2410 fputc ('\n', stdout);
2416 fprintf(stderr, "started reading\n");
2419 if( pool = bt_pinpool (bt, page_no) )
2420 page = bt_page (bt, pool, page_no);
2423 set = bt_pinlatch (bt, page_no);
2424 bt_lockpage (BtLockRead, set);
2426 next = bt_getid (page->right);
2427 bt_unlockpage (BtLockRead, set);
2428 bt_unpinlatch (set);
2429 bt_unpinpool (pool);
2430 } while( page_no = next );
2432 cnt--; // remove stopper key
2433 fprintf(stderr, " Total keys read %d\n", cnt);
2445 typedef struct timeval timer;
2447 int main (int argc, char **argv)
2449 int idx, cnt, len, slot, err;
2450 int segsize, bits = 16;
2455 time_t start[1], stop[1];
2468 fprintf (stderr, "Usage: %s idx_file Read/Write/Scan/Delete/Find [page_bits mapped_segments seg_bits line_numbers src_file1 src_file2 ... ]\n", argv[0]);
2469 fprintf (stderr, " where page_bits is the page size in bits\n");
2470 fprintf (stderr, " mapped_segments is the number of mmap segments in buffer pool\n");
2471 fprintf (stderr, " seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2472 fprintf (stderr, " line_numbers = 1 to append line numbers to keys\n");
2473 fprintf (stderr, " src_file1 thru src_filen are files of keys separated by newline\n");
2478 gettimeofday(&start, NULL);
2484 bits = atoi(argv[3]);
2487 poolsize = atoi(argv[4]);
2490 fprintf (stderr, "Warning: no mapped_pool\n");
2492 if( poolsize > 65535 )
2493 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2496 segsize = atoi(argv[5]);
2498 segsize = 4; // 16 pages per mmap segment
2501 num = atoi(argv[6]);
2505 threads = malloc (cnt * sizeof(pthread_t));
2507 threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2509 args = malloc (cnt * sizeof(ThreadArg));
2511 mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2514 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2520 for( idx = 0; idx < cnt; idx++ ) {
2521 args[idx].infile = argv[idx + 7];
2522 args[idx].type = argv[2][0];
2523 args[idx].mgr = mgr;
2524 args[idx].num = num;
2525 args[idx].idx = idx;
2527 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2528 fprintf(stderr, "Error creating thread %d\n", err);
2530 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2534 // wait for termination
2537 for( idx = 0; idx < cnt; idx++ )
2538 pthread_join (threads[idx], NULL);
2539 gettimeofday(&stop, NULL);
2540 real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2542 WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2544 for( idx = 0; idx < cnt; idx++ )
2545 CloseHandle(threads[idx]);
2548 real_time = 1000 * (*stop - *start);
2550 fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);