]> git.sur5r.net Git - openldap/blobdiff - libraries/liblmdb/mdb.c
Add MDB_NOTLS envflag.
[openldap] / libraries / liblmdb / mdb.c
index 7866e89cb65dbaafde31981d514614e9178ff2b7..71575d604bf9d08239b2e1b9af18bc3fd57fc8c2 100644 (file)
@@ -286,6 +286,8 @@ typedef MDB_ID      txnid_t;
 #endif
 
 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
+# undef  MDB_DEBUG
+# define MDB_DEBUG     0
 # define DPRINTF       (void)  /* Vararg macros may be unsupported */
 #elif MDB_DEBUG
 static int mdb_debug;
@@ -404,6 +406,8 @@ typedef uint16_t     indx_t;
  *     slot's address is saved in thread-specific data so that subsequent read
  *     transactions started by the same thread need no further locking to proceed.
  *
+ *     If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
+ *
  *     No reader table is used if the database is on a read-only filesystem.
  *
  *     Since the database uses multi-version concurrency control, readers don't
@@ -743,6 +747,11 @@ typedef struct MDB_db {
        pgno_t          md_root;                /**< the root page of this tree */
 } MDB_db;
 
+       /** mdb_dbi_open flags */
+#define PERSISTENT_FLAGS       0x7fff
+#define VALID_FLAGS    (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
+       MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
+
        /** Handle for the DB used to track free pages. */
 #define        FREE_DBI        0
        /** Handle for the default DB. */
