]> git.sur5r.net Git - openldap/blobdiff - libraries/liblmdb/mdb.c
ITS#7718 invalidate cursor when DB gets emptied
[openldap] / libraries / liblmdb / mdb.c
index 620e5b51ff309828f289bee69b090ec4b58f17e8..e935dc633aa8d0917855ef94935c7c9d1f78e8db 100644 (file)
  *     @{
  */
 #ifdef _WIN32
+#define MDB_PIDLOCK    0
 #define pthread_t      DWORD
 #define pthread_mutex_t        HANDLE
 #define pthread_key_t  DWORD
 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
 #define        close(fd)       (CloseHandle(fd) ? 0 : -1)
 #define        munmap(ptr,len) UnmapViewOfFile(ptr)
+#ifdef PROCESS_QUERY_LIMITED_INFORMATION
+#define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
 #else
+#define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
+#endif
+#define        Z       "I"
+#else
+
+#define        Z       "z"                     /**< printf format modifier for size_t */
+
+       /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
+#define MDB_PIDLOCK                    1
 
 #ifdef MDB_USE_POSIX_SEM
 
@@ -281,33 +293,33 @@ typedef MDB_ID    txnid_t;
  *     @{
  */
 #ifndef MDB_DEBUG
-       /**     Enable debug output.
+       /**     Enable debug output.  Needs variable argument macros (a C99 feature).
         *      Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
         *      read from and written to the database (used for free space management).
         */
 #define MDB_DEBUG 0
 #endif
 
-#if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
-# undef  MDB_DEBUG
-# define MDB_DEBUG     0
-# define DPRINTF       (void)  /* Vararg macros may be unsupported */
-#elif MDB_DEBUG
+#if MDB_DEBUG
 static int mdb_debug;
 static txnid_t mdb_debug_start;
 
-       /**     Print a debug message with printf formatting. */
-# define DPRINTF(fmt, ...)     /**< Requires 2 or more args */ \
-       ((void) ((mdb_debug) && \
-        fprintf(stderr, "%s:%d " fmt "\n", __func__, __LINE__, __VA_ARGS__)))
+       /**     Print a debug message with printf formatting.
+        *      Requires double parenthesis around 2 or more args.
+        */
+# define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
+# define DPRINTF0(fmt, ...) \
+       fprintf(stderr, "%s:%d " fmt "\n", __func__, __LINE__, __VA_ARGS__)
 #else
-# define DPRINTF(fmt, ...)     ((void) 0)
-# define MDB_DEBUG_SKIP
+# define DPRINTF(args) ((void) 0)
 #endif
        /**     Print a debug string.
         *      The string is printed literally, with no format processing.
         */
-#define DPUTS(arg)     DPRINTF("%s", arg)
+#define DPUTS(arg)     DPRINTF(("%s", arg))
+       /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
+#define DDBI(mc) \
+       (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
 /** @} */
 
        /** A default memory page size.
@@ -344,8 +356,10 @@ static txnid_t mdb_debug_start;
         */
 #define MDB_MAGIC       0xBEEFC0DE
 
-       /**     The version number for a database's file format. */
-#define MDB_VERSION     1
+       /**     The version number for a database's datafile format. */
+#define MDB_DATA_VERSION        1
+       /**     The version number for a database's lockfile format. */
+#define MDB_LOCK_VERSION        1
 
        /**     @brief The maximum size of a key in the database.
         *
@@ -381,7 +395,7 @@ static txnid_t mdb_debug_start;
         */
 #define        DKEY(x) mdb_dkey(x, kbuf)
 #else
-#define        DKBUF   typedef int dummy_kbuf  /* so we can put ';' after */
+#define        DKBUF
 #define DKEY(x)        0
 #endif
 
@@ -414,7 +428,8 @@ typedef uint16_t     indx_t;
  *
  *     If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
  *
- *     No reader table is used if the database is on a read-only filesystem.
+ *     No reader table is used if the database is on a read-only filesystem, or
+ *     if #MDB_NOLOCK is set.
  *
  *     Since the database uses multi-version concurrency control, readers don't
  *     actually need any locking. This table is used to keep track of which
@@ -513,8 +528,8 @@ typedef struct MDB_txbody {
                /** Stamp identifying this as an MDB file. It must be set
                 *      to #MDB_MAGIC. */
        uint32_t        mtb_magic;
-               /** Version number of this lock file. Must be set to #MDB_VERSION. */
-       uint32_t        mtb_version;
+               /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
+       uint32_t        mtb_format;
 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
        char    mtb_rmname[MNAME_LEN];
 #else
@@ -540,7 +555,7 @@ typedef struct MDB_txninfo {
        union {
                MDB_txbody mtb;
 #define mti_magic      mt1.mtb.mtb_magic
-#define mti_version    mt1.mtb.mtb_version
+#define mti_format     mt1.mtb.mtb_format
 #define mti_mutex      mt1.mtb.mtb_mutex
 #define mti_rmname     mt1.mtb.mtb_rmname
 #define mti_txnid      mt1.mtb.mtb_txnid
@@ -559,6 +574,13 @@ typedef struct MDB_txninfo {
        } mt2;
        MDB_reader      mti_readers[1];
 } MDB_txninfo;
+
+       /** Lockfile format signature: version, features and field layout */
+#define MDB_LOCK_FORMAT \
+       ((uint32_t) \
+        ((MDB_LOCK_VERSION) \
+         /* Flags which describe functionality */ \
+         + (((MDB_PIDLOCK) != 0) << 16)))
 /** @} */
 
 /** Common header for all page types.
@@ -582,9 +604,10 @@ typedef struct MDB_page {
 #define        P_LEAF           0x02           /**< leaf page */
 #define        P_OVERFLOW       0x04           /**< overflow page */
 #define        P_META           0x08           /**< meta page */
-#define        P_DIRTY          0x10           /**< dirty page */
+#define        P_DIRTY          0x10           /**< dirty page, also set for #P_SUBP pages */
 #define        P_LEAF2          0x20           /**< for #MDB_DUPFIXED records */
 #define        P_SUBP           0x40           /**< for #MDB_DUPSORT sub-pages */
+#define        P_KEEP           0x8000         /**< leave this page alone during spill */
 /** @} */
        uint16_t        mp_flags;               /**< @ref mdb_page */
 #define mp_lower       mp_pb.pb.pb_lower
@@ -737,9 +760,12 @@ typedef struct MDB_node {
         */
 #define LEAF2KEY(p, i, ks)     ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
 
-       /** Set the \b node's key into \b key, if requested. */
-#define MDB_GET_KEY(node, key) { if ((key) != NULL) { \
-       (key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node); } }
+       /** Set the \b node's key into \b keyptr, if requested. */
+#define MDB_GET_KEY(node, keyptr)      { if ((keyptr) != NULL) { \
+       (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
+
+       /** Set the \b node's key into \b key. */
+#define MDB_GET_KEY2(node, key)        { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
 
        /** Information about a single database in the environment. */
 typedef struct MDB_db {
@@ -764,12 +790,15 @@ typedef struct MDB_db {
        /** Handle for the default DB. */
 #define        MAIN_DBI        1
 
-       /** Meta page content. */
+       /** Meta page content.
+        *      A meta page is the start point for accessing a database snapshot.
+        *      Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
+        */
 typedef struct MDB_meta {
                /** Stamp identifying this as an MDB file. It must be set
                 *      to #MDB_MAGIC. */
        uint32_t        mm_magic;
-               /** Version number of this lock file. Must be set to #MDB_VERSION. */
+               /** Version number of this lock file. Must be set to #MDB_DATA_VERSION. */
        uint32_t        mm_version;
        void            *mm_address;            /**< address for fixed mapping */
        size_t          mm_mapsize;                     /**< size of mmap region */
@@ -824,9 +853,16 @@ struct MDB_txn {
        /** The list of pages that became unused during this transaction.
         */
        MDB_IDL         mt_free_pgs;
+       /** The sorted list of dirty pages we temporarily wrote to disk
+        *      because the dirty list was full. page numbers in here are
+        *      shifted left by 1, deleted slots have the LSB set.
+        */
+       MDB_IDL         mt_spill_pgs;
        union {
-               MDB_ID2L        dirty_list;     /**< for write txns: modified pages */
-               MDB_reader      *reader;        /**< this thread's reader table slot or NULL */
+               /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
+               MDB_ID2L        dirty_list;
+               /** For read txns: This thread/txn's reader table slot, or NULL. */
+               MDB_reader      *reader;
        } mt_u;
        /** Array of records for each DB known in the environment. */
        MDB_dbx         *mt_dbxs;
@@ -836,9 +872,9 @@ struct MDB_txn {
  *     @ingroup internal
  * @{
  */
-#define DB_DIRTY       0x01            /**< DB was written in this txn */
-#define DB_STALE       0x02            /**< DB record is older than txnID */
-#define DB_NEW         0x04            /**< DB handle opened in this txn */
+#define DB_DIRTY       0x01            /**< DB was modified or is DUPSORT data */
+#define DB_STALE       0x02            /**< Named-DB record is older than txnID */
+#define DB_NEW         0x04            /**< Named-DB handle opened in this txn */
 #define DB_VALID       0x08            /**< DB handle is valid, see also #MDB_VALID */
 /** @} */
        /** In write txns, array of cursors for each DB */
@@ -857,14 +893,15 @@ struct MDB_txn {
 #define MDB_TXN_RDONLY         0x01            /**< read-only transaction */
 #define MDB_TXN_ERROR          0x02            /**< an error has occurred */
 #define MDB_TXN_DIRTY          0x04            /**< must write, even if dirty list is empty */
+#define MDB_TXN_SPILLS         0x08            /**< txn or a parent has spilled pages */
 /** @} */
        unsigned int    mt_flags;               /**< @ref mdb_txn */
-       /** dirty_list maxsize - # of allocated pages allowed, including in parent txns */
-       unsigned int    mt_dirty_room;
-       /** Tracks which of the two meta pages was used at the start
-        *      of this transaction.
+       /** dirty_list room: Array size - #dirty pages visible to this txn.
+        *      Includes ancestor txns' dirty pages not hidden by other txns'
+        *      dirty/spilled pages. Thus commit(nested txn) has room to merge
+        *      dirty_list into mt_parent after freeing hidden mt_parent pages.
         */
-       unsigned int    mt_toggle;
+       unsigned int    mt_dirty_room;
 };
 
 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
@@ -875,7 +912,14 @@ struct MDB_txn {
 
 struct MDB_xcursor;
 
-       /** Cursors are used for all DB operations */
+       /** Cursors are used for all DB operations.
+        *      A cursor holds a path of (page pointer, key index) from the DB
+        *      root to a position in the DB, plus other state. #MDB_DUPSORT
+        *      cursors include an xcursor to the current data item. Write txns
+        *      track their cursors and keep them up to date when data moves.
+        *      Exception: An xcursor's pointer to a #P_SUBP page can be stale.
+        *      (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
+        */
 struct MDB_cursor {
        /** Next cursor on this DB in this txn */
        MDB_cursor      *mc_next;
@@ -903,6 +947,7 @@ struct MDB_cursor {
 #define C_INITIALIZED  0x01    /**< cursor has been initialized and is valid */
 #define C_EOF  0x02                    /**< No more data */
 #define C_SUB  0x04                    /**< Cursor is a sub-cursor */
+#define C_DEL  0x08                    /**< last op was a cursor_del */
 #define C_SPLITTING    0x20            /**< Cursor is in page_split */
 #define C_UNTRACK      0x40            /**< Un-track cursor when closing */
 /** @} */
@@ -944,6 +989,8 @@ struct MDB_env {
 #define        MDB_ENV_ACTIVE  0x20000000U
        /** me_txkey is set */
 #define        MDB_ENV_TXKEY   0x10000000U
+       /** Have liveness lock in reader table */
+#define        MDB_LIVE_READER 0x08000000U
        uint32_t        me_flags;               /**< @ref mdb_env */
        unsigned int    me_psize;       /**< size of a page, from #GET_PAGESIZE */
        unsigned int    me_maxreaders;  /**< size of the reader table */
@@ -975,6 +1022,7 @@ struct MDB_env {
        /** Max size of a node on a page */
        unsigned int    me_nodemax;
 #ifdef _WIN32
+       int             me_pidquery;            /**< Used in OpenProcess */
        HANDLE          me_rmutex;              /* Windows mutexes don't reside in shared mem */
        HANDLE          me_wmutex;
 #elif defined(MDB_USE_POSIX_SEM)
@@ -985,8 +1033,8 @@ struct MDB_env {
 
        /** Nested transaction */
 typedef struct MDB_ntxn {
-       MDB_txn         mnt_txn;                /* the transaction */
-       MDB_pgstate     mnt_pgstate;    /* parent transaction's saved freestate */
+       MDB_txn         mnt_txn;                /**< the transaction */
+       MDB_pgstate     mnt_pgstate;    /**< parent transaction's saved freestate */
 } MDB_ntxn;
 
        /** max number of pages to commit in one writev() call */
@@ -1008,6 +1056,8 @@ static int  mdb_page_search_root(MDB_cursor *mc,
                            MDB_val *key, int modify);
 #define MDB_PS_MODIFY  1
 #define MDB_PS_ROOTONLY        2
+#define MDB_PS_FIRST   4
+#define MDB_PS_LAST            8
 static int  mdb_page_search(MDB_cursor *mc,
                            MDB_val *key, int flags);
 static int     mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
@@ -1093,8 +1143,10 @@ static char *const mdb_errstr[] = {
        "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
        "MDB_PAGE_FULL: Internal error - page has no more space",
        "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
-       "MDB_INCOMPATIBLE: Database flags changed or would change",
+       "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
        "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
+       "MDB_BAD_TXN: Transaction cannot recover - it must be aborted",
+       "MDB_BAD_VALSIZE: Too big key/data, key is empty, or wrong DUPFIXED size",
 };
 
 char *
@@ -1153,14 +1205,14 @@ mdb_page_list(MDB_page *mp)
        DKBUF;
 
        nkeys = NUMKEYS(mp);
-       fprintf(stderr, "Page %zu numkeys %d\n", mp->mp_pgno, nkeys);
+       fprintf(stderr, "Page %"Z"u numkeys %d\n", mp->mp_pgno, nkeys);
        for (i=0; i<nkeys; i++) {
                node = NODEPTR(mp, i);
                key.mv_size = node->mn_ksize;
                key.mv_data = node->mn_data;
                nsize = NODESIZE + NODEKSZ(node) + sizeof(indx_t);
                if (IS_BRANCH(mp)) {
-                       fprintf(stderr, "key %d: page %zu, %s\n", i, NODEPGNO(node),
+                       fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
                                DKEY(&key));
                } else {
                        if (F_ISSET(node->mn_flags, F_BIGDATA))
@@ -1191,7 +1243,7 @@ mdb_cursor_chk(MDB_cursor *mc)
 }
 #endif
 
-#if MDB_DEBUG > 2
+#if (MDB_DEBUG) > 2
 /** Count all the pages in each DB and in the freelist
  *  and make sure it matches the actual number of pages
  *  being used.
@@ -1219,7 +1271,7 @@ static void mdb_audit(MDB_txn *txn)
                        txn->mt_dbs[i].md_leaf_pages +
                        txn->mt_dbs[i].md_overflow_pages;
                if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
-                       mdb_page_search(&mc, NULL, 0);
+                       mdb_page_search(&mc, NULL, MDB_PS_FIRST);
                        do {
                                unsigned j;
                                MDB_page *mp;
@@ -1256,7 +1308,7 @@ mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
        return txn->mt_dbxs[dbi].md_dcmp(a, b);
 }
 
-/** Allocate a page.
+/** Allocate memory for a page.
  * Re-use old malloc'd pages first for singletons, otherwise just malloc.
  */
 static MDB_page *
@@ -1293,7 +1345,7 @@ mdb_page_free(MDB_env *env, MDB_page *mp)
        env->me_dpages = mp;
 }
 
-/* Free a dirty page */
+/** Free a dirty page */
 static void
 mdb_dpage_free(MDB_env *env, MDB_page *dp)
 {
@@ -1306,7 +1358,7 @@ mdb_dpage_free(MDB_env *env, MDB_page *dp)
        }
 }
 
-/* Return all dirty pages to dpage list */
+/**    Return all dirty pages to dpage list */
 static void
 mdb_dlist_free(MDB_txn *txn)
 {
@@ -1320,26 +1372,249 @@ mdb_dlist_free(MDB_txn *txn)
        dl[0].mid = 0;
 }
 
+/** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
+ * @param[in] mc A cursor handle for the current operation.
+ * @param[in] pflags Flags of the pages to update:
+ * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
+ * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
+ * @return 0 on success, non-zero on failure.
+ */
+static int
+mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
+{
+       enum { Mask = P_SUBP|P_DIRTY|P_KEEP };
+       MDB_txn *txn = mc->mc_txn;
+       MDB_cursor *m3;
+       MDB_xcursor *mx;
+       MDB_page *dp, *mp;
+       MDB_node *leaf;
+       unsigned i, j;
+       int rc = MDB_SUCCESS, level;
+
+       /* Mark pages seen by cursors */
+       if (mc->mc_flags & C_UNTRACK)
+               mc = NULL;                              /* will find mc in mt_cursors */
+       for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
+               for (; mc; mc=mc->mc_next) {
+                       if (!(mc->mc_flags & C_INITIALIZED))
+                               continue;
+                       for (m3 = mc;; m3 = &mx->mx_cursor) {
+                               mp = NULL;
+                               for (j=0; j<m3->mc_snum; j++) {
+                                       mp = m3->mc_pg[j];
+                                       if ((mp->mp_flags & Mask) == pflags)
+                                               mp->mp_flags ^= P_KEEP;
+                               }
+                               mx = m3->mc_xcursor;
+                               /* Proceed to mx if it is at a sub-database */
+                               if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
+                                       break;
+                               if (! (mp && (mp->mp_flags & P_LEAF)))
+                                       break;
+                               leaf = NODEPTR(mp, m3->mc_ki[j-1]);
+                               if (!(leaf->mn_flags & F_SUBDATA))
+                                       break;
+                       }
+               }
+               if (i == 0)
+                       break;
+       }
+
+       if (all) {
+               /* Mark dirty root pages */
+               for (i=0; i<txn->mt_numdbs; i++) {
+                       if (txn->mt_dbflags[i] & DB_DIRTY) {
+                               pgno_t pgno = txn->mt_dbs[i].md_root;
+                               if (pgno == P_INVALID)
+                                       continue;
+                               if ((rc = mdb_page_get(txn, pgno, &dp, &level)) != MDB_SUCCESS)
+                                       break;
+                               if ((dp->mp_flags & Mask) == pflags && level <= 1)
+                                       dp->mp_flags ^= P_KEEP;
+                       }
+               }
+       }
+
+       return rc;
+}
+
+static int mdb_page_flush(MDB_txn *txn, int keep);
+
+/**    Spill pages from the dirty list back to disk.
+ * This is intended to prevent running into #MDB_TXN_FULL situations,
+ * but note that they may still occur in a few cases:
+ *     1) our estimate of the txn size could be too small. Currently this
+ *      seems unlikely, except with a large number of #MDB_MULTIPLE items.
+ *     2) child txns may run out of space if their parents dirtied a
+ *      lot of pages and never spilled them. TODO: we probably should do
+ *      a preemptive spill during #mdb_txn_begin() of a child txn, if
+ *      the parent's dirty_room is below a given threshold.
+ *
+ * Otherwise, if not using nested txns, it is expected that apps will
+ * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
+ * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
+ * If the txn never references them again, they can be left alone.
+ * If the txn only reads them, they can be used without any fuss.
+ * If the txn writes them again, they can be dirtied immediately without
+ * going thru all of the work of #mdb_page_touch(). Such references are
+ * handled by #mdb_page_unspill().
+ *
+ * Also note, we never spill DB root pages, nor pages of active cursors,
+ * because we'll need these back again soon anyway. And in nested txns,
+ * we can't spill a page in a child txn if it was already spilled in a
+ * parent txn. That would alter the parent txns' data even though
+ * the child hasn't committed yet, and we'd have no way to undo it if
+ * the child aborted.
+ *
+ * @param[in] m0 cursor A cursor handle identifying the transaction and
+ *     database for which we are checking space.
+ * @param[in] key For a put operation, the key being stored.
+ * @param[in] data For a put operation, the data being stored.
+ * @return 0 on success, non-zero on failure.
+ */
+static int
+mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
+{
+       MDB_txn *txn = m0->mc_txn;
+       MDB_page *dp;
+       MDB_ID2L dl = txn->mt_u.dirty_list;
+       unsigned int i, j, need;
+       int rc;
+
+       if (m0->mc_flags & C_SUB)
+               return MDB_SUCCESS;
+
+       /* Estimate how much space this op will take */
+       i = m0->mc_db->md_depth;
+       /* Named DBs also dirty the main DB */
+       if (m0->mc_dbi > MAIN_DBI)
+               i += txn->mt_dbs[MAIN_DBI].md_depth;
+       /* For puts, roughly factor in the key+data size */
+       if (key)
+               i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
+       i += i; /* double it for good measure */
+       need = i;
+
+       if (txn->mt_dirty_room > i)
+               return MDB_SUCCESS;
+
+       if (!txn->mt_spill_pgs) {
+               txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
+               if (!txn->mt_spill_pgs)
+                       return ENOMEM;
+       } else {
+               /* purge deleted slots */
+               MDB_IDL sl = txn->mt_spill_pgs;
+               unsigned int num = sl[0];
+               j=0;
+               for (i=1; i<=num; i++) {
+                       if (!(sl[i] & 1))
+                               sl[++j] = sl[i];
+               }
+               sl[0] = j;
+       }
+
+       /* Preserve pages which may soon be dirtied again */
+       if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
+               goto done;
+
+       /* Less aggressive spill - we originally spilled the entire dirty list,
+        * with a few exceptions for cursor pages and DB root pages. But this
+        * turns out to be a lot of wasted effort because in a large txn many
+        * of those pages will need to be used again. So now we spill only 1/8th
+        * of the dirty pages. Testing revealed this to be a good tradeoff,
+        * better than 1/2, 1/4, or 1/10.
+        */
+       if (need < MDB_IDL_UM_MAX / 8)
+               need = MDB_IDL_UM_MAX / 8;
+
+       /* Save the page IDs of all the pages we're flushing */
+       /* flush from the tail forward, this saves a lot of shifting later on. */
+       for (i=dl[0].mid; i && need; i--) {
+               MDB_ID pn = dl[i].mid << 1;
+               dp = dl[i].mptr;
+               if (dp->mp_flags & P_KEEP)
+                       continue;
+               /* Can't spill twice, make sure it's not already in a parent's
+                * spill list.
+                */
+               if (txn->mt_parent) {
+                       MDB_txn *tx2;
+                       for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
+                               if (tx2->mt_spill_pgs) {
+                                       j = mdb_midl_search(tx2->mt_spill_pgs, pn);
+                                       if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
+                                               dp->mp_flags |= P_KEEP;
+                                               break;
+                                       }
+                               }
+                       }
+                       if (tx2)
+                               continue;
+               }
+               if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
+                       goto done;
+               need--;
+       }
+       mdb_midl_sort(txn->mt_spill_pgs);
+
+       /* Flush the spilled part of dirty list */
+       if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
+               goto done;
+
+       /* Reset any dirty pages we kept that page_flush didn't see */
+       rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
+
+done:
+       txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
+       return rc;
+}
+
 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
 static txnid_t
 mdb_find_oldest(MDB_txn *txn)
 {
        int i;
        txnid_t mr, oldest = txn->mt_txnid - 1;
-       MDB_reader *r = txn->mt_env->me_txns->mti_readers;
-       for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
-               if (r[i].mr_pid) {
-                       mr = r[i].mr_txnid;
-                       if (oldest > mr)
-                               oldest = mr;
+       if (txn->mt_env->me_txns) {
+               MDB_reader *r = txn->mt_env->me_txns->mti_readers;
+               for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
+                       if (r[i].mr_pid) {
+                               mr = r[i].mr_txnid;
+                               if (oldest > mr)
+                                       oldest = mr;
+                       }
                }
        }
        return oldest;
 }
 
-/** Allocate pages for writing.
+/** Add a page to the txn's dirty list */
+static void
+mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
+{
+       MDB_ID2 mid;
+       int (*insert)(MDB_ID2L, MDB_ID2 *);
+
+       if (txn->mt_env->me_flags & MDB_WRITEMAP) {
+               insert = mdb_mid2l_append;
+       } else {
+               insert = mdb_mid2l_insert;
+       }
+       mid.mid = mp->mp_pgno;
+       mid.mptr = mp;
+       insert(txn->mt_u.dirty_list, &mid);
+       txn->mt_dirty_room--;
+}
+
+/** Allocate page numbers and memory for writing.  Maintain me_pglast,
+ * me_pghead and mt_next_pgno.
+ *
  * If there are free pages available from older transactions, they
- * will be re-used first. Otherwise a new page will be allocated.
+ * are re-used first. Otherwise allocate a new page at mt_next_pgno.
+ * Do not modify the freedB, just merge freeDB records into me_pghead[]
+ * and move me_pglast to say which records were consumed.  Only this
+ * function can create me_pghead and move me_pglast/mt_next_pgno.
  * @param[in] mc cursor A cursor handle identifying the transaction and
  *     database for which we are allocating.
  * @param[in] num the number of pages to allocate.
@@ -1367,11 +1642,9 @@ mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
        pgno_t pgno, *mop = env->me_pghead;
        unsigned i, j, k, mop_len = mop ? mop[0] : 0;
        MDB_page *np;
-       MDB_ID2 mid;
        txnid_t oldest = 0, last;
        MDB_cursor_op op;
        MDB_cursor m2;
-       int (*insert)(MDB_ID2L, MDB_ID2 *);
 
        *mp = NULL;
 
@@ -1405,7 +1678,7 @@ mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
                        mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
                        if (last) {
                                op = MDB_SET_RANGE;
-                               key.mv_data = &last; /* will loop up last+1 */
+                               key.mv_data = &last; /* will look up last+1 */
                                key.mv_size = sizeof(last);
                        }
                        if (Paranoid && mc->mc_dbi == FREE_DBI)
@@ -1443,11 +1716,11 @@ mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
                        mop = env->me_pghead;
                }
                env->me_pglast = last;
-#if MDB_DEBUG > 1
-               DPRINTF("IDL read txn %zu root %zu num %u",
-                               last, txn->mt_dbs[FREE_DBI].md_root, i);
+#if (MDB_DEBUG) > 1
+               DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
+                       last, txn->mt_dbs[FREE_DBI].md_root, i));
                for (k = i; k; k--)
-                       DPRINTF("IDL %zu", idl[k]);
+                       DPRINTF(("IDL %"Z"u", idl[k]));
 #endif
                /* Merge in descending sorted order */
                j = mop_len;
@@ -1474,11 +1747,9 @@ mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
 search_done:
        if (env->me_flags & MDB_WRITEMAP) {
                np = (MDB_page *)(env->me_map + env->me_psize * pgno);
-               insert = mdb_mid2l_append;
        } else {
                if (!(np = mdb_page_malloc(txn, num)))
                        return ENOMEM;
-               insert = mdb_mid2l_insert;
        }
        if (i) {
                mop[0] = mop_len -= num;
@@ -1488,10 +1759,8 @@ search_done:
        } else {
                txn->mt_next_pgno = pgno + num;
        }
-       mid.mid = np->mp_pgno = pgno;
-       mid.mptr = np;
-       insert(txn->mt_u.dirty_list, &mid);
-       txn->mt_dirty_room--;
+       np->mp_pgno = pgno;
+       mdb_page_dirty(txn, np);
        *mp = np;
 
        return MDB_SUCCESS;
@@ -1521,6 +1790,68 @@ mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
        }
 }
 
+/** Pull a page off the txn's spill list, if present.
+ * If a page being referenced was spilled to disk in this txn, bring
+ * it back and make it dirty/writable again.
+ * @param[in] txn the transaction handle.
+ * @param[in] mp the page being referenced.
+ * @param[out] ret the writable page, if any. ret is unchanged if
+ * mp wasn't spilled.
+ */
+static int
+mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
+{
+       MDB_env *env = txn->mt_env;
+       const MDB_txn *tx2;
+       unsigned x;
+       pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
+
+       for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
+               if (!tx2->mt_spill_pgs)
+                       continue;
+               x = mdb_midl_search(tx2->mt_spill_pgs, pn);
+               if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
+                       MDB_page *np;
+                       int num;
+                       if (txn->mt_dirty_room == 0)
+                               return MDB_TXN_FULL;
+                       if (IS_OVERFLOW(mp))
+                               num = mp->mp_pages;
+                       else
+                               num = 1;
+                       if (env->me_flags & MDB_WRITEMAP) {
+                               np = mp;
+                       } else {
+                               np = mdb_page_malloc(txn, num);
+                               if (!np)
+                                       return ENOMEM;
+                               if (num > 1)
+                                       memcpy(np, mp, num * env->me_psize);
+                               else
+                                       mdb_page_copy(np, mp, env->me_psize);
+                       }
+                       if (tx2 == txn) {
+                               /* If in current txn, this page is no longer spilled.
+                                * If it happens to be the last page, truncate the spill list.
+                                * Otherwise mark it as deleted by setting the LSB.
+                                */
+                               if (x == txn->mt_spill_pgs[0])
+                                       txn->mt_spill_pgs[0]--;
+                               else
+                                       txn->mt_spill_pgs[x] |= 1;
+                       }       /* otherwise, if belonging to a parent txn, the
+                                * page remains spilled until child commits
+                                */
+
+                       mdb_page_dirty(txn, np);
+                       np->mp_flags |= P_DIRTY;
+                       *ret = np;
+                       break;
+               }
+       }
+       return MDB_SUCCESS;
+}
+
 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
  * @param[in] mc cursor pointing to the page to be touched
  * @return 0 on success, non-zero on failure.
@@ -1531,16 +1862,24 @@ mdb_page_touch(MDB_cursor *mc)
        MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
        MDB_txn *txn = mc->mc_txn;
        MDB_cursor *m2, *m3;
-       MDB_dbi dbi;
        pgno_t  pgno;
        int rc;
 
        if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
+               if (txn->mt_flags & MDB_TXN_SPILLS) {
+                       np = NULL;
+                       rc = mdb_page_unspill(txn, mp, &np);
+                       if (rc)
+                               return rc;
+                       if (np)
+                               goto done;
+               }
                if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
                        (rc = mdb_page_alloc(mc, 1, &np)))
                        return rc;
                pgno = np->mp_pgno;
-               DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi,mp->mp_pgno,pgno);
+               DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
+                       mp->mp_pgno, pgno));
                assert(mp->mp_pgno != pgno);
                mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
                /* Update the parent page, if any, to point to the new page */
@@ -1583,19 +1922,19 @@ mdb_page_touch(MDB_cursor *mc)
        np->mp_pgno = pgno;
        np->mp_flags |= P_DIRTY;
 
+done:
        /* Adjust cursors pointing to mp */
        mc->mc_pg[mc->mc_top] = np;
-       dbi = mc->mc_dbi;
+       m2 = txn->mt_cursors[mc->mc_dbi];
        if (mc->mc_flags & C_SUB) {
-               dbi--;
-               for (m2 = txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
+               for (; m2; m2=m2->mc_next) {
                        m3 = &m2->mc_xcursor->mx_cursor;
                        if (m3->mc_snum < mc->mc_snum) continue;
                        if (m3->mc_pg[mc->mc_top] == mp)
                                m3->mc_pg[mc->mc_top] = np;
                }
        } else {
-               for (m2 = txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
+               for (; m2; m2=m2->mc_next) {
                        if (m2->mc_snum < mc->mc_snum) continue;
                        if (m2->mc_pg[mc->mc_top] == mp) {
                                m2->mc_pg[mc->mc_top] = np;
@@ -1705,18 +2044,73 @@ mdb_cursors_close(MDB_txn *txn, unsigned merge)
                                }
                                mc = bk;
                        }
+                       /* Only malloced cursors are permanently tracked. */
                        free(mc);
                }
                cursors[i] = NULL;
        }
 }
 
-#ifdef MDB_DEBUG_SKIP
+#if !(MDB_DEBUG)
 #define mdb_txn_reset0(txn, act) mdb_txn_reset0(txn)
 #endif
 static void
 mdb_txn_reset0(MDB_txn *txn, const char *act);
 
+#if !(MDB_PIDLOCK)             /* Currently the same as defined(_WIN32) */
+enum Pidlock_op {
+       Pidset, Pidcheck
+};
+#else
+enum Pidlock_op {
+       Pidset = F_SETLK, Pidcheck = F_GETLK
+};
+#endif
+
+/** Set or check a pid lock. Set returns 0 on success.
+ * Check returns 0 if the process is certainly dead, nonzero if it may
+ * be alive (the lock exists or an error happened so we do not know).
+ *
+ * On Windows Pidset is a no-op, we merely check for the existence
+ * of the process with the given pid. On POSIX we use a single byte
+ * lock on the lockfile, set at an offset equal to the pid.
+ */
+static int
+mdb_reader_pid(MDB_env *env, enum Pidlock_op op, pid_t pid)
+{
+#if !(MDB_PIDLOCK)             /* Currently the same as defined(_WIN32) */
+       int ret = 0;
+       HANDLE h;
+       if (op == Pidcheck) {
+               h = OpenProcess(env->me_pidquery, FALSE, pid);
+               /* No documented "no such process" code, but other program use this: */
+               if (!h)
+                       return ErrCode() != ERROR_INVALID_PARAMETER;
+               /* A process exists until all handles to it close. Has it exited? */
+               ret = WaitForSingleObject(h, 0) != 0;
+               CloseHandle(h);
+       }
+       return ret;
+#else
+       for (;;) {
+               int rc;
+               struct flock lock_info;
+               memset(&lock_info, 0, sizeof(lock_info));
+               lock_info.l_type = F_WRLCK;
+               lock_info.l_whence = SEEK_SET;
+               lock_info.l_start = pid;
+               lock_info.l_len = 1;
+               if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
+                       if (op == F_GETLK && lock_info.l_type != F_UNLCK)
+                               rc = -1;
+               } else if ((rc = ErrCode()) == EINTR) {
+                       continue;
+               }
+               return rc;
+       }
+#endif
+}
+
 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
  * @param[in] txn the transaction handle to initialize
  * @return 0 on success, non-zero on failure.
