]> git.sur5r.net Git - openldap/blobdiff - libraries/liblmdb/mdb.c
ITS#8504 mdb_env_copyfd2(): Don't abort on SIGPIPE
[openldap] / libraries / liblmdb / mdb.c
index 0a7fcc02e82c5f4ca1e401a5228f5fc56ce6a034..b87e576fda5913c89005352200c5690e1fa67ff5 100644 (file)
@@ -160,6 +160,7 @@ typedef SSIZE_T     ssize_t;
 
 #ifndef _WIN32
 #include <pthread.h>
+#include <signal.h>
 #ifdef MDB_USE_POSIX_SEM
 # define MDB_USE_HASH          1
 #include <semaphore.h>
@@ -1129,7 +1130,7 @@ typedef struct MDB_meta {
 #else
        void            *mm_address;            /**< address for fixed mapping */
 #endif
-       pgno_t          mm_mapsize;                     /**< size of mmap region */
+       mdb_size_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
@@ -1214,11 +1215,12 @@ struct MDB_txn {
  *     @ingroup internal
  * @{
  */
-#define DB_DIRTY       0x01            /**< DB was modified or is DUPSORT data */
+#define DB_DIRTY       0x01            /**< DB was written in this txn */
 #define DB_STALE       0x02            /**< Named-DB record is older than txnID */
 #define DB_NEW         0x04            /**< Named-DB handle opened in this txn */
 #define DB_VALID       0x08            /**< DB handle is valid, see also #MDB_VALID */
 #define DB_USRVALID    0x10            /**< As #DB_VALID, but not set for #FREE_DBI */
+#define DB_DUPDATA     0x20            /**< DB is #MDB_DUPSORT data */
 /** @} */
        /** In write txns, array of cursors for each DB */
        MDB_cursor      **mt_cursors;
@@ -1352,6 +1354,21 @@ typedef struct MDB_xcursor {
        unsigned char mx_dbflag;
 } MDB_xcursor;
 
+       /** Check if there is an inited xcursor, so #XCURSOR_REFRESH() is proper */
+#define XCURSOR_INITED(mc) \
+       ((mc)->mc_xcursor && ((mc)->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
+
+       /** Update sub-page pointer, if any, in \b mc->mc_xcursor.  Needed
+        *      when the node which contains the sub-page may have moved.  Called
+        *      with \b mp = mc->mc_pg[mc->mc_top], \b ki = mc->mc_ki[mc->mc_top].
+        */
+#define XCURSOR_REFRESH(mc, mp, ki) do { \
+       MDB_page *xr_pg = (mp); \
+       MDB_node *xr_node = NODEPTR(xr_pg, ki); \
+       if ((xr_node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) \
+               (mc)->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(xr_node); \
+} while (0)
+
        /** State of FreeDB old pages, stored in the MDB_env */
 typedef struct MDB_pgstate {
        pgno_t          *mf_pghead;     /**< Reclaimed freeDB pages, or NULL before use */
@@ -1362,7 +1379,7 @@ typedef struct MDB_pgstate {
 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 */
+       HANDLE          me_mfd;         /**< For writing and syncing the meta pages */
 #if defined(MDB_VL32) && defined(_WIN32)
        HANDLE          me_fmh;         /**< File Mapping handle */
 #endif
@@ -1799,7 +1816,7 @@ 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)) {
+       if (XCURSOR_INITED(mc)) {
                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)) {
@@ -1884,6 +1901,7 @@ mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
 
 /** Allocate memory for a page.
  * Re-use old malloc'd pages first for singletons, otherwise just malloc.
+ * Set #MDB_TXN_ERROR on failure.
  */
 static MDB_page *
 mdb_page_malloc(MDB_txn *txn, unsigned num)
@@ -2077,13 +2095,9 @@ mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
        unsigned i, j;
        int rc = MDB_SUCCESS, level;
 
-       /* Mark pages seen by cursors */
-       if (mc->mc_flags & C_UNTRACK)
-               mc = NULL;                              /* will find mc in mt_cursors */
-       for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
-               for (; mc; mc=mc->mc_next) {
-                       if (!(mc->mc_flags & C_INITIALIZED))
-                               continue;
+       /* Mark pages seen by cursors: First m0, then tracked cursors */
+       for (i = txn->mt_numdbs;; ) {
+               if (mc->mc_flags & C_INITIALIZED) {
                        for (m3 = mc;; m3 = &mx->mx_cursor) {
                                mp = NULL;
                                for (j=0; j<m3->mc_snum; j++) {
@@ -2102,10 +2116,13 @@ mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
                                        break;
                        }
                }
-               if (i == 0)
-                       break;
+               mc = mc->mc_next;
+               for (; !mc || mc == m0; mc = txn->mt_cursors[--i])
+                       if (i == 0)
+                               goto mark_done;
        }
 
+mark_done:
        if (all) {
                /* Mark dirty root pages */
                for (i=0; i<txn->mt_numdbs; i++) {
@@ -2295,7 +2312,7 @@ mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
 }
 
 /** Allocate page numbers and memory for writing.  Maintain me_pglast,
- * me_pghead and mt_next_pgno.
+ * me_pghead and mt_next_pgno.  Set #MDB_TXN_ERROR on failure.
  *
  * If there are free pages available from older transactions, they
  * are re-used first. Otherwise allocate a new page at mt_next_pgno.
@@ -2427,7 +2444,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(&m2, leaf, &data)) != MDB_SUCCESS)
-                       return rc;
+                       goto fail;
 
                idl = (MDB_ID *) data.mv_data;
                i = idl[0];
@@ -2591,6 +2608,7 @@ mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
 }
 
 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
+ * Set #MDB_TXN_ERROR on failure.
  * @param[in] mc cursor pointing to the page to be touched
  * @return 0 on success, non-zero on failure.
  */
@@ -2679,14 +2697,8 @@ done:
                        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_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
-                               {
-                                       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);
-                               }
+                               if (XCURSOR_INITED(m2) && IS_LEAF(np))
+                                       XCURSOR_REFRESH(m2, np, m2->mc_ki[mc->mc_top]);
                        }
                }
        }
@@ -4100,7 +4112,10 @@ mdb_env_write_meta(MDB_txn *txn)
        len = sizeof(MDB_meta) - off;
        off += (char *)mp - env->me_map;
 
-       /* Write to the SYNC fd */
+       /* Write to the SYNC fd unless MDB_NOSYNC/MDB_NOMETASYNC.
+        * (me_mfd goes to the same file as me_fd, but writing to it
+        * also syncs to disk.  Avoids a separate fdatasync() call.)
+        */
        mfd = (flags & (MDB_NOSYNC|MDB_NOMETASYNC)) ? env->me_fd : env->me_mfd;
 #ifdef _WIN32
        {
@@ -4462,8 +4477,8 @@ enum mdb_fopen_type {
        /* A comment in mdb_fopen() explains some O_* flag choices. */
        MDB_O_RDONLY= O_RDONLY,                            /**< for RDONLY me_fd */
        MDB_O_RDWR  = O_RDWR  |O_CREAT,                    /**< for me_fd */
-       MDB_O_META  = O_RDWR  |MDB_DSYNC,                  /**< for me_mfd */
-       MDB_O_COPY  = O_WRONLY|O_CREAT|O_EXCL,             /**< for #mdb_env_copy() */
+       MDB_O_META  = O_WRONLY|MDB_DSYNC     |MDB_CLOEXEC, /**< for me_mfd */
+       MDB_O_COPY  = O_WRONLY|O_CREAT|O_EXCL|MDB_CLOEXEC, /**< for #mdb_env_copy() */
        /** Bitmask for open() flags in enum #mdb_fopen_type.  The other bits
         * distinguish otherwise-equal MDB_O_* constants from each other.
         */
@@ -4507,6 +4522,9 @@ mdb_fopen(const MDB_env *env, MDB_name *fname,
         *
         * The lockfile needs FD_CLOEXEC (close file descriptor on exec*())
         * to avoid the flock() issues noted under Caveats in lmdb.h.
+        * Also set it for other filehandles which the user cannot get at
+        * and close himself, which he may need after fork().  I.e. all but
+        * me_fd, which programs do use via mdb_env_get_fd().
         */
 
 #ifdef _WIN32
@@ -4520,6 +4538,7 @@ mdb_fopen(const MDB_env *env, MDB_name *fname,
                disp = OPEN_EXISTING;
                break;
        case MDB_O_META:                        /* for writing metapages */
+               acc = GENERIC_WRITE;
                disp = OPEN_EXISTING;
                attrs = FILE_ATTRIBUTE_NORMAL|FILE_FLAG_WRITE_THROUGH;
                break;
@@ -4540,7 +4559,7 @@ mdb_fopen(const MDB_env *env, MDB_name *fname,
                rc = ErrCode();
 #ifndef _WIN32
        else {
-               if (which == MDB_O_LOCKS) {
+               if (which != MDB_O_RDONLY && which != MDB_O_RDWR) {
                        /* Set CLOEXEC if we could not pass it to open() */
                        if (!MDB_CLOEXEC && (flags = fcntl(fd, F_GETFD)) != -1)
                                (void) fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
@@ -4744,7 +4763,11 @@ mdb_env_reader_dest(void *ptr)
 {
        MDB_reader *reader = ptr;
 
-       reader->mr_pid = 0;
+#ifndef _WIN32
+       if (reader->mr_pid == getpid()) /* catch pthread_exit() in child process */
+#endif
+               /* We omit the mutex, so do this atomically (i.e. skip mr_txnid) */
+               reader->mr_pid = 0;
 }
 
 #ifdef _WIN32
@@ -5225,13 +5248,6 @@ mdb_env_setup_locks(MDB_env *env, MDB_name *fname, 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;
@@ -5279,6 +5295,21 @@ mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode
        if (rc)
                return rc;
 
+#ifdef MDB_VL32
+#ifdef _WIN32
+       env->me_rpmutex = CreateMutex(NULL, FALSE, NULL);
+       if (!env->me_rpmutex) {
+               rc = ErrCode();
+               goto leave;
+       }
+#else
+       rc = pthread_mutex_init(&env->me_rpmutex, NULL);
+       if (rc)
+               goto leave;
+#endif
+#endif
+       flags |= MDB_ENV_ACTIVE;        /* tell mdb_env_close0() to clean up */
+
        if (flags & MDB_RDONLY) {
                /* silently ignore WRITEMAP when we're only getting read access */
                flags &= ~MDB_WRITEMAP;
@@ -5287,8 +5318,13 @@ 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;
        }
+
+       env->me_flags = flags;
+       if (rc)
+               goto leave;
+
 #ifdef MDB_VL32
-       if (!rc) {
+       {
                env->me_rpages = malloc(MDB_ERPAGE_SIZE * sizeof(MDB_ID3));
                if (!env->me_rpages) {
                        rc = ENOMEM;
@@ -5298,9 +5334,6 @@ mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode
                env->me_rpcheck = MDB_ERPAGE_SIZE/2;
        }
 #endif
-       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));
@@ -5332,9 +5365,7 @@ mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode
        }
 
        if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
-               if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
-                       env->me_mfd = env->me_fd;
-               } else {
+               if (!(flags & (MDB_RDONLY|MDB_WRITEMAP))) {
                        /* Synchronous fd for meta writes. Needed even with
                         * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
                         */
@@ -5411,11 +5442,13 @@ mdb_env_close0(MDB_env *env, int excl)
 #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);
+       if (env->me_rpages) {
+               MDB_ID3L el = env->me_rpages;
+               unsigned int x;
+               for (x=1; x<=el[0].mid; x++)
+                       munmap(el[x].mptr, el[x].mcnt * env->me_psize);
+               free(el);
        }
-       free(env->me_rpages);
 #endif
        free(env->me_txn0);
        mdb_midl_free(env->me_free_pgs);
@@ -5440,7 +5473,7 @@ mdb_env_close0(MDB_env *env, int excl)
                munmap(env->me_map, env->me_mapsize);
 #endif
        }
-       if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
+       if (env->me_mfd != INVALID_HANDLE_VALUE)
                (void) close(env->me_mfd);
        if (env->me_fd != INVALID_HANDLE_VALUE)
                (void) close(env->me_fd);
@@ -5758,7 +5791,9 @@ mdb_cursor_pop(MDB_cursor *mc)
        }
 }
 
-/** Push a page onto the top of the cursor's stack. */
+/** Push a page onto the top of the cursor's stack.
+ * Set #MDB_TXN_ERROR on failure.
+ */
 static int
 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
 {
@@ -6066,6 +6101,7 @@ ok:
 #endif
 
 /** Find the address of the page corresponding to a given page number.
+ * Set #MDB_TXN_ERROR on failure.
  * @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.
@@ -6120,8 +6156,10 @@ mapped:
        {
 #ifdef MDB_VL32
                int rc = mdb_rpage_get(txn, pgno, &p);
-               if (rc)
+               if (rc) {
+                       txn->mt_flags |= MDB_TXN_ERROR;
                        return rc;
+               }
 #else
                MDB_env *env = txn->mt_env;
                p = (MDB_page *)(env->me_map + env->me_psize * pgno);
@@ -6676,8 +6714,6 @@ mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
        } else
                mc->mc_ki[mc->mc_top]--;
 
-       mc->mc_flags &= ~C_EOF;
-
        DPRINTF(("==> cursor points to page %"Yu" with %u keys, key index %u",
            mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
 
@@ -7193,7 +7229,8 @@ mdb_cursor_touch(MDB_cursor *mc)
 {
        int rc = MDB_SUCCESS;
 
-       if (mc->mc_dbi >= CORE_DBS && !(*mc->mc_dbflag & DB_DIRTY)) {
+       if (mc->mc_dbi >= CORE_DBS && !(*mc->mc_dbflag & (DB_DIRTY|DB_DUPDATA))) {
+               /* Touch DB record of named DB */
                MDB_cursor mc2;
                MDB_xcursor mcx;
                if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
@@ -7645,11 +7682,8 @@ new_sub:
                                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);
-                               }
+                               if (XCURSOR_INITED(m3))
+                                       XCURSOR_REFRESH(m3, mp, m3->mc_ki[i]);
                        }
                }
        }
@@ -7700,9 +7734,7 @@ put_sub:
                                                if (m2->mc_ki[i] == mc->mc_ki[i]) {
                                                        mdb_xcursor_init2(m2, mx, new_dupdata);
                                                } else if (!insert_key && m2->mc_ki[i] < nkeys) {
-                                                       MDB_node *n2 = NODEPTR(mp, m2->mc_ki[i]);
-                                                       if ((n2->mn_flags & (F_SUBDATA|F_DUPDATA)) == F_DUPDATA)
-                                                               m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
+                                                       XCURSOR_REFRESH(m2, mp, m2->mc_ki[i]);
                                                }
                                        }
                                }
@@ -7807,13 +7839,12 @@ mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
                                                if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
                                                if (!(m2->mc_flags & C_INITIALIZED)) continue;
                                                if (m2->mc_pg[mc->mc_top] == mp) {
-                                                       if (m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top]) {
-                                                               m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
-                                                       } else {
-                                                               MDB_node *n2 = NODEPTR(mp, m2->mc_ki[mc->mc_top]);
-                                                               if (!(n2->mn_flags & F_SUBDATA))
-                                                                       m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
+                                                       MDB_node *n2 = leaf;
+                                                       if (m2->mc_ki[mc->mc_top] != mc->mc_ki[mc->mc_top]) {
+                                                               n2 = NODEPTR(mp, m2->mc_ki[mc->mc_top]);
+                                                               if (n2->mn_flags & F_SUBDATA) continue;
                                                        }
+                                                       m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
                                                }
                                        }
                                }
@@ -7858,6 +7889,7 @@ fail:
 }
 
 /** Allocate and initialize new pages for a database.
+ * Set #MDB_TXN_ERROR on failure.
  * @param[in] mc a cursor on the database being added to.
  * @param[in] flags flags defining what type of page is being allocated.
  * @param[in] num the number of pages to allocate. This is usually 1,
@@ -7943,6 +7975,7 @@ mdb_branch_size(MDB_env *env, MDB_val *key)
 }
 
 /** Add a node to the page pointed to by the cursor.
+ * Set #MDB_TXN_ERROR on failure.
  * @param[in] mc The cursor for this operation.
  * @param[in] indx The index on the page where the new node should be added.
  * @param[in] key The key for the new node.
@@ -8253,7 +8286,7 @@ mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
        }
        DPRINTF(("Sub-db -%u root page %"Yu, 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 */
+       mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DUPDATA;
        if (NEED_CMP_CLONG(mx->mx_dbx.md_cmp, mx->mx_db.md_pad))
                mx->mx_dbx.md_cmp = mdb_cmp_clong;
 }
@@ -8277,7 +8310,7 @@ mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int new_dupdata)
                mx->mx_cursor.mc_top = 0;
                mx->mx_cursor.mc_flags |= C_INITIALIZED;
                mx->mx_cursor.mc_ki[0] = 0;
