1 // foster btree version e
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.
89 // Define the length of the page and key pointers
93 // Page key slot definition.
95 // If BT_maxbits is 15 or less, you can save 4 bytes
96 // for each key stored by making the first two uints
97 // into ushorts. You can also save 4 bytes by removing
98 // the tod field from the key.
100 // Keys are marked dead, but remain on the page until
101 // it cleanup is called. The fence key (highest key) for
102 // the page is always present, even after cleanup.
105 uint off:BT_maxbits; // page offset for key start
106 uint dead:1; // set for deleted key
107 uint tod; // time-stamp for key
108 unsigned char id[BtId]; // id associated with key
111 // The key structure occupies space at the upper end of
112 // each page. It's a length byte followed by the value
117 unsigned char key[1];
120 // The first part of an index page.
121 // It is immediately followed
122 // by the BtSlot array of keys.
124 typedef struct Page {
125 uint cnt; // count of keys in page
126 uint act; // count of active keys
127 uint min; // next key offset
128 uint foster; // count of foster children
129 unsigned char bits; // page size in bits
130 unsigned char lvl:6; // level of page
131 unsigned char kill:1; // page is being deleted
132 unsigned char dirty:1; // page needs to be cleaned
133 unsigned char right[BtId]; // page number to right
136 // mode & definition for hash latch implementation
145 // mutex locks the other fields
146 // exclusive is set for write access
147 // share is count of read accessors
150 volatile ushort mutex:1;
151 volatile ushort exclusive:1;
152 volatile ushort pending:1;
153 volatile ushort share:13;
156 // hash table entries
159 BtSpinLatch latch[1];
160 volatile ushort slot; // Latch table entry at head of chain
163 // latch table lock structure
164 // implements a fair read-write lock
168 pthread_rwlock_t lock[1];
175 BtLatch readwr[1]; // read/write page lock
176 BtLatch access[1]; // Access Intent/Page delete
177 BtLatch parent[1]; // adoption of foster children
178 BtSpinLatch busy[1]; // slot is being moved between chains
179 volatile ushort next; // next entry in hash table chain
180 volatile ushort prev; // prev entry in hash table chain
181 volatile ushort pin; // number of outstanding locks
182 volatile ushort hash; // hash slot entry is under
183 volatile uid page_no; // latch set page number
186 // The memory mapping pool table buffer manager entry
189 unsigned long long int lru; // number of times accessed
190 uid basepage; // mapped base page number
191 char *map; // mapped memory pointer
192 ushort pin; // mapped page pin counter
193 ushort slot; // slot index in this array
194 void *hashprev; // previous pool entry for the same hash idx
195 void *hashnext; // next pool entry for the same hash idx
197 HANDLE hmap; // Windows memory mapping handle
201 // structure for latch manager on ALLOC_page
204 struct Page alloc[2]; // next & free page_nos in right ptr
205 BtSpinLatch lock[1]; // allocation area lite latch
206 ushort latchdeployed; // highest number of latch entries deployed
207 ushort nlatchpage; // number of latch pages at BT_latch
208 ushort latchtotal; // number of page latch entries
209 ushort latchhash; // number of latch hash table slots
210 ushort latchvictim; // next latch entry to examine
211 BtHashEntry table[0]; // the hash table
214 // The object structure for Btree access
217 uint page_size; // page size
218 uint page_bits; // page size in bits
219 uint seg_bits; // seg size in pages in bits
220 uint mode; // read-write mode
223 char *pooladvise; // bit maps for pool page advisements
227 ushort poolcnt; // highest page pool node in use
228 ushort poolmax; // highest page pool node allocated
229 ushort poolmask; // total size of pages in mmap segment - 1
230 ushort hashsize; // size of Hash Table for pool entries
231 ushort evicted; // last evicted hash table slot
232 ushort *hash; // hash table of pool entries
233 BtPool *pool; // memory pool page segments
234 BtSpinLatch *latch; // latches for pool hash slots
235 BtLatchMgr *latchmgr; // mapped latch page from allocation page
236 BtLatchSet *latchsets; // mapped latch set from latch pages
238 HANDLE halloc; // allocation and latch table handle
243 BtMgr *mgr; // buffer manager for thread
244 BtPage temp; // temporary frame buffer (memory mapped/file IO)
245 BtPage cursor; // cached frame for start/next (never mapped)
246 BtPage frame; // spare frame for the page split (never mapped)
247 BtPage zero; // page frame for zeroes at end of file
248 BtPage page; // current page
249 uid page_no; // current page number
250 uid cursor_page; // current cursor page number
251 BtLatchSet *set; // current page latch set
252 unsigned char *mem; // frame, cursor, page memory buffer
253 int err; // last error
268 extern void bt_close (BtDb *bt);
269 extern BtDb *bt_open (BtMgr *mgr);
270 extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod);
271 extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl);
272 extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
273 extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
274 extern uint bt_nextkey (BtDb *bt, uint slot);
277 extern BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolsize, uint segsize, uint hashsize);
278 void bt_mgrclose (BtMgr *mgr);
280 // Helper functions to return cursor slot values
282 extern BtKey bt_key (BtDb *bt, uint slot);
283 extern uid bt_uid (BtDb *bt, uint slot);
284 extern uint bt_tod (BtDb *bt, uint slot);
286 // BTree page number constants
287 #define ALLOC_page 0 // allocation & lock manager hash table
288 #define ROOT_page 1 // root of the btree
289 #define LEAF_page 2 // first page of leaves
290 #define LATCH_page 3 // pages for lock manager
292 // Number of levels to create in a new BTree
296 // The page is allocated from low and hi ends.
297 // The key offsets and row-id's are allocated
298 // from the bottom, while the text of the key
299 // is allocated from the top. When the two
300 // areas meet, the page is split into two.
302 // A key consists of a length byte, two bytes of
303 // index number (0 - 65534), and up to 253 bytes
304 // of key value. Duplicate keys are discarded.
305 // Associated with each key is a 48 bit row-id.
307 // The b-tree root is always located at page 1.
308 // The first leaf page of level zero is always
309 // located on page 2.
311 // When to root page fills, it is split in two and
312 // the tree height is raised by a new root at page
313 // one with two keys.
315 // Deleted keys are marked with a dead bit until
316 // page cleanup The fence key for a node is always
317 // present, even after deletion and cleanup.
319 // Groups of pages called segments from the btree are
320 // cached with memory mapping. A hash table is used to keep
321 // track of the cached segments. This behaviour is controlled
322 // by the cache block size parameter to bt_open.
324 // To achieve maximum concurrency one page is locked at a time
325 // as the tree is traversed to find leaf key in question.
327 // An adoption traversal leaves the parent node locked as the
328 // tree is traversed to the level in quesiton.
330 // Page 0 is dedicated to lock for new page extensions,
331 // and chains empty pages together for reuse.
333 // Empty pages are chained together through the ALLOC page and reused.
335 // Access macros to address slot and key values from the page
337 #define slotptr(page, slot) (((BtSlot *)(page+1)) + (slot-1))
338 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
340 void bt_putid(unsigned char *dest, uid id)
345 dest[i] = (unsigned char)id, id >>= 8;
348 uid bt_getid(unsigned char *src)
353 for( i = 0; i < BtId; i++ )
354 id <<= 8, id |= *src++;
359 // wait until write lock mode is clear
360 // and add 1 to the share count
362 void bt_spinreadlock(BtSpinLatch *latch)
368 while( __sync_fetch_and_or((ushort *)latch, Mutex) & Mutex )
371 while( _InterlockedOr16((ushort *)latch, Mutex) & Mutex )
375 // see if exclusive request is granted or pending
377 if( prev = !(latch->exclusive | latch->pending) )
379 __sync_fetch_and_add((ushort *)latch, Share);
381 _InterlockedExchangeAdd16 ((ushort *)latch, Share);
385 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
387 _InterlockedAnd16((ushort *)latch, ~Mutex);
392 } while( sched_yield(), 1 );
394 } while( SwitchToThread(), 1 );
398 // wait for other read and write latches to relinquish
400 void bt_spinwritelock(BtSpinLatch *latch)
406 while( __sync_fetch_and_or((ushort *)latch, Mutex | Pending) & Mutex )
409 while( _InterlockedOr16((ushort *)latch, Mutex | Pending) & Mutex )
412 if( prev = !(latch->share | latch->exclusive) )
414 __sync_fetch_and_or((ushort *)latch, Write);
416 _InterlockedOr16((ushort *)latch, Write);
420 __sync_fetch_and_and ((ushort *)latch, ~(Mutex | Pending));
422 _InterlockedAnd16((ushort *)latch, ~(Mutex | Pending));
434 // try to obtain write lock
436 // return 1 if obtained,
439 int bt_spinwritetry(BtSpinLatch *latch)
444 if( prev = __sync_fetch_and_or((ushort *)latch, Mutex), prev & Mutex )
447 if( prev = _InterlockedOr16((ushort *)latch, Mutex), prev & Mutex )
450 // take write access if all bits are clear
454 __sync_fetch_and_or ((ushort *)latch, Write);
456 _InterlockedOr16((ushort *)latch, Write);
460 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
462 _InterlockedAnd16((ushort *)latch, ~Mutex);
469 void bt_spinreleasewrite(BtSpinLatch *latch)
472 __sync_fetch_and_and ((ushort *)latch, ~Write);
474 _InterlockedAnd16((ushort *)latch, ~Write);
478 // decrement reader count
480 void bt_spinreleaseread(BtSpinLatch *latch)
483 __sync_fetch_and_add((ushort *)latch, -Share);
485 _InterlockedExchangeAdd16 ((ushort *)latch, -Share);
489 void bt_initlockset (BtLatchSet *set)
492 pthread_rwlockattr_t rwattr[1];
494 pthread_rwlockattr_init (rwattr);
495 pthread_rwlockattr_setkind_np (rwattr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
496 pthread_rwlockattr_setpshared (rwattr, PTHREAD_PROCESS_SHARED);
498 pthread_rwlock_init (set->readwr->lock, rwattr);
499 pthread_rwlock_init (set->access->lock, rwattr);
500 pthread_rwlock_init (set->parent->lock, rwattr);
501 pthread_rwlockattr_destroy (rwattr);
503 InitializeSRWLock (set->readwr->srw);
504 InitializeSRWLock (set->access->srw);
505 InitializeSRWLock (set->parent->srw);
509 // link latch table entry into latch hash table
511 void bt_latchlink (BtDb *bt, ushort hashidx, ushort victim, uid page_no)
513 BtLatchSet *set = bt->mgr->latchsets + victim;
515 if( set->next = bt->mgr->latchmgr->table[hashidx].slot )
516 bt->mgr->latchsets[set->next].prev = victim;
518 bt->mgr->latchmgr->table[hashidx].slot = victim;
519 set->page_no = page_no;
524 // find existing latchset or inspire new one
525 // return with latchset pinned
527 BtLatchSet *bt_bindlatch (BtDb *bt, uid page_no, int incr)
529 ushort hashidx = page_no % bt->mgr->latchmgr->latchhash;
530 ushort slot, avail = 0, victim, idx;
533 // obtain read lock on hash table entry
535 bt_spinreadlock(bt->mgr->latchmgr->table[hashidx].latch);
537 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
539 set = bt->mgr->latchsets + slot;
540 if( page_no == set->page_no )
542 } while( slot = set->next );
546 __sync_fetch_and_add(&set->pin, 1);
548 _InterlockedIncrement16 (&set->pin);
552 bt_spinreleaseread (bt->mgr->latchmgr->table[hashidx].latch);
557 // try again, this time with write lock
559 bt_spinwritelock(bt->mgr->latchmgr->table[hashidx].latch);
561 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
563 set = bt->mgr->latchsets + slot;
564 if( page_no == set->page_no )
566 if( !set->pin && !avail )
568 } while( slot = set->next );
570 // found our entry, or take over an unpinned one
572 if( slot || (slot = avail) ) {
573 set = bt->mgr->latchsets + slot;
576 __sync_fetch_and_add(&set->pin, 1);
578 _InterlockedIncrement16 (&set->pin);
580 set->page_no = page_no;
581 bt_spinreleasewrite(bt->mgr->latchmgr->table[hashidx].latch);
585 // see if there are any unused entries
587 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, 1) + 1;
589 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchdeployed);
592 if( victim < bt->mgr->latchmgr->latchtotal ) {
593 set = bt->mgr->latchsets + victim;
596 __sync_fetch_and_add(&set->pin, 1);
598 _InterlockedIncrement16 (&set->pin);
600 bt_initlockset (set);
601 bt_latchlink (bt, hashidx, victim, page_no);
602 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
607 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, -1);
609 victim = _InterlockedDecrement16 (&bt->mgr->latchmgr->latchdeployed);
611 // find and reuse previous lock entry
615 victim = __sync_fetch_and_add(&bt->mgr->latchmgr->latchvictim, 1);
617 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchvictim) - 1;
619 // we don't use slot zero
621 if( victim %= bt->mgr->latchmgr->latchtotal )
622 set = bt->mgr->latchsets + victim;
626 // take control of our slot
627 // from other threads
629 if( set->pin || !bt_spinwritetry (set->busy) )
634 // try to get write lock on hash chain
635 // skip entry if not obtained
636 // or has outstanding locks
638 if( !bt_spinwritetry (bt->mgr->latchmgr->table[idx].latch) ) {
639 bt_spinreleasewrite (set->busy);
644 bt_spinreleasewrite (set->busy);
645 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
649 // unlink our available victim from its hash chain
652 bt->mgr->latchsets[set->prev].next = set->next;
654 bt->mgr->latchmgr->table[idx].slot = set->next;
657 bt->mgr->latchsets[set->next].prev = set->prev;
659 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
663 __sync_fetch_and_add(&set->pin, 1);
665 _InterlockedIncrement16 (&set->pin);
668 bt_latchlink (bt, hashidx, victim, page_no);
669 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
670 bt_spinreleasewrite (set->busy);
675 void bt_mgrclose (BtMgr *mgr)
680 // release mapped pages
681 // note that slot zero is never used
683 for( slot = 1; slot < mgr->poolmax; slot++ ) {
684 pool = mgr->pool + slot;
687 munmap (pool->map, (mgr->poolmask+1) << mgr->page_bits);
690 FlushViewOfFile(pool->map, 0);
691 UnmapViewOfFile(pool->map);
692 CloseHandle(pool->hmap);
702 free (mgr->pooladvise);
705 FlushFileBuffers(mgr->idx);
706 CloseHandle(mgr->idx);
707 GlobalFree (mgr->pool);
708 GlobalFree (mgr->hash);
709 GlobalFree (mgr->latch);
714 // close and release memory
716 void bt_close (BtDb *bt)
723 VirtualFree (bt->mem, 0, MEM_RELEASE);
728 // open/create new btree buffer manager
730 // call with file_name, BT_openmode, bits in page size (e.g. 16),
731 // size of mapped page pool (e.g. 8192)
733 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
735 uint lvl, attr, cacheblk, last, slot, idx;
736 uint nlatchpage, latchhash;
737 BtLatchMgr *latchmgr;
745 SYSTEM_INFO sysinfo[1];
748 // determine sanity of page size and buffer pool
750 if( bits > BT_maxbits )
752 else if( bits < BT_minbits )
756 return NULL; // must have buffer pool
759 mgr = calloc (1, sizeof(BtMgr));
761 mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
764 return free(mgr), NULL;
766 cacheblk = 4096; // minimum mmap segment size for unix
769 mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
770 attr = FILE_ATTRIBUTE_NORMAL;
771 mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
773 if( mgr->idx == INVALID_HANDLE_VALUE )
774 return GlobalFree(mgr), NULL;
776 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
777 GetSystemInfo(sysinfo);
778 cacheblk = sysinfo->dwAllocationGranularity;
782 latchmgr = malloc (BT_maxpage);
785 // read minimum page size to get root info
787 if( size = lseek (mgr->idx, 0L, 2) ) {
788 if( pread(mgr->idx, latchmgr, BT_minpage, 0) == BT_minpage )
789 bits = latchmgr->alloc->bits;
791 return free(mgr), free(latchmgr), NULL;
792 } else if( mode == BT_ro )
793 return bt_mgrclose (mgr), NULL;
795 latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
796 size = GetFileSize(mgr->idx, amt);
799 if( !ReadFile(mgr->idx, (char *)latchmgr, BT_minpage, amt, NULL) )
800 return bt_mgrclose (mgr), NULL;
801 bits = latchmgr->alloc->bits;
802 } else if( mode == BT_ro )
803 return bt_mgrclose (mgr), NULL;
806 mgr->page_size = 1 << bits;
807 mgr->page_bits = bits;
809 mgr->poolmax = poolmax;
812 if( cacheblk < mgr->page_size )
813 cacheblk = mgr->page_size;
815 // mask for partial memmaps
817 mgr->poolmask = (cacheblk >> bits) - 1;
819 // see if requested size of pages per memmap is greater
821 if( (1 << segsize) > mgr->poolmask )
822 mgr->poolmask = (1 << segsize) - 1;
826 while( (1 << mgr->seg_bits) <= mgr->poolmask )
829 mgr->hashsize = hashsize;
832 mgr->pool = calloc (poolmax, sizeof(BtPool));
833 mgr->hash = calloc (hashsize, sizeof(ushort));
834 mgr->latch = calloc (hashsize, sizeof(BtSpinLatch));
835 mgr->pooladvise = calloc (poolmax, (mgr->poolmask + 8) / 8);
837 mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * sizeof(BtPool));
838 mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
839 mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtSpinLatch));
845 // initialize an empty b-tree with latch page, root page, page of leaves
846 // and page(s) of latches
848 memset (latchmgr, 0, 1 << bits);
849 nlatchpage = BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1;
850 bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
851 latchmgr->alloc->bits = mgr->page_bits;
853 latchmgr->nlatchpage = nlatchpage;
854 latchmgr->latchtotal = nlatchpage * (mgr->page_size / sizeof(BtLatchSet));
856 // initialize latch manager
858 latchhash = (mgr->page_size - sizeof(BtLatchMgr)) / sizeof(BtHashEntry);
860 // size of hash table = total number of latchsets
862 if( latchhash > latchmgr->latchtotal )
863 latchhash = latchmgr->latchtotal;
865 latchmgr->latchhash = latchhash;
868 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
869 return bt_mgrclose (mgr), NULL;
871 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
872 return bt_mgrclose (mgr), NULL;
874 if( *amt < mgr->page_size )
875 return bt_mgrclose (mgr), NULL;
878 memset (latchmgr, 0, 1 << bits);
879 latchmgr->alloc->bits = mgr->page_bits;
881 for( lvl=MIN_lvl; lvl--; ) {
882 slotptr(latchmgr->alloc, 1)->off = mgr->page_size - 3;
883 bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
884 key = keyptr(latchmgr->alloc, 1);
885 key->len = 2; // create stopper key
888 latchmgr->alloc->min = mgr->page_size - 3;
889 latchmgr->alloc->lvl = lvl;
890 latchmgr->alloc->cnt = 1;
891 latchmgr->alloc->act = 1;
893 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
894 return bt_mgrclose (mgr), NULL;
896 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
897 return bt_mgrclose (mgr), NULL;
899 if( *amt < mgr->page_size )
900 return bt_mgrclose (mgr), NULL;
904 // clear out latch manager locks
905 // and rest of pages to round out segment
907 memset(latchmgr, 0, mgr->page_size);
910 while( last <= ((MIN_lvl + 1 + nlatchpage) | mgr->poolmask) ) {
912 pwrite(mgr->idx, latchmgr, mgr->page_size, last << mgr->page_bits);
914 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
915 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
916 return bt_mgrclose (mgr), NULL;
917 if( *amt < mgr->page_size )
918 return bt_mgrclose (mgr), NULL;
925 flag = PROT_READ | PROT_WRITE;
926 mgr->latchmgr = mmap (0, mgr->page_size, flag, MAP_SHARED, mgr->idx, ALLOC_page * mgr->page_size);
927 if( mgr->latchmgr == MAP_FAILED )
928 return bt_mgrclose (mgr), NULL;
929 mgr->latchsets = (BtLatchSet *)mmap (0, mgr->latchmgr->nlatchpage * mgr->page_size, flag, MAP_SHARED, mgr->idx, LATCH_page * mgr->page_size);
930 if( mgr->latchsets == MAP_FAILED )
931 return bt_mgrclose (mgr), NULL;
933 flag = PAGE_READWRITE;
934 mgr->halloc = CreateFileMapping(mgr->idx, NULL, flag, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size, NULL);
936 return bt_mgrclose (mgr), NULL;
938 flag = FILE_MAP_WRITE;
939 mgr->latchmgr = MapViewOfFile(mgr->halloc, flag, 0, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size);
941 return GetLastError(), bt_mgrclose (mgr), NULL;
943 mgr->latchsets = (void *)((char *)mgr->latchmgr + LATCH_page * mgr->page_size);
949 VirtualFree (latchmgr, 0, MEM_RELEASE);
954 // open BTree access method
955 // based on buffer manager
957 BtDb *bt_open (BtMgr *mgr)
959 BtDb *bt = malloc (sizeof(*bt));
961 memset (bt, 0, sizeof(*bt));
964 bt->mem = malloc (3 *mgr->page_size);
966 bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
968 bt->frame = (BtPage)bt->mem;
969 bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
970 bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
974 // compare two keys, returning > 0, = 0, or < 0
975 // as the comparison value
977 int keycmp (BtKey key1, unsigned char *key2, uint len2)
979 uint len1 = key1->len;
982 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
995 void bt_readlock(BtLatch *latch)
998 pthread_rwlock_rdlock (latch->lock);
1000 AcquireSRWLockShared (latch->srw);
1004 // wait for other read and write latches to relinquish
1006 void bt_writelock(BtLatch *latch)
1009 pthread_rwlock_wrlock (latch->lock);
1011 AcquireSRWLockExclusive (latch->srw);
1015 // try to obtain write lock
1017 // return 1 if obtained,
1018 // 0 if already write or read locked
1020 int bt_writetry(BtLatch *latch)
1025 result = !pthread_rwlock_trywrlock (latch->lock);
1027 result = TryAcquireSRWLockExclusive (latch->srw);
1034 void bt_releasewrite(BtLatch *latch)
1037 pthread_rwlock_unlock (latch->lock);
1039 ReleaseSRWLockExclusive (latch->srw);
1043 // decrement reader count
1045 void bt_releaseread(BtLatch *latch)
1048 pthread_rwlock_unlock (latch->lock);
1050 ReleaseSRWLockShared (latch->srw);
1056 // find segment in pool
1057 // must be called with hashslot idx locked
1058 // return NULL if not there
1059 // otherwise return node
1061 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
1066 // compute start of hash chain in pool
1068 if( slot = bt->mgr->hash[idx] )
1069 pool = bt->mgr->pool + slot;
1073 page_no &= ~bt->mgr->poolmask;
1075 while( pool->basepage != page_no )
1076 if( pool = pool->hashnext )
1084 // add segment to hash table
1086 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
1091 pool->hashprev = pool->hashnext = NULL;
1092 pool->basepage = page_no & ~bt->mgr->poolmask;
1095 if( slot = bt->mgr->hash[idx] ) {
1096 node = bt->mgr->pool + slot;
1097 pool->hashnext = node;
1098 node->hashprev = pool;
1101 bt->mgr->hash[idx] = pool->slot;
1104 // find best segment to evict from buffer pool
1106 BtPool *bt_findlru (BtDb *bt, uint hashslot)
1108 unsigned long long int target = ~0LL;
1109 BtPool *pool = NULL, *node;
1114 node = bt->mgr->pool + hashslot;
1116 // scan pool entries under hash table slot
1121 if( node->lru > target )
1125 } while( node = node->hashnext );
1130 // map new buffer pool segment to virtual memory
1132 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
1134 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
1135 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
1139 flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
1140 pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED, bt->mgr->idx, off);
1141 if( pool->map == MAP_FAILED )
1142 return bt->err = BTERR_map;
1143 // clear out madvise issued bits
1144 memset (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8) / 8), 0, (bt->mgr->poolmask + 8)/8);
1146 flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
1147 pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
1149 return bt->err = BTERR_map;
1151 flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
1152 pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1154 return bt->err = BTERR_map;
1159 // find or place requested page in segment-pool
1160 // return pool table entry, incrementing pin
1162 BtPool *bt_pinpage(BtDb *bt, uid page_no)
1164 BtPool *pool, *node, *next;
1165 uint slot, idx, victim;
1168 // lock hash table chain
1170 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1171 bt_spinreadlock (&bt->mgr->latch[idx]);
1173 // look up in hash table
1175 if( pool = bt_findpool(bt, page_no, idx) ) {
1177 __sync_fetch_and_add(&pool->pin, 1);
1179 _InterlockedIncrement16 (&pool->pin);
1181 bt_spinreleaseread (&bt->mgr->latch[idx]);
1186 // upgrade to write lock
1188 bt_spinreleaseread (&bt->mgr->latch[idx]);
1189 bt_spinwritelock (&bt->mgr->latch[idx]);
1191 // try to find page in pool with write lock
1193 if( pool = bt_findpool(bt, page_no, idx) ) {
1195 __sync_fetch_and_add(&pool->pin, 1);
1197 _InterlockedIncrement16 (&pool->pin);
1199 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1204 // allocate a new pool node
1205 // and add to hash table
1208 slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
1210 slot = _InterlockedIncrement16 (&bt->mgr->poolcnt) - 1;
1213 if( ++slot < bt->mgr->poolmax ) {
1214 pool = bt->mgr->pool + slot;
1217 if( bt_mapsegment(bt, pool, page_no) )
1220 bt_linkhash(bt, pool, page_no, idx);
1222 __sync_fetch_and_add(&pool->pin, 1);
1224 _InterlockedIncrement16 (&pool->pin);
1226 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1230 // pool table is full
1231 // find best pool entry to evict
1234 __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
1236 _InterlockedDecrement16 (&bt->mgr->poolcnt);
1241 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
1243 victim = _InterlockedIncrement16 (&bt->mgr->evicted) - 1;
1245 victim %= bt->mgr->hashsize;
1247 // try to get write lock
1248 // skip entry if not obtained
1250 if( !bt_spinwritetry (&bt->mgr->latch[victim]) )
1253 // if cache entry is empty
1254 // or no slots are unpinned
1257 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
1258 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1262 // unlink victim pool node from hash table
1264 if( node = pool->hashprev )
1265 node->hashnext = pool->hashnext;
1266 else if( node = pool->hashnext )
1267 bt->mgr->hash[victim] = node->slot;
1269 bt->mgr->hash[victim] = 0;
1271 if( node = pool->hashnext )
1272 node->hashprev = pool->hashprev;
1274 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1276 // remove old file mapping
1278 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1280 FlushViewOfFile(pool->map, 0);
1281 UnmapViewOfFile(pool->map);
1282 CloseHandle(pool->hmap);
1286 // create new pool mapping
1287 // and link into hash table
1289 if( bt_mapsegment(bt, pool, page_no) )
1292 bt_linkhash(bt, pool, page_no, idx);
1294 __sync_fetch_and_add(&pool->pin, 1);
1296 _InterlockedIncrement16 (&pool->pin);
1298 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1303 // place write, read, or parent lock on requested page_no.
1304 // pin to buffer pool and return latchset pointer
1306 BtLatchSet *bt_lockpage(BtDb *bt, uid page_no, BtLock mode, BtPage *pageptr, BtLatchSet *set)
1312 // find/create maping in pool table
1313 // and pin our pool slot
1315 if( pool = bt_pinpage(bt, page_no) )
1316 subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1322 __sync_fetch_and_add(&set->pin, 1);
1324 _InterlockedIncrement16 (&set->pin);
1326 else if( !(set = bt_bindlatch (bt, page_no, 1)) )
1329 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1333 uint idx = subpage / 8;
1334 uint bit = subpage % 8;
1336 if( mode == BtLockRead || mode == BtLockWrite )
1337 if( ~((bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] >> bit) & 1 ) {
1338 madvise (page, bt->mgr->page_size, MADV_WILLNEED);
1339 (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] |= 1 << bit;
1346 bt_readlock (set->readwr);
1349 bt_writelock (set->readwr);
1352 bt_readlock (set->access);
1355 bt_writelock (set->access);
1358 bt_writelock (set->parent);
1363 return bt->err = BTERR_lock, NULL;
1372 // remove write, read, or parent lock on requested page_no.
1374 BTERR bt_unlockpage(BtDb *bt, uid page_no, BtLock mode, BtLatchSet *set)
1379 // since page is pinned
1380 // it should still be in the buffer pool
1381 // and is in no danger of being a victim for reuse
1383 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1384 bt_spinreadlock (&bt->mgr->latch[idx]);
1386 if( !(pool = bt_findpool(bt, page_no, idx)) )
1387 return bt->err = BTERR_hash;
1389 bt_spinreleaseread (&bt->mgr->latch[idx]);
1393 bt_releaseread (set->readwr);
1396 bt_releasewrite (set->readwr);
1399 bt_releaseread (set->access);
1402 bt_releasewrite (set->access);
1405 bt_releasewrite (set->parent);
1410 return bt->err = BTERR_lock;
1414 __sync_fetch_and_add(&pool->pin, -1);
1415 __sync_fetch_and_add (&set->pin, -1);
1417 _InterlockedDecrement16 (&pool->pin);
1418 _InterlockedDecrement16 (&set->pin);
1423 // deallocate a deleted page
1424 // place on free chain out of allocator page
1425 // fence key must already be removed from parent
1427 BTERR bt_freepage(BtDb *bt, uid page_no, BtLatchSet *set)
1429 // obtain delete lock on deleted page
1431 if( !bt_lockpage(bt, page_no, BtLockDelete, NULL, set) )
1434 // obtain write lock on deleted page
1436 if( !bt_lockpage(bt, page_no, BtLockWrite, &bt->temp, set) )
1439 // lock allocation page
1441 bt_spinwritelock(bt->mgr->latchmgr->lock);
1443 // store free chain in allocation page second right
1444 bt_putid(bt->temp->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1445 bt_putid(bt->mgr->latchmgr->alloc[1].right, page_no);
1449 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1451 // remove write lock on deleted node
1453 if( bt_unlockpage(bt, page_no, BtLockWrite, set) )
1456 // remove delete lock on deleted node
1458 if( bt_unlockpage(bt, page_no, BtLockDelete, set) )
1464 // allocate a new page and write page into it
1466 uid bt_newpage(BtDb *bt, BtPage page)
1473 // lock allocation page
1475 bt_spinwritelock(bt->mgr->latchmgr->lock);
1477 // use empty chain first
1478 // else allocate empty page
1480 if( new_page = bt_getid(bt->mgr->latchmgr->alloc[1].right) ) {
1481 if( !(set = bt_lockpage (bt, new_page, BtLockWrite, &bt->temp, NULL)) )
1483 bt_putid(bt->mgr->latchmgr->alloc[1].right, bt_getid(bt->temp->right));
1484 if( bt_unlockpage (bt, new_page, BtLockWrite, set) )
1488 new_page = bt_getid(bt->mgr->latchmgr->alloc->right);
1489 bt_putid(bt->mgr->latchmgr->alloc->right, new_page+1);
1493 if ( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1494 return bt->err = BTERR_wrt, 0;
1496 // if writing first page of pool block, zero last page in the block
1498 if ( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1500 // use zero buffer to write zeros
1501 memset(bt->zero, 0, bt->mgr->page_size);
1502 if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1503 return bt->err = BTERR_wrt, 0;
1506 // bring new page into pool and copy page.
1507 // this will extend the file into the new pages.
1509 if( !(set = bt_lockpage(bt, new_page, BtLockWrite, &pmap, NULL)) )
1512 memcpy(pmap, page, bt->mgr->page_size);
1514 if( bt_unlockpage (bt, new_page, BtLockWrite, set) )
1517 // unlock allocation latch and return new page no
1519 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1523 // find slot in page for given key at a given level
1525 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1527 uint diff, higher = bt->page->cnt, low = 1, slot;
1529 // low is the lowest candidate, higher is already
1530 // tested as .ge. the given key, loop ends when they meet
1532 while( diff = higher - low ) {
1533 slot = low + ( diff >> 1 );
1534 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1543 // find and load page at given level for given key
1544 // leave page rd or wr locked as requested
1546 int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, BtLock lock)
1548 uid page_no = ROOT_page, prevpage = 0;
1549 BtLatchSet *set, *prevset;
1550 uint drill = 0xff, slot;
1551 uint mode, prevmode;
1555 // start at root of btree and drill down
1558 // determine lock mode of drill level
1559 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1561 bt->page_no = page_no;
1563 // obtain access lock using lock chaining with Access mode
1565 if( page_no > ROOT_page )
1566 if( !(bt->set = bt_lockpage(bt, page_no, BtLockAccess, NULL, NULL)) )
1569 // now unlock our (possibly foster) parent
1572 if( bt_unlockpage(bt, prevpage, prevmode, prevset) )
1577 // obtain read lock using lock chaining
1578 // and pin page contents
1580 if( !(bt->set = bt_lockpage(bt, page_no, mode, &bt->page, bt->set)) )
1583 if( page_no > ROOT_page )
1584 if( bt_unlockpage(bt, page_no, BtLockAccess, bt->set) )
1587 // re-read and re-lock root after determining actual level of root
1589 if( bt->page_no == ROOT_page )
1590 if( bt->page->lvl != drill) {
1591 drill = bt->page->lvl;
1593 if( lock == BtLockWrite && drill == lvl )
1594 if( bt_unlockpage(bt, page_no, mode, bt->set) )
1600 prevpage = bt->page_no;
1604 // if page is being deleted,
1605 // move back to preceeding page
1607 if( bt->page->kill ) {
1608 page_no = bt_getid (bt->page->right);
1612 // find key on page at this level
1613 // and descend to requested level
1615 slot = bt_findslot (bt, key, len);
1617 // is this slot a foster child?
1619 if( slot <= bt->page->cnt - bt->page->foster )
1623 while( slotptr(bt->page, slot)->dead )
1624 if( slot++ < bt->page->cnt )
1629 if( slot <= bt->page->cnt - bt->page->foster )
1632 // continue down / right using overlapping locks
1633 // to protect pages being killed or split.
1635 page_no = bt_getid(slotptr(bt->page, slot)->id);
1639 page_no = bt_getid(bt->page->right);
1643 // return error on end of chain
1645 bt->err = BTERR_struct;
1646 return 0; // return error
1649 // find and delete key on page by marking delete flag bit
1650 // when page becomes empty, delete it from the btree
1652 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl)
1654 unsigned char leftkey[256], rightkey[256];
1655 BtLatchSet *rset, *set;
1660 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1661 ptr = keyptr(bt->page, slot);
1665 // if key is found delete it, otherwise ignore request
1667 if( !keycmp (ptr, key, len) )
1668 if( slotptr(bt->page, slot)->dead == 0 ) {
1669 slotptr(bt->page,slot)->dead = 1;
1670 if( slot < bt->page->cnt )
1671 bt->page->dirty = 1;
1675 // return if page is not empty, or it has no right sibling
1677 right = bt_getid(bt->page->right);
1678 page_no = bt->page_no;
1681 if( !right || bt->page->act )
1682 return bt_unlockpage(bt, page_no, BtLockWrite, set);
1684 // obtain Parent lock over write lock
1686 if( !bt_lockpage(bt, page_no, BtLockParent, NULL, set) )
1689 // cache copy of key to delete
1691 ptr = keyptr(bt->page, bt->page->cnt);
1692 memcpy(leftkey, ptr, ptr->len + 1);
1694 // lock and map right page
1696 if( !(rset = bt_lockpage(bt, right, BtLockWrite, &bt->temp, NULL)) )
1699 // pull contents of next page into current empty page
1700 memcpy (bt->page, bt->temp, bt->mgr->page_size);
1702 // cache copy of key to update
1703 ptr = keyptr(bt->temp, bt->temp->cnt);
1704 memcpy(rightkey, ptr, ptr->len + 1);
1706 // Mark right page as deleted and point it to left page
1707 // until we can post updates at higher level.
1709 bt_putid(bt->temp->right, page_no);
1713 if( bt_unlockpage(bt, right, BtLockWrite, rset) )
1715 if( bt_unlockpage(bt, page_no, BtLockWrite, set) )
1718 // delete old lower key to consolidated node
1720 if( bt_deletekey (bt, leftkey + 1, *leftkey, lvl + 1) )
1723 // redirect higher key directly to consolidated node
1725 if( slot = bt_loadpage (bt, rightkey+1, *rightkey, lvl+1, BtLockWrite) )
1726 ptr = keyptr(bt->page, slot);
1730 // since key already exists, update id
1732 if( keycmp (ptr, rightkey+1, *rightkey) )
1733 return bt->err = BTERR_struct;
1735 slotptr(bt->page, slot)->dead = 0;
1736 bt_putid(slotptr(bt->page,slot)->id, page_no);
1738 if( bt_unlockpage(bt, bt->page_no, BtLockWrite, bt->set) )
1741 // obtain write lock and
1742 // add right block to free chain
1744 if( bt_freepage (bt, right, rset) )
1747 // remove ParentModify lock
1749 if( bt_unlockpage(bt, page_no, BtLockParent, set) )
1755 // find key in leaf level and return row-id
1757 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1763 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1764 ptr = keyptr(bt->page, slot);
1768 // if key exists, return row-id
1769 // otherwise return 0
1771 if( ptr->len == len && !memcmp (ptr->key, key, len) )
1772 id = bt_getid(slotptr(bt->page,slot)->id);
1776 if( bt_unlockpage (bt, bt->page_no, BtLockRead, bt->set) )
1782 // check page for space available,
1783 // clean if necessary and return
1784 // 0 - page needs splitting
1787 uint bt_cleanpage(BtDb *bt, uint amt)
1789 uint nxt = bt->mgr->page_size;
1790 BtPage page = bt->page;
1791 uint cnt = 0, idx = 0;
1792 uint max = page->cnt;
1795 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1798 // skip cleanup if nothing to reclaim
1803 memcpy (bt->frame, page, bt->mgr->page_size);
1805 // skip page info and set rest of page to zero
1807 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1811 // try cleaning up page first
1813 while( cnt++ < max ) {
1814 // always leave fence key and foster children in list
1815 if( cnt < max - page->foster && slotptr(bt->frame,cnt)->dead )
1819 key = keyptr(bt->frame, cnt);
1820 nxt -= key->len + 1;
1821 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1824 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1825 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1827 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1828 slotptr(page, idx)->off = nxt;
1834 // see if page has enough space now, or does it need splitting?
1836 if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1842 // add key to current page
1843 // page must already be writelocked
1845 void bt_addkeytopage (BtDb *bt, uint slot, unsigned char *key, uint len, uid id, uint tod)
1847 BtPage page = bt->page;
1850 // calculate next available slot and copy key into page
1852 page->min -= len + 1;
1853 ((unsigned char *)page)[page->min] = len;
1854 memcpy ((unsigned char *)page + page->min +1, key, len );
1856 for( idx = slot; idx < page->cnt; idx++ )
1857 if( slotptr(page, idx)->dead )
1860 // now insert key into array before slot
1861 // preserving the fence slot
1863 if( idx == page->cnt )
1869 *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
1871 bt_putid(slotptr(page,slot)->id, id);
1872 slotptr(page, slot)->off = page->min;
1873 slotptr(page, slot)->tod = tod;
1874 slotptr(page, slot)->dead = 0;
1877 // split the root and raise the height of the btree
1878 // call with current page locked and page no of foster child
1879 // return with current page (root) unlocked
1881 BTERR bt_splitroot(BtDb *bt, uid right)
1883 uint nxt = bt->mgr->page_size;
1884 unsigned char fencekey[256];
1885 BtPage root = bt->page;
1889 // Obtain an empty page to use, and copy the left page
1890 // contents into it from the root. Strip foster child key.
1891 // (it's the stopper key)
1897 // Save left fence key.
1899 key = keyptr(root, root->cnt);
1900 memcpy (fencekey, key, key->len + 1);
1902 // copy the lower keys into a new left page
1904 if( !(new_page = bt_newpage(bt, root)) )
1907 // preserve the page info at the bottom
1908 // and set rest of the root to zero
1910 memset (root+1, 0, bt->mgr->page_size - sizeof(*root));
1912 // insert left fence key on empty newroot page
1914 nxt -= *fencekey + 1;
1915 memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
1916 bt_putid(slotptr(root, 1)->id, new_page);
1917 slotptr(root, 1)->off = nxt;
1919 // insert stopper key on newroot page
1920 // and increase the root height
1926 memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
1927 bt_putid(slotptr(root, 2)->id, right);
1928 slotptr(root, 2)->off = nxt;
1930 bt_putid(root->right, 0);
1931 root->min = nxt; // reset lowest used offset and key count
1936 // release root (bt->page)
1938 return bt_unlockpage(bt, ROOT_page, BtLockWrite, bt->set);
1941 // split already locked full node
1942 // in current page variables
1945 BTERR bt_splitpage (BtDb *bt)
1947 uint slot, cnt, idx, max, nxt = bt->mgr->page_size;
1948 unsigned char fencekey[256];
1949 uid page_no = bt->page_no;
1950 BtLatchSet *set = bt->set;
1951 BtPage page = bt->page;
1952 uint tod = time(NULL);
1953 uint lvl = page->lvl;
1954 uid new_page, right;
1957 // initialize frame buffer
1959 memset (bt->frame, 0, bt->mgr->page_size);
1960 max = page->cnt - page->foster;
1961 tod = (uint)time(NULL);
1965 // split higher half of keys to bt->frame
1966 // leaving foster children in the left node.
1968 while( cnt++ < max ) {
1969 key = keyptr(page, cnt);
1970 nxt -= key->len + 1;
1971 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
1972 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
1973 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
1974 slotptr(bt->frame, idx)->off = nxt;
1978 // transfer right link node
1980 if( page_no > ROOT_page ) {
1981 right = bt_getid (page->right);
1982 bt_putid(bt->frame->right, right);
1985 bt->frame->bits = bt->mgr->page_bits;
1986 bt->frame->min = nxt;
1987 bt->frame->cnt = idx;
1988 bt->frame->lvl = lvl;
1990 // get new free page and write frame to it.
1992 if( !(new_page = bt_newpage(bt, bt->frame)) )
1995 // remember fence key for new page to add
1998 key = keyptr(bt->frame, idx);
1999 memcpy (fencekey, key, key->len + 1);
2001 // update lower keys and foster children to continue in old page
2003 memcpy (bt->frame, page, bt->mgr->page_size);
2004 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
2005 nxt = bt->mgr->page_size;
2010 // assemble page of smaller keys
2011 // to remain in the old page
2013 while( cnt++ < max / 2 ) {
2014 key = keyptr(bt->frame, cnt);
2015 nxt -= key->len + 1;
2016 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2017 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
2018 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2019 slotptr(page, idx)->off = nxt;
2023 // insert new foster child at beginning of the current foster children
2025 nxt -= *fencekey + 1;
2026 memcpy ((unsigned char *)page + nxt, fencekey, *fencekey + 1);
2027 bt_putid (slotptr(page,++idx)->id, new_page);
2028 slotptr(page, idx)->tod = tod;
2029 slotptr(page, idx)->off = nxt;
2033 // continue with old foster child keys if any
2035 cnt = bt->frame->cnt - bt->frame->foster;
2037 while( cnt++ < bt->frame->cnt ) {
2038 key = keyptr(bt->frame, cnt);
2039 nxt -= key->len + 1;
2040 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
2041 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
2042 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
2043 slotptr(page, idx)->off = nxt;
2050 // link new right page
2052 bt_putid (page->right, new_page);
2054 // if current page is the root page, split it
2056 if( page_no == ROOT_page )
2057 return bt_splitroot (bt, new_page);
2059 // keep our latch set
2060 // release wr lock on our page
2062 if( !bt_lockpage (bt, page_no, BtLockPin, NULL, set) )
2065 if( bt_unlockpage (bt, page_no, BtLockWrite, set) )
2068 // obtain ParentModification lock for current page
2069 // to fix fence key and highest foster child on page
2071 if( !bt_lockpage (bt, page_no, BtLockParent, NULL, set) )
2074 // get our highest foster child key to find in parent node
2076 if( !bt_lockpage (bt, page_no, BtLockRead, &page, set) )
2079 key = keyptr(page, page->cnt);
2080 memcpy (fencekey, key, key->len+1);
2082 if( bt_unlockpage (bt, page_no, BtLockRead, set) )
2085 // update our parent
2089 slot = bt_loadpage (bt, fencekey + 1, *fencekey, lvl + 1, BtLockWrite);
2094 // check if parent page has enough space for any possible key
2096 if( bt_cleanpage (bt, 256) )
2099 if( bt_splitpage (bt) )
2103 // see if we are still a foster child from another node
2105 if( bt_getid (slotptr(bt->page, slot)->id) != page_no ) {
2106 if( bt_unlockpage (bt, bt->page_no, BtLockWrite, bt->set) )
2116 // wait until readers from parent get their locks
2119 if( !bt_lockpage (bt, page_no, BtLockDelete, NULL, set) )
2122 // lock our page for writing
2124 if( !bt_lockpage (bt, page_no, BtLockWrite, &page, set) )
2127 // switch parent fence key to foster child
2129 if( slotptr(page, page->cnt)->dead )
2130 slotptr(bt->page, slot)->dead = 1;
2132 bt_putid (slotptr(bt->page, slot)->id, bt_getid(slotptr(page, page->cnt)->id));
2134 // remove highest foster child from our page
2140 key = keyptr(page, page->cnt);
2142 // add our new fence key for foster child to our parent
2144 bt_addkeytopage (bt, slot, key->key, key->len, page_no, tod);
2146 if( bt_unlockpage (bt, bt->page_no, BtLockWrite, bt->set) )
2149 if( bt_unlockpage (bt, page_no, BtLockDelete, set) )
2152 if( bt_unlockpage (bt, page_no, BtLockWrite, set) )
2155 if( bt_unlockpage (bt, page_no, BtLockParent, set) )
2158 // release extra latch pin
2160 return bt_unlockpage (bt, page_no, BtLockPin, set);
2163 // Insert new key into the btree at leaf level.
2165 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod)
2172 if( slot = bt_loadpage (bt, key, len, 0, BtLockWrite) )
2173 ptr = keyptr(bt->page, slot);
2177 bt->err = BTERR_ovflw;
2181 // if key already exists, update id and return
2185 if( !keycmp (ptr, key, len) ) {
2186 slotptr(page, slot)->dead = 0;
2187 slotptr(page, slot)->tod = tod;
2188 bt_putid(slotptr(page,slot)->id, id);
2189 return bt_unlockpage(bt, bt->page_no, BtLockWrite, bt->set);
2192 // check if page has enough space
2194 if( bt_cleanpage (bt, len) )
2197 if( bt_splitpage (bt) )
2201 bt_addkeytopage (bt, slot, key, len, id, tod);
2203 return bt_unlockpage (bt, bt->page_no, BtLockWrite, bt->set);
2206 // cache page of keys into cursor and return starting slot for given key
2208 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2212 // cache page for retrieval
2213 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
2214 memcpy (bt->cursor, bt->page, bt->mgr->page_size);
2215 bt->cursor_page = bt->page_no;
2216 if ( bt_unlockpage(bt, bt->page_no, BtLockRead, bt->set) )
2222 // return next slot for cursor page
2223 // or slide cursor right into next page
2225 uint bt_nextkey (BtDb *bt, uint slot)
2232 right = bt_getid(bt->cursor->right);
2233 while( slot++ < bt->cursor->cnt - bt->cursor->foster )
2234 if( slotptr(bt->cursor,slot)->dead )
2236 else if( right || (slot < bt->cursor->cnt - bt->cursor->foster) )
2244 bt->cursor_page = right;
2246 if( !(bt->set = bt_lockpage(bt, right, BtLockRead, &page, NULL)) )
2249 memcpy (bt->cursor, page, bt->mgr->page_size);
2251 if ( bt_unlockpage(bt, right, BtLockRead, bt->set) )
2260 BtKey bt_key(BtDb *bt, uint slot)
2262 return keyptr(bt->cursor, slot);
2265 uid bt_uid(BtDb *bt, uint slot)
2267 return bt_getid(slotptr(bt->cursor,slot)->id);
2270 uint bt_tod(BtDb *bt, uint slot)
2272 return slotptr(bt->cursor,slot)->tod;
2285 // standalone program to index file of keys
2286 // then list them onto std-out
2289 void *index_file (void *arg)
2291 uint __stdcall index_file (void *arg)
2294 int line = 0, found = 0, cnt = 0;
2295 uid next, page_no = LEAF_page; // start on first page of leaves
2296 unsigned char key[256];
2297 ThreadArg *args = arg;
2298 int ch, len = 0, slot;
2305 bt = bt_open (args->mgr);
2308 switch(args->type | 0x20)
2311 fprintf(stderr, "started indexing for %s\n", args->infile);
2312 if( in = fopen (args->infile, "rb") )
2313 while( ch = getc(in), ch != EOF )
2318 if( args->num == 1 )
2319 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2321 else if( args->num )
2322 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2324 if( bt_insertkey (bt, key, len, line, *tod) )
2325 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2328 else if( len < 255 )
2330 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
2334 fprintf(stderr, "started deleting keys for %s\n", args->infile);
2335 if( in = fopen (args->infile, "rb") )
2336 while( ch = getc(in), ch != EOF )
2340 if( args->num == 1 )
2341 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2343 else if( args->num )
2344 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2346 if( bt_deletekey (bt, key, len, 0) )
2347 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2350 else if( len < 255 )
2352 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2356 fprintf(stderr, "started finding keys for %s\n", args->infile);
2357 if( in = fopen (args->infile, "rb") )
2358 while( ch = getc(in), ch != EOF )
2362 if( args->num == 1 )
2363 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2365 else if( args->num )
2366 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2368 if( bt_findkey (bt, key, len) )
2371 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2374 else if( len < 255 )
2376 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2382 fprintf(stderr, "started reading\n");
2384 if( slot = bt_startkey (bt, key, len) )
2387 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
2389 while( slot = bt_nextkey (bt, slot) ) {
2390 ptr = bt_key(bt, slot);
2391 fwrite (ptr->key, ptr->len, 1, stdout);
2392 fputc ('\n', stdout);
2398 fprintf(stderr, "started reading\n");
2401 bt->set = bt_lockpage (bt, page_no, BtLockRead, &page, NULL);
2403 next = bt_getid (page->right);
2404 bt_unlockpage (bt, page_no, BtLockRead, bt->set);
2405 } while( page_no = next );
2407 cnt--; // remove stopper key
2408 fprintf(stderr, " Total keys read %d\n", cnt);
2420 typedef struct timeval timer;
2422 int main (int argc, char **argv)
2424 int idx, cnt, len, slot, err;
2425 int segsize, bits = 16;
2430 time_t start[1], stop[1];
2443 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]);
2444 fprintf (stderr, " where page_bits is the page size in bits\n");
2445 fprintf (stderr, " mapped_segments is the number of mmap segments in buffer pool\n");
2446 fprintf (stderr, " seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2447 fprintf (stderr, " line_numbers = 1 to append line numbers to keys\n");
2448 fprintf (stderr, " src_file1 thru src_filen are files of keys separated by newline\n");
2453 gettimeofday(&start, NULL);
2459 bits = atoi(argv[3]);
2462 poolsize = atoi(argv[4]);
2465 fprintf (stderr, "Warning: no mapped_pool\n");
2467 if( poolsize > 65535 )
2468 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2471 segsize = atoi(argv[5]);
2473 segsize = 4; // 16 pages per mmap segment
2476 num = atoi(argv[6]);
2480 threads = malloc (cnt * sizeof(pthread_t));
2482 threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2484 args = malloc (cnt * sizeof(ThreadArg));
2486 mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2489 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2495 for( idx = 0; idx < cnt; idx++ ) {
2496 args[idx].infile = argv[idx + 7];
2497 args[idx].type = argv[2][0];
2498 args[idx].mgr = mgr;
2499 args[idx].num = num;
2500 args[idx].idx = idx;
2502 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2503 fprintf(stderr, "Error creating thread %d\n", err);
2505 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2509 // wait for termination
2512 for( idx = 0; idx < cnt; idx++ )
2513 pthread_join (threads[idx], NULL);
2514 gettimeofday(&stop, NULL);
2515 real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2517 WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2519 for( idx = 0; idx < cnt; idx++ )
2520 CloseHandle(threads[idx]);
2523 real_time = 1000 * (*stop - *start);
2525 fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);