]> git.sur5r.net Git - openldap/blobdiff - libraries/liblmdb/mdb.c
ITS#8263 streamline prev patch
[openldap] / libraries / liblmdb / mdb.c
index 6284edccd13753a0dd6a8ffa415461d8c1d3410f..03c4429169a23a312e6eef624e77314bd79b9a3c 100644 (file)
@@ -5,7 +5,7 @@
  *     BerkeleyDB API, but much simplified.
  */
 /*
- * Copyright 2011-2014 Howard Chu, Symas Corp.
+ * Copyright 2011-2015 Howard Chu, Symas Corp.
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
 #include <fcntl.h>
 #endif
 
+#if defined(__mips) && defined(__linux)
+/* MIPS has cache coherency issues, requires explicit cache control */
+#include <asm/cachectl.h>
+extern int cacheflush(char *addr, int nbytes, int cache);
+#define CACHEFLUSH(addr, bytes, cache) cacheflush(addr, bytes, cache)
+#else
+#define CACHEFLUSH(addr, bytes, cache)
+#endif
+
+#if defined(__linux) && !defined(MDB_FDATASYNC_WORKS)
+/** fdatasync is broken on ext3/ext4fs on older kernels, see
+ *     description in #mdb_env_open2 comments. You can safely
+ *     define MDB_FDATASYNC_WORKS if this code will only be run
+ *     on kernels 3.6 and newer.
+ */
+#define        BROKEN_FDATASYNC
+#endif
+
 #include <errno.h>
 #include <limits.h>
 #include <stddef.h>
 #include <time.h>
 #include <unistd.h>
 
+#if defined(__sun) || defined(ANDROID)
+/* Most platforms have posix_memalign, older may only have memalign */
+#define HAVE_MEMALIGN  1
+#include <malloc.h>
+#endif
+
 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
 #include <netinet/in.h>
 #include <resolv.h>    /* defines BYTE_ORDER on HPUX and Solaris */
@@ -422,18 +446,24 @@ static txnid_t mdb_debug_start;
        /**     The version number for a database's lockfile format. */
 #define MDB_LOCK_VERSION        1
 
-       /**     @brief The max size of a key we can write, or 0 for dynamic max.
+       /**     @brief The max size of a key we can write, or 0 for computed max.
         *
-        *      Define this as 0 to compute the max from the page size.  511
-        *      is default for backwards compat: liblmdb <= 0.9.10 can break
-        *      when modifying a DB with keys/dupsort data bigger than its max.
+        *      This macro should normally be left alone or set to 0.
+        *      Note that a database with big keys or dupsort data cannot be
+        *      reliably modified by a liblmdb which uses a smaller max.
+        *      The default is 511 for backwards compat, or 0 when #MDB_DEVEL.
+        *
+        *      Other values are allowed, for backwards compat.  However:
+        *      A value bigger than the computed max can break if you do not
+        *      know what you are doing, and liblmdb <= 0.9.10 can break when
+        *      modifying a DB with keys/dupsort data bigger than its max.
         *
         *      Data items in an #MDB_DUPSORT database are also limited to
         *      this size, since they're actually keys of a sub-DB.  Keys and
         *      #MDB_DUPSORT data items must fit on a node in a regular page.
         */
 #ifndef MDB_MAXKEYSIZE
-#define MDB_MAXKEYSIZE  511
+#define MDB_MAXKEYSIZE  ((MDB_DEVEL) ? 0 : 511)
 #endif
 
        /**     The maximum size of a key we can write to the environment. */
@@ -563,11 +593,11 @@ typedef struct MDB_rxbody {
         *      started from so we can avoid overwriting any data used in that
         *      particular version.
         */
-       txnid_t         mrb_txnid;
+       volatile txnid_t                mrb_txnid;
        /** The process ID of the process owning this reader txn. */
-       MDB_PID_T       mrb_pid;
+       volatile MDB_PID_T      mrb_pid;
        /** The thread ID of the thread owning this txn. */
-       MDB_THR_T       mrb_tid;
+       volatile MDB_THR_T      mrb_tid;
 } MDB_rxbody;
 
        /** The actual reader record, with cacheline padding. */
@@ -615,12 +645,12 @@ typedef struct MDB_txbody {
                 *      This is recorded here only for convenience; the value can always
                 *      be determined by reading the main database meta pages.
                 */
-       txnid_t         mtb_txnid;
+       volatile txnid_t                mtb_txnid;
                /** The number of slots that have been used in the reader table.
                 *      This always records the maximum count, it is not decremented
                 *      when readers release their slots.
                 */
-       unsigned        mtb_numreaders;
+       volatile unsigned       mtb_numreaders;
 } MDB_txbody;
 
        /** The actual reader table definition. */
@@ -734,7 +764,7 @@ typedef struct MDB_page {
        /** The number of overflow pages needed to store the given size. */
 #define OVPAGES(size, psize)   ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
 
-       /** Link in #MDB_txn.%mt_loose_pages list */
+       /** Link in #MDB_txn.%mt_loose_pgs list */
 #define NEXT_LOOSE_PAGE(p)             (*(MDB_page **)((p) + 2))
 
        /** Header for a single key/data pair within a page.
@@ -881,7 +911,7 @@ typedef struct MDB_meta {
                /** Stamp identifying this as an LMDB file. It must be set
                 *      to #MDB_MAGIC. */
        uint32_t        mm_magic;
-               /** Version number of this lock file. Must be set to #MDB_DATA_VERSION. */
+               /** Version number of this 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 */
@@ -891,7 +921,7 @@ typedef struct MDB_meta {
        /** Any persistent environment flags. @ref mdb_env */
 #define        mm_flags        mm_dbs[0].md_flags
        pgno_t          mm_last_pg;                     /**< last used page in file */
-       txnid_t         mm_txnid;                       /**< txnid that committed this page */
+       volatile txnid_t        mm_txnid;       /**< txnid that committed this page */
 } MDB_meta;
 
        /** Buffer for a stack-allocated meta page.
@@ -939,6 +969,8 @@ struct MDB_txn {
         *      in this transaction, linked through #NEXT_LOOSE_PAGE(page).
         */
        MDB_page        *mt_loose_pgs;
+       /* #Number of loose pages (#mt_loose_pgs) */
+       int                     mt_loose_count;
        /** 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.
@@ -1073,12 +1105,12 @@ struct MDB_env {
        HANDLE          me_mfd;                 /**< just for writing the meta pages */
        /** Failed to update the meta page. Probably an I/O error. */
 #define        MDB_FATAL_ERROR 0x80000000U
-       /** We're explicitly changing the mapsize. */
-#define        MDB_RESIZING    0x40000000U
        /** Some fields are initialized. */
 #define        MDB_ENV_ACTIVE  0x20000000U
        /** me_txkey is set */
 #define        MDB_ENV_TXKEY   0x10000000U
+       /** fdatasync is unreliable */
+#define        MDB_FSYNCONLY   0x08000000U
        uint32_t        me_flags;               /**< @ref mdb_env */
        unsigned int    me_psize;       /**< DB page size, inited from me_os_psize */
        unsigned int    me_os_psize;    /**< OS page size, from #GET_PAGESIZE */
@@ -1093,6 +1125,7 @@ struct MDB_env {
        MDB_meta        *me_metas[2];   /**< pointers to the two meta pages */
        void            *me_pbuf;               /**< scratch area for DUPSORT put() */
        MDB_txn         *me_txn;                /**< current write transaction */
+       MDB_txn         *me_txn0;               /**< prealloc'd write transaction */
        size_t          me_mapsize;             /**< size of the data memory map */
        off_t           me_size;                /**< current file size */
        pgno_t          me_maxpg;               /**< me_mapsize / me_psize */
@@ -1100,6 +1133,7 @@ struct MDB_env {
        uint16_t        *me_dbflags;    /**< array of flags from MDB_db.md_flags */
        unsigned int    *me_dbiseqs;    /**< array of dbi sequence numbers */
        pthread_key_t   me_txkey;       /**< thread-key for readers */
+       txnid_t         me_pgoldest;    /**< ID of oldest reader last time we looked */
        MDB_pgstate     me_pgstate;             /**< state of old pages from freeDB */
 #      define          me_pglast       me_pgstate.mf_pglast
 #      define          me_pghead       me_pgstate.mf_pghead
@@ -1208,6 +1242,7 @@ static int        mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
 static void    mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
 static void    mdb_xcursor_init0(MDB_cursor *mc);
 static void    mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
+static void    mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int force);
 
 static int     mdb_drop0(MDB_cursor *mc, int subs);
 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
@@ -1216,6 +1251,13 @@ static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
 static MDB_cmp_func    mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
 /** @endcond */
 
+/** Compare two items pointing at size_t's of unknown alignment. */
+#ifdef MISALIGNED_OK
+# define mdb_cmp_clong mdb_cmp_long
+#else
+# define mdb_cmp_clong mdb_cmp_cint
+#endif
+
 #ifdef _WIN32
 static SECURITY_DESCRIPTOR mdb_null_sd;
 static SECURITY_ATTRIBUTES mdb_all_sa;
@@ -1297,7 +1339,7 @@ mdb_strerror(int err)
        buf[0] = 0;
        FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
                FORMAT_MESSAGE_IGNORE_INSERTS,
-               NULL, err, 0, ptr, sizeof(buf), pad);
+               NULL, err, 0, ptr, sizeof(buf), (va_list *)pad);
        return ptr;
 #else
        return strerror(err);
