+ if( chk < 0 ) {
+ next->page_no = bt_getid (next->page->right);
+ bt_unlockpage (BtLockWrite, next->latch);
+ bt_unlockpage (BtLockParent, next->latch);
+ bt_unpinlatch (next->latch);
+ bt_unpinpool (next->pool);
+ continue;
+ }
+
+ if( chk > 0 )
+ return bt->err = BTERR_struct;
+
+ if( bt_fixfences (bt, next, newfence) )
+ return bt->err;
+
+ break;
+ }
+
+ memcpy (set->page->fence, newfence, 256);
+
+ bt_unlockpage (BtLockWrite, set->latch);
+ bt_unlockpage (BtLockParent, set->latch);
+ bt_unpinlatch (set->latch);
+ bt_unpinpool (set->pool);
+ return 0;
+}
+
+// return page to free list
+// page must be delete & write locked
+
+void bt_freepage (BtDb *bt, BtPageSet *set)
+{
+ // lock allocation page
+
+ bt_spinwritelock (bt->mgr->latchmgr->lock);
+
+ // store chain in second right
+ bt_putid(set->page->right, bt_getid(bt->mgr->latchmgr->alloc[1].right));
+ bt_putid(bt->mgr->latchmgr->alloc[1].right, set->page_no);
+ set->page->free = 1;
+
+ // unlock released page
+
+ bt_unlockpage (BtLockDelete, set->latch);
+ bt_unlockpage (BtLockWrite, set->latch);
+ bt_unpinlatch (set->latch);
+ bt_unpinpool (set->pool);
+
+ // unlock allocation page
+
+ bt_spinreleasewrite (bt->mgr->latchmgr->lock);
+}
+
+// remove the root level by promoting its only child
+// call with parent and child pages
+
+BTERR bt_removeroot (BtDb *bt, BtPageSet *root, BtPageSet *child)
+{
+uid next = 0;
+
+ do {
+ if( next ) {
+ child->latch = bt_pinlatch (bt, next);
+ bt_lockpage (BtLockDelete, child->latch);
+ bt_lockpage (BtLockWrite, child->latch);
+
+ if( child->pool = bt_pinpool (bt, next) )
+ child->page = bt_page (bt, child->pool, next);
+ else
+ return bt->err;
+
+ child->page_no = next;
+ }
+
+ memcpy (root->page, child->page, bt->mgr->page_size);
+ next = bt_getid (slotptr(child->page, child->page->cnt)->id);
+ bt_freepage (bt, child);
+ } while( root->page->lvl > 1 && root->page->cnt == 1 );
+
+ bt_unlockpage (BtLockWrite, root->latch);
+ bt_unpinlatch (root->latch);
+ bt_unpinpool (root->pool);
+ return 0;
+}
+
+// pull right page over ourselves in simple merge
+
+BTERR bt_mergeright (BtDb *bt, BtPageSet *set, BtPageSet *parent, BtPageSet *right, uint slot, uint idx)
+{
+ // install ourselves as child page
+ // and delete ourselves from parent
+
+ bt_putid (slotptr(parent->page, idx)->id, set->page_no);
+ slotptr(parent->page, slot)->dead = 1;
+ parent->page->act--;
+
+ // collapse any empty slots
+
+ while( idx = parent->page->cnt - 1 )
+ if( slotptr(parent->page, idx)->dead ) {
+ *slotptr(parent->page, idx) = *slotptr(parent->page, idx + 1);
+ memset (slotptr(parent->page, parent->page->cnt--), 0, sizeof(BtSlot));
+ } else
+ break;
+
+ memcpy (set->page, right->page, bt->mgr->page_size);
+ bt_unlockpage (BtLockParent, right->latch);