]> git.sur5r.net Git - openldap/blobdiff - libraries/liblmdb/mdb.c
ITS#7992 Fix memleak in prev change
[openldap] / libraries / liblmdb / mdb.c
index 927c52c65c7e3e0af0a9e5c5c1223532aaa27f64..ea9e4729025f4934af2a0e473d268f8b9973385d 100644 (file)
@@ -5,7 +5,7 @@
  *     BerkeleyDB API, but much simplified.
  */
 /*
- * Copyright 2011-2015 Howard Chu, Symas Corp.
+ * Copyright 2011-2016 Howard Chu, Symas Corp.
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
 #ifndef _GNU_SOURCE
 #define _GNU_SOURCE 1
 #endif
+#if defined(MDB_VL32) || defined(__WIN64__)
+#define _FILE_OFFSET_BITS      64
+#endif
 #ifdef _WIN32
 #include <malloc.h>
 #include <windows.h>
+
+/* We use native NT APIs to setup the memory map, so that we can
+ * let the DB file grow incrementally instead of always preallocating
+ * the full size. These APIs are defined in <wdm.h> and <ntifs.h>
+ * but those headers are meant for driver-level development and
+ * conflict with the regular user-level headers, so we explicitly
+ * declare them here. Using these APIs also means we must link to
+ * ntdll.dll, which is not linked by default in user code.
+ */
+NTSTATUS WINAPI
+NtCreateSection(OUT PHANDLE sh, IN ACCESS_MASK acc,
+  IN void * oa OPTIONAL,
+  IN PLARGE_INTEGER ms OPTIONAL,
+  IN ULONG pp, IN ULONG aa, IN HANDLE fh OPTIONAL);
+
+typedef enum _SECTION_INHERIT {
+       ViewShare = 1,
+       ViewUnmap = 2
+} SECTION_INHERIT;
+
+NTSTATUS WINAPI
+NtMapViewOfSection(IN PHANDLE sh, IN HANDLE ph,
+  IN OUT PVOID *addr, IN ULONG_PTR zbits,
+  IN SIZE_T cs, IN OUT PLARGE_INTEGER off OPTIONAL,
+  IN OUT PSIZE_T vs, IN SECTION_INHERIT ih,
+  IN ULONG at, IN ULONG pp);
+
+NTSTATUS WINAPI
+NtClose(HANDLE h);
+
 /** getpid() returns int; MinGW defines pid_t but MinGW64 typedefs it
  *  as int64 which is wrong. MSVC doesn't define it at all, so just
  *  don't use it.
@@ -210,7 +243,7 @@ union semun {
 #define ESECT
 #endif
 
-#ifdef _MSC_VER
+#ifdef _WIN32
 #define CALL_CONV WINAPI
 #else
 #define CALL_CONV
@@ -270,8 +303,8 @@ union semun {
 #  define MDB_USE_ROBUST       0
 # else
 #  define MDB_USE_ROBUST       1
-/* glibc < 2.10 only provided _np API */
-#  if defined(__GLIBC__) && GLIBC_VER < 0x02000a
+/* glibc < 2.12 only provided _np API */
+#  if defined(__GLIBC__) && GLIBC_VER < 0x02000c
 #   define PTHREAD_MUTEX_ROBUST        PTHREAD_MUTEX_ROBUST_NP
 #   define pthread_mutexattr_setrobust(attr, flag)     pthread_mutexattr_setrobust_np(attr, flag)
 #   define pthread_mutex_consistent(mutex)     pthread_mutex_consistent_np(mutex)
@@ -422,6 +455,16 @@ typedef pthread_mutex_t mdb_mutex_t[1], *mdb_mutexref_t;
 #define        GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
 #endif
 
+#ifdef MDB_VL32
+#ifdef _WIN32
+#define        Y       "I64"
+#else
+#define        Y       "ll"
+#endif
+#else
+#define Y      Z
+#endif
+
 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
 #define MNAME_LEN      32
 #elif defined(MDB_USE_SYSV_SEM)
@@ -1032,7 +1075,7 @@ typedef struct MDB_db {
        pgno_t          md_branch_pages;        /**< number of internal pages */
        pgno_t          md_leaf_pages;          /**< number of leaf pages */
        pgno_t          md_overflow_pages;      /**< number of overflow pages */
-       size_t          md_entries;             /**< number of data items */
+       mdb_size_t      md_entries;             /**< number of data items */
        pgno_t          md_root;                /**< the root page of this tree */
 } MDB_db;
 
@@ -1062,8 +1105,16 @@ typedef struct MDB_meta {
        uint32_t        mm_magic;
                /** Version number of this file. Must be set to #MDB_DATA_VERSION. */
        uint32_t        mm_version;
+#ifdef MDB_VL32
+       union {         /* always zero since we don't support fixed mapping in MDB_VL32 */
+               MDB_ID  mmun_ull;
+               void *mmun_address;
+       } mm_un;
+#define        mm_address mm_un.mmun_address
+#else
        void            *mm_address;            /**< address for fixed mapping */
-       size_t          mm_mapsize;                     /**< size of mmap region */
+#endif
+       pgno_t          mm_mapsize;                     /**< size of mmap region */
        MDB_db          mm_dbs[CORE_DBS];       /**< first is free space, 2nd is main db */
        /** The size of pages used in this DB */
 #define        mm_psize        mm_dbs[FREE_DBI].md_pad
@@ -1106,6 +1157,9 @@ struct MDB_txn {
        /** Nested txn under this txn, set together with flag #MDB_TXN_HAS_CHILD */
        MDB_txn         *mt_child;
        pgno_t          mt_next_pgno;   /**< next unallocated page */
+#ifdef MDB_VL32
+       pgno_t          mt_last_pgno;   /**< last written page */
+#endif
        /** The ID of this transaction. IDs are integers incrementing from 1.
         *      Only committed write transactions increment the ID. If a transaction
         *      aborts, the ID may be re-used by the next writer.
@@ -1152,6 +1206,19 @@ struct MDB_txn {
        MDB_cursor      **mt_cursors;
        /** Array of flags for each DB */
        unsigned char   *mt_dbflags;
+#ifdef MDB_VL32
+       /** List of read-only pages (actually chunks) */
+       MDB_ID3L        mt_rpages;
+       /** We map chunks of 16 pages. Even though Windows uses 4KB pages, all
+        * mappings must begin on 64KB boundaries. So we round off all pgnos to
+        * a chunk boundary. We do the same on Linux for symmetry, and also to
+        * reduce the frequency of mmap/munmap calls.
+        */
+#define MDB_RPAGE_CHUNK        16
+#define MDB_TRPAGE_SIZE        4096    /**< size of #mt_rpages array of chunks */
+#define MDB_TRPAGE_MAX (MDB_TRPAGE_SIZE-1)     /**< maximum chunk index */
+       unsigned int mt_rpcheck;        /**< threshold for reclaiming unref'd chunks */
+#endif
        /**     Number of DB records in use, or 0 when the txn is finished.
         *      This number only ever increments until the txn finishes; we
         *      don't decrement it when individual DB handles are closed.
@@ -1230,12 +1297,20 @@ struct MDB_cursor {
 #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 */
+#define C_WRITEMAP     MDB_TXN_WRITEMAP /**< Copy of txn flag */
+/** Read-only cursor into the txn's original snapshot in the map.
+ *     Set for read-only txns, and in #mdb_page_alloc() for #FREE_DBI when
+ *     #MDB_DEVEL & 2. Only implements code which is necessary for this.
+ */
+#define C_ORIG_RDONLY  MDB_TXN_RDONLY
 /** @} */
        unsigned int    mc_flags;       /**< @ref mdb_cursor */
        MDB_page        *mc_pg[CURSOR_STACK];   /**< stack of pushed pages */
        indx_t          mc_ki[CURSOR_STACK];    /**< stack of page indices */
+#ifdef MDB_VL32
+       MDB_page        *mc_ovpg;               /**< a referenced overflow page */
+#endif
 };
 
        /** Context for sorted-dup records.
@@ -1265,6 +1340,9 @@ struct MDB_env {
        HANDLE          me_fd;          /**< The main data file */
        HANDLE          me_lfd;         /**< The lock file */
        HANDLE          me_mfd;                 /**< just for writing the meta pages */
+#if defined(MDB_VL32) && defined(_WIN32)
+       HANDLE          me_fmh;         /**< File Mapping handle */
+#endif
        /** Failed to update the meta page. Probably an I/O error. */
 #define        MDB_FATAL_ERROR 0x80000000U
        /** Some fields are initialized. */
@@ -1289,7 +1367,7 @@ struct MDB_env {
        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 */
+       mdb_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 */
        MDB_dbx         *me_dbxs;               /**< array of static DB info */
@@ -1322,6 +1400,13 @@ struct MDB_env {
 #else
        mdb_mutex_t     me_rmutex;
        mdb_mutex_t     me_wmutex;
+#endif
+#ifdef MDB_VL32
+       MDB_ID3L        me_rpages;      /**< like #mt_rpages, but global to env */
+       pthread_mutex_t me_rpmutex;     /**< control access to #me_rpages */
+#define MDB_ERPAGE_SIZE        16384
+#define MDB_ERPAGE_MAX (MDB_ERPAGE_SIZE-1)
+       unsigned int me_rpcheck;
 #endif
        void            *me_userctx;     /**< User-settable context */
        MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
@@ -1341,7 +1426,7 @@ typedef struct MDB_ntxn {
 #endif
 
        /** max bytes to write in one call */
-#define MAX_WRITE              (0x80000000U >> (sizeof(ssize_t) == 4))
+#define MAX_WRITE              (0x40000000U >> (sizeof(ssize_t) == 4))
 
        /** Check \b txn and \b dbi arguments to a function */
 #define TXN_DBI_EXIST(txn, dbi, validity) \
@@ -1368,7 +1453,7 @@ enum {
 #define MDB_END_SLOT MDB_NOTLS /**< release any reader slot if #MDB_NOTLS */
 static void mdb_txn_end(MDB_txn *txn, unsigned mode);
 
-static int  mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp, int *lvl);
+static int  mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **mp, int *lvl);
 static int  mdb_page_search_root(MDB_cursor *mc,
                            MDB_val *key, int modify);
 #define MDB_PS_MODIFY  1
@@ -1396,8 +1481,8 @@ static int  mdb_node_add(MDB_cursor *mc, indx_t indx,
                            MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
 static void mdb_node_del(MDB_cursor *mc, int ksize);
 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
-static int     mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
-static int  mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
+static int     mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft);
+static int  mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data);
 static size_t  mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
 static size_t  mdb_branch_size(MDB_env *env, MDB_val *key);
 
@@ -1441,6 +1526,8 @@ static MDB_cmp_func       mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_
 static SECURITY_DESCRIPTOR mdb_null_sd;
 static SECURITY_ATTRIBUTES mdb_all_sa;
 static int mdb_sec_inited;
+
+static int utf8_to_utf16(const char *src, int srcsize, wchar_t **dst, int *dstsize);
 #endif
 
 /** Return the library version info. */
@@ -1618,20 +1705,20 @@ mdb_page_list(MDB_page *mp)
        case P_LEAF|P_LEAF2:        type = "LEAF2 page";                break;
        case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page";    break;
        case P_OVERFLOW:
-               fprintf(stderr, "Overflow page %"Z"u pages %u%s\n",
+               fprintf(stderr, "Overflow page %"Y"u pages %u%s\n",
                        pgno, mp->mp_pages, state);
                return;
        case P_META:
-               fprintf(stderr, "Meta-page %"Z"u txnid %"Z"u\n",
+               fprintf(stderr, "Meta-page %"Y"u txnid %"Y"u\n",
                        pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
                return;
        default:
-               fprintf(stderr, "Bad page %"Z"u flags 0x%u\n", pgno, mp->mp_flags);
+               fprintf(stderr, "Bad page %"Y"u flags 0x%u\n", pgno, mp->mp_flags);
                return;
        }
 
        nkeys = NUMKEYS(mp);
-       fprintf(stderr, "%s %"Z"u numkeys %d%s\n", type, pgno, nkeys, state);
+       fprintf(stderr, "%s %"Y"u numkeys %d%s\n", type, pgno, nkeys, state);
 
        for (i=0; i<nkeys; i++) {
                if (IS_LEAF2(mp)) {     /* LEAF2 pages have no mp_ptrs[] or node headers */
@@ -1646,7 +1733,7 @@ mdb_page_list(MDB_page *mp)
                key.mv_data = node->mn_data;
                nsize = NODESIZE + key.mv_size;
                if (IS_BRANCH(mp)) {
-                       fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
+                       fprintf(stderr, "key %d: page %"Y"u, %s\n", i, NODEPGNO(node),
                                DKEY(&key));
                        total += nsize;
                } else {
@@ -1672,7 +1759,7 @@ mdb_cursor_chk(MDB_cursor *mc)
        MDB_node *node;
        MDB_page *mp;
 
-       if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
+       if (!mc->mc_snum || !(mc->mc_flags & C_INITIALIZED)) return;
        for (i=0; i<mc->mc_top; i++) {
                mp = mc->mc_pg[i];
                node = NODEPTR(mp, mc->mc_ki[i]);
@@ -1681,6 +1768,13 @@ mdb_cursor_chk(MDB_cursor *mc)
        }
        if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
                printf("ack!\n");
+       if (mc->mc_xcursor && (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
+               node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
+               if (((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) &&
+                       mc->mc_xcursor->mx_cursor.mc_pg[0] != NODEDATA(node)) {
+                       printf("blah!\n");
+               }
+       }
 }
 #endif
 
@@ -1735,7 +1829,7 @@ static void mdb_audit(MDB_txn *txn)
                }
        }
        if (freecount + count + NUM_METAS != txn->mt_next_pgno) {
-               fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
+               fprintf(stderr, "audit: %"Y"u freecount: %"Y"u count: %"Y"u total: %"Y"u next_pgno: %"Y"u\n",
                        txn->mt_txnid, freecount, count+NUM_METAS,
                        freecount+count+NUM_METAS, txn->mt_next_pgno);
        }
@@ -1752,8 +1846,8 @@ int
 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *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))
+#if UINT_MAX < SIZE_MAX || defined(MDB_VL32)
+       if (dcmp == mdb_cmp_int && a->mv_size == sizeof(mdb_size_t))
                dcmp = mdb_cmp_clong;
 #endif
        return dcmp(a, b);
@@ -1835,6 +1929,45 @@ mdb_dlist_free(MDB_txn *txn)
        dl[0].mid = 0;
 }
 
+#ifdef MDB_VL32
+static void
+mdb_page_unref(MDB_txn *txn, MDB_page *mp)
+{
+       pgno_t pgno;
+       MDB_ID3L tl = txn->mt_rpages;
+       unsigned x, rem;
+       if (mp->mp_flags & (P_SUBP|P_DIRTY))
+               return;
+       rem = mp->mp_pgno & (MDB_RPAGE_CHUNK-1);
+       pgno = mp->mp_pgno ^ rem;
+       x = mdb_mid3l_search(tl, pgno);
+       if (x != tl[0].mid && tl[x+1].mid == mp->mp_pgno)
+               x++;
+       if (tl[x].mref)
+               tl[x].mref--;
+}
+#define MDB_PAGE_UNREF(txn, mp)        mdb_page_unref(txn, mp)
+
+static void
+mdb_cursor_unref(MDB_cursor *mc)
+{
+       int i;
+       if (!mc->mc_snum || !mc->mc_pg[0] || IS_SUBP(mc->mc_pg[0]))
+               return;
+       for (i=0; i<mc->mc_snum; i++)
+               mdb_page_unref(mc->mc_txn, mc->mc_pg[i]);
+       if (mc->mc_ovpg) {
+               mdb_page_unref(mc->mc_txn, mc->mc_ovpg);
+               mc->mc_ovpg = 0;
+       }
+       mc->mc_snum = mc->mc_top = 0;
+       mc->mc_pg[0] = NULL;
+       mc->mc_flags &= ~C_INITIALIZED;
+}
+#else
+#define MDB_PAGE_UNREF(txn, mp)
+#endif /* MDB_VL32 */
+
 /** Loosen or free a single page.
  * Saves single pages to a list for future reuse
  * in this same txn. It has been pulled from the freeDB
@@ -1876,7 +2009,7 @@ mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
                }
        }
        if (loose) {
-               DPRINTF(("loosen db %d page %"Z"u", DDBI(mc),
+               DPRINTF(("loosen db %d page %"Y"u", DDBI(mc),
                        mp->mp_pgno));
                NEXT_LOOSE_PAGE(mp) = txn->mt_loose_pgs;
                txn->mt_loose_pgs = mp;
@@ -1903,7 +2036,7 @@ mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
 {
        enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
        MDB_txn *txn = mc->mc_txn;
-       MDB_cursor *m3;
+       MDB_cursor *m3, *m0 = mc;
        MDB_xcursor *mx;
        MDB_page *dp, *mp;
        MDB_node *leaf;
@@ -1946,7 +2079,7 @@ mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
                                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)
+                               if ((rc = mdb_page_get(m0, pgno, &dp, &level)) != MDB_SUCCESS)
                                        break;
                                if ((dp->mp_flags & Mask) == pflags && level <= 1)
                                        dp->mp_flags ^= P_KEEP;
@@ -2135,6 +2268,8 @@ mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
  * 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.
+ * When #MDB_DEVEL & 2, it is not affected by #mdb_freelist_save(): it
+ * then uses the transaction's original snapshot of the freeDB.
  * @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.
@@ -2172,7 +2307,7 @@ mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
                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),
+               DPRINTF(("db %d use loose page %"Y"u", DDBI(mc),
                                np->mp_pgno));
                *mp = np;
                return MDB_SUCCESS;
@@ -2210,6 +2345,14 @@ mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
                        last = env->me_pglast;
                        oldest = env->me_pgoldest;
                        mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
+#if (MDB_DEVEL) & 2    /* "& 2" so MDB_DEVEL=1 won't hide bugs breaking freeDB */
+                       /* Use original snapshot. TODO: Should need less care in code
+                        * which modifies the database. Maybe we can delete some code?
+                        */
+                       m2.mc_flags |= C_ORIG_RDONLY;
+                       m2.mc_db = &env->me_metas[(txn->mt_txnid-1) & 1]->mm_dbs[FREE_DBI];
+                       m2.mc_dbflag = (unsigned char *)""; /* probably unnecessary */
+#endif
                        if (last) {
                                op = MDB_SET_RANGE;
                                key.mv_data = &last; /* will look up last+1 */
@@ -2250,7 +2393,7 @@ mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
                }
                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)
+               if ((rc = mdb_node_read(&m2, leaf, &data)) != MDB_SUCCESS)
                        return rc;
 
                idl = (MDB_ID *) data.mv_data;
@@ -2267,10 +2410,10 @@ mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
                }
                env->me_pglast = last;
 #if (MDB_DEBUG) > 1
-               DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
+               DPRINTF(("IDL read txn %"Y"u root %"Y"u num %u",
                        last, txn->mt_dbs[FREE_DBI].md_root, i));
                for (j = i; j; j--)
-                       DPRINTF(("IDL %"Z"u", idl[j]));
+                       DPRINTF(("IDL %"Y"u", idl[j]));
 #endif
                /* Merge in descending sorted order */
                mdb_midl_xmerge(mop, idl);
@@ -2285,6 +2428,20 @@ mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
                        rc = MDB_MAP_FULL;
                        goto fail;
        }