@@ -1529,7 +1571,12 @@ mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
 int
 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);
+       MDB_cmp_func *dcmp = txn->mt_dbxs[dbi].md_dcmp;
+#if UINT_MAX < SIZE_MAX
+       if (dcmp == mdb_cmp_int && a->mv_size == sizeof(size_t))
+               dcmp = mdb_cmp_clong;
+#endif
+       return dcmp(a, b);
 }
 
 /** Allocate memory for a page.
@@ -1623,10 +1670,11 @@ mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
 {
        int loose = 0;
        pgno_t pgno = mp->mp_pgno;
+       MDB_txn *txn = mc->mc_txn;
 
        if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
-               if (mc->mc_txn->mt_parent) {
-                       MDB_ID2 *dl = mc->mc_txn->mt_u.dirty_list;
+               if (txn->mt_parent) {
+                       MDB_ID2 *dl = txn->mt_u.dirty_list;
                        /* If txn has a parent, make sure the page is in our
                         * dirty list.
                         */
@@ -1635,7 +1683,7 @@ mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
                                if (x <= dl[0].mid && dl[x].mid == pgno) {
                                        if (mp != dl[x].mptr) { /* bad cursor? */
                                                mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
-                                               mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
+                                               txn->mt_flags |= MDB_TXN_ERROR;
                                                return MDB_CORRUPTED;
                                        }
                                        /* ok, it's ours */
@@ -1650,11 +1698,12 @@ mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
        if (loose) {
                DPRINTF(("loosen db %d page %"Z"u", DDBI(mc),
                        mp->mp_pgno));
-               NEXT_LOOSE_PAGE(mp) = mc->mc_txn->mt_loose_pgs;
-               mc->mc_txn->mt_loose_pgs = mp;
+               NEXT_LOOSE_PAGE(mp) = txn->mt_loose_pgs;
+               txn->mt_loose_pgs = mp;
+               txn->mt_loose_count++;
                mp->mp_flags |= P_LOOSE;
        } else {
-               int rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, pgno);
+               int rc = mdb_midl_append(&txn->mt_free_pgs, pgno);
                if (rc)
                        return rc;
        }
@@ -1927,20 +1976,22 @@ mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
 #else
        enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
 #endif
-       int rc, retry = num * 20;
+       int rc, retry = num * 60;
        MDB_txn *txn = mc->mc_txn;
        MDB_env *env = txn->mt_env;
        pgno_t pgno, *mop = env->me_pghead;
-       unsigned i, j, k, mop_len = mop ? mop[0] : 0, n2 = num-1;
+       unsigned i, j, mop_len = mop ? mop[0] : 0, n2 = num-1;
        MDB_page *np;
        txnid_t oldest = 0, last;
        MDB_cursor_op op;
        MDB_cursor m2;