-               mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
+               mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DUPDATA;
 #if UINT_MAX < MDB_SIZE_MAX    /* matches mdb_xcursor_init1:NEED_CMP_CLONG() */
                mx->mx_dbx.md_cmp = src_mx->mx_dbx.md_cmp;
 #endif
@@ -8409,7 +8442,10 @@ mdb_cursor_close(MDB_cursor *mc)
                MDB_CURSOR_UNREF(mc, 0);
        }
        if (mc && !mc->mc_backup) {
-               /* remove from txn, if tracked */
+               /* Remove from txn, if tracked.
+                * A read-only txn (!C_UNTRACK) may have been freed already,
+                * so do not peek inside it.  Only write txns track cursors.
+                */
                if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
                        MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
                        while (*prev && *prev != mc) prev = &(*prev)->mc_next;
@@ -8434,6 +8470,7 @@ mdb_cursor_dbi(MDB_cursor *mc)
 }
 
 /** Replace the key for a branch node with a new key.
+ * Set #MDB_TXN_ERROR on failure.
  * @param[in] mc Cursor pointing to the node to operate on.
  * @param[in] key The new key to use.
  * @return 0 on success, non-zero on failure.
@@ -8653,12 +8690,8 @@ mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft)
                                        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);
-                               }
+                               if (XCURSOR_INITED(m3) && IS_LEAF(mps))
+                                       XCURSOR_REFRESH(m3, m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
                        }
                } else
                /* Adding on the right, bump others down */
