]> pd.if.org Git - btree/blobdiff - threads2j.c
release of multi-threaded/multi-process btree code
[btree] / threads2j.c
similarity index 73%
rename from fosterbtreef2.c
rename to threads2j.c
index e4592d2d2611a5911fa4006ba67c0532d41db766..d7cb99498cb37d383ed6494aa049337fb6522866 100644 (file)
@@ -1,5 +1,5 @@
-// foster btree version f2
-// 18 JAN 2014
+// btree version threads2j linux futex concurrency version
+// 24 JAN 2014
 
 // author: karl malbrain, malbrain@cal.berkeley.edu
 
@@ -25,6 +25,8 @@ REDISTRIBUTION OF THIS SOFTWARE.
 
 #ifdef linux
 #define _GNU_SOURCE
+#include <linux/futex.h>
+#define SYS_futex 202
 #endif
 
 #ifdef unix
@@ -36,6 +38,7 @@ REDISTRIBUTION OF THIS SOFTWARE.
 #include <sys/mman.h>
 #include <errno.h>
 #include <pthread.h>
+#include <limits.h>
 #else
 #define WIN32_LEAN_AND_MEAN
 #include <windows.h>
@@ -74,7 +77,7 @@ There are five lock types for each node in three independent sets:
 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{
@@ -83,7 +86,33 @@ 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
 
@@ -121,50 +150,30 @@ typedef struct {
 //     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
@@ -178,8 +187,8 @@ typedef struct {
        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
@@ -191,7 +200,7 @@ typedef struct {
 
 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
@@ -208,19 +217,19 @@ typedef struct {
        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
@@ -232,11 +241,11 @@ typedef struct {
        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
@@ -257,8 +266,8 @@ typedef enum {
 // 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);
@@ -267,7 +276,7 @@ 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);
@@ -298,6 +307,10 @@ extern uint bt_tod (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.
@@ -306,20 +319,22 @@ extern uint bt_tod (BtDb *bt, uint slot);
 //     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
@@ -346,76 +361,83 @@ int i;
        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
@@ -423,54 +445,81 @@ void bt_spinwritelock(BtSpinLatch *latch)
 //     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
@@ -510,7 +559,7 @@ BtLatchSet *set;
 
        //  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
        {
@@ -527,14 +576,14 @@ BtLatchSet *set;
 #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
   {
@@ -555,7 +604,7 @@ BtLatchSet *set;
        _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;
   }
 
@@ -574,7 +623,7 @@ BtLatchSet *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;
        }
 
@@ -611,13 +660,13 @@ BtLatchSet *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;
        }
 
@@ -631,15 +680,15 @@ BtLatchSet *set;
        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;
   }
 }
@@ -668,7 +717,7 @@ uint slot;
 
 #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);
@@ -720,7 +769,6 @@ uint amt[1];
 BtMgr* mgr;
 BtKey key;
 int flag;
-
 #ifndef unix
 SYSTEM_INFO sysinfo[1];
 #endif
@@ -737,7 +785,6 @@ SYSTEM_INFO sysinfo[1];
 
 #ifdef unix
        mgr = calloc (1, sizeof(BtMgr));
-
        mgr->idx = open ((char*)name, O_RDWR | O_CREAT, 0666);
 
        if( mgr->idx == -1 )
@@ -770,7 +817,7 @@ SYSTEM_INFO sysinfo[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);
@@ -811,12 +858,12 @@ SYSTEM_INFO sysinfo[1];
 #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 )
@@ -900,6 +947,27 @@ SYSTEM_INFO sysinfo[1];
                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;
@@ -949,7 +1017,7 @@ BtDb *bt = malloc (sizeof(*bt));
        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;
 }
 
@@ -1034,7 +1102,7 @@ BtPool *pool = NULL, *node;
 
        node = bt->mgr->pool + hashslot;
 
-       //      scan pool entries under hash table slot
+       //  scan pool entries under hash table slot
 
        do {
          if( node->pin )
@@ -1061,6 +1129,7 @@ int flag;
        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
@@ -1117,12 +1186,11 @@ BtPool *bt_pinpool(BtDb *bt, uid page_no)
 {
 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
 
@@ -1132,15 +1200,15 @@ BtLatchSet *set;
 #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
 
@@ -1150,7 +1218,7 @@ BtLatchSet *set;
 #else
                _InterlockedIncrement16 (&pool->pin);
 #endif
-               bt_spinreleasewrite (&bt->mgr->latch[idx]);
+               bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
                pool->lru++;
                return pool;
        }
@@ -1177,7 +1245,7 @@ BtLatchSet *set;
 #else
                _InterlockedIncrement16 (&pool->pin);
 #endif
-               bt_spinreleasewrite (&bt->mgr->latch[idx]);
+               bt_spinreleasewrite (&bt->mgr->latch[idx], 1);
                return pool;
        }
 
@@ -1204,12 +1272,12 @@ BtLatchSet *set;
                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;
                }
 
@@ -1225,7 +1293,7 @@ BtLatchSet *set;
                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
@@ -1249,54 +1317,54 @@ BtLatchSet *set;
 #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;
        }
 }