+       int found_old = 0;
 
        /* If there are any loose pages, just use them */
        if (num == 1 && txn->mt_loose_pgs) {
                np = txn->mt_loose_pgs;
                txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
+               txn->mt_loose_count--;
                DPRINTF(("db %d use loose page %"Z"u", DDBI(mc),
                                np->mp_pgno));
                *mp = np;
@@ -1958,7 +2009,7 @@ mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
        for (op = MDB_FIRST;; op = MDB_NEXT) {
                MDB_val key, data;
                MDB_node *leaf;
-               pgno_t *idl, old_id, new_id;
+               pgno_t *idl;
 
                /* Seek a big enough contiguous page range. Prefer
                 * pages at the tail, just truncating the list.
@@ -1976,8 +2027,8 @@ mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
 
                if (op == MDB_FIRST) {  /* 1st iteration */
                        /* Prepare to fetch more and coalesce */
-                       oldest = mdb_find_oldest(txn);
                        last = env->me_pglast;
+                       oldest = env->me_pgoldest;
                        mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
                        if (last) {
                                op = MDB_SET_RANGE;
@@ -1992,8 +2043,15 @@ mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
 
                last++;
                /* Do not fetch more if the record will be too recent */
-               if (oldest <= last)
-                       break;
+               if (oldest <= last) {
+                       if (!found_old) {
+                               oldest = mdb_find_oldest(txn);
+                               env->me_pgoldest = oldest;
+                               found_old = 1;
+                       }
+                       if (oldest <= last)
+                               break;
+               }
                rc = mdb_cursor_get(&m2, &key, NULL, op);
                if (rc) {
                        if (rc == MDB_NOTFOUND)
@@ -2001,8 +2059,15 @@ mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
                        goto fail;
                }
                last = *(txnid_t*)key.mv_data;
-               if (oldest <= last)
-                       break;
+               if (oldest <= last) {
+                       if (!found_old) {
+                               oldest = mdb_find_oldest(txn);
+                               env->me_pgoldest = oldest;
+                               found_old = 1;
+                       }
+                       if (oldest <= last)
+                               break;
+               }
                np = m2.mc_pg[m2.mc_top];
                leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
                if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
@@ -2024,21 +2089,12 @@ mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
 #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 %"Z"u", idl[k]));
+               for (j = i; j; j--)
+                       DPRINTF(("IDL %"Z"u", idl[j]));
 #endif
                /* Merge in descending sorted order */
-               j = mop_len;
-               k = mop_len += i;
-               mop[0] = (pgno_t)-1;
-               old_id = mop[j];
-               while (i) {
-                       new_id = idl[i--];
-                       for (; old_id < new_id; old_id = mop[--j])
-                               mop[k--] = old_id;
-                       mop[k--] = new_id;
-               }
-               mop[0] = mop_len;
+               mdb_midl_xmerge(mop, idl);
+               mop_len = mop[0];
        }
 
        /* Use new pages from the map when nothing suitable in the freeDB */
@@ -2274,6 +2330,8 @@ int
 mdb_env_sync(MDB_env *env, int force)
 {
        int rc = 0;
+       if (env->me_flags & MDB_RDONLY)
+               return EACCES;
        if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
                if (env->me_flags & MDB_WRITEMAP) {
                        int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
@@ -2285,6 +2343,12 @@ mdb_env_sync(MDB_env *env, int force)
                                rc = ErrCode();
 #endif
                } else {
+#ifdef BROKEN_FDATASYNC
+                       if (env->me_flags & MDB_FSYNCONLY) {
+                               if (fsync(env->me_fd))
+                                       rc = ErrCode();
+                       } else
+#endif
                        if (MDB_FDATASYNC(env->me_fd))
                                rc = ErrCode();
                }
@@ -2440,15 +2504,11 @@ mdb_txn_renew0(MDB_txn *txn)
        MDB_env *env = txn->mt_env;
        MDB_txninfo *ti = env->me_txns;
        MDB_meta *meta;
-       unsigned int i, nr;
+       unsigned int i, nr, flags = txn->mt_flags;
        uint16_t x;
        int rc, new_notls = 0;
 
-       /* Setup db info */
-       txn->mt_numdbs = env->me_numdbs;
-       txn->mt_dbxs = env->me_dbxs;    /* mostly static anyway */
-
-       if (txn->mt_flags & MDB_TXN_RDONLY) {
+       if ((flags &= MDB_TXN_RDONLY) != 0) {
                if (!ti) {
                        meta = env->me_metas[ mdb_env_pick_meta(env) ];
                        txn->mt_txnid = meta->mm_txnid;
@@ -2494,10 +2554,14 @@ mdb_txn_renew0(MDB_txn *txn)
                                        return rc;
                                }
                        }
-                       txn->mt_txnid = r->mr_txnid = ti->mti_txnid;
+                       do /* LY: Retry on a race, ITS#7970. */
+                               r->mr_txnid = ti->mti_txnid;
+                       while(r->mr_txnid != ti->mti_txnid);
+                       txn->mt_txnid = r->mr_txnid;
                        txn->mt_u.reader = r;
                        meta = env->me_metas[txn->mt_txnid & 1];
                }
+               txn->mt_dbxs = env->me_dbxs;    /* mostly static anyway */
        } else {
                if (ti) {
                        LOCK_MUTEX_W(env);
@@ -2513,6 +2577,9 @@ mdb_txn_renew0(MDB_txn *txn)
                if (txn->mt_txnid == mdb_debug_start)
                        mdb_debug = 1;
 #endif
+               txn->mt_child = NULL;
+               txn->mt_loose_pgs = NULL;
+               txn->mt_loose_count = 0;
                txn->mt_dirty_room = MDB_IDL_UM_MAX;
                txn->mt_u.dirty_list = env->me_dirty_list;
                txn->mt_u.dirty_list[0].mid = 0;
@@ -2529,6 +2596,10 @@ mdb_txn_renew0(MDB_txn *txn)
        /* Moved to here to avoid a data race in read TXNs */
        txn->mt_next_pgno = meta->mm_last_pg+1;
 
+       txn->mt_flags = flags;
+
+       /* Setup db info */
+       txn->mt_numdbs = env->me_numdbs;
        for (i=2; i<txn->mt_numdbs; i++) {
                x = env->me_dbflags[i];
                txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
@@ -2536,9 +2607,7 @@ mdb_txn_renew0(MDB_txn *txn)
        }
        txn->mt_dbflags[0] = txn->mt_dbflags[1] = DB_VALID;
 
-       /* If we didn't ask for a resize, but the size grew, fail */
-       if (!(env->me_flags & MDB_RESIZING)
-               && env->me_mapsize < meta->mm_mapsize) {
+       if (env->me_maxpg < txn->mt_next_pgno) {
                mdb_txn_reset0(txn, "renew0-mapfail");
                if (new_notls) {
                        txn->mt_u.reader->mr_pid = 0;
@@ -2596,13 +2665,16 @@ mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
                }
                tsize = sizeof(MDB_ntxn);
        }
-       size = tsize + env->me_maxdbs * (sizeof(MDB_db)+1);
+       size = tsize;
        if (!(flags & MDB_RDONLY)) {
+               if (!parent) {
+                       txn = env->me_txn0;     /* just reuse preallocated write txn */
+                       goto ok;
+               }
+               /* child txns use own copy of cursors */
                size += env->me_maxdbs * sizeof(MDB_cursor *);
-               /* child txns use parent's dbiseqs */
-               if (!parent)
-                       size += env->me_maxdbs * sizeof(unsigned int);
        }
+       size += env->me_maxdbs * (sizeof(MDB_db)+1);
 
        if ((txn = calloc(1, size)) == NULL) {
                DPRINTF(("calloc: %s", strerror(errno)));
@@ -2625,6 +2697,7 @@ mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
        }
        txn->mt_env = env;
 
+ok:
        if (parent) {
                unsigned int i;
                txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
@@ -2667,9 +2740,10 @@ mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
        } else {
                rc = mdb_txn_renew0(txn);
        }
-       if (rc)
-               free(txn);
-       else {
+       if (rc) {
+               if (txn != env->me_txn0)
+                       free(txn);
+       } else {
                *ret = txn;
                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',
@@ -2741,31 +2815,33 @@ mdb_txn_reset0(MDB_txn *txn, const char *act)
                txn->mt_numdbs = 0;             /* close nothing if called again */
                txn->mt_dbxs = NULL;    /* mark txn as reset */
        } else {
-               mdb_cursors_close(txn, 0);
+               pgno_t *pghead = env->me_pghead;
 
+               mdb_cursors_close(txn, 0);
                if (!(env->me_flags & MDB_WRITEMAP)) {
                        mdb_dlist_free(txn);
                }
-               mdb_midl_free(env->me_pghead);
 
-               if (txn->mt_parent) {
+               if (!txn->mt_parent) {
+                       mdb_midl_shrink(&txn->mt_free_pgs);
+                       env->me_free_pgs = txn->mt_free_pgs;
+                       /* me_pgstate: */
+                       env->me_pghead = NULL;
+                       env->me_pglast = 0;
+
+                       env->me_txn = NULL;
+                       /* The writer mutex was locked in mdb_txn_begin. */
+                       if (env->me_txns)
+                               UNLOCK_MUTEX_W(env);
+               } else {
                        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;
                }
 
-               if (mdb_midl_shrink(&txn->mt_free_pgs))
-                       env->me_free_pgs = txn->mt_free_pgs;
-               env->me_pghead = NULL;
-               env->me_pglast = 0;
-
-               env->me_txn = NULL;
-               /* The writer mutex was locked in mdb_txn_begin. */
-               if (env->me_txns)
-                       UNLOCK_MUTEX_W(env);
+               mdb_midl_free(pghead);
        }
 }
 
@@ -2796,7 +2872,8 @@ mdb_txn_abort(MDB_txn *txn)
        if ((txn->mt_flags & MDB_TXN_RDONLY) && txn->mt_u.reader)
                txn->mt_u.reader->mr_pid = 0;
 
-       free(txn);
+       if (txn != txn->mt_env->me_txn0)
+               free(txn);
 }
 
 /** Save the freelist as of this transaction to the freeDB.
@@ -2825,30 +2902,17 @@ mdb_freelist_save(MDB_txn *txn)
                        return rc;
        }
 
-       /* Dispose of loose pages. Usually they will have all
-        * been used up by the time we get here.
-        */
-       if (txn->mt_loose_pgs) {
+       if (!env->me_pghead && txn->mt_loose_pgs) {
+               /* Put loose page numbers in mt_free_pgs, since
+                * we may be unable to return them to me_pghead.
+                */
                MDB_page *mp = txn->mt_loose_pgs;
-               /* Just return them to freeDB */
-               if (env->me_pghead) {
-                       int i, j;
-                       mop = env->me_pghead;
-                       for (; mp; mp = NEXT_LOOSE_PAGE(mp)) {
-                               pgno_t pg = mp->mp_pgno;
-                               j = mop[0] + 1;
-                               for (i = mop[0]; i && mop[i] < pg; i--)
-                                       mop[j--] = mop[i];
-                               mop[j] = pg;
-                               mop[0] += 1;
-                       }
-               } else {
-               /* Oh well, they were wasted. Put on freelist */
-                       for (; mp; mp = NEXT_LOOSE_PAGE(mp)) {
-                               mdb_midl_append(&txn->mt_free_pgs, mp->mp_pgno);
-                       }
-               }
+               if ((rc = mdb_midl_need(&txn->mt_free_pgs, txn->mt_loose_count)) != 0)
+                       return rc;
+               for (; mp; mp = NEXT_LOOSE_PAGE(mp))
+                       mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
                txn->mt_loose_pgs = NULL;
+               txn->mt_loose_count = 0;
        }
 
        /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
@@ -2912,7 +2976,7 @@ mdb_freelist_save(MDB_txn *txn)
                }
 
                mop = env->me_pghead;
-               mop_len = mop ? mop[0] : 0;
+               mop_len = (mop ? mop[0] : 0) + txn->mt_loose_count;
 
                /* Reserve records for me_pghead[]. Split it if multi-page,
                 * to avoid searching freeDB for a page range. Use keys in
@@ -2952,6 +3016,28 @@ mdb_freelist_save(MDB_txn *txn)
                total_room += head_room;
        }
 
+       /* Return loose page numbers to me_pghead, though usually none are
+        * left at this point.  The pages themselves remain in dirty_list.
+        */
+       if (txn->mt_loose_pgs) {
+               MDB_page *mp = txn->mt_loose_pgs;
+               unsigned count = txn->mt_loose_count;
+               MDB_IDL loose;
+               /* Room for loose pages + temp IDL with same */
+               if ((rc = mdb_midl_need(&env->me_pghead, 2*count+1)) != 0)
+                       return rc;
+               mop = env->me_pghead;
+               loose = mop + MDB_IDL_ALLOCLEN(mop) - count;
+               for (count = 0; mp; mp = NEXT_LOOSE_PAGE(mp))
+                       loose[ ++count ] = mp->mp_pgno;
+               loose[0] = count;
+               mdb_midl_sort(loose);
+               mdb_midl_xmerge(mop, loose);
+               txn->mt_loose_pgs = NULL;
+               txn->mt_loose_count = 0;
+               mop_len = mop[0];
+       }
+
        /* Fill in the reserved me_pghead records */
        rc = MDB_SUCCESS;
        if (mop_len) {
@@ -3063,6 +3149,7 @@ mdb_page_flush(MDB_txn *txn, int keep)
                /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
                if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
                        if (n) {
+retry_write:
                                /* Write previous page(s) */
 #ifdef MDB_USE_PWRITEV
                                wres = pwritev(env->me_fd, iov, n, wpos);
@@ -3070,8 +3157,11 @@ mdb_page_flush(MDB_txn *txn, int keep)
                                if (n == 1) {
                                        wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
                                } else {
+retry_seek:
                                        if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
                                                rc = ErrCode();
+                                               if (rc == EINTR)
+                                                       goto retry_seek;
                                                DPRINTF(("lseek: %s", strerror(rc)));
                                                return rc;
                                        }
@@ -3081,6 +3171,8 @@ mdb_page_flush(MDB_txn *txn, int keep)
                                if (wres != wsize) {
                                        if (wres < 0) {
                                                rc = ErrCode();
+                                               if (rc == EINTR)
+                                                       goto retry_write;
                                                DPRINTF(("Write error: %s", strerror(rc)));
                                        } else {
                                                rc = EIO; /* TODO: Use which error code? */
@@ -3104,6 +3196,12 @@ mdb_page_flush(MDB_txn *txn, int keep)
 #endif /* _WIN32 */
        }
 
+       /* MIPS has cache coherency issues, this is a no-op everywhere else
+        * Note: for any size >= on-chip cache size, entire on-chip cache is
+        * flushed.
+        */
+       CACHEFLUSH(env->me_map, txn->mt_next_pgno * env->me_psize, DCACHE);
+
        for (i = keep; ++i <= pagecount; ) {
                dp = dl[i].mptr;
                /* This is a page we skipped above */
@@ -3260,6 +3358,7 @@ mdb_txn_commit(MDB_txn *txn)
                for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(lp))
                        ;
                *lp = txn->mt_loose_pgs;
+               parent->mt_loose_count += txn->mt_loose_count;
 
                parent->mt_child = NULL;
                mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
@@ -3276,13 +3375,8 @@ 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|MDB_TXN_SPILLS))) {
-               if ((env->me_flags & MDB_RESIZING)
-                       && (rc = mdb_env_write_meta(txn))) {
-                       goto fail;
-               }
+               !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
                goto done;
-       }
 
        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));
@@ -3302,7 +3396,8 @@ mdb_txn_commit(MDB_txn *txn)
                                        goto fail;
                                }
                                data.mv_data = &txn->mt_dbs[i];
-                               rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
+                               rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data,
+                                       F_SUBDATA);
                                if (rc)
                                        goto fail;
                        }