@@ -8679,12 +8712,8 @@ mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft)
                                        } 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);
-                                       }
+                                       if (XCURSOR_INITED(m3) && IS_LEAF(mps))
+                                               XCURSOR_REFRESH(m3, m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
                                }
                        }
                }
@@ -8885,12 +8914,8 @@ mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
                                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);
-                       }
+                       if (XCURSOR_INITED(m3) && IS_LEAF(psrc))
+                               XCURSOR_REFRESH(m3, m3->mc_pg[top], m3->mc_ki[top]);
                }
        }
        {
@@ -9145,14 +9170,16 @@ mdb_cursor_del0(MDB_cursor *mc)
                        if (m3->mc_pg[mc->mc_top] == mp) {
                                if (m3->mc_ki[mc->mc_top] == ki) {
                                        m3->mc_flags |= C_DEL;
+                                       if (mc->mc_db->md_flags & MDB_DUPSORT) {
+                                               /* Sub-cursor referred into dataset which is gone */
+                                               m3->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
+                                       }
+                                       continue;
                                } 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);
-                               }
+                               if (XCURSOR_INITED(m3))
+                                       XCURSOR_REFRESH(m3, m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
                        }
                }
        }
@@ -9189,9 +9216,15 @@ mdb_cursor_del0(MDB_cursor *mc)
                                        }
                                        if (mc->mc_db->md_flags & MDB_DUPSORT) {
                                                MDB_node *node = NODEPTR(m3->mc_pg[m3->mc_top], m3->mc_ki[m3->mc_top]);
-                                               if (node->mn_flags & F_DUPDATA) {
-                                                       mdb_xcursor_init1(m3, node);
-                                                       m3->mc_xcursor->mx_cursor.mc_flags |= C_DEL;
+                                               /* If this node is a fake page, it needs to be reinited
+                                                * because its data has moved. But just reset mc_pg[0]
+                                                * if the xcursor is already live.
+                                                */
+                                               if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) {
+                                                       if (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)
+                                                               m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
+                                                       else
+                                                               mdb_xcursor_init1(m3, node);
                                                }
                                        }
                                }