+#if defined(_WIN32) && !defined(MDB_VL32)
+       if (!(env->me_flags & MDB_RDONLY)) {
+               void *p;
+               p = (MDB_page *)(env->me_map + env->me_psize * pgno);
+               p = VirtualAlloc(p, env->me_psize * num, MEM_COMMIT,
+                       (env->me_flags & MDB_WRITEMAP) ? PAGE_READWRITE:
+                       PAGE_READONLY);
+               if (!p) {
+                       DPUTS("VirtualAlloc failed");
+                       rc = ErrCode();
+                       goto fail;
+               }
+       }
+#endif
 
 search_done:
        if (env->me_flags & MDB_WRITEMAP) {
@@ -2426,7 +2583,7 @@ mdb_page_touch(MDB_cursor *mc)
                        (rc = mdb_page_alloc(mc, 1, &np)))
                        goto fail;
                pgno = np->mp_pgno;
-               DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
+               DPRINTF(("touched db %d page %"Y"u -> %"Y"u", DDBI(mc),
                        mp->mp_pgno, pgno));
                mdb_cassert(mc, mp->mp_pgno != pgno);
                mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
@@ -2486,19 +2643,21 @@ done:
        } else {
                for (; m2; m2=m2->mc_next) {
                        if (m2->mc_snum < mc->mc_snum) continue;
+                       if (m2 == mc) continue;
                        if (m2->mc_pg[mc->mc_top] == mp) {
                                m2->mc_pg[mc->mc_top] = np;
                                if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
                                        IS_LEAF(np) &&
-                                       m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
+                                       (m2->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
                                {
-                                       MDB_node *leaf = NODEPTR(np, mc->mc_ki[mc->mc_top]);
-                                       if (!(leaf->mn_flags & F_SUBDATA))
+                                       MDB_node *leaf = NODEPTR(np, m2->mc_ki[mc->mc_top]);
+                                       if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
                                                m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
                                }
                        }
                }
        }
+       MDB_PAGE_UNREF(mc->mc_txn, mp);
        return 0;
 
 fail:
@@ -2507,7 +2666,7 @@ fail:
 }
 
 int