@@ -3315,17 +3410,22 @@ mdb_txn_commit(MDB_txn *txn)
 
        mdb_midl_free(env->me_pghead);
        env->me_pghead = NULL;
-       if (mdb_midl_shrink(&txn->mt_free_pgs))
-               env->me_free_pgs = txn->mt_free_pgs;
+       mdb_midl_shrink(&txn->mt_free_pgs);
+       env->me_free_pgs = txn->mt_free_pgs;
 
 #if (MDB_DEBUG) > 2
        mdb_audit(txn);
 #endif
 
        if ((rc = mdb_page_flush(txn, 0)) ||
+               (rc = mdb_env_sync(env, 0)) ||
                (rc = mdb_env_write_meta(txn)))
                goto fail;
 
+       /* Free P_LOOSE pages left behind in dirty_list */
+       if (!(env->me_flags & MDB_WRITEMAP))
+               mdb_dlist_free(txn);
+
 done:
        env->me_pglast = 0;
        env->me_txn = NULL;
@@ -3333,7 +3433,8 @@ done:
 
        if (env->me_txns)
                UNLOCK_MUTEX_W(env);
-       free(txn);
+       if (txn != env->me_txn0)
+               free(txn);
 
        return MDB_SUCCESS;
 
@@ -3442,7 +3543,8 @@ mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
        int len;
 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
        len = pwrite(fd, ptr, size, pos);       \
-       rc = (len >= 0); } while(0)
+       if (len == -1 && ErrCode() == EINTR) continue; \
+       rc = (len >= 0); break; } while(1)
 #endif
 
        DPUTS("writing new meta page");
@@ -3452,6 +3554,9 @@ mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
        mdb_env_init_meta0(env, meta);
 
        p = calloc(2, psize);
+       if (!p)
+               return ENOMEM;
+
        p->mp_pgno = 0;
        p->mp_flags = P_META;
        *(MDB_meta *)METADATA(p) = *meta;
@@ -3479,8 +3584,9 @@ mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
 static int
 mdb_env_write_meta(MDB_txn *txn)
 {
-       MDB_env *env = txn->mt_env;
+       MDB_env *env;
        MDB_meta        meta, metab, *mp;
+       size_t mapsize;
        off_t off;
        int rc, len, toggle;
        char *ptr;
@@ -3491,22 +3597,19 @@ mdb_env_write_meta(MDB_txn *txn)
        int r2;
 #endif
 
-       /* Sync data and previous metapage before writing a new metapage */
-       if ((rc = mdb_env_sync(env, 0)) != MDB_SUCCESS)
-               return rc;
-
        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];
+       mapsize = env->me_metas[toggle ^ 1]->mm_mapsize;
+       /* Persist any increases of mapsize config */
+       if (mapsize < env->me_mapsize)
+               mapsize = env->me_mapsize;
 
        if (env->me_flags & MDB_WRITEMAP) {
-               /* Persist any changes of mapsize config */
-               if (env->me_flags & MDB_RESIZING) {
-                       mp->mm_mapsize = env->me_mapsize;
-                       env->me_flags ^= MDB_RESIZING;
-               }
+               mp->mm_mapsize = mapsize;
                mp->mm_dbs[0] = txn->mt_dbs[0];
                mp->mm_dbs[1] = txn->mt_dbs[1];
                mp->mm_last_pg = txn->mt_next_pgno - 1;
@@ -3533,23 +3636,15 @@ mdb_env_write_meta(MDB_txn *txn)
        metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
        metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
 
-       ptr = (char *)&meta;
-       if (env->me_flags & MDB_RESIZING) {
-               /* Persist any changes of mapsize config */
-               meta.mm_mapsize = env->me_mapsize;
-               off = offsetof(MDB_meta, mm_mapsize);
-               env->me_flags ^= MDB_RESIZING;
-       } else {
-               off = offsetof(MDB_meta, mm_dbs[0].md_depth);
-       }
-       len = sizeof(MDB_meta) - off;
-
-       ptr += off;
+       meta.mm_mapsize = mapsize;
        meta.mm_dbs[0] = txn->mt_dbs[0];
        meta.mm_dbs[1] = txn->mt_dbs[1];
        meta.mm_last_pg = txn->mt_next_pgno - 1;
        meta.mm_txnid = txn->mt_txnid;
 
+       off = offsetof(MDB_meta, mm_mapsize);
+       ptr = (char *)&meta + off;
+       len = sizeof(MDB_meta) - off;
        if (toggle)
                off += env->me_psize;
        off += PAGEHDRSZ;
@@ -3565,10 +3660,15 @@ mdb_env_write_meta(MDB_txn *txn)
                        rc = -1;
        }
 #else