@@ -9257,7 +9290,6 @@ mdb_del0(MDB_txn *txn, MDB_dbi dbi,
                 * run out of space, triggering a split. We need this
                 * cursor to be consistent until the end of the rebalance.
                 */
-               mc.mc_flags |= C_UNTRACK;
                mc.mc_next = txn->mt_cursors[dbi];
                txn->mt_cursors[dbi] = &mc;
                rc = mdb_cursor_del(&mc, flags);
@@ -9267,6 +9299,7 @@ mdb_del0(MDB_txn *txn, MDB_dbi dbi,
 }
 
 /** Split a page and insert a new node.
+ * Set #MDB_TXN_ERROR on failure.
  * @param[in,out] mc Cursor pointing to the page and desired insertion index.
  * The cursor will be updated to point to the actual page and index where
  * the node got inserted after the split.
@@ -9516,7 +9549,7 @@ mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno
                        } else {
                                /* find right page's left sibling */
                                mc->mc_ki[ptop] = mn.mc_ki[ptop];
-                               mdb_cursor_sibling(mc, 0);
+                               rc = mdb_cursor_sibling(mc, 0);
                        }
                }
        } else {
@@ -9525,6 +9558,8 @@ mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno
                mn.mc_top++;
        }
        if (rc != MDB_SUCCESS) {
+               if (rc == MDB_NOTFOUND) /* improper mdb_cursor_sibling() result */
+                       rc = MDB_PROBLEM;
                goto done;
        }
        if (nflags & MDB_APPEND) {
@@ -9676,12 +9711,8 @@ mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno
                                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);
