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, hlatch; // allocation and latch table handles
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 do prev = __sync_fetch_and_or((ushort *)latch, Mutex);
356 while( prev & Mutex );
358 do prev = _InterlockedOr16((ushort *)latch, Mutex);
359 while( prev & Mutex );
362 // see if exclusive request is pending, or granted
364 if( prev = !(latch->exclusive | latch->pending) )
372 } while( sched_yield(), 1 );
374 } while( SwitchToThread(), 1 );
378 // wait for other read and write latches to relinquish
380 void bt_spinwritelock(BtSpinLatch *latch)
386 do prev = __sync_fetch_and_or((ushort *)latch, (Pending | Mutex));
387 while( prev & Mutex );
389 do prev = _InterlockedOr16((ushort *)latch, (Pending | Mutex));
390 while( prev & Mutex );
392 if( prev = !(latch->share | latch->exclusive) )
393 latch->exclusive = 1, latch->pending = 0;
407 // try to obtain write lock
409 // return 1 if obtained,
412 int bt_spinwritetry(BtSpinLatch *latch)
417 do prev = __sync_fetch_and_or((ushort *)latch, Mutex);
418 while( prev & Mutex );
420 do prev = _InterlockedOr16((ushort *)latch, Mutex);
421 while( prev & Mutex );
423 // take write access if all bits are clear
426 latch->exclusive = 1;
434 void bt_spinreleasewrite(BtSpinLatch *latch)
439 do prev = __sync_fetch_and_or((ushort *)latch, Mutex);
440 while( prev & Mutex );
442 do prev = _InterlockedOr16((ushort *)latch, Mutex);
443 while( prev & Mutex );
446 latch->exclusive = 0;
450 // decrement reader count
452 void bt_spinreleaseread(BtSpinLatch *latch)
457 do prev = __sync_fetch_and_or((ushort *)latch, Mutex);
458 while( prev & Mutex );
460 do prev = _InterlockedOr16((ushort *)latch, Mutex);
461 while( prev & Mutex );
468 // link latch table entry into latch hash table
470 void bt_latchlink (BtDb *bt, ushort hashidx, ushort victim, uid page_no)
472 BtLatchSet *set = bt->mgr->latchset + victim;
474 if( set->next = bt->mgr->latchmgr->table[hashidx].slot )
475 bt->mgr->latchset[set->next].prev = victim;
477 bt->mgr->latchmgr->table[hashidx].slot = victim;
478 set->page_no = page_no;
483 // find existing latchset or inspire new one
484 // return with latchset pinned
486 BtLatchSet *bt_bindlatch (BtDb *bt, uid page_no, int incr)
488 ushort hashidx = page_no % bt->mgr->latchmgr->latchhash;
489 ushort slot, avail = 0, victim, idx;
492 // obtain read lock on hash table entry
494 bt_spinreadlock(bt->mgr->latchmgr->table[hashidx].latch);
496 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
498 set = bt->mgr->latchset + slot;
499 if( page_no == set->page_no )
501 } while( slot = set->next );
505 __sync_fetch_and_add(&set->pin, 1);
507 _InterlockedIncrement16 (&set->pin);
511 bt_spinreleaseread (bt->mgr->latchmgr->table[hashidx].latch);
516 // try again, this time with write lock
518 bt_spinwritelock(bt->mgr->latchmgr->table[hashidx].latch);
520 if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
522 set = bt->mgr->latchset + slot;
523 if( page_no == set->page_no )
525 if( !set->pin && !avail )
527 } while( slot = set->next );
529 // found our entry, or take over an unpinned one
531 if( slot || (slot = avail) ) {
532 set = bt->mgr->latchset + slot;
535 __sync_fetch_and_add(&set->pin, 1);
537 _InterlockedIncrement16 (&set->pin);
540 set->page_no = page_no;
541 bt_spinreleasewrite(bt->mgr->latchmgr->table[hashidx].latch);
545 // see if there are any unused entries
547 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, 1) + 1;
549 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchdeployed);
552 if( victim < bt->mgr->latchmgr->latchtotal ) {
553 set = bt->mgr->latchset + victim;
555 __sync_fetch_and_add(&set->pin, 1);
557 _InterlockedIncrement16 (&set->pin);
559 bt_latchlink (bt, hashidx, victim, page_no);
560 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
565 victim = __sync_fetch_and_add (&bt->mgr->latchmgr->latchdeployed, -1);
567 victim = _InterlockedDecrement16 (&bt->mgr->latchmgr->latchdeployed);
569 // find and reuse previous lock entry
573 victim = __sync_fetch_and_add(&bt->mgr->latchmgr->latchvictim, 1);
575 victim = _InterlockedIncrement16 (&bt->mgr->latchmgr->latchvictim) - 1;
577 // we don't use slot zero
579 if( victim %= bt->mgr->latchmgr->latchtotal )
580 set = bt->mgr->latchset + victim;
584 // take control of our slot
585 // from other threads
587 if( set->pin || !bt_spinwritetry (set->busy) )
592 // try to get write lock on hash chain
593 // skip entry if not obtained
594 // or has outstanding locks
596 if( !bt_spinwritetry (bt->mgr->latchmgr->table[idx].latch) ) {
597 bt_spinreleasewrite (set->busy);
602 bt_spinreleasewrite (set->busy);
603 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
607 // unlink our available victim from its hash chain
610 bt->mgr->latchset[set->prev].next = set->next;
612 bt->mgr->latchmgr->table[idx].slot = set->next;
615 bt->mgr->latchset[set->next].prev = set->prev;
617 bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
622 bt_latchlink (bt, hashidx, victim, page_no);
623 bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
624 bt_spinreleasewrite (set->busy);
629 void bt_mgrclose (BtMgr *mgr)
634 // release mapped pages
635 // note that slot zero is never used
637 for( slot = 1; slot < mgr->poolmax; slot++ ) {
638 pool = mgr->pool + slot;
641 munmap (pool->map, (mgr->poolmask+1) << mgr->page_bits);
644 FlushViewOfFile(pool->map, 0);
645 UnmapViewOfFile(pool->map);
646 CloseHandle(pool->hmap);
656 free (mgr->pooladvise);
659 FlushFileBuffers(mgr->idx);
660 CloseHandle(mgr->idx);
661 GlobalFree (mgr->pool);
662 GlobalFree (mgr->hash);
663 GlobalFree (mgr->latch);
668 // close and release memory
670 void bt_close (BtDb *bt)
677 VirtualFree (bt->mem, 0, MEM_RELEASE);
682 // open/create new btree buffer manager
684 // call with file_name, BT_openmode, bits in page size (e.g. 16),
685 // size of mapped page pool (e.g. 8192)
687 BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolmax, uint segsize, uint hashsize)
689 uint lvl, attr, cacheblk, last, slot, idx;
690 uint nlatchpage, latchhash;
691 BtLatchMgr *latchmgr;
700 SYSTEM_INFO sysinfo[1];
703 // determine sanity of page size and buffer pool
705 if( bits > BT_maxbits )
707 else if( bits < BT_minbits )
711 return NULL; // must have buffer pool
714 mgr = calloc (1, sizeof(BtMgr));
716 switch (mode & 0x7fff)
719 mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
725 mgr->idx = open ((char*)name, O_RDONLY);
730 return free(mgr), NULL;
732 cacheblk = 4096; // minimum mmap segment size for unix
735 mgr = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, sizeof(BtMgr));
736 attr = FILE_ATTRIBUTE_NORMAL;
737 switch (mode & 0x7fff)
740 mgr->idx = CreateFile(name, GENERIC_READ| GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, attr, NULL);
746 mgr->idx = CreateFile(name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, attr, NULL);
750 if( mgr->idx == INVALID_HANDLE_VALUE )
751 return GlobalFree(mgr), NULL;
753 // normalize cacheblk to multiple of sysinfo->dwAllocationGranularity
754 GetSystemInfo(sysinfo);
755 cacheblk = sysinfo->dwAllocationGranularity;
759 latchmgr = malloc (BT_maxpage);
762 // read minimum page size to get root info
764 if( size = lseek (mgr->idx, 0L, 2) ) {
765 if( pread(mgr->idx, latchmgr, BT_minpage, 0) == BT_minpage )
766 bits = latchmgr->alloc->bits;
768 return free(mgr), free(latchmgr), NULL;
769 } else if( mode == BT_ro )
770 return bt_mgrclose (mgr), NULL;
772 latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
773 size = GetFileSize(mgr->idx, amt);
776 if( !ReadFile(mgr->idx, (char *)latchmgr, BT_minpage, amt, NULL) )
777 return bt_mgrclose (mgr), NULL;
778 bits = latchmgr->alloc->bits;
779 } else if( mode == BT_ro )
780 return bt_mgrclose (mgr), NULL;
783 mgr->page_size = 1 << bits;
784 mgr->page_bits = bits;
786 mgr->poolmax = poolmax;
789 if( cacheblk < mgr->page_size )
790 cacheblk = mgr->page_size;
792 // mask for partial memmaps
794 mgr->poolmask = (cacheblk >> bits) - 1;
796 // see if requested size of pages per memmap is greater
798 if( (1 << segsize) > mgr->poolmask )
799 mgr->poolmask = (1 << segsize) - 1;
803 while( (1 << mgr->seg_bits) <= mgr->poolmask )
806 mgr->hashsize = hashsize;
809 mgr->pool = calloc (poolmax, sizeof(BtPool));
810 mgr->hash = calloc (hashsize, sizeof(ushort));
811 mgr->latch = calloc (hashsize, sizeof(BtSpinLatch));
812 mgr->pooladvise = calloc (poolmax, (mgr->poolmask + 8) / 8);
814 mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * sizeof(BtPool));
815 mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
816 mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtSpinLatch));
822 // initialize an empty b-tree with latch page, root page, page of leaves
823 // and page(s) of latches
825 memset (latchmgr, 0, 1 << bits);
826 nlatchpage = BT_latchtable / (mgr->page_size / sizeof(BtLatchSet)) + 1;
827 bt_putid(latchmgr->alloc->right, MIN_lvl+1+nlatchpage);
828 latchmgr->alloc->bits = mgr->page_bits;
830 latchmgr->nlatchpage = nlatchpage;
831 latchmgr->latchtotal = nlatchpage * (mgr->page_size / sizeof(BtLatchSet));
833 // initialize latch manager
835 latchhash = (mgr->page_size - sizeof(BtLatchMgr)) / sizeof(BtHashEntry);
837 // size of hash table = total number of latchsets
839 if( latchhash > latchmgr->latchtotal )
840 latchhash = latchmgr->latchtotal;
842 latchmgr->latchhash = latchhash;
845 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
846 return bt_mgrclose (mgr), NULL;
848 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
849 return bt_mgrclose (mgr), NULL;
851 if( *amt < mgr->page_size )
852 return bt_mgrclose (mgr), NULL;
855 memset (latchmgr, 0, 1 << bits);
856 latchmgr->alloc->bits = mgr->page_bits;
858 for( lvl=MIN_lvl; lvl--; ) {
859 slotptr(latchmgr->alloc, 1)->off = mgr->page_size - 3;
860 bt_putid(slotptr(latchmgr->alloc, 1)->id, lvl ? MIN_lvl - lvl + 1 : 0); // next(lower) page number
861 key = keyptr(latchmgr->alloc, 1);
862 key->len = 2; // create stopper key
865 latchmgr->alloc->min = mgr->page_size - 3;
866 latchmgr->alloc->lvl = lvl;
867 latchmgr->alloc->cnt = 1;
868 latchmgr->alloc->act = 1;
870 if( write (mgr->idx, latchmgr, mgr->page_size) < mgr->page_size )
871 return bt_mgrclose (mgr), NULL;
873 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
874 return bt_mgrclose (mgr), NULL;
876 if( *amt < mgr->page_size )
877 return bt_mgrclose (mgr), NULL;
881 // clear out latch manager locks
882 // and rest of pages to round out segment
884 memset(latchmgr, 0, mgr->page_size);
887 while( last <= ((MIN_lvl + 1 + nlatchpage) | mgr->poolmask) ) {
889 pwrite(mgr->idx, latchmgr, mgr->page_size, last << mgr->page_bits);
891 SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
892 if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
893 return bt_mgrclose (mgr), NULL;
894 if( *amt < mgr->page_size )
895 return bt_mgrclose (mgr), NULL;
902 flag = PROT_READ | ( mgr->mode == BT_ro ? 0 : PROT_WRITE );
903 mgr->latchmgr = mmap (0, mgr->page_size, flag, MAP_SHARED, mgr->idx, ALLOC_page * mgr->page_size);
904 if( mgr->latchmgr == MAP_FAILED )
905 return bt_mgrclose (mgr), NULL;
906 mgr->latchset = (BtLatchSet *)mmap (0, mgr->latchmgr->nlatchpage * mgr->page_size, flag, MAP_SHARED, mgr->idx, LATCH_page * mgr->page_size);
907 if( mgr->latchset == MAP_FAILED )
908 return bt_mgrclose (mgr), NULL;
910 flag = ( mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
911 mgr->halloc = CreateFileMapping(mgr->idx, NULL, flag, 0, mgr->page_size, NULL);
913 return bt_mgrclose (mgr), NULL;
915 flag = ( mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
916 mgr->latchmgr = MapViewOfFile(mgr->halloc, flag, 0, ALLOC_page * mgr->page_size, mgr->page_size);
918 return bt_mgrclose (mgr), NULL;
919 flag = ( mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
920 mgr->hlatch = CreateFileMapping(mgr->idx, NULL, flag, 0, (mgr->latchmgr->nlatchpage + 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->latchset = MapViewOfFile(mgr->halloc, flag, 0, LATCH_page * mgr->page_size, mgr->page_size * mgr->latchmgr->nlatchpage);
927 return bt_mgrclose (mgr), NULL;
933 VirtualFree (latchmgr, 0, MEM_RELEASE);
938 // open BTree access method
939 // based on buffer manager
941 BtDb *bt_open (BtMgr *mgr)
943 BtDb *bt = malloc (sizeof(*bt));
945 memset (bt, 0, sizeof(*bt));
948 bt->mem = malloc (3 *mgr->page_size);
950 bt->mem = VirtualAlloc(NULL, 3 * mgr->page_size, MEM_COMMIT, PAGE_READWRITE);
952 bt->frame = (BtPage)bt->mem;
953 bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
954 bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
958 // compare two keys, returning > 0, = 0, or < 0
959 // as the comparison value
961 int keycmp (BtKey key1, unsigned char *key2, uint len2)
963 uint len1 = key1->len;
966 if( ans = memcmp (key1->key, key2, len1 > len2 ? len2 : len1) )
979 // find segment in pool
980 // must be called with hashslot idx locked
981 // return NULL if not there
982 // otherwise return node
984 BtPool *bt_findpool(BtDb *bt, uid page_no, uint idx)
989 // compute start of hash chain in pool
991 if( slot = bt->mgr->hash[idx] )
992 pool = bt->mgr->pool + slot;
996 page_no &= ~bt->mgr->poolmask;
998 while( pool->basepage != page_no )
999 if( pool = pool->hashnext )
1007 // add segment to hash table
1009 void bt_linkhash(BtDb *bt, BtPool *pool, uid page_no, int idx)
1014 pool->hashprev = pool->hashnext = NULL;
1015 pool->basepage = page_no & ~bt->mgr->poolmask;
1018 if( slot = bt->mgr->hash[idx] ) {
1019 node = bt->mgr->pool + slot;
1020 pool->hashnext = node;
1021 node->hashprev = pool;
1024 bt->mgr->hash[idx] = pool->slot;
1027 // find best segment to evict from buffer pool
1029 BtPool *bt_findlru (BtDb *bt, uint hashslot)
1031 unsigned long long int target = ~0LL;
1032 BtPool *pool = NULL, *node;
1037 node = bt->mgr->pool + hashslot;
1039 // scan pool entries under hash table slot
1044 if( node->lru > target )
1048 } while( node = node->hashnext );
1053 // map new buffer pool segment to virtual memory
1055 BTERR bt_mapsegment(BtDb *bt, BtPool *pool, uid page_no)
1057 off64_t off = (page_no & ~bt->mgr->poolmask) << bt->mgr->page_bits;
1058 off64_t limit = off + ((bt->mgr->poolmask+1) << bt->mgr->page_bits);
1062 flag = PROT_READ | ( bt->mgr->mode == BT_ro ? 0 : PROT_WRITE );
1063 pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED, bt->mgr->idx, off);
1064 if( pool->map == MAP_FAILED )
1065 return bt->err = BTERR_map;
1066 // clear out madvise issued bits
1067 memset (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8) / 8), 0, (bt->mgr->poolmask + 8)/8);
1069 flag = ( bt->mgr->mode == BT_ro ? PAGE_READONLY : PAGE_READWRITE );
1070 pool->hmap = CreateFileMapping(bt->mgr->idx, NULL, flag, (DWORD)(limit >> 32), (DWORD)limit, NULL);
1072 return bt->err = BTERR_map;
1074 flag = ( bt->mgr->mode == BT_ro ? FILE_MAP_READ : FILE_MAP_WRITE );
1075 pool->map = MapViewOfFile(pool->hmap, flag, (DWORD)(off >> 32), (DWORD)off, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1077 return bt->err = BTERR_map;
1082 // find or place requested page in segment-pool
1083 // return pool table entry, incrementing pin
1085 BtPool *bt_pinpage(BtDb *bt, uid page_no)
1087 BtPool *pool, *node, *next;
1088 uint slot, idx, victim;
1091 // lock hash table chain
1093 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1094 bt_spinreadlock (&bt->mgr->latch[idx]);
1096 // look up in hash table
1098 if( pool = bt_findpool(bt, page_no, idx) ) {
1100 __sync_fetch_and_add(&pool->pin, 1);
1102 _InterlockedIncrement16 (&pool->pin);
1104 bt_spinreleaseread (&bt->mgr->latch[idx]);
1109 // upgrade to write lock
1111 bt_spinreleaseread (&bt->mgr->latch[idx]);
1112 bt_spinwritelock (&bt->mgr->latch[idx]);
1114 // try to find page in pool with write lock
1116 if( pool = bt_findpool(bt, page_no, idx) ) {
1118 __sync_fetch_and_add(&pool->pin, 1);
1120 _InterlockedIncrement16 (&pool->pin);
1122 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1127 // allocate a new pool node
1128 // and add to hash table
1131 slot = __sync_fetch_and_add(&bt->mgr->poolcnt, 1);
1133 slot = _InterlockedIncrement16 (&bt->mgr->poolcnt) - 1;
1136 if( ++slot < bt->mgr->poolmax ) {
1137 pool = bt->mgr->pool + slot;
1140 if( bt_mapsegment(bt, pool, page_no) )
1143 bt_linkhash(bt, pool, page_no, idx);
1145 __sync_fetch_and_add(&pool->pin, 1);
1147 _InterlockedIncrement16 (&pool->pin);
1149 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1153 // pool table is full
1154 // find best pool entry to evict
1157 __sync_fetch_and_add(&bt->mgr->poolcnt, -1);
1159 _InterlockedDecrement16 (&bt->mgr->poolcnt);
1164 victim = __sync_fetch_and_add(&bt->mgr->evicted, 1);
1166 victim = _InterlockedIncrement16 (&bt->mgr->evicted) - 1;
1168 victim %= bt->mgr->hashsize;
1170 // try to get write lock
1171 // skip entry if not obtained
1173 if( !bt_spinwritetry (&bt->mgr->latch[victim]) )
1176 // if cache entry is empty
1177 // or no slots are unpinned
1180 if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
1181 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1185 // unlink victim pool node from hash table
1187 if( node = pool->hashprev )
1188 node->hashnext = pool->hashnext;
1189 else if( node = pool->hashnext )
1190 bt->mgr->hash[victim] = node->slot;
1192 bt->mgr->hash[victim] = 0;
1194 if( node = pool->hashnext )
1195 node->hashprev = pool->hashprev;
1197 bt_spinreleasewrite (&bt->mgr->latch[victim]);
1199 // remove old file mapping
1201 munmap (pool->map, (bt->mgr->poolmask+1) << bt->mgr->page_bits);
1203 FlushViewOfFile(pool->map, 0);
1204 UnmapViewOfFile(pool->map);
1205 CloseHandle(pool->hmap);
1209 // create new pool mapping
1210 // and link into hash table
1212 if( bt_mapsegment(bt, pool, page_no) )
1215 bt_linkhash(bt, pool, page_no, idx);
1217 __sync_fetch_and_add(&pool->pin, 1);
1219 _InterlockedIncrement16 (&pool->pin);
1221 bt_spinreleasewrite (&bt->mgr->latch[idx]);
1226 // place write, read, or parent lock on requested page_no.
1227 // pin to buffer pool and return page pointer
1229 BTERR bt_lockpage(BtDb *bt, uid page_no, BtLock mode, BtPage *pageptr)
1236 // find/create maping in pool table
1237 // and pin our pool slot
1239 if( pool = bt_pinpage(bt, page_no) )
1240 subpage = (uint)(page_no & bt->mgr->poolmask); // page within mapping
1244 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);
1279 return bt->err = BTERR_lock;
1288 // remove write, read, or parent lock on requested page_no.
1290 BTERR bt_unlockpage(BtDb *bt, uid page_no, BtLock mode)
1296 // since page is pinned
1297 // it should still be in the buffer pool
1298 // and is in no danger of being a victim for reuse
1300 if( !(set = bt_bindlatch (bt, page_no, 0)) )
1301 return bt->err = BTERR_latch;
1303 idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
1304 bt_spinreadlock (&bt->mgr->latch[idx]);
1306 if( !(pool = bt_findpool(bt, page_no, idx)) )
1307 return bt->err = BTERR_hash;
1309 bt_spinreleaseread (&bt->mgr->latch[idx]);
1313 bt_spinreleaseread (set->readwr);
1316 bt_spinreleasewrite (set->readwr);
1319 bt_spinreleaseread (set->access);
1322 bt_spinreleasewrite (set->access);
1325 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)
1347 // obtain delete lock on deleted page
1349 if( bt_lockpage(bt, page_no, BtLockDelete, NULL) )
1352 // obtain write lock on deleted page
1354 if( bt_lockpage(bt, page_no, BtLockWrite, &bt->temp) )
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) )
1374 // remove delete lock on deleted node
1376 if( bt_unlockpage(bt, page_no, BtLockDelete) )
1382 // allocate a new page and write page into it
1384 uid bt_newpage(BtDb *bt, BtPage page)
1390 // lock allocation page
1392 bt_spinwritelock(bt->mgr->latchmgr->lock);
1394 // use empty chain first
1395 // else allocate empty page
1397 if( new_page = bt_getid(bt->mgr->latchmgr->alloc[1].right) ) {
1398 if( bt_lockpage (bt, new_page, BtLockWrite, &bt->temp) )
1400 bt_putid(bt->mgr->latchmgr->alloc[1].right, bt_getid(bt->temp->right));
1401 if( bt_unlockpage (bt, new_page, BtLockWrite) )
1405 new_page = bt_getid(bt->mgr->latchmgr->alloc->right);
1406 bt_putid(bt->mgr->latchmgr->alloc->right, new_page+1);
1410 if ( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
1411 return bt->err = BTERR_wrt, 0;
1413 // if writing first page of pool block, zero last page in the block
1415 if ( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
1417 // use zero buffer to write zeros
1418 memset(bt->zero, 0, bt->mgr->page_size);
1419 if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
1420 return bt->err = BTERR_wrt, 0;
1423 // bring new page into pool and copy page.
1424 // this will extend the file into the new pages.
1426 if( bt_lockpage(bt, new_page, BtLockWrite, &pmap) )
1429 memcpy(pmap, page, bt->mgr->page_size);
1431 if( bt_unlockpage (bt, new_page, BtLockWrite) )
1434 // unlock allocation latch and return new page no
1436 bt_spinreleasewrite(bt->mgr->latchmgr->lock);
1440 // find slot in page for given key at a given level
1442 int bt_findslot (BtDb *bt, unsigned char *key, uint len)
1444 uint diff, higher = bt->page->cnt, low = 1, slot;
1446 // low is the lowest candidate, higher is already
1447 // tested as .ge. the given key, loop ends when they meet
1449 while( diff = higher - low ) {
1450 slot = low + ( diff >> 1 );
1451 if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
1460 // find and load page at given level for given key
1461 // leave page rd or wr locked as requested
1463 int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, uint lock)
1465 uid page_no = ROOT_page, prevpage = 0;
1466 uint drill = 0xff, slot;
1467 uint mode, prevmode;
1469 // start at root of btree and drill down
1472 // determine lock mode of drill level
1473 mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
1475 bt->page_no = page_no;
1477 // obtain access lock using lock chaining with Access mode
1479 if( page_no > ROOT_page )
1480 if( bt_lockpage(bt, page_no, BtLockAccess, NULL) )
1483 // now unlock our (possibly foster) parent
1486 if( bt_unlockpage(bt, prevpage, prevmode) )
1491 // obtain read lock using lock chaining
1492 // and pin page contents
1494 if( bt_lockpage(bt, page_no, mode, &bt->page) )
1497 if( page_no > ROOT_page )
1498 if( bt_unlockpage(bt, page_no, BtLockAccess) )
1501 // re-read and re-lock root after determining actual level of root
1503 if( bt->page_no == ROOT_page )
1504 if( bt->page->lvl != drill) {
1505 drill = bt->page->lvl;
1507 if( lock == BtLockWrite && drill == lvl )
1508 if( bt_unlockpage(bt, page_no, mode) )
1514 prevpage = bt->page_no;
1517 // if page is being deleted,
1518 // move back to preceeding page
1520 if( bt->page->kill ) {
1521 page_no = bt_getid (bt->page->right);
1525 // find key on page at this level
1526 // and descend to requested level
1528 slot = bt_findslot (bt, key, len);
1530 // is this slot a foster child?
1532 if( slot <= bt->page->cnt - bt->page->foster )
1536 while( slotptr(bt->page, slot)->dead )
1537 if( slot++ < bt->page->cnt )
1542 if( slot <= bt->page->cnt - bt->page->foster )
1545 // continue down / right using overlapping locks
1546 // to protect pages being killed or split.
1548 page_no = bt_getid(slotptr(bt->page, slot)->id);
1552 page_no = bt_getid(bt->page->right);
1556 // return error on end of chain
1558 bt->err = BTERR_struct;
1559 return 0; // return error
1562 // find and delete key on page by marking delete flag bit
1563 // when page becomes empty, delete it from the btree
1565 BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl)
1567 unsigned char leftkey[256], rightkey[256];
1572 if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
1573 ptr = keyptr(bt->page, slot);
1577 // if key is found delete it, otherwise ignore request
1579 if( !keycmp (ptr, key, len) )
1580 if( slotptr(bt->page, slot)->dead == 0 ) {
1581 slotptr(bt->page,slot)->dead = 1;
1582 if( slot < bt->page->cnt )
1583 bt->page->dirty = 1;
1587 // return if page is not empty, or it has no right sibling
1589 right = bt_getid(bt->page->right);
1590 page_no = bt->page_no;
1592 if( !right || bt->page->act )
1593 return bt_unlockpage(bt, page_no, BtLockWrite);
1595 // obtain Parent lock over write lock
1597 if( bt_lockpage(bt, page_no, BtLockParent, NULL) )
1600 // cache copy of key to delete
1602 ptr = keyptr(bt->page, bt->page->cnt);
1603 memcpy(leftkey, ptr, ptr->len + 1);
1605 // lock and map right page
1607 if( bt_lockpage(bt, right, BtLockWrite, &bt->temp) )
1610 // pull contents of next page into current empty page
1611 memcpy (bt->page, bt->temp, bt->mgr->page_size);
1613 // cache copy of key to update
1614 ptr = keyptr(bt->temp, bt->temp->cnt);
1615 memcpy(rightkey, ptr, ptr->len + 1);
1617 // Mark right page as deleted and point it to left page
1618 // until we can post updates at higher level.
1620 bt_putid(bt->temp->right, page_no);
1624 if( bt_unlockpage(bt, right, BtLockWrite) )
1626 if( bt_unlockpage(bt, page_no, BtLockWrite) )
1629 // delete old lower key to consolidated node
1631 if( bt_deletekey (bt, leftkey + 1, *leftkey, lvl + 1) )
1634 // redirect higher key directly to consolidated node
1636 if( slot = bt_loadpage (bt, rightkey+1, *rightkey, lvl+1, BtLockWrite) )
1637 ptr = keyptr(bt->page, slot);
1641 // since key already exists, update id
1643 if( keycmp (ptr, rightkey+1, *rightkey) )
1644 return bt->err = BTERR_struct;
1646 slotptr(bt->page, slot)->dead = 0;
1647 bt_putid(slotptr(bt->page,slot)->id, page_no);
1649 if( bt_unlockpage(bt, bt->page_no, BtLockWrite) )
1652 // obtain write lock and
1653 // add right block to free chain
1655 if( bt_freepage (bt, right) )
1658 // remove ParentModify lock
1660 if( bt_unlockpage(bt, page_no, BtLockParent) )
1666 // find key in leaf level and return row-id
1668 uid bt_findkey (BtDb *bt, unsigned char *key, uint len)
1674 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
1675 ptr = keyptr(bt->page, slot);
1679 // if key exists, return row-id
1680 // otherwise return 0
1682 if( ptr->len == len && !memcmp (ptr->key, key, len) )
1683 id = bt_getid(slotptr(bt->page,slot)->id);
1687 if( bt_unlockpage (bt, bt->page_no, BtLockRead) )
1693 // check page for space available,
1694 // clean if necessary and return
1695 // 0 - page needs splitting
1698 uint bt_cleanpage(BtDb *bt, uint amt)
1700 uint nxt = bt->mgr->page_size;
1701 BtPage page = bt->page;
1702 uint cnt = 0, idx = 0;
1703 uint max = page->cnt;
1706 if( page->min >= (max+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1709 // skip cleanup if nothing to reclaim
1714 memcpy (bt->frame, page, bt->mgr->page_size);
1716 // skip page info and set rest of page to zero
1718 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1722 // try cleaning up page first
1724 while( cnt++ < max ) {
1725 // always leave fence key and foster children in list
1726 if( cnt < max - page->foster && slotptr(bt->frame,cnt)->dead )
1730 key = keyptr(bt->frame, cnt);
1731 nxt -= key->len + 1;
1732 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1735 memcpy(slotptr(page, ++idx)->id, slotptr(bt->frame, cnt)->id, BtId);
1736 if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
1738 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1739 slotptr(page, idx)->off = nxt;
1745 // see if page has enough space now, or does it need splitting?
1747 if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
1753 // add key to current page
1754 // page must already be writelocked
1756 void bt_addkeytopage (BtDb *bt, uint slot, unsigned char *key, uint len, uid id, uint tod)
1758 BtPage page = bt->page;
1761 // calculate next available slot and copy key into page
1763 page->min -= len + 1;
1764 ((unsigned char *)page)[page->min] = len;
1765 memcpy ((unsigned char *)page + page->min +1, key, len );
1767 for( idx = slot; idx < page->cnt; idx++ )
1768 if( slotptr(page, idx)->dead )
1771 // now insert key into array before slot
1772 // preserving the fence slot
1774 if( idx == page->cnt )
1780 *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
1782 bt_putid(slotptr(page,slot)->id, id);
1783 slotptr(page, slot)->off = page->min;
1784 slotptr(page, slot)->tod = tod;
1785 slotptr(page, slot)->dead = 0;
1788 // split the root and raise the height of the btree
1789 // call with current page locked and page no of foster child
1790 // return with current page (root) unlocked
1792 BTERR bt_splitroot(BtDb *bt, uid right)
1794 uint nxt = bt->mgr->page_size;
1795 unsigned char fencekey[256];
1796 BtPage root = bt->page;
1800 // Obtain an empty page to use, and copy the left page
1801 // contents into it from the root. Strip foster child key.
1802 // (it's the stopper key)
1808 // Save left fence key.
1810 key = keyptr(root, root->cnt);
1811 memcpy (fencekey, key, key->len + 1);
1813 // copy the lower keys into a new left page
1815 if( !(new_page = bt_newpage(bt, root)) )
1818 // preserve the page info at the bottom
1819 // and set rest of the root to zero
1821 memset (root+1, 0, bt->mgr->page_size - sizeof(*root));
1823 // insert left fence key on empty newroot page
1825 nxt -= *fencekey + 1;
1826 memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
1827 bt_putid(slotptr(root, 1)->id, new_page);
1828 slotptr(root, 1)->off = nxt;
1830 // insert stopper key on newroot page
1831 // and increase the root height
1837 memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
1838 bt_putid(slotptr(root, 2)->id, right);
1839 slotptr(root, 2)->off = nxt;
1841 bt_putid(root->right, 0);
1842 root->min = nxt; // reset lowest used offset and key count
1847 // release root (bt->page)
1849 return bt_unlockpage(bt, ROOT_page, BtLockWrite);
1852 // split already locked full node
1853 // in current page variables
1856 BTERR bt_splitpage (BtDb *bt)
1858 uint slot, cnt, idx, max, nxt = bt->mgr->page_size;
1859 unsigned char fencekey[256];
1860 uid page_no = bt->page_no;
1861 BtPage page = bt->page;
1862 uint tod = time(NULL);
1863 uint lvl = page->lvl;
1864 uid new_page, right;
1867 // initialize frame buffer
1869 memset (bt->frame, 0, bt->mgr->page_size);
1870 max = page->cnt - page->foster;
1871 tod = (uint)time(NULL);
1875 // split higher half of keys to bt->frame
1876 // leaving foster children in the left node.
1878 while( cnt++ < max ) {
1879 key = keyptr(page, cnt);
1880 nxt -= key->len + 1;
1881 memcpy ((unsigned char *)bt->frame + nxt, key, key->len + 1);
1882 memcpy(slotptr(bt->frame,++idx)->id, slotptr(page,cnt)->id, BtId);
1883 slotptr(bt->frame, idx)->tod = slotptr(page, cnt)->tod;
1884 slotptr(bt->frame, idx)->off = nxt;
1888 // transfer right link node
1890 if( page_no > ROOT_page ) {
1891 right = bt_getid (page->right);
1892 bt_putid(bt->frame->right, right);
1895 bt->frame->bits = bt->mgr->page_bits;
1896 bt->frame->min = nxt;
1897 bt->frame->cnt = idx;
1898 bt->frame->lvl = lvl;
1900 // get new free page and write frame to it.
1902 if( !(new_page = bt_newpage(bt, bt->frame)) )
1905 // remember fence key for new page to add
1908 key = keyptr(bt->frame, idx);
1909 memcpy (fencekey, key, key->len + 1);
1911 // update lower keys and foster children to continue in old page
1913 memcpy (bt->frame, page, bt->mgr->page_size);
1914 memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
1915 nxt = bt->mgr->page_size;
1920 // assemble page of smaller keys
1921 // to remain in the old page
1923 while( cnt++ < max / 2 ) {
1924 key = keyptr(bt->frame, cnt);
1925 nxt -= key->len + 1;
1926 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1927 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1928 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1929 slotptr(page, idx)->off = nxt;
1933 // insert new foster child at beginning of the current foster children
1935 nxt -= *fencekey + 1;
1936 memcpy ((unsigned char *)page + nxt, fencekey, *fencekey + 1);
1937 bt_putid (slotptr(page,++idx)->id, new_page);
1938 slotptr(page, idx)->tod = tod;
1939 slotptr(page, idx)->off = nxt;
1943 // continue with old foster child keys if any
1945 cnt = bt->frame->cnt - bt->frame->foster;
1947 while( cnt++ < bt->frame->cnt ) {
1948 key = keyptr(bt->frame, cnt);
1949 nxt -= key->len + 1;
1950 memcpy ((unsigned char *)page + nxt, key, key->len + 1);
1951 memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
1952 slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
1953 slotptr(page, idx)->off = nxt;
1960 // link new right page
1962 bt_putid (page->right, new_page);
1964 // if current page is the root page, split it
1966 if( page_no == ROOT_page )
1967 return bt_splitroot (bt, new_page);
1969 // release wr lock on our page
1971 if( bt_unlockpage (bt, page_no, BtLockWrite) )
1974 // obtain ParentModification lock for current page
1975 // to fix fence key and highest foster child on page
1977 if( bt_lockpage (bt, page_no, BtLockParent, NULL) )
1980 // get our highest foster child key to find in parent node
1982 if( bt_lockpage (bt, page_no, BtLockRead, &page) )
1985 key = keyptr(page, page->cnt);
1986 memcpy (fencekey, key, key->len+1);
1988 if( bt_unlockpage (bt, page_no, BtLockRead) )
1991 // update our parent
1995 slot = bt_loadpage (bt, fencekey + 1, *fencekey, lvl + 1, BtLockWrite);
2000 // check if parent page has enough space for any possible key
2002 if( bt_cleanpage (bt, 256) )
2005 if( bt_splitpage (bt) )
2009 // see if we are still a foster child from another node
2011 if( bt_getid (slotptr(bt->page, slot)->id) != page_no ) {
2012 if( bt_unlockpage (bt, bt->page_no, BtLockWrite) )
2022 // wait until readers from parent get their locks
2025 if( bt_lockpage (bt, page_no, BtLockDelete, NULL) )
2028 // lock our page for writing
2030 if( bt_lockpage (bt, page_no, BtLockWrite, &page) )
2033 // switch parent fence key to foster child
2035 if( slotptr(page, page->cnt)->dead )
2036 slotptr(bt->page, slot)->dead = 1;
2038 bt_putid (slotptr(bt->page, slot)->id, bt_getid(slotptr(page, page->cnt)->id));
2040 // remove highest foster child from our page
2046 key = keyptr(page, page->cnt);
2048 // add our new fence key for foster child to our parent
2050 bt_addkeytopage (bt, slot, key->key, key->len, page_no, tod);
2052 if( bt_unlockpage (bt, bt->page_no, BtLockWrite) )
2055 if( bt_unlockpage (bt, page_no, BtLockDelete) )
2058 if( bt_unlockpage (bt, page_no, BtLockWrite) )
2061 return bt_unlockpage (bt, page_no, BtLockParent);
2064 // Insert new key into the btree at leaf level.
2066 BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod)
2073 if( slot = bt_loadpage (bt, key, len, 0, BtLockWrite) )
2074 ptr = keyptr(bt->page, slot);
2078 bt->err = BTERR_ovflw;
2082 // if key already exists, update id and return
2086 if( !keycmp (ptr, key, len) ) {
2087 slotptr(page, slot)->dead = 0;
2088 slotptr(page, slot)->tod = tod;
2089 bt_putid(slotptr(page,slot)->id, id);
2090 return bt_unlockpage(bt, bt->page_no, BtLockWrite);
2093 // check if page has enough space
2095 if( bt_cleanpage (bt, len) )
2098 if( bt_splitpage (bt) )
2102 bt_addkeytopage (bt, slot, key, len, id, tod);
2104 return bt_unlockpage (bt, bt->page_no, BtLockWrite);
2107 // cache page of keys into cursor and return starting slot for given key
2109 uint bt_startkey (BtDb *bt, unsigned char *key, uint len)
2113 // cache page for retrieval
2114 if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
2115 memcpy (bt->cursor, bt->page, bt->mgr->page_size);
2116 bt->cursor_page = bt->page_no;
2117 if ( bt_unlockpage(bt, bt->page_no, BtLockRead) )
2123 // return next slot for cursor page
2124 // or slide cursor right into next page
2126 uint bt_nextkey (BtDb *bt, uint slot)
2132 right = bt_getid(bt->cursor->right);
2133 while( slot++ < bt->cursor->cnt - bt->cursor->foster )
2134 if( slotptr(bt->cursor,slot)->dead )
2136 else if( right || (slot < bt->cursor->cnt - bt->cursor->foster) )
2144 bt->cursor_page = right;
2146 if( bt_lockpage(bt, right, BtLockRead, &page) )
2149 memcpy (bt->cursor, page, bt->mgr->page_size);
2151 if ( bt_unlockpage(bt, right, BtLockRead) )
2160 BtKey bt_key(BtDb *bt, uint slot)
2162 return keyptr(bt->cursor, slot);
2165 uid bt_uid(BtDb *bt, uint slot)
2167 return bt_getid(slotptr(bt->cursor,slot)->id);
2170 uint bt_tod(BtDb *bt, uint slot)
2172 return slotptr(bt->cursor,slot)->tod;
2185 // standalone program to index file of keys
2186 // then list them onto std-out
2189 void *index_file (void *arg)
2191 uint __stdcall index_file (void *arg)
2194 int line = 0, found = 0, cnt = 0;
2195 uid next, page_no = LEAF_page; // start on first page of leaves
2196 unsigned char key[256];
2197 ThreadArg *args = arg;
2198 int ch, len = 0, slot;
2205 bt = bt_open (args->mgr);
2208 switch(args->type | 0x20)
2211 fprintf(stderr, "started indexing for %s\n", args->infile);
2212 if( in = fopen (args->infile, "rb") )
2213 while( ch = getc(in), ch != EOF )
2218 if( args->num == 1 )
2219 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2221 else if( args->num )
2222 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2224 if( bt_insertkey (bt, key, len, line, *tod) )
2225 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2228 else if( len < 255 )
2230 fprintf(stderr, "finished %s for %d keys\n", args->infile, line);
2234 fprintf(stderr, "started deleting keys for %s\n", args->infile);
2235 if( in = fopen (args->infile, "rb") )
2236 while( ch = getc(in), ch != EOF )
2240 if( args->num == 1 )
2241 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2243 else if( args->num )
2244 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2246 if( bt_deletekey (bt, key, len, 0) )
2247 fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
2250 else if( len < 255 )
2252 fprintf(stderr, "finished %s for keys, %d \n", args->infile, line);
2256 fprintf(stderr, "started finding keys for %s\n", args->infile);
2257 if( in = fopen (args->infile, "rb") )
2258 while( ch = getc(in), ch != EOF )
2262 if( args->num == 1 )
2263 sprintf((char *)key+len, "%.9d", 1000000000 - line), len += 9;
2265 else if( args->num )
2266 sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
2268 if( bt_findkey (bt, key, len) )
2271 fprintf(stderr, "Error %d Syserr %d Line: %d\n", bt->err, errno, line), exit(0);
2274 else if( len < 255 )
2276 fprintf(stderr, "finished %s for %d keys, found %d\n", args->infile, line, found);
2282 fprintf(stderr, "started reading\n");
2284 if( slot = bt_startkey (bt, key, len) )
2287 fprintf(stderr, "Error %d in StartKey. Syserror: %d\n", bt->err, errno), exit(0);
2289 while( slot = bt_nextkey (bt, slot) ) {
2290 ptr = bt_key(bt, slot);
2291 fwrite (ptr->key, ptr->len, 1, stdout);
2292 fputc ('\n', stdout);
2298 fprintf(stderr, "started reading\n");
2301 bt_lockpage (bt, page_no, BtLockRead, &page);
2303 next = bt_getid (page->right);
2304 bt_unlockpage (bt, page_no, BtLockRead);
2305 } while( page_no = next );
2307 cnt--; // remove stopper key
2308 fprintf(stderr, " Total keys read %d\n", cnt);
2320 typedef struct timeval timer;
2322 int main (int argc, char **argv)
2324 int idx, cnt, len, slot, err;
2325 int segsize, bits = 16;
2330 time_t start[1], stop[1];
2343 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]);
2344 fprintf (stderr, " where page_bits is the page size in bits\n");
2345 fprintf (stderr, " mapped_segments is the number of mmap segments in buffer pool\n");
2346 fprintf (stderr, " seg_bits is the size of individual segments in buffer pool in pages in bits\n");
2347 fprintf (stderr, " line_numbers = 1 to append line numbers to keys\n");
2348 fprintf (stderr, " src_file1 thru src_filen are files of keys separated by newline\n");
2353 gettimeofday(&start, NULL);
2359 bits = atoi(argv[3]);
2362 poolsize = atoi(argv[4]);
2365 fprintf (stderr, "Warning: no mapped_pool\n");
2367 if( poolsize > 65535 )
2368 fprintf (stderr, "Warning: mapped_pool > 65535 segments\n");
2371 segsize = atoi(argv[5]);
2373 segsize = 4; // 16 pages per mmap segment
2376 num = atoi(argv[6]);
2380 threads = malloc (cnt * sizeof(pthread_t));
2382 threads = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, cnt * sizeof(HANDLE));
2384 args = malloc (cnt * sizeof(ThreadArg));
2386 mgr = bt_mgr ((argv[1]), BT_rw, bits, poolsize, segsize, poolsize / 8);
2389 fprintf(stderr, "Index Open Error %s\n", argv[1]);
2395 for( idx = 0; idx < cnt; idx++ ) {
2396 args[idx].infile = argv[idx + 7];
2397 args[idx].type = argv[2][0];
2398 args[idx].mgr = mgr;
2399 args[idx].num = num;
2400 args[idx].idx = idx;
2402 if( err = pthread_create (threads + idx, NULL, index_file, args + idx) )
2403 fprintf(stderr, "Error creating thread %d\n", err);
2405 threads[idx] = (HANDLE)_beginthreadex(NULL, 65536, index_file, args + idx, 0, NULL);
2409 // wait for termination
2412 for( idx = 0; idx < cnt; idx++ )
2413 pthread_join (threads[idx], NULL);
2414 gettimeofday(&stop, NULL);
2415 real_time = 1000.0 * ( stop.tv_sec - start.tv_sec ) + 0.001 * (stop.tv_usec - start.tv_usec );
2417 WaitForMultipleObjects (cnt, threads, TRUE, INFINITE);
2419 for( idx = 0; idx < cnt; idx++ )
2420 CloseHandle(threads[idx]);
2423 real_time = 1000 * (*stop - *start);
2425 fprintf(stderr, " Time to complete: %.2f seconds\n", real_time/1000);