+retry_write:
        rc = pwrite(mfd, ptr, len, off);
 #endif
        if (rc != len) {
                rc = rc < 0 ? ErrCode() : EIO;
+#ifndef _WIN32
+               if (rc == EINTR)
+                       goto retry_write;
+#endif
                DPUTS("write failed, disk error?");
                /* On a failure, the pagecache still contains the new data.
                 * Write some old data back, to prevent it from being used.
@@ -3588,6 +3688,8 @@ fail:
                env->me_flags |= MDB_FATAL_ERROR;
                return rc;
        }
+       /* MIPS has cache coherency issues, this is a no-op everywhere else */
+       CACHEFLUSH(env->me_map + off, len, DCACHE);
 done:
        /* Memory ordering issues are irrelevant; since the entire writer
         * is wrapped by wmutex, all of these changes will become visible
@@ -3727,25 +3829,19 @@ mdb_env_set_mapsize(MDB_env *env, size_t size)
         * sure there are no active txns.
         */
        if (env->me_map) {
-               int rc, change = 0;
+               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;
-                       }
-                       /* nothing actually changed */
-                       if (size == env->me_mapsize)
-                               return MDB_SUCCESS;
-                       change = 1;
+               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;
@@ -3753,8 +3849,6 @@ mdb_env_set_mapsize(MDB_env *env, size_t size)
                rc = mdb_env_map(env, old);
                if (rc)
                        return rc;
-               if (change)
-                       env->me_flags |= MDB_RESIZING;
        }
        env->me_mapsize = size;
        if (env->me_psize)
@@ -3789,6 +3883,32 @@ mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
        return MDB_SUCCESS;
 }
 
+static int ESECT
+mdb_fsize(HANDLE fd, size_t *size)
+{
+#ifdef _WIN32
+       LARGE_INTEGER fsize;
+
+       if (!GetFileSizeEx(fd, &fsize))
+               return ErrCode();
+
+       *size = fsize.QuadPart;
+#else
+       struct stat st;
+
+       if (fstat(fd, &st))
+               return ErrCode();
+
+       *size = st.st_size;
+#endif
+       return MDB_SUCCESS;
+}
+
+#ifdef BROKEN_FDATASYNC
+#include <sys/utsname.h>
+#include <sys/vfs.h>
+#endif
+
 /** Further setup required for opening an LMDB environment
  */
 static int ESECT
@@ -3806,6 +3926,53 @@ mdb_env_open2(MDB_env *env)
        else
                env->me_pidquery = PROCESS_QUERY_INFORMATION;
 #endif /* _WIN32 */
+#ifdef BROKEN_FDATASYNC
+       /* ext3/ext4 fdatasync is broken on some older Linux kernels.
+        * https://lkml.org/lkml/2012/9/3/83
+        * Kernels after 3.6-rc6 are known good.
+        * https://lkml.org/lkml/2012/9/10/556
+        * See if the DB is on ext3/ext4, then check for new enough kernel
+        * Kernels 2.6.32.60, 2.6.34.15, 3.2.30, and 3.5.4 are also known
+        * to be patched.
+        */
+       {
+               struct statfs st;
+               fstatfs(env->me_fd, &st);
+               while (st.f_type == 0xEF53) {
+                       struct utsname uts;
+                       int i;
+                       uname(&uts);
+                       if (uts.release[0] < '3') {
+                               if (!strncmp(uts.release, "2.6.32.", 7)) {
+                                       i = atoi(uts.release+7);
+                                       if (i >= 60)
+                                               break;  /* 2.6.32.60 and newer is OK */
+                               } else if (!strncmp(uts.release, "2.6.34.", 7)) {
+                                       i = atoi(uts.release+7);
+                                       if (i >= 15)
+                                               break;  /* 2.6.34.15 and newer is OK */
+                               }
+                       } else if (uts.release[0] == '3') {
+                               i = atoi(uts.release+2);
+                               if (i > 5)
+                                       break;  /* 3.6 and newer is OK */
+                               if (i == 5) {
+                                       i = atoi(uts.release+4);
+                                       if (i >= 4)
+                                               break;  /* 3.5.4 and newer is OK */
+                               } else if (i == 2) {
+                                       i = atoi(uts.release+4);
+                                       if (i >= 30)
+                                               break;  /* 3.2.30 and newer is OK */
+                               }
+                       } else {        /* 4.x and newer is OK */
+                               break;
+                       }
+                       env->me_flags |= MDB_FSYNCONLY;
+                       break;
+               }
+       }
+#endif
 
        memset(&meta, 0, sizeof(meta));
 
@@ -3827,20 +3994,16 @@ mdb_env_open2(MDB_env *env)
                 * else use the size recorded in the existing env.
                 */
                env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
-       } else {
-               if (env->me_mapsize < meta.mm_mapsize) {
-                       /* If the configured size is smaller, make sure it's
-                        * still big enough. Silently round up to minimum if not.
-                        */
-                       size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
-                       if (env->me_mapsize < minsize)
-                               env->me_mapsize = minsize;
-               }
-               if (env->me_mapsize != meta.mm_mapsize)
-                       env->me_flags |= MDB_RESIZING;
+       } else if (env->me_mapsize < meta.mm_mapsize) {
+               /* If the configured size is smaller, make sure it's
+                * still big enough. Silently round up to minimum if not.
+                */
+               size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
+               if (env->me_mapsize < minsize)
+                       env->me_mapsize = minsize;
        }
 
-       rc = mdb_env_map(env, meta.mm_address);
+       rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
        if (rc)
                return rc;
 
@@ -3941,7 +4104,7 @@ PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_
 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
 #pragma const_seg()
-#else  /* WIN32 */
+#else  /* _WIN32 */
 #pragma comment(linker, "/INCLUDE:__tls_used")
 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
 #pragma data_seg(".CRT$XLB")
@@ -3991,7 +4154,7 @@ mdb_env_share_locks(MDB_env *env, int *excl)
        return rc;
 }
 
-/** Try to get exlusive lock, otherwise shared.
+/** Try to get exclusive lock, otherwise shared.
  *     Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
  */
 static int ESECT
@@ -4132,7 +4295,6 @@ mdb_hash_enc(MDB_val *val, char *encbuf)
  * @param[in] env The LMDB environment.
  * @param[in] lpath The pathname of the file used for the lock region.
  * @param[in] mode The Unix permissions for the file, if we create it.
- * @param[out] excl Resulting file lock type: -1 none, 0 shared, 1 exclusive
  * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
  * @return 0 on success, non-zero on failure.
  */
@@ -4484,6 +4646,23 @@ mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode
                if (!((flags & MDB_RDONLY) ||
                          (env->me_pbuf = calloc(1, env->me_psize))))
                        rc = ENOMEM;
+               if (!(flags & MDB_RDONLY)) {
+                       MDB_txn *txn;
+                       int tsize = sizeof(MDB_txn), size = tsize + env->me_maxdbs *
+                               (sizeof(MDB_db)+sizeof(MDB_cursor *)+sizeof(unsigned int)+1);
+                       txn = calloc(1, size);
+                       if (txn) {
+                               txn->mt_dbs = (MDB_db *)((char *)txn + tsize);
+                               txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
+                               txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
+                               txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
+                               txn->mt_env = env;
+                               txn->mt_dbxs = env->me_dbxs;
+                               env->me_txn0 = txn;
+                       } else {
+                               rc = ENOMEM;
+                       }
+               }
        }
 
 leave:
@@ -4504,15 +4683,18 @@ mdb_env_close0(MDB_env *env, int excl)
                return;
 
        /* Doing this here since me_dbxs may not exist during mdb_env_close */
-       for (i = env->me_maxdbs; --i > MAIN_DBI; )
-               free(env->me_dbxs[i].md_name.mv_data);
+       if (env->me_dbxs) {
+               for (i = env->me_maxdbs; --i > MAIN_DBI; )
+                       free(env->me_dbxs[i].md_name.mv_data);
+               free(env->me_dbxs);
+       }
 
        free(env->me_pbuf);
        free(env->me_dbiseqs);
        free(env->me_dbflags);