-                       }
+                       if (XCURSOR_INITED(m3) && IS_LEAF(mp))
+                               XCURSOR_REFRESH(m3, m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
                }
        }
        DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
@@ -9738,7 +9769,10 @@ typedef struct mdb_copy {
        HANDLE mc_fd;
        int mc_toggle;                  /**< Buffer number in provider */
        int mc_new;                             /**< (0-2 buffers to write) | (#MDB_EOF at end) */
-       volatile int mc_error;  /**< Error code, never cleared if set */
+       /** Error code.  Never cleared if set.  Both threads can set nonzero
+        *      to fail the copy.  Not mutex-protected, LMDB expects atomic int.
+        */
+       volatile int mc_error;
 } mdb_copy;
 
        /** Dedicated writer thread for compacting copy. */
@@ -9753,10 +9787,17 @@ mdb_env_copythr(void *arg)
 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
 #else
        int len;
+       sigset_t set;
 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
+
+       sigemptyset(&set);
+       sigaddset(&set, SIGPIPE);
 #endif
 
        pthread_mutex_lock(&my->mc_mutex);
+#ifndef _WIN32
+       my->mc_error = pthread_sigmask(SIG_BLOCK, &set, NULL);
+#endif
        for(;;) {
                while (!my->mc_new)
                        pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
@@ -9770,6 +9811,12 @@ again:
                        DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
                        if (!rc) {
                                rc = ErrCode();
+#ifndef _WIN32
+                               if (rc == EPIPE) {
+                                       int tmp;
+                                       sigwait(&set, &tmp);
+                               }
+#endif
                                break;
                        } else if (len > 0) {
                                rc = MDB_SUCCESS;
@@ -9823,7 +9870,11 @@ mdb_env_cthr_toggle(mdb_copy *my, int adjust)
        return my->mc_error;
 }
 
-       /** Depth-first tree traversal for compacting copy. */
+       /** Depth-first tree traversal for compacting copy.
+        * @param[in] my control structure.
+        * @param[in,out] pg database root.
+        * @param[in] flags includes #F_DUPDATA if it is a sorted-duplicate sub-DB.
+        */
 static int ESECT
 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
 {
@@ -10479,7 +10530,8 @@ int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *db
                memset(&dummy, 0, sizeof(dummy));
                dummy.md_root = P_INVALID;
                dummy.md_flags = flags & PERSISTENT_FLAGS;
-               rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
+               WITH_CURSOR_TRACKING(mc,
+                       rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA));
                dbflag |= DB_DIRTY;
        }
 
@@ -10839,7 +10891,7 @@ mdb_reader_check(MDB_env *env, int *dead)
        return env->me_txns ? mdb_reader_check0(env, 0, dead) : MDB_SUCCESS;
 }
 
-/** As #mdb_reader_check(). rlocked = <caller locked the reader mutex>. */
+/** As #mdb_reader_check(). \b rlocked is set if caller locked #me_rmutex. */
 static int ESECT
 mdb_reader_check0(MDB_env *env, int rlocked, int *dead)
 {