@@ -1725,7 +2119,9 @@ static int
 mdb_txn_renew0(MDB_txn *txn)
 {
        MDB_env *env = txn->mt_env;
-       unsigned int i;
+       MDB_txninfo *ti = env->me_txns;
+       MDB_meta *meta;
+       unsigned int i, nr;
        uint16_t x;
        int rc, new_notls = 0;
 
@@ -1734,9 +2130,9 @@ mdb_txn_renew0(MDB_txn *txn)
        txn->mt_dbxs = env->me_dbxs;    /* mostly static anyway */
 
        if (txn->mt_flags & MDB_TXN_RDONLY) {
-               if (!env->me_txns) {
-                       i = mdb_env_pick_meta(env);
-                       txn->mt_txnid = env->me_metas[i]->mm_txnid;
+               if (!ti) {
+                       meta = env->me_metas[ mdb_env_pick_meta(env) ];
+                       txn->mt_txnid = meta->mm_txnid;
                        txn->mt_u.reader = NULL;
                } else {
                        MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
@@ -1748,37 +2144,53 @@ mdb_txn_renew0(MDB_txn *txn)
                                pid_t pid = env->me_pid;
                                pthread_t tid = pthread_self();
 
+                               if (!(env->me_flags & MDB_LIVE_READER)) {
+                                       rc = mdb_reader_pid(env, Pidset, pid);
+                                       if (rc) {
+                                               UNLOCK_MUTEX_R(env);
+                                               return rc;
+                                       }
+                                       env->me_flags |= MDB_LIVE_READER;
+                               }
+
                                LOCK_MUTEX_R(env);
-                               for (i=0; i<env->me_txns->mti_numreaders; i++)
-                                       if (env->me_txns->mti_readers[i].mr_pid == 0)
+                               nr = ti->mti_numreaders;
+                               for (i=0; i<nr; i++)
+                                       if (ti->mti_readers[i].mr_pid == 0)
                                                break;
                                if (i == env->me_maxreaders) {
                                        UNLOCK_MUTEX_R(env);
                                        return MDB_READERS_FULL;
                                }
-                               env->me_txns->mti_readers[i].mr_pid = pid;
-                               env->me_txns->mti_readers[i].mr_tid = tid;
-                               if (i >= env->me_txns->mti_numreaders)
-                                       env->me_txns->mti_numreaders = i+1;
+                               ti->mti_readers[i].mr_pid = pid;
+                               ti->mti_readers[i].mr_tid = tid;
+                               if (i == nr)
+                                       ti->mti_numreaders = ++nr;
                                /* Save numreaders for un-mutexed mdb_env_close() */
-                               env->me_numreaders = env->me_txns->mti_numreaders;
+                               env->me_numreaders = nr;
                                UNLOCK_MUTEX_R(env);
-                               r = &env->me_txns->mti_readers[i];
+
+                               r = &ti->mti_readers[i];
                                new_notls = (env->me_flags & MDB_NOTLS);
                                if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
                                        r->mr_pid = 0;
                                        return rc;
                                }
                        }
-                       txn->mt_txnid = r->mr_txnid = env->me_txns->mti_txnid;
+                       txn->mt_txnid = r->mr_txnid = ti->mti_txnid;
                        txn->mt_u.reader = r;
+                       meta = env->me_metas[txn->mt_txnid & 1];
                }
-               txn->mt_toggle = txn->mt_txnid & 1;
        } else {
-               LOCK_MUTEX_W(env);
+               if (ti) {
+                       LOCK_MUTEX_W(env);
 
-               txn->mt_txnid = env->me_txns->mti_txnid;
-               txn->mt_toggle = txn->mt_txnid & 1;
+                       txn->mt_txnid = ti->mti_txnid;
+                       meta = env->me_metas[txn->mt_txnid & 1];
+               } else {
+                       meta = env->me_metas[ mdb_env_pick_meta(env) ];
+                       txn->mt_txnid = meta->mm_txnid;
+               }
                txn->mt_txnid++;
 #if MDB_DEBUG
                if (txn->mt_txnid == mdb_debug_start)
@@ -1789,14 +2201,15 @@ mdb_txn_renew0(MDB_txn *txn)
                txn->mt_u.dirty_list[0].mid = 0;
                txn->mt_free_pgs = env->me_free_pgs;
                txn->mt_free_pgs[0] = 0;
+               txn->mt_spill_pgs = NULL;
                env->me_txn = txn;
        }
 
        /* Copy the DB info and flags */