-       free(env->me_dbxs);
        free(env->me_path);
        free(env->me_dirty_list);
+       free(env->me_txn0);
        mdb_midl_free(env->me_free_pgs);
 
        if (env->me_flags & MDB_ENV_TXKEY) {
@@ -4612,7 +4794,11 @@ 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 unsigned int's */
+/** Compare two items pointing at aligned unsigned int's.
+ *
+ *     This is also set as #MDB_INTEGERDUP|#MDB_DUPFIXED's #MDB_dbx.%md_dcmp,
+ *     but #mdb_cmp_clong() is called instead if the data type is size_t.
+ */
 static int
 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
 {
@@ -4650,13 +4836,6 @@ mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
 #endif
 }
 
-/** Compare two items pointing at size_t's of unknown alignment. */
-#ifdef MISALIGNED_OK
-# define mdb_cmp_clong mdb_cmp_long
-#else
-# define mdb_cmp_clong mdb_cmp_cint
-#endif
-
 /** Compare two items lexically */
 static int
 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
@@ -5042,6 +5221,8 @@ mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
                                                &mc->mc_dbx->md_name, &exact);
                                        if (!exact)
                                                return MDB_NOTFOUND;
+                                       if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
+                                               return MDB_INCOMPATIBLE; /* not a named DB */
                                        rc = mdb_node_read(mc->mc_txn, leaf, &data);
                                        if (rc)
                                                return rc;
@@ -5370,15 +5551,17 @@ mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
                        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 (rc == MDB_SUCCESS)
+                                       if (rc == MDB_SUCCESS) {
                                                MDB_GET_KEY(leaf, key);
+                                               mc->mc_flags &= ~C_EOF;
+                                       }
                                        return rc;
                                }
-                       } else {
-                               mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
-                               if (op == MDB_PREV_DUP)
-                                       return MDB_NOTFOUND;
                        }
+               } else {
+                       mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
+                       if (op == MDB_PREV_DUP)
+                               return MDB_NOTFOUND;
                }
        }
 
@@ -5551,8 +5734,10 @@ set2:
 
        if (leaf == NULL) {
                DPUTS("===> inexact leaf not found, goto sibling");
-               if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
+               if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
+                       mc->mc_flags |= C_EOF;
                        return rc;              /* no entries matched */
+               }
                mp = mc->mc_pg[mc->mc_top];
                mdb_cassert(mc, IS_LEAF(mp));
                leaf = NODEPTR(mp, 0);
@@ -5590,15 +5775,21 @@ set1:
                                        return rc;
                        }
                } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
-                       MDB_val d2;
-                       if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
+                       MDB_val olddata;
+                       MDB_cmp_func *dcmp;
+                       if ((rc = mdb_node_read(mc->mc_txn, leaf, &olddata)) != MDB_SUCCESS)
                                return rc;
-                       rc = mc->mc_dbx->md_dcmp(data, &d2);
+                       dcmp = mc->mc_dbx->md_dcmp;
+#if UINT_MAX < SIZE_MAX
+                       if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
+                               dcmp = mdb_cmp_clong;
+#endif
+                       rc = dcmp(data, &olddata);
                        if (rc) {
                                if (op == MDB_GET_BOTH || rc > 0)
                                        return MDB_NOTFOUND;
                                rc = 0;
-                               *data = d2;
+                               *data = olddata;
                        }
 
                } else {
@@ -5848,6 +6039,14 @@ fetchm:
                        rc = MDB_INCOMPATIBLE;
                        break;
                }
+               {
+                       MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
+                       if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
+                               MDB_GET_KEY(leaf, key);
+                               rc = mdb_node_read(mc->mc_txn, leaf, data);
+                               break;
+                       }
+               }
                if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
                        rc = EINVAL;
                        break;
@@ -5912,7 +6111,7 @@ mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
        enum { MDB_NO_ROOT = MDB_LAST_ERRCODE+10 }; /* internal code */
        MDB_env         *env;
        MDB_node        *leaf = NULL;
-       MDB_page        *fp, *mp;
+       MDB_page        *fp, *mp, *sub_root = NULL;
        uint16_t        fp_flags;
        MDB_val         xdata, *rdata, dkey, olddata;
        MDB_db dummy;
@@ -6061,6 +6260,24 @@ mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
                                return MDB_BAD_VALSIZE;
                        ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
                        memcpy(ptr, key->mv_data, ksize);
+fix_parent:
+                       /* if overwriting slot 0 of leaf, need to
+                        * update branch key if there is a parent page
+                        */
+                       if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
+                               unsigned short top = mc->mc_top;
+                               mc->mc_top--;
+                               /* slot 0 is always an empty key, find real slot */
+                               while (mc->mc_top && !mc->mc_ki[mc->mc_top])
+                                       mc->mc_top--;
+                               if (mc->mc_ki[mc->mc_top])
+                                       rc2 = mdb_update_key(mc, key);
+                               else
+                                       rc2 = MDB_SUCCESS;
+                               mc->mc_top = top;
+                               if (rc2)
+                                       return rc2;
+                       }
                        return MDB_SUCCESS;
                }
 
@@ -6082,16 +6299,17 @@ more:
 
                        /* Was a single item before, must convert now */
                        if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
+                               MDB_cmp_func *dcmp;
                                /* Just overwrite the current item */
                                if (flags == MDB_CURRENT)
                                        goto current;
-
+                               dcmp = mc->mc_dbx->md_dcmp;
 #if UINT_MAX < SIZE_MAX
-                               if (mc->mc_dbx->md_dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
-                                       mc->mc_dbx->md_dcmp = mdb_cmp_clong;
+                               if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
+                                       dcmp = mdb_cmp_clong;
 #endif
                                /* does data match? */
-                               if (!mc->mc_dbx->md_dcmp(data, &olddata)) {
+                               if (!dcmp(data, &olddata)) {
                                        if (flags & MDB_NODUPDATA)
                                                return MDB_KEYEXIST;
                                        /* overwrite it */
@@ -6173,6 +6391,7 @@ prep_subDB:
                                        offset = env->me_psize - olddata.mv_size;
                                        flags |= F_DUPDATA|F_SUBDATA;
                                        dummy.md_root = mp->mp_pgno;
+                                       sub_root = mp;
                        }
                        if (mp != fp) {
                                mp->mp_flags = fp_flags | P_DIRTY;
@@ -6197,6 +6416,9 @@ prep_subDB:
                        goto new_sub;
                }
 current:
+               /* LMDB passes F_SUBDATA in 'flags' to write a DB record */
+               if ((leaf->mn_flags ^ flags) & F_SUBDATA)
+                       return MDB_INCOMPATIBLE;
                /* overflow page overwrites need special handling */
                if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
                        MDB_page *omp;
@@ -6266,8 +6488,10 @@ current:
                                data->mv_data = olddata.mv_data;
                        else if (!(mc->mc_flags & C_SUB))
                                memcpy(olddata.mv_data, data->mv_data, data->mv_size);
-                       else
+                       else {
                                memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
+                               goto fix_parent;
+                       }
                        return MDB_SUCCESS;
                }
                mdb_node_del(mc, 0);
@@ -6314,7 +6538,7 @@ new_sub:
                 * DB are all zero size.
                 */
                if (do_sub) {
-                       int xflags;
+                       int xflags, new_dupdata;
                        size_t ecount;
 put_sub:
                        xdata.mv_size = 0;
@@ -6327,28 +6551,32 @@ put_sub:
                                xflags = (flags & MDB_NODUPDATA) ?
                                        MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
                        }
+                       if (sub_root)
+                               mc->mc_xcursor->mx_cursor.mc_pg[0] = sub_root;
+                       new_dupdata = (int)dkey.mv_size;
                        /* converted, write the original data first */
                        if (dkey.mv_size) {
                                rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
                                if (rc)
                                        goto bad_sub;
-                               {
-                                       /* Adjust other cursors pointing to mp */
-                                       MDB_cursor *m2;
-                                       unsigned i = mc->mc_top;
-                                       MDB_page *mp = mc->mc_pg[i];
-
-                                       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);
-                                               }
-                                       }
-                               }
                                /* we've done our job */
                                dkey.mv_size = 0;
                        }