@@ -822,6 +831,9 @@ struct MDB_txn {
  */
 #define DB_DIRTY       0x01            /**< DB was written in this txn */
 #define DB_STALE       0x02            /**< DB record is older than txnID */
+#define DB_NEW         0x04            /**< DB handle opened in this txn */
+#define DB_VALID       0x08            /**< DB handle is valid */
+#define MDB_VALID      0x8000          /**< DB handle is valid, for me_dbflags */
 /** @} */
        /** In write txns, array of cursors for each DB */
        MDB_cursor      **mt_cursors;
@@ -924,10 +936,10 @@ struct MDB_env {
        HANDLE          me_mfd;                 /**< just for writing the meta pages */
        /** Failed to update the meta page. Probably an I/O error. */
 #define        MDB_FATAL_ERROR 0x80000000U
-       /** Read-only Filesystem. Allow read access, no locking. */
-#define        MDB_ROFS        0x40000000U
        /** Some fields are initialized. */
 #define        MDB_ENV_ACTIVE  0x20000000U
+       /** me_txkey is set */
+#define        MDB_ENV_TXKEY   0x10000000U
        uint32_t        me_flags;               /**< @ref mdb_env */
        unsigned int    me_psize;       /**< size of a page, from #GET_PAGESIZE */
        unsigned int    me_maxreaders;  /**< size of the reader table */
@@ -953,8 +965,8 @@ struct MDB_env {
        MDB_page        *me_dpages;             /**< list of malloc'd blocks for re-use */
        /** IDL of pages that became unused in a write txn */
        MDB_IDL         me_free_pgs;
-       /** ID2L of pages that were written during a write txn */
-       MDB_ID2         me_dirty_list[MDB_IDL_UM_SIZE];
+       /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
+       MDB_ID2L        me_dirty_list;
        /** Max number of freelist items that can fit in a single overflow page */
        unsigned int    me_maxfree_1pg;
        /** Max size of a node on a page */
@@ -1073,6 +1085,7 @@ static char *const mdb_errstr[] = {
        "MDB_PAGE_FULL: Internal error - page has no more space",
        "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
        "MDB_INCOMPATIBLE: Database flags changed or would change",
+       "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
 };
 
 char *
@@ -1768,6 +1781,7 @@ mdb_txn_renew0(MDB_txn *txn)
 {
        MDB_env *env = txn->mt_env;
        unsigned int i;
+       uint16_t x;
        int rc;
 
        /* Setup db info */
@@ -1775,13 +1789,17 @@ mdb_txn_renew0(MDB_txn *txn)
        txn->mt_dbxs = env->me_dbxs;    /* mostly static anyway */
 
        if (txn->mt_flags & MDB_TXN_RDONLY) {
-               if (env->me_flags & MDB_ROFS) {
+               if (!env->me_txns) {
                        i = mdb_env_pick_meta(env);
                        txn->mt_txnid = env->me_metas[i]->mm_txnid;
                        txn->mt_u.reader = NULL;
                } else {
-                       MDB_reader *r = pthread_getspecific(env->me_txkey);
-                       if (!r) {
+                       MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
+                               pthread_getspecific(env->me_txkey);
+                       if (r) {
+                               if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
+                                       return MDB_BAD_RSLOT;
+                       } else {
                                pid_t pid = env->me_pid;
                                pthread_t tid = pthread_self();
 
@@ -1801,7 +1819,8 @@ mdb_txn_renew0(MDB_txn *txn)
                                env->me_numreaders = env->me_txns->mti_numreaders;
                                UNLOCK_MUTEX_R(env);
                                r = &env->me_txns->mti_readers[i];
-                               if ((rc = pthread_setspecific(env->me_txkey, r)) != 0) {
+                               if (!(env->me_flags & MDB_NOTLS) &&
+                                       (rc = pthread_setspecific(env->me_txkey, r)) != 0) {
                                        env->me_txns->mti_readers[i].mr_pid = 0;
                                        return rc;
                                }
@@ -1832,11 +1851,12 @@ mdb_txn_renew0(MDB_txn *txn)
 
        /* Copy the DB info and flags */
        memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
-       for (i=2; i<txn->mt_numdbs; i++)
-               txn->mt_dbs[i].md_flags = env->me_dbflags[i];
-       txn->mt_dbflags[0] = txn->mt_dbflags[1] = 0;
-       if (txn->mt_numdbs > 2)
-               memset(txn->mt_dbflags+2, DB_STALE, txn->mt_numdbs-2);
+       for (i=2; i<txn->mt_numdbs; i++) {
+               x = env->me_dbflags[i];
+               txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
+               txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_STALE : 0;
+       }
+       txn->mt_dbflags[0] = txn->mt_dbflags[1] = DB_VALID;
 
        if (env->me_maxpg < txn->mt_next_pgno) {
                mdb_txn_reset0(txn);
@@ -1851,7 +1871,7 @@ mdb_txn_renew(MDB_txn *txn)
 {
        int rc;
 
-       if (! (txn && (txn->mt_flags & MDB_TXN_RDONLY)))
+       if (!txn || txn->mt_numdbs || !(txn->mt_flags & MDB_TXN_RDONLY))
                return EINVAL;
 
        if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
@@ -1910,6 +1930,7 @@ mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
        txn->mt_env = env;
 
        if (parent) {
+               unsigned int i;
                txn->mt_free_pgs = mdb_midl_alloc();
                if (!txn->mt_free_pgs) {
                        free(txn);
@@ -1932,7 +1953,9 @@ mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
                txn->mt_numdbs = parent->mt_numdbs;
                txn->mt_dbxs = parent->mt_dbxs;
                memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
-               memcpy(txn->mt_dbflags, parent->mt_dbflags, txn->mt_numdbs);
+               /* Copy parent's mt_dbflags, but clear DB_NEW */
+               for (i=0; i<txn->mt_numdbs; i++)
+                       txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
                rc = 0;
                ntxn = (MDB_ntxn *)txn;
                ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
@@ -1965,19 +1988,34 @@ mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
 }
 
 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
+ * May be called twice for readonly txns: First reset it, then abort.
  * @param[in] txn the transaction handle to reset
  */
 static void
 mdb_txn_reset0(MDB_txn *txn)
 {
        MDB_env *env = txn->mt_env;
+       unsigned int i;
+
+       /* Close any DBI handles opened in this txn */
+       for (i=2; i<txn->mt_numdbs; i++) {
+               if (txn->mt_dbflags[i] & DB_NEW) {
+                       char *ptr = env->me_dbxs[i].md_name.mv_data;
+                       env->me_dbxs[i].md_name.mv_data = NULL;
+                       env->me_dbxs[i].md_name.mv_size = 0;
+                       free(ptr);
+               }
+       }
 
        if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
-               if (!(env->me_flags & MDB_ROFS))
+               if (txn->mt_u.reader) {
                        txn->mt_u.reader->mr_txnid = (txnid_t)-1;
+                       if (!(env->me_flags & MDB_NOTLS))
+                               txn->mt_u.reader = NULL; /* txn does not own reader */
+               }
+               txn->mt_numdbs = 0;     /* mark txn as reset, do not close DBs again */
        } else {
                MDB_page *dp;
-               unsigned int i;
 
                /* close(free) all cursors */
                for (i=0; i<txn->mt_numdbs; i++) {
@@ -2037,6 +2075,10 @@ mdb_txn_reset(MDB_txn *txn)
                txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
                (void *) txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
 
+       /* This call is only valid for read-only txns */
+       if (!(txn->mt_flags & MDB_TXN_RDONLY))
+               return;
+
        mdb_txn_reset0(txn);
 }
 
@@ -2054,6 +2096,10 @@ mdb_txn_abort(MDB_txn *txn)
                mdb_txn_abort(txn->mt_child);
 
        mdb_txn_reset0(txn);
+       /* Free reader slot tied to this txn (if MDB_NOTLS && writable FS) */
+       if ((txn->mt_flags & MDB_TXN_RDONLY) && txn->mt_u.reader)
+               txn->mt_u.reader->mr_pid = 0;
+
        free(txn);
 }
 
@@ -2081,13 +2127,14 @@ mdb_txn_commit(MDB_txn *txn)
        env = txn->mt_env;
 
        if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
-               if (txn->mt_numdbs > env->me_numdbs) {
-                       /* update the DB flags */
-                       MDB_dbi i;
-                       for (i = env->me_numdbs; i<txn->mt_numdbs; i++)
-                               env->me_dbflags[i] = txn->mt_dbs[i].md_flags;
-                       env->me_numdbs = i;
+               /* update the DB flags */
+               for (i = 2; i<txn->mt_numdbs; i++) {
+                       if (txn->mt_dbflags[i] & DB_NEW)
+                               env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
                }
+               if (txn->mt_numdbs > env->me_numdbs)
+                       env->me_numdbs = txn->mt_numdbs;
+               txn->mt_numdbs = 2; /* so txn_abort() doesn't close any new handles */
                mdb_txn_abort(txn);
                return MDB_SUCCESS;
        }
@@ -2120,8 +2167,14 @@ mdb_txn_commit(MDB_txn *txn)
 
                /* Update parent's DB table. */
                memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
-               memcpy(parent->mt_dbflags, txn->mt_dbflags, txn->mt_numdbs);
                txn->mt_parent->mt_numdbs = txn->mt_numdbs;
+               txn->mt_parent->mt_dbflags[0] = txn->mt_dbflags[0];
+               txn->mt_parent->mt_dbflags[1] = txn->mt_dbflags[1];
+               for (i=2; i<txn->mt_numdbs; i++) {
+                       /* preserve parent's DB_NEW status */
+                       x = txn->mt_parent->mt_dbflags[i] & DB_NEW;
+                       txn->mt_parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
+               }
 
                dst = txn->mt_parent->mt_u.dirty_list;
                src = txn->mt_u.dirty_list;
@@ -2464,13 +2517,13 @@ sync:
 done:
        env->me_pglast = 0;
        env->me_txn = NULL;
-       if (txn->mt_numdbs > env->me_numdbs) {
-               /* update the DB flags */
-               MDB_dbi i;
-               for (i = env->me_numdbs; i<txn->mt_numdbs; i++)
-                       env->me_dbflags[i] = txn->mt_dbs[i].md_flags;
-               env->me_numdbs = i;
+       /* update the DB flags */
+       for (i = 2; i<txn->mt_numdbs; i++) {
+               if (txn->mt_dbflags[i] & DB_NEW)
+                       env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
        }
+       if (txn->mt_numdbs > env->me_numdbs)
+               env->me_numdbs = txn->mt_numdbs;
 
        UNLOCK_MUTEX_W(env);
        free(txn);
@@ -2738,13 +2791,8 @@ mdb_env_create(MDB_env **env)
        if (!e)
                return ENOMEM;
 
-       e->me_free_pgs = mdb_midl_alloc();
-       if (!e->me_free_pgs) {
-               free(e);
-               return ENOMEM;
-       }
        e->me_maxreaders = DEFAULT_READERS;
-       e->me_maxdbs = 2;
+       e->me_maxdbs = e->me_numdbs = 2;
        e->me_fd = INVALID_HANDLE_VALUE;
        e->me_lfd = INVALID_HANDLE_VALUE;
        e->me_mfd = INVALID_HANDLE_VALUE;
@@ -3161,65 +3209,69 @@ mdb_hash_hex(MDB_val *val, char *hexbuf)
  * @param[in] lpath The pathname of the file used for the lock region.
  * @param[in] mode The Unix permissions for the file, if we create it.
  * @param[out] excl Resulting file lock type: -1 none, 0 shared, 1 exclusive
+ * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
  * @return 0 on success, non-zero on failure.
  */
 static int
 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
 {
+#ifdef _WIN32
+#      define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
+#else
+#      define MDB_ERRCODE_ROFS EROFS
+#ifdef O_CLOEXEC       /* Linux: Open file and set FD_CLOEXEC atomically */
+#      define MDB_CLOEXEC              O_CLOEXEC
+#else
+       int fdflags;
+#      define MDB_CLOEXEC              0
+#endif
+#endif
        int rc;
        off_t size, rsize;
 
-       *excl = -1;
-
 #ifdef _WIN32
-       if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
+       env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
                FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
-               FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
+               FILE_ATTRIBUTE_NORMAL, NULL);
+#else
+       env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
+#endif
+       if (env->me_lfd == INVALID_HANDLE_VALUE) {
                rc = ErrCode();
-               if (rc == ERROR_WRITE_PROTECT && (env->me_flags & MDB_RDONLY)) {
-                       env->me_flags |= MDB_ROFS;
+               if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
                        return MDB_SUCCESS;
                }
                goto fail_errno;
        }
-       /* Try to get exclusive lock. If we succeed, then
-        * nobody is using the lock region and we should initialize it.
-        */
-       if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
-       size = GetFileSize(env->me_lfd, NULL);
-
-#else
-#if !(O_CLOEXEC)
-       {
-               int fdflags;
-               if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
-                       rc = ErrCode();
-                       if (rc == EROFS && (env->me_flags & MDB_RDONLY)) {
-                               env->me_flags |= MDB_ROFS;
-                               return MDB_SUCCESS;
-                       }
-                       goto fail_errno;
-               }
-               /* Lose record locks when exec*() */
-               if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
+#if ! ((MDB_CLOEXEC) || defined(_WIN32))
+       /* Lose record locks when exec*() */
+       if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
                        fcntl(env->me_lfd, F_SETFD, fdflags);
-       }
-#else /* O_CLOEXEC on Linux: Open file and set FD_CLOEXEC atomically */
-       if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT|O_CLOEXEC, mode)) == -1) {
-               rc = ErrCode();
-               if (rc == EROFS && (env->me_flags & MDB_RDONLY)) {
-                       env->me_flags |= MDB_ROFS;
-                       return MDB_SUCCESS;
+#endif
+
+       if (!(env->me_flags & MDB_NOTLS)) {
+               rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
+               if (rc)
+                       goto fail;
+               env->me_flags |= MDB_ENV_TXKEY;
+#ifdef _WIN32
+               /* Windows TLS callbacks need help finding their TLS info. */
+               if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
+                       rc = MDB_TLS_FULL;
+                       goto fail;
                }
-               goto fail_errno;
-       }
+               mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
 #endif
+       }
 
        /* Try to get exclusive lock. If we succeed, then
         * nobody is using the lock region and we should initialize it.
         */
        if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
 
+#ifdef _WIN32
+       size = GetFileSize(env->me_lfd, NULL);
+#else
        size = lseek(env->me_lfd, 0, SEEK_END);
 #endif
        rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
@@ -3375,12 +3427,12 @@ fail:
         *      environment and re-opening it with the new flags.
         */
 #define        CHANGEABLE      (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC)
-#define        CHANGELESS      (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP)
+#define        CHANGELESS      (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP|MDB_NOTLS)
 
 int
-mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
+mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
 {
-       int             oflags, rc, len, excl;
+       int             oflags, rc, len, excl = -1;
        char *lpath, *dpath;
 
        if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
@@ -3405,11 +3457,27 @@ mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
                sprintf(dpath, "%s" DATANAME, path);
        }
 
+       rc = MDB_SUCCESS;
        flags |= env->me_flags;
-       /* silently ignore WRITEMAP if we're only getting read access */
-       if (F_ISSET(flags, MDB_RDONLY|MDB_WRITEMAP))
-               flags ^= MDB_WRITEMAP;
+       if (flags & MDB_RDONLY) {
+               /* silently ignore WRITEMAP when we're only getting read access */
+               flags &= ~MDB_WRITEMAP;
+       } else {
+               if (!((env->me_free_pgs = mdb_midl_alloc()) &&
+                         (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
+                       rc = ENOMEM;
+       }
        env->me_flags = flags |= MDB_ENV_ACTIVE;
+       if (rc)
+               goto leave;
+
+       env->me_path = strdup(path);
+       env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
+       env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
+       if (!(env->me_dbxs && env->me_path && env->me_dbflags)) {
+               rc = ENOMEM;
+               goto leave;
+       }
 
        rc = mdb_env_setup_locks(env, lpath, mode, &excl);
        if (rc)
@@ -3459,29 +3527,9 @@ mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
                        }
                }
                DPRINTF("opened dbenv %p", (void *) env);
-               rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
-               if (rc)
-                       goto leave;
-               env->me_numdbs = 2;     /* this notes that me_txkey was set */
-#ifdef _WIN32
-               /* Windows TLS callbacks need help finding their TLS info. */
-               if (mdb_tls_nkeys < MAX_TLS_KEYS)
-                       mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
-               else {
-                       rc = MDB_TLS_FULL;
-                       goto leave;
-               }
-#endif
                if (excl > 0) {
                        rc = mdb_env_share_locks(env, &excl);
-                       if (rc)
-                               goto leave;
                }
-               env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
-               env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
-               env->me_path = strdup(path);
-               if (!env->me_dbxs || !env->me_dbflags || !env->me_path)
-                       rc = ENOMEM;
        }
 
 leave:
@@ -3504,8 +3552,11 @@ mdb_env_close0(MDB_env *env, int excl)
        free(env->me_dbflags);
        free(env->me_dbxs);
        free(env->me_path);
+       free(env->me_dirty_list);
+       if (env->me_free_pgs)
+               mdb_midl_free(env->me_free_pgs);
 
-       if (env->me_numdbs) {
+       if (env->me_flags & MDB_ENV_TXKEY) {
                pthread_key_delete(env->me_txkey);
 #ifdef _WIN32
                /* Delete our key from the global list */
@@ -3571,7 +3622,7 @@ mdb_env_close0(MDB_env *env, int excl)
                close(env->me_lfd);
        }
 
-       env->me_flags &= ~MDB_ENV_ACTIVE;
+       env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
 }
 
 int
@@ -3630,7 +3681,7 @@ mdb_env_copy(MDB_env *env, const char *path)
        if (rc)
                goto leave;
 
-       if (!(env->me_flags & MDB_ROFS)) {
+       if (env->me_txns) {
                /* We must start the actual read txn after blocking writers */
                mdb_txn_reset0(txn);
 
@@ -3655,7 +3706,7 @@ mdb_env_copy(MDB_env *env, const char *path)
        rc = write(newfd, env->me_map, wsize);
        rc = (rc == (int)wsize) ? MDB_SUCCESS : ErrCode();
 #endif
-       if (! (env->me_flags & MDB_ROFS))
+       if (env->me_txns)
                UNLOCK_MUTEX_W(env);
 
        if (rc)
@@ -3705,10 +3756,14 @@ void
 mdb_env_close(MDB_env *env)
 {
        MDB_page *dp;
+       int i;
 
        if (env == NULL)
                return;
 
+       for (i = env->me_numdbs; --i > MAIN_DBI; )
+               free(env->me_dbxs[i].md_name.mv_data);
+
        VGMEMP_DESTROY(env);
        while ((dp = env->me_dpages) != NULL) {
                VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
@@ -3717,7 +3772,6 @@ mdb_env_close(MDB_env *env)
        }
 
        mdb_env_close0(env, 0);
-       mdb_midl_free(env->me_free_pgs);
        free(env);
 }
 
@@ -4124,13 +4178,14 @@ mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
                                        /* The txn may not know this DBI, or another process may
                                         * have dropped and recreated the DB with other flags.
                                         */
-                                       if (mc->mc_db->md_flags != flags)
+                                       if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
                                                return MDB_INCOMPATIBLE;
                                        memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
                                }
                                if (flags & MDB_PS_MODIFY)
                                        dbflag = DB_DIRTY;
-                               *mc->mc_dbflag = dbflag;
+                               *mc->mc_dbflag &= ~DB_STALE;
+                               *mc->mc_dbflag |= dbflag;
                        }
                }
                root = mc->mc_db->md_root;
@@ -4208,7 +4263,7 @@ mdb_get(MDB_txn *txn, MDB_dbi dbi,
        assert(data);
        DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
 
-       if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
+       if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
                return EINVAL;
 
        if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
@@ -4267,6 +4322,8 @@ mdb_cursor_sibling(MDB_cursor *mc, int move_right)
                return rc;
 
        mdb_cursor_push(mc, mp);
+       if (!move_right)
+               mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
 
        return MDB_SUCCESS;
 }
@@ -4661,9 +4718,9 @@ mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
        }
        assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
 
-       mc->mc_flags |= C_INITIALIZED|C_EOF;
        mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
        }
+       mc->mc_flags |= C_INITIALIZED|C_EOF;
        leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
 
        if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
@@ -4791,7 +4848,7 @@ fetchm:
        case MDB_PREV:
        case MDB_PREV_DUP:
        case MDB_PREV_NODUP:
-               if (!(mc->mc_flags & C_INITIALIZED) || (mc->mc_flags & C_EOF)) {
+               if (!(mc->mc_flags & C_INITIALIZED)) {
                        rc = mdb_cursor_last(mc, key, data);
                        mc->mc_flags |= C_INITIALIZED;
                        mc->mc_ki[mc->mc_top]++;
@@ -4850,7 +4907,7 @@ mdb_cursor_touch(MDB_cursor *mc)
                rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
                if (rc)
                         return rc;
-               *mc->mc_dbflag = DB_DIRTY;
+               *mc->mc_dbflag |= DB_DIRTY;
        }
        for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
                rc = mdb_page_touch(mc);
@@ -4912,7 +4969,7 @@ mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
                mdb_cursor_push(mc, np);
                mc->mc_db->md_root = np->mp_pgno;
                mc->mc_db->md_depth++;
-               *mc->mc_dbflag = DB_DIRTY;
+               *mc->mc_dbflag |= DB_DIRTY;
                if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
                        == MDB_DUPFIXED)
                        np->mp_flags |= P_LEAF2;
@@ -4931,7 +4988,8 @@ mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
                                        rc = MDB_NOTFOUND;
                                        mc->mc_ki[mc->mc_top]++;
                                } else {
-                                       rc = 0;
+                                       /* new key is <= last key */
+                                       rc = MDB_KEYEXIST;
                                }
                        }
                } else {
@@ -5705,8 +5763,8 @@ mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
        }
        DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
                mx->mx_db.md_root);
-       mx->mx_dbflag = (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY)) ?
-               DB_DIRTY : 0;
+       mx->mx_dbflag = DB_VALID | (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY) ?
+               DB_DIRTY : 0);
        mx->mx_dbx.md_name.mv_data = NODEKEY(node);
        mx->mx_dbx.md_name.mv_size = node->mn_ksize;
 #if UINT_MAX < SIZE_MAX
@@ -5752,7 +5810,7 @@ mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
        MDB_xcursor     *mx = NULL;
        size_t size = sizeof(MDB_cursor);
 
-       if (txn == NULL || ret == NULL || dbi >= txn->mt_numdbs)
+       if (txn == NULL || ret == NULL || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
                return EINVAL;
 
        /* Allow read access to the freelist */
@@ -6252,10 +6310,11 @@ static int
 mdb_rebalance(MDB_cursor *mc)
 {
        MDB_node        *node;
-       int rc, minkeys;
-       unsigned int ptop;
+       int rc;
+       unsigned int ptop, minkeys;
        MDB_cursor      mn;
 
+       minkeys = 1 + (IS_BRANCH(mc->mc_pg[mc->mc_top]));
 #if MDB_DEBUG
        {
        pgno_t pgno;
@@ -6266,7 +6325,8 @@ mdb_rebalance(MDB_cursor *mc)
        }
 #endif
 
-       if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD) {
+       if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD &&
+               NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
 #if MDB_DEBUG
                pgno_t pgno;
                COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
@@ -6278,6 +6338,10 @@ mdb_rebalance(MDB_cursor *mc)
 
        if (mc->mc_snum < 2) {
                MDB_page *mp = mc->mc_pg[0];
+               if (IS_SUBP(mp)) {
+                       DPUTS("Can't rebalance a subpage, ignoring");
+                       return MDB_SUCCESS;
+               }
                if (NUMKEYS(mp) == 0) {
                        DPUTS("tree is completely empty");
                        mc->mc_db->md_root = P_INVALID;
@@ -6333,6 +6397,8 @@ mdb_rebalance(MDB_cursor *mc)
                                        if (m3->mc_snum < mc->mc_snum) continue;
                                        if (m3->mc_pg[0] == mp) {
                                                m3->mc_pg[0] = mc->mc_pg[0];
+                                               m3->mc_snum = 1;
+                                               m3->mc_top = 0;
                                        }
                                }
                        }
@@ -6446,7 +6512,7 @@ mdb_del(MDB_txn *txn, MDB_dbi dbi,
 
        DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
 
-       if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
+       if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
                return EINVAL;
 
        if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
@@ -6897,7 +6963,7 @@ mdb_put(MDB_txn *txn, MDB_dbi dbi,
        assert(key != NULL);
        assert(data != NULL);
 
-       if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
+       if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
                return EINVAL;
 
        if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
@@ -6908,7 +6974,7 @@ mdb_put(MDB_txn *txn, MDB_dbi dbi,
                return EINVAL;
        }
 
-       if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND)) != flags)
+       if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP)) != flags)
                return EINVAL;
 
        mdb_cursor_init(&mc, txn, dbi, &mx);