-       memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
+       memcpy(txn->mt_dbs, meta->mm_dbs, 2 * sizeof(MDB_db));
 
        /* Moved to here to avoid a data race in read TXNs */
-       txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
+       txn->mt_next_pgno = meta->mm_last_pg+1;
 
        for (i=2; i<txn->mt_numdbs; i++) {
                x = env->me_dbflags[i];
@@ -1832,9 +2245,9 @@ mdb_txn_renew(MDB_txn *txn)
 
        rc = mdb_txn_renew0(txn);
        if (rc == MDB_SUCCESS) {
-               DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
+               DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
                        txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
-                       (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
+                       (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
        }
        return rc;
 }
@@ -1855,10 +2268,11 @@ mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
        if (parent) {
                /* Nested transactions: Max 1 child, write txns only, no writemap */
                if (parent->mt_child ||
-                       (flags & MDB_RDONLY) || (parent->mt_flags & MDB_TXN_RDONLY) ||
+                       (flags & MDB_RDONLY) ||
+                       (parent->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR)) ||
                        (env->me_flags & MDB_WRITEMAP))
                {
-                       return EINVAL;
+                       return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
                }
                tsize = sizeof(MDB_ntxn);
        }
@@ -1867,7 +2281,7 @@ mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
                size += env->me_maxdbs * sizeof(MDB_cursor *);
 
        if ((txn = calloc(1, size)) == NULL) {
-               DPRINTF("calloc: %s", strerror(ErrCode()));
+               DPRINTF(("calloc: %s", strerror(ErrCode())));
                return ENOMEM;
        }
        txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
@@ -1891,9 +2305,9 @@ mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
                        return ENOMEM;
                }
                txn->mt_txnid = parent->mt_txnid;
-               txn->mt_toggle = parent->mt_toggle;
                txn->mt_dirty_room = parent->mt_dirty_room;
                txn->mt_u.dirty_list[0].mid = 0;
+               txn->mt_spill_pgs = NULL;
                txn->mt_next_pgno = parent->mt_next_pgno;
                parent->mt_child = txn;
                txn->mt_parent = parent;
@@ -1926,14 +2340,21 @@ mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
                free(txn);
        else {
                *ret = txn;
-               DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
+               DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
                        txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
-                       (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
+                       (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
        }
 
        return rc;
 }
 
+MDB_env *
+mdb_txn_env(MDB_txn *txn)
+{
+       if(!txn) return NULL;
+       return txn->mt_env;
+}
+
 /** Export or close DBI handles opened in this txn. */
 static void
 mdb_dbis_update(MDB_txn *txn, int keep)
@@ -1963,6 +2384,7 @@ mdb_dbis_update(MDB_txn *txn, int keep)
 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
  * May be called twice for readonly txns: First reset it, then abort.
  * @param[in] txn the transaction handle to reset
+ * @param[in] act why the transaction is being reset
  */
 static void
 mdb_txn_reset0(MDB_txn *txn, const char *act)
@@ -1972,9 +2394,9 @@ mdb_txn_reset0(MDB_txn *txn, const char *act)
        /* Close any DBI handles opened in this txn */
        mdb_dbis_update(txn, 0);
 
-       DPRINTF("%s txn %zu%c %p on mdbenv %p, root page %zu",
+       DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
                act, txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
-               (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
+               (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
 
        if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
                if (txn->mt_u.reader) {
@@ -1996,6 +2418,7 @@ mdb_txn_reset0(MDB_txn *txn, const char *act)
                        txn->mt_parent->mt_child = NULL;
                        env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
                        mdb_midl_free(txn->mt_free_pgs);
+                       mdb_midl_free(txn->mt_spill_pgs);
                        free(txn->mt_u.dirty_list);
                        return;
                }
@@ -2007,7 +2430,8 @@ mdb_txn_reset0(MDB_txn *txn, const char *act)
 
                env->me_txn = NULL;
                /* The writer mutex was locked in mdb_txn_begin. */
-               UNLOCK_MUTEX_W(env);
+               if (env->me_txns)
+                       UNLOCK_MUTEX_W(env);
        }
 }
 
@@ -2062,7 +2486,7 @@ mdb_freelist_save(MDB_txn *txn)
 
        if (env->me_pghead) {
                /* Make sure first page of freeDB is touched and on freelist */
-               rc = mdb_page_search(&mc, NULL, MDB_PS_MODIFY);
+               rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
                if (rc && rc != MDB_NOTFOUND)
                        return rc;
        }
@@ -2090,9 +2514,7 @@ mdb_freelist_save(MDB_txn *txn)
                if (freecnt < txn->mt_free_pgs[0]) {
                        if (!freecnt) {
                                /* Make sure last page of freeDB is touched and on freelist */
-                               key.mv_size = MDB_MAXKEYSIZE+1;
-                               key.mv_data = NULL;
-                               rc = mdb_page_search(&mc, &key, MDB_PS_MODIFY);
+                               rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
                                if (rc && rc != MDB_NOTFOUND)
                                        return rc;
                        }
@@ -2111,13 +2533,13 @@ mdb_freelist_save(MDB_txn *txn)
                        } while (freecnt < free_pgs[0]);
                        mdb_midl_sort(free_pgs);
                        memcpy(data.mv_data, free_pgs, data.mv_size);
-#if MDB_DEBUG > 1
+#if (MDB_DEBUG) > 1
                        {
                                unsigned int i = free_pgs[0];
-                               DPRINTF("IDL write txn %zu root %zu num %u",
-                                       txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i);
+                               DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
+                                       txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
                                for (; i; i--)
-                                       DPRINTF("IDL %zu", free_pgs[i]);
+                                       DPRINTF(("IDL %"Z"u", free_pgs[i]));
                        }
 #endif
                        continue;
@@ -2159,39 +2581,49 @@ mdb_freelist_save(MDB_txn *txn)
                total_room += head_room;
        }
 
-       /* Fill in the reserved, touched me_pghead records. Avoid write ops
-        * so they cannot rearrange anything, just read the destinations.
-        */
+       /* Fill in the reserved me_pghead records */
        rc = MDB_SUCCESS;
        if (mop_len) {
                MDB_val key, data;
 
-               mop += mop_len + 1;
+               mop += mop_len;
                rc = mdb_cursor_first(&mc, &key, &data);
                for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
-                       MDB_IDL dest = data.mv_data;
+                       unsigned flags = MDB_CURRENT;
+                       txnid_t id = *(txnid_t *)key.mv_data;
                        ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
+                       MDB_ID save;
 
-                       assert(len >= 0 && *(txnid_t*)key.mv_data <= env->me_pglast);
-                       if (len > mop_len)
+                       assert(len >= 0 && id <= env->me_pglast);
+                       key.mv_data = &id;
+                       if (len > mop_len) {
                                len = mop_len;
-                       *dest++ = len;
-                       memcpy(dest, mop -= len, len * sizeof(MDB_ID));
-                       if (! (mop_len -= len))
+                               data.mv_size = (len + 1) * sizeof(MDB_ID);
+                               flags = 0;
+                       }
+                       data.mv_data = mop -= len;
+                       save = mop[0];
+                       mop[0] = len;
+                       rc = mdb_cursor_put(&mc, &key, &data, flags);
+                       mop[0] = save;
+                       if (rc || !(mop_len -= len))
                                break;
                }
        }
        return rc;
 }
 
-/** Flush dirty pages to the map, after clearing their dirty flag.
+/** Flush (some) dirty pages to the map, after clearing their dirty flag.
+ * @param[in] txn the transaction that's being committed
+ * @param[in] keep number of initial pages in dirty_list to keep dirty.
+ * @return 0 on success, non-zero on failure.
  */
 static int