-mdb_env_sync(MDB_env *env, int force)
+mdb_env_sync0(MDB_env *env, int force, pgno_t numpgs)
 {
        int rc = 0;
        if (env->me_flags & MDB_RDONLY)
@@ -2516,7 +2675,7 @@ mdb_env_sync(MDB_env *env, int force)
                if (env->me_flags & MDB_WRITEMAP) {
                        int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
                                ? MS_ASYNC : MS_SYNC;
-                       if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
+                       if (MDB_MSYNC(env->me_map, env->me_psize * numpgs, flags))
                                rc = ErrCode();
 #ifdef _WIN32
                        else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
@@ -2536,6 +2695,13 @@ mdb_env_sync(MDB_env *env, int force)
        return rc;
 }
 
+int
+mdb_env_sync(MDB_env *env, int force)
+{
+       MDB_meta *m = mdb_env_pick_meta(env);
+       return mdb_env_sync0(env, force, m->mm_last_pg+1);
+}
+
 /** Back up parent txn's cursors, then grab the originals for tracking */
 static int
 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
@@ -2557,14 +2723,15 @@ mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
                                *bk = *mc;
                                mc->mc_backup = bk;
                                mc->mc_db = &dst->mt_dbs[i];
-                               /* Kill pointers into src - and dst to reduce abuse: The
-                                * user may not use mc until dst ends. Otherwise we'd...
+                               /* Kill pointers into src to reduce abuse: The
+                                * user may not use mc until dst ends. But we need a valid
+                                * txn pointer here for cursor fixups to keep working.
                                 */
-                               mc->mc_txn    = NULL;   /* ...set this to dst */
-                               mc->mc_dbflag = NULL;   /* ...and &dst->mt_dbflags[i] */
+                               mc->mc_txn    = dst;
+                               mc->mc_dbflag = &dst->mt_dbflags[i];
                                if ((mx = mc->mc_xcursor) != NULL) {
                                        *(MDB_xcursor *)(bk+1) = *mx;
-                                       mx->mx_cursor.mc_txn = NULL; /* ...and dst. */
+                                       mx->mx_cursor.mc_txn = dst;
                                }
                                mc->mc_next = dst->mt_cursors[i];
                                dst->mt_cursors[i] = mc;
@@ -2779,6 +2946,9 @@ 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;
+#ifdef MDB_VL32
+       txn->mt_last_pgno = txn->mt_next_pgno - 1;
+#endif
 
        txn->mt_flags = flags;
 
@@ -2814,7 +2984,7 @@ mdb_txn_renew(MDB_txn *txn)
 
        rc = mdb_txn_renew0(txn);
        if (rc == MDB_SUCCESS) {
-               DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
+               DPRINTF(("renew txn %"Y"u%c %p on mdbenv %p, root page %"Y"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));
        }
@@ -2857,6 +3027,17 @@ mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
                DPRINTF(("calloc: %s", strerror(errno)));
                return ENOMEM;
        }
+#ifdef MDB_VL32
+       if (!parent) {
+               txn->mt_rpages = malloc(MDB_TRPAGE_SIZE * sizeof(MDB_ID3));
+               if (!txn->mt_rpages) {
+                       free(txn);
+                       return ENOMEM;
+               }
+               txn->mt_rpages[0].mid = 0;
+               txn->mt_rpcheck = MDB_TRPAGE_SIZE/2;
+       }
+#endif
        txn->mt_dbxs = env->me_dbxs;    /* static */
        txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
        txn->mt_dbflags = (unsigned char *)txn + size - env->me_maxdbs;
@@ -2884,6 +3065,9 @@ mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
                parent->mt_child = txn;
                txn->mt_parent = parent;
                txn->mt_numdbs = parent->mt_numdbs;
+#ifdef MDB_VL32
+               txn->mt_rpages = parent->mt_rpages;
+#endif
                memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
                /* Copy parent's mt_dbflags, but clear DB_NEW */
                for (i=0; i<txn->mt_numdbs; i++)
@@ -2909,12 +3093,16 @@ renew:
                rc = mdb_txn_renew0(txn);
        }
        if (rc) {
-               if (txn != env->me_txn0)
+               if (txn != env->me_txn0) {
+#ifdef MDB_VL32
+                       free(txn->mt_rpages);
+#endif
                        free(txn);
+               }
        } else {
                txn->mt_flags |= flags; /* could not change txn=me_txn0 earlier */
                *ret = txn;
-               DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
+               DPRINTF(("begin txn %"Y"u%c %p on mdbenv %p, root page %"Y"u",
                        txn->mt_txnid, (flags & MDB_RDONLY) ? 'r' : 'w',
                        (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
        }
@@ -2929,7 +3117,7 @@ mdb_txn_env(MDB_txn *txn)
        return txn->mt_env;
 }
 
-size_t
+mdb_size_t
 mdb_txn_id(MDB_txn *txn)
 {
     if(!txn) return 0;
@@ -2981,7 +3169,7 @@ mdb_txn_end(MDB_txn *txn, unsigned mode)
        /* Export or close DBI handles opened in this txn */
        mdb_dbis_update(txn, mode & MDB_END_UPDATE);
 
-       DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
+       DPRINTF(("%s txn %"Y"u%c %p on mdbenv %p, root page %"Y"u",
                names[mode & MDB_END_OPMASK],
                txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
                (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
@@ -3035,7 +3223,31 @@ mdb_txn_end(MDB_txn *txn, unsigned mode)
 
                mdb_midl_free(pghead);
        }
-
+#ifdef MDB_VL32
+       if (!txn->mt_parent) {
+               MDB_ID3L el = env->me_rpages, tl = txn->mt_rpages;
+               unsigned i, x, n = tl[0].mid;
+               pthread_mutex_lock(&env->me_rpmutex);
+               for (i = 1; i <= n; i++) {
+                       if (tl[i].mid & (MDB_RPAGE_CHUNK-1)) {
+                               /* tmp overflow pages that we didn't share in env */
+                               munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
+                       } else {
+                               x = mdb_mid3l_search(el, tl[i].mid);
+                               if (tl[i].mptr == el[x].mptr) {
+                                       el[x].mref--;
+                               } else {
+                                       /* another tmp overflow page */
+                                       munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
+                               }
+                       }
+               }
+               pthread_mutex_unlock(&env->me_rpmutex);
+               tl[0].mid = 0;
+               if (mode & MDB_END_FREE)
+                       free(tl);
+       }
+#endif
        if (mode & MDB_END_FREE)
                free(txn);
 }
@@ -3067,6 +3279,9 @@ mdb_txn_abort(MDB_txn *txn)
 
 /** Save the freelist as of this transaction to the freeDB.
  * This changes the freelist. Keep trying until it stabilizes.
+ *
+ * When (MDB_DEVEL) & 2, the changes do not affect #mdb_page_alloc(),
+ * it then uses the transaction's original snapshot of the freeDB.
  */
 static int
 mdb_freelist_save(MDB_txn *txn)
@@ -3155,10 +3370,10 @@ mdb_freelist_save(MDB_txn *txn)
 #if (MDB_DEBUG) > 1
                        {
                                unsigned int i = free_pgs[0];
-                               DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
+                               DPRINTF(("IDL write txn %"Y"u root %"Y"u num %u",
                                        txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
                                for (; i; i--)
-                                       DPRINTF(("IDL %"Z"u", free_pgs[i]));
+                                       DPRINTF(("IDL %"Y"u", free_pgs[i]));
                        }
 #endif
                        continue;
@@ -3269,15 +3484,16 @@ mdb_page_flush(MDB_txn *txn, int keep)
        MDB_ID2L        dl = txn->mt_u.dirty_list;
        unsigned        psize = env->me_psize, j;
        int                     i, pagecount = dl[0].mid, rc;
-       size_t          size = 0, pos = 0;
+       size_t          size = 0;
+       off_t           pos = 0;
        pgno_t          pgno = 0;
        MDB_page        *dp = NULL;
 #ifdef _WIN32
        OVERLAPPED      ov;
 #else
        struct iovec iov[MDB_COMMIT_PAGES];
-       ssize_t         wpos = 0, wsize = 0, wres;
-       size_t          next_pos = 1; /* impossible pos, so pos != next_pos */
+       ssize_t         wsize = 0, wres;
+       off_t           wpos = 0, next_pos = 1; /* impossible pos, so pos != next_pos */
        int                     n = 0;
 #endif
 
@@ -3376,7 +3592,7 @@ retry_seek:
                        wpos = pos;
                        wsize = 0;
                }
-               DPRINTF(("committing page %"Z"u", pgno));
+               DPRINTF(("committing page %"Y"u", pgno));
                next_pos = pos + size;
                iov[n].iov_len = size;
                iov[n].iov_base = (char *)dp;
@@ -3384,6 +3600,10 @@ retry_seek:
                n++;
 #endif /* _WIN32 */
        }
+#ifdef MDB_VL32
+       if (pgno > txn->mt_last_pgno)
+               txn->mt_last_pgno = pgno;
+#endif
 
        /* 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
@@ -3498,6 +3718,25 @@ mdb_txn_commit(MDB_txn *txn)
                        pspill[0] = y;
                }
 
+               /* Remove anything in our spill list from parent's dirty list */
+               if (txn->mt_spill_pgs && txn->mt_spill_pgs[0]) {
+                       for (i=1; i<=txn->mt_spill_pgs[0]; i++) {
+                               MDB_ID pn = txn->mt_spill_pgs[i];
+                               if (pn & 1)
+                                       continue;       /* deleted spillpg */
+                               pn >>= 1;
+                               y = mdb_mid2l_search(dst, pn);
+                               if (y <= dst[0].mid && dst[y].mid == pn) {
+                                       free(dst[y].mptr);
+                                       while (y < dst[0].mid) {
+                                               dst[y] = dst[y+1];
+                                               y++;
+                                       }
+                                       dst[0].mid--;
+                               }
+                       }
+               }
+
                /* Find len = length of merging our dirty list with parent's */
                x = dst[0].mid;
                dst[0].mid = 0;         /* simplify loops */
@@ -3543,7 +3782,7 @@ mdb_txn_commit(MDB_txn *txn)
                }
 
                /* Append our loose page list to parent's */
-               for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(lp))
+               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;
@@ -3566,7 +3805,7 @@ mdb_txn_commit(MDB_txn *txn)
                !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
                goto done;
 
-       DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
+       DPRINTF(("committing txn %"Y"u %p on mdbenv %p, root page %"Y"u",
            txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
 
        /* Update DB root pointers */
@@ -3607,7 +3846,7 @@ mdb_txn_commit(MDB_txn *txn)
        if ((rc = mdb_page_flush(txn, 0)))
                goto fail;
        if (!F_ISSET(txn->mt_flags, MDB_TXN_NOSYNC) &&
-               (rc = mdb_env_sync(env, 0)))
+               (rc = mdb_env_sync0(env, 0, txn->mt_next_pgno)))
                goto fail;
        if ((rc = mdb_env_write_meta(txn)))
                goto fail;
@@ -3664,7 +3903,7 @@ mdb_env_read_header(MDB_env *env, MDB_meta *meta)
                p = (MDB_page *)&pbuf;
 
                if (!F_ISSET(p->mp_flags, P_META)) {
-                       DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
+                       DPRINTF(("page %"Y"u not a meta page", p->mp_pgno));
                        return MDB_INVALID;
                }
 
@@ -3764,7 +4003,7 @@ mdb_env_write_meta(MDB_txn *txn)
        MDB_env *env;
        MDB_meta        meta, metab, *mp;
        unsigned flags;
-       size_t mapsize;
+       mdb_size_t mapsize;
        off_t off;
        int rc, len, toggle;
        char *ptr;
@@ -3776,7 +4015,7 @@ mdb_env_write_meta(MDB_txn *txn)
 #endif
 
        toggle = txn->mt_txnid & 1;
-       DPRINTF(("writing meta page %d for root page %"Z"u",
+       DPRINTF(("writing meta page %d for root page %"Y"u",
                toggle, txn->mt_dbs[MAIN_DBI].md_root));
 
        env = txn->mt_env;
@@ -3927,42 +4166,51 @@ mdb_env_map(MDB_env *env, void *addr)
        unsigned int flags = env->me_flags;
 #ifdef _WIN32
        int rc;
+       int access = SECTION_MAP_READ;
        HANDLE mh;
-       LONG sizelo, sizehi;
-       size_t msize;
+       void *map;
+       SIZE_T msize;
+       ULONG pageprot = PAGE_READONLY, secprot, alloctype;
 
+       if (flags & MDB_WRITEMAP) {
+               access |= SECTION_MAP_WRITE;
+               pageprot = PAGE_READWRITE;
+       }
        if (flags & MDB_RDONLY) {
-               /* Don't set explicit map size, use whatever exists */
+               secprot = PAGE_READONLY;
                msize = 0;
-               sizelo = 0;
-               sizehi = 0;
+               alloctype = 0;
        } else {
+               secprot = PAGE_READWRITE;
                msize = env->me_mapsize;
-               sizelo = msize & 0xffffffff;
-               sizehi = msize >> 16 >> 16; /* only needed on Win64 */
-
-               /* Windows won't create mappings for zero length files.
-                * and won't map more than the file size.
-                * Just set the maxsize right now.
-                */
-               if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
-                       || !SetEndOfFile(env->me_fd)
-                       || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
-                       return ErrCode();
+               alloctype = MEM_RESERVE;
        }
 
-       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, msize, addr);
-       rc = env->me_map ? 0 : ErrCode();
-       CloseHandle(mh);
+       rc = NtCreateSection(&mh, access, NULL, NULL, secprot, SEC_RESERVE, env->me_fd);
        if (rc)
                return rc;
+       map = addr;
+#ifdef MDB_VL32
+       msize = NUM_METAS * env->me_psize;
+#endif
+       rc = NtMapViewOfSection(mh, GetCurrentProcess(), &map, 0, 0, NULL, &msize, ViewUnmap, alloctype, pageprot);
+#ifdef MDB_VL32
+       env->me_fmh = mh;
+#else
+       NtClose(mh);
+#endif
+       if (rc)
+               return rc;
+       env->me_map = map;
+#else
+#ifdef MDB_VL32
+       (void) flags;
+       env->me_map = mmap(addr, NUM_METAS * env->me_psize, PROT_READ, MAP_SHARED,
+               env->me_fd, 0);
+       if (env->me_map == MAP_FAILED) {
+               env->me_map = NULL;
+               return ErrCode();
+       }
 #else
        int prot = PROT_READ;
        if (flags & MDB_WRITEMAP) {
@@ -3996,6 +4244,7 @@ mdb_env_map(MDB_env *env, void *addr)
         */
        if (addr && env->me_map != addr)
                return EBUSY;   /* TODO: Make a new MDB_* error code? */
+#endif
 
        p = (MDB_page *)env->me_map;
        env->me_metas[0] = METADATA(p);
@@ -4005,15 +4254,17 @@ mdb_env_map(MDB_env *env, void *addr)
 }
 
 int ESECT
-mdb_env_set_mapsize(MDB_env *env, size_t size)
+mdb_env_set_mapsize(MDB_env *env, mdb_size_t size)
 {
        /* If env is already open, caller is responsible for making
         * sure there are no active txns.
         */
        if (env->me_map) {
-               int rc;
                MDB_meta *meta;
+#ifndef MDB_VL32
                void *old;
+               int rc;
+#endif
                if (env->me_txn)
                        return EINVAL;
                meta = mdb_env_pick_meta(env);
@@ -4021,16 +4272,21 @@ mdb_env_set_mapsize(MDB_env *env, size_t size)
                        size = meta->mm_mapsize;
                {
                        /* Silently round up to minimum if the size is too small */
-                       size_t minsize = (meta->mm_last_pg + 1) * env->me_psize;
+                       mdb_size_t minsize = (meta->mm_last_pg + 1) * env->me_psize;
                        if (size < minsize)
                                size = minsize;
                }
+#ifndef MDB_VL32
+               /* For MDB_VL32 this bit is a noop since we dynamically remap
+                * chunks of the DB anyway.
+                */
                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);
                if (rc)
                        return rc;
+#endif /* !MDB_VL32 */
        }
        env->me_mapsize = size;
        if (env->me_psize)
@@ -4066,7 +4322,7 @@ mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
 }
 
 static int ESECT
-mdb_fsize(HANDLE fd, size_t *size)
+mdb_fsize(HANDLE fd, mdb_size_t *size)
 {
 #ifdef _WIN32
        LARGE_INTEGER fsize;
@@ -4180,7 +4436,7 @@ mdb_env_open2(MDB_env *env)
                /* Make sure mapsize >= committed data size.  Even when using
                 * mm_mapsize, which could be broken in old files (ITS#7789).
                 */
-               size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
+               mdb_size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
                if (env->me_mapsize < minsize)
                        env->me_mapsize = minsize;
        }
@@ -4199,6 +4455,18 @@ mdb_env_open2(MDB_env *env)
                        return rc;
                newenv = 0;
        }
+#ifdef _WIN32
+       /* For FIXEDMAP, make sure the file is non-empty before we attempt to map it */
+       if (newenv) {
+               char dummy = 0;
+               DWORD len;
+               rc = WriteFile(env->me_fd, &dummy, 1, &len, NULL);
+               if (!rc) {
+                       rc = ErrCode();
+                       return rc;
+               }
+       }
+#endif
 
        rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
        if (rc)
@@ -4230,11 +4498,11 @@ mdb_env_open2(MDB_env *env)
                        meta->mm_version, env->me_psize));
                DPRINTF(("using meta page %d",    (int) (meta->mm_txnid & 1)));
                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));
+               DPRINTF(("entries: %"Y"u",        db->md_entries));
+               DPRINTF(("branch pages: %"Y"u",   db->md_branch_pages));
+               DPRINTF(("leaf pages: %"Y"u",     db->md_leaf_pages));
+               DPRINTF(("overflow pages: %"Y"u", db->md_overflow_pages));
+               DPRINTF(("root: %"Y"u",           db->md_root));
        }
 #endif
 
@@ -4518,9 +4786,14 @@ mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
        off_t size, rsize;
 
 #ifdef _WIN32
