-// foster btree version f2
-// 18 JAN 2014
+// btree version threads2j linux futex concurrency version
+// 24 JAN 2014
// author: karl malbrain, malbrain@cal.berkeley.edu
#ifdef linux
#define _GNU_SOURCE
+#include <linux/futex.h>
+#define SYS_futex 202
#endif
#ifdef unix
#include <sys/mman.h>
#include <errno.h>
#include <pthread.h>
+#include <limits.h>
#else
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
2. (set 1) NodeDelete: Exclusive. About to release the node. Incompatible with AccessIntent.
3. (set 2) ReadLock: Sharable. Read the node. Incompatible with WriteLock.
4. (set 2) WriteLock: Exclusive. Modify the node. Incompatible with ReadLock and other WriteLocks.
-5. (set 3) ParentLock: Exclusive. Have parent adopt/delete maximum foster child from the node.
+5. (set 3) ParentModification: Exclusive. Change the node's parent keys. Incompatible with another ParentModification.
*/
typedef enum{
BtLockRead,
BtLockWrite,
BtLockParent
-}BtLock;
+} BtLock;
+
+// mode & definition for latch implementation
+
+enum {
+ Mutex = 1 << 0, // the mutex bit
+ Write = 1 << 1, // the writers bit
+ Share = 1 << 2, // reader count
+ PendRd = 1 << 12, // reader contended count
+ PendWr = 1 << 22 // writer contended count
+} LockMode;
+
+enum {
+ QueRd = 1, // reader queue
+ QueWr = 2 // writer queue
+} RWQueue;
+
+// share is count of read accessors
+// grant write lock when share == 0
+
+typedef struct {
+ volatile uint mutex:1; // 1 = busy
+ volatile uint write:1; // 1 = exclusive
+ volatile uint share:10; // count of readers holding locks
+ volatile uint readwait:10; // count of readers waiting
+ volatile uint writewait:10; // count of writers waiting
+} BtLatch;
// Define the length of the page and key pointers
// by the BtSlot array of keys.
typedef struct Page {
- volatile uint cnt; // count of keys in page
- volatile uint act; // count of active keys
- volatile uint min; // next key offset
- volatile uint foster; // count of foster children
+ uint cnt; // count of keys in page
+ uint act; // count of active keys
+ uint min; // next key offset
unsigned char bits; // page size in bits
- unsigned char lvl:7; // level of page
- unsigned char dirty:1; // page needs to be cleaned
+ unsigned char lvl:6; // level of page
+ unsigned char kill:1; // page is being deleted
+ unsigned char dirty:1; // page has deleted keys
unsigned char right[BtId]; // page number to right
} *BtPage;
-// mode & definition for hash latch implementation
-
-enum {
- Mutex = 1,
- Write = 2,
- Pending = 4,
- Share = 8
-} LockMode;
-
-// mutex locks the other fields
-// exclusive is set for write access
-// share is count of read accessors
-
-typedef struct {
- volatile ushort mutex:1;
- volatile ushort exclusive:1;
- volatile ushort pending:1;
- volatile ushort share:13;
-} BtSpinLatch;
-
// hash table entries
typedef struct {
- BtSpinLatch latch[1];
+ BtLatch latch[1];
volatile ushort slot; // Latch table entry at head of chain
} BtHashEntry;
// latch manager table structure
typedef struct {
- BtSpinLatch readwr[1]; // read/write page lock
- BtSpinLatch access[1]; // Access Intent/Page delete
- BtSpinLatch parent[1]; // adoption of foster children
- BtSpinLatch busy[1]; // slot is being moved between chains
+ BtLatch readwr[1]; // read/write page lock
+ BtLatch access[1]; // Access Intent/Page delete
+ BtLatch parent[1]; // adoption of foster children
+ BtLatch busy[1]; // slot is being moved between chains
volatile ushort next; // next entry in hash table chain
volatile ushort prev; // prev entry in hash table chain
volatile ushort pin; // number of outstanding locks
unsigned long long int lru; // number of times accessed
uid basepage; // mapped base page number
char *map; // mapped memory pointer
- ushort pin; // mapped page pin counter
ushort slot; // slot index in this array
+ ushort pin; // mapped page pin counter
void *hashprev; // previous pool entry for the same hash idx
void *hashnext; // next pool entry for the same hash idx
#ifndef unix
typedef struct {
struct Page alloc[2]; // next & free page_nos in right ptr
- BtSpinLatch lock[1]; // allocation area lite latch
+ BtLatch lock[1]; // allocation area lite latch
ushort latchdeployed; // highest number of latch entries deployed
ushort nlatchpage; // number of latch pages at BT_latch
ushort latchtotal; // number of page latch entries
uint seg_bits; // seg size in pages in bits
uint mode; // read-write mode
#ifdef unix
- int idx;
char *pooladvise; // bit maps for pool page advisements
+ int idx;
#else
HANDLE idx;
#endif
ushort poolcnt; // highest page pool node in use
ushort poolmax; // highest page pool node allocated
ushort poolmask; // total number of pages in mmap segment - 1
- ushort hashsize; // size of Hash Table for pool entries
ushort evicted; // last evicted hash table slot
- ushort *hash; // hash table of pool entries
+ ushort hashsize; // size of Hash Table for pool entries
+ ushort *hash; // pool index for hash entries
BtPool *pool; // memory pool page segments
- BtSpinLatch *latch; // latches for pool hash slots
+ BtLatch *latch; // latches for pool hash slots
BtLatchMgr *latchmgr; // mapped latch page from allocation page
BtLatchSet *latchsets; // mapped latch set from latch pages
#ifndef unix
BtMgr *mgr; // buffer manager for thread
BtPage cursor; // cached frame for start/next (never mapped)
BtPage frame; // spare frame for the page split (never mapped)
- BtPage zero; // page frame for zeroes at end of file
- BtPage page; // current page
+ BtPage zero; // page of zeroes to extend the file (never mapped)
+ BtPage page; // current page mapped from file
uid page_no; // current page number
uid cursor_page; // current cursor page number
- BtLatchSet *set; // current page latch set
+ BtLatchSet *set; // current page latchset
BtPool *pool; // current page pool
unsigned char *mem; // frame, cursor, page memory buffer
int found; // last delete was found
// B-Tree functions
extern void bt_close (BtDb *bt);
extern BtDb *bt_open (BtMgr *mgr);
-extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod, uint lvl);
-extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len);
+extern BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod);
+extern BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl);
extern uid bt_findkey (BtDb *bt, unsigned char *key, uint len);
extern uint bt_startkey (BtDb *bt, unsigned char *key, uint len);
extern uint bt_nextkey (BtDb *bt, uint slot);
extern BtMgr *bt_mgr (char *name, uint mode, uint bits, uint poolsize, uint segsize, uint hashsize);
void bt_mgrclose (BtMgr *mgr);
-// Helper functions to return cursor slot values
+// Helper functions to return slot values
extern BtKey bt_key (BtDb *bt, uint slot);
extern uid bt_uid (BtDb *bt, uint slot);
// The first leaf page of level zero is always
// located on page 2.
+// The b-tree pages are linked with next
+// pointers to facilitate enumerators,
+// and provide for concurrency.
+
// When to root page fills, it is split in two and
// the tree height is raised by a new root at page
// one with two keys.
// page cleanup The fence key for a node is always
// present, even after deletion and cleanup.
-// Groups of pages called segments from the btree are
-// cached with memory mapping. A hash table is used to keep
+// Groups of pages called segments from the btree are optionally
+// cached with a memory mapped pool. A hash table is used to keep
// track of the cached segments. This behaviour is controlled
// by the cache block size parameter to bt_open.
// To achieve maximum concurrency one page is locked at a time
-// as the tree is traversed to find leaf key in question.
-
-// An adoption traversal leaves the parent node locked as the
-// tree is traversed to the level in quesiton.
+// as the tree is traversed to find leaf key in question. The right
+// page numbers are used in cases where the page is being split,
+// or consolidated.
// Page 0 is dedicated to lock for new page extensions,
// and chains empty pages together for reuse.
+// The ParentModification lock on a node is obtained to prevent resplitting
+// or deleting a node before its fence is posted into its upper level.
+
// Empty pages are chained together through the ALLOC page and reused.
// Access macros to address slot and key values from the page
return id;
}
+// Latch Manager
+
+int sys_futex(void *addr1, int op, int val1, struct timespec *timeout, void *addr2, int val3)
+{
+ return syscall(SYS_futex, addr1, op, val1, timeout, addr2, val3);
+}
+
// wait until write lock mode is clear
// and add 1 to the share count
-void bt_spinreadlock(BtSpinLatch *latch)
+void bt_spinreadlock(BtLatch *latch, int private)
{
-ushort prev;
+uint prev;
- do {
-#ifdef unix
- while( __sync_fetch_and_or((ushort *)latch, Mutex) & Mutex )
+ if( private )
+ private = FUTEX_PRIVATE_FLAG;
+
+ while( 1 ) {
+ // obtain latch mutex
+ if( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex ) {
sched_yield();
-#else
- while( _InterlockedOr16((ushort *)latch, Mutex) & Mutex )
- SwitchToThread();
-#endif
+ continue;
+ }
- // see if exclusive request is granted or pending
+ // wait for writers to clear
+ // increment read waiters and wait
- if( prev = !(latch->exclusive | latch->pending) )
-#ifdef unix
- __sync_fetch_and_add((ushort *)latch, Share);
-#else
- _InterlockedExchangeAdd16 ((ushort *)latch, Share);
-#endif
+ if( latch->write || latch->writewait ) {
+ __sync_fetch_and_add ((uint *)latch, PendRd);
+ prev = __sync_fetch_and_and ((uint *)latch, ~Mutex) & ~Mutex;
+ sys_futex( (uint *)latch, FUTEX_WAIT_BITSET | private, prev, NULL, NULL, QueRd );
+ __sync_fetch_and_sub ((uint *)latch, PendRd);
+ continue;
+ }
+
+ // increment reader lock count
+ // and release latch mutex
-#ifdef unix
- __sync_fetch_and_and ((ushort *)latch, ~Mutex);
-#else
- _InterlockedAnd16((ushort *)latch, ~Mutex);
-#endif
- if( prev )
- return;
-#ifdef unix
- } while( sched_yield(), 1 );
-#else
- } while( SwitchToThread(), 1 );
-#endif
+ __sync_fetch_and_add ((uint *)latch, Share);
+ __sync_fetch_and_and ((uint *)latch, ~Mutex);
+ return;
+ }
}
// wait for other read and write latches to relinquish
-void bt_spinwritelock(BtSpinLatch *latch)
+void bt_spinwritelock(BtLatch *latch, int private)
{
- do {
-#ifdef unix
- while( __sync_fetch_and_or((ushort *)latch, Mutex | Pending) & Mutex )
+uint prev;
+
+ if( private )
+ private = FUTEX_PRIVATE_FLAG;
+
+ while( 1 ) {
+ // obtain latch mutex
+ if( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex ) {
sched_yield();
-#else
- while( _InterlockedOr16((ushort *)latch, Mutex | Pending) & Mutex )
- SwitchToThread();
-#endif
- if( !(latch->share | latch->exclusive) ) {
-#ifdef unix
- __sync_fetch_and_or((ushort *)latch, Write);
- __sync_fetch_and_and ((ushort *)latch, ~(Mutex | Pending));
-#else
- _InterlockedOr16((ushort *)latch, Write);
- _InterlockedAnd16((ushort *)latch, ~(Mutex | Pending));
-#endif
- return;
+ continue;
}
-#ifdef unix
- __sync_fetch_and_and ((ushort *)latch, ~Mutex);
- sched_yield();
-#else
- _InterlockedAnd16((ushort *)latch, ~Mutex);
- SwitchToThread();
-#endif
- } while( 1 );
+ // wait for write and reader count to clear
+
+ if( latch->write || latch->share ) {
+ __sync_fetch_and_add ((uint *)latch, PendWr);
+ prev = __sync_fetch_and_and ((uint *)latch, ~Mutex) & ~Mutex;
+ sys_futex( (uint *)latch, FUTEX_WAIT_BITSET | private, prev, NULL, NULL, QueWr );
+ __sync_fetch_and_sub ((uint *)latch, PendWr);
+ continue;
+ }
+
+ // take write mutex
+ // release latch mutex
+
+ __sync_fetch_and_or ((uint *)latch, Write);
+ __sync_fetch_and_and ((uint *)latch, ~Mutex);
+ return;
+ }
}
// try to obtain write lock
// return 1 if obtained,
// 0 otherwise
-int bt_spinwritetry(BtSpinLatch *latch)
+int bt_spinwritetry(BtLatch *latch)
{
-ushort prev;
+int ans;
-#ifdef unix
- if( prev = __sync_fetch_and_or((ushort *)latch, Mutex), prev & Mutex )
- return 0;
-#else
- if( prev = _InterlockedOr16((ushort *)latch, Mutex), prev & Mutex )
+ // try for mutex,
+ // abandon request if not taken
+
+ if( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex )
return 0;
-#endif
- // take write access if all bits are clear
- if( !prev )
-#ifdef unix
- __sync_fetch_and_or ((ushort *)latch, Write);
-#else
- _InterlockedOr16((ushort *)latch, Write);
-#endif
+ // see if write mode is available
-#ifdef unix
- __sync_fetch_and_and ((ushort *)latch, ~Mutex);
-#else
- _InterlockedAnd16((ushort *)latch, ~Mutex);
-#endif
- return !prev;
+ if( !latch->write && !latch->share ) {
+ __sync_fetch_and_or ((uint *)latch, Write);
+ ans = 1;
+ } else
+ ans = 0;
+
+ // release latch mutex
+
+ __sync_fetch_and_and ((uint *)latch, ~Mutex);
+ return ans;
}
-// clear write mode
+// clear write lock
-void bt_spinreleasewrite(BtSpinLatch *latch)
+void bt_spinreleasewrite(BtLatch *latch, int private)
{
-#ifdef unix
- __sync_fetch_and_and ((ushort *)latch, ~Write);
-#else
- _InterlockedAnd16((ushort *)latch, ~Write);
-#endif
+ if( private )
+ private = FUTEX_PRIVATE_FLAG;
+
+ // obtain latch mutex
+
+ while( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex )
+ sched_yield();
+
+ __sync_fetch_and_and ((uint *)latch, ~Write);
+
+ // favor writers
+
+ if( latch->writewait )
+ if( sys_futex( (uint *)latch, FUTEX_WAKE_BITSET | private, 1, NULL, NULL, QueWr ) )
+ goto wakexit;
+
+ if( latch->readwait )
+ sys_futex( (uint *)latch, FUTEX_WAKE_BITSET | private, INT_MAX, NULL, NULL, QueRd );
+
+ // release latch mutex
+
+wakexit:
+ __sync_fetch_and_and ((uint *)latch, ~Mutex);
}
// decrement reader count
-void bt_spinreleaseread(BtSpinLatch *latch)
+void bt_spinreleaseread(BtLatch *latch, int private)
{
-#ifdef unix
- __sync_fetch_and_add((ushort *)latch, -Share);
-#else
- _InterlockedExchangeAdd16 ((ushort *)latch, -Share);
-#endif
+ if( private )
+ private = FUTEX_PRIVATE_FLAG;
+
+ // obtain latch mutex
+
+ while( __sync_fetch_and_or((uint *)latch, Mutex) & Mutex )
+ sched_yield();
+
+ __sync_fetch_and_sub ((uint *)latch, Share);
+
+ // wake waiting writers
+
+ if( !latch->share && latch->writewait )
+ sys_futex( (uint *)latch, FUTEX_WAKE_BITSET | private, 1, NULL, NULL, QueWr );
+
+ // release latch mutex
+
+ __sync_fetch_and_and ((uint *)latch, ~Mutex);
}
// link latch table entry into latch hash table
// obtain read lock on hash table entry
- bt_spinreadlock(bt->mgr->latchmgr->table[hashidx].latch);
+ bt_spinreadlock(bt->mgr->latchmgr->table[hashidx].latch, 0);
if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
{
#endif
}
- bt_spinreleaseread (bt->mgr->latchmgr->table[hashidx].latch);
+ bt_spinreleaseread (bt->mgr->latchmgr->table[hashidx].latch, 0);
if( slot )
return set;
// try again, this time with write lock
- bt_spinwritelock(bt->mgr->latchmgr->table[hashidx].latch);
+ bt_spinwritelock(bt->mgr->latchmgr->table[hashidx].latch, 0);
if( slot = bt->mgr->latchmgr->table[hashidx].slot ) do
{
_InterlockedIncrement16 (&set->pin);
#endif
set->page_no = page_no;
- bt_spinreleasewrite(bt->mgr->latchmgr->table[hashidx].latch);
+ bt_spinreleasewrite(bt->mgr->latchmgr->table[hashidx].latch, 0);
return set;
}
_InterlockedIncrement16 (&set->pin);
#endif
bt_latchlink (bt, hashidx, victim, page_no);
- bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
+ bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch, 0);
return set;
}
// or has outstanding locks
if( !bt_spinwritetry (bt->mgr->latchmgr->table[idx].latch) ) {
- bt_spinreleasewrite (set->busy);
+ bt_spinreleasewrite (set->busy, 0);
continue;
}
if( set->pin ) {
- bt_spinreleasewrite (set->busy);
- bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
+ bt_spinreleasewrite (set->busy, 0);
+ bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch, 0);
continue;
}
if( set->next )
bt->mgr->latchsets[set->next].prev = set->prev;
- bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch);
+ bt_spinreleasewrite (bt->mgr->latchmgr->table[idx].latch, 0);
#ifdef unix
__sync_fetch_and_add(&set->pin, 1);
#else
_InterlockedIncrement16 (&set->pin);
#endif
bt_latchlink (bt, hashidx, victim, page_no);
- bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch);
- bt_spinreleasewrite (set->busy);
+ bt_spinreleasewrite (bt->mgr->latchmgr->table[hashidx].latch, 0);
+ bt_spinreleasewrite (set->busy, 0);
return set;
}
}
#ifdef unix
munmap (mgr->latchsets, mgr->latchmgr->nlatchpage * mgr->page_size);
- munmap (mgr->latchmgr, mgr->page_size);
+ munmap (mgr->latchmgr, mgr->page_size);
#else
FlushViewOfFile(mgr->latchmgr, 0);
UnmapViewOfFile(mgr->latchmgr);
BtMgr* mgr;
BtKey key;
int flag;
-
#ifndef unix
SYSTEM_INFO sysinfo[1];
#endif
#ifdef unix
mgr = calloc (1, sizeof(BtMgr));
-
mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
if( mgr->idx == -1 )
else
return free(mgr), free(latchmgr), NULL;
} else if( mode == BT_ro )
- return free(latchmgr), bt_mgrclose (mgr), NULL;
+ return free(latchmgr), free (mgr), NULL;
#else
latchmgr = VirtualAlloc(NULL, BT_maxpage, MEM_COMMIT, PAGE_READWRITE);
size = GetFileSize(mgr->idx, amt);
#ifdef unix
mgr->pool = calloc (poolmax, sizeof(BtPool));
mgr->hash = calloc (hashsize, sizeof(ushort));
- mgr->latch = calloc (hashsize, sizeof(BtSpinLatch));
+ mgr->latch = calloc (hashsize, sizeof(BtLatch));
mgr->pooladvise = calloc (poolmax, (mgr->poolmask + 8) / 8);
#else
mgr->pool = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, poolmax * sizeof(BtPool));
mgr->hash = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(ushort));
- mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtSpinLatch));
+ mgr->latch = GlobalAlloc (GMEM_FIXED|GMEM_ZEROINIT, hashsize * sizeof(BtLatch));
#endif
if( size || *amt )
last++;
}
+ // create empty page area by writing last page of first
+ // segment area (other pages are zeroed by O/S)
+
+ if( mgr->poolmask ) {
+ memset(latchmgr, 0, mgr->page_size);
+ last = mgr->poolmask;
+
+ while( last < MIN_lvl + 1 )
+ last += mgr->poolmask + 1;
+
+#ifdef unix
+ pwrite(mgr->idx, latchmgr, mgr->page_size, last << mgr->page_bits);
+#else
+ SetFilePointer (mgr->idx, last << mgr->page_bits, NULL, FILE_BEGIN);
+ if( !WriteFile (mgr->idx, (char *)latchmgr, mgr->page_size, amt, NULL) )
+ return bt_mgrclose (mgr), NULL;
+ if( *amt < mgr->page_size )
+ return bt_mgrclose (mgr), NULL;
+#endif
+ }
+
mgrlatch:
#ifdef unix
flag = PROT_READ | PROT_WRITE;
bt->zero = (BtPage)(bt->mem + 1 * mgr->page_size);
bt->cursor = (BtPage)(bt->mem + 2 * mgr->page_size);
- memset(bt->zero, 0, mgr->page_size);
+ memset (bt->zero, 0, mgr->page_size);
return bt;
}
node = bt->mgr->pool + hashslot;
- // scan pool entries under hash table slot
+ // scan pool entries under hash table slot
do {
if( node->pin )
pool->map = mmap (0, (bt->mgr->poolmask+1) << bt->mgr->page_bits, flag, MAP_SHARED, bt->mgr->idx, off);
if( pool->map == MAP_FAILED )
return bt->err = BTERR_map;
+
// clear out madvise issued bits
memset (bt->mgr->pooladvise + pool->slot * ((bt->mgr->poolmask + 8) / 8), 0, (bt->mgr->poolmask + 8)/8);
#else
{
BtPool *pool, *node, *next;
uint slot, idx, victim;
-BtLatchSet *set;
// lock hash table chain
idx = (uint)(page_no >> bt->mgr->seg_bits) % bt->mgr->hashsize;
- bt_spinreadlock (&bt->mgr->latch[idx]);
+ bt_spinreadlock (&bt->mgr->latch[idx], 1);
// look up in hash table
#else
_InterlockedIncrement16 (&pool->pin);
#endif
- bt_spinreleaseread (&bt->mgr->latch[idx]);
+ bt_spinreleaseread (&bt->mgr->latch[idx], 1);
pool->lru++;
return pool;
}
// upgrade to write lock
- bt_spinreleaseread (&bt->mgr->latch[idx]);
- bt_spinwritelock (&bt->mgr->latch[idx]);
+ bt_spinreleaseread (&bt->mgr->latch[idx], 1);
+ bt_spinwritelock (&bt->mgr->latch[idx], 1);
// try to find page in pool with write lock
#else
_InterlockedIncrement16 (&pool->pin);
#endif
- bt_spinreleasewrite (&bt->mgr->latch[idx]);
+ bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
pool->lru++;
return pool;
}
#else
_InterlockedIncrement16 (&pool->pin);
#endif
- bt_spinreleasewrite (&bt->mgr->latch[idx]);
+ bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
return pool;
}
if( !bt_spinwritetry (&bt->mgr->latch[victim]) )
continue;
- // if cache entry is empty
- // or no slots are unpinned
+ // if pool entry is empty
+ // or any pages are pinned
// skip this entry
if( !(pool = bt_findlru(bt, bt->mgr->hash[victim])) ) {
- bt_spinreleasewrite (&bt->mgr->latch[victim]);
+ bt_spinreleasewrite (&bt->mgr->latch[victim], 1);
continue;
}
if( node = pool->hashnext )
node->hashprev = pool->hashprev;
- bt_spinreleasewrite (&bt->mgr->latch[victim]);
+ bt_spinreleasewrite (&bt->mgr->latch[victim], 1);
// remove old file mapping
#ifdef unix
#else
_InterlockedIncrement16 (&pool->pin);
#endif
- bt_spinreleasewrite (&bt->mgr->latch[idx]);
+ bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
return pool;
}
}
// place write, read, or parent lock on requested page_no.
-// pin to buffer pool and return latchset pointer
+// pin to buffer pool and return page pointer
void bt_lockpage(BtLock mode, BtLatchSet *set)
{
switch( mode ) {
case BtLockRead:
- bt_spinreadlock (set->readwr);
+ bt_spinreadlock (set->readwr, 0);
break;
case BtLockWrite:
- bt_spinwritelock (set->readwr);
+ bt_spinwritelock (set->readwr, 0);
break;
case BtLockAccess:
- bt_spinreadlock (set->access);
+ bt_spinreadlock (set->access, 0);
break;
case BtLockDelete:
- bt_spinwritelock (set->access);
+ bt_spinwritelock (set->access, 0);
break;
case BtLockParent:
- bt_spinwritelock (set->parent);
+ bt_spinwritelock (set->parent, 0);
break;
}
}
-// remove write, read, or parent lock on requested page_no.
+// remove write, read, or parent lock on requested page
void bt_unlockpage(BtLock mode, BtLatchSet *set)
{
switch( mode ) {
case BtLockRead:
- bt_spinreleaseread (set->readwr);
+ bt_spinreleaseread (set->readwr, 0);
break;
case BtLockWrite:
- bt_spinreleasewrite (set->readwr);
+ bt_spinreleasewrite (set->readwr, 0);
break;
case BtLockAccess:
- bt_spinreleaseread (set->access);
+ bt_spinreleaseread (set->access, 0);
break;
case BtLockDelete:
- bt_spinreleasewrite (set->access);
+ bt_spinreleasewrite (set->access, 0);
break;
case BtLockParent:
- bt_spinreleasewrite (set->parent);
+ bt_spinreleasewrite (set->parent, 0);
break;
}
}
// lock allocation page
- bt_spinwritelock(bt->mgr->latchmgr->lock);
+ bt_spinwritelock(bt->mgr->latchmgr->lock, 0);
// use empty chain first
// else allocate empty page
reuse = 0;
}
#ifdef unix
+ if ( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
+ return bt->err = BTERR_wrt, 0;
+
// if writing first page of pool block, zero last page in the block
if ( !reuse && bt->mgr->poolmask > 0 && (new_page & bt->mgr->poolmask) == 0 )
{
// use zero buffer to write zeros
+ memset(bt->zero, 0, bt->mgr->page_size);
if ( pwrite(bt->mgr->idx,bt->zero, bt->mgr->page_size, (new_page | bt->mgr->poolmask) << bt->mgr->page_bits) < bt->mgr->page_size )
return bt->err = BTERR_wrt, 0;
}
-
- // unlock allocation latch
-
- bt_spinreleasewrite(bt->mgr->latchmgr->lock);
-
- if ( pwrite(bt->mgr->idx, page, bt->mgr->page_size, new_page << bt->mgr->page_bits) < bt->mgr->page_size )
- return bt->err = BTERR_wrt, 0;
-
#else
- // unlock allocation latch
-
- bt_spinreleasewrite(bt->mgr->latchmgr->lock);
-
// bring new page into pool and copy page.
// this will extend the file into the new pages.
- // NB -- no latch required
if( pool = bt_pinpool (bt, new_page) )
pmap = bt_page (bt, pool, new_page);
memcpy(pmap, page, bt->mgr->page_size);
bt_unpinpool (pool);
#endif
+ // unlock allocation latch and return new page no
+
+ bt_spinreleasewrite(bt->mgr->latchmgr->lock, 0);
return new_page;
}
int bt_findslot (BtDb *bt, unsigned char *key, uint len)
{
uint diff, higher = bt->page->cnt, low = 1, slot;
+uint good = 0;
+
+ // make stopper key an infinite fence value
- // low is the lowest candidate, higher is already
+ if( bt_getid (bt->page->right) )
+ higher++;
+ else
+ good++;
+
+ // low is the next candidate, higher is already
// tested as .ge. the given key, loop ends when they meet
while( diff = higher - low ) {
if( keycmp (keyptr(bt->page, slot), key, len) < 0 )
low = slot + 1;
else
- higher = slot;
+ higher = slot, good++;
}
- return higher;
+ // return zero if key is on right link page
+
+ return good ? higher : 0;
}
// find and load page at given level for given key
// leave page rd or wr locked as requested
-int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, BtLock lock)
+int bt_loadpage (BtDb *bt, unsigned char *key, uint len, uint lvl, uint lock)
{
uid page_no = ROOT_page, prevpage = 0;
BtLatchSet *set, *prevset;
// start at root of btree and drill down
+ bt->set = NULL;
+
do {
// determine lock mode of drill level
mode = (lock == BtLockWrite) && (drill == lvl) ? BtLockWrite : BtLockRead;
- // obtain latch set for this page
-
bt->set = bt_pinlatch (bt, page_no);
bt->page_no = page_no;
if( page_no > ROOT_page )
bt_lockpage(BtLockAccess, bt->set);
- // now unlock and unpin our (possibly foster) parent
+ // release & unpin parent page
if( prevpage ) {
bt_unlockpage(prevmode, prevset);
// re-read and re-lock root after determining actual level of root
- if( page_no == ROOT_page )
- if( bt->page->lvl != drill) {
+ if( bt->page->lvl != drill) {
+ if ( bt->page_no != ROOT_page )
+ return bt->err = BTERR_struct, 0;
+
drill = bt->page->lvl;
- if( lock == BtLockWrite && drill == lvl ) {
+ if( lock == BtLockWrite && drill == lvl ) {
bt_unlockpage(mode, bt->set);
bt_unpinlatch (bt->set);
bt_unpinpool (bt->pool);
continue;
}
- }
-
- prevpage = bt->page_no;
- prevpool = bt->pool;
- prevset = bt->set;
- prevmode = mode;
+ }
// find key on page at this level
- // and either descend to requested level
- // or return key slot
-
- slot = bt_findslot (bt, key, len);
+ // and descend to requested level
- // is this slot < foster child area
- // on the requested level?
-
- // if so, return actual slot even if dead
-
- if( slot <= bt->page->cnt - bt->page->foster )
+ if( !bt->page->kill && (slot = bt_findslot (bt, key, len)) ) {
if( drill == lvl )
return slot;
- // find next active slot
-
- // note: foster children are never dead
- // nor fence keys for interiour nodes
-
- while( slotptr(bt->page, slot)->dead )
- if( slot++ < bt->page->cnt )
- continue;
- else
- return bt->err = BTERR_struct, 0; // last key shouldn't be deleted
+ while( slotptr(bt->page, slot)->dead )
+ if( slot++ < bt->page->cnt )
+ continue;
+ else {
+ page_no = bt_getid(bt->page->right);
+ goto slideright;
+ }
- // is this slot < foster child area
- // if so, drill to next level
+ page_no = bt_getid(slotptr(bt->page, slot)->id);
+ drill--;
+ }
- if( slot <= bt->page->cnt - bt->page->foster )
- drill--;
+ // or slide right into next page
+ // (slide left from deleted page)
- // continue right onto foster child
- // or down to next level.
+ else
+ page_no = bt_getid(bt->page->right);
- page_no = bt_getid(slotptr(bt->page, slot)->id);
+ // continue down / right using overlapping locks
+ // to protect pages being killed or split.
+slideright:
+ prevpage = bt->page_no;
+ prevpool = bt->pool;
+ prevset = bt->set;
+ prevmode = mode;
} while( page_no );
- // return error on end of chain
+ // return error on end of right chain
bt->err = BTERR_struct;
return 0; // return error
}
// find and delete key on page by marking delete flag bit
-// when leaf page becomes empty, delete it from the btree
+// when page becomes empty, delete it
-BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len)
+BTERR bt_deletekey (BtDb *bt, unsigned char *key, uint len, uint lvl)
{
-unsigned char leftkey[256];
+unsigned char lowerkey[256], higherkey[256];
BtLatchSet *rset, *set;
BtPool *pool, *rpool;
-BtPage rpage, page;
uid page_no, right;
uint slot, tod;
+BtPage rpage;
BtKey ptr;
- if( slot = bt_loadpage (bt, key, len, 0, BtLockWrite) )
+ if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
ptr = keyptr(bt->page, slot);
else
return bt->err;
// if key is found delete it, otherwise ignore request
- // note that fence keys of interiour nodes are not deleted.
if( bt->found = !keycmp (ptr, key, len) )
if( bt->found = slotptr(bt->page, slot)->dead == 0 ) {
- slotptr(bt->page,slot)->dead = 1;
+ slotptr(bt->page,slot)->dead = 1;
if( slot < bt->page->cnt )
- bt->page->dirty = 1;
- bt->page->act--;
+ bt->page->dirty = 1;
+ bt->page->act--;
}
+ // return if page is not empty, or it has no right sibling
+
+ right = bt_getid(bt->page->right);
page_no = bt->page_no;
pool = bt->pool;
- page = bt->page;
set = bt->set;
- // return if page is not empty or not found
-
- if( page->act || !bt->found ) {
+ if( !right || bt->page->act ) {
bt_unlockpage(BtLockWrite, set);
bt_unpinlatch (set);
bt_unpinpool (pool);
return bt->err;
}
- // cache copy of fence key of empty node
-
- ptr = keyptr(page, page->cnt);
- memcpy(leftkey, ptr, ptr->len + 1);
+ // obtain Parent lock over write lock
- // release write lock on empty node
- // obtain Parent lock
-
- bt_unlockpage(BtLockWrite, set);
bt_lockpage(BtLockParent, set);
- // load and lock parent to see
- // if delete of empty node is OK
- // ie, not a fence key of parent
-
- while( 1 ) {
- if( slot = bt_loadpage (bt, leftkey+1, *leftkey, 1, BtLockWrite) )
- ptr = keyptr(bt->page, slot);
- else
- return bt->err;
-
- // does parent level contain our fence key yet?
- // and is it free of foster children?
-
- if( !bt->page->foster )
- if( !keycmp (ptr, leftkey+1, *leftkey) )
- break;
-
- bt_unlockpage(BtLockWrite, bt->set);
- bt_unpinlatch (bt->set);
- bt_unpinpool (bt->pool);
-#ifdef unix
- sched_yield();
-#else
- SwitchToThread();
-#endif
- }
-
- // find our left fence key
-
- while( slotptr(bt->page, slot)->dead )
- if( slot++ < bt->page->cnt )
- continue;
- else
- return bt->err = BTERR_struct; // last key shouldn't be deleted
-
- // now we have both parent and child
-
- bt_lockpage(BtLockDelete, set);
- bt_lockpage(BtLockWrite, set);
+ // keep copy of key to delete
- // return if page has no right sibling within parent
- // or if empty node is no longer empty
-
- if( page->act || slot == bt->page->cnt ) {
- // unpin parent
- bt_unlockpage(BtLockWrite, bt->set);
- bt_unpinlatch (bt->set);
- bt_unpinpool (bt->pool);
- // unpin empty node
- bt_unlockpage(BtLockParent, set);
- bt_unlockpage(BtLockDelete, set);
- bt_unlockpage(BtLockWrite, set);
- bt_unpinlatch (set);
- bt_unpinpool (pool);
- return bt->err;
- }
+ ptr = keyptr(bt->page, bt->page->cnt);
+ memcpy(lowerkey, ptr, ptr->len + 1);
- // lock and map our right page
- // note that it cannot be our foster child
- // since the our node is empty
-
- right = bt_getid(page->right);
+ // lock and map right page
if( rpool = bt_pinpool (bt, right) )
rpage = bt_page (bt, rpool, right);
rset = bt_pinlatch (bt, right);
bt_lockpage(BtLockWrite, rset);
- bt_lockpage(BtLockDelete, rset);
-
- // pull contents of right page into empty page
- memcpy (page, rpage, bt->mgr->page_size);
+ // pull contents of next page into current empty page
- // delete left parent slot for old empty page
- // and redirect right parent slot to it
+ memcpy (bt->page, rpage, bt->mgr->page_size);
- bt->page->act--;
- bt->page->dirty = 1;
- slotptr(bt->page, slot)->dead = 1;
+ // keep copy of key to update
- while( slot++ < bt->page->cnt )
- if( !slotptr(bt->page, slot)->dead )
- break;
+ ptr = keyptr(rpage, rpage->cnt);
+ memcpy(higherkey, ptr, ptr->len + 1);
- bt_putid(slotptr(bt->page,slot)->id, page_no);
+ // Mark right page as deleted and point it to left page
+ // until we can post updates at higher level.
- // release parent level lock
- // and our empty node lock
+ bt_putid(rpage->right, page_no);
+ rpage->kill = 1;
+ rpage->cnt = 0;
+ bt_unlockpage(BtLockWrite, rset);
bt_unlockpage(BtLockWrite, set);
- bt_unlockpage(BtLockWrite, bt->set);
- bt_unpinlatch (bt->set);
- bt_unpinpool (bt->pool);
+
+ // delete old lower key to consolidated node
+
+ if( bt_deletekey (bt, lowerkey + 1, *lowerkey, lvl + 1) )
+ return bt->err;
+
+ // redirect higher key directly to consolidated node
+
+ tod = (uint)time(NULL);
+
+ if( bt_insertkey (bt, higherkey+1, *higherkey, lvl + 1, page_no, tod) )
+ return bt->err;
// add killed right block to free chain
// lock latch mgr
- bt_spinwritelock(bt->mgr->latchmgr->lock);
+ bt_spinwritelock(bt->mgr->latchmgr->lock, 0);
// store free chain in allocation page second right
bt_putid(rpage->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
// unlock latch mgr and right page
- bt_spinreleasewrite(bt->mgr->latchmgr->lock);
+ bt_spinreleasewrite(bt->mgr->latchmgr->lock, 0);
bt_unlockpage(BtLockWrite, rset);
bt_unlockpage(BtLockDelete, rset);
// remove ParentModify lock
bt_unlockpage(BtLockParent, set);
- bt_unlockpage(BtLockDelete, set);
bt_unpinlatch (set);
bt_unpinpool (pool);
return 0;
-}
+}
// find key in leaf level and return row-id
// if key exists, return row-id
// otherwise return 0
- if( slot <= bt->page->cnt && !keycmp (ptr, key, len) )
+ if( ptr->len == len && !memcmp (ptr->key, key, len) )
id = bt_getid(slotptr(bt->page,slot)->id);
else
id = 0;
// check page for space available,
// clean if necessary and return
-// 0 - page needs splitting
-// >0 new slot value
+// =0 - page needs splitting
+// >0 - go ahead at returned slot
uint bt_cleanpage(BtDb *bt, uint amt, uint slot)
{
page->dirty = 0;
page->act = 0;
- // try cleaning up page first
-
- // always leave fence key in the array
- // otherwise, remove deleted key
-
- // note: foster children are never dead
- // nor are fence keys for interiour nodes
+ // always leave fence key in list
while( cnt++ < max ) {
if( cnt == slot )
continue;
// copy key
-
key = keyptr(bt->frame, cnt);
nxt -= key->len + 1;
memcpy ((unsigned char *)page + nxt, key, key->len + 1);
slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
slotptr(page, idx)->off = nxt;
}
-
page->min = nxt;
page->cnt = idx;
- // see if page has enough space now, or does it need splitting?
-
if( page->min >= (idx+1) * sizeof(BtSlot) + sizeof(*page) + amt + 1 )
return newslot;
return 0;
}
-// add key to current page
-// page must already be writelocked
-
-void bt_addkeytopage (BtDb *bt, uint slot, unsigned char *key, uint len, uid id, uint tod)
-{
-BtPage page = bt->page;
-uint idx;
-
- // find next available dead slot and copy key onto page
- // note that foster children on the page are never dead
-
- // look for next hole, but stay back from the fence key
-
- for( idx = slot; idx < page->cnt; idx++ )
- if( slotptr(page, idx)->dead )
- break;
-
- if( idx == page->cnt )
- idx++, page->cnt++;
-
- page->act++;
-
- // now insert key into array before slot
-
- while( idx > slot )
- *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
-
- page->min -= len + 1;
- ((unsigned char *)page)[page->min] = len;
- memcpy ((unsigned char *)page + page->min +1, key, len );
-
- bt_putid(slotptr(page,slot)->id, id);
- slotptr(page, slot)->off = page->min;
- slotptr(page, slot)->tod = tod;
- slotptr(page, slot)->dead = 0;
-}
-
// split the root and raise the height of the btree
-// call with current page locked and page no of foster child
-// return with current page (root) unlocked
-BTERR bt_splitroot(BtDb *bt, uid right)
+BTERR bt_splitroot(BtDb *bt, unsigned char *newkey, unsigned char *oldkey, uid page_no2)
{
uint nxt = bt->mgr->page_size;
-unsigned char fencekey[256];
BtPage root = bt->page;
uid new_page;
-BtKey key;
- // Obtain an empty page to use, and copy the left page
- // contents into it from the root. Strip foster child key.
- // (it's the stopper key)
-
- memset (slotptr(root, root->cnt), 0, sizeof(BtSlot));
- root->dirty = 1;
- root->foster--;
- root->act--;
- root->cnt--;
-
- // Save left fence key.
-
- key = keyptr(root, root->cnt);
- memcpy (fencekey, key, key->len + 1);
-
- // copy the lower keys into a new left page
+ // Obtain an empty page to use, and copy the current
+ // root contents into it which is the lower half of
+ // the old root.
if( !(new_page = bt_newpage(bt, root)) )
return bt->err;
// preserve the page info at the bottom
- // and set rest of the root to zero
+ // and set rest to zero
- memset (root+1, 0, bt->mgr->page_size - sizeof(*root));
+ memset(root+1, 0, bt->mgr->page_size - sizeof(*root));
- // insert left fence key on empty newroot page
+ // insert first key on newroot page
- nxt -= *fencekey + 1;
- memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
+ nxt -= *newkey + 1;
+ memcpy ((unsigned char *)root + nxt, newkey, *newkey + 1);
bt_putid(slotptr(root, 1)->id, new_page);
slotptr(root, 1)->off = nxt;
- // insert stopper key on newroot page
+ // insert second key on newroot page
// and increase the root height
- nxt -= 3;
- fencekey[0] = 2;
- fencekey[1] = 0xff;
- fencekey[2] = 0xff;
- memcpy ((unsigned char *)root + nxt, fencekey, *fencekey + 1);
- bt_putid(slotptr(root, 2)->id, right);
+ nxt -= *oldkey + 1;
+ memcpy ((unsigned char *)root + nxt, oldkey, *oldkey + 1);
+ bt_putid(slotptr(root, 2)->id, page_no2);
slotptr(root, 2)->off = nxt;
bt_putid(root->right, 0);
}
// split already locked full node
-// in current page variables
-// return unlocked and unpinned.
+// return unlocked.
BTERR bt_splitpage (BtDb *bt)
{
-uint slot, cnt, idx, max, nxt = bt->mgr->page_size;
-unsigned char fencekey[256];
-uid page_no = bt->page_no;
-BtLatchSet *set = bt->set;
+uint cnt = 0, idx = 0, max, nxt = bt->mgr->page_size;
+unsigned char oldkey[256], lowerkey[256];
+uid page_no = bt->page_no, right;
+BtLatchSet *nset, *set = bt->set;
BtPool *pool = bt->pool;
BtPage page = bt->page;
-uint tod = time(NULL);
uint lvl = page->lvl;
-uid new_page, right;
+uid new_page;
BtKey key;
+uint tod;
- // initialize frame buffer for right node
+ // split higher half of keys to bt->frame
+ // the last key (fence key) might be dead
- memset (bt->frame, 0, bt->mgr->page_size);
- max = page->cnt - page->foster;
tod = (uint)time(NULL);
+
+ memset (bt->frame, 0, bt->mgr->page_size);
+ max = (int)page->cnt;
cnt = max / 2;
idx = 0;
- // split higher half of keys to bt->frame
- // leaving old foster children in the left node,
- // and adding a new foster child there.
-
while( cnt++ < max ) {
key = keyptr(page, cnt);
nxt -= key->len + 1;
slotptr(bt->frame, idx)->off = nxt;
}
- // transfer right link node to new right node
+ // remember existing fence key for new page to the right
- if( page_no > ROOT_page ) {
- right = bt_getid (page->right);
- bt_putid(bt->frame->right, right);
- }
+ memcpy (oldkey, key, key->len + 1);
bt->frame->bits = bt->mgr->page_bits;
bt->frame->min = nxt;
bt->frame->cnt = idx;
bt->frame->lvl = lvl;
- // get new free page and write right frame to it.
+ // link right node
- if( !(new_page = bt_newpage(bt, bt->frame)) )
- return bt->err;
+ if( page_no > ROOT_page ) {
+ right = bt_getid (page->right);
+ bt_putid(bt->frame->right, right);
+ }
- // remember fence key for new right page to add
- // as foster child to the left node
+ // get new free page and write frame to it.
- key = keyptr(bt->frame, idx);
- memcpy (fencekey, key, key->len + 1);
+ if( !(new_page = bt_newpage(bt, bt->frame)) )
+ return bt->err;
- // update lower keys and foster children to continue in old page
+ // update lower keys to continue in old page
memcpy (bt->frame, page, bt->mgr->page_size);
memset (page+1, 0, bt->mgr->page_size - sizeof(*page));
nxt = bt->mgr->page_size;
- page->dirty = 0;
page->act = 0;
cnt = 0;
idx = 0;
// assemble page of smaller keys
- // to remain in the old page
+ // (they're all active keys)
while( cnt++ < max / 2 ) {
key = keyptr(bt->frame, cnt);
nxt -= key->len + 1;
memcpy ((unsigned char *)page + nxt, key, key->len + 1);
- memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
- if( !(slotptr(page, idx)->dead = slotptr(bt->frame, cnt)->dead) )
- page->act++;
- slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
- slotptr(page, idx)->off = nxt;
- }
-
- // insert new foster child for right page in queue
- // before any of the current foster children
-
- nxt -= *fencekey + 1;
- memcpy ((unsigned char *)page + nxt, fencekey, *fencekey + 1);
-
- bt_putid (slotptr(page,++idx)->id, new_page);
- slotptr(page, idx)->tod = tod;
- slotptr(page, idx)->off = nxt;
- page->foster++;
- page->act++;
-
- // continue with old foster child keys
- // note that none will be dead
-
- cnt = bt->frame->cnt - bt->frame->foster;
-
- while( cnt++ < bt->frame->cnt ) {
- key = keyptr(bt->frame, cnt);
- nxt -= key->len + 1;
- memcpy ((unsigned char *)page + nxt, key, key->len + 1);
- memcpy (slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
+ memcpy(slotptr(page,++idx)->id, slotptr(bt->frame,cnt)->id, BtId);
slotptr(page, idx)->tod = slotptr(bt->frame, cnt)->tod;
slotptr(page, idx)->off = nxt;
page->act++;
}
+ // remember fence key for old page
+
+ memcpy(lowerkey, key, key->len + 1);
+ bt_putid(page->right, new_page);
page->min = nxt;
page->cnt = idx;
- // link new right page
-
- bt_putid (page->right, new_page);
-
// if current page is the root page, split it
if( page_no == ROOT_page )
- return bt_splitroot (bt, new_page);
+ return bt_splitroot (bt, lowerkey, oldkey, new_page);
- // release wr lock on our page
+ // release wr lock on left page
bt_unlockpage (BtLockWrite, set);
- // obtain ParentModification lock for current page
- // to fix new fence key and oldest foster child on page
+ // obtain Parent/Write locks
+ // for left and right node pages
- bt_lockpage (BtLockParent, set);
+ nset = bt_pinlatch (bt, new_page);
- // get our new fence key to insert in parent node
-
- bt_lockpage (BtLockRead, set);
-
- key = keyptr(page, page->cnt-1);
- memcpy (fencekey, key, key->len+1);
+ bt_lockpage (BtLockParent, nset);
+ bt_lockpage (BtLockParent, set);
- bt_unlockpage (BtLockRead, set);
+ // insert new fence for reformulated left block
- if( bt_insertkey (bt, fencekey + 1, *fencekey, page_no, tod, lvl + 1) )
+ if( bt_insertkey (bt, lowerkey+1, *lowerkey, lvl + 1, page_no, tod) )
return bt->err;
- // lock our page for writing
-
- bt_lockpage (BtLockRead, set);
-
- // switch old parent key from us to our oldest foster child
+ // fix old fence for newly allocated right block page
- key = keyptr(page, page->cnt);
- memcpy (fencekey, key, key->len+1);
-
- new_page = bt_getid (slotptr(page, page->cnt)->id);
- bt_unlockpage (BtLockRead, set);
-
- if( bt_insertkey (bt, fencekey + 1, *fencekey, new_page, tod, lvl + 1) )
+ if( bt_insertkey (bt, oldkey+1, *oldkey, lvl + 1, new_page, tod) )
return bt->err;
- // now that it has its own parent pointer,
- // remove oldest foster child from our page
-
- bt_lockpage (BtLockWrite, set);
- memset (slotptr(page, page->cnt), 0, sizeof(BtSlot));
- page->dirty = 1;
- page->foster--;
- page->cnt--;
- page->act--;
+ // release Parent locks
- // unlock and unpin
-
- bt_unlockpage (BtLockWrite, set);
+ bt_unlockpage (BtLockParent, nset);
bt_unlockpage (BtLockParent, set);
+ bt_unpinlatch (nset);
bt_unpinlatch (set);
bt_unpinpool (pool);
return 0;
}
-// Insert new key into the btree at leaf level.
+// Insert new key into the btree at requested level.
+// Level zero pages are leaf pages. Page is unlocked at exit.
-BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uid id, uint tod, uint lvl)
+BTERR bt_insertkey (BtDb *bt, unsigned char *key, uint len, uint lvl, uid id, uint tod)
{
uint slot, idx;
BtPage page;
BtKey ptr;
- while( 1 ) {
- if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
- ptr = keyptr(bt->page, slot);
- else
- {
- if ( !bt->err )
- bt->err = BTERR_ovflw;
- return bt->err;
- }
+ while( 1 ) {
+ if( slot = bt_loadpage (bt, key, len, lvl, BtLockWrite) )
+ ptr = keyptr(bt->page, slot);
+ else
+ {
+ if ( !bt->err )
+ bt->err = BTERR_ovflw;
+ return bt->err;
+ }
- // if key already exists, update id and return
+ // if key already exists, update id and return
- page = bt->page;
+ page = bt->page;
- if( !keycmp (ptr, key, len) ) {
- if( slotptr(page, slot)->dead )
- page->act++;
- slotptr(page, slot)->dead = 0;
- slotptr(page, slot)->tod = tod;
- bt_putid(slotptr(page,slot)->id, id);
- bt_unlockpage(BtLockWrite, bt->set);
- bt_unpinlatch (bt->set);
- bt_unpinpool (bt->pool);
- return bt->err;
- }
+ if( !keycmp (ptr, key, len) ) {
+ slotptr(page, slot)->dead = 0;
+ slotptr(page, slot)->tod = tod;
+ bt_putid(slotptr(page,slot)->id, id);
+ bt_unlockpage(BtLockWrite, bt->set);
+ bt_unpinlatch(bt->set);
+ bt_unpinpool (bt->pool);
+ return bt->err;
+ }
- // check if page has enough space
+ // check if page has enough space
- if( slot = bt_cleanpage (bt, len, slot) )
- break;
+ if( slot = bt_cleanpage (bt, len, slot) )
+ break;
- if( bt_splitpage (bt) )
- return bt->err;
- }
+ if( bt_splitpage (bt) )
+ return bt->err;
+ }
- bt_addkeytopage (bt, slot, key, len, id, tod);
+ // calculate next available slot and copy key into page
- bt_unlockpage (BtLockWrite, bt->set);
- bt_unpinlatch (bt->set);
- bt_unpinpool (bt->pool);
- return 0;
+ page->min -= len + 1; // reset lowest used offset
+ ((unsigned char *)page)[page->min] = len;
+ memcpy ((unsigned char *)page + page->min +1, key, len );
+
+ for( idx = slot; idx < page->cnt; idx++ )
+ if( slotptr(page, idx)->dead )
+ break;
+
+ // now insert key into array before slot
+ // preserving the fence slot
+
+ if( idx == page->cnt )
+ idx++, page->cnt++;
+
+ page->act++;
+
+ while( idx > slot )
+ *slotptr(page, idx) = *slotptr(page, idx -1), idx--;
+
+ bt_putid(slotptr(page,slot)->id, id);
+ slotptr(page, slot)->off = page->min;
+ slotptr(page, slot)->tod = tod;
+ slotptr(page, slot)->dead = 0;
+
+ bt_unlockpage (BtLockWrite, bt->set);
+ bt_unpinlatch (bt->set);
+ bt_unpinpool (bt->pool);
+ return 0;
}
// cache page of keys into cursor and return starting slot for given key
// cache page for retrieval
if( slot = bt_loadpage (bt, key, len, 0, BtLockRead) )
memcpy (bt->cursor, bt->page, bt->mgr->page_size);
-
bt->cursor_page = bt->page_no;
-
bt_unlockpage(BtLockRead, bt->set);
bt_unpinlatch (bt->set);
bt_unpinpool (bt->pool);
uint bt_nextkey (BtDb *bt, uint slot)
{
-BtLatchSet *set;
BtPool *pool;
BtPage page;
uid right;
do {
right = bt_getid(bt->cursor->right);
- while( slot++ < bt->cursor->cnt - bt->cursor->foster )
+ while( slot++ < bt->cursor->cnt )
if( slotptr(bt->cursor,slot)->dead )
continue;
- else if( right || (slot < bt->cursor->cnt - bt->cursor->foster) )
+ else if( right || (slot < bt->cursor->cnt))
return slot;
else
break;
break;
bt->cursor_page = right;
+
if( pool = bt_pinpool (bt, right) )
page = bt_page (bt, pool, right);
else
return 0;
- set = bt_pinlatch (bt, right);
- bt_lockpage(BtLockRead, set);
+ bt->set = bt_pinlatch (bt, right);
+ bt_lockpage(BtLockRead, bt->set);
memcpy (bt->cursor, page, bt->mgr->page_size);
- bt_unlockpage(BtLockRead, set);
- bt_unpinlatch (set);
+ bt_unlockpage(BtLockRead, bt->set);
+ bt_unpinlatch (bt->set);
bt_unpinpool (pool);
slot = 0;
} while( 1 );
return slotptr(bt->cursor,slot)->tod;
}
-
#ifdef STANDALONE
void bt_latchaudit (BtDb *bt)
}
for( hashidx = 0; hashidx < bt->mgr->latchmgr->latchhash; hashidx++ ) {
- if( *(ushort *)bt->mgr->latchmgr->table[hashidx].latch )
+ if( *(uint *)bt->mgr->latchmgr->table[hashidx].latch )
fprintf(stderr, "latchmgr locked\n");
if( idx = bt->mgr->latchmgr->table[hashidx].slot ) do {
set = bt->mgr->latchsets + idx;
- if( *(ushort *)set->readwr || *(ushort *)set->access || *(ushort *)set->parent )
+ if( *(uint *)set->readwr || *(ushort *)set->access || *(ushort *)set->parent )
fprintf(stderr, "latchset %d locked\n", idx);
if( set->hash != hashidx )
fprintf(stderr, "latchset %d wrong hashidx\n", idx);
unsigned char key[256];
ThreadArg *args = arg;
int ch, len = 0, slot;
-BtLatchSet *set;
time_t tod[1];
BtPool *pool;
BtPage page;
bt_latchaudit (bt);
fprintf(stderr, "finished latch mgr audit\n");
break;
+
case 'w':
fprintf(stderr, "started indexing for %s\n", args->infile);
if( in = fopen (args->infile, "rb") )
else if( args->num )
sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
- if( bt_insertkey (bt, key, len, line, *tod, 0) )
+ if( bt_insertkey (bt, key, len, 0, line, *tod) )
fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
len = 0;
}
else if( args->num )
sprintf((char *)key+len, "%.9d", line + args->idx * args->num), len += 9;
- if( bt_deletekey (bt, key, len) )
+ if( bt_deletekey (bt, key, len, 0) )
fprintf(stderr, "Error %d Line: %d\n", bt->err, line), exit(0);
len = 0;
}
fprintf(stderr, "started reading\n");
do {
- if( pool = bt_pinpool (bt, page_no) )
- page = bt_page (bt, pool, page_no);
+ if( bt->pool = bt_pinpool (bt, page_no) )
+ page = bt_page (bt, bt->pool, page_no);
else
break;
- set = bt_pinlatch (bt, page_no);
- bt_lockpage (BtLockRead, set);
+ bt->set = bt_pinlatch (bt, page_no);
+ bt_lockpage (BtLockRead, bt->set);
cnt += page->act;
next = bt_getid (page->right);
- bt_unlockpage (BtLockRead, set);
- bt_unpinlatch (set);
- bt_unpinpool (pool);
+ bt_unlockpage (BtLockRead, bt->set);
+ bt_unpinlatch (bt->set);
+ bt_unpinpool (bt->pool);
} while( page_no = next );
cnt--; // remove stopper key