@@ -7019,15 +7085,11 @@ mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
                 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
 }
 
-#define PERSISTENT_FLAGS       0xffff
-#define VALID_FLAGS    (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
-       MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
 {
        MDB_val key, data;
        MDB_dbi i;
        MDB_cursor mc;
-       uint16_t mdflags;
        int rc, dbflag, exact;
        unsigned int unused = 0;
        size_t len;
@@ -7078,7 +7140,7 @@ int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *db
                return MDB_DBS_FULL;
 
        /* Find the DB info */
-       dbflag = 0;
+       dbflag = DB_NEW|DB_VALID;
        exact = 0;
        key.mv_size = len;
        key.mv_data = (void *)name;
@@ -7098,7 +7160,7 @@ int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *db
                dummy.md_root = P_INVALID;
                dummy.md_flags = flags & PERSISTENT_FLAGS;
                rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
-               dbflag = DB_DIRTY;
+               dbflag |= DB_DIRTY;
        }
 
        /* OK, got info, add to table */
@@ -7110,18 +7172,10 @@ int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *db
                txn->mt_dbflags[slot] = dbflag;
                memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
                *dbi = slot;
-               txn->mt_env->me_dbflags[slot] = mdflags = txn->mt_dbs[slot].md_flags;
+               txn->mt_env->me_dbflags[slot] = txn->mt_dbs[slot].md_flags;
                mdb_default_cmp(txn, slot);
                if (!unused) {
                        txn->mt_numdbs++;
-                       txn->mt_env->me_numdbs++;
-               }
-               /* Open the DB in parent txns as well */
-               while ((txn = txn->mt_parent) != NULL) {
-                       txn->mt_dbflags[slot] = DB_STALE;
-                       txn->mt_dbs[slot].md_flags = mdflags;
-                       if (!unused)
-                               txn->mt_numdbs++;
                }
        }
 
