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.
88 // Define the length of the page and key pointers
92 // Page key slot definition.
94 // If BT_maxbits is 15 or less, you can save 4 bytes
95 // for each key stored by making the first two uints
96 // into ushorts. You can also save 4 bytes by removing
97 // the tod field from the key.
99 // Keys are marked dead, but remain on the page until
100 // it cleanup is called. The fence key (highest key) for
101 // the page is always present, even after cleanup.
104 uint off:BT_maxbits; // page offset for key start
105 uint dead:1; // set for deleted key
106 uint tod; // time-stamp for key
107 unsigned char id[BtId]; // id associated with key
110 // The key structure occupies space at the upper end of
111 // each page. It's a length byte followed by the value
116 unsigned char key[1];
119 // The first part of an index page.
120 // It is immediately followed
121 // by the BtSlot array of keys.
123 typedef struct Page {
124 uint cnt; // count of keys in page
125 uint act; // count of active keys
126 uint min; // next key offset
127 uint foster; // count of foster children
128 unsigned char bits; // page size in bits
129 unsigned char lvl:6; // level of page
130 unsigned char kill:1; // page is being deleted
131 unsigned char dirty:1; // page needs to be cleaned
132 unsigned char right[BtId]; // page number to right
135 // mode & definition for spin latch implementation
144 // mutex locks the other fields
145 // exclusive is set for write access
146 // share is count of read accessors
149 volatile ushort mutex:1;
150 volatile ushort exclusive:1;
151 volatile ushort pending:1;
152 volatile ushort share:13;
155 // hash table entries
158 BtSpinLatch latch[1];
159 volatile ushort slot; // Latch table entry at head of chain
163 BtSpinLatch readwr[1]; // read/write page lock
164 BtSpinLatch access[1]; // Access Intent/Page delete
165 BtSpinLatch parent[1]; // adoption of foster children
166 BtSpinLatch busy[1]; // slot is being moved between chains
167 volatile ushort next; // next entry in hash table chain
168 volatile ushort prev; // prev entry in hash table chain
169 volatile ushort pin; // number of outstanding locks
170 volatile ushort hash; // hash slot entry is under
171 volatile uid page_no; // latch set page number
174 // The memory mapping pool table buffer manager entry
177 unsigned long long int lru; // number of times accessed
178 uid basepage; // mapped base page number
179 char *map; // mapped memory pointer
180 ushort pin; // mapped page pin counter
181 ushort slot; // slot index in this array
182 void *hashprev; // previous pool entry for the same hash idx
183 void *hashnext; // next pool entry for the same hash idx
185 HANDLE hmap; // Windows memory mapping handle
189 // structure for latch manager on ALLOC_page
192 struct Page alloc[2]; // next & free page_nos in right ptr
193 BtSpinLatch lock[1]; // allocation area lite latch
194 ushort latchdeployed; // highest number of latch entries deployed
195 ushort nlatchpage; // number of latch pages at BT_latch
196 ushort latchtotal; // number of page latch entries
197 ushort latchhash; // number of latch hash table slots
198 ushort latchvictim; // next latch entry to examine
199 BtHashEntry table[0]; // the hash table
202 // The object structure for Btree access
205 uint page_size; // page size
206 uint page_bits; // page size in bits
207 uint seg_bits; // seg size in pages in bits
208 uint mode; // read-write mode
211 char *pooladvise; // bit maps for pool page advisements
215 ushort poolcnt; // highest page pool node in use
216 ushort poolmax; // highest page pool node allocated
217 ushort poolmask; // total size of pages in mmap segment - 1
218 ushort hashsize; // size of Hash Table for pool entries
219 ushort evicted; // last evicted hash table slot
220 ushort *hash; // hash table of pool entries
221 BtPool *pool; // memory pool page segments
222 BtSpinLatch *latch; // latches for pool hash slots
223 BtLatchMgr *latchmgr; // mapped latch page from allocation page
224 BtLatchSet *latchset; // first mapped latch set from latch pages
226 HANDLE halloc; // allocation and latch table
231 BtMgr *mgr; // buffer manager for thread
232 BtPage temp; // temporary frame buffer (memory mapped/file IO)
233 BtPage cursor; // cached frame for start/next (never mapped)
234 BtPage frame; // spare frame for the page split (never mapped)
235 BtPage zero; // page frame for zeroes at end of file
236 BtPage page; // current page
237 uid page_no; // current page number
238 uid cursor_page; // current cursor page number
239 unsigned char *mem; // frame, cursor, page memory buffer
240 int err; // last error
255 extern void bt_close (BtDb *bt);
256 extern BtDb *bt_open (BtMgr *mgr);
257 extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod);
258 extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl);
259 extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
260 extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
261 extern uint bt_nextkey (BtDb *bt, uint slot);
264 extern BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolsize, uint segsize, uint hashsize);
265 void bt_mgrclose (BtMgr *mgr);
267 // Helper functions to return cursor slot values
269 extern BtKey bt_key (BtDb *bt, uint slot);
270 extern uid bt_uid (BtDb *bt, uint slot);
271 extern uint bt_tod (BtDb *bt, uint slot);
273 // BTree page number constants
274 #define ALLOC_page 0 // allocation & lock manager hash table
275 #define ROOT_page 1 // root of the btree
276 #define LEAF_page 2 // first page of leaves
277 #define LATCH_page 3 // pages for lock manager
279 // Number of levels to create in a new BTree
283 // The page is allocated from low and hi ends.
284 // The key offsets and row-id's are allocated
285 // from the bottom, while the text of the key
286 // is allocated from the top. When the two
287 // areas meet, the page is split into two.
289 // A key consists of a length byte, two bytes of
290 // index number (0 - 65534), and up to 253 bytes
291 // of key value. Duplicate keys are discarded.
292 // Associated with each key is a 48 bit row-id.
294 // The b-tree root is always located at page 1.
295 // The first leaf page of level zero is always
296 // located on page 2.
298 // When to root page fills, it is split in two and
299 // the tree height is raised by a new root at page
300 // one with two keys.
302 // Deleted keys are marked with a dead bit until
303 // page cleanup The fence key for a node is always
304 // present, even after deletion and cleanup.
306 // Groups of pages called segments from the btree are
307 // cached with memory mapping. A hash table is used to keep
308 // track of the cached segments. This behaviour is controlled
309 // by the cache block size parameter to bt_open.
311 // To achieve maximum concurrency one page is locked at a time
312 // as the tree is traversed to find leaf key in question.
314 // An adoption traversal leaves the parent node locked as the
315 // tree is traversed to the level in quesiton.
317 // Page 0 is dedicated to lock for new page extensions,
318 // and chains empty pages together for reuse.
320 // Empty pages are chained together through the ALLOC page and reused.
322 // Access macros to address slot and key values from the page
324 #define slotptr(page, slot) (((BtSlot *)(page+1)) + (slot-1))
325 #define keyptr(page, slot) ((BtKey)((unsigned char*)(page) + slotptr(page, slot)->off))
327 void bt_putid(unsigned char *dest, uid id)
332 dest[i] = (unsigned char)id, id >>= 8;
335 uid bt_getid(unsigned char *src)
340 for( i = 0; i < BtId; i++ )
341 id <<= 8, id |= *src++;
346 // wait until write lock mode is clear
347 // and add 1 to the share count
349 void bt_spinreadlock(BtSpinLatch *latch)
355 while( __sync_fetch_and_or((ushort *)latch, Mutex) & Mutex )
358 while( _InterlockedOr16((ushort *)latch, Mutex) & Mutex )
362 // see if exclusive request is granted or pending
364 if( prev = !(latch->exclusive | latch->pending) )
366 __sync_fetch_and_add((ushort *)latch, Share);
368 _InterlockedExchangeAdd16 ((ushort *)latch, Share);
372 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
374 _InterlockedAnd16((ushort *)latch, ~Mutex);
380 } while( sched_yield(), 1 );
382 } while( SwitchToThread(), 1 );
386 // wait for other read and write latches to relinquish
388 void bt_spinwritelock(BtSpinLatch *latch)
394 while( __sync_fetch_and_or((ushort *)latch, Mutex | Pending) & Mutex )
397 while( _InterlockedOr16((ushort *)latch, Mutex | Pending) & Mutex )
400 if( prev = !(latch->share | latch->exclusive) )
402 __sync_fetch_and_or((ushort *)latch, Write);
404 _InterlockedOr16((ushort *)latch, Write);
408 __sync_fetch_and_and ((ushort *)latch, ~(Mutex | Pending));
410 _InterlockedAnd16((ushort *)latch, ~(Mutex | Pending));
422 // try to obtain write lock
424 // return 1 if obtained,
427 int bt_spinwritetry(BtSpinLatch *latch)
432 if( prev = __sync_fetch_and_or((ushort *)latch, Mutex), prev & Mutex )
435 if( prev = _InterlockedOr16((ushort *)latch, Mutex), prev & Mutex )
438 // take write access if all bits are clear
442 __sync_fetch_and_or ((ushort *)latch, Write);
444 _InterlockedOr16((ushort *)latch, Write);
448 __sync_fetch_and_and ((ushort *)latch, ~Mutex);
450 _InterlockedAnd16((ushort *)latch, ~Mutex);
457 void bt_spinreleasewrite(BtSpinLatch *latch)
460 __sync_fetch_and_and ((ushort *)latch, ~Write);
462 _InterlockedAnd16((ushort *)latch, ~Write);
466 // decrement reader count
468 void bt_spinreleaseread(BtSpinLatch *latch)
471 __sync_fetch_and_add((ushort *)latch, -Share);
473 _InterlockedExchangeAdd16 ((ushort *)latch, -Share);
477 // link latch table entry into latch hash table
479 void bt_latchlink (BtDb *bt, ushort hashidx, ushort victim, uid page_no)
481 BtLatchSet *set = bt->mgr->latchset + victim;
483 if( set->next = bt->mgr->latchmgr->table[hashidx].slot )
484 bt->mgr->latchset[set->next].prev = victim;
486 bt->mgr->latchmgr->table[hashidx].slot = victim;
487 set->page_no = page_no;
492 // find existing latchset or inspire new one
493 // return with latchset pinned
495 BtLatchSet *bt_bindlatch (BtDb *bt, uid page_no, int incr)
497 ushort hashidx = page_no % bt->mgr->latchmgr->latchhash;
498 ushort slot, avail = 0, victim, idx;
501 // obtain read lock on hash table entry
503 bt_spinreadlock(bt->mgr->latchmgr->table[hashidx].latch);
505 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
507 set = bt->mgr->latchset + slot;
508 if( page_no == set->page_no )
510 } while( slot = set->next );
514 __sync_fetch_and_add(&set->pin, 1);
516 _InterlockedIncrement16 (&set->pin);
520 bt_spinreleaseread (bt->mgr->latchmgr->table[hashidx].latch);
525 // try again, this time with write lock
527 bt_spinwritelock(bt->mgr->latchmgr->table[hashidx].latch);
529 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
531 set = bt->mgr->latchset + slot;
532 if( page_no == set->page_no )
534 if( !set->pin && !avail )
536 } while( slot = set->next );
538 // found our entry, or take over an unpinned one
540 if( slot || (slot = avail) ) {
541 set = bt->mgr->latchset + slot;
544 __sync_fetch_and_add(&set->pin, 1);
546 _InterlockedIncrement16 (&set->pin);
549 set->page_no = page_no;
550 bt_spinreleasewrite(bt->mgr->latchmgr->table[hashidx].latch);
554 // see if there are any unused entries
556 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, 1) + 1;
558 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchdeployed);
561 if( victim < bt->mgr->latchmgr->latchtotal ) {
562 set = bt->mgr->latchset + victim;
564 __sync_fetch_and_add(&set->pin, 1);
566 _InterlockedIncrement16 (&set->pin);
568 bt_latchlink (bt, hashidx, victim, page_no);
569 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
574 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, -1);
576 victim = _InterlockedDecrement16 (&bt->mgr->latchmgr->latchdeployed);
578 // find and reuse previous lock entry
582 victim = __sync_fetch_and_add(&bt->mgr->latchmgr->latchvictim, 1);
584 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchvictim) - 1;
586 // we don't use slot zero
588 if( victim %= bt->mgr->latchmgr->latchtotal )
589 set = bt->mgr->latchset + victim;
593 // take control of our slot
594 // from other threads
596 if( set->pin || !bt_spinwritetry (set->busy) )
601 // try to get write lock on hash chain
602 // skip entry if not obtained
603 // or has outstanding locks
605 if( !bt_spinwritetry (bt->mgr->latchmgr->table[idx].latch) ) {
606 bt_spinreleasewrite (set->busy);
611 bt_spinreleasewrite (set->busy);
612 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
616 // unlink our available victim from its hash chain
619 bt->mgr->latchset[set->prev].next = set->next;
621 bt->mgr->latchmgr->table[idx].slot = set->next;
624 bt->mgr->latchset[set->next].prev = set->prev;
626 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
631 bt_latchlink (bt, hashidx, victim, page_no);
632 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
633 bt_spinreleasewrite (set->busy);
638 void bt_mgrclose (BtMgr *mgr)
643 // release mapped pages
644 // note that slot zero is never used
646 for( slot = 1; slot < mgr->poolmax; slot++ ) {
647 pool = mgr->pool + slot;
650 munmap (pool->map, (mgr->poolmask+1) << mgr->page_bits);
653 FlushViewOfFile(pool->map, 0);
654 UnmapViewOfFile(pool->map);
655 CloseHandle(pool->hmap);
665 free (mgr->pooladvise);
668 FlushFileBuffers(mgr->idx);
669 CloseHandle(mgr->idx);
670 GlobalFree (mgr->pool);
671 GlobalFree (mgr->hash);
672 GlobalFree (mgr->latch);
677 // close and release memory
679 void bt_close (BtDb *bt)
686 VirtualFree (bt->mem, 0, MEM_RELEASE);
691 // open/create new btree buffer manager
693 // call with file_name, BT_openmode, bits in page size (e.g. 16),
694 // size of mapped page pool (e.g. 8192)
696 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
698 uint lvl, attr, cacheblk, last, slot, idx;
699 uint nlatchpage, latchhash;
700 BtLatchMgr *latchmgr;
709 SYSTEM_INFO sysinfo[1];
712 // determine sanity of page size and buffer pool
714 if( bits > BT_maxbits )
716 else if( bits < BT_minbits )
720 return NULL; // must have buffer pool
723 mgr = calloc (1, sizeof(BtMgr));
725 switch (mode & 0x7fff)
728 mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
734 mgr->idx = open ((char*)name, O_RDONLY);
739 return free(mgr), NULL;
741 cacheblk = 4096; // minimum mmap segment size for unix
744 mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
745 attr = FILE_ATTRIBUTE_NORMAL;
746 switch (mode & 0x7fff)
749 mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
755 mgr->idx = CreateFile(name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, attr, NULL);
759 if( mgr->idx == INVALID_HANDLE_VALUE )
760 return GlobalFree(mgr), NULL;
762 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
763 GetSystemInfo(sysinfo);
764 cacheblk = sysinfo->dwAllocationGranularity;
768 latchmgr = malloc (BT_maxpage);
771 // read minimum page size to get root info
773 if( size = lseek (mgr->idx, 0L, 2) ) {
774 if( pread(mgr->idx, latchmgr, BT_minpage, 0) == BT_minpage )
775 bits = latchmgr->alloc->bits;
777 return free(mgr), free(latchmgr), NULL;
778 } else if( mode == BT_ro )
779 return bt_mgrclose (mgr), NULL;
781 latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
782 size = GetFileSize(mgr->idx, amt);
785 if( !ReadFile(mgr->idx, (char *)latchmgr, BT_minpage, amt, NULL) )
786 return bt_mgrclose (mgr), NULL;
787 bits = latchmgr->alloc->bits;
788 } else if( mode == BT_ro )
789 return bt_mgrclose (mgr), NULL;
792 mgr->page_size = 1 << bits;
793 mgr->page_bits = bits;
795 mgr->poolmax = poolmax;
798 if( cacheblk < mgr->page_size )
799 cacheblk = mgr->page_size;
801 // mask for partial memmaps
803 mgr->poolmask = (cacheblk >> bits) - 1;
805 // see if requested size of pages per memmap is greater
807 if( (1 << segsize) > mgr->poolmask )
808 mgr->poolmask = (1 << segsize) - 1;
812 while( (1 << mgr->seg_bits) <= mgr->poolmask )
815 mgr->hashsize = hashsize;
818 mgr->pool = calloc (poolmax, sizeof(BtPool));
819 mgr->hash = calloc (hashsize, sizeof(ushort));
820 mgr->latch = calloc (hashsize, sizeof(BtSpinLatch));
821 mgr->pooladvise = calloc (poolmax, (mgr->poolmask + 8) / 8);
823 mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * sizeof(BtPool));
824 mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
825 mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtSpinLatch));
831 // initialize an empty b-tree with latch page, root page, page of leaves
832 // and page(s) of latches
834 memset (latchmgr, 0, 1 << bits);
835 nlatchpage = BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1;
836 bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
837 latchmgr->alloc->bits = mgr->page_bits;
839 latchmgr->nlatchpage = nlatchpage;
840 latchmgr->latchtotal = nlatchpage * (mgr->page_size / sizeof(BtLatchSet));
842 // initialize latch manager
844 latchhash = (mgr->page_size - sizeof(BtLatchMgr)) / sizeof(BtHashEntry);
846 // size of hash table = total number of latchsets
848 if( latchhash > latchmgr->latchtotal )
849 latchhash = latchmgr->latchtotal;
851 latchmgr->latchhash = latchhash;
854 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
855 return bt_mgrclose (mgr), NULL;
857 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
858 return bt_mgrclose (mgr), NULL;
860 if( *amt < mgr->page_size )
861 return bt_mgrclose (mgr), NULL;
864 memset (latchmgr, 0, 1 << bits);
865 latchmgr->alloc->bits = mgr->page_bits;
867 for( lvl=MIN_lvl; lvl--; ) {
868 slotptr(latchmgr->alloc, 1)->off = mgr->page_size - 3;
869 bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
870 key = keyptr(latchmgr->alloc, 1);
871 key->len = 2; // create stopper key
874 latchmgr->alloc->min = mgr->page_size - 3;
875 latchmgr->alloc->lvl = lvl;
876 latchmgr->alloc->cnt = 1;
877 latchmgr->alloc->act = 1;
879 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
880 return bt_mgrclose (mgr), NULL;
882 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
883 return bt_mgrclose (mgr), NULL;
885 if( *amt < mgr->page_size )
886 return bt_mgrclose (mgr), NULL;
890 // clear out latch manager locks
891 // and rest of pages to round out segment
893 memset(latchmgr, 0, mgr->page_size);
896 while( last <= ((MIN_lvl + 1 + nlatchpage) | mgr->poolmask) ) {
898 pwrite(mgr->idx, latchmgr, mgr->page_size, last << mgr->page_bits);
900 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
901 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
902 return bt_mgrclose (mgr), NULL;
903 if( *amt < mgr->page_size )
904 return bt_mgrclose (mgr), NULL;
911 flag = PROT_READ | ( mgr->mode == BT_ro ? 0 : PROT_WRITE );
912 mgr->latchmgr = mmap (0, mgr->page_size, flag, MAP_SHARED, mgr->idx, ALLOC_page * mgr->page_size);
913 if( mgr->latchmgr == MAP_FAILED )
914 return bt_mgrclose (mgr), NULL;
915 mgr->latchset = (BtLatchSet *)mmap (0, mgr->latchmgr->nlatchpage * mgr->page_size, flag, MAP_SHARED, mgr->idx, LATCH_page * mgr->page_size);
916 if( mgr->latchset == MAP_FAILED )
917 return bt_mgrclose (mgr), NULL;
919 flag = ( mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
920 mgr->halloc = CreateFileMapping(mgr->idx, NULL, flag, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size, NULL);
922 return bt_mgrclose (mgr), NULL;
924 flag = ( mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
925 mgr->latchmgr = MapViewOfFile(mgr->halloc, flag, 0, 0, (BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1 + LATCH_page) * mgr->page_size);
927 return GetLastError(), bt_mgrclose (mgr), NULL;
929 mgr->latchset = (void *)((char *)mgr->latchmgr + LATCH_page * mgr->page_size);
935 VirtualFree (latchmgr, 0, MEM_RELEASE);
940 // open BTree access method
941 // based on buffer manager
943 BtDb *bt_open (BtMgr *mgr)
945 BtDb *bt = malloc (sizeof(*bt));
947 memset (bt, 0, sizeof(*bt));
950 bt->mem = malloc (3 *mgr->page_size);
952 bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
954 bt->frame = (BtPage)bt->mem;
955 bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
956 bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
960 // compare two keys, returning > 0, = 0, or < 0
961 // as the comparison value
963 int keycmp (BtKey key1, unsigned char *key2, uint len2)
965 uint len1 = key1->len;
968 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
981 // find segment in pool
982 // must be called with hashslot idx locked
983 // return NULL if not there
984 // otherwise return node
986 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
991 // compute start of hash chain in pool
993 if( slot = bt->mgr->hash[idx] )
994 pool = bt->mgr->pool + slot;
998 page_no &= ~bt->mgr->poolmask;
1000 while( pool->basepage != page_no )
1001 if( pool = pool->hashnext )
1009 // add segment to hash table
1011 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
1016 pool->hashprev = pool->hashnext = NULL;
1017 pool->basepage = page_no & ~bt->mgr->poolmask;
1020 if( slot = bt->mgr->hash[idx] ) {
1021 node = bt->mgr->pool + slot;
1022 pool->hashnext = node;
1023 node->hashprev = pool;
1026 bt->mgr->hash[idx] = pool->slot;
1029 // find best segment to evict from buffer pool
1031 BtPool *bt_findlru (BtDb *bt, uint hashslot)
1033 unsigned long long int target = ~0LL;
1034 BtPool *pool = NULL, *node;
1039 node = bt->mgr->pool + hashslot;
1041 // scan pool entries under hash table slot
1046 if( node->lru > target )
1050 } while( node = node->hashnext );
1055 // map new buffer pool segment to virtual memory
1057 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
1059 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
1060 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
1064 flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
1065 pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED, bt->mgr->idx, off);
1066 if( pool->map == MAP_FAILED )
1067 return bt->err = BTERR_map;
1068 // clear out madvise issued bits
1069 memset (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8) / 8), 0, (bt->mgr->poolmask + 8)/8);
1071 flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
1072 pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
1074 return bt->err = BTERR_map;
1076 flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
1077 pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1079 return bt->err = BTERR_map;
1084 // find or place requested page in segment-pool
1085 // return pool table entry, incrementing pin
1087 BtPool *bt_pinpage(BtDb *bt, uid page_no)
1089 BtPool *pool, *node, *next;
1090 uint slot, idx, victim;
1093 // lock hash table chain
1095 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1096 bt_spinreadlock (&bt->mgr->latch[idx]);
1098 // look up in hash table
1100 if( pool = bt_findpool(bt, page_no, idx) ) {
1102 __sync_fetch_and_add(&pool->pin, 1);
1104 _InterlockedIncrement16 (&pool->pin);
1106 bt_spinreleaseread (&bt->mgr->latch[idx]);
1111 // upgrade to write lock
1113 bt_spinreleaseread (&bt->mgr->latch[idx]);
1114 bt_spinwritelock (&bt->mgr->latch[idx]);
1116 // try to find page in pool with write lock
1118 if( pool = bt_findpool(bt, page_no, idx) ) {
1120 __sync_fetch_and_add(&pool->pin, 1);
1122 _InterlockedIncrement16 (&pool->pin);
1124 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1129 // allocate a new pool node
1130 // and add to hash table
1133 slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
1135 slot = _InterlockedIncrement16 (&bt->mgr->poolcnt) - 1;
1138 if( ++slot < bt->mgr->poolmax ) {
1139 pool = bt->mgr->pool + slot;
1142 if( bt_mapsegment(bt, pool, page_no) )
1145 bt_linkhash(bt, pool, page_no, idx);
1147 __sync_fetch_and_add(&pool->pin, 1);
1149 _InterlockedIncrement16 (&pool->pin);
1151 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1155 // pool table is full
1156 // find best pool entry to evict
1159 __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
1161 _InterlockedDecrement16 (&bt->mgr->poolcnt);
1166 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
1168 victim = _InterlockedIncrement16 (&bt->mgr->evicted) - 1;
1170 victim %= bt->mgr->hashsize;
1172 // try to get write lock
1173 // skip entry if not obtained
1175 if( !bt_spinwritetry (&bt->mgr->latch[victim]) )
1178 // if cache entry is empty
1179 // or no slots are unpinned
1182 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
1183 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1187 // unlink victim pool node from hash table
1189 if( node = pool->hashprev )
1190 node->hashnext = pool->hashnext;
1191 else if( node = pool->hashnext )
1192 bt->mgr->hash[victim] = node->slot;
1194 bt->mgr->hash[victim] = 0;
1196 if( node = pool->hashnext )
1197 node->hashprev = pool->hashprev;
1199 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1201 // remove old file mapping
1203 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1205 FlushViewOfFile(pool->map, 0);
1206 UnmapViewOfFile(pool->map);
1207 CloseHandle(pool->hmap);
1211 // create new pool mapping
1212 // and link into hash table
1214 if( bt_mapsegment(bt, pool, page_no) )
1217 bt_linkhash(bt, pool, page_no, idx);
1219 __sync_fetch_and_add(&pool->pin, 1);
1221 _InterlockedIncrement16 (&pool->pin);
1223 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1228 // place write, read, or parent lock on requested page_no.
1229 // pin to buffer pool and return page pointer
1231 BTERR bt_lockpage(BtDb *bt, uid page_no, BtLock mode, BtPage *pageptr)
1238 // find/create maping in pool table
1239 // and pin our pool slot
1241 if( pool = bt_pinpage(bt, page_no) )
1242 subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1246 if( !(set = bt_bindlatch (bt, page_no, 1)) )
1249 page = (BtPage)(pool->map + (subpage << bt->mgr->page_bits));
1253 uint idx = subpage / 8;
1254 uint bit = subpage % 8;
1256 if( mode == BtLockRead || mode == BtLockWrite )
1257 if( ~((bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] >> bit) & 1 ) {
1258 madvise (page, bt->mgr->page_size, MADV_WILLNEED);
1259 (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8)/8))[idx] |= 1 << bit;
1266 bt_spinreadlock (set->readwr);
1269 bt_spinwritelock (set->readwr);
1272 bt_spinreadlock (set->access);
1275 bt_spinwritelock (set->access);
1278 bt_spinwritelock (set->parent);
1281 return bt->err = BTERR_lock;
1290 // remove write, read, or parent lock on requested page_no.
1292 BTERR bt_unlockpage(BtDb *bt, uid page_no, BtLock mode)
1298 // since page is pinned
1299 // it should still be in the buffer pool
1300 // and is in no danger of being a victim for reuse
1302 if( !(set = bt_bindlatch (bt, page_no, 0)) )
1303 return bt->err = BTERR_latch;
1305 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1306 bt_spinreadlock (&bt->mgr->latch[idx]);
1308 if( !(pool = bt_findpool(bt, page_no, idx)) )
1309 return bt->err = BTERR_hash;
1311 bt_spinreleaseread (&bt->mgr->latch[idx]);
1315 bt_spinreleaseread (set->readwr);
1318 bt_spinreleasewrite (set->readwr);
1321 bt_spinreleaseread (set->access);
1324 bt_spinreleasewrite (set->access);
1327 bt_spinreleasewrite (set->parent);
1330 return bt->err = BTERR_lock;
1334 __sync_fetch_and_add(&pool->pin, -1);
1335 __sync_fetch_and_add (&set->pin, -1);
1337 _InterlockedDecrement16 (&pool->pin);
1338 _InterlockedDecrement16 (&set->pin);
1343 // deallocate a deleted page
1344 // place on free chain out of allocator page
1345 // fence key must already be removed from parent
1347 BTERR bt_freepage(BtDb *bt, uid page_no)
1349 // obtain delete lock on deleted page
1351 if( bt_lockpage(bt, page_no, BtLockDelete, NULL) )
1354 // obtain write lock on deleted page
1356 if( bt_lockpage(bt, page_no, BtLockWrite, &bt->temp) )
1359 // lock allocation page
1361 bt_spinwritelock(bt->mgr->latchmgr->lock);
1363 // store free chain in allocation page second right
1364 bt_putid(bt->temp->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
1365 bt_putid(bt->mgr->latchmgr->alloc[1].right, page_no);
1369 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1371 // remove write lock on deleted node
1373 if( bt_unlockpage(bt, page_no, BtLockWrite) )
1376 // remove delete lock on deleted node
1378 if( bt_unlockpage(bt, page_no, BtLockDelete) )
1384 // allocate a new page and write page into it
1386 uid bt_newpage(BtDb *bt, BtPage page)
1392 // lock allocation page
1394 bt_spinwritelock(bt->mgr->latchmgr->lock);
1396 // use empty chain first
1397 // else allocate empty page
1399 if( new_page = bt_getid(bt->mgr->latchmgr->alloc[1].right) ) {
1400 if( bt_lockpage (bt, new_page, BtLockWrite, &bt->temp) )
1402 bt_putid(bt->mgr->latchmgr->alloc[1].right, bt_getid(bt->temp->right));
1403 if( bt_unlockpage (bt, new_page, BtLockWrite) )
1407 new_page = bt_getid(bt->mgr->latchmgr->alloc->right);
1408 bt_putid(bt->mgr->latchmgr->alloc->right, new_page+1);
1412 if ( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1413 return bt->err = BTERR_wrt, 0;
1415 // if writing first page of pool block, zero last page in the block
1417 if ( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1419 // use zero buffer to write zeros
1420 memset(bt->zero, 0, bt->mgr->page_size);
1421 if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1422 return bt->err = BTERR_wrt, 0;
1425 // bring new page into pool and copy page.
1426 // this will extend the file into the new pages.
1428 if( bt_lockpage(bt, new_page, BtLockWrite, &pmap) )
1431 memcpy(pmap, page, bt->mgr->page_size);
1433 if( bt_unlockpage (bt, new_page, BtLockWrite) )
1436 // unlock allocation latch and return new page no
1438 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1442 // find slot in page for given key at a given level
1444 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1446 uint diff, higher = bt->page->cnt, low = 1, slot;
1448 // low is the lowest candidate, higher is already
1449 // tested as .ge. the given key, loop ends when they meet
1451 while( diff = higher - low ) {
1452 slot = low + ( diff >> 1 );
1453 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1462 // find and load page at given level for given key
1463 // leave page rd or wr locked as requested
1465 int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, uint lock)
1467 uid page_no = ROOT_page, prevpage = 0;
1468 uint drill = 0xff, slot;
1469 uint mode, prevmode;
1471 // start at root of btree and drill down
1474 // determine lock mode of drill level
1475 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1477 bt->page_no = page_no;
1479 // obtain access lock using lock chaining with Access mode
1481 if( page_no > ROOT_page )
1482 if( bt_lockpage(bt, page_no, BtLockAccess, NULL) )
1485 // now unlock our (possibly foster) parent
1488 if( bt_unlockpage(bt, prevpage, prevmode) )
1493 // obtain read lock using lock chaining
1494 // and pin page contents
1496 if( bt_lockpage(bt, page_no, mode, &bt->page) )
1499 if( page_no > ROOT_page )
1500 if( bt_unlockpage(bt, page_no, BtLockAccess) )
1503 // re-read and re-lock root after determining actual level of root
1505 if( bt->page_no == ROOT_page )
1506 if( bt->page->lvl != drill) {
1507 drill = bt->page->lvl;
1509 if( lock == BtLockWrite && drill == lvl )
1510 if( bt_unlockpage(bt, page_no, mode) )
1516 prevpage = bt->page_no;
1519 // if page is being deleted,
1520 // move back to preceeding page
1522 if( bt->page->kill ) {
1523 page_no = bt_getid (bt->page->right);
1527 // find key on page at this level
1528 // and descend to requested level
1530 slot = bt_findslot (bt, key, len);
1532 // is this slot a foster child?
1534 if( slot <= bt->page->cnt - bt->page->foster )
1538 while( slotptr(bt->page, slot)->dead )
1539 if( slot++ < bt->page->cnt )
1544 if( slot <= bt->page->cnt - bt->page->foster )
1547 // continue down / right using overlapping locks
1548 // to protect pages being killed or split.
1550 page_no = bt_getid(slotptr(bt->page, slot)->id);
1554 page_no = bt_getid(bt->page->right);
1558 // return error on end of chain
1560 bt->err = BTERR_struct;
1561 return 0; // return error
1564 // find and delete key on page by marking delete flag bit
1565 // when page becomes empty, delete it from the btree
1567 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl)
1569 unsigned char leftkey[256], rightkey[256];
1574 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1575 ptr = keyptr(bt->page, slot);
1579 // if key is found delete it, otherwise ignore request
1581 if( !keycmp (ptr, key, len) )
1582 if( slotptr(bt->page, slot)->dead == 0 ) {
1583 slotptr(bt->page,slot)->dead = 1;
1584 if( slot < bt->page->cnt )
1585 bt->page->dirty = 1;
1589 // return if page is not empty, or it has no right sibling
1591 right = bt_getid(bt->page->right);
1592 page_no = bt->page_no;
1594 if( !right || bt->page->act )
1595 return bt_unlockpage(bt, page_no, BtLockWrite);
1597 // obtain Parent lock over write lock
1599 if( bt_lockpage(bt, page_no, BtLockParent, NULL) )
1602 // cache copy of key to delete
1604 ptr = keyptr(bt->page, bt->page->cnt);
1605 memcpy(leftkey, ptr, ptr->len + 1);
1607 // lock and map right page
1609 if( bt_lockpage(bt, right, BtLockWrite, &bt->temp) )
1612 // pull contents of next page into current empty page
1613 memcpy (bt->page, bt->temp, bt->mgr->page_size);
1615 // cache copy of key to update
1616 ptr = keyptr(bt->temp, bt->temp->cnt);
1617 memcpy(rightkey, ptr, ptr->len + 1);
1619 // Mark right page as deleted and point it to left page
1620 // until we can post updates at higher level.
1622 bt_putid(bt->temp->right, page_no);
1626 if( bt_unlockpage(bt, right, BtLockWrite) )
1628 if( bt_unlockpage(bt, page_no, BtLockWrite) )
1631 // delete old lower key to consolidated node
1633 if( bt_deletekey (bt, leftkey + 1, *leftkey, lvl + 1) )
1636 // redirect higher key directly to consolidated node
1638 if( slot = bt_loadpage (bt, rightkey+1, *rightkey, lvl+1, BtLockWrite) )
1639 ptr = keyptr(bt->page, slot);
1643 // since key already exists, update id
1645 if( keycmp (ptr, rightkey+1, *rightkey) )
1646 return bt->err = BTERR_struct;
1648 slotptr(bt->page, slot)->dead = 0;
1649 bt_putid(slotptr(bt->page,slot)->id, page_no);
1651 if( bt_unlockpage(bt, bt->page_no, BtLockWrite) )
1654 // obtain write lock and
1655 // add right block to free chain
1657 if( bt_freepage (bt, right) )
1660 // remove ParentModify lock
1662 if( bt_unlockpage(bt, page_no, BtLockParent) )
1668 // find key in leaf level and return row-id
1670 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1676 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1677 ptr = keyptr(bt->page, slot);
1681 // if key exists, return row-id
1682 // otherwise return 0
1684 if( ptr->len == len && !memcmp (ptr->key, key, len) )
1685 id = bt_getid(slotptr(bt->page,slot)->id);
1689 if( bt_unlockpage (bt, bt->page_no, BtLockRead) )
1695 // check page for space available,
1696 // clean if necessary and return
1697 // 0 - page needs splitting
1700 uint bt_cleanpage(BtDb *bt, uint amt)
1702 uint nxt = bt->mgr->page_size;
1703 BtPage page = bt->page;
1704 uint cnt = 0, idx = 0;
1705 uint max = page->cnt;
1708 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1711 // skip cleanup if nothing to reclaim
1716 memcpy (bt->frame, page, bt->mgr->page_size);
1718 // skip page info and set rest of page to zero
1720 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1724 // try cleaning up page first
1726 while( cnt++ < max ) {
1727 // always leave fence key and foster children in list
1728 if( cnt < max - page->foster && slotptr(bt->frame,cnt)->dead )
1732 key = keyptr(bt->frame, cnt);
1733 nxt -= key->len + 1;
1734 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1737 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1738 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1740 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1741 slotptr(page, idx)->off = nxt;
1747 // see if page has enough space now, or does it need splitting?
1749 if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1755 // add key to current page
1756 // page must already be writelocked
1758 void bt_addkeytopage (BtDb *bt, uint slot, unsigned char *key, uint len, uid id, uint tod)
1760 BtPage page = bt->page;
1763 // calculate next available slot and copy key into page
1765 page->min -= len + 1;
1766 ((unsigned char *)page)[page->min] = len;
1767 memcpy ((unsigned char *)page + page->min +1, key, len );
1769 for( idx = slot; idx < page->cnt; idx++ )
1770 if( slotptr(page, idx)->dead )
1773 // now insert key into array before slot
1774 // preserving the fence slot
1776 if( idx == page->cnt )
1782 *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
1784 bt_putid(slotptr(page,slot)->id, id);
1785 slotptr(page, slot)->off = page->min;
1786 slotptr(page, slot)->tod = tod;
1787 slotptr(page, slot)->dead = 0;
1790 // split the root and raise the height of the btree
1791 // call with current page locked and page no of foster child
1792 // return with current page (root) unlocked
1794 BTERR bt_splitroot(BtDb *bt, uid right)
1796 uint nxt = bt->mgr->page_size;
1797 unsigned char fencekey[256];
1798 BtPage root = bt->page;
1802 // Obtain an empty page to use, and copy the left page
1803 // contents into it from the root. Strip foster child key.
1804 // (it's the stopper key)
1810 // Save left fence key.
1812 key = keyptr(root, root->cnt);
1813 memcpy (fencekey, key, key->len + 1);
1815 // copy the lower keys into a new left page
1817 if( !(new_page = bt_newpage(bt, root)) )
1820 // preserve the page info at the bottom
1821 // and set rest of the root to zero
1823 memset (root+1, 0, bt->mgr->page_size - sizeof(*root));
1825 // insert left fence key on empty newroot page
1827 nxt -= *fencekey + 1;
1828 memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
1829 bt_putid(slotptr(root, 1)->id, new_page);
1830 slotptr(root, 1)->off = nxt;
1832 // insert stopper key on newroot page
1833 // and increase the root height
1839 memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
1840 bt_putid(slotptr(root, 2)->id, right);
1841 slotptr(root, 2)->off = nxt;
1843 bt_putid(root->right, 0);
1844 root->min = nxt; // reset lowest used offset and key count
1849 // release root (bt->page)
1851 return bt_unlockpage(bt, ROOT_page, BtLockWrite);
1854 // split already locked full node
1855 // in current page variables
1858 BTERR bt_splitpage (BtDb *bt)
1860 uint slot, cnt, idx, max, nxt = bt->mgr->page_size;
1861 unsigned char fencekey[256];
1862 uid page_no = bt->page_no;
1863 BtPage page = bt->page;
1864 uint tod = time(NULL);
1865 uint lvl = page->lvl;
1866 uid new_page, right;
1869 // initialize frame buffer
1871 memset (bt->frame, 0, bt->mgr->page_size);
1872 max = page->cnt - page->foster;
1873 tod = (uint)time(NULL);
1877 // split higher half of keys to bt->frame
1878 // leaving foster children in the left node.
1880 while( cnt++ < max ) {
1881 key = keyptr(page, cnt);
1882 nxt -= key->len + 1;
1883 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
1884 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
1885 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
1886 slotptr(bt->frame, idx)->off = nxt;
1890 // transfer right link node
1892 if( page_no > ROOT_page ) {
1893 right = bt_getid (page->right);
1894 bt_putid(bt->frame->right, right);
1897 bt->frame->bits = bt->mgr->page_bits;
1898 bt->frame->min = nxt;
1899 bt->frame->cnt = idx;
1900 bt->frame->lvl = lvl;
1902 // get new free page and write frame to it.
1904 if( !(new_page = bt_newpage(bt, bt->frame)) )
1907 // remember fence key for new page to add
1910 key = keyptr(bt->frame, idx);
1911 memcpy (fencekey, key, key->len + 1);
1913 // update lower keys and foster children to continue in old page
1915 memcpy (bt->frame, page, bt->mgr->page_size);
1916 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1917 nxt = bt->mgr->page_size;
1922 // assemble page of smaller keys
1923 // to remain in the old page
1925 while( cnt++ < max / 2 ) {
1926 key = keyptr(bt->frame, cnt);
1927 nxt -= key->len + 1;
1928 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1929 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1930 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1931 slotptr(page, idx)->off = nxt;
1935 // insert new foster child at beginning of the current foster children
1937 nxt -= *fencekey + 1;
1938 memcpy ((unsigned char *)page + nxt, fencekey, *fencekey + 1);
1939 bt_putid (slotptr(page,++idx)->id, new_page);
1940 slotptr(page, idx)->tod = tod;
1941 slotptr(page, idx)->off = nxt;
1945 // continue with old foster child keys if any
1947 cnt = bt->frame->cnt - bt->frame->foster;
1949 while( cnt++ < bt->frame->cnt ) {
1950 key = keyptr(bt->frame, cnt);
1951 nxt -= key->len + 1;
1952 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1953 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1954 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1955 slotptr(page, idx)->off = nxt;
1962 // link new right page
1964 bt_putid (page->right, new_page);
1966 // if current page is the root page, split it
1968 if( page_no == ROOT_page )
1969 return bt_splitroot (bt, new_page);
1971 // release wr lock on our page
1973 if( bt_unlockpage (bt, page_no, BtLockWrite) )
1976 // obtain ParentModification lock for current page
1977 // to fix fence key and highest foster child on page
1979 if( bt_lockpage (bt, page_no, BtLockParent, NULL) )
1982 // get our highest foster child key to find in parent node
1984 if( bt_lockpage (bt, page_no, BtLockRead, &page) )
1987 key = keyptr(page, page->cnt);
1988 memcpy (fencekey, key, key->len+1);
1990 if( bt_unlockpage (bt, page_no, BtLockRead) )
1993 // update our parent
1997 slot = bt_loadpage (bt, fencekey + 1, *fencekey, lvl + 1, BtLockWrite);
2002 // check if parent page has enough space for any possible key
2004 if( bt_cleanpage (bt, 256) )
2007 if( bt_splitpage (bt) )
2011 // see if we are still a foster child from another node
2013 if( bt_getid (slotptr(bt->page, slot)->id) != page_no ) {
2014 if( bt_unlockpage (bt, bt->page_no, BtLockWrite) )
2024 // wait until readers from parent get their locks
2027 if( bt_lockpage (bt, page_no, BtLockDelete, NULL) )
2030 // lock our page for writing
2032 if( bt_lockpage (bt, page_no, BtLockWrite, &page) )
2035 // switch parent fence key to foster child
2037 if( slotptr(page, page->cnt)->dead )
2038 slotptr(bt->page, slot)->dead = 1;
2040 bt_putid (slotptr(bt->page, slot)->id, bt_getid(slotptr(page, page->cnt)->id));
2042 // remove highest foster child from our page
2048 key = keyptr(page, page->cnt);
2050 // add our new fence key for foster child to our parent
2052 bt_addkeytopage (bt, slot, key->key, key->len, page_no, tod);
2054 if( bt_unlockpage (bt, bt->page_no, BtLockWrite) )
2057 if( bt_unlockpage (bt, page_no, BtLockDelete) )
2060 if( bt_unlockpage (bt, page_no, BtLockWrite) )
2063 return bt_unlockpage (bt, page_no, BtLockParent);
2066 // Insert new key into the btree at leaf level.
2068 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod)
2075 if( slot = bt_loadpage (bt, key, len, 0, BtLockWrite) )
2076 ptr = keyptr(bt->page, slot);
2080 bt->err = BTERR_ovflw;
2084 // if key already exists, update id and return
2088 if( !keycmp (ptr, key, len) ) {
2089 slotptr(page, slot)->dead = 0;
2090 slotptr(page, slot)->tod = tod;
2091 bt_putid(slotptr(page,slot)->id, id);
2092 return bt_unlockpage(bt, bt->page_no, BtLockWrite);
2095 // check if page has enough space
2097 if( bt_cleanpage (bt, len) )
2100 if( bt_splitpage (bt) )
2104 bt_addkeytopage (bt, slot, key, len, id, tod);
2106 return bt_unlockpage (bt, bt->page_no, BtLockWrite);
2109 // cache page of keys into cursor and return starting slot for given key
2111 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2115 // cache page for retrieval
2116 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
2117 memcpy (bt->cursor, bt->page, bt->mgr->page_size);
2118 bt->cursor_page = bt->page_no;
2119 if ( bt_unlockpage(bt, bt->page_no, BtLockRead) )
2125 // return next slot for cursor page
2126 // or slide cursor right into next page
2128 uint bt_nextkey (BtDb *bt, uint slot)
2134 right = bt_getid(bt->cursor->right);
2135 while( slot++ < bt->cursor->cnt - bt->cursor->foster )
2136 if( slotptr(bt->cursor,slot)->dead )
2138 else if( right || (slot < bt->cursor->cnt - bt->cursor->foster) )
2146 bt->cursor_page = right;
2148 if( bt_lockpage(bt, right, BtLockRead, &page) )
2151 memcpy (bt->cursor, page, bt->mgr->page_size);
2153 if ( bt_unlockpage(bt, right, BtLockRead) )
2162 BtKey bt_key(BtDb *bt, uint slot)
2164 return keyptr(bt->cursor, slot);
2167 uid bt_uid(BtDb *bt, uint slot)
2169 return bt_getid(slotptr(bt->cursor,slot)->id);
2172 uint bt_tod(BtDb *bt, uint slot)
2174 return slotptr(bt->cursor,slot)->tod;
2187 // standalone program to index file of keys
2188 // then list them onto std-out
2191 void *index_file (void *arg)
2193 uint __stdcall index_file (void *arg)
2196 int line = 0, found = 0, cnt = 0;
2197 uid next, page_no = LEAF_page; // start on first page of leaves
2198 unsigned char key[256];
2199 ThreadArg *args = arg;
2200 int ch, len = 0, slot;
2207 bt = bt_open (args->mgr);
2210 switch(args->type | 0x20)
2213 fprintf(stderr, "started indexing for %s\n", args->infile);
2214 if( in = fopen (args->infile, "rb") )
2215 while( ch = getc(in), ch != EOF )
2220 if( args->num == 1 )
2221 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2223 else if( args->num )
2224 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2226 if( bt_insertkey (bt, key, len, line, *tod) )
2227 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2230 else if( len < 255 )
2232 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
2236 fprintf(stderr, "started deleting keys for %s\n", args->infile);
2237 if( in = fopen (args->infile, "rb") )
2238 while( ch = getc(in), ch != EOF )
2242 if( args->num == 1 )
2243 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2245 else if( args->num )
2246 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2248 if( bt_deletekey (bt, key, len, 0) )
2249 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2252 else if( len < 255 )
2254 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2258 fprintf(stderr, "started finding keys for %s\n", args->infile);
2259 if( in = fopen (args->infile, "rb") )
2260 while( ch = getc(in), ch != EOF )
2264 if( args->num == 1 )
2265 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2267 else if( args->num )
2268 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2270 if( bt_findkey (bt, key, len) )
2273 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2276 else if( len < 255 )
2278 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2284 fprintf(stderr, "started reading\n");
2286 if( slot = bt_startkey (bt, key, len) )
2289 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
2291 while( slot = bt_nextkey (bt, slot) ) {
2292 ptr = bt_key(bt, slot);
2293 fwrite (ptr->key, ptr->len, 1, stdout);
2294 fputc ('\n', stdout);
2300 fprintf(stderr, "started reading\n");
2303 bt_lockpage (bt, page_no, BtLockRead, &page);
2305 next = bt_getid (page->right);
2306 bt_unlockpage (bt, page_no, BtLockRead);
2307 } while( page_no = next );
2309 cnt--; // remove stopper key
2310 fprintf(stderr, " Total keys read %d\n", cnt);
2322 typedef struct timeval timer;
2324 int main (int argc, char **argv)
2326 int idx, cnt, len, slot, err;
2327 int segsize, bits = 16;
2332 time_t start[1], stop[1];
2345 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]);
2346 fprintf (stderr, " where page_bits is the page size in bits\n");
2347 fprintf (stderr, " mapped_segments is the number of mmap segments in buffer pool\n");
2348 fprintf (stderr, " seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2349 fprintf (stderr, " line_numbers = 1 to append line numbers to keys\n");
2350 fprintf (stderr, " src_file1 thru src_filen are files of keys separated by newline\n");
2355 gettimeofday(&start, NULL);
2361 bits = atoi(argv[3]);
2364 poolsize = atoi(argv[4]);
2367 fprintf (stderr, "Warning: no mapped_pool\n");
2369 if( poolsize > 65535 )
2370 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2373 segsize = atoi(argv[5]);
2375 segsize = 4; // 16 pages per mmap segment
2378 num = atoi(argv[6]);
2382 threads = malloc (cnt * sizeof(pthread_t));
2384 threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2386 args = malloc (cnt * sizeof(ThreadArg));
2388 mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2391 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2397 for( idx = 0; idx < cnt; idx++ ) {
2398 args[idx].infile = argv[idx + 7];
2399 args[idx].type = argv[2][0];
2400 args[idx].mgr = mgr;
2401 args[idx].num = num;
2402 args[idx].idx = idx;
2404 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2405 fprintf(stderr, "Error creating thread %d\n", err);
2407 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2411 // wait for termination
2414 for( idx = 0; idx < cnt; idx++ )
2415 pthread_join (threads[idx], NULL);
2416 gettimeofday(&stop, NULL);
2417 real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2419 WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2421 for( idx = 0; idx < cnt; idx++ )
2422 CloseHandle(threads[idx]);
2425 real_time = 1000 * (*stop - *start);
2427 fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);