-mdb_page_flush(MDB_txn *txn)
+mdb_page_flush(MDB_txn *txn, int keep)
 {
        MDB_env         *env = txn->mt_env;
        MDB_ID2L        dl = txn->mt_u.dirty_list;
-       unsigned        psize = env->me_psize;
+       unsigned        psize = env->me_psize, j;
        int                     i, pagecount = dl[0].mid, rc;
        size_t          size = 0, pos = 0;
        pgno_t          pgno = 0;
@@ -2205,20 +2637,33 @@ mdb_page_flush(MDB_txn *txn)
        int                     n = 0;
 #endif
 
+       j = i = keep;
+
        if (env->me_flags & MDB_WRITEMAP) {
                /* Clear dirty flags */
-               for (i = pagecount; i; i--) {
+               while (++i <= pagecount) {
                        dp = dl[i].mptr;
+                       /* Don't flush this page yet */
+                       if (dp->mp_flags & P_KEEP) {
+                               dp->mp_flags ^= P_KEEP;
+                               dl[++j] = dl[i];
+                               continue;
+                       }
                        dp->mp_flags &= ~P_DIRTY;
                }
-               dl[0].mid = 0;
-               return MDB_SUCCESS;
+               goto done;
        }
 
        /* Write the pages */
-       for (i = 1;; i++) {
-               if (i <= pagecount) {
+       for (;;) {
+               if (++i <= pagecount) {
                        dp = dl[i].mptr;
+                       /* Don't flush this page yet */
+                       if (dp->mp_flags & P_KEEP) {
+                               dp->mp_flags ^= P_KEEP;
+                               dl[i].mid = 0;
+                               continue;
+                       }
                        pgno = dl[i].mid;
                        /* clear dirty flag */
                        dp->mp_flags &= ~P_DIRTY;
@@ -2236,13 +2681,13 @@ mdb_page_flush(MDB_txn *txn)
                 * the write offset, to at least save the overhead of a Seek
                 * system call.
                 */
-               DPRINTF("committing page %zu", pgno);
+               DPRINTF(("committing page %"Z"u", pgno));
                memset(&ov, 0, sizeof(ov));
                ov.Offset = pos & 0xffffffff;
                ov.OffsetHigh = pos >> 16 >> 16;
                if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
                        rc = ErrCode();
-                       DPRINTF("WriteFile: %d", rc);
+                       DPRINTF(("WriteFile: %d", rc));
                        return rc;
                }
 #else
@@ -2258,7 +2703,7 @@ mdb_page_flush(MDB_txn *txn)
                                } else {
                                        if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
                                                rc = ErrCode();
-                                               DPRINTF("lseek: %s", strerror(rc));
+                                               DPRINTF(("lseek: %s", strerror(rc)));
                                                return rc;
                                        }
                                        wres = writev(env->me_fd, iov, n);
@@ -2267,7 +2712,7 @@ mdb_page_flush(MDB_txn *txn)
                                if (wres != wsize) {
                                        if (wres < 0) {
                                                rc = ErrCode();
-                                               DPRINTF("Write error: %s", strerror(rc));
+                                               DPRINTF(("Write error: %s", strerror(rc)));
                                        } else {
                                                rc = EIO; /* TODO: Use which error code? */
                                                DPUTS("short write, filesystem full?");
@@ -2281,7 +2726,7 @@ mdb_page_flush(MDB_txn *txn)
                        wpos = pos;
                        wsize = 0;
                }
-               DPRINTF("committing page %zu", pgno);
+               DPRINTF(("committing page %"Z"u", pgno));
                next_pos = pos + size;
                iov[n].iov_len = size;
                iov[n].iov_base = (char *)dp;
@@ -2290,8 +2735,21 @@ mdb_page_flush(MDB_txn *txn)
 #endif /* _WIN32 */
        }
 
-       mdb_dlist_free(txn);
+       for (i = keep; ++i <= pagecount; ) {
+               dp = dl[i].mptr;
+               /* This is a page we skipped above */
+               if (!dl[i].mid) {
+                       dl[++j] = dl[i];
+                       dl[j].mid = dp->mp_pgno;
+                       continue;
+               }
+               mdb_dpage_free(env, dp);
+       }
 
+done:
+       i--;
+       txn->mt_dirty_room += i - j;
+       dl[0].mid = j;
        return MDB_SUCCESS;
 }
 
@@ -2325,20 +2783,24 @@ mdb_txn_commit(MDB_txn *txn)
                DPUTS("error flag is set, can't commit");
                if (txn->mt_parent)
                        txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
-               rc = EINVAL;
+               rc = MDB_BAD_TXN;
                goto fail;
        }
 
        if (txn->mt_parent) {
                MDB_txn *parent = txn->mt_parent;
-               unsigned x, y, len;
                MDB_ID2L dst, src;
+               MDB_IDL pspill;
+               unsigned x, y, len, ps_len;
 
                /* Append our free list to parent's */
                rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
                if (rc)
                        goto fail;
                mdb_midl_free(txn->mt_free_pgs);
+               /* Failures after this must either undo the changes
+                * to the parent or set MDB_TXN_ERROR in the parent.
+                */
 
                parent->mt_next_pgno = txn->mt_next_pgno;
                parent->mt_flags = txn->mt_flags;
@@ -2348,17 +2810,38 @@ mdb_txn_commit(MDB_txn *txn)
 
                /* Update parent's DB table. */
                memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
-               txn->mt_parent->mt_numdbs = txn->mt_numdbs;
-               txn->mt_parent->mt_dbflags[0] = txn->mt_dbflags[0];
-               txn->mt_parent->mt_dbflags[1] = txn->mt_dbflags[1];
+               parent->mt_numdbs = txn->mt_numdbs;
+               parent->mt_dbflags[0] = txn->mt_dbflags[0];
+               parent->mt_dbflags[1] = txn->mt_dbflags[1];
                for (i=2; i<txn->mt_numdbs; i++) {
                        /* preserve parent's DB_NEW status */
-                       x = txn->mt_parent->mt_dbflags[i] & DB_NEW;
-                       txn->mt_parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
+                       x = parent->mt_dbflags[i] & DB_NEW;
+                       parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
                }
 
-               dst = txn->mt_parent->mt_u.dirty_list;
+               dst = parent->mt_u.dirty_list;
                src = txn->mt_u.dirty_list;
+               /* Remove anything in our dirty list from parent's spill list */
+               if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
+                       x = y = ps_len;
+                       pspill[0] = (pgno_t)-1;
+                       /* Mark our dirty pages as deleted in parent spill list */
+                       for (i=0, len=src[0].mid; ++i <= len; ) {
+                               MDB_ID pn = src[i].mid << 1;
+                               while (pn > pspill[x])
+                                       x--;
+                               if (pn == pspill[x]) {
+                                       pspill[x] = 1;
+                                       y = --x;
+                               }
+                       }
+                       /* Squash deleted pagenums if we deleted any */
+                       for (x=y; ++x <= ps_len; )
+                               if (!(pspill[x] & 1))
+                                       pspill[++y] = pspill[x];
+                       pspill[0] = y;
+               }
+
                /* Find len = length of merging our dirty list with parent's */
                x = dst[0].mid;
                dst[0].mid = 0;         /* simplify loops */
@@ -2390,11 +2873,23 @@ mdb_txn_commit(MDB_txn *txn)
                dst[0].mid = len;
                free(txn->mt_u.dirty_list);
                parent->mt_dirty_room = txn->mt_dirty_room;
+               if (txn->mt_spill_pgs) {
+                       if (parent->mt_spill_pgs) {
+                               /* TODO: Prevent failure here, so parent does not fail */
+                               rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
+                               if (rc)
+                                       parent->mt_flags |= MDB_TXN_ERROR;
+                               mdb_midl_free(txn->mt_spill_pgs);
+                               mdb_midl_sort(parent->mt_spill_pgs);
+                       } else {
+                               parent->mt_spill_pgs = txn->mt_spill_pgs;
+                       }
+               }
 
-               txn->mt_parent->mt_child = NULL;
+               parent->mt_child = NULL;
                mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
                free(txn);
-               return MDB_SUCCESS;
+               return rc;
        }
 
        if (txn != env->me_txn) {
@@ -2405,11 +2900,12 @@ mdb_txn_commit(MDB_txn *txn)
 
        mdb_cursors_close(txn, 0);
 
-       if (!txn->mt_u.dirty_list[0].mid && !(txn->mt_flags & MDB_TXN_DIRTY))
+       if (!txn->mt_u.dirty_list[0].mid &&
+               !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
                goto done;
 
-       DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
-           txn->mt_txnid, (void *)txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
+       DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
+           txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
 
        /* Update DB root pointers */
        if (txn->mt_numdbs > 2) {
@@ -2438,11 +2934,11 @@ mdb_txn_commit(MDB_txn *txn)
        if (mdb_midl_shrink(&txn->mt_free_pgs))
                env->me_free_pgs = txn->mt_free_pgs;
 
-#if MDB_DEBUG > 2
+#if (MDB_DEBUG) > 2
        mdb_audit(txn);
 #endif
 
-       if ((rc = mdb_page_flush(txn)) ||
+       if ((rc = mdb_page_flush(txn, 0)) ||
                (rc = mdb_env_sync(env, 0)) ||
                (rc = mdb_env_write_meta(txn)))
                goto fail;
@@ -2452,7 +2948,8 @@ done:
        env->me_txn = NULL;
        mdb_dbis_update(txn, 1);
 
-       UNLOCK_MUTEX_W(env);
+       if (env->me_txns)
+               UNLOCK_MUTEX_W(env);
        free(txn);
 
        return MDB_SUCCESS;
@@ -2487,6 +2984,8 @@ mdb_env_read_header(MDB_env *env, MDB_meta *meta)
                memset(&ov, 0, sizeof(ov));
                ov.Offset = off;
                rc = ReadFile(env->me_fd,&pbuf,MDB_PAGESIZE,&len,&ov) ? (int)len : -1;
+               if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
+                       rc = 0;
 #else
                rc = pread(env->me_fd, &pbuf, MDB_PAGESIZE, off);
 #endif
@@ -2494,14 +2993,14 @@ mdb_env_read_header(MDB_env *env, MDB_meta *meta)
                        if (rc == 0 && off == 0)
                                return ENOENT;
                        rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
-                       DPRINTF("read: %s", mdb_strerror(rc));
+                       DPRINTF(("read: %s", mdb_strerror(rc)));
                        return rc;
                }
 
                p = (MDB_page *)&pbuf;
 
                if (!F_ISSET(p->mp_flags, P_META)) {
-                       DPRINTF("page %zu not a meta page", p->mp_pgno);
+                       DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
                        return MDB_INVALID;
                }
 
@@ -2511,9 +3010,9 @@ mdb_env_read_header(MDB_env *env, MDB_meta *meta)
                        return MDB_INVALID;
                }
 
-               if (m->mm_version != MDB_VERSION) {
-                       DPRINTF("database is version %u, expected version %u",
-                               m->mm_version, MDB_VERSION);
+               if (m->mm_version != MDB_DATA_VERSION) {
+                       DPRINTF(("database is version %u, expected version %u",
+                               m->mm_version, MDB_DATA_VERSION));
                        return MDB_VERSION_MISMATCH;
                }
 
@@ -2534,13 +3033,26 @@ mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
        MDB_page *p, *q;
        int rc;
        unsigned int     psize;
+#ifdef _WIN32
+       DWORD len;
+       OVERLAPPED ov;
+       memset(&ov, 0, sizeof(ov));
+#define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
+       ov.Offset = pos;        \
+       rc = WriteFile(fd, ptr, size, &len, &ov);       } while(0)
+#else
+       int len;
+#define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
+       len = pwrite(fd, ptr, size, pos);       \
+       rc = (len >= 0); } while(0)
+#endif
 
        DPUTS("writing new meta page");
 
-       GET_PAGESIZE(psize);
+       psize = env->me_psize;
 
        meta->mm_magic = MDB_MAGIC;
-       meta->mm_version = MDB_VERSION;
+       meta->mm_version = MDB_DATA_VERSION;
        meta->mm_mapsize = env->me_mapsize;
        meta->mm_psize = psize;
        meta->mm_last_pg = 1;
@@ -2559,18 +3071,13 @@ mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
        q->mp_flags = P_META;
        *(MDB_meta *)METADATA(q) = *meta;
 
-#ifdef _WIN32
-       {
-               DWORD len;
-               OVERLAPPED ov;
-               memset(&ov, 0, sizeof(ov));
-               rc = WriteFile(env->me_fd, p, psize * 2, &len, &ov);
-               rc = rc ? (len == psize * 2 ? MDB_SUCCESS : EIO) : ErrCode();
-       }
-#else
-       rc = pwrite(env->me_fd, p, psize * 2, 0);
-       rc = (rc == (int)psize * 2) ? MDB_SUCCESS : rc < 0 ? ErrCode() : EIO;
-#endif
+       DO_PWRITE(rc, env->me_fd, p, psize * 2, len, 0);
+       if (!rc)
+               rc = ErrCode();
+       else if ((unsigned) len == psize * 2)
+               rc = MDB_SUCCESS;
+       else
+               rc = ENOSPC;
        free(p);
        return rc;
 }
@@ -2597,9 +3104,9 @@ mdb_env_write_meta(MDB_txn *txn)
        assert(txn != NULL);
        assert(txn->mt_env != NULL);
 
-       toggle = !txn->mt_toggle;
-       DPRINTF("writing meta page %d for root page %zu",
-               toggle, txn->mt_dbs[MAIN_DBI].md_root);
+       toggle = txn->mt_txnid & 1;
+       DPRINTF(("writing meta page %d for root page %"Z"u",
+               toggle, txn->mt_dbs[MAIN_DBI].md_root));
 
        env = txn->mt_env;
        mp = env->me_metas[toggle];
@@ -2675,6 +3182,7 @@ mdb_env_write_meta(MDB_txn *txn)
                WriteFile(env->me_fd, ptr, len, NULL, &ov);
 #else
                r2 = pwrite(env->me_fd, ptr, len, off);
+               (void)r2;       /* Silence warnings. We don't care about pwrite's return value */
 #endif
 fail:
                env->me_flags |= MDB_FATAL_ERROR;
@@ -2687,7 +3195,8 @@ done:
         * readers will get consistent data regardless of how fresh or
         * how stale their view of these values is.
         */
-       env->me_txns->mti_txnid = txn->mt_txnid;
+       if (env->me_txns)
+               env->me_txns->mti_txnid = txn->mt_txnid;
 
        return MDB_SUCCESS;
 }
@@ -2726,11 +3235,105 @@ mdb_env_create(MDB_env **env)
        return MDB_SUCCESS;
 }
 
+static int
+mdb_env_map(MDB_env *env, void *addr, int newsize)
+{
+       MDB_page *p;
+       unsigned int flags = env->me_flags;
+#ifdef _WIN32
+       int rc;
+       HANDLE mh;
+       LONG sizelo, sizehi;
+       sizelo = env->me_mapsize & 0xffffffff;
+       sizehi = env->me_mapsize >> 16 >> 16; /* only needed on Win64 */
+
+       /* Windows won't create mappings for zero length files.
+        * Just allocate the maxsize right now.
+        */
+       if (newsize) {
+               if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
+                       || !SetEndOfFile(env->me_fd)
+                       || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
+                       return ErrCode();
+       }
+       mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
+               PAGE_READWRITE : PAGE_READONLY,
+               sizehi, sizelo, NULL);
+       if (!mh)
+               return ErrCode();
+       env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
+               FILE_MAP_WRITE : FILE_MAP_READ,
+               0, 0, env->me_mapsize, addr);
+       rc = env->me_map ? 0 : ErrCode();
+       CloseHandle(mh);
+       if (rc)
+               return rc;
+#else
+       int prot = PROT_READ;
+       if (flags & MDB_WRITEMAP) {
+               prot |= PROT_WRITE;
+               if (ftruncate(env->me_fd, env->me_mapsize) < 0)
+                       return ErrCode();
+       }
+       env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
+               env->me_fd, 0);
+       if (env->me_map == MAP_FAILED) {
+               env->me_map = NULL;
+               return ErrCode();
+       }
+       /* Turn off readahead. It's harmful when the DB is larger than RAM. */
+#ifdef MADV_RANDOM
+       madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
+#else
+#ifdef POSIX_MADV_RANDOM
+       posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
+#endif /* POSIX_MADV_RANDOM */
+#endif /* MADV_RANDOM */
+#endif /* _WIN32 */
+
+       /* Can happen because the address argument to mmap() is just a
+        * hint.  mmap() can pick another, e.g. if the range is in use.
+        * The MAP_FIXED flag would prevent that, but then mmap could
+        * instead unmap existing pages to make room for the new map.
+        */
+       if (addr && env->me_map != addr)
+               return EBUSY;   /* TODO: Make a new MDB_* error code? */
+
+       p = (MDB_page *)env->me_map;
+       env->me_metas[0] = METADATA(p);
+       env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
+
+       return MDB_SUCCESS;
+}
+
 int
 mdb_env_set_mapsize(MDB_env *env, size_t size)
 {
-       if (env->me_map)
-               return EINVAL;
+       /* If env is already open, caller is responsible for making
+        * sure there are no active txns.
+        */
+       if (env->me_map) {
+               int rc;
+               void *old;
+               if (env->me_txn)
+                       return EINVAL;
+               if (!size)
+                       size = env->me_metas[mdb_env_pick_meta(env)]->mm_mapsize;
+               else if (size < env->me_mapsize) {
+                       /* If the configured size is smaller, make sure it's
+                        * still big enough. Silently round up to minimum if not.
+                        */
+                       size_t minsize = (env->me_metas[mdb_env_pick_meta(env)]->mm_last_pg + 1) * env->me_psize;
+                       if (size < minsize)
+                               size = minsize;
+               }
+               munmap(env->me_map, env->me_mapsize);
+               env->me_mapsize = size;
+               old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
+               rc = mdb_env_map(env, old, 1);
+               if (rc)
+                       return rc;
+       }
        env->me_mapsize = size;
        if (env->me_psize)
                env->me_maxpg = env->me_mapsize / env->me_psize;
@@ -2770,12 +3373,17 @@ static int
 mdb_env_open2(MDB_env *env)
 {
        unsigned int flags = env->me_flags;
-       int i, newenv = 0;
+       int i, newenv = 0, rc;
        MDB_meta meta;
-       MDB_page *p;
-#ifndef _WIN32
-       int prot;
-#endif
+
+#ifdef _WIN32
+       /* See if we should use QueryLimited */
+       rc = GetVersion();
+       if ((rc & 0xff) > 5)
+               env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
+       else
+               env->me_pidquery = PROCESS_QUERY_INFORMATION;
+#endif /* _WIN32 */
 
        memset(&meta, 0, sizeof(meta));
 
@@ -2784,6 +3392,9 @@ mdb_env_open2(MDB_env *env)
                        return i;
                DPUTS("new mdbenv");
                newenv = 1;
+               GET_PAGESIZE(env->me_psize);
+       } else {
+               env->me_psize = meta.mm_psize;
        }
 
        /* Was a mapsize configured? */
@@ -2801,58 +3412,9 @@ mdb_env_open2(MDB_env *env)
                        env->me_mapsize = minsize;
        }
 
-#ifdef _WIN32
-       {
-               int rc;
-               HANDLE mh;
-               LONG sizelo, sizehi;
-               sizelo = env->me_mapsize & 0xffffffff;
-               sizehi = env->me_mapsize >> 16 >> 16; /* only needed on Win64 */
-               /* Windows won't create mappings for zero length files.
-                * Just allocate the maxsize right now.
-                */
-               if (newenv) {
-                       if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
-                               || !SetEndOfFile(env->me_fd)
-                               || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
-                               return ErrCode();
-               }
-               mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
-                       PAGE_READWRITE : PAGE_READONLY,
-                       sizehi, sizelo, NULL);
-               if (!mh)
-                       return ErrCode();
-               env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
-                       FILE_MAP_WRITE : FILE_MAP_READ,
-                       0, 0, env->me_mapsize, meta.mm_address);
-               rc = env->me_map ? 0 : ErrCode();
-               CloseHandle(mh);
-               if (rc)
-                       return rc;
-       }
-#else
-       i = MAP_SHARED;
-       prot = PROT_READ;
-       if (flags & MDB_WRITEMAP) {
-               prot |= PROT_WRITE;
-               if (ftruncate(env->me_fd, env->me_mapsize) < 0)
-                       return ErrCode();
-       }
-       env->me_map = mmap(meta.mm_address, env->me_mapsize, prot, i,
-               env->me_fd, 0);
-       if (env->me_map == MAP_FAILED) {
-               env->me_map = NULL;
-               return ErrCode();
-       }
-       /* Turn off readahead. It's harmful when the DB is larger than RAM. */
-#ifdef MADV_RANDOM
-       madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
-#else
-#ifdef POSIX_MADV_RANDOM
-       posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
-#endif /* POSIX_MADV_RANDOM */
-#endif /* MADV_RANDOM */
-#endif /* _WIN32 */
+       rc = mdb_env_map(env, meta.mm_address, newenv);
+       if (rc)
+               return rc;
 
        if (newenv) {
                if (flags & MDB_FIXEDMAP)
@@ -2861,38 +3423,25 @@ mdb_env_open2(MDB_env *env)
                if (i != MDB_SUCCESS) {
                        return i;
                }
-       } else if (meta.mm_address && env->me_map != meta.mm_address) {
-               /* Can happen because the address argument to mmap() is just a
-                * hint.  mmap() can pick another, e.g. if the range is in use.
-                * The MAP_FIXED flag would prevent that, but then mmap could
-                * instead unmap existing pages to make room for the new map.
-                */
-               return EBUSY;   /* TODO: Make a new MDB_* error code? */
        }
-       env->me_psize = meta.mm_psize;
        env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
        env->me_nodemax = (env->me_psize - PAGEHDRSZ) / MDB_MINKEYS;
 
        env->me_maxpg = env->me_mapsize / env->me_psize;
-
-       p = (MDB_page *)env->me_map;
-       env->me_metas[0] = METADATA(p);
-       env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
-
 #if MDB_DEBUG
        {
                int toggle = mdb_env_pick_meta(env);
                MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
 
-               DPRINTF("opened database version %u, pagesize %u",
-                       env->me_metas[0]->mm_version, env->me_psize);
-               DPRINTF("using meta page %d",  toggle);
-               DPRINTF("depth: %u",           db->md_depth);
-               DPRINTF("entries: %zu",        db->md_entries);
-               DPRINTF("branch pages: %zu",   db->md_branch_pages);
-               DPRINTF("leaf pages: %zu",     db->md_leaf_pages);
-               DPRINTF("overflow pages: %zu", db->md_overflow_pages);
-               DPRINTF("root: %zu",           db->md_root);
+               DPRINTF(("opened database version %u, pagesize %u",
+                       env->me_metas[0]->mm_version, env->me_psize));
+               DPRINTF(("using meta page %d",    toggle));
+               DPRINTF(("depth: %u",             db->md_depth));
+               DPRINTF(("entries: %"Z"u",        db->md_entries));
+               DPRINTF(("branch pages: %"Z"u",   db->md_branch_pages));
+               DPRINTF(("leaf pages: %"Z"u",     db->md_leaf_pages));
+               DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
+               DPRINTF(("root: %"Z"u",           db->md_root));
        }
 #endif
 
@@ -3085,7 +3634,7 @@ typedef unsigned long long        mdb_hash_t;
 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
 
 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
- * @param[in] str string to hash
+ * @param[in] val      value to hash
  * @param[in] hval     initial value for hash
  * @return 64 bit hash
  *
@@ -3112,20 +3661,36 @@ mdb_hash_val(MDB_val *val, mdb_hash_t hval)
        return hval;
 }
 
-/** Hash the string and output the hash in hex.
+/** Hash the string and output the encoded hash.
+ * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
+ * very short name limits. We don't care about the encoding being reversible,
+ * we just want to preserve as many bits of the input as possible in a
+ * small printable string.
  * @param[in] str string to hash
- * @param[out] hexbuf an array of 17 chars to hold the hash
+ * @param[out] encbuf an array of 11 chars to hold the hash
  */
+static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
+
 static void