+                       if (!(leaf->mn_flags & F_SUBDATA) || sub_root) {
+                               /* Adjust other cursors pointing to mp */
+                               MDB_cursor *m2;
+                               MDB_xcursor *mx = mc->mc_xcursor;
+                               unsigned i = mc->mc_top;
+                               MDB_page *mp = mc->mc_pg[i];
+
+                               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_init2(m2, mx, new_dupdata);
+                                       }
+                               }
+                       }
                        ecount = mc->mc_xcursor->mx_db.md_entries;
                        if (flags & MDB_APPENDDUP)
                                xflags |= MDB_APPEND;
@@ -6465,6 +6693,11 @@ mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
                                goto fail;
                }
        }
+       /* LMDB passes F_SUBDATA in 'flags' to delete a DB record */
+       else if ((leaf->mn_flags ^ flags) & F_SUBDATA) {
+               rc = MDB_INCOMPATIBLE;
+               goto fail;
+       }
 
        /* add overflow pages to free list */
        if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
@@ -6895,6 +7128,38 @@ mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
 #endif
 }
 
+
+/** Fixup a sorted-dups cursor due to underlying update.
+ *     Sets up some fields that depend on the data from the main cursor.
+ *     Almost the same as init1, but skips initialization steps if the
+ *     xcursor had already been used.
+ * @param[in] mc The main cursor whose sorted-dups cursor is to be fixed up.
+ * @param[in] src_mx The xcursor of an up-to-date cursor.
+ * @param[in] new_dupdata True if converting from a non-#F_DUPDATA item.
+ */
+static void
+mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int new_dupdata)
+{
+       MDB_xcursor *mx = mc->mc_xcursor;
+
+       if (new_dupdata) {
+               mx->mx_cursor.mc_snum = 1;
+               mx->mx_cursor.mc_top = 0;
+               mx->mx_cursor.mc_flags |= C_INITIALIZED;
+               mx->mx_cursor.mc_ki[0] = 0;
+               mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
+#if UINT_MAX < SIZE_MAX
+               mx->mx_dbx.md_cmp = src_mx->mx_dbx.md_cmp;
+#endif
+       } else if (!(mx->mx_cursor.mc_flags & C_INITIALIZED)) {
+               return;
+       }
+       mx->mx_db = src_mx->mx_db;
+       mx->mx_cursor.mc_pg[0] = src_mx->mx_cursor.mc_pg[0];
+       DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
+               mx->mx_db.md_root));
+}
+
 /** Initialize a cursor for a given transaction and database. */
 static void
 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
@@ -6909,6 +7174,7 @@ mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
        mc->mc_snum = 0;
        mc->mc_top = 0;
        mc->mc_pg[0] = 0;
+       mc->mc_ki[0] = 0;
        mc->mc_flags = 0;
        if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
                mdb_tassert(txn, mx != NULL);
@@ -6988,6 +7254,12 @@ mdb_cursor_count(MDB_cursor *mc, size_t *countp)
        if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
                return MDB_BAD_TXN;
 
+       if (!(mc->mc_flags & C_INITIALIZED))
+               return EINVAL;
+
+       if (!mc->mc_snum || (mc->mc_flags & C_EOF))
+               return MDB_NOTFOUND;
+
        leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
        if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
                *countp = 1;
@@ -7206,8 +7478,22 @@ mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
                /* Adjust other cursors pointing to mp */
                MDB_cursor *m2, *m3;
                MDB_dbi dbi = csrc->mc_dbi;
-               MDB_page *mp = csrc->mc_pg[csrc->mc_top];
+               MDB_page *mp;
+
+               mp = cdst->mc_pg[csrc->mc_top];
+               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;
+                       else
+                               m3 = m2;
+                       if (m3 == cdst) continue;
+                       if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] >=
+                               cdst->mc_ki[csrc->mc_top]) {
+                               m3->mc_ki[csrc->mc_top]++;
+                       }
+               }
 
+               mp = csrc->mc_pg[csrc->mc_top];
                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;
@@ -7276,7 +7562,7 @@ mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
                        cdst->mc_ki[cdst->mc_top] = 0;
                        rc = mdb_update_key(cdst, &nullkey);
                        cdst->mc_ki[cdst->mc_top] = ix;
-                       mdb_cassert(csrc, rc == MDB_SUCCESS);
+                       mdb_cassert(cdst, rc == MDB_SUCCESS);
                }
        }
 
@@ -7409,9 +7695,9 @@ mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
                uint16_t depth = cdst->mc_db->md_depth;
                mdb_cursor_pop(cdst);
                rc = mdb_rebalance(cdst);
-               /* Did the tree shrink? */
-               if (depth > cdst->mc_db->md_depth)
-                       snum--;
+               /* Did the tree height change? */
+               if (depth != cdst->mc_db->md_depth)
+                       snum += cdst->mc_db->md_depth - depth;
                cdst->mc_snum = snum;
                cdst->mc_top = snum-1;
        }
@@ -7451,17 +7737,23 @@ mdb_rebalance(MDB_cursor *mc)
 {
        MDB_node        *node;
        int rc;
-       unsigned int ptop, minkeys;
+       unsigned int ptop, minkeys, thresh;
        MDB_cursor      mn;
        indx_t oldki;
 
-       minkeys = 1 + (IS_BRANCH(mc->mc_pg[mc->mc_top]));
+       if (IS_BRANCH(mc->mc_pg[mc->mc_top])) {
+               minkeys = 2;
+               thresh = 1;
+       } else {
+               minkeys = 1;
+               thresh = FILL_THRESHOLD;
+       }
        DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
            IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
            mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
                (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
 
-       if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD &&
+       if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= thresh &&
                NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
                DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
                    mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
@@ -7532,12 +7824,12 @@ mdb_rebalance(MDB_cursor *mc)
                                                m3 = m2;
                                        if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
                                        if (m3->mc_pg[0] == mp) {
-                                               m3->mc_snum--;
-                                               m3->mc_top--;
                                                for (i=0; i<m3->mc_snum; i++) {
                                                        m3->mc_pg[i] = m3->mc_pg[i+1];
                                                        m3->mc_ki[i] = m3->mc_ki[i+1];
                                                }
+                                               m3->mc_snum--;
+                                               m3->mc_top--;
                                        }
                                }
                        }
@@ -7595,19 +7887,32 @@ mdb_rebalance(MDB_cursor *mc)
         * move one key from it. Otherwise we should try to merge them.
         * (A branch page must never have less than 2 keys.)
         */
-       minkeys = 1 + (IS_BRANCH(mn.mc_pg[mn.mc_top]));
-       if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
+       if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= thresh && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
                rc = mdb_node_move(&mn, mc);