@@ -1313,7 +1381,7 @@ int reuse;
 
        //      lock allocation page
 
-       bt_spinwritelock(bt->mgr->latchmgr->lock);
+       bt_spinwritelock(bt->mgr->latchmgr->lock, 0);
 
        // use empty chain first
        // else allocate empty page
@@ -1332,30 +1400,21 @@ int reuse;
                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);
@@ -1365,6 +1424,9 @@ int reuse;
        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;
 }
 
@@ -1373,8 +1435,16 @@ int reuse;
 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 ) {
@@ -1382,16 +1452,18 @@ uint diff, higher = bt->page->cnt, low = 1, slot;
                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;
@@ -1401,12 +1473,12 @@ BtPool *prevpool;
 
   //  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;
 
@@ -1422,7 +1494,7 @@ BtPool *prevpool;
        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);
@@ -1440,184 +1512,113 @@ BtPool *prevpool;
 
        // 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);
@@ -1626,37 +1627,42 @@ BtKey ptr;
 
        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));
@@ -1664,7 +1670,7 @@ BtKey ptr;
 
        // 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);
@@ -1674,11 +1680,10 @@ BtKey ptr;
        //      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
 
@@ -1696,7 +1701,7 @@ uid 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;
@@ -1709,8 +1714,8 @@ uid id;
 
 //     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)
 {
@@ -1737,13 +1742,7 @@ BtKey key;
        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 )
@@ -1752,7 +1751,6 @@ BtKey key;
                        continue;
 
                // copy key
-
                key = keyptr(bt->frame, cnt);
                nxt -= key->len + 1;
                memcpy ((unsigned char *)page + nxt, key, key->len + 1);
@@ -1764,108 +1762,48 @@ BtKey key;
                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);
@@ -1883,34 +1821,31 @@ BtKey key;
 }
 
 //  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;
@@ -1922,196 +1857,165 @@ BtKey key;
                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
@@ -2123,9 +2027,7 @@ uint slot;
        // 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);
@@ -2137,17 +2039,16 @@ uint slot;
 
 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;
@@ -2156,18 +2057,19 @@ uid right;
                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 );
@@ -2190,7 +2092,6 @@ uint bt_tod(BtDb *bt, uint slot)
        return slotptr(bt->cursor,slot)->tod;
 }
 
-
 #ifdef STANDALONE
 
 void bt_latchaudit (BtDb *bt)
@@ -2217,11 +2118,11 @@ uid page_no;
        }
 
        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);
@@ -2262,7 +2163,6 @@ uid next, page_no = LEAF_page;    // start on first page of leaves
 unsigned char key[256];
 ThreadArg *args = arg;
 int ch, len = 0, slot;
-BtLatchSet *set;
 time_t tod[1];
 BtPool *pool;
 BtPage page;
@@ -2280,6 +2180,7 @@ FILE *in;
                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") )
@@ -2294,7 +2195,7 @@ FILE *in;
                          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;
                        }
@@ -2316,7 +2217,7 @@ FILE *in;
                          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;
                        }
@@ -2371,17 +2272,17 @@ FILE *in;
                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