-mdb_hash_hex(MDB_val *val, char *hexbuf)
+mdb_pack85(unsigned long l, char *out)
 {
        int i;
-       mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
-       for (i=0; i<8; i++) {
-               hexbuf += sprintf(hexbuf, "%02x", (unsigned int)h & 0xff);
-               h >>= 8;
+
+       for (i=0; i<5; i++) {
+               *out++ = mdb_a85[l % 85];
+               l /= 85;
        }
 }
+
+static void
+mdb_hash_enc(MDB_val *val, char *encbuf)
+{
+       mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
+
+       mdb_pack85(h, encbuf);
+       mdb_pack85(h>>32, encbuf+5);
+       encbuf[10] = '\0';
+}
 #endif
 
 /** Open and/or initialize the lock region for the environment.
@@ -3238,7 +3803,7 @@ mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
                        DWORD nlow;
                } idbuf;
                MDB_val val;
-               char hexbuf[17];
+               char encbuf[11];
 
                if (!mdb_sec_inited) {
                        InitializeSecurityDescriptor(&mdb_null_sd,
@@ -3255,9 +3820,9 @@ mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
                idbuf.nlow   = stbuf.nFileIndexLow;
                val.mv_data = &idbuf;
                val.mv_size = sizeof(idbuf);
-               mdb_hash_hex(&val, hexbuf);
-               sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", hexbuf);
-               sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", hexbuf);
+               mdb_hash_enc(&val, encbuf);
+               sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
+               sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
                env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
                if (!env->me_rmutex) goto fail_errno;
                env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
@@ -3269,16 +3834,22 @@ mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
                        ino_t ino;
                } idbuf;
                MDB_val val;
-               char hexbuf[17];
+               char encbuf[11];
 
+#if defined(__NetBSD__)
+#define        MDB_SHORT_SEMNAMES      1       /* limited to 14 chars */
+#endif
                if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
                idbuf.dev = stbuf.st_dev;
                idbuf.ino = stbuf.st_ino;
                val.mv_data = &idbuf;
                val.mv_size = sizeof(idbuf);
-               mdb_hash_hex(&val, hexbuf);
-               sprintf(env->me_txns->mti_rmname, "/MDBr%s", hexbuf);
-               sprintf(env->me_txns->mti_wmname, "/MDBw%s", hexbuf);
+               mdb_hash_enc(&val, encbuf);
+#ifdef MDB_SHORT_SEMNAMES
+               encbuf[9] = '\0';       /* drop name from 15 chars to 14 chars */
+#endif
+               sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
+               sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
                /* Clean up after a previous run, if needed:  Try to
                 * remove both semaphores before doing anything else.
                 */
@@ -3301,8 +3872,8 @@ mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
                pthread_mutexattr_destroy(&mattr);
 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
 
-               env->me_txns->mti_version = MDB_VERSION;
                env->me_txns->mti_magic = MDB_MAGIC;
+               env->me_txns->mti_format = MDB_LOCK_FORMAT;
                env->me_txns->mti_txnid = 0;
                env->me_txns->mti_numreaders = 0;
 
@@ -3312,9 +3883,9 @@ mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
                        rc = MDB_INVALID;
                        goto fail;
                }
-               if (env->me_txns->mti_version != MDB_VERSION) {
-                       DPRINTF("lock region is version %u, expected version %u",
-                               env->me_txns->mti_version, MDB_VERSION);
+               if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
+                       DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
+                               env->me_txns->mti_format, MDB_LOCK_FORMAT));
                        rc = MDB_VERSION_MISMATCH;
                        goto fail;
                }
@@ -3353,7 +3924,7 @@ fail:
         *      environment and re-opening it with the new flags.
         */
 #define        CHANGEABLE      (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC)
-#define        CHANGELESS      (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP|MDB_NOTLS)
+#define        CHANGELESS      (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP|MDB_NOTLS|MDB_NOLOCK)
 
 int
 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
@@ -3405,10 +3976,13 @@ mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode
                goto leave;
        }
 
-       rc = mdb_env_setup_locks(env, lpath, mode, &excl);
-       if (rc)
-               goto leave;
-
+       /* For RDONLY, get lockfile after we know datafile exists */
+       if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
+               rc = mdb_env_setup_locks(env, lpath, mode, &excl);
+               if (rc)
+                       goto leave;
+       }
+
 #ifdef _WIN32
        if (F_ISSET(flags, MDB_RDONLY)) {
                oflags = GENERIC_READ;
@@ -3433,6 +4007,12 @@ mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode
                goto leave;
        }
 
+       if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
+               rc = mdb_env_setup_locks(env, lpath, mode, &excl);
+               if (rc)
+                       goto leave;
+       }
+
        if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
                if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
                        env->me_mfd = env->me_fd;
@@ -3441,10 +4021,12 @@ mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode
                         * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
                         */
 #ifdef _WIN32
+                       len = OPEN_EXISTING;
                        env->me_mfd = CreateFile(dpath, oflags,
                                FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
                                mode | FILE_FLAG_WRITE_THROUGH, NULL);
 #else
+                       oflags &= ~O_CREAT;
                        env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
 #endif
                        if (env->me_mfd == INVALID_HANDLE_VALUE) {
@@ -3452,7 +4034,7 @@ mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode
                                goto leave;
                        }
                }
-               DPRINTF("opened dbenv %p", (void *) env);
+               DPRINTF(("opened dbenv %p", (void *) env));
                if (excl > 0) {
                        rc = mdb_env_share_locks(env, &excl);
                }
@@ -3561,6 +4143,14 @@ mdb_env_copyfd(MDB_env *env, HANDLE fd)
        int rc;
        size_t wsize;
        char *ptr;
+#ifdef _WIN32
+       DWORD len, w2;
+#define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
+#else
+       ssize_t len;
+       size_t w2;
+#define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
+#endif
 
        /* Do the lock/unlock of the reader mutex before starting the
         * write txn.  Otherwise other read txns could block writers.
@@ -3584,52 +4174,50 @@ mdb_env_copyfd(MDB_env *env, HANDLE fd)
        }
 
        wsize = env->me_psize * 2;
-#ifdef _WIN32
-       {
-               DWORD len;
-               rc = WriteFile(fd, env->me_map, wsize, &len, NULL);
-               rc = rc ? (len == wsize ? MDB_SUCCESS : EIO) : ErrCode();
+       ptr = env->me_map;
+       w2 = wsize;
+       while (w2 > 0) {
+               DO_WRITE(rc, fd, ptr, w2, len);
+               if (!rc) {
+                       rc = ErrCode();
+                       break;
+               } else if (len > 0) {
+                       rc = MDB_SUCCESS;
+                       ptr += len;
+                       w2 -= len;
+                       continue;
+               } else {
+                       /* Non-blocking or async handles are not supported */
+                       rc = EIO;
+                       break;
+               }
        }
-#else
-       rc = write(fd, env->me_map, wsize);
-       rc = rc == (int)wsize ? MDB_SUCCESS : rc < 0 ? ErrCode() : EIO;
-#endif
        if (env->me_txns)
                UNLOCK_MUTEX_W(env);
 
        if (rc)
                goto leave;
 
-       ptr = env->me_map + wsize;
        wsize = txn->mt_next_pgno * env->me_psize - wsize;
-#ifdef _WIN32
-       while (wsize > 0) {
-               DWORD len, w2;
-               if (wsize > MAX_WRITE)
-                       w2 = MAX_WRITE;
-               else
-                       w2 = wsize;
-               rc = WriteFile(fd, ptr, w2, &len, NULL);
-               rc = rc ? (len == w2 ? MDB_SUCCESS : EIO) : ErrCode();
-               if (rc) break;
-               wsize -= w2;
-               ptr += w2;
-       }
-#else
        while (wsize > 0) {
-               size_t w2;
-               ssize_t wres;
                if (wsize > MAX_WRITE)
                        w2 = MAX_WRITE;
                else
                        w2 = wsize;
-               wres = write(fd, ptr, w2);
-               rc = wres == (ssize_t)w2 ? MDB_SUCCESS : wres < 0 ? ErrCode() : EIO;
-               if (rc) break;
-               wsize -= wres;
-               ptr += wres;
+               DO_WRITE(rc, fd, ptr, w2, len);
+               if (!rc) {
+                       rc = ErrCode();
+                       break;
+               } else if (len > 0) {
+                       rc = MDB_SUCCESS;
+                       ptr += len;
+                       wsize -= len;
+                       continue;
+               } else {
+                       rc = EIO;
+                       break;
+               }
        }
-#endif
 
 leave:
        mdb_txn_abort(txn);
@@ -3662,17 +4250,18 @@ mdb_env_copy(MDB_env *env, const char *path)
        newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
                                FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
 #else
-       newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL
-#ifdef O_DIRECT
-               |O_DIRECT
-#endif
-               , 0666);
+       newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
 #endif
        if (newfd == INVALID_HANDLE_VALUE) {
                rc = ErrCode();
                goto leave;
        }
 
+#ifdef O_DIRECT
+       /* Set O_DIRECT if the file system supports it */
+       if ((rc = fcntl(newfd, F_GETFL)) != -1)
+               (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
+#endif
 #ifdef F_NOCACHE       /* __APPLE__ */
        rc = fcntl(newfd, F_NOCACHE, 1);
        if (rc) {
@@ -3720,7 +4309,7 @@ mdb_cmp_long(const MDB_val *a, const MDB_val *b)
                *(size_t *)a->mv_data > *(size_t *)b->mv_data;
 }
 
-/** Compare two items pointing at aligned int's */
+/** Compare two items pointing at aligned unsigned int's */
 static int
 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
 {
@@ -3728,7 +4317,7 @@ mdb_cmp_int(const MDB_val *a, const MDB_val *b)
                *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
 }
 
-/** Compare two items pointing at ints of unknown alignment.
+/** Compare two items pointing at unsigned ints of unknown alignment.
  *     Nodes and keys are guaranteed to be 2-byte aligned.
  */
 static int
@@ -3819,9 +4408,9 @@ mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
        {
        pgno_t pgno;
        COPY_PGNO(pgno, mp->mp_pgno);
-       DPRINTF("searching %u keys in %s %spage %zu",
+       DPRINTF(("searching %u keys in %s %spage %"Z"u",
            nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
-           pgno);
+           pgno));
        }
 #endif
 
@@ -3848,8 +4437,8 @@ mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
                        i = (low + high) >> 1;
                        nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
                        rc = cmp(key, &nodekey);
-                       DPRINTF("found leaf index %u [%s], rc = %i",
-                           i, DKEY(&nodekey), rc);
+                       DPRINTF(("found leaf index %u [%s], rc = %i",
+                           i, DKEY(&nodekey), rc));
                        if (rc == 0)
                                break;
                        if (rc > 0)
@@ -3868,11 +4457,11 @@ mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
                        rc = cmp(key, &nodekey);
 #if MDB_DEBUG
                        if (IS_LEAF(mp))
-                               DPRINTF("found leaf index %u [%s], rc = %i",
-                                   i, DKEY(&nodekey), rc);
+                               DPRINTF(("found leaf index %u [%s], rc = %i",
+                                   i, DKEY(&nodekey), rc));
                        else
-                               DPRINTF("found branch index %u [%s -> %zu], rc = %i",
-                                   i, DKEY(&nodekey), NODEPGNO(node), rc);
+                               DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
+                                   i, DKEY(&nodekey), NODEPGNO(node), rc));
 #endif
                        if (rc == 0)
                                break;
@@ -3919,15 +4508,15 @@ static void
 mdb_cursor_pop(MDB_cursor *mc)
 {
        if (mc->mc_snum) {
-#ifndef MDB_DEBUG_SKIP
+#if MDB_DEBUG
                MDB_page        *top = mc->mc_pg[mc->mc_top];
 #endif
                mc->mc_snum--;
                if (mc->mc_snum)
                        mc->mc_top--;
 
-               DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
-                       mc->mc_dbi, (void *) mc);
+               DPRINTF(("popped page %"Z"u off db %d cursor %p", top->mp_pgno,
+                       DDBI(mc), (void *) mc));
        }
 }
 