-       env->me_lfd = CreateFileA(lpath, GENERIC_READ|GENERIC_WRITE,
+       wchar_t *wlpath;
+       rc = utf8_to_utf16(lpath, -1, &wlpath, NULL);
+       if (rc)
+               return rc;
+       env->me_lfd = CreateFileW(wlpath, GENERIC_READ|GENERIC_WRITE,
                FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
                FILE_ATTRIBUTE_NORMAL, NULL);
+       free(wlpath);
 #else
        env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
 #endif
@@ -4738,6 +5011,13 @@ mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
        env->me_wmutex->semnum = 1;
        env->me_rmutex->locked = &env->me_txns->mti_rlocked;
        env->me_wmutex->locked = &env->me_txns->mti_wlocked;
+#endif
+#ifdef MDB_VL32
+#ifdef _WIN32
+       env->me_rpmutex = CreateMutex(NULL, FALSE, NULL);
+#else
+       pthread_mutex_init(&env->me_rpmutex, NULL);
+#endif
 #endif
 
        return MDB_SUCCESS;
@@ -4771,10 +5051,24 @@ mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode
 {
        int             oflags, rc, len, excl = -1;
        char *lpath, *dpath;
+#ifdef _WIN32
+       wchar_t *wpath;
+#endif
 
        if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
                return EINVAL;
 
+#ifdef MDB_VL32
+       if (flags & MDB_WRITEMAP) {
+               /* silently ignore WRITEMAP in 32 bit mode */
+               flags ^= MDB_WRITEMAP;
+       }
+       if (flags & MDB_FIXEDMAP) {
+               /* cannot support FIXEDMAP */
+               return EINVAL;
+       }
+#endif
+
        len = strlen(path);
        if (flags & MDB_NOSUBDIR) {
                rc = len + sizeof(LOCKSUFF) + len + 1;
@@ -4804,6 +5098,17 @@ mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode
                          (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
                        rc = ENOMEM;
        }
+#ifdef MDB_VL32
+       if (!rc) {
+               env->me_rpages = malloc(MDB_ERPAGE_SIZE * sizeof(MDB_ID3));
+               if (!env->me_rpages) {
+                       rc = ENOMEM;
+                       goto leave;
+               }
+               env->me_rpages[0].mid = 0;
+               env->me_rpcheck = MDB_ERPAGE_SIZE/2;
+       }
+#endif
        env->me_flags = flags |= MDB_ENV_ACTIVE;
        if (rc)
                goto leave;
@@ -4834,8 +5139,12 @@ mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode
                len = OPEN_ALWAYS;
        }
        mode = FILE_ATTRIBUTE_NORMAL;
-       env->me_fd = CreateFileA(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
+       rc = utf8_to_utf16(dpath, -1, &wpath, NULL);
+       if (rc)
+               goto leave;
+       env->me_fd = CreateFileW(wpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
                NULL, len, mode, NULL);
+       free(wpath);
 #else
        if (F_ISSET(flags, MDB_RDONLY))
                oflags = O_RDONLY;
@@ -4864,9 +5173,13 @@ mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode
                         */
 #ifdef _WIN32
                        len = OPEN_EXISTING;
-                       env->me_mfd = CreateFileA(dpath, oflags,
+                       rc = utf8_to_utf16(dpath, -1, &wpath, NULL);
+                       if (rc)
+                               goto leave;
+                       env->me_mfd = CreateFileW(wpath, oflags,
                                FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
                                mode | FILE_FLAG_WRITE_THROUGH, NULL);
+                       free(wpath);
 #else
                        oflags &= ~O_CREAT;
                        env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
@@ -4894,6 +5207,16 @@ mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode
                                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;
+#ifdef MDB_VL32
+                               txn->mt_rpages = malloc(MDB_TRPAGE_SIZE * sizeof(MDB_ID3));
+                               if (!txn->mt_rpages) {
+                                       free(txn);
+                                       rc = ENOMEM;
+                                       goto leave;
+                               }
+                               txn->mt_rpages[0].mid = 0;
+                               txn->mt_rpcheck = MDB_TRPAGE_SIZE/2;
+#endif
                                txn->mt_dbxs = env->me_dbxs;
                                txn->mt_flags = MDB_TXN_FINISHED;
                                env->me_txn0 = txn;
@@ -4932,6 +5255,15 @@ mdb_env_close0(MDB_env *env, int excl)
        free(env->me_dbflags);
        free(env->me_path);
        free(env->me_dirty_list);
+#ifdef MDB_VL32
+       if (env->me_txn0 && env->me_txn0->mt_rpages)
+               free(env->me_txn0->mt_rpages);
+       { unsigned int x;
+               for (x=1; x<=env->me_rpages[0].mid; x++)
+               munmap(env->me_rpages[x].mptr, env->me_rpages[x].mcnt * env->me_psize);
+       }
+       free(env->me_rpages);
+#endif
        free(env->me_txn0);
        mdb_midl_free(env->me_free_pgs);
 
@@ -4949,7 +5281,11 @@ mdb_env_close0(MDB_env *env, int excl)
        }
 
        if (env->me_map) {
+#ifdef MDB_VL32
+               munmap(env->me_map, NUM_METAS*env->me_psize);
+#else
                munmap(env->me_map, env->me_mapsize);
+#endif
        }
        if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
                (void) close(env->me_mfd);
@@ -5014,6 +5350,14 @@ mdb_env_close0(MDB_env *env, int excl)
 #endif
                (void) close(env->me_lfd);
        }
+#ifdef MDB_VL32
+#ifdef _WIN32
+       if (env->me_fmh) CloseHandle(env->me_fmh);
+       if (env->me_rpmutex) CloseHandle(env->me_rpmutex);
+#else
+       pthread_mutex_destroy(&env->me_rpmutex);
+#endif
+#endif
 
        env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
 }
@@ -5037,18 +5381,18 @@ mdb_env_close(MDB_env *env)
        free(env);
 }
 
-/** Compare two items pointing at aligned size_t's */
+/** Compare two items pointing at aligned mdb_size_t's */
 static int
 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
 {
-       return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
-               *(size_t *)a->mv_data > *(size_t *)b->mv_data;
+       return (*(mdb_size_t *)a->mv_data < *(mdb_size_t *)b->mv_data) ? -1 :
+               *(mdb_size_t *)a->mv_data > *(mdb_size_t *)b->mv_data;
 }
 
 /** 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.
+ *     but #mdb_cmp_clong() is called instead if the data type is mdb_size_t.
  */
 static int
 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
@@ -5153,7 +5497,7 @@ mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
 
        nkeys = NUMKEYS(mp);
 