@@ -7139,7 +7193,7 @@ int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
 {
        char *ptr;
-       if (dbi <= MAIN_DBI || dbi >= env->me_numdbs)
+       if (dbi <= MAIN_DBI || dbi >= env->me_maxdbs)
                return;
        ptr = env->me_dbxs[dbi].md_name.mv_data;
        env->me_dbxs[dbi].md_name.mv_data = NULL;
@@ -7164,7 +7218,7 @@ mdb_drop0(MDB_cursor *mc, int subs)
                unsigned int i;
 
                /* LEAF2 pages have no nodes, cannot have sub-DBs */
-               if (!subs || IS_LEAF2(mc->mc_pg[mc->mc_top]))
+               if (IS_LEAF2(mc->mc_pg[mc->mc_top]))
                        mdb_cursor_pop(mc);
 
                mdb_cursor_copy(mc, &mx);
@@ -7172,7 +7226,15 @@ mdb_drop0(MDB_cursor *mc, int subs)
                        if (IS_LEAF(mc->mc_pg[mc->mc_top])) {
                                for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
                                        ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
-                                       if (ni->mn_flags & F_SUBDATA) {
+                                       if (ni->mn_flags & F_BIGDATA) {
+                                               int j, ovpages = OVPAGES(NODEDSZ(ni), mc->mc_txn->mt_env->me_psize);
+                                               pgno_t pg;
+                                               memcpy(&pg, NODEDATA(ni), sizeof(pg));
+                                               for (j=0; j<ovpages; j++) {
+                                                       mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
+                                                       pg++;
+                                               }
+                                       } else if (subs && (ni->mn_flags & F_SUBDATA)) {
                                                mdb_xcursor_init1(mc, ni);
                                                rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
                                                if (rc)
@@ -7190,14 +7252,18 @@ mdb_drop0(MDB_cursor *mc, int subs)
                        }
                        if (!mc->mc_top)
                                break;
+                       mc->mc_ki[mc->mc_top] = i;
                        rc = mdb_cursor_sibling(mc, 1);
                        if (rc) {
                                /* no more siblings, go back to beginning
                                 * of previous level.
                                 */
                                mdb_cursor_pop(mc);
-                               for (i=1; i<mc->mc_top; i++)
+                               mc->mc_ki[0] = 0;
+                               for (i=1; i<mc->mc_snum; i++) {
+                                       mc->mc_ki[i] = 0;
                                        mc->mc_pg[i] = mx.mc_pg[i];
+                               }
                        }
                }
                /* free it */
@@ -7212,7 +7278,7 @@ int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
        MDB_cursor *mc;
        int rc;
 
-       if (!txn || !dbi || dbi >= txn->mt_numdbs || (unsigned)del > 1)
+       if (!txn || !dbi || dbi >= txn->mt_numdbs || (unsigned)del > 1 || !(txn->mt_dbflags[dbi] & DB_VALID))
                return EINVAL;
 
        if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
@@ -7243,19 +7309,7 @@ int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
                txn->mt_dbs[dbi].md_entries = 0;
                txn->mt_dbs[dbi].md_root = P_INVALID;
 
-               if (!txn->mt_u.dirty_list[0].mid) {
-                       MDB_cursor m2;
-                       MDB_val key, data;
-                       /* make sure we have at least one dirty page in this txn
-                        * otherwise these changes will be ignored.
-                        */
-                       key.mv_size = sizeof(txnid_t);
-                       key.mv_data = &txn->mt_txnid;
-                       data.mv_size = sizeof(MDB_ID);
-                       data.mv_data = txn->mt_free_pgs;
-                       mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
-                       rc = mdb_cursor_put(&m2, &key, &data, 0);
-               }
+               txn->mt_flags |= MDB_TXN_DIRTY;
        }
 leave:
        mdb_cursor_close(mc);
@@ -7264,7 +7318,7 @@ leave:
 
 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
 {
-       if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
+       if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
                return EINVAL;
 
        txn->mt_dbxs[dbi].md_cmp = cmp;
@@ -7273,7 +7327,7 @@ int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
 
 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
 {
-       if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
+       if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
                return EINVAL;
 
        txn->mt_dbxs[dbi].md_dcmp = cmp;
@@ -7282,7 +7336,7 @@ int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
 
 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
 {
-       if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
+       if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
                return EINVAL;
 
        txn->mt_dbxs[dbi].md_rel = rel;
@@ -7291,7 +7345,7 @@ int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
 
 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
 {
-       if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
+       if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
                return EINVAL;
 
        txn->mt_dbxs[dbi].md_relctx = ctx;