@@ -3935,8 +4524,8 @@ mdb_cursor_pop(MDB_cursor *mc)
 static int
 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
 {
-       DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
-               mc->mc_dbi, (void *) mc);
+       DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
+               DDBI(mc), (void *) mc));
 
        if (mc->mc_snum >= CURSOR_STACK) {
                assert(mc->mc_snum < CURSOR_STACK);
@@ -3960,16 +4549,29 @@ mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
 static int
 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
 {
+       MDB_env *env = txn->mt_env;
        MDB_page *p = NULL;
        int level;
 
-       if (!((txn->mt_flags & MDB_TXN_RDONLY) |
-                 (txn->mt_env->me_flags & MDB_WRITEMAP)))
-       {
+       if (!((txn->mt_flags & MDB_TXN_RDONLY) | (env->me_flags & MDB_WRITEMAP))) {
                MDB_txn *tx2 = txn;
                level = 1;
                do {
                        MDB_ID2L dl = tx2->mt_u.dirty_list;
+                       unsigned x;
+                       /* Spilled pages were dirtied in this txn and flushed
+                        * because the dirty list got full. Bring this page
+                        * back in from the map (but don't unspill it here,
+                        * leave that unless page_touch happens again).
+                        */
+                       if (tx2->mt_spill_pgs) {
+                               MDB_ID pn = pgno << 1;
+                               x = mdb_midl_search(tx2->mt_spill_pgs, pn);
+                               if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
+                                       p = (MDB_page *)(env->me_map + env->me_psize * pgno);
+                                       goto done;
+                               }
+                       }
                        if (dl[0].mid) {
                                unsigned x = mdb_mid2l_search(dl, pgno);
                                if (x <= dl[0].mid && dl[x].mid == pgno) {
@@ -3983,9 +4585,9 @@ mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
 
        if (pgno < txn->mt_next_pgno) {
                level = 0;
-               p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
+               p = (MDB_page *)(env->me_map + env->me_psize * pgno);
        } else {
-               DPRINTF("page %zu not found", pgno);
+               DPRINTF(("page %"Z"u not found", pgno));
                assert(p != NULL);
                return MDB_PAGE_NOTFOUND;
        }
@@ -3997,37 +4599,28 @@ done:
        return MDB_SUCCESS;
 }
 
-/** Search for the page a given key should be in.
- * Pushes parent pages on the cursor stack. This function continues a
- * search on a cursor that has already been initialized. (Usually by
- * #mdb_page_search() but also by #mdb_node_move().)
- * @param[in,out] mc the cursor for this operation.
- * @param[in] key the key to search for. If NULL, search for the lowest
- * page. (This is used by #mdb_cursor_first().)
- * @param[in] modify If true, visited pages are updated with new page numbers.
- * @return 0 on success, non-zero on failure.
+/** Finish #mdb_page_search() / #mdb_page_search_lowest().
+ *     The cursor is at the root page, set up the rest of it.
  */
 static int
-mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
+mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
 {
        MDB_page        *mp = mc->mc_pg[mc->mc_top];
-       DKBUF;
        int rc;
-
+       DKBUF;
 
        while (IS_BRANCH(mp)) {
                MDB_node        *node;
                indx_t          i;
 
-               DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
+               DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
                assert(NUMKEYS(mp) > 1);
-               DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
+               DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
 
-               if (key == NULL)        /* Initialize cursor to first page. */
+               if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
                        i = 0;
-               else if (key->mv_size > MDB_MAXKEYSIZE && key->mv_data == NULL) {
-                                                       /* cursor to last page */
-                       i = NUMKEYS(mp)-1;
+                       if (flags & MDB_PS_LAST)
+                               i = NUMKEYS(mp) - 1;
                } else {
                        int      exact;
                        node = mdb_node_search(mc, key, &exact);
@@ -4040,11 +4633,9 @@ mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
                                        i--;
                                }
                        }
+                       DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
                }
 
-               if (key)
-                       DPRINTF("following index %u for key [%s]",
-                           i, DKEY(key));
                assert(i < NUMKEYS(mp));
                node = NODEPTR(mp, i);
 
@@ -4055,7 +4646,7 @@ mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
                if ((rc = mdb_cursor_push(mc, mp)))
                        return rc;
 
-               if (modify) {
+               if (flags & MDB_PS_MODIFY) {
                        if ((rc = mdb_page_touch(mc)) != 0)
                                return rc;
                        mp = mc->mc_pg[mc->mc_top];
@@ -4063,13 +4654,15 @@ mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
        }
 
        if (!IS_LEAF(mp)) {
-               DPRINTF("internal error, index points to a %02X page!?",
-                   mp->mp_flags);
+               DPRINTF(("internal error, index points to a %02X page!?",
+                   mp->mp_flags));
                return MDB_CORRUPTED;
        }
 
-       DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
-           key ? DKEY(key) : NULL);
+       DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
+           key ? DKEY(key) : "null"));
+       mc->mc_flags |= C_INITIALIZED;
+       mc->mc_flags &= ~C_EOF;
 
        return MDB_SUCCESS;
 }
@@ -4093,18 +4686,17 @@ mdb_page_search_lowest(MDB_cursor *mc)
        mc->mc_ki[mc->mc_top] = 0;
        if ((rc = mdb_cursor_push(mc, mp)))
                return rc;
-       return mdb_page_search_root(mc, NULL, 0);
+       return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
 }
 
 /** Search for the page a given key should be in.
- * Pushes parent pages on the cursor stack. This function just sets up
- * the search; it finds the root page for \b mc's database and sets this
- * as the root of the cursor's stack. Then #mdb_page_search_root() is
- * called to complete the search.
+ * Push it and its parent pages on the cursor stack.
  * @param[in,out] mc the cursor for this operation.
- * @param[in] key the key to search for. If NULL, search for the lowest
- * page. (This is used by #mdb_cursor_first().)
- * @param[in] flags If MDB_PS_MODIFY set, visited pages are updated with new page numbers.
+ * @param[in] key the key to search for, or NULL for first/last page.
+ * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
+ *   are touched (updated with new page numbers).
+ *   If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
+ *   This is used by #mdb_cursor_first() and #mdb_cursor_last().
  *   If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
  * @return 0 on success, non-zero on failure.
  */
@@ -4115,23 +4707,20 @@ mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
        pgno_t           root;
 
        /* Make sure the txn is still viable, then find the root from
-        * the txn's db table.
+        * the txn's db table and set it as the root of the cursor's stack.
         */
        if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
                DPUTS("transaction has failed, must abort");
-               return EINVAL;
+               return MDB_BAD_TXN;
        } else {
                /* Make sure we're using an up-to-date root */
-               if (mc->mc_dbi > MAIN_DBI) {
-                       if ((*mc->mc_dbflag & DB_STALE) ||
-                       ((flags & MDB_PS_MODIFY) && !(*mc->mc_dbflag & DB_DIRTY))) {
+               if (*mc->mc_dbflag & DB_STALE) {
                                MDB_cursor mc2;
-                               unsigned char dbflag = 0;
                                mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
-                               rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, flags & MDB_PS_MODIFY);
+                               rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
                                if (rc)
                                        return rc;
-                               if (*mc->mc_dbflag & DB_STALE) {
+                               {
                                        MDB_val data;
                                        int exact = 0;
                                        uint16_t flags;
@@ -4151,11 +4740,7 @@ mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
                                                return MDB_INCOMPATIBLE;
                                        memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
                                }
-                               if (flags & MDB_PS_MODIFY)
-                                       dbflag = DB_DIRTY;
                                *mc->mc_dbflag &= ~DB_STALE;
-                               *mc->mc_dbflag |= dbflag;
-                       }
                }
                root = mc->mc_db->md_root;
 
@@ -4173,8 +4758,8 @@ mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
        mc->mc_snum = 1;
        mc->mc_top = 0;
 
-       DPRINTF("db %u root page %zu has flags 0x%X",
-               mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
+       DPRINTF(("db %d root page %"Z"u has flags 0x%X",
+               DDBI(mc), root, mc->mc_pg[0]->mp_flags));
 
        if (flags & MDB_PS_MODIFY) {
                if ((rc = mdb_page_touch(mc)))
@@ -4192,23 +4777,40 @@ mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
 {
        MDB_txn *txn = mc->mc_txn;
        pgno_t pg = mp->mp_pgno;
-       unsigned i, ovpages = mp->mp_pages;
+       unsigned x = 0, ovpages = mp->mp_pages;
        MDB_env *env = txn->mt_env;
+       MDB_IDL sl = txn->mt_spill_pgs;
+       MDB_ID pn = pg << 1;
        int rc;
 
-       DPRINTF("free ov page %zu (%d)", pg, ovpages);
-       /* If the page is dirty we just acquired it, so we should
-        * give it back to our current free list, if any.
-        * Not currently supported in nested txns.
+       DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
+       /* If the page is dirty or on the spill list we just acquired it,
+        * so we should give it back to our current free list, if any.
         * Otherwise put it onto the list of pages we freed in this txn.
+        *
+        * Won't create me_pghead: me_pglast must be inited along with it.
+        * Unsupported in nested txns: They would need to hide the page
+        * range in ancestor txns' dirty and spilled lists.
         */
-       if ((mp->mp_flags & P_DIRTY) && !txn->mt_parent && env->me_pghead) {
-               unsigned j, x;
+       if (env->me_pghead &&
+               !txn->mt_parent &&
+               ((mp->mp_flags & P_DIRTY) ||
+                (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
+       {
+               unsigned i, j;
                pgno_t *mop;
                MDB_ID2 *dl, ix, iy;
                rc = mdb_midl_need(&env->me_pghead, ovpages);
                if (rc)
                        return rc;
+               if (!(mp->mp_flags & P_DIRTY)) {
+                       /* This page is no longer spilled */
+                       if (x == sl[0])
+                               sl[0]--;
+                       else
+                               sl[x] |= 1;
+                       goto release;
+               }
                /* Remove from dirty list */
                dl = txn->mt_u.dirty_list;
                x = dl[0].mid--;
@@ -4227,6 +4829,7 @@ mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
                }
                if (!(env->me_flags & MDB_WRITEMAP))
                        mdb_dpage_free(env, mp);
+release:
                /* Insert in me_pghead */
                mop = env->me_pghead;
                j = mop[0] + ovpages;
@@ -4268,7 +4871,7 @@ mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
        data->mv_size = NODEDSZ(leaf);
        memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
        if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
-               DPRINTF("read overflow page %zu failed", pgno);
+               DPRINTF(("read overflow page %"Z"u failed", pgno));
                return rc;
        }
        data->mv_data = METADATA(omp);
@@ -4287,13 +4890,16 @@ mdb_get(MDB_txn *txn, MDB_dbi dbi,
 
        assert(key);
        assert(data);
-       DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
+       DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
 
        if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
                return EINVAL;
 
-       if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
-               return EINVAL;
+       if (txn->mt_flags & MDB_TXN_ERROR)
+               return MDB_BAD_TXN;
+
+       if (key->mv_size > MDB_MAXKEYSIZE) {
+               return MDB_BAD_VALSIZE;
        }
 
        mdb_cursor_init(&mc, txn, dbi, &mx);
@@ -4320,13 +4926,13 @@ mdb_cursor_sibling(MDB_cursor *mc, int move_right)
        }
 
        mdb_cursor_pop(mc);
-       DPRINTF("parent page is page %zu, index %u",
-               mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
+       DPRINTF(("parent page is page %"Z"u, index %u",
+               mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
 
        if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
                       : (mc->mc_ki[mc->mc_top] == 0)) {
-               DPRINTF("no more keys left, moving to %s sibling",
-                   move_right ? "right" : "left");
+               DPRINTF(("no more keys left, moving to %s sibling",
+                   move_right ? "right" : "left"));
                if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
                        /* undo cursor_pop before returning */
                        mc->mc_top++;
@@ -4338,14 +4944,17 @@ mdb_cursor_sibling(MDB_cursor *mc, int move_right)
                        mc->mc_ki[mc->mc_top]++;
                else
                        mc->mc_ki[mc->mc_top]--;
-               DPRINTF("just moving to %s index key %u",
-                   move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
+               DPRINTF(("just moving to %s index key %u",
+                   move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
        }
        assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
 
        indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
-       if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL) != 0))
+       if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL)) != 0) {
+               /* mc will be inconsistent if caller does mc_snum++ as above */
+               mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
                return rc;
+       }
 
        mdb_cursor_push(mc, mp);
        if (!move_right)
@@ -4375,8 +4984,11 @@ mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
                if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
                        if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
                                rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
-                               if (op != MDB_NEXT || rc != MDB_NOTFOUND)
+                               if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
+                                       if (rc == MDB_SUCCESS)
+                                               MDB_GET_KEY(leaf, key);
                                        return rc;
+                               }
                        }
                } else {
                        mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
@@ -4385,7 +4997,9 @@ mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
                }
        }
 
-       DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
+       DPRINTF(("cursor_next: top page is %"Z"u in cursor %p", mp->mp_pgno, (void *) mc));
+       if (mc->mc_flags & C_DEL)
+               goto skip;
 
        if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
                DPUTS("=====> move to next sibling page");
@@ -4394,12 +5008,13 @@ mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
                        return rc;
                }
                mp = mc->mc_pg[mc->mc_top];
-               DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
+               DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
        } else
                mc->mc_ki[mc->mc_top]++;
 
-       DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
-           mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
+skip:
+       DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
+           mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
 
        if (IS_LEAF2(mp)) {
                key->mv_size = mc->mc_db->md_pad;
@@ -4442,11 +5057,14 @@ mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
 
        if (mc->mc_db->md_flags & MDB_DUPSORT) {
                leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
-               if (op == MDB_PREV || op == MDB_PREV_DUP) {
-                       if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
+               if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
+                       if (op == MDB_PREV || op == MDB_PREV_DUP) {
                                rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
-                               if (op != MDB_PREV || rc != MDB_NOTFOUND)
+                               if (op != MDB_PREV || rc != MDB_NOTFOUND) {
+                                       if (rc == MDB_SUCCESS)
+                                               MDB_GET_KEY(leaf, key);
                                        return rc;
+                               }
                        } else {
                                mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
                                if (op == MDB_PREV_DUP)
@@ -4455,7 +5073,7 @@ mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
                }
        }
 
-       DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
+       DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p", mp->mp_pgno, (void *) mc));
 
        if (mc->mc_ki[mc->mc_top] == 0)  {
                DPUTS("=====> move to prev sibling page");
@@ -4464,14 +5082,14 @@ mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
                }
                mp = mc->mc_pg[mc->mc_top];
                mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
-               DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
+               DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
        } else
                mc->mc_ki[mc->mc_top]--;
 
        mc->mc_flags &= ~C_EOF;
 
-       DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
-           mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
+       DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
+           mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
 
        if (IS_LEAF2(mp)) {
                key->mv_size = mc->mc_db->md_pad;
@@ -4512,7 +5130,11 @@ mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
 
        assert(mc);
        assert(key);
-       assert(key->mv_size > 0);
+       if (key->mv_size == 0)
+               return MDB_BAD_VALSIZE;
+
+       if (mc->mc_xcursor)
+               mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
 
        /* See if we're already on the right page */
        if (mc->mc_flags & C_INITIALIZED) {
@@ -4528,7 +5150,7 @@ mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
                        nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
                } else {
                        leaf = NODEPTR(mp, 0);
-                       MDB_GET_KEY(leaf, &nodekey);
+                       MDB_GET_KEY2(leaf, nodekey);
                }
                rc = mc->mc_dbx->md_cmp(key, &nodekey);
                if (rc == 0) {
@@ -4549,7 +5171,7 @@ mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
                                                 nkeys-1, nodekey.mv_size);
                                } else {
                                        leaf = NODEPTR(mp, nkeys-1);
-                                       MDB_GET_KEY(leaf, &nodekey);
+                                       MDB_GET_KEY2(leaf, nodekey);
                                }
                                rc = mc->mc_dbx->md_cmp(key, &nodekey);
                                if (rc == 0) {
@@ -4567,7 +5189,7 @@ mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
                                                                 mc->mc_ki[mc->mc_top], nodekey.mv_size);
                                                } else {
                                                        leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
-                                                       MDB_GET_KEY(leaf, &nodekey);
+                                                       MDB_GET_KEY2(leaf, nodekey);
                                                }
                                                rc = mc->mc_dbx->md_cmp(key, &nodekey);
                                                if (rc == 0) {
@@ -4597,7 +5219,11 @@ mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
                if (!mc->mc_top) {
                        /* There are no other pages */
                        mc->mc_ki[mc->mc_top] = 0;
-                       return MDB_NOTFOUND;
+                       if (op == MDB_SET_RANGE) {
+                               rc = 0;
+                               goto set1;
+                       } else
+                               return MDB_NOTFOUND;
                }
        }
 
@@ -4661,6 +5287,7 @@ set1:
                        if (rc) {
                                if (op == MDB_GET_BOTH || rc > 0)
                                        return MDB_NOTFOUND;
+                               rc = 0;
                        }
 
                } else {
@@ -4674,7 +5301,7 @@ set1:
        /* The key already matches in all other cases */
        if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
                MDB_GET_KEY(leaf, key);
-       DPRINTF("==> cursor placed on key [%s]", DKEY(key));
+       DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
 
        return rc;
 }
@@ -4686,8 +5313,11 @@ mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
        int              rc;
        MDB_node        *leaf;
 
+       if (mc->mc_xcursor)
+               mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
+
        if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
-               rc = mdb_page_search(mc, NULL, 0);
+               rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
                if (rc != MDB_SUCCESS)
                        return rc;
        }
@@ -4712,8 +5342,6 @@ mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
                        if (rc)
                                return rc;
                } else {
-                       if (mc->mc_xcursor)
-                               mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
                        if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
                                return rc;
                }
@@ -4729,14 +5357,13 @@ mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
        int              rc;
        MDB_node        *leaf;
 
+       if (mc->mc_xcursor)
+               mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
+
        if (!(mc->mc_flags & C_EOF)) {
 
                if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
-                       MDB_val lkey;
-
-                       lkey.mv_size = MDB_MAXKEYSIZE+1;
-                       lkey.mv_data = NULL;
-                       rc = mdb_page_search(mc, &lkey, 0);
+                       rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
                        if (rc != MDB_SUCCESS)
                                return rc;
                }
@@ -4760,8 +5387,6 @@ mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
                        if (rc)
                                return rc;
                } else {
-                       if (mc->mc_xcursor)
-                               mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
                        if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
                                return rc;
                }
@@ -4777,9 +5402,13 @@ mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
 {
        int              rc;
        int              exact = 0;
+       int              (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
 
        assert(mc);
 
+       if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
+               return MDB_BAD_TXN;
+
        switch (op) {
        case MDB_GET_CURRENT:
                if (!(mc->mc_flags & C_INITIALIZED)) {
@@ -4800,6 +5429,8 @@ mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
                                MDB_GET_KEY(leaf, key);
                                if (data) {
                                        if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
+                                               if (mc->mc_flags & C_DEL)
+                                                       mdb_xcursor_init1(mc, leaf);
                                                rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
                                        } else {
                                                rc = mdb_node_read(mc->mc_txn, leaf, data);
@@ -4810,39 +5441,50 @@ mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
                break;
        case MDB_GET_BOTH:
        case MDB_GET_BOTH_RANGE:
-               if (data == NULL || mc->mc_xcursor == NULL) {
+               if (data == NULL) {
                        rc = EINVAL;
                        break;
                }
+               if (mc->mc_xcursor == NULL) {
+                       rc = MDB_INCOMPATIBLE;
+                       break;
+               }
                /* FALLTHRU */
        case MDB_SET:
        case MDB_SET_KEY:
        case MDB_SET_RANGE:
-               if (key == NULL || key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
+               if (key == NULL) {
                        rc = EINVAL;
+               } else if (key->mv_size > MDB_MAXKEYSIZE) {
+                       rc = MDB_BAD_VALSIZE;
                } else if (op == MDB_SET_RANGE)
                        rc = mdb_cursor_set(mc, key, data, op, NULL);
                else
                        rc = mdb_cursor_set(mc, key, data, op, &exact);
                break;
        case MDB_GET_MULTIPLE:
-               if (data == NULL ||
-                       !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
-                       !(mc->mc_flags & C_INITIALIZED)) {
+               if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
                        rc = EINVAL;
                        break;
                }
+               if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
+                       rc = MDB_INCOMPATIBLE;
+                       break;
+               }
                rc = MDB_SUCCESS;
                if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
                        (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
                        break;
                goto fetchm;
        case MDB_NEXT_MULTIPLE:
-               if (data == NULL ||
-                       !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
+               if (data == NULL) {
                        rc = EINVAL;
                        break;
                }
+               if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
+                       rc = MDB_INCOMPATIBLE;
+                       break;
+               }
                if (!(mc->mc_flags & C_INITIALIZED))
                        rc = mdb_cursor_first(mc, key, data);
                else
@@ -4885,45 +5527,48 @@ fetchm:
                rc = mdb_cursor_first(mc, key, data);
                break;
        case MDB_FIRST_DUP:
-               if (data == NULL ||
-                       !(mc->mc_db->md_flags & MDB_DUPSORT) ||
-                       !(mc->mc_flags & C_INITIALIZED) ||
-                       !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
+               mfunc = mdb_cursor_first;
+       mmove:
+               if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
+                       rc = EINVAL;
+                       break;
+               }
+               if (mc->mc_xcursor == NULL) {
+                       rc = MDB_INCOMPATIBLE;
+                       break;
+               }
+               if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
                        rc = EINVAL;
                        break;
                }
-               rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
+               rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
                break;
        case MDB_LAST:
                rc = mdb_cursor_last(mc, key, data);
                break;
        case MDB_LAST_DUP:
-               if (data == NULL ||
-                       !(mc->mc_db->md_flags & MDB_DUPSORT) ||
-                       !(mc->mc_flags & C_INITIALIZED) ||
-                       !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
-                       rc = EINVAL;
-                       break;
-               }
-               rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
-               break;
+               mfunc = mdb_cursor_last;
+               goto mmove;
        default:
-               DPRINTF("unhandled/unimplemented cursor operation %u", op);
+               DPRINTF(("unhandled/unimplemented cursor operation %u", op));
                rc = EINVAL;
                break;
        }
 
+       if (mc->mc_flags & C_DEL)
+               mc->mc_flags ^= C_DEL;
+
        return rc;
 }
 
-/** Touch all the pages in the cursor stack.
+/** Touch all the pages in the cursor stack. Set mc_top.
  *     Makes sure all the pages are writable, before attempting a write operation.
  * @param[in] mc The cursor to operate on.
  */
 static int
 mdb_cursor_touch(MDB_cursor *mc)
 {
-       int rc;
+       int rc = MDB_SUCCESS;
 
        if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
                MDB_cursor mc2;
@@ -4934,25 +5579,30 @@ mdb_cursor_touch(MDB_cursor *mc)
                         return rc;
                *mc->mc_dbflag |= DB_DIRTY;
        }
-       for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
-               rc = mdb_page_touch(mc);
-               if (rc)
-                       return rc;
+       mc->mc_top = 0;
+       if (mc->mc_snum) {
+               do {
+                       rc = mdb_page_touch(mc);
+               } while (!rc && ++(mc->mc_top) < mc->mc_snum);
+               mc->mc_top = mc->mc_snum-1;
        }
-       mc->mc_top = mc->mc_snum-1;
-       return MDB_SUCCESS;
+       return rc;
 }
 
+/** Do not spill pages to disk if txn is getting full, may fail instead */
+#define MDB_NOSPILL    0x8000
+
 int
 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
     unsigned int flags)
 {
+       enum { MDB_NO_ROOT = MDB_LAST_ERRCODE+10 }; /* internal code */
        MDB_node        *leaf = NULL;
        MDB_val xdata, *rdata, dkey;
        MDB_page        *fp;
        MDB_db dummy;
        int do_sub = 0, insert = 0;
-       unsigned int mcount = 0, dcount = 0;
+       unsigned int mcount = 0, dcount = 0, nospill;
        size_t nsize;
        int rc, rc2;
        MDB_pagebuf pbuf;
@@ -4967,25 +5617,28 @@ mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
                dcount = data[1].mv_size;
                data[1].mv_size = 0;
                if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
-                       return EINVAL;
+                       return MDB_INCOMPATIBLE;
        }
 
-       if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
-               return EACCES;
+       nospill = flags & MDB_NOSPILL;
+       flags &= ~MDB_NOSPILL;
+
+       if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
+               return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
 
        if (flags != MDB_CURRENT && (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE))
-               return EINVAL;
+               return MDB_BAD_VALSIZE;
 
        if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT) && data->mv_size > MDB_MAXKEYSIZE)