-       DPRINTF(("searching %u keys in %s %spage %"Z"u",
+       DPRINTF(("searching %u keys in %s %spage %"Y"u",
            nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
            mdb_dbg_pgno(mp)));
 
@@ -5165,7 +5509,7 @@ mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
         * alignment is guaranteed. Use faster mdb_cmp_int.
         */
        if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
-               if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
+               if (NODEPTR(mp, 1)->mn_ksize == sizeof(mdb_size_t))
                        cmp = mdb_cmp_long;
                else
                        cmp = mdb_cmp_int;
@@ -5201,7 +5545,7 @@ mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
                                DPRINTF(("found leaf index %u [%s], rc = %i",
                                    i, DKEY(&nodekey), rc));
                        else
-                               DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
+                               DPRINTF(("found branch index %u [%s -> %"Y"u], rc = %i",
                                    i, DKEY(&nodekey), NODEPGNO(node), rc));
 #endif
                        if (rc == 0)
@@ -5249,12 +5593,15 @@ static void
 mdb_cursor_pop(MDB_cursor *mc)
 {
        if (mc->mc_snum) {
-               DPRINTF(("popping page %"Z"u off db %d cursor %p",
+               DPRINTF(("popping page %"Y"u off db %d cursor %p",
                        mc->mc_pg[mc->mc_top]->mp_pgno, DDBI(mc), (void *) mc));
 
                mc->mc_snum--;
-               if (mc->mc_snum)
+               if (mc->mc_snum) {
                        mc->mc_top--;
+               } else {
+                       mc->mc_flags &= ~C_INITIALIZED;
+               }
        }
 }
 
@@ -5262,7 +5609,7 @@ mdb_cursor_pop(MDB_cursor *mc)
 static int
 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
 {
-       DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
+       DPRINTF(("pushing page %"Y"u on db %d cursor %p", mp->mp_pgno,
                DDBI(mc), (void *) mc));
 
        if (mc->mc_snum >= CURSOR_STACK) {
@@ -5277,21 +5624,311 @@ mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
        return MDB_SUCCESS;
 }
 
-/** Find the address of the page corresponding to a given page number.
+#ifdef MDB_VL32
+/** Map a read-only page.
+ * There are two levels of tracking in use, a per-txn list and a per-env list.
+ * ref'ing and unref'ing the per-txn list is faster since it requires no
+ * locking. Pages are cached in the per-env list for global reuse, and a lock
+ * is required. Pages are not immediately unmapped when their refcnt goes to
+ * zero; they hang around in case they will be reused again soon.
+ *
+ * When the per-txn list gets full, all pages with refcnt=0 are purged from the
+ * list and their refcnts in the per-env list are decremented.
+ *
+ * When the per-env list gets full, all pages with refcnt=0 are purged from the
+ * list and their pages are unmapped.
+ *
+ * @note "full" means the list has reached its respective rpcheck threshold.
+ * This threshold slowly raises if no pages could be purged on a given check,
+ * and returns to its original value when enough pages were purged.
+ *
+ * If purging doesn't free any slots, filling the per-txn list will return
+ * MDB_TXN_FULL, and filling the per-env list returns MDB_MAP_FULL.
+ *
+ * Reference tracking in a txn is imperfect, pages can linger with non-zero
+ * refcnt even without active references. It was deemed to be too invasive
+ * to add unrefs in every required location. However, all pages are unref'd
+ * at the end of the transaction. This guarantees that no stale references
+ * linger in the per-env list.
+ *
+ * Usually we map chunks of 16 pages at a time, but if an overflow page begins
+ * at the tail of the chunk we extend the chunk to include the entire overflow
+ * page. Unfortunately, pages can be turned into overflow pages after their
+ * chunk was already mapped. In that case we must remap the chunk if the
+ * overflow page is referenced. If the chunk's refcnt is 0 we can just remap
+ * it, otherwise we temporarily map a new chunk just for the overflow page.
+ *
+ * @note this chunk handling means we cannot guarantee that a data item
+ * returned from the DB will stay alive for the duration of the transaction:
+ *   We unref pages as soon as a cursor moves away from the page
+ *   A subsequent op may cause a purge, which may unmap any unref'd chunks
+ * The caller must copy the data if it must be used later in the same txn.
+ *
+ * Also - our reference counting revolves around cursors, but overflow pages
+ * aren't pointed to by a cursor's page stack. We have to remember them
+ * explicitly, in the added mc_ovpg field. A single cursor can only hold a
+ * reference to one overflow page at a time.
+ *
  * @param[in] txn the transaction for this access.
  * @param[in] pgno the page number for the page to retrieve.
  * @param[out] ret address of a pointer where the page's address will be stored.
+ * @return 0 on success, non-zero on failure.
+ */
+static int
+mdb_rpage_get(MDB_txn *txn, pgno_t pg0, MDB_page **ret)
+{
+       MDB_env *env = txn->mt_env;
+       MDB_page *p;
+       MDB_ID3L tl = txn->mt_rpages;
+       MDB_ID3L el = env->me_rpages;
+       MDB_ID3 id3;
+       unsigned x, rem;
+       pgno_t pgno;
+       int rc, retries = 1;
+#ifdef _WIN32
+       LARGE_INTEGER off;
+       SIZE_T len;
+#define SET_OFF(off,val)       off.QuadPart = val
+#define MAP(rc,env,addr,len,off)       \
+       addr = NULL; \
+       rc = NtMapViewOfSection(env->me_fmh, GetCurrentProcess(), &addr, 0, \
+               len, &off, &len, ViewUnmap, (env->me_flags & MDB_RDONLY) ? 0 : MEM_RESERVE, PAGE_READONLY)
+#else
+       off_t off;
+       size_t len;
+#define SET_OFF(off,val)       off = val
+#define MAP(rc,env,addr,len,off)       \
+       addr = mmap(NULL, len, PROT_READ, MAP_SHARED, env->me_fd, off); \
+       rc = (addr == MAP_FAILED) ? errno : 0
+#endif
+
+       /* remember the offset of the actual page number, so we can
+        * return the correct pointer at the end.
+        */
+       rem = pg0 & (MDB_RPAGE_CHUNK-1);
+       pgno = pg0 ^ rem;
+
+       id3.mid = 0;
+       x = mdb_mid3l_search(tl, pgno);
+       if (x <= tl[0].mid && tl[x].mid == pgno) {
+               if (x != tl[0].mid && tl[x+1].mid == pg0)
+                       x++;
+               /* check for overflow size */
+               p = (MDB_page *)((char *)tl[x].mptr + rem * env->me_psize);
+               if (IS_OVERFLOW(p) && p->mp_pages + rem > tl[x].mcnt) {
+                       id3.mcnt = p->mp_pages + rem;
+                       len = id3.mcnt * env->me_psize;
+                       SET_OFF(off, pgno * env->me_psize);
+                       MAP(rc, env, id3.mptr, len, off);
+                       if (rc)
+                               return rc;
+                       /* check for local-only page */
+                       if (rem) {
+                               mdb_tassert(txn, tl[x].mid != pg0);
+                               /* hope there's room to insert this locally.
+                                * setting mid here tells later code to just insert
+                                * this id3 instead of searching for a match.
+                                */
+                               id3.mid = pg0;
+                               goto notlocal;
+                       } else {
+                               /* ignore the mapping we got from env, use new one */
+                               tl[x].mptr = id3.mptr;
+                               tl[x].mcnt = id3.mcnt;
+                               /* if no active ref, see if we can replace in env */
+                               if (!tl[x].mref) {
+                                       unsigned i;
+                                       pthread_mutex_lock(&env->me_rpmutex);
+                                       i = mdb_mid3l_search(el, tl[x].mid);
+                                       if (el[i].mref == 1) {
+                                               /* just us, replace it */
+                                               munmap(el[i].mptr, el[i].mcnt * env->me_psize);
+                                               el[i].mptr = tl[x].mptr;
+                                               el[i].mcnt = tl[x].mcnt;
+                                       } else {
+                                               /* there are others, remove ourself */
+                                               el[i].mref--;
+                                       }
+                                       pthread_mutex_unlock(&env->me_rpmutex);
+                               }
+                       }
+               }
+               id3.mptr = tl[x].mptr;
+               id3.mcnt = tl[x].mcnt;
+               tl[x].mref++;
+               goto ok;
+       }
+
+notlocal:
+       if (tl[0].mid >= MDB_TRPAGE_MAX - txn->mt_rpcheck) {
+               unsigned i, y;
+               /* purge unref'd pages from our list and unref in env */
+               pthread_mutex_lock(&env->me_rpmutex);
+retry:
+               y = 0;
+               for (i=1; i<=tl[0].mid; i++) {
+                       if (!tl[i].mref) {
+                               if (!y) y = i;
+                               /* tmp overflow pages don't go to env */
+                               if (tl[i].mid & (MDB_RPAGE_CHUNK-1)) {
+                                       munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
+                                       continue;
+                               }
+                               x = mdb_mid3l_search(el, tl[i].mid);
+                               el[x].mref--;
+                       }
+               }
+               pthread_mutex_unlock(&env->me_rpmutex);
+               if (!y) {
+                       /* we didn't find any unref'd chunks.
+                        * if we're out of room, fail.
+                        */
+                       if (tl[0].mid >= MDB_TRPAGE_MAX)
+                               return MDB_TXN_FULL;
+                       /* otherwise, raise threshold for next time around
+                        * and let this go.
+                        */
+                       txn->mt_rpcheck /= 2;
+               } else {
+                       /* we found some unused; consolidate the list */
+                       for (i=y+1; i<= tl[0].mid; i++)
+                               if (tl[i].mref)
+                                       tl[y++] = tl[i];
+                       tl[0].mid = y-1;
+                       /* decrease the check threshold toward its original value */
+                       if (!txn->mt_rpcheck)
+                               txn->mt_rpcheck = 1;
+                       while (txn->mt_rpcheck < tl[0].mid && txn->mt_rpcheck < MDB_TRPAGE_SIZE/2)
+                               txn->mt_rpcheck *= 2;
+               }
+       }
+       if (tl[0].mid < MDB_TRPAGE_SIZE) {
+               id3.mref = 1;
+               if (id3.mid)
+                       goto found;
+               /* don't map past last written page in read-only envs */
+               if ((env->me_flags & MDB_RDONLY) && pgno + MDB_RPAGE_CHUNK-1 > txn->mt_last_pgno)
+                       id3.mcnt = txn->mt_last_pgno + 1 - pgno;
+               else
+                       id3.mcnt = MDB_RPAGE_CHUNK;
+               len = id3.mcnt * env->me_psize;
+               id3.mid = pgno;
+
+               /* search for page in env */
+               pthread_mutex_lock(&env->me_rpmutex);
+               x = mdb_mid3l_search(el, pgno);
+               if (x <= el[0].mid && el[x].mid == pgno) {
+                       id3.mptr = el[x].mptr;
+                       id3.mcnt = el[x].mcnt;
+                       /* check for overflow size */
+                       p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
+                       if (IS_OVERFLOW(p) && p->mp_pages + rem > id3.mcnt) {
+                               id3.mcnt = p->mp_pages + rem;
+                               len = id3.mcnt * env->me_psize;
+                               SET_OFF(off, pgno * env->me_psize);
+                               MAP(rc, env, id3.mptr, len, off);
+                               if (rc)
+                                       goto fail;
+                               if (!el[x].mref) {
+                                       munmap(el[x].mptr, env->me_psize * el[x].mcnt);
+                                       el[x].mptr = id3.mptr;
+                                       el[x].mcnt = id3.mcnt;
+                               } else {
+                                       id3.mid = pg0;
+                                       pthread_mutex_unlock(&env->me_rpmutex);
+                                       goto found;
+                               }
+                       }
+                       el[x].mref++;
+                       pthread_mutex_unlock(&env->me_rpmutex);
+                       goto found;
+               }
+               if (el[0].mid >= MDB_ERPAGE_MAX - env->me_rpcheck) {
+                       /* purge unref'd pages */
+                       unsigned i, y = 0;
+                       for (i=1; i<=el[0].mid; i++) {
+                               if (!el[i].mref) {
+                                       if (!y) y = i;
+                                       munmap(el[i].mptr, env->me_psize * el[i].mcnt);
+                               }
+                       }
+                       if (!y) {
+                               if (retries) {
+                                       /* see if we can unref some local pages */
+                                       retries--;
+                                       id3.mid = 0;
+                                       goto retry;
+                               }
+                               if (el[0].mid >= MDB_ERPAGE_MAX) {
+                                       pthread_mutex_unlock(&env->me_rpmutex);
+                                       return MDB_MAP_FULL;
+                               }
+                               env->me_rpcheck /= 2;
+                       } else {
+                               for (i=y+1; i<= el[0].mid; i++)
+                                       if (el[i].mref)
+                                               el[y++] = el[i];
+                               el[0].mid = y-1;
+                               if (!env->me_rpcheck)
+                                       env->me_rpcheck = 1;
+                               while (env->me_rpcheck < el[0].mid && env->me_rpcheck < MDB_ERPAGE_SIZE/2)
+                                       env->me_rpcheck *= 2;
+                       }
+               }
+               SET_OFF(off, pgno * env->me_psize);
+               MAP(rc, env, id3.mptr, len, off);
+               if (rc) {
+fail:
+                       pthread_mutex_unlock(&env->me_rpmutex);
+                       return rc;
+               }
+               /* check for overflow size */
+               p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
+               if (IS_OVERFLOW(p) && p->mp_pages + rem > id3.mcnt) {
+                       id3.mcnt = p->mp_pages + rem;
+                       munmap(id3.mptr, len);
+                       len = id3.mcnt * env->me_psize;
+                       MAP(rc, env, id3.mptr, len, off);
+                       if (rc)
+                               goto fail;
+               }
+               mdb_mid3l_insert(el, &id3);
+               pthread_mutex_unlock(&env->me_rpmutex);
+found:
+               mdb_mid3l_insert(tl, &id3);
+       } else {
+               return MDB_TXN_FULL;
+       }
+ok:
+       p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
+#if MDB_DEBUG  /* we don't need this check any more */
+       if (IS_OVERFLOW(p)) {
+               mdb_tassert(txn, p->mp_pages + rem <= id3.mcnt);
+       }
+#endif
+       *ret = p;
+       return MDB_SUCCESS;
+}
+#endif
+
+/** Find the address of the page corresponding to a given page number.
+ * @param[in] mc the cursor accessing the page.
+ * @param[in] pgno the page number for the page to retrieve.
+ * @param[out] ret address of a pointer where the page's address will be stored.
  * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
  * @return 0 on success, non-zero on failure.
  */
 static int
-mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
+mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **ret, int *lvl)
 {
+       MDB_txn *txn = mc->mc_txn;
+#ifndef MDB_VL32
        MDB_env *env = txn->mt_env;
+#endif
        MDB_page *p = NULL;
        int level;
 
-       if (! (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_WRITEMAP))) {
+       if (! (mc->mc_flags & (C_ORIG_RDONLY|C_WRITEMAP))) {
                MDB_txn *tx2 = txn;
                level = 1;
                do {
@@ -5306,7 +5943,13 @@ mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
                                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) {
+#ifdef MDB_VL32
+                                       int rc = mdb_rpage_get(txn, pgno, &p);
+                                       if (rc)
+                                               return rc;
+#else
                                        p = (MDB_page *)(env->me_map + env->me_psize * pgno);
+#endif
                                        goto done;
                                }
                        }
@@ -5323,9 +5966,17 @@ mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
 
        if (pgno < txn->mt_next_pgno) {
                level = 0;
+#ifdef MDB_VL32
+               {
+                       int rc = mdb_rpage_get(txn, pgno, &p);
+                       if (rc)
+                               return rc;
+               }
+#else
                p = (MDB_page *)(env->me_map + env->me_psize * pgno);
+#endif
        } else {
-               DPRINTF(("page %"Z"u not found", pgno));
+               DPRINTF(("page %"Y"u not found", pgno));
                txn->mt_flags |= MDB_TXN_ERROR;
                return MDB_PAGE_NOTFOUND;
        }
@@ -5351,9 +6002,13 @@ mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
                MDB_node        *node;
                indx_t          i;
 
-               DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
-               mdb_cassert(mc, NUMKEYS(mp) > 1);
-               DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
+               DPRINTF(("branch page %"Y"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
+               /* Don't assert on branch pages in the FreeDB. We can get here
+                * while in the process of rebalancing a FreeDB branch page; we must
+                * let that proceed. ITS#8336
+                */
+               mdb_cassert(mc, !mc->mc_dbi || NUMKEYS(mp) > 1);
+               DPRINTF(("found index 0 to page %"Y"u", NODEPGNO(NODEPTR(mp, 0))));
 
                if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
                        i = 0;
@@ -5377,7 +6032,7 @@ mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
                mdb_cassert(mc, i < NUMKEYS(mp));
                node = NODEPTR(mp, i);
 
-               if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
+               if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
                        return rc;
 
                mc->mc_ki[mc->mc_top] = i;
@@ -5398,7 +6053,7 @@ mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
                return MDB_CORRUPTED;
        }
 
-       DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
+       DPRINTF(("found leaf page %"Y"u for key [%s]", mp->mp_pgno,
            key ? DKEY(key) : "null"));
        mc->mc_flags |= C_INITIALIZED;
        mc->mc_flags &= ~C_EOF;
@@ -5419,7 +6074,7 @@ mdb_page_search_lowest(MDB_cursor *mc)
        MDB_node        *node = NODEPTR(mp, 0);
        int rc;
 
-       if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
+       if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
                return rc;
 
        mc->mc_ki[mc->mc_top] = 0;
@@ -5471,7 +6126,7 @@ mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
                                                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);
+                                       rc = mdb_node_read(&mc2, leaf, &data);
                                        if (rc)
                                                return rc;
                                        memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
@@ -5494,14 +6149,26 @@ mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
        }
 
        mdb_cassert(mc, root > 1);
-       if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
-               if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
+       if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root) {
+#ifdef MDB_VL32
+               if (mc->mc_pg[0])
+                       MDB_PAGE_UNREF(mc->mc_txn, mc->mc_pg[0]);
+#endif
+               if ((rc = mdb_page_get(mc, root, &mc->mc_pg[0], NULL)) != 0)
                        return rc;
+       }
 
+#ifdef MDB_VL32
+       {
+               int i;
+               for (i=1; i<mc->mc_snum; i++)
+                       MDB_PAGE_UNREF(mc->mc_txn, mc->mc_pg[i]);
+       }
+#endif
        mc->mc_snum = 1;
        mc->mc_top = 0;
 
-       DPRINTF(("db %d root page %"Z"u has flags 0x%X",
+       DPRINTF(("db %d root page %"Y"u has flags 0x%X",
                DDBI(mc), root, mc->mc_pg[0]->mp_flags));
 
        if (flags & MDB_PS_MODIFY) {
@@ -5526,7 +6193,7 @@ mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
        MDB_ID pn = pg << 1;
        int rc;
 
-       DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
+       DPRINTF(("free ov page %"Y"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.
@@ -5570,6 +6237,7 @@ mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
                                return MDB_CORRUPTED;
                        }
                }
+               txn->mt_dirty_room++;
                if (!(env->me_flags & MDB_WRITEMAP))
                        mdb_dpage_free(env, mp);
 release:
@@ -5591,18 +6259,24 @@ release:
 }
 
 /** Return the data associated with a given node.
- * @param[in] txn The transaction for this operation.
+ * @param[in] mc The cursor for this operation.
  * @param[in] leaf The node being read.
  * @param[out] data Updated to point to the node's data.
  * @return 0 on success, non-zero on failure.
  */
 static int
-mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
+mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data)
 {
        MDB_page        *omp;           /* overflow page */
        pgno_t           pgno;
        int rc;
 
+#ifdef MDB_VL32
+       if (mc->mc_ovpg) {
+               MDB_PAGE_UNREF(mc->mc_txn, mc->mc_ovpg);
+               mc->mc_ovpg = 0;
+       }
+#endif
        if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
                data->mv_size = NODEDSZ(leaf);
                data->mv_data = NODEDATA(leaf);
@@ -5613,11 +6287,14 @@ 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 %"Z"u failed", pgno));
+       if ((rc = mdb_page_get(mc, pgno, &omp, NULL)) != 0) {
+               DPRINTF(("read overflow page %"Y"u failed", pgno));
                return rc;
        }
        data->mv_data = METADATA(omp);
+#ifdef MDB_VL32
+       mc->mc_ovpg = omp;
+#endif
 
        return MDB_SUCCESS;
 }
@@ -5628,7 +6305,7 @@ mdb_get(MDB_txn *txn, MDB_dbi dbi,
 {
        MDB_cursor      mc;
        MDB_xcursor     mx;
-       int exact = 0;
+       int exact = 0, rc;
        DKBUF;
 
        DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
@@ -5640,7 +6317,16 @@ mdb_get(MDB_txn *txn, MDB_dbi dbi,
                return MDB_BAD_TXN;
 
        mdb_cursor_init(&mc, txn, dbi, &mx);
-       return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
+       rc = mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
+#ifdef MDB_VL32
+       {
+               /* unref all the pages - caller must copy the data
+                * before doing anything else
+                */
+               mdb_cursor_unref(&mc);
+       }
+#endif
+       return rc;
 }
 
 /** Find a sibling for a page.
@@ -5657,13 +6343,19 @@ mdb_cursor_sibling(MDB_cursor *mc, int move_right)
        int              rc;
        MDB_node        *indx;
        MDB_page        *mp;
+#ifdef MDB_VL32
+       MDB_page        *op;
+#endif
 
        if (mc->mc_snum < 2) {
                return MDB_NOTFOUND;            /* root has no siblings */
        }
 
+#ifdef MDB_VL32
+       op = mc->mc_pg[mc->mc_top];
+#endif
        mdb_cursor_pop(mc);
-       DPRINTF(("parent page is page %"Z"u, index %u",
+       DPRINTF(("parent page is page %"Y"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]))
@@ -5686,8 +6378,10 @@ mdb_cursor_sibling(MDB_cursor *mc, int move_right)
        }
        mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
 
+       MDB_PAGE_UNREF(mc->mc_txn, op);
+
        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, 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;
@@ -5727,6 +6421,13 @@ mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
                                        return rc;
                                }
                        }
+#ifdef MDB_VL32
+                       else {
+                               if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
+                                       mdb_cursor_unref(&mc->mc_xcursor->mx_cursor);
+                               }
+                       }
+#endif
                } else {
                        mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
                        if (op == MDB_NEXT_DUP)
@@ -5734,10 +6435,12 @@ mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
                }
        }
 
-       DPRINTF(("cursor_next: top page is %"Z"u in cursor %p",
+       DPRINTF(("cursor_next: top page is %"Y"u in cursor %p",
                mdb_dbg_pgno(mp), (void *) mc));
-       if (mc->mc_flags & C_DEL)
+       if (mc->mc_flags & C_DEL) {
+               mc->mc_flags ^= C_DEL;
                goto skip;
+       }
 
        if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
                DPUTS("=====> move to next sibling page");
@@ -5746,12 +6449,12 @@ 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 %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
+               DPRINTF(("next page is %"Y"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
        } else
                mc->mc_ki[mc->mc_top]++;
 
 skip:
-       DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
+       DPRINTF(("==> cursor points to page %"Y"u with %u keys, key index %u",
            mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
 
        if (IS_LEAF2(mp)) {
@@ -5767,7 +6470,7 @@ skip:
                mdb_xcursor_init1(mc, leaf);
        }
        if (data) {
-               if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
+               if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
                        return rc;
 
                if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
@@ -5806,6 +6509,13 @@ mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
                                        return rc;
                                }
                        }
+#ifdef MDB_VL32
+                       else {
+                               if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
+                                       mdb_cursor_unref(&mc->mc_xcursor->mx_cursor);
+                               }
+                       }
+#endif
                } else {
                        mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
                        if (op == MDB_PREV_DUP)
@@ -5813,9 +6523,11 @@ mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
                }
        }
 
-       DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p",
+       DPRINTF(("cursor_prev: top page is %"Y"u in cursor %p",
                mdb_dbg_pgno(mp), (void *) mc));
 
+       mc->mc_flags &= ~(C_EOF|C_DEL);
+
        if (mc->mc_ki[mc->mc_top] == 0)  {
                DPUTS("=====> move to prev sibling page");
                if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
@@ -5823,13 +6535,13 @@ 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 %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
+               DPRINTF(("prev page is %"Y"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 %"Z"u with %u keys, key index %u",
+       DPRINTF(("==> cursor points to page %"Y"u with %u keys, key index %u",
            mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
 
        if (IS_LEAF2(mp)) {
@@ -5845,7 +6557,7 @@ mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
                mdb_xcursor_init1(mc, leaf);
        }
        if (data) {
-               if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
+               if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
                        return rc;
 
                if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
@@ -5964,6 +6676,8 @@ mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
                        } else
                                return MDB_NOTFOUND;
                }
+       } else {
+               mc->mc_pg[0] = 0;
        }
 
        rc = mdb_page_search(mc, key, 0);
@@ -6003,6 +6717,11 @@ set1:
                return MDB_SUCCESS;
        }
 
+#ifdef MDB_VL32
+       if (mc->mc_xcursor && mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
+               mdb_cursor_unref(&mc->mc_xcursor->mx_cursor);
+       }
+#endif
        if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
                mdb_xcursor_init1(mc, leaf);
        }
@@ -6025,11 +6744,11 @@ set1:
                } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
                        MDB_val olddata;
                        MDB_cmp_func *dcmp;
-                       if ((rc = mdb_node_read(mc->mc_txn, leaf, &olddata)) != MDB_SUCCESS)
+                       if ((rc = mdb_node_read(mc, leaf, &olddata)) != MDB_SUCCESS)
                                return rc;
                        dcmp = mc->mc_dbx->md_dcmp;
-#if UINT_MAX < SIZE_MAX
-                       if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
+#if UINT_MAX < SIZE_MAX || defined(MDB_VL32)
+                       if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(mdb_size_t))
                                dcmp = mdb_cmp_clong;
 #endif
                        rc = dcmp(data, &olddata);
@@ -6043,7 +6762,7 @@ set1:
                } 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)
+                       if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
                                return rc;
                }
        }