-               if (mc->mc_ki[ptop]) {
+               if (mc->mc_ki[mc->mc_top-1]) {
                        oldki++;
                }
        } else {
                if (mc->mc_ki[ptop] == 0) {
                        rc = mdb_page_merge(&mn, mc);
                } else {
+                       MDB_cursor dummy;
                        oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
                        mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
+                       /* We want mdb_rebalance to find mn when doing fixups */
+                       if (mc->mc_flags & C_SUB) {
+                               dummy.mc_next = mc->mc_txn->mt_cursors[mc->mc_dbi];
+                               mc->mc_txn->mt_cursors[mc->mc_dbi] = &dummy;
+                               dummy.mc_xcursor = (MDB_xcursor *)&mn;
+                       } else {
+                               mn.mc_next = mc->mc_txn->mt_cursors[mc->mc_dbi];
+                               mc->mc_txn->mt_cursors[mc->mc_dbi] = &mn;
+                       }
                        rc = mdb_page_merge(mc, &mn);
+                       if (mc->mc_flags & C_SUB)
+                               mc->mc_txn->mt_cursors[mc->mc_dbi] = dummy.mc_next;
+                       else
+                               mc->mc_txn->mt_cursors[mc->mc_dbi] = mn.mc_next;
                        mdb_cursor_copy(&mn, mc);
                }
                mc->mc_flags &= ~C_EOF;
@@ -7624,41 +7929,54 @@ mdb_cursor_del0(MDB_cursor *mc)
        MDB_page *mp;
        indx_t ki;
        unsigned int nkeys;
+       MDB_cursor *m2, *m3;
+       MDB_dbi dbi = mc->mc_dbi;
 
        ki = mc->mc_ki[mc->mc_top];
+       mp = mc->mc_pg[mc->mc_top];
        mdb_node_del(mc, mc->mc_db->md_pad);
        mc->mc_db->md_entries--;
+       {
+               /* Adjust other cursors pointing to mp */
+               for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
+                       m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
+                       if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
+                               continue;
+                       if (m3 == mc || m3->mc_snum < mc->mc_snum)
+                               continue;
+                       if (m3->mc_pg[mc->mc_top] == mp) {
+                               if (m3->mc_ki[mc->mc_top] >= ki) {
+                                       m3->mc_flags |= C_DEL;
+                                       if (m3->mc_ki[mc->mc_top] > ki)
+                                               m3->mc_ki[mc->mc_top]--;
+                                       else if (mc->mc_db->md_flags & MDB_DUPSORT)
+                                               m3->mc_xcursor->mx_cursor.mc_flags |= C_EOF;
+                               }
+                       }
+               }
+       }
        rc = mdb_rebalance(mc);
 
        if (rc == MDB_SUCCESS) {
-               MDB_cursor *m2, *m3;
-               MDB_dbi dbi = mc->mc_dbi;
+               /* DB is totally empty now, just bail out.
+                * Other cursors adjustments were already done
+                * by mdb_rebalance and aren't needed here.
+                */
+               if (!mc->mc_snum)
+                       return rc;
 
                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) {
-                       rc = mdb_cursor_sibling(mc, 1);
-                       if (rc == MDB_NOTFOUND) {
-                               mc->mc_flags |= C_EOF;
-                               rc = MDB_SUCCESS;
-                       }
-               }
-
                /* Adjust other cursors pointing to mp */
                for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
                        m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
                        if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
                                continue;
-                       if (m3 == mc || m3->mc_snum < mc->mc_snum)
+                       if (m3->mc_snum < mc->mc_snum)
                                continue;
                        if (m3->mc_pg[mc->mc_top] == mp) {
-                               if (m3->mc_ki[mc->mc_top] >= ki) {
-                                       m3->mc_flags |= C_DEL;
-                                       if (m3->mc_ki[mc->mc_top] > ki)
-                                               m3->mc_ki[mc->mc_top]--;
-                               }
+                               /* if m3 points past last node in page, find next sibling */
                                if (m3->mc_ki[mc->mc_top] >= nkeys) {
                                        rc = mdb_cursor_sibling(m3, 1);
                                        if (rc == MDB_NOTFOUND) {
@@ -7788,8 +8106,7 @@ mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno
                mc->mc_ki[0] = 0;
                mc->mc_db->md_root = pp->mp_pgno;
                DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
-               mc->mc_db->md_depth++;
-               new_root = 1;
+               new_root = mc->mc_db->md_depth++;
 
                /* Add left (implicit) pointer. */
                if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
@@ -7910,7 +8227,7 @@ mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno
                                psize = 0;
                                if (newindx <= split_indx || newindx >= nkeys) {
                                        i = 0; j = 1;
-                                       k = newindx >= nkeys ? nkeys : split_indx+2;
+                                       k = newindx >= nkeys ? nkeys : split_indx+1+IS_LEAF(mp);
                                } else {
                                        i = nkeys; j = -1;
                                        k = split_indx-1;
@@ -8102,7 +8419,7 @@ mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno
                        if (new_root) {
                                int k;
                                /* root split */
-                               for (k=m3->mc_top; k>=0; k--) {
+                               for (k=new_root; k>=0; k--) {
                                        m3->mc_ki[k+1] = m3->mc_ki[k];
                                        m3->mc_pg[k+1] = m3->mc_pg[k];
                                }
@@ -8434,16 +8751,23 @@ mdb_env_copyfd1(MDB_env *env, HANDLE fd)
 #ifdef _WIN32
        my.mc_mutex = CreateMutex(NULL, FALSE, NULL);
        my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL);
-       my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_psize);
+       my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
        if (my.mc_wbuf[0] == NULL)
                return errno;
 #else
        pthread_mutex_init(&my.mc_mutex, NULL);
        pthread_cond_init(&my.mc_cond, NULL);
-       rc = posix_memalign((void **)&my.mc_wbuf[0], env->me_psize, MDB_WBUF*2);
+#ifdef HAVE_MEMALIGN
+       my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
+       if (my.mc_wbuf[0] == NULL)
+               return errno;
+#else
+       rc = posix_memalign((void **)&my.mc_wbuf[0], env->me_os_psize, MDB_WBUF*2);
        if (rc)
                return rc;
 #endif
+#endif
+       memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
        my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
        my.mc_wlen[0] = 0;
        my.mc_wlen[1] = 0;
@@ -8492,8 +8816,12 @@ mdb_env_copyfd1(MDB_env *env, HANDLE fd)
                /* Set metapage 1 */
                mm->mm_last_pg = txn->mt_next_pgno - freecount - 1;
                mm->mm_dbs[1] = txn->mt_dbs[1];
-               mm->mm_dbs[1].md_root = mm->mm_last_pg;
-               mm->mm_txnid = 1;
+               if (mm->mm_last_pg > 1) {
+                       mm->mm_dbs[1].md_root = mm->mm_last_pg;
+                       mm->mm_txnid = 1;
+               } else {
+                       mm->mm_dbs[1].md_root = P_INVALID;
+               }
        }
        my.mc_wlen[0] = env->me_psize * 2;
        my.mc_txn = txn;
@@ -8588,21 +8916,13 @@ mdb_env_copyfd0(MDB_env *env, HANDLE fd)
                goto leave;
 
        w2 = txn->mt_next_pgno * env->me_psize;
-#ifdef WIN32
-       {
-               LARGE_INTEGER fsize;
-               GetFileSizeEx(env->me_fd, &fsize);
-               if (w2 > fsize.QuadPart)
-                       w2 = fsize.QuadPart;
-       }
-#else
        {
-               struct stat st;
-               fstat(env->me_fd, &st);
-               if (w2 > (size_t)st.st_size)
-                       w2 = st.st_size;
+               size_t fsize = 0;
+               if ((rc = mdb_fsize(env->me_fd, &fsize)))
+                       goto leave;
+               if (w2 > fsize)
+                       w2 = fsize;
        }
-#endif
        wsize = w2 - wsize;
        while (wsize > 0) {
                if (wsize > MAX_WRITE)
@@ -8677,6 +8997,7 @@ mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
                goto leave;
        }
 
+       if (env->me_psize >= env->me_os_psize) {
 #ifdef O_DIRECT
        /* Set O_DIRECT if the file system supports it */
        if ((rc = fcntl(newfd, F_GETFL)) != -1)
@@ -8689,6 +9010,7 @@ mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
                goto leave;
        }
 #endif
+       }
 
        rc = mdb_env_copyfd2(env, newfd, flags);
 
@@ -8859,6 +9181,7 @@ int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *db
        MDB_val key, data;
        MDB_dbi i;
        MDB_cursor mc;
+       MDB_db dummy;
        int rc, dbflag, exact;
        unsigned int unused = 0, seq;
        size_t len;
@@ -8924,11 +9247,10 @@ int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *db
        if (rc == MDB_SUCCESS) {
                /* 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))
+               if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
                        return MDB_INCOMPATIBLE;
        } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
                /* Create if requested */
-               MDB_db dummy;
                data.mv_size = sizeof(MDB_db);
                data.mv_data = &dummy;
                memset(&dummy, 0, sizeof(dummy));
@@ -9118,7 +9440,7 @@ int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
 
        /* Can't delete the main DB */
        if (del && dbi > MAIN_DBI) {
-               rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, 0);
+               rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, F_SUBDATA);
                if (!rc) {
                        txn->mt_dbflags[dbi] = DB_STALE;
                        mdb_dbi_close(txn->mt_env, dbi);