-               return EINVAL;
+               return MDB_BAD_VALSIZE;
 
 #if SIZE_MAX > MAXDATASIZE
        if (data->mv_size > MAXDATASIZE)
-               return EINVAL;
+               return MDB_BAD_VALSIZE;
 #endif
 
-       DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
-               mc->mc_dbi, DKEY(key), key ? key->mv_size:0, data->mv_size);
+       DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
+               DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
 
        dkey.mv_size = 0;
 
@@ -4994,23 +5647,11 @@ mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
                        return EINVAL;
                rc = MDB_SUCCESS;
        } else if (mc->mc_db->md_root == P_INVALID) {
-               MDB_page *np;
-               /* new database, write a root leaf page */
-               DPUTS("allocating new root leaf page");
-               if ((rc = mdb_page_new(mc, P_LEAF, 1, &np))) {
-                       return rc;
-               }
+               /* new database, cursor has nothing to point to */
                mc->mc_snum = 0;
-               mdb_cursor_push(mc, np);
-               mc->mc_db->md_root = np->mp_pgno;
-               mc->mc_db->md_depth++;
-               *mc->mc_dbflag |= DB_DIRTY;
-               if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
-                       == MDB_DUPFIXED)
-                       np->mp_flags |= P_LEAF2;
-               mc->mc_flags |= C_INITIALIZED;
-               rc = MDB_NOTFOUND;
-               goto top;
+               mc->mc_top = 0;
+               mc->mc_flags &= ~C_INITIALIZED;
+               rc = MDB_NO_ROOT;
        } else {
                int exact = 0;
                MDB_val d2;
@@ -5028,10 +5669,10 @@ mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
                                }
                        }
                } else {
-               rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
+                       rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
                }
                if ((flags & MDB_NOOVERWRITE) && rc == 0) {
-                       DPRINTF("duplicate key [%s]", DKEY(key));
+                       DPRINTF(("duplicate key [%s]", DKEY(key)));
                        *data = d2;
                        return MDB_KEYEXIST;
                }
@@ -5039,19 +5680,50 @@ mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
                        return rc;
        }
 
-       /* Cursor is positioned, now make sure all pages are writable */
-       rc2 = mdb_cursor_touch(mc);
-       if (rc2)
-               return rc2;
+       if (mc->mc_flags & C_DEL)
+               mc->mc_flags ^= C_DEL;
+
+       /* Cursor is positioned, check for room in the dirty list */
+       if (!nospill) {
+               if (flags & MDB_MULTIPLE) {
+                       rdata = &xdata;
+                       xdata.mv_size = data->mv_size * dcount;
+               } else {
+                       rdata = data;
+               }
+               if ((rc2 = mdb_page_spill(mc, key, rdata)))
+                       return rc2;
+       }
+
+       if (rc == MDB_NO_ROOT) {
+               MDB_page *np;
+               /* new database, write a root leaf page */
+               DPUTS("allocating new root leaf page");
+               if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
+                       return rc2;
+               }
+               mdb_cursor_push(mc, np);
+               mc->mc_db->md_root = np->mp_pgno;
+               mc->mc_db->md_depth++;
+               *mc->mc_dbflag |= DB_DIRTY;
+               if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
+                       == MDB_DUPFIXED)
+                       np->mp_flags |= P_LEAF2;
+               mc->mc_flags |= C_INITIALIZED;
+       } else {
+               /* make sure all cursor pages are writable */
+               rc2 = mdb_cursor_touch(mc);
+               if (rc2)
+                       return rc2;
+       }
 
-top:
        /* The key already exists */
        if (rc == MDB_SUCCESS) {
                /* there's only a key anyway, so this is a no-op */
                if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
                        unsigned int ksize = mc->mc_db->md_pad;
                        if (key->mv_size != ksize)
-                               return EINVAL;
+                               return MDB_BAD_VALSIZE;
                        if (flags == MDB_CURRENT) {
                                char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
                                memcpy(ptr, key->mv_data, ksize);
@@ -5080,9 +5752,16 @@ more:
                                        mc->mc_dbx->md_dcmp = mdb_cmp_cint;
 #endif
 #endif
-                               /* if data matches, ignore it */
-                               if (!mc->mc_dbx->md_dcmp(data, &dkey))
-                                       return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
+                               /* if data matches, skip it */
+                               if (!mc->mc_dbx->md_dcmp(data, &dkey)) {
+                                       if (flags & MDB_NODUPDATA)
+                                               rc = MDB_KEYEXIST;
+                                       else if (flags & MDB_MULTIPLE)
+                                               goto next_mult;
+                                       else
+                                               rc = MDB_SUCCESS;
+                                       return rc;
+                               }
 
                                /* create a fake page for the dup items */
                                memcpy(dbuf, dkey.mv_data, dkey.mv_size);
@@ -5200,8 +5879,18 @@ current:
                                return rc2;
                        ovpages = omp->mp_pages;
 
-                       /* Is the ov page writable and large enough? */
-                       if ((omp->mp_flags & P_DIRTY) && ovpages >= dpages) {
+                       /* Is the ov page large enough? */
+                       if (ovpages >= dpages) {
+                         if (!(omp->mp_flags & P_DIRTY) &&
+                                 (level || (mc->mc_txn->mt_env->me_flags & MDB_WRITEMAP)))
+                         {
+                               rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
+                               if (rc)
+                                       return rc;
+                               level = 0;              /* dirty in this txn or clean */
+                         }
+                         /* Is it dirty? */
+                         if (omp->mp_flags & P_DIRTY) {
                                /* yes, overwrite it. Note in this case we don't
                                 * bother to try shrinking the page if the new data
                                 * is smaller than the overflow threshold.
@@ -5234,10 +5923,10 @@ current:
                                else
                                        memcpy(METADATA(omp), data->mv_data, data->mv_size);
                                goto done;
-                       } else {
-                               if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
-                                       return rc2;
+                         }
                        }
+                       if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
+                               return rc2;
                } else if (NODEDSZ(leaf) == data->mv_size) {
                        /* same size, just replace it. Note that we could
                         * also reuse this node if the new data is smaller,
@@ -5254,7 +5943,7 @@ current:
                mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
                mc->mc_db->md_entries--;
        } else {
-               DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
+               DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
                insert = 1;
        }
 
@@ -5279,9 +5968,6 @@ new_sub:
                        unsigned i = mc->mc_top;
                        MDB_page *mp = mc->mc_pg[i];
 
-                       if (mc->mc_flags & C_SUB)
-                               dbi--;
-
                        for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
                                if (mc->mc_flags & C_SUB)
                                        m3 = &m2->mc_xcursor->mx_cursor;
@@ -5310,10 +5996,11 @@ put_sub:
                        xdata.mv_data = "";
                        leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
                        if (flags & MDB_CURRENT) {
-                               xflags = MDB_CURRENT;
+                               xflags = MDB_CURRENT|MDB_NOSPILL;
                        } else {
                                mdb_xcursor_init1(mc, leaf);
-                               xflags = (flags & MDB_NODUPDATA) ? MDB_NOOVERWRITE : 0;
+                               xflags = (flags & MDB_NODUPDATA) ?
+                                       MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
                        }
                        /* converted, write the original data first */
                        if (dkey.mv_size) {
@@ -5328,6 +6015,7 @@ put_sub:
 
                                        for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
                                                if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
+                                               if (!(m2->mc_flags & C_INITIALIZED)) continue;
                                                if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
                                                        mdb_xcursor_init1(m2, leaf);
                                                }
@@ -5351,15 +6039,16 @@ put_sub:
                        mc->mc_db->md_entries++;
                if (flags & MDB_MULTIPLE) {
                        if (!rc) {
+next_mult:
                                mcount++;
+                               /* let caller know how many succeeded, if any */
+                               data[1].mv_size = mcount;
                                if (mcount < dcount) {
                                        data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
                                        leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
                                        goto more;
                                }
                        }
-                       /* let caller know how many succeeded, if any */
-                       data[1].mv_size = mcount;
                }
        }
 done:
@@ -5377,12 +6066,15 @@ mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
        MDB_node        *leaf;
        int rc;
 
-       if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
-               return EACCES;
+       if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
+               return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
 
        if (!(mc->mc_flags & C_INITIALIZED))
                return EINVAL;
 
+       if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
+               return rc;
+
        rc = mdb_cursor_touch(mc);
        if (rc)
                return rc;
@@ -5390,11 +6082,11 @@ mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
        leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
 
        if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
-               if (flags != MDB_NODUPDATA) {
+               if (!(flags & MDB_NODUPDATA)) {
                        if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
                                mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
                        }
-                       rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
+                       rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
                        /* If sub-DB still has entries, we're done */
                        if (mc->mc_xcursor->mx_db.md_entries) {
                                if (leaf->mn_flags & F_SUBDATA) {
@@ -5416,6 +6108,7 @@ mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
                                        }
                                }
                                mc->mc_db->md_entries--;
+                               mc->mc_flags |= C_DEL;
                                return rc;
                        }
                        /* otherwise fall thru and delete the sub-DB */
@@ -5450,8 +6143,8 @@ mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
 
        if ((rc = mdb_page_alloc(mc, num, &np)))
                return rc;
-       DPRINTF("allocated new mpage %zu, page size %u",
-           np->mp_pgno, mc->mc_txn->mt_env->me_psize);
+       DPRINTF(("allocated new mpage %"Z"u, page size %u",
+           np->mp_pgno, mc->mc_txn->mt_env->me_psize));
        np->mp_flags = flags | P_DIRTY;
        np->mp_lower = PAGEHDRSZ;
        np->mp_upper = mc->mc_txn->mt_env->me_psize;
@@ -5541,6 +6234,7 @@ mdb_node_add(MDB_cursor *mc, indx_t indx,
 {
        unsigned int     i;
        size_t           node_size = NODESIZE;
+       ssize_t          room;
        indx_t           ofs;
        MDB_node        *node;
        MDB_page        *mp = mc->mc_pg[mc->mc_top];
@@ -5549,11 +6243,11 @@ mdb_node_add(MDB_cursor *mc, indx_t indx,
 
        assert(mp->mp_upper >= mp->mp_lower);
 
-       DPRINTF("add to %s %spage %zu index %i, data size %zu key size %zu [%s]",
+       DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
            IS_LEAF(mp) ? "leaf" : "branch",
                IS_SUBP(mp) ? "sub-" : "",
            mp->mp_pgno, indx, data ? data->mv_size : 0,
-               key ? key->mv_size : 0, key ? DKEY(key) : NULL);
+               key ? key->mv_size : 0, key ? DKEY(key) : "null"));
 
        if (IS_LEAF2(mp)) {
                /* Move higher keys up one slot. */
@@ -5571,9 +6265,9 @@ mdb_node_add(MDB_cursor *mc, indx_t indx,
                return MDB_SUCCESS;
        }
 
+       room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
        if (key != NULL)
                node_size += key->mv_size;
-
        if (IS_LEAF(mp)) {
                assert(data);
                if (F_ISSET(flags, F_BIGDATA)) {
@@ -5583,28 +6277,25 @@ mdb_node_add(MDB_cursor *mc, indx_t indx,
                        int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
                        int rc;
                        /* Put data on overflow page. */
-                       DPRINTF("data size is %zu, node would be %zu, put data on overflow page",
-                           data->mv_size, node_size+data->mv_size);
-                       node_size += sizeof(pgno_t);
+                       DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
+                           data->mv_size, node_size+data->mv_size));
+                       node_size += sizeof(pgno_t) + (node_size & 1);
+                       if ((ssize_t)node_size > room)
+                               goto full;
                        if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
                                return rc;
-                       DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
+                       DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
                        flags |= F_BIGDATA;
+                       goto update;
                } else {
                        node_size += data->mv_size;
                }
        }
        node_size += node_size & 1;
+       if ((ssize_t)node_size > room)
+               goto full;
 
-       if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
-               DPRINTF("not enough room in page %zu, got %u ptrs",
-                   mp->mp_pgno, NUMKEYS(mp));
-               DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
-                   mp->mp_upper - mp->mp_lower);
-               DPRINTF("node size = %zu", node_size);
-               return MDB_PAGE_FULL;
-       }
-
+update:
        /* Move higher pointers up one slot. */
        for (i = NUMKEYS(mp); i > indx; i--)
                mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
@@ -5650,6 +6341,13 @@ mdb_node_add(MDB_cursor *mc, indx_t indx,
        }
 
        return MDB_SUCCESS;
+
+full:
+       DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
+               mp->mp_pgno, NUMKEYS(mp)));
+       DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
+       DPRINTF(("node size = %"Z"u", node_size));
+       return MDB_PAGE_FULL;
 }
 
 /** Delete the specified node from a page.
@@ -5670,8 +6368,8 @@ mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
        {
        pgno_t pgno;
        COPY_PGNO(pgno, mp->mp_pgno);
-       DPRINTF("delete node %u on %s page %zu", indx,
-           IS_LEAF(mp) ? "leaf" : "branch", pgno);
+       DPRINTF(("delete node %u on %s page %"Z"u", indx,
+           IS_LEAF(mp) ? "leaf" : "branch", pgno));
        }
 #endif
        assert(indx < NUMKEYS(mp));
@@ -5784,11 +6482,13 @@ mdb_xcursor_init0(MDB_cursor *mc)
        mx->mx_cursor.mc_txn = mc->mc_txn;
        mx->mx_cursor.mc_db = &mx->mx_db;
        mx->mx_cursor.mc_dbx = &mx->mx_dbx;
-       mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
+       mx->mx_cursor.mc_dbi = mc->mc_dbi;
        mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
        mx->mx_cursor.mc_snum = 0;
        mx->mx_cursor.mc_top = 0;
        mx->mx_cursor.mc_flags = C_SUB;
+       mx->mx_dbx.md_name.mv_size = 0;
+       mx->mx_dbx.md_name.mv_data = NULL;
        mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
        mx->mx_dbx.md_dcmp = NULL;
        mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
@@ -5809,6 +6509,7 @@ mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
                memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
                mx->mx_cursor.mc_pg[0] = 0;
                mx->mx_cursor.mc_snum = 0;
+               mx->mx_cursor.mc_top = 0;
                mx->mx_cursor.mc_flags = C_SUB;
        } else {
                MDB_page *fp = NODEDATA(node);
@@ -5821,8 +6522,8 @@ mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
                mx->mx_db.md_entries = NUMKEYS(fp);
                COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
                mx->mx_cursor.mc_snum = 1;
-               mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
                mx->mx_cursor.mc_top = 0;
+               mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
                mx->mx_cursor.mc_pg[0] = fp;
                mx->mx_cursor.mc_ki[0] = 0;
                if (mc->mc_db->md_flags & MDB_DUPFIXED) {
@@ -5832,12 +6533,9 @@ mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
                                mx->mx_db.md_flags |= MDB_INTEGERKEY;
                }
        }
-       DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
-               mx->mx_db.md_root);
-       mx->mx_dbflag = DB_VALID | (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY) ?
-               DB_DIRTY : 0);
-       mx->mx_dbx.md_name.mv_data = NODEKEY(node);
-       mx->mx_dbx.md_name.mv_size = node->mn_ksize;
+       DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
+               mx->mx_db.md_root));
+       mx->mx_dbflag = DB_VALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
 #if UINT_MAX < SIZE_MAX
        if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
 #ifdef MISALIGNED_OK
@@ -5852,6 +6550,7 @@ mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
 static void
 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
 {
+       mc->mc_next = NULL;
        mc->mc_backup = NULL;
        mc->mc_dbi = dbi;
        mc->mc_txn = txn;
@@ -5883,6 +6582,9 @@ mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
        if (txn == NULL || ret == NULL || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
                return EINVAL;
 
+       if (txn->mt_flags & MDB_TXN_ERROR)
+               return MDB_BAD_TXN;
+
        /* Allow read access to the freelist */
        if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
                return EINVAL;
@@ -5928,8 +6630,8 @@ mdb_cursor_count(MDB_cursor *mc, size_t *countp)
        if (mc == NULL || countp == NULL)
                return EINVAL;
 
-       if (!(mc->mc_db->md_flags & MDB_DUPSORT))
-               return EINVAL;
+       if (mc->mc_xcursor == NULL)
+               return MDB_INCOMPATIBLE;
 
        leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
        if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
@@ -5998,11 +6700,11 @@ mdb_update_key(MDB_cursor *mc, MDB_val *key)
                char kbuf2[(MDB_MAXKEYSIZE*2+1)];
                k2.mv_data = NODEKEY(node);
                k2.mv_size = node->mn_ksize;
-               DPRINTF("update key %u (ofs %u) [%s] to [%s] on page %zu",
+               DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
                        indx, ptr,
                        mdb_dkey(&k2, kbuf2),
                        DKEY(key),
-                       mp->mp_pgno);
+                       mp->mp_pgno));
        }
 #endif
 
@@ -6016,7 +6718,7 @@ mdb_update_key(MDB_cursor *mc, MDB_val *key)
                if (delta > 0 && SIZELEFT(mp) < delta) {
                        pgno_t pgno;
                        /* not enough space left, do a delete and split */
-                       DPRINTF("Not enough room, delta = %d, splitting...", delta);
+                       DPRINTF(("Not enough room, delta = %d, splitting...", delta));
                        pgno = NODEPGNO(node);
                        mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
                        return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
@@ -6126,12 +6828,12 @@ mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
                        return rc;
        }
 
-       DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
+       DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
            IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
            csrc->mc_ki[csrc->mc_top],
                DKEY(&key),
            csrc->mc_pg[csrc->mc_top]->mp_pgno,
-           cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
+           cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
 
        /* Add the node to the destination page.
         */
@@ -6149,9 +6851,6 @@ mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
                MDB_dbi dbi = csrc->mc_dbi;
                MDB_page *mp = csrc->mc_pg[csrc->mc_top];
 
-               if (csrc->mc_flags & C_SUB)
-                       dbi--;
-
                for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
                        if (csrc->mc_flags & C_SUB)
                                m3 = &m2->mc_xcursor->mx_cursor;
@@ -6177,8 +6876,8 @@ mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
                                key.mv_size = NODEKSZ(srcnode);
                                key.mv_data = NODEKEY(srcnode);
                        }
-                       DPRINTF("update separator for source page %zu to [%s]",
-                               csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
+                       DPRINTF(("update separator for source page %"Z"u to [%s]",
+                               csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
                        mdb_cursor_copy(csrc, &mn);
                        mn.mc_snum--;
                        mn.mc_top--;
@@ -6205,8 +6904,8 @@ mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
                                key.mv_size = NODEKSZ(srcnode);
                                key.mv_data = NODEKEY(srcnode);
                        }
-                       DPRINTF("update separator for destination page %zu to [%s]",
-                               cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
+                       DPRINTF(("update separator for destination page %"Z"u to [%s]",
+                               cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
                        mdb_cursor_copy(cdst, &mn);
                        mn.mc_snum--;
                        mn.mc_top--;
@@ -6243,8 +6942,8 @@ mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
        MDB_val          key, data;
        unsigned        nkeys;
 
-       DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
-               cdst->mc_pg[cdst->mc_top]->mp_pgno);
+       DPRINTF(("merging page %"Z"u into %"Z"u", csrc->mc_pg[csrc->mc_top]->mp_pgno,
+               cdst->mc_pg[cdst->mc_top]->mp_pgno));
 
        assert(csrc->mc_snum > 1);      /* can't merge root page */
        assert(cdst->mc_snum > 1);
@@ -6296,8 +6995,9 @@ mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
                }
        }
 
-       DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
-           cdst->mc_pg[cdst->mc_top]->mp_pgno, NUMKEYS(cdst->mc_pg[cdst->mc_top]), (float)PAGEFILL(cdst->mc_txn->mt_env, cdst->mc_pg[cdst->mc_top]) / 10);
+       DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
+           cdst->mc_pg[cdst->mc_top]->mp_pgno, NUMKEYS(cdst->mc_pg[cdst->mc_top]),
+               (float)PAGEFILL(cdst->mc_txn->mt_env, cdst->mc_pg[cdst->mc_top]) / 10));
 
        /* Unlink the src page from parent and add to free list.
         */
@@ -6325,9 +7025,6 @@ mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
                MDB_dbi dbi = csrc->mc_dbi;
                MDB_page *mp = cdst->mc_pg[cdst->mc_top];
 
-               if (csrc->mc_flags & C_SUB)
-                       dbi--;
-
                for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
                        if (csrc->mc_flags & C_SUB)
                                m3 = &m2->mc_xcursor->mx_cursor;
@@ -6387,9 +7084,10 @@ mdb_rebalance(MDB_cursor *mc)
        {
        pgno_t pgno;
        COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
-       DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
+       DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
            IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
-           pgno, NUMKEYS(mc->mc_pg[mc->mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10);
+           pgno, NUMKEYS(mc->mc_pg[mc->mc_top]),
+               (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
        }
 #endif
 
@@ -6398,8 +7096,8 @@ mdb_rebalance(MDB_cursor *mc)
 #if MDB_DEBUG
                pgno_t pgno;
                COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
-               DPRINTF("no need to rebalance page %zu, above fill threshold",
-                   pgno);
+               DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
+                   pgno));
 #endif
                return MDB_SUCCESS;
        }
@@ -6421,13 +7119,11 @@ mdb_rebalance(MDB_cursor *mc)
                        /* Adjust cursors pointing to mp */
                        mc->mc_snum = 0;
                        mc->mc_top = 0;
+                       mc->mc_flags &= ~C_INITIALIZED;
                        {
                                MDB_cursor *m2, *m3;
                                MDB_dbi dbi = mc->mc_dbi;
 
-                               if (mc->mc_flags & C_SUB)
-                                       dbi--;
-
                                for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
                                        if (mc->mc_flags & C_SUB)
                                                m3 = &m2->mc_xcursor->mx_cursor;
@@ -6437,6 +7133,7 @@ mdb_rebalance(MDB_cursor *mc)
                                        if (m3->mc_pg[0] == mp) {
                                                m3->mc_snum = 0;
                                                m3->mc_top = 0;
+                                               m3->mc_flags &= ~C_INITIALIZED;
                                        }
                                }
                        }
@@ -6457,9 +7154,6 @@ mdb_rebalance(MDB_cursor *mc)
                                MDB_cursor *m2, *m3;
                                MDB_dbi dbi = mc->mc_dbi;
 
-                               if (mc->mc_flags & C_SUB)
-                                       dbi--;
-
                                for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
                                        if (mc->mc_flags & C_SUB)
                                                m3 = &m2->mc_xcursor->mx_cursor;
@@ -6519,8 +7213,9 @@ mdb_rebalance(MDB_cursor *mc)
                mc->mc_ki[mc->mc_top] = 0;
        }
 
-       DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
-           mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10);
+       DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
+           mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
+               (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
 
        /* If the neighbor page is above threshold and has enough keys,
         * move one key from it. Otherwise we should try to merge them.
@@ -6532,8 +7227,11 @@ mdb_rebalance(MDB_cursor *mc)
        else {
                if (mc->mc_ki[ptop] == 0)
                        rc = mdb_page_merge(&mn, mc);
-               else
+               else {
+                       mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
                        rc = mdb_page_merge(mc, &mn);
+                       mdb_cursor_copy(&mn, mc);
+               }
                mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
        }
        return rc;
@@ -6546,6 +7244,7 @@ mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
        int rc;
        MDB_page *mp;
        indx_t ki;
+       unsigned int nkeys;
 
        mp = mc->mc_pg[mc->mc_top];
        ki = mc->mc_ki[mc->mc_top];
@@ -6565,30 +7264,34 @@ mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
        rc = mdb_rebalance(mc);
        if (rc != MDB_SUCCESS)
                mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
-       /* if mc points past last node in page, invalidate */
-       else if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
-               mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
-
-       {
-               /* Adjust other cursors pointing to mp */
+       else {
                MDB_cursor *m2;
-               unsigned int nkeys;
                MDB_dbi dbi = mc->mc_dbi;
 
                mp = mc->mc_pg[mc->mc_top];
                nkeys = NUMKEYS(mp);
+
+               /* if mc points past last node in page, find next sibling */
+               if (mc->mc_ki[mc->mc_top] >= nkeys)
+                       mdb_cursor_sibling(mc, 1);
+
+               /* Adjust other cursors pointing to mp */
                for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
                        if (m2 == mc)
                                continue;
                        if (!(m2->mc_flags & C_INITIALIZED))
                                continue;
                        if (m2->mc_pg[mc->mc_top] == mp) {
-                               if (m2->mc_ki[mc->mc_top] > ki)
-                                       m2->mc_ki[mc->mc_top]--;
+                               if (m2->mc_ki[mc->mc_top] >= ki) {
+                                       m2->mc_flags |= C_DEL;
+                                       if (m2->mc_ki[mc->mc_top] > ki)
+                                               m2->mc_ki[mc->mc_top]--;
+                               }
                                if (m2->mc_ki[mc->mc_top] >= nkeys)
-                                       m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
+                                       mdb_cursor_sibling(m2, 1);
                        }
                }
+               mc->mc_flags |= C_DEL;
        }
 
        return rc;
@@ -6607,22 +7310,25 @@ mdb_del(MDB_txn *txn, MDB_dbi dbi,
 
        assert(key != NULL);
 
-       DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
+       DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
 
        if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
                return EINVAL;
 
-       if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
-               return EACCES;
-       }
+       if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
+               return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
 
-       if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
-               return EINVAL;
+       if (key->mv_size > MDB_MAXKEYSIZE) {
+               return MDB_BAD_VALSIZE;
        }
 
        mdb_cursor_init(&mc, txn, dbi, &mx);
 
        exact = 0;
+       if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
+               /* must ignore any data */
+               data = NULL;
+       }
        if (data) {
                op = MDB_GET_BOTH;
                rdata = *data;
@@ -6641,6 +7347,7 @@ mdb_del(MDB_txn *txn, MDB_dbi dbi,
                 * run out of space, triggering a split. We need this
                 * cursor to be consistent until the end of the rebalance.
                 */
+               mc.mc_flags |= C_UNTRACK;
                mc.mc_next = txn->mt_cursors[dbi];
                txn->mt_cursors[dbi] = &mc;
                rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
@@ -6679,14 +7386,14 @@ mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno
        mp = mc->mc_pg[mc->mc_top];
        newindx = mc->mc_ki[mc->mc_top];
 
-       DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
+       DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i",
            IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
-           DKEY(newkey), mc->mc_ki[mc->mc_top]);
+           DKEY(newkey), mc->mc_ki[mc->mc_top]));
 
        /* Create a right sibling. */
        if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
                return rc;
-       DPRINTF("new right sibling: page %zu", rp->mp_pgno);
+       DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
 
        if (mc->mc_snum < 2) {
                if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
@@ -6697,7 +7404,7 @@ mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno
                mc->mc_pg[0] = pp;
                mc->mc_ki[0] = 0;
                mc->mc_db->md_root = pp->mp_pgno;
-               DPRINTF("root split! new root = %zu", pp->mp_pgno);
+               DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
                mc->mc_db->md_depth++;
                new_root = 1;
 
@@ -6715,7 +7422,7 @@ mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno
                ptop = 0;
        } else {
                ptop = mc->mc_top-1;
-               DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
+               DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
        }
 
        mc->mc_flags |= C_SPLITTING;
@@ -6858,7 +7565,7 @@ mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno
        }
 
 newsep:
-       DPRINTF("separator is [%s]", DKEY(&sepkey));
+       DPRINTF(("separator is [%s]", DKEY(&sepkey)));
 
        /* Copy separator key to the parent.
         */
@@ -7015,9 +7722,6 @@ done:
                MDB_dbi dbi = mc->mc_dbi;
                int fixup = NUMKEYS(mp);
 
-               if (mc->mc_flags & C_SUB)
-                       dbi--;
-
                for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
                        if (mc->mc_flags & C_SUB)
                                m3 = &m2->mc_xcursor->mx_cursor;
@@ -7025,7 +7729,7 @@ done:
                                m3 = m2;
                        if (m3 == mc)
                                continue;
-                       if (!(m3->mc_flags & C_INITIALIZED))
+                       if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
                                continue;
                        if (m3->mc_flags & C_SPLITTING)
                                continue;
@@ -7045,7 +7749,7 @@ done:
                                m3->mc_snum++;
                                m3->mc_top++;
                        }
-                       if (m3->mc_pg[mc->mc_top] == mp) {
+                       if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
                                if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
                                        m3->mc_ki[mc->mc_top]++;
                                if (m3->mc_ki[mc->mc_top] >= fixup) {
@@ -7053,7 +7757,7 @@ done:
                                        m3->mc_ki[mc->mc_top] -= fixup;
                                        m3->mc_ki[ptop] = mn.mc_ki[ptop];
                                }
-                       } else if (!did_split && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
+                       } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
                                m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
                                m3->mc_ki[ptop]++;
                        }
@@ -7075,14 +7779,6 @@ mdb_put(MDB_txn *txn, MDB_dbi dbi,
        if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
                return EINVAL;
 
-       if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
-               return EACCES;
-       }
-
-       if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
-               return EINVAL;
-       }
-
        if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP)) != flags)
                return EINVAL;
 
@@ -7165,7 +7861,12 @@ mdb_env_info(MDB_env *env, MDB_envinfo *arg)
        arg->me_mapaddr = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : 0;
        arg->me_mapsize = env->me_mapsize;
        arg->me_maxreaders = env->me_maxreaders;
-       arg->me_numreaders = env->me_numreaders;
+
+       /* me_numreaders may be zero if this process never used any readers. Use
+        * the shared numreader count if it exists.
+        */
+       arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : env->me_numreaders;
+
        arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
        arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
        return MDB_SUCCESS;
@@ -7209,6 +7910,8 @@ int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *db
 
        if ((flags & VALID_FLAGS) != flags)
                return EINVAL;
+       if (txn->mt_flags & MDB_TXN_ERROR)
+               return MDB_BAD_TXN;
 
        /* main DB? */
        if (!name) {
@@ -7263,7 +7966,7 @@ int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *db
                /* make sure this is actually a DB */
                MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
                if (!(node->mn_flags & F_SUBDATA))
-                       return EINVAL;
+                       return MDB_INCOMPATIBLE;
        } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
                /* Create if requested */
                MDB_db dummy;
@@ -7285,7 +7988,6 @@ int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *db
                txn->mt_dbflags[slot] = dbflag;
                memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
                *dbi = slot;
-               txn->mt_env->me_dbflags[slot] = txn->mt_dbs[slot].md_flags;
                mdb_default_cmp(txn, slot);
                if (!unused) {
                        txn->mt_numdbs++;
@@ -7321,6 +8023,15 @@ void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
        free(ptr);
 }
 
+int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
+{
+       /* We could return the flags for the FREE_DBI too but what's the point? */
+       if (txn == NULL || dbi < MAIN_DBI || dbi >= txn->mt_numdbs)
+               return EINVAL;
+       *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
+       return MDB_SUCCESS;
+}
+
 /** Add all the DB's pages to the free list.
  * @param[in] mc Cursor on the DB to free.
  * @param[in] subs non-Zero to check for sub-DBs in this DB.
@@ -7331,7 +8042,7 @@ mdb_drop0(MDB_cursor *mc, int subs)
 {
        int rc;
 
-       rc = mdb_page_search(mc, NULL, 0);
+       rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
        if (rc == MDB_SUCCESS) {
                MDB_txn *txn = mc->mc_txn;
                MDB_node *ni;
@@ -7485,4 +8196,133 @@ int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
        return MDB_SUCCESS;
 }
 
+int mdb_env_get_maxkeysize(MDB_env *env)
+{
+       return MDB_MAXKEYSIZE;
+}
+
+int mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
+{
+       unsigned int i, rdrs;
+       MDB_reader *mr;
+       char buf[64];
+       int first = 1;
+
+       if (!env || !func)
+               return -1;
+       if (!env->me_txns) {
+               return func("(no reader locks)\n", ctx);
+       }
+       rdrs = env->me_txns->mti_numreaders;
+       mr = env->me_txns->mti_readers;
+       for (i=0; i<rdrs; i++) {
+               if (mr[i].mr_pid) {
+                       size_t tid;
+                       int rc;
+                       tid = mr[i].mr_tid;
+                       if (mr[i].mr_txnid == (txnid_t)-1) {
+                               sprintf(buf, "%10d %"Z"x -\n", mr[i].mr_pid, tid);
+                       } else {
+                               sprintf(buf, "%10d %"Z"x %"Z"u\n", mr[i].mr_pid, tid, mr[i].mr_txnid);
+                       }
+                       if (first) {
+                               first = 0;
+                               func("    pid     thread     txnid\n", ctx);
+                       }
+                       rc = func(buf, ctx);
+                       if (rc < 0)
+                               return rc;
+               }
+       }
+       if (first) {
+               func("(no active readers)\n", ctx);
+       }
+       return 0;
+}
+
+/** Insert pid into list if not already present.
+ * return -1 if already present.
+ */
+static int mdb_pid_insert(pid_t *ids, pid_t pid)
+{
+       /* binary search of pid in list */
+       unsigned base = 0;
+       unsigned cursor = 1;
+       int val = 0;
+       unsigned n = ids[0];
+
+       while( 0 < n ) {
+               unsigned pivot = n >> 1;
+               cursor = base + pivot + 1;
+               val = pid - ids[cursor];
+
+               if( val < 0 ) {
+                       n = pivot;
+
+               } else if ( val > 0 ) {
+                       base = cursor;
+                       n -= pivot + 1;
+
+               } else {
+                       /* found, so it's a duplicate */
+                       return -1;
+               }
+       }
+
+       if( val > 0 ) {
+               ++cursor;
+       }
+       ids[0]++;
+       for (n = ids[0]; n > cursor; n--)
+               ids[n] = ids[n-1];
+       ids[n] = pid;
+       return 0;
+}
+
+int mdb_reader_check(MDB_env *env, int *dead)
+{
+       unsigned int i, j, rdrs;
+       MDB_reader *mr;
+       pid_t *pids, pid;
+       int count = 0;
+
+       if (!env)
+               return EINVAL;
+       if (dead)
+               *dead = 0;
+       if (!env->me_txns)
+               return MDB_SUCCESS;
+       rdrs = env->me_txns->mti_numreaders;
+       pids = malloc((rdrs+1) * sizeof(pid_t));
+       if (!pids)
+               return ENOMEM;
+       pids[0] = 0;
+       mr = env->me_txns->mti_readers;
+       j = 0;
+       for (i=0; i<rdrs; i++) {
+               if (mr[i].mr_pid && mr[i].mr_pid != env->me_pid) {
+                       pid = mr[i].mr_pid;
+                       if (mdb_pid_insert(pids, pid) == 0) {
+                               if (!mdb_reader_pid(env, Pidcheck, pid)) {
+                                       LOCK_MUTEX_R(env);
+                                       /* Recheck, a new process may have reused pid */
+                                       if (!mdb_reader_pid(env, Pidcheck, pid)) {
+                                               for (j=i; j<rdrs; j++)
+                                                       if (mr[j].mr_pid == pid) {
+                                                               DPRINTF(("clear stale reader pid %u txn %"Z"d",
+                                                                       (unsigned) pid, mr[j].mr_txnid));
+                                                               mr[j].mr_pid = 0;
+                                                               count++;
+                                                       }
+                                       }
+                                       UNLOCK_MUTEX_R(env);
+                               }
+                       }
+               }
+       }
+       free(pids);
+       if (dead)
+               *dead = count;
+       return MDB_SUCCESS;
+}
 /** @} */