1 // foster btree version f
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 BtSpinLatch readwr[1]; // read/write page lock
176 BtSpinLatch access[1]; // Access Intent/Page delete
177 BtSpinLatch 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 // link latch table entry into latch hash table
491 void bt_latchlink (BtDb *bt, ushort hashidx, ushort victim, uid page_no)
493 BtLatchSet *set = bt->mgr->latchsets + victim;
495 if( set->next = bt->mgr->latchmgr->table[hashidx].slot )
496 bt->mgr->latchsets[set->next].prev = victim;
498 bt->mgr->latchmgr->table[hashidx].slot = victim;
499 set->page_no = page_no;
504 // find existing latchset or inspire new one
505 // return with latchset pinned
507 BtLatchSet *bt_bindlatch (BtDb *bt, uid page_no, int incr)
509 ushort hashidx = page_no % bt->mgr->latchmgr->latchhash;
510 ushort slot, avail = 0, victim, idx;
513 // obtain read lock on hash table entry
515 bt_spinreadlock(bt->mgr->latchmgr->table[hashidx].latch);
517 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
519 set = bt->mgr->latchsets + slot;
520 if( page_no == set->page_no )
522 } while( slot = set->next );
526 __sync_fetch_and_add(&set->pin, 1);
528 _InterlockedIncrement16 (&set->pin);
532 bt_spinreleaseread (bt->mgr->latchmgr->table[hashidx].latch);
537 // try again, this time with write lock
539 bt_spinwritelock(bt->mgr->latchmgr->table[hashidx].latch);
541 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
543 set = bt->mgr->latchsets + slot;
544 if( page_no == set->page_no )
546 if( !set->pin && !avail )
548 } while( slot = set->next );
550 // found our entry, or take over an unpinned one
552 if( slot || (slot = avail) ) {
553 set = bt->mgr->latchsets + slot;
556 __sync_fetch_and_add(&set->pin, 1);
558 _InterlockedIncrement16 (&set->pin);
560 set->page_no = page_no;
561 bt_spinreleasewrite(bt->mgr->latchmgr->table[hashidx].latch);
565 // see if there are any unused entries
567 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, 1) + 1;
569 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchdeployed);
572 if( victim < bt->mgr->latchmgr->latchtotal ) {
573 set = bt->mgr->latchsets + victim;
576 __sync_fetch_and_add(&set->pin, 1);
578 _InterlockedIncrement16 (&set->pin);
580 bt_latchlink (bt, hashidx, victim, page_no);
581 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
586 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, -1);
588 victim = _InterlockedDecrement16 (&bt->mgr->latchmgr->latchdeployed);
590 // find and reuse previous lock entry
594 victim = __sync_fetch_and_add(&bt->mgr->latchmgr->latchvictim, 1);
596 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchvictim) - 1;
598 // we don't use slot zero
600 if( victim %= bt->mgr->latchmgr->latchtotal )
601 set = bt->mgr->latchsets + victim;
605 // take control of our slot
606 // from other threads
608 if( set->pin || !bt_spinwritetry (set->busy) )
613 // try to get write lock on hash chain
614 // skip entry if not obtained
615 // or has outstanding locks
617 if( !bt_spinwritetry (bt->mgr->latchmgr->table[idx].latch) ) {
618 bt_spinreleasewrite (set->busy);
623 bt_spinreleasewrite (set->busy);
624 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
628 // unlink our available victim from its hash chain
631 bt->mgr->latchsets[set->prev].next = set->next;
633 bt->mgr->latchmgr->table[idx].slot = set->next;
636 bt->mgr->latchsets[set->next].prev = set->prev;
638 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
642 __sync_fetch_and_add(&set->pin, 1);
644 _InterlockedIncrement16 (&set->pin);
647 bt_latchlink (bt, hashidx, victim, page_no);
648 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
649 bt_spinreleasewrite (set->busy);
654 void bt_mgrclose (BtMgr *mgr)
659 // release mapped pages
660 // note that slot zero is never used
662 for( slot = 1; slot < mgr->poolmax; slot++ ) {
663 pool = mgr->pool + slot;
666 munmap (pool->map, (mgr->poolmask+1) << mgr->page_bits);
669 FlushViewOfFile(pool->map, 0);
670 UnmapViewOfFile(pool->map);
671 CloseHandle(pool->hmap);
681 free (mgr->pooladvise);
684 FlushFileBuffers(mgr->idx);
685 CloseHandle(mgr->idx);
686 GlobalFree (mgr->pool);
687 GlobalFree (mgr->hash);
688 GlobalFree (mgr->latch);
693 // close and release memory
695 void bt_close (BtDb *bt)
702 VirtualFree (bt->mem, 0, MEM_RELEASE);
707 // open/create new btree buffer manager
709 // call with file_name, BT_openmode, bits in page size (e.g. 16),
710 // size of mapped page pool (e.g. 8192)
712 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
714 uint lvl, attr, cacheblk, last, slot, idx;
715 uint nlatchpage, latchhash;
716 BtLatchMgr *latchmgr;
724 SYSTEM_INFO sysinfo[1];
727 // determine sanity of page size and buffer pool
729 if( bits > BT_maxbits )
731 else if( bits < BT_minbits )
735 return NULL; // must have buffer pool
738 mgr = calloc (1, sizeof(BtMgr));
740 mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
743 return free(mgr), NULL;
745 cacheblk = 4096; // minimum mmap segment size for unix
748 mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
749 attr = FILE_ATTRIBUTE_NORMAL;
750 mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
752 if( mgr->idx == INVALID_HANDLE_VALUE )
753 return GlobalFree(mgr), NULL;
755 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
756 GetSystemInfo(sysinfo);
757 cacheblk = sysinfo->dwAllocationGranularity;
761 latchmgr = malloc (BT_maxpage);
764 // read minimum page size to get root info
766 if( size = lseek (mgr->idx, 0L, 2) ) {
767 if( pread(mgr->idx, latchmgr, BT_minpage, 0) == BT_minpage )
768 bits = latchmgr->alloc->bits;
770 return free(mgr), free(latchmgr), NULL;
771 } else if( mode == BT_ro )
772 return bt_mgrclose (mgr), NULL;
774 latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
775 size = GetFileSize(mgr->idx, amt);
778 if( !ReadFile(mgr->idx, (char *)latchmgr, BT_minpage, amt, NULL) )
779 return bt_mgrclose (mgr), NULL;
780 bits = latchmgr->alloc->bits;
781 } else if( mode == BT_ro )
782 return bt_mgrclose (mgr), NULL;
785 mgr->page_size = 1 << bits;
786 mgr->page_bits = bits;
788 mgr->poolmax = poolmax;
791 if( cacheblk < mgr->page_size )
792 cacheblk = mgr->page_size;
794 // mask for partial memmaps
796 mgr->poolmask = (cacheblk >> bits) - 1;
798 // see if requested size of pages per memmap is greater
800 if( (1 << segsize) > mgr->poolmask )
801 mgr->poolmask = (1 << segsize) - 1;
805 while( (1 << mgr->seg_bits) <= mgr->poolmask )
808 mgr->hashsize = hashsize;
811 mgr->pool = calloc (poolmax, sizeof(BtPool));
812 mgr->hash = calloc (hashsize, sizeof(ushort));
813 mgr->latch = calloc (hashsize, sizeof(BtSpinLatch));
814 mgr->pooladvise = calloc (poolmax, (mgr->poolmask + 8) / 8);
816 mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * sizeof(BtPool));
817 mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
818 mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtSpinLatch));
824 // initialize an empty b-tree with latch page, root page, page of leaves
825 // and page(s) of latches
827 memset (latchmgr, 0, 1 << bits);
828 nlatchpage = BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1;
829 bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
830 latchmgr->alloc->bits = mgr->page_bits;
832 latchmgr->nlatchpage = nlatchpage;
833 latchmgr->latchtotal = nlatchpage * (mgr->page_size / sizeof(BtLatchSet));
835 // initialize latch manager
837 latchhash = (mgr->page_size - sizeof(BtLatchMgr)) / sizeof(BtHashEntry);
839 // size of hash table = total number of latchsets
841 if( latchhash > latchmgr->latchtotal )
842 latchhash = latchmgr->latchtotal;
844 latchmgr->latchhash = latchhash;
847 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
848 return bt_mgrclose (mgr), NULL;
850 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
851 return bt_mgrclose (mgr), NULL;
853 if( *amt < mgr->page_size )
854 return bt_mgrclose (mgr), NULL;
857 memset (latchmgr, 0, 1 << bits);
858 latchmgr->alloc->bits = mgr->page_bits;
860 for( lvl=MIN_lvl; lvl--; ) {
861 slotptr(latchmgr->alloc, 1)->off = mgr->page_size - 3;
862 bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
863 key = keyptr(latchmgr->alloc, 1);
864 key->len = 2; // create stopper key
867 latchmgr->alloc->min = mgr->page_size - 3;
868 latchmgr->alloc->lvl = lvl;
869 latchmgr->alloc->cnt = 1;
870 latchmgr->alloc->act = 1;
872 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
873 return bt_mgrclose (mgr), NULL;
875 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
876 return bt_mgrclose (mgr), NULL;
878 if( *amt < mgr->page_size )
879 return bt_mgrclose (mgr), NULL;
883 // clear out latch manager locks
884 // and rest of pages to round out segment
886 memset(latchmgr, 0, mgr->page_size);
889 while( last <= ((MIN_lvl + 1 + nlatchpage) | mgr->poolmask) ) {
891 pwrite(mgr->idx, latchmgr, mgr->page_size, last << mgr->page_bits);
893 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
894 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
895 return bt_mgrclose (mgr), NULL;
896 if( *amt < mgr->page_size )
897 return bt_mgrclose (mgr), NULL;
904 flag = PROT_READ | PROT_WRITE;
905 mgr->latchmgr = mmap (0, mgr->page_size, flag, MAP_SHARED, mgr->idx, ALLOC_page * mgr->page_size);
906 if( mgr->latchmgr == MAP_FAILED )
907 return bt_mgrclose (mgr), NULL;
908 mgr->latchsets = (BtLatchSet *)mmap (0, mgr->latchmgr->nlatchpage * mgr->page_size, flag, MAP_SHARED, mgr->idx, LATCH_page * mgr->page_size);
909 if( mgr->latchsets == MAP_FAILED )
910 return bt_mgrclose (mgr), NULL;
912 flag = PAGE_READWRITE;
913 mgr->halloc = CreateFileMapping(mgr->idx, NULL, flag, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size, NULL);
915 return bt_mgrclose (mgr), NULL;
917 flag = FILE_MAP_WRITE;
918 mgr->latchmgr = MapViewOfFile(mgr->halloc, flag, 0, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size);
920 return GetLastError(), bt_mgrclose (mgr), NULL;
922 mgr->latchsets = (void *)((char *)mgr->latchmgr + LATCH_page * mgr->page_size);
928 VirtualFree (latchmgr, 0, MEM_RELEASE);
933 // open BTree access method
934 // based on buffer manager
936 BtDb *bt_open (BtMgr *mgr)
938 BtDb *bt = malloc (sizeof(*bt));
940 memset (bt, 0, sizeof(*bt));
943 bt->mem = malloc (3 *mgr->page_size);
945 bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
947 bt->frame = (BtPage)bt->mem;
948 bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
949 bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
953 // compare two keys, returning > 0, = 0, or < 0
954 // as the comparison value
956 int keycmp (BtKey key1, unsigned char *key2, uint len2)
958 uint len1 = key1->len;
961 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
974 // find segment in pool
975 // must be called with hashslot idx locked
976 // return NULL if not there
977 // otherwise return node
979 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
984 // compute start of hash chain in pool
986 if( slot = bt->mgr->hash[idx] )
987 pool = bt->mgr->pool + slot;
991 page_no &= ~bt->mgr->poolmask;
993 while( pool->basepage != page_no )
994 if( pool = pool->hashnext )
1002 // add segment to hash table
1004 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
1009 pool->hashprev = pool->hashnext = NULL;
1010 pool->basepage = page_no & ~bt->mgr->poolmask;
1013 if( slot = bt->mgr->hash[idx] ) {
1014 node = bt->mgr->pool + slot;
1015 pool->hashnext = node;
1016 node->hashprev = pool;
1019 bt->mgr->hash[idx] = pool->slot;
1022 // find best segment to evict from buffer pool
1024 BtPool *bt_findlru (BtDb *bt, uint hashslot)
1026 unsigned long long int target = ~0LL;
1027 BtPool *pool = NULL, *node;
1032 node = bt->mgr->pool + hashslot;
1034 // scan pool entries under hash table slot
1039 if( node->lru > target )
1043 } while( node = node->hashnext );
1048 // map new buffer pool segment to virtual memory
1050 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
1052 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
1053 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
1057 flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
1058 pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED, bt->mgr->idx, off);
1059 if( pool->map == MAP_FAILED )
1060 return bt->err = BTERR_map;
1061 // clear out madvise issued bits
1062 memset (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8) / 8), 0, (bt->mgr->poolmask + 8)/8);
1064 flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
1065 pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
1067 return bt->err = BTERR_map;
1069 flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
1070 pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1072 return bt->err = BTERR_map;
1077 // find or place requested page in segment-pool
1078 // return pool table entry, incrementing pin
1080 BtPool *bt_pinpage(BtDb *bt, uid page_no)
1082 BtPool *pool, *node, *next;
1083 uint slot, idx, victim;
1086 // lock hash table chain
1088 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1089 bt_spinreadlock (&bt->mgr->latch[idx]);
1091 // look up in hash table
1093 if( pool = bt_findpool(bt, page_no, idx) ) {
1095 __sync_fetch_and_add(&pool->pin, 1);
1097 _InterlockedIncrement16 (&pool->pin);
1099 bt_spinreleaseread (&bt->mgr->latch[idx]);
1104 // upgrade to write lock
1106 bt_spinreleaseread (&bt->mgr->latch[idx]);
1107 bt_spinwritelock (&bt->mgr->latch[idx]);
1109 // try to find page in pool with write lock
1111 if( pool = bt_findpool(bt, page_no, idx) ) {
1113 __sync_fetch_and_add(&pool->pin, 1);
1115 _InterlockedIncrement16 (&pool->pin);
1117 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1122 // allocate a new pool node
1123 // and add to hash table
1126 slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
1128 slot = _InterlockedIncrement16 (&bt->mgr->poolcnt) - 1;
1131 if( ++slot < bt->mgr->poolmax ) {
1132 pool = bt->mgr->pool + slot;
1135 if( bt_mapsegment(bt, pool, page_no) )
1138 bt_linkhash(bt, pool, page_no, idx);
1140 __sync_fetch_and_add(&pool->pin, 1);
1142 _InterlockedIncrement16 (&pool->pin);
1144 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1148 // pool table is full
1149 // find best pool entry to evict
1152 __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
1154 _InterlockedDecrement16 (&bt->mgr->poolcnt);
1159 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
1161 victim = _InterlockedIncrement16 (&bt->mgr->evicted) - 1;
1163 victim %= bt->mgr->hashsize;
1165 // try to get write lock
1166 // skip entry if not obtained
1168 if( !bt_spinwritetry (&bt->mgr->latch[victim]) )
1171 // if cache entry is empty
1172 // or no slots are unpinned
1175 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
1176 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1180 // unlink victim pool node from hash table
1182 if( node = pool->hashprev )
1183 node->hashnext = pool->hashnext;
1184 else if( node = pool->hashnext )
1185 bt->mgr->hash[victim] = node->slot;
1187 bt->mgr->hash[victim] = 0;
1189 if( node = pool->hashnext )
1190 node->hashprev = pool->hashprev;
1192 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1194 // remove old file mapping
1196 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1198 FlushViewOfFile(pool->map, 0);
1199 UnmapViewOfFile(pool->map);
1200 CloseHandle(pool->hmap);
1204 // create new pool mapping
1205 // and link into hash table
1207 if( bt_mapsegment(bt, pool, page_no) )
1210 bt_linkhash(bt, pool, page_no, idx);
1212 __sync_fetch_and_add(&pool->pin, 1);
1214 _InterlockedIncrement16 (&pool->pin);
1216 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1221 // place write, read, or parent lock on requested page_no.
1222 // pin to buffer pool and return latchset pointer
1224 BtLatchSet *bt_lockpage(BtDb *bt, uid page_no, BtLock mode, BtPage *pageptr, BtLatchSet *set)
1230 // find/create maping in pool table
1231 // and pin our pool slot
1233 if( pool = bt_pinpage(bt, page_no) )
1234 subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1240 __sync_fetch_and_add(&set->pin, 1);
1242 _InterlockedIncrement16 (&set->pin);
1244 else if( !(set = bt_bindlatch (bt, page_no, 1)) )
1247 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1251 uint idx = subpage / 8;
1252 uint bit = subpage % 8;
1254 if( mode == BtLockRead || mode == BtLockWrite )
1255 if( ~((bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] >> bit) & 1 ) {
1256 madvise (page, bt->mgr->page_size, MADV_WILLNEED);
1257 (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] |= 1 << bit;
1264 bt_spinreadlock (set->readwr);
1267 bt_spinwritelock (set->readwr);
1270 bt_spinreadlock (set->access);
1273 bt_spinwritelock (set->access);
1276 bt_spinwritelock (set->parent);
1281 return bt->err = BTERR_lock, NULL;
1290 // remove write, read, or parent lock on requested page_no.
1292 BTERR bt_unlockpage(BtDb *bt, uid page_no, BtLock mode, BtLatchSet *set)
1297 // since page is pinned
1298 // it should still be in the buffer pool
1299 // and is in no danger of being a victim for reuse
1301 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1302 bt_spinreadlock (&bt->mgr->latch[idx]);
1304 if( !(pool = bt_findpool(bt, page_no, idx)) )
1305 return bt->err = BTERR_hash;
1307 bt_spinreleaseread (&bt->mgr->latch[idx]);
1311 bt_spinreleaseread (set->readwr);
1314 bt_spinreleasewrite (set->readwr);
1317 bt_spinreleaseread (set->access);
1320 bt_spinreleasewrite (set->access);
1323 bt_spinreleasewrite (set->parent);
1328 return bt->err = BTERR_lock;
1332 __sync_fetch_and_add(&pool->pin, -1);
1333 __sync_fetch_and_add (&set->pin, -1);
1335 _InterlockedDecrement16 (&pool->pin);
1336 _InterlockedDecrement16 (&set->pin);
1341 // deallocate a deleted page
1342 // place on free chain out of allocator page
1343 // fence key must already be removed from parent
1345 BTERR bt_freepage(BtDb *bt, uid page_no, BtLatchSet *set)
1347 // obtain delete lock on deleted page
1349 if( !bt_lockpage(bt, page_no, BtLockDelete, NULL, set) )
1352 // obtain write lock on deleted page
1354 if( !bt_lockpage(bt, page_no, BtLockWrite, &bt->temp, set) )
1357 // lock allocation page
1359 bt_spinwritelock(bt->mgr->latchmgr->lock);
1361 // store free chain in allocation page second right
1362 bt_putid(bt->temp->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1363 bt_putid(bt->mgr->latchmgr->alloc[1].right, page_no);
1367 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1369 // remove write lock on deleted node
1371 if( bt_unlockpage(bt, page_no, BtLockWrite, set) )
1374 // remove delete lock on deleted node
1376 if( bt_unlockpage(bt, page_no, BtLockDelete, set) )
1382 // allocate a new page and write page into it
1384 uid bt_newpage(BtDb *bt, BtPage page)
1391 // lock allocation page
1393 bt_spinwritelock(bt->mgr->latchmgr->lock);
1395 // use empty chain first
1396 // else allocate empty page
1398 if( new_page = bt_getid(bt->mgr->latchmgr->alloc[1].right) ) {
1399 if( !(set = bt_lockpage (bt, new_page, BtLockWrite, &bt->temp, NULL)) )
1401 bt_putid(bt->mgr->latchmgr->alloc[1].right, bt_getid(bt->temp->right));
1402 if( bt_unlockpage (bt, new_page, BtLockWrite, set) )
1406 new_page = bt_getid(bt->mgr->latchmgr->alloc->right);
1407 bt_putid(bt->mgr->latchmgr->alloc->right, new_page+1);
1411 if ( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1412 return bt->err = BTERR_wrt, 0;
1414 // if writing first page of pool block, zero last page in the block
1416 if ( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1418 // use zero buffer to write zeros
1419 memset(bt->zero, 0, bt->mgr->page_size);
1420 if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1421 return bt->err = BTERR_wrt, 0;
1424 // bring new page into pool and copy page.
1425 // this will extend the file into the new pages.
1427 if( !(set = bt_lockpage(bt, new_page, BtLockWrite, &pmap, NULL)) )
1430 memcpy(pmap, page, bt->mgr->page_size);
1432 if( bt_unlockpage (bt, new_page, BtLockWrite, set) )
1435 // unlock allocation latch and return new page no
1437 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1441 // find slot in page for given key at a given level
1443 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1445 uint diff, higher = bt->page->cnt, low = 1, slot;
1447 // low is the lowest candidate, higher is already
1448 // tested as .ge. the given key, loop ends when they meet
1450 while( diff = higher - low ) {
1451 slot = low + ( diff >> 1 );
1452 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1461 // find and load page at given level for given key
1462 // leave page rd or wr locked as requested
1464 int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, BtLock lock)
1466 uid page_no = ROOT_page, prevpage = 0;
1467 BtLatchSet *set, *prevset;
1468 uint drill = 0xff, slot;
1469 uint mode, prevmode;
1473 // start at root of btree and drill down
1476 // determine lock mode of drill level
1477 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1479 bt->page_no = page_no;
1481 // obtain access lock using lock chaining with Access mode
1483 if( page_no > ROOT_page )
1484 if( !(bt->set = bt_lockpage(bt, page_no, BtLockAccess, NULL, NULL)) )
1487 // now unlock our (possibly foster) parent
1490 if( bt_unlockpage(bt, prevpage, prevmode, prevset) )
1495 // obtain read lock using lock chaining
1496 // and pin page contents
1498 if( !(bt->set = bt_lockpage(bt, page_no, mode, &bt->page, bt->set)) )
1501 if( page_no > ROOT_page )
1502 if( bt_unlockpage(bt, page_no, BtLockAccess, bt->set) )
1505 // re-read and re-lock root after determining actual level of root
1507 if( bt->page_no == ROOT_page )
1508 if( bt->page->lvl != drill) {
1509 drill = bt->page->lvl;
1511 if( lock == BtLockWrite && drill == lvl )
1512 if( bt_unlockpage(bt, page_no, mode, bt->set) )
1518 prevpage = bt->page_no;
1522 // if page is being deleted,
1523 // move back to preceeding page
1525 if( bt->page->kill ) {
1526 page_no = bt_getid (bt->page->right);
1530 // find key on page at this level
1531 // and descend to requested level
1533 slot = bt_findslot (bt, key, len);
1535 // is this slot a foster child?
1537 if( slot <= bt->page->cnt - bt->page->foster )
1541 while( slotptr(bt->page, slot)->dead )
1542 if( slot++ < bt->page->cnt )
1547 if( slot <= bt->page->cnt - bt->page->foster )
1550 // continue down / right using overlapping locks
1551 // to protect pages being killed or split.
1553 page_no = bt_getid(slotptr(bt->page, slot)->id);
1557 page_no = bt_getid(bt->page->right);
1561 // return error on end of chain
1563 bt->err = BTERR_struct;
1564 return 0; // return error
1567 // find and delete key on page by marking delete flag bit
1568 // when page becomes empty, delete it from the btree
1570 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl)
1572 unsigned char leftkey[256], rightkey[256];
1573 BtLatchSet *rset, *set;
1578 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1579 ptr = keyptr(bt->page, slot);
1583 // if key is found delete it, otherwise ignore request
1585 if( !keycmp (ptr, key, len) )
1586 if( slotptr(bt->page, slot)->dead == 0 ) {
1587 slotptr(bt->page,slot)->dead = 1;
1588 if( slot < bt->page->cnt )
1589 bt->page->dirty = 1;
1593 // return if page is not empty, or it has no right sibling
1595 right = bt_getid(bt->page->right);
1596 page_no = bt->page_no;
1599 if( !right || bt->page->act )
1600 return bt_unlockpage(bt, page_no, BtLockWrite, set);
1602 // obtain Parent lock over write lock
1604 if( !bt_lockpage(bt, page_no, BtLockParent, NULL, set) )
1607 // cache copy of key to delete
1609 ptr = keyptr(bt->page, bt->page->cnt);
1610 memcpy(leftkey, ptr, ptr->len + 1);
1612 // lock and map right page
1614 if( !(rset = bt_lockpage(bt, right, BtLockWrite, &bt->temp, NULL)) )
1617 // pull contents of next page into current empty page
1618 memcpy (bt->page, bt->temp, bt->mgr->page_size);
1620 // cache copy of key to update
1621 ptr = keyptr(bt->temp, bt->temp->cnt);
1622 memcpy(rightkey, ptr, ptr->len + 1);
1624 // Mark right page as deleted and point it to left page
1625 // until we can post updates at higher level.
1627 bt_putid(bt->temp->right, page_no);
1631 if( bt_unlockpage(bt, right, BtLockWrite, rset) )
1633 if( bt_unlockpage(bt, page_no, BtLockWrite, set) )
1636 // delete old lower key to consolidated node
1638 if( bt_deletekey (bt, leftkey + 1, *leftkey, lvl + 1) )
1641 // redirect higher key directly to consolidated node
1643 if( slot = bt_loadpage (bt, rightkey+1, *rightkey, lvl+1, BtLockWrite) )
1644 ptr = keyptr(bt->page, slot);
1648 // since key already exists, update id
1650 if( keycmp (ptr, rightkey+1, *rightkey) )
1651 return bt->err = BTERR_struct;
1653 slotptr(bt->page, slot)->dead = 0;
1654 bt_putid(slotptr(bt->page,slot)->id, page_no);
1656 if( bt_unlockpage(bt, bt->page_no, BtLockWrite, bt->set) )
1659 // obtain write lock and
1660 // add right block to free chain
1662 if( bt_freepage (bt, right, rset) )
1665 // remove ParentModify lock
1667 if( bt_unlockpage(bt, page_no, BtLockParent, set) )
1673 // find key in leaf level and return row-id
1675 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1681 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1682 ptr = keyptr(bt->page, slot);
1686 // if key exists, return row-id
1687 // otherwise return 0
1689 if( ptr->len == len && !memcmp (ptr->key, key, len) )
1690 id = bt_getid(slotptr(bt->page,slot)->id);
1694 if( bt_unlockpage (bt, bt->page_no, BtLockRead, bt->set) )
1700 // check page for space available,
1701 // clean if necessary and return
1702 // 0 - page needs splitting
1705 uint bt_cleanpage(BtDb *bt, uint amt)
1707 uint nxt = bt->mgr->page_size;
1708 BtPage page = bt->page;
1709 uint cnt = 0, idx = 0;
1710 uint max = page->cnt;
1713 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1716 // skip cleanup if nothing to reclaim
1721 memcpy (bt->frame, page, bt->mgr->page_size);
1723 // skip page info and set rest of page to zero
1725 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1729 // try cleaning up page first
1731 while( cnt++ < max ) {
1732 // always leave fence key and foster children in list
1733 if( cnt < max - page->foster && slotptr(bt->frame,cnt)->dead )
1737 key = keyptr(bt->frame, cnt);
1738 nxt -= key->len + 1;
1739 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1742 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1743 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1745 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1746 slotptr(page, idx)->off = nxt;
1752 // see if page has enough space now, or does it need splitting?
1754 if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1760 // add key to current page
1761 // page must already be writelocked
1763 void bt_addkeytopage (BtDb *bt, uint slot, unsigned char *key, uint len, uid id, uint tod)
1765 BtPage page = bt->page;
1768 // calculate next available slot and copy key into page
1770 page->min -= len + 1;
1771 ((unsigned char *)page)[page->min] = len;
1772 memcpy ((unsigned char *)page + page->min +1, key, len );
1774 for( idx = slot; idx < page->cnt; idx++ )
1775 if( slotptr(page, idx)->dead )
1778 // now insert key into array before slot
1779 // preserving the fence slot
1781 if( idx == page->cnt )
1787 *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
1789 bt_putid(slotptr(page,slot)->id, id);
1790 slotptr(page, slot)->off = page->min;
1791 slotptr(page, slot)->tod = tod;
1792 slotptr(page, slot)->dead = 0;
1795 // split the root and raise the height of the btree
1796 // call with current page locked and page no of foster child
1797 // return with current page (root) unlocked
1799 BTERR bt_splitroot(BtDb *bt, uid right)
1801 uint nxt = bt->mgr->page_size;
1802 unsigned char fencekey[256];
1803 BtPage root = bt->page;
1807 // Obtain an empty page to use, and copy the left page
1808 // contents into it from the root. Strip foster child key.
1809 // (it's the stopper key)
1815 // Save left fence key.
1817 key = keyptr(root, root->cnt);
1818 memcpy (fencekey, key, key->len + 1);
1820 // copy the lower keys into a new left page
1822 if( !(new_page = bt_newpage(bt, root)) )
1825 // preserve the page info at the bottom
1826 // and set rest of the root to zero
1828 memset (root+1, 0, bt->mgr->page_size - sizeof(*root));
1830 // insert left fence key on empty newroot page
1832 nxt -= *fencekey + 1;
1833 memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
1834 bt_putid(slotptr(root, 1)->id, new_page);
1835 slotptr(root, 1)->off = nxt;
1837 // insert stopper key on newroot page
1838 // and increase the root height
1844 memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
1845 bt_putid(slotptr(root, 2)->id, right);
1846 slotptr(root, 2)->off = nxt;
1848 bt_putid(root->right, 0);
1849 root->min = nxt; // reset lowest used offset and key count
1854 // release root (bt->page)
1856 return bt_unlockpage(bt, ROOT_page, BtLockWrite, bt->set);
1859 // split already locked full node
1860 // in current page variables
1863 BTERR bt_splitpage (BtDb *bt)
1865 uint slot, cnt, idx, max, nxt = bt->mgr->page_size;
1866 unsigned char fencekey[256];
1867 uid page_no = bt->page_no;
1868 BtLatchSet *set = bt->set;
1869 BtPage page = bt->page;
1870 uint tod = time(NULL);
1871 uint lvl = page->lvl;
1872 uid new_page, right;
1875 // initialize frame buffer
1877 memset (bt->frame, 0, bt->mgr->page_size);
1878 max = page->cnt - page->foster;
1879 tod = (uint)time(NULL);
1883 // split higher half of keys to bt->frame
1884 // leaving foster children in the left node.
1886 while( cnt++ < max ) {
1887 key = keyptr(page, cnt);
1888 nxt -= key->len + 1;
1889 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
1890 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
1891 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
1892 slotptr(bt->frame, idx)->off = nxt;
1896 // transfer right link node
1898 if( page_no > ROOT_page ) {
1899 right = bt_getid (page->right);
1900 bt_putid(bt->frame->right, right);
1903 bt->frame->bits = bt->mgr->page_bits;
1904 bt->frame->min = nxt;
1905 bt->frame->cnt = idx;
1906 bt->frame->lvl = lvl;
1908 // get new free page and write frame to it.
1910 if( !(new_page = bt_newpage(bt, bt->frame)) )
1913 // remember fence key for new page to add
1916 key = keyptr(bt->frame, idx);
1917 memcpy (fencekey, key, key->len + 1);
1919 // update lower keys and foster children to continue in old page
1921 memcpy (bt->frame, page, bt->mgr->page_size);
1922 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1923 nxt = bt->mgr->page_size;
1928 // assemble page of smaller keys
1929 // to remain in the old page
1931 while( cnt++ < max / 2 ) {
1932 key = keyptr(bt->frame, cnt);
1933 nxt -= key->len + 1;
1934 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1935 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1936 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1937 slotptr(page, idx)->off = nxt;
1941 // insert new foster child at beginning of the current foster children
1943 nxt -= *fencekey + 1;
1944 memcpy ((unsigned char *)page + nxt, fencekey, *fencekey + 1);
1945 bt_putid (slotptr(page,++idx)->id, new_page);
1946 slotptr(page, idx)->tod = tod;
1947 slotptr(page, idx)->off = nxt;
1951 // continue with old foster child keys if any
1953 cnt = bt->frame->cnt - bt->frame->foster;
1955 while( cnt++ < bt->frame->cnt ) {
1956 key = keyptr(bt->frame, cnt);
1957 nxt -= key->len + 1;
1958 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1959 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1960 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1961 slotptr(page, idx)->off = nxt;
1968 // link new right page
1970 bt_putid (page->right, new_page);
1972 // if current page is the root page, split it
1974 if( page_no == ROOT_page )
1975 return bt_splitroot (bt, new_page);
1977 // keep our latch set
1978 // release wr lock on our page
1980 if( !bt_lockpage (bt, page_no, BtLockPin, NULL, set) )
1983 if( bt_unlockpage (bt, page_no, BtLockWrite, set) )
1986 // obtain ParentModification lock for current page
1987 // to fix fence key and highest foster child on page
1989 if( !bt_lockpage (bt, page_no, BtLockParent, NULL, set) )
1992 // get our highest foster child key to find in parent node
1994 if( !bt_lockpage (bt, page_no, BtLockRead, &page, set) )
1997 key = keyptr(page, page->cnt);
1998 memcpy (fencekey, key, key->len+1);
2000 if( bt_unlockpage (bt, page_no, BtLockRead, set) )
2003 // update our parent
2007 slot = bt_loadpage (bt, fencekey + 1, *fencekey, lvl + 1, BtLockWrite);
2012 // check if parent page has enough space for any possible key
2014 if( bt_cleanpage (bt, 256) )
2017 if( bt_splitpage (bt) )
2021 // see if we are still a foster child from another node
2023 if( bt_getid (slotptr(bt->page, slot)->id) != page_no ) {
2024 if( bt_unlockpage (bt, bt->page_no, BtLockWrite, bt->set) )
2034 // wait until readers from parent get their locks
2037 if( !bt_lockpage (bt, page_no, BtLockDelete, NULL, set) )
2040 // lock our page for writing
2042 if( !bt_lockpage (bt, page_no, BtLockWrite, &page, set) )
2045 // switch parent fence key to foster child
2047 if( slotptr(page, page->cnt)->dead )
2048 slotptr(bt->page, slot)->dead = 1;
2050 bt_putid (slotptr(bt->page, slot)->id, bt_getid(slotptr(page, page->cnt)->id));
2052 // remove highest foster child from our page
2058 key = keyptr(page, page->cnt);
2060 // add our new fence key for foster child to our parent
2062 bt_addkeytopage (bt, slot, key->key, key->len, page_no, tod);
2064 if( bt_unlockpage (bt, bt->page_no, BtLockWrite, bt->set) )
2067 if( bt_unlockpage (bt, page_no, BtLockDelete, set) )
2070 if( bt_unlockpage (bt, page_no, BtLockWrite, set) )
2073 if( bt_unlockpage (bt, page_no, BtLockParent, set) )
2076 // release extra latch pin
2078 return bt_unlockpage (bt, page_no, BtLockPin, set);
2081 // Insert new key into the btree at leaf level.
2083 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod)
2090 if( slot = bt_loadpage (bt, key, len, 0, BtLockWrite) )
2091 ptr = keyptr(bt->page, slot);
2095 bt->err = BTERR_ovflw;
2099 // if key already exists, update id and return
2103 if( !keycmp (ptr, key, len) ) {
2104 slotptr(page, slot)->dead = 0;
2105 slotptr(page, slot)->tod = tod;
2106 bt_putid(slotptr(page,slot)->id, id);
2107 return bt_unlockpage(bt, bt->page_no, BtLockWrite, bt->set);
2110 // check if page has enough space
2112 if( bt_cleanpage (bt, len) )
2115 if( bt_splitpage (bt) )
2119 bt_addkeytopage (bt, slot, key, len, id, tod);
2121 return bt_unlockpage (bt, bt->page_no, BtLockWrite, bt->set);
2124 // cache page of keys into cursor and return starting slot for given key
2126 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2130 // cache page for retrieval
2131 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
2132 memcpy (bt->cursor, bt->page, bt->mgr->page_size);
2133 bt->cursor_page = bt->page_no;
2134 if ( bt_unlockpage(bt, bt->page_no, BtLockRead, bt->set) )
2140 // return next slot for cursor page
2141 // or slide cursor right into next page
2143 uint bt_nextkey (BtDb *bt, uint slot)
2150 right = bt_getid(bt->cursor->right);
2151 while( slot++ < bt->cursor->cnt - bt->cursor->foster )
2152 if( slotptr(bt->cursor,slot)->dead )
2154 else if( right || (slot < bt->cursor->cnt - bt->cursor->foster) )
2162 bt->cursor_page = right;
2164 if( !(bt->set = bt_lockpage(bt, right, BtLockRead, &page, NULL)) )
2167 memcpy (bt->cursor, page, bt->mgr->page_size);
2169 if ( bt_unlockpage(bt, right, BtLockRead, bt->set) )
2178 BtKey bt_key(BtDb *bt, uint slot)
2180 return keyptr(bt->cursor, slot);
2183 uid bt_uid(BtDb *bt, uint slot)
2185 return bt_getid(slotptr(bt->cursor,slot)->id);
2188 uint bt_tod(BtDb *bt, uint slot)
2190 return slotptr(bt->cursor,slot)->tod;
2203 // standalone program to index file of keys
2204 // then list them onto std-out
2207 void *index_file (void *arg)
2209 uint __stdcall index_file (void *arg)
2212 int line = 0, found = 0, cnt = 0;
2213 uid next, page_no = LEAF_page; // start on first page of leaves
2214 unsigned char key[256];
2215 ThreadArg *args = arg;
2216 int ch, len = 0, slot;
2223 bt = bt_open (args->mgr);
2226 switch(args->type | 0x20)
2229 fprintf(stderr, "started indexing for %s\n", args->infile);
2230 if( in = fopen (args->infile, "rb") )
2231 while( ch = getc(in), ch != EOF )
2236 if( args->num == 1 )
2237 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2239 else if( args->num )
2240 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2242 if( bt_insertkey (bt, key, len, line, *tod) )
2243 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2246 else if( len < 255 )
2248 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
2252 fprintf(stderr, "started deleting keys for %s\n", args->infile);
2253 if( in = fopen (args->infile, "rb") )
2254 while( ch = getc(in), ch != EOF )
2258 if( args->num == 1 )
2259 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2261 else if( args->num )
2262 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2264 if( bt_deletekey (bt, key, len, 0) )
2265 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2268 else if( len < 255 )
2270 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2274 fprintf(stderr, "started finding keys for %s\n", args->infile);
2275 if( in = fopen (args->infile, "rb") )
2276 while( ch = getc(in), ch != EOF )
2280 if( args->num == 1 )
2281 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2283 else if( args->num )
2284 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2286 if( bt_findkey (bt, key, len) )
2289 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2292 else if( len < 255 )
2294 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2300 fprintf(stderr, "started reading\n");
2302 if( slot = bt_startkey (bt, key, len) )
2305 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
2307 while( slot = bt_nextkey (bt, slot) ) {
2308 ptr = bt_key(bt, slot);
2309 fwrite (ptr->key, ptr->len, 1, stdout);
2310 fputc ('\n', stdout);
2316 fprintf(stderr, "started reading\n");
2319 bt->set = bt_lockpage (bt, page_no, BtLockRead, &page, NULL);
2321 next = bt_getid (page->right);
2322 bt_unlockpage (bt, page_no, BtLockRead, bt->set);
2323 } while( page_no = next );
2325 cnt--; // remove stopper key
2326 fprintf(stderr, " Total keys read %d\n", cnt);
2338 typedef struct timeval timer;
2340 int main (int argc, char **argv)
2342 int idx, cnt, len, slot, err;
2343 int segsize, bits = 16;
2348 time_t start[1], stop[1];
2361 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]);
2362 fprintf (stderr, " where page_bits is the page size in bits\n");
2363 fprintf (stderr, " mapped_segments is the number of mmap segments in buffer pool\n");
2364 fprintf (stderr, " seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2365 fprintf (stderr, " line_numbers = 1 to append line numbers to keys\n");
2366 fprintf (stderr, " src_file1 thru src_filen are files of keys separated by newline\n");
2371 gettimeofday(&start, NULL);
2377 bits = atoi(argv[3]);
2380 poolsize = atoi(argv[4]);
2383 fprintf (stderr, "Warning: no mapped_pool\n");
2385 if( poolsize > 65535 )
2386 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2389 segsize = atoi(argv[5]);
2391 segsize = 4; // 16 pages per mmap segment
2394 num = atoi(argv[6]);
2398 threads = malloc (cnt * sizeof(pthread_t));
2400 threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2402 args = malloc (cnt * sizeof(ThreadArg));
2404 mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2407 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2413 for( idx = 0; idx < cnt; idx++ ) {
2414 args[idx].infile = argv[idx + 7];
2415 args[idx].type = argv[2][0];
2416 args[idx].mgr = mgr;
2417 args[idx].num = num;
2418 args[idx].idx = idx;
2420 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2421 fprintf(stderr, "Error creating thread %d\n", err);
2423 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2427 // wait for termination
2430 for( idx = 0; idx < cnt; idx++ )
2431 pthread_join (threads[idx], NULL);
2432 gettimeofday(&stop, NULL);
2433 real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2435 WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2437 for( idx = 0; idx < cnt; idx++ )
2438 CloseHandle(threads[idx]);
2441 real_time = 1000 * (*stop - *start);
2443 fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);