@@ -6063,8 +6782,14 @@ mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
        int              rc;
        MDB_node        *leaf;
 
-       if (mc->mc_xcursor)
+       if (mc->mc_xcursor) {
+#ifdef MDB_VL32
+               if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
+                       mdb_cursor_unref(&mc->mc_xcursor->mx_cursor);
+               }
+#endif
                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, MDB_PS_FIRST);
@@ -6092,7 +6817,7 @@ mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
                        if (rc)
                                return rc;
                } else {
-                       if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
+                       if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
                                return rc;
                }
        }
@@ -6107,8 +6832,14 @@ mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
        int              rc;
        MDB_node        *leaf;
 
-       if (mc->mc_xcursor)
+       if (mc->mc_xcursor) {
+#ifdef MDB_VL32
+               if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
+                       mdb_cursor_unref(&mc->mc_xcursor->mx_cursor);
+               }
+#endif
                mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
+       }
 
        if (!(mc->mc_flags & C_EOF)) {
 
@@ -6137,7 +6868,7 @@ mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
                        if (rc)
                                return rc;
                } else {
-                       if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
+                       if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
                                return rc;
                }
        }
@@ -6181,11 +6912,9 @@ 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);
+                                               rc = mdb_node_read(mc, leaf, data);
                                        }
                                }
                        }
@@ -6253,6 +6982,28 @@ fetchm:
                        }
                }
                break;
+       case MDB_PREV_MULTIPLE:
+               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 {
+                       MDB_cursor *mx = &mc->mc_xcursor->mx_cursor;
+                       if (mx->mc_flags & C_INITIALIZED) {
+                               rc = mdb_cursor_sibling(mx, 0);
+                               if (rc == MDB_SUCCESS)
+                                       goto fetchm;
+                       } else {
+                               rc = MDB_NOTFOUND;
+                       }
+               }
+               break;
        case MDB_NEXT:
        case MDB_NEXT_DUP:
        case MDB_NEXT_NODUP:
@@ -6291,7 +7042,7 @@ fetchm:
                        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);
+                               rc = mdb_node_read(mc, leaf, data);
                                break;
                        }
                }
@@ -6512,16 +7263,18 @@ fix_parent:
                         * 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;
+                               unsigned short dtop = 1;
                                mc->mc_top--;
                                /* slot 0 is always an empty key, find real slot */
-                               while (mc->mc_top && !mc->mc_ki[mc->mc_top])
+                               while (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
                                        mc->mc_top--;
+                                       dtop++;
+                               }
                                if (mc->mc_ki[mc->mc_top])
                                        rc2 = mdb_update_key(mc, key);
                                else
                                        rc2 = MDB_SUCCESS;
-                               mc->mc_top top;
+                               mc->mc_top += dtop;
                                if (rc2)
                                        return rc2;
                        }
@@ -6551,13 +7304,13 @@ more:
                                if (flags == MDB_CURRENT)
                                        goto current;
                                dcmp = mc->mc_dbx->md_dcmp;
-#if UINT_MAX < SIZE_MAX
-                               if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
+#if UINT_MAX < SIZE_MAX || defined(MDB_VL32)
+                               if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(mdb_size_t))
                                        dcmp = mdb_cmp_clong;
 #endif
                                /* does data match? */
                                if (!dcmp(data, &olddata)) {
-                                       if (flags & MDB_NODUPDATA)
+                                       if (flags & (MDB_NODUPDATA|MDB_APPENDDUP))
                                                return MDB_KEYEXIST;
                                        /* overwrite it */
                                        goto current;
@@ -6673,7 +7426,7 @@ current:
                        int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
 
                        memcpy(&pg, olddata.mv_data, sizeof(pg));
-                       if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
+                       if ((rc2 = mdb_page_get(mc, pg, &omp, &level)) != 0)
                                return rc2;
                        ovpages = omp->mp_pages;
 
@@ -6702,6 +7455,7 @@ current:
                                                return ENOMEM;
                                        id2.mid = pg;
                                        id2.mptr = np;
+                                       /* Note - this page is already counted in parent's dirty_room */
                                        rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
                                        mdb_cassert(mc, rc2 == 0);
                                        if (!(flags & MDB_RESERVE)) {
@@ -6758,7 +7512,7 @@ new_sub:
        } else {
                /* There is room already in this leaf page. */
                rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
-               if (rc == 0 && insert_key) {
+               if (rc == 0) {
                        /* Adjust other cursors pointing to mp */
                        MDB_cursor *m2, *m3;
                        MDB_dbi dbi = mc->mc_dbi;
@@ -6770,10 +7524,15 @@ new_sub:
                                        m3 = &m2->mc_xcursor->mx_cursor;
                                else
                                        m3 = m2;
-                               if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
-                               if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
+                               if (m3 == mc || m3->mc_snum < mc->mc_snum || m3->mc_pg[i] != mp) continue;
+                               if (m3->mc_ki[i] >= mc->mc_ki[i] && insert_key) {
                                        m3->mc_ki[i]++;
                                }
+                               if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
+                                       MDB_node *n2 = NODEPTR(mp, m3->mc_ki[i]);
+                                       if ((n2->mn_flags & (F_SUBDATA|F_DUPDATA)) == F_DUPDATA)
+                                               m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
+                               }
                        }
                }
        }
@@ -6786,7 +7545,7 @@ new_sub:
                 */
                if (do_sub) {
                        int xflags, new_dupdata;
-                       size_t ecount;
+                       mdb_size_t ecount;
 put_sub:
                        xdata.mv_size = 0;
                        xdata.mv_data = "";
@@ -6815,6 +7574,7 @@ put_sub:
                                MDB_xcursor *mx = mc->mc_xcursor;
                                unsigned i = mc->mc_top;
                                MDB_page *mp = mc->mc_pg[i];
+                               int nkeys = NUMKEYS(mp);
 
                                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;
@@ -6822,9 +7582,9 @@ put_sub:
                                        if (m2->mc_pg[i] == mp) {
                                                if (m2->mc_ki[i] == mc->mc_ki[i]) {
                                                        mdb_xcursor_init2(m2, mx, new_dupdata);
-                                               } else if (!insert_key) {
+                                               } else if (!insert_key && m2->mc_ki[i] < nkeys) {
                                                        MDB_node *n2 = NODEPTR(mp, m2->mc_ki[i]);
-                                                       if (!(n2->mn_flags & F_SUBDATA))
+                                                       if ((n2->mn_flags & (F_SUBDATA|F_DUPDATA)) == F_DUPDATA)
                                                                m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
                                                }
                                        }
@@ -6905,6 +7665,7 @@ mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
                if (flags & MDB_NODUPDATA) {
                        /* mdb_cursor_del0() will subtract the final entry */
                        mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
+                       mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
                } else {
                        if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
                                mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
@@ -6940,8 +7701,9 @@ mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
                                        }
                                }
                                mc->mc_db->md_entries--;
-                               mc->mc_flags |= C_DEL;
                                return rc;
+                       } else {
+                               mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
                        }
                        /* otherwise fall thru and delete the sub-DB */
                }
@@ -6965,7 +7727,7 @@ mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
                pgno_t pg;
 
                memcpy(&pg, NODEDATA(leaf), sizeof(pg));
-               if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
+               if ((rc = mdb_page_get(mc, pg, &omp, NULL)) ||
                        (rc = mdb_ovpage_free(mc, omp)))
                        goto fail;
        }
@@ -6994,7 +7756,7 @@ 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 %"Z"u, page size %u",
+       DPRINTF(("allocated new mpage %"Y"u, page size %u",
            np->mp_pgno, mc->mc_txn->mt_env->me_psize));
        np->mp_flags = flags | P_DIRTY;
        np->mp_lower = (PAGEHDRSZ-PAGEBASE);
@@ -7094,7 +7856,7 @@ mdb_node_add(MDB_cursor *mc, indx_t indx,
 
        mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
 
-       DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
+       DPRINTF(("add to %s %spage %"Y"u index %i, data size %"Z"u key size %"Z"u [%s]",
            IS_LEAF(mp) ? "leaf" : "branch",
                IS_SUBP(mp) ? "sub-" : "",
                mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
@@ -7135,7 +7897,7 @@ mdb_node_add(MDB_cursor *mc, indx_t indx,
                                goto full;
                        if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
                                return rc;
-                       DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
+                       DPRINTF(("allocated overflow page %"Y"u", ofp->mp_pgno));
                        flags |= F_BIGDATA;
                        goto update;
                } else {
@@ -7192,7 +7954,7 @@ update:
        return MDB_SUCCESS;
 
 full:
-       DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
+       DPRINTF(("not enough room in page %"Y"u, got %u ptrs",
                mdb_dbg_pgno(mp), NUMKEYS(mp)));
        DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
        DPRINTF(("node size = %"Z"u", node_size));
@@ -7215,7 +7977,7 @@ mdb_node_del(MDB_cursor *mc, int ksize)
        MDB_node        *node;
        char            *base;
 
-       DPRINTF(("delete node %u on %s page %"Z"u", indx,
+       DPRINTF(("delete node %u on %s page %"Y"u", indx,
            IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
        numkeys = NUMKEYS(mp);
        mdb_cassert(mc, indx < numkeys);
@@ -7324,7 +8086,10 @@ mdb_xcursor_init0(MDB_cursor *mc)
        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;
+#ifdef MDB_VL32
+       mx->mx_cursor.mc_ovpg = 0;
+#endif
+       mx->mx_cursor.mc_flags = C_SUB | (mc->mc_flags & (C_ORIG_RDONLY|C_WRITEMAP));
        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;
@@ -7343,12 +8108,12 @@ mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
 {
        MDB_xcursor *mx = mc->mc_xcursor;
 
+       mx->mx_cursor.mc_flags &= C_SUB|C_ORIG_RDONLY|C_WRITEMAP;
        if (node->mn_flags & F_SUBDATA) {
                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);
                mx->mx_db.md_pad = 0;
@@ -7361,7 +8126,7 @@ mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
                COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
                mx->mx_cursor.mc_snum = 1;
                mx->mx_cursor.mc_top = 0;
-               mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
+               mx->mx_cursor.mc_flags |= C_INITIALIZED;
                mx->mx_cursor.mc_pg[0] = fp;
                mx->mx_cursor.mc_ki[0] = 0;
                if (mc->mc_db->md_flags & MDB_DUPFIXED) {
@@ -7371,11 +8136,11 @@ mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
                                mx->mx_db.md_flags |= MDB_INTEGERKEY;
                }
        }
-       DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
+       DPRINTF(("Sub-db -%u root page %"Y"u", mx->mx_cursor.mc_dbi,
                mx->mx_db.md_root));
        mx->mx_dbflag = DB_VALID|DB_USRVALID|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))
+#if UINT_MAX < SIZE_MAX || defined(MDB_VL32)
+       if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(mdb_size_t))
                mx->mx_dbx.md_cmp = mdb_cmp_clong;
 #endif
 }
@@ -7408,7 +8173,7 @@ mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int new_dupdata)
        }
        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,
+       DPRINTF(("Sub-db -%u root page %"Y"u", mx->mx_cursor.mc_dbi,
                mx->mx_db.md_root));
 }
 
@@ -7427,7 +8192,10 @@ mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
        mc->mc_top = 0;
        mc->mc_pg[0] = 0;
        mc->mc_ki[0] = 0;
-       mc->mc_flags = 0;
+#ifdef MDB_VL32
+       mc->mc_ovpg = 0;
+#endif
+       mc->mc_flags = txn->mt_flags & (C_ORIG_RDONLY|C_WRITEMAP);
        if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
                mdb_tassert(txn, mx != NULL);
                mc->mc_xcursor = mx;
@@ -7492,7 +8260,7 @@ mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
 
 /* Return the count of duplicate data items for the current key */
 int
-mdb_cursor_count(MDB_cursor *mc, size_t *countp)
+mdb_cursor_count(MDB_cursor *mc, mdb_size_t *countp)
 {
        MDB_node        *leaf;
 
@@ -7577,7 +8345,7 @@ mdb_update_key(MDB_cursor *mc, MDB_val *key)
                char kbuf2[DKBUF_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 %"Z"u",
+               DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Y"u",
                        indx, ptr,
                        mdb_dkey(&k2, kbuf2),
                        DKEY(key),
@@ -7628,10 +8396,26 @@ mdb_update_key(MDB_cursor *mc, MDB_val *key)
 static void
 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
 
+/** Perform \b act while tracking temporary cursor \b mn */
+#define WITH_CURSOR_TRACKING(mn, act) do { \
+       MDB_cursor dummy, *tracked, **tp = &(mn).mc_txn->mt_cursors[mn.mc_dbi]; \
+       if ((mn).mc_flags & C_SUB) { \
+               dummy.mc_flags =  C_INITIALIZED; \
+               dummy.mc_xcursor = (MDB_xcursor *)&(mn);        \
+               tracked = &dummy; \
+       } else { \
+               tracked = &(mn); \
+       } \
+       tracked->mc_next = *tp; \
+       *tp = tracked; \
+       { act; } \
+       *tp = tracked->mc_next; \
+} while (0)
+
 /** Move a node from csrc to cdst.
  */
 static int
-mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
+mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft)
 {
        MDB_node                *srcnode;
        MDB_val          key, data;
@@ -7683,6 +8467,7 @@ mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
                data.mv_size = NODEDSZ(srcnode);
                data.mv_data = NODEDATA(srcnode);
        }
+       mn.mc_xcursor = NULL;
        if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
                unsigned int snum = cdst->mc_snum;
                MDB_node *s2;
@@ -7708,7 +8493,7 @@ mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
                        return rc;
        }
 
-       DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
+       DPRINTF(("moving %s node %u [%s] on page %"Y"u to node %u on page %"Y"u",
            IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
            csrc->mc_ki[csrc->mc_top],
                DKEY(&key),
@@ -7733,13 +8518,15 @@ mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
 
                mps = csrc->mc_pg[csrc->mc_top];
                /* If we're adding on the left, bump others up */
-               if (!cdst->mc_ki[csrc->mc_top]) {
+               if (fromleft) {
                        mpd = 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->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
+                                       continue;
                                if (m3 != cdst &&
                                        m3->mc_pg[csrc->mc_top] == mpd &&
                                        m3->mc_ki[csrc->mc_top] >= cdst->mc_ki[csrc->mc_top]) {
@@ -7752,6 +8539,12 @@ mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
                                        m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
                                        m3->mc_ki[csrc->mc_top-1]++;
                                }
+                               if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
+                                       IS_LEAF(mps)) {
+                                       MDB_node *node = NODEPTR(m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
+                                       if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
+                                               m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
+                               }
                        }
                } else
                /* Adding on the right, bump others down */
@@ -7762,6 +8555,8 @@ mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
                                else
                                        m3 = m2;
                                if (m3 == csrc) continue;
+                               if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
+                                       continue;
                                if (m3->mc_pg[csrc->mc_top] == mps) {
                                        if (!m3->mc_ki[csrc->mc_top]) {
                                                m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
@@ -7770,6 +8565,12 @@ mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
                                        } else {
                                                m3->mc_ki[csrc->mc_top]--;
                                        }
+                                       if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
+                                               IS_LEAF(mps)) {
+                                               MDB_node *node = NODEPTR(m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
+                                               if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
+                                                       m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
+                                       }
                                }
                        }
                }
@@ -7786,12 +8587,15 @@ 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 %"Z"u to [%s]",
+                       DPRINTF(("update separator for source page %"Y"u to [%s]",
                                csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
                        mdb_cursor_copy(csrc, &mn);
                        mn.mc_snum--;
                        mn.mc_top--;
-                       if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
+                       /* We want mdb_rebalance to find mn when doing fixups */
+                       WITH_CURSOR_TRACKING(mn,
+                               rc = mdb_update_key(&mn, &key));
+                       if (rc)
                                return rc;
                }
                if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
@@ -7814,12 +8618,15 @@ 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 %"Z"u to [%s]",
+                       DPRINTF(("update separator for destination page %"Y"u to [%s]",
                                cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
                        mdb_cursor_copy(cdst, &mn);
                        mn.mc_snum--;
                        mn.mc_top--;
-                       if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
+                       /* We want mdb_rebalance to find mn when doing fixups */
+                       WITH_CURSOR_TRACKING(mn,
+                               rc = mdb_update_key(&mn, &key));
+                       if (rc)
                                return rc;
                }
                if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
@@ -7857,7 +8664,7 @@ mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
        psrc = csrc->mc_pg[csrc->mc_top];
        pdst = cdst->mc_pg[cdst->mc_top];
 
-       DPRINTF(("merging page %"Z"u into %"Z"u", psrc->mp_pgno, pdst->mp_pgno));
+       DPRINTF(("merging page %"Y"u into %"Y"u", psrc->mp_pgno, pdst->mp_pgno));
 
        mdb_cassert(csrc, csrc->mc_snum > 1);   /* can't merge root page */
        mdb_cassert(csrc, cdst->mc_snum > 1);
@@ -7888,6 +8695,7 @@ mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
                                MDB_cursor mn;
                                MDB_node *s2;
                                mdb_cursor_copy(csrc, &mn);
+                               mn.mc_xcursor = NULL;
                                /* must find the lowest key below src */
                                rc = mdb_page_search_lowest(&mn);
                                if (rc)
@@ -7913,7 +8721,7 @@ mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
                }
        }
 
-       DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
+       DPRINTF(("dst page %"Y"u now has %u keys (%.1f%% filled)",
            pdst->mp_pgno, NUMKEYS(pdst),
                (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
 
@@ -7959,6 +8767,15 @@ mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
                                m3->mc_pg[top] = pdst;
                                m3->mc_ki[top] += nkeys;
                                m3->mc_ki[top-1] = cdst->mc_ki[top-1];
+                       } else if (m3->mc_pg[top-1] == csrc->mc_pg[top-1] &&
+                               m3->mc_ki[top-1] > csrc->mc_ki[top-1]) {
+                               m3->mc_ki[top-1]--;
+                       }
+                       if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
+                               IS_LEAF(psrc)) {
+                               MDB_node *node = NODEPTR(m3->mc_pg[top], m3->mc_ki[top]);
+                               if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
+                                       m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
                        }
                }
        }
@@ -7992,6 +8809,9 @@ mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
        cdst->mc_snum = csrc->mc_snum;
        cdst->mc_top = csrc->mc_top;
        cdst->mc_flags = csrc->mc_flags;
+#ifdef MDB_VL32
+       cdst->mc_ovpg = csrc->mc_ovpg;
+#endif
 
        for (i=0; i<csrc->mc_snum; i++) {
                cdst->mc_pg[i] = csrc->mc_pg[i];
@@ -8008,7 +8828,7 @@ static int
 mdb_rebalance(MDB_cursor *mc)
 {
        MDB_node        *node;
-       int rc;
+       int rc, fromleft;
        unsigned int ptop, minkeys, thresh;
        MDB_cursor      mn;
        indx_t oldki;
@@ -8020,14 +8840,14 @@ mdb_rebalance(MDB_cursor *mc)
                minkeys = 1;
                thresh = FILL_THRESHOLD;
        }
-       DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
+       DPRINTF(("rebalancing %s page %"Y"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]) >= thresh &&
                NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
-               DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
+               DPRINTF(("no need to rebalance page %"Y"u, above fill threshold",
                    mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
                return MDB_SUCCESS;
        }
@@ -8059,7 +8879,8 @@ mdb_rebalance(MDB_cursor *mc)
                                                m3 = &m2->mc_xcursor->mx_cursor;
                                        else
                                                m3 = m2;
-                                       if (m3->mc_snum < mc->mc_snum) continue;
+                                       if (!(m3->mc_flags & C_INITIALIZED) || (m3->mc_snum < mc->mc_snum))
+                                               continue;
                                        if (m3->mc_pg[0] == mp) {
                                                m3->mc_snum = 0;
                                                m3->mc_top = 0;
@@ -8074,7 +8895,7 @@ mdb_rebalance(MDB_cursor *mc)
                        if (rc)
                                return rc;
                        mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
-                       rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
+                       rc = mdb_page_get(mc, mc->mc_db->md_root, &mc->mc_pg[0], NULL);
                        if (rc)
                                return rc;
                        mc->mc_db->md_depth--;
@@ -8095,6 +8916,8 @@ mdb_rebalance(MDB_cursor *mc)
                                        else
                                                m3 = m2;
                                        if (m3 == mc) continue;
+                                       if (!(m3->mc_flags & C_INITIALIZED))
+                                               continue;
                                        if (m3->mc_pg[0] == mp) {
                                                for (i=0; i<mc->mc_db->md_depth; i++) {
                                                        m3->mc_pg[i] = m3->mc_pg[i+1];
@@ -8133,25 +8956,27 @@ mdb_rebalance(MDB_cursor *mc)
                DPUTS("reading right neighbor");
                mn.mc_ki[ptop]++;
                node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
-               rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
+               rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
                if (rc)
                        return rc;
                mn.mc_ki[mn.mc_top] = 0;
                mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
+               fromleft = 0;
        } else {
                /* There is at least one neighbor to the left.
                 */
                DPUTS("reading left neighbor");
                mn.mc_ki[ptop]--;
                node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
-               rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
+               rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
                if (rc)
                        return rc;
                mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
                mc->mc_ki[mc->mc_top] = 0;
+               fromleft = 1;
        }
 
-       DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
+       DPRINTF(("found neighbor page %"Y"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));
 
@@ -8160,32 +8985,20 @@ mdb_rebalance(MDB_cursor *mc)
         * (A branch page must never have less than 2 keys.)
         */
        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[mc->mc_top]) {
+               rc = mdb_node_move(&mn, mc, fromleft);
+               if (fromleft) {
                        /* if we inserted on left, bump position up */
                        oldki++;
                }
        } else {
-               if (mc->mc_ki[ptop] == 0) {
+               if (!fromleft) {
                        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;
+                       WITH_CURSOR_TRACKING(mn,
+                               rc = mdb_page_merge(mc, &mn));
                        mdb_cursor_copy(&mn, mc);
                }
                mc->mc_flags &= ~C_EOF;
@@ -8218,12 +9031,17 @@ mdb_cursor_del0(MDB_cursor *mc)
                        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) {
+                               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;
+                                       if (mc->mc_db->md_flags & MDB_DUPSORT)
+                                               m3->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
+                               } else if (m3->mc_ki[mc->mc_top] > ki) {
+                                       m3->mc_ki[mc->mc_top]--;
+                               }
+                               if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
+                                       MDB_node *node = NODEPTR(m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
+                                       if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
+                                               m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
                                }
                        }
                }
@@ -8360,7 +9178,7 @@ mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno
        newindx = mc->mc_ki[mc->mc_top];
        nkeys = NUMKEYS(mp);
 
-       DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
+       DPRINTF(("-----> splitting %s page %"Y"u and adding [%s] at index %i/%i",
            IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
            DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
 
@@ -8368,18 +9186,25 @@ mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno
        if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
                return rc;
        rp->mp_pad = mp->mp_pad;
-       DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
+       DPRINTF(("new right sibling: page %"Y"u", rp->mp_pgno));
 
-       if (mc->mc_snum < 2) {
+       /* Usually when splitting the root page, the cursor
+        * height is 1. But when called from mdb_update_key,
+        * the cursor height may be greater because it walks
+        * up the stack while finding the branch slot to update.
+        */
+       if (mc->mc_top < 1) {
                if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
                        goto done;
                /* shift current top to make room for new parent */
-               mc->mc_pg[1] = mc->mc_pg[0];
-               mc->mc_ki[1] = mc->mc_ki[0];
+               for (i=mc->mc_snum; i>0; i--) {
+                       mc->mc_pg[i] = mc->mc_pg[i-1];
+                       mc->mc_ki[i] = mc->mc_ki[i-1];
+               }
                mc->mc_pg[0] = pp;
                mc->mc_ki[0] = 0;
                mc->mc_db->md_root = pp->mp_pgno;
-               DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
+               DPRINTF(("root split! new root = %"Y"u", pp->mp_pgno));
                new_root = mc->mc_db->md_depth++;
 
                /* Add left (implicit) pointer. */
@@ -8391,16 +9216,16 @@ mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno
                        mc->mc_db->md_depth--;
                        goto done;
                }
-               mc->mc_snum = 2;
-               mc->mc_top = 1;
+               mc->mc_snum++;
+               mc->mc_top++;
                ptop = 0;
        } else {
                ptop = mc->mc_top-1;
-               DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
+               DPRINTF(("parent branch page is %"Y"u", mc->mc_pg[ptop]->mp_pgno));
        }
 
-       mc->mc_flags |= C_SPLITTING;
        mdb_cursor_copy(mc, &mn);
+       mn.mc_xcursor = NULL;
        mn.mc_pg[mn.mc_top] = rp;
        mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
 
@@ -8450,8 +9275,6 @@ mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno
                                rp->mp_lower += sizeof(indx_t);
                                rp->mp_upper -= ksize - sizeof(indx_t);
                                mc->mc_ki[mc->mc_top] = x;
-                               mc->mc_pg[mc->mc_top] = rp;
-                               mc->mc_ki[ptop]++;
                        }
                } else {
                        int psize, nsize, k;
@@ -8544,21 +9367,18 @@ mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno
        /* Copy separator key to the parent.
         */
        if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
+               int snum = mc->mc_snum;
                mn.mc_snum--;
                mn.mc_top--;
                did_split = 1;
-               rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
+               /* We want other splits to find mn when doing fixups */
+               WITH_CURSOR_TRACKING(mn,
+                       rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0));
                if (rc)
                        goto done;
 
                /* root split? */
-               if (mn.mc_snum == mc->mc_snum) {
-                       mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
-                       mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
-                       mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
-                       mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
-                       mc->mc_snum++;
-                       mc->mc_top++;
+               if (mc->mc_snum > snum) {
                        ptop++;
                }
                /* Right page might now have changed parent.
@@ -8584,7 +9404,6 @@ mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno
                rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
                mn.mc_top++;
        }
-       mc->mc_flags ^= C_SPLITTING;
        if (rc != MDB_SUCCESS) {
                goto done;
        }
@@ -8654,11 +9473,6 @@ mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno
                /* reset back to original page */
                if (newindx < split_indx) {
                        mc->mc_pg[mc->mc_top] = mp;
-                       if (nflags & MDB_RESERVE) {
-                               node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
-                               if (!(node->mn_flags & F_BIGDATA))
-                                       newdata->mv_data = NODEDATA(node);
-                       }
                } else {
                        mc->mc_pg[mc->mc_top] = rp;
                        mc->mc_ki[ptop]++;
@@ -8672,13 +9486,32 @@ mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno
                                }
                        }
                }
+               if (nflags & MDB_RESERVE) {
+                       node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
+                       if (!(node->mn_flags & F_BIGDATA))
+                               newdata->mv_data = NODEDATA(node);
+               }
+       } else {
+               if (newindx >= split_indx) {
+                       mc->mc_pg[mc->mc_top] = rp;
+                       mc->mc_ki[ptop]++;
+                       /* Make sure mc_ki is still valid.
+                        */
+                       if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
+                               mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
+                               for (i=0; i<=ptop; i++) {
+                                       mc->mc_pg[i] = mn.mc_pg[i];
+                                       mc->mc_ki[i] = mn.mc_ki[i];
+                               }
+                       }
+               }
        }
 
        {
                /* Adjust other cursors pointing to mp */
                MDB_cursor *m2, *m3;
                MDB_dbi dbi = mc->mc_dbi;
-               int fixup = NUMKEYS(mp);
+               nkeys = NUMKEYS(mp);
 
                for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
                        if (mc->mc_flags & C_SUB)
@@ -8689,16 +9522,17 @@ mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno
                                continue;
                        if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
                                continue;
-                       if (m3->mc_flags & C_SPLITTING)
-                               continue;
                        if (new_root) {
                                int k;
+                               /* sub cursors may be on different DB */
+                               if (m3->mc_pg[0] != mp)
+                                       continue;
                                /* root split */
                                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];
                                }
-                               if (m3->mc_ki[0] >= split_indx) {
+                               if (m3->mc_ki[0] >= nkeys) {
                                        m3->mc_ki[0] = 1;
                                } else {
                                        m3->mc_ki[0] = 0;
@@ -8710,15 +9544,24 @@ mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno
                        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) {
+                               if (m3->mc_ki[mc->mc_top] >= nkeys) {
                                        m3->mc_pg[mc->mc_top] = rp;
-                                       m3->mc_ki[mc->mc_top] -= fixup;
-                                       m3->mc_ki[ptop] = mn.mc_ki[ptop];
+                                       m3->mc_ki[mc->mc_top] -= nkeys;
+                                       for (i=0; i<mc->mc_top; i++) {
+                                               m3->mc_ki[i] = mn.mc_ki[i];
+                                               m3->mc_pg[i] = mn.mc_pg[i];
+                                       }
                                }
                        } 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]++;
                        }
+                       if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
+                               IS_LEAF(mp)) {
+                               MDB_node *node = NODEPTR(m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
+                               if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
+                                       m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
+                       }
                }
        }
        DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
@@ -8737,6 +9580,7 @@ mdb_put(MDB_txn *txn, MDB_dbi dbi,
 {
        MDB_cursor mc;
        MDB_xcursor mx;
+       int rc;
 
        if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
                return EINVAL;
@@ -8748,7 +9592,11 @@ mdb_put(MDB_txn *txn, MDB_dbi dbi,
                return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
 
        mdb_cursor_init(&mc, txn, dbi, &mx);
-       return mdb_cursor_put(&mc, key, data, flags);
+       mc.mc_next = txn->mt_cursors[dbi];
+       txn->mt_cursors[dbi] = &mc;
+       rc = mdb_cursor_put(&mc, key, data, flags);
+       txn->mt_cursors[dbi] = mc.mc_next;
+       return rc;
 }
 
 #ifndef MDB_WBUF
@@ -8862,7 +9710,6 @@ static int ESECT
 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
 {
        MDB_cursor mc;
-       MDB_txn *txn = my->mc_txn;
        MDB_node *ni;
        MDB_page *mo, *mp, *leaf;
        char *buf, *ptr;
@@ -8875,9 +9722,9 @@ mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
 
        mc.mc_snum = 1;
        mc.mc_top = 0;
-       mc.mc_txn = txn;
+       mc.mc_txn = my->mc_txn;
 
-       rc = mdb_page_get(my->mc_txn, *pg, &mc.mc_pg[0], NULL);
+       rc = mdb_page_get(&mc, *pg, &mc.mc_pg[0], NULL);
        if (rc)
                return rc;
        rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
@@ -8921,7 +9768,7 @@ mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
                                                }
 
                                                memcpy(&pg, NODEDATA(ni), sizeof(pg));
-                                               rc = mdb_page_get(txn, pg, &omp, NULL);
+                                               rc = mdb_page_get(&mc, pg, &omp, NULL);
                                                if (rc)
                                                        goto done;
                                                if (my->mc_wlen[toggle] >= MDB_WBUF) {
@@ -8972,7 +9819,7 @@ mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
 again:
                                ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
                                pg = NODEPGNO(ni);
-                               rc = mdb_page_get(txn, pg, &mp, NULL);
+                               rc = mdb_page_get(&mc, pg, &mp, NULL);
                                if (rc)
                                        goto done;
                                mc.mc_top++;
@@ -9137,7 +9984,7 @@ mdb_env_copyfd0(MDB_env *env, HANDLE fd)
        MDB_txn *txn = NULL;
        mdb_mutexref_t wmutex = NULL;
        int rc;
-       size_t wsize;
+       mdb_size_t wsize, w3;
        char *ptr;
 #ifdef _WIN32
        DWORD len, w2;
@@ -9196,15 +10043,15 @@ mdb_env_copyfd0(MDB_env *env, HANDLE fd)
        if (rc)
                goto leave;
 
-       w2 = txn->mt_next_pgno * env->me_psize;
+       w3 = txn->mt_next_pgno * env->me_psize;
        {
-               size_t fsize = 0;
+               mdb_size_t fsize = 0;
                if ((rc = mdb_fsize(env->me_fd, &fsize)))
                        goto leave;
-               if (w2 > fsize)
-                       w2 = fsize;
+               if (w3 > fsize)
+                       w3 = fsize;
        }
-       wsize = w2 - wsize;
+       wsize = w3 - wsize;
        while (wsize > 0) {
                if (wsize > MAX_WRITE)
                        w2 = MAX_WRITE;
@@ -9251,6 +10098,9 @@ mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
        int rc, len;
        char *lpath;
        HANDLE newfd = INVALID_HANDLE_VALUE;
+#ifdef _WIN32
+       wchar_t *wpath;
+#endif
 
        if (env->me_flags & MDB_NOSUBDIR) {
                lpath = (char *)path;
@@ -9268,8 +10118,12 @@ mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
         * already in the OS cache.
         */
 #ifdef _WIN32
-       newfd = CreateFileA(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
+       rc = utf8_to_utf16(lpath, -1, &wpath, NULL);
+       if (rc)
+               goto leave;
+       newfd = CreateFileW(wpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
                                FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
+       free(wpath);
 #else
        newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
 #endif
@@ -9461,6 +10315,7 @@ int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *db
        MDB_db dummy;
        int rc, dbflag, exact;
        unsigned int unused = 0, seq;
+       char *namedup;
        size_t len;
 
        if (flags & ~VALID_FLAGS)
@@ -9522,8 +10377,16 @@ int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *db
                MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
                if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
                        return MDB_INCOMPATIBLE;
-       } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
-               /* Create if requested */
+       } else if (! (rc == MDB_NOTFOUND && (flags & MDB_CREATE))) {
+               return rc;
+       }
+
+       /* Done here so we cannot fail after creating a new DB */
+       if ((namedup = strdup(name)) == NULL)
+               return ENOMEM;
+
+       if (rc) {
+               /* MDB_NOTFOUND and MDB_CREATE: Create new DB */
                data.mv_size = sizeof(MDB_db);
                data.mv_data = &dummy;
                memset(&dummy, 0, sizeof(dummy));
@@ -9533,10 +10396,12 @@ int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *db
                dbflag |= DB_DIRTY;
        }
 
-       /* OK, got info, add to table */
-       if (rc == MDB_SUCCESS) {
+       if (rc) {
+               free(namedup);
+       } else {
+               /* Got info, register DBI in this txn */
                unsigned int slot = unused ? unused : txn->mt_numdbs;
-               txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
+               txn->mt_dbxs[slot].md_name.mv_data = namedup;
                txn->mt_dbxs[slot].md_name.mv_size = len;
                txn->mt_dbxs[slot].md_rel = NULL;
                txn->mt_dbflags[slot] = dbflag;
@@ -9624,6 +10489,11 @@ mdb_drop0(MDB_cursor *mc, int subs)
                        mdb_cursor_pop(mc);
 
                mdb_cursor_copy(mc, &mx);
+#ifdef MDB_VL32
+               /* bump refcount for mx's pages */
+               for (i=0; i<mc->mc_snum; i++)
+                       mdb_page_get(&mx, mc->mc_pg[i]->mp_pgno, &mx.mc_pg[i], NULL);
+#endif
                while (mc->mc_snum > 0) {
                        MDB_page *mp = mc->mc_pg[mc->mc_top];
                        unsigned n = NUMKEYS(mp);
@@ -9634,7 +10504,7 @@ mdb_drop0(MDB_cursor *mc, int subs)
                                                MDB_page *omp;
                                                pgno_t pg;
                                                memcpy(&pg, NODEDATA(ni), sizeof(pg));
-                                               rc = mdb_page_get(txn, pg, &omp, NULL);
+                                               rc = mdb_page_get(mc, pg, &omp, NULL);
                                                if (rc != 0)
                                                        goto done;
                                                mdb_cassert(mc, IS_OVERFLOW(omp));
@@ -9683,9 +10553,14 @@ mdb_drop0(MDB_cursor *mc, int subs)
 done:
                if (rc)
                        txn->mt_flags |= MDB_TXN_ERROR;
+#ifdef MDB_VL32
+               /* drop refcount for mx's pages */
+               mdb_cursor_unref(&mx);
+#endif
        } else if (rc == MDB_NOTFOUND) {
                rc = MDB_SUCCESS;
        }
+       mc->mc_flags &= ~C_INITIALIZED;
        return rc;
 }
 
@@ -9801,7 +10676,7 @@ mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
                if (mr[i].mr_pid) {
                        txnid_t txnid = mr[i].mr_txnid;
                        sprintf(buf, txnid == (txnid_t)-1 ?
-                               "%10d %"Z"x -\n" : "%10d %"Z"x %"Z"u\n",
+                               "%10d %"Z"x -\n" : "%10d %"Z"x %"Y"u\n",
                                (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
                        if (first) {
                                first = 0;
@@ -9906,7 +10781,7 @@ mdb_reader_check0(MDB_env *env, int rlocked, int *dead)
                                        }
                                        for (; j<rdrs; j++)
                                                        if (mr[j].mr_pid == pid) {
-                                                               DPRINTF(("clear stale reader pid %u txn %"Z"d",
+                                                               DPRINTF(("clear stale reader pid %u txn %"Y"d",
                                                                        (unsigned) pid, mr[j].mr_txnid));
                                                                mr[j].mr_pid = 0;
                                                                count++;
@@ -9974,3 +10849,24 @@ mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc)
 }
 #endif /* MDB_ROBUST_SUPPORTED */
 /** @} */
+
+#if defined(_WIN32)
+static int utf8_to_utf16(const char *src, int srcsize, wchar_t **dst, int *dstsize)
+{
+       int need;
+       wchar_t *result;
+       need = MultiByteToWideChar(CP_UTF8, 0, src, srcsize, NULL, 0);
+       if (need == 0xFFFD)
+               return EILSEQ;
+       if (need == 0)
+               return EINVAL;
+       result = malloc(sizeof(wchar_t) * need);
+       if (!result)
+               return ENOMEM;
+       MultiByteToWideChar(CP_UTF8, 0, src, srcsize, result, need);
+       if (dstsize)
+               *dstsize = need;
+       *dst = result;
+       return 0;
+}
+#endif /* defined(_WIN32) */