]> git.proxmox.com Git - mirror_zfs.git/blobdiff - module/zfs/dmu_tx.c
OpenZFS 8997 - ztest assertion failure in zil_lwb_write_issue
[mirror_zfs.git] / module / zfs / dmu_tx.c
index 1cad8d20e6ad0e883644704ee8b9cb95f4264608..6ebff267144fbdd1471308aa9b6bfcf326a1871f 100644 (file)
@@ -21,7 +21,7 @@
 /*
  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
  * Copyright 2011 Nexenta Systems, Inc.  All rights reserved.
- * Copyright (c) 2013 by Delphix. All rights reserved.
+ * Copyright (c) 2012, 2017 by Delphix. All rights reserved.
  */
 
 #include <sys/dmu.h>
 #include <sys/dbuf.h>
 #include <sys/dmu_tx.h>
 #include <sys/dmu_objset.h>
-#include <sys/dsl_dataset.h> /* for dsl_dataset_block_freeable() */
-#include <sys/dsl_dir.h> /* for dsl_dir_tempreserve_*() */
+#include <sys/dsl_dataset.h>
+#include <sys/dsl_dir.h>
 #include <sys/dsl_pool.h>
-#include <sys/zap_impl.h> /* for fzap_default_block_shift */
+#include <sys/zap_impl.h>
 #include <sys/spa.h>
 #include <sys/sa.h>
 #include <sys/sa_impl.h>
 #include <sys/zfs_context.h>
 #include <sys/varargs.h>
+#include <sys/trace_dmu.h>
 
 typedef void (*dmu_tx_hold_func_t)(dmu_tx_t *tx, struct dnode *dn,
     uint64_t arg1, uint64_t arg2);
@@ -48,12 +49,11 @@ dmu_tx_stats_t dmu_tx_stats = {
        { "dmu_tx_error",               KSTAT_DATA_UINT64 },
        { "dmu_tx_suspended",           KSTAT_DATA_UINT64 },
        { "dmu_tx_group",               KSTAT_DATA_UINT64 },
-       { "dmu_tx_how",                 KSTAT_DATA_UINT64 },
        { "dmu_tx_memory_reserve",      KSTAT_DATA_UINT64 },
        { "dmu_tx_memory_reclaim",      KSTAT_DATA_UINT64 },
-       { "dmu_tx_memory_inflight",     KSTAT_DATA_UINT64 },
        { "dmu_tx_dirty_throttle",      KSTAT_DATA_UINT64 },
-       { "dmu_tx_write_limit",         KSTAT_DATA_UINT64 },
+       { "dmu_tx_dirty_delay",         KSTAT_DATA_UINT64 },
+       { "dmu_tx_dirty_over_max",      KSTAT_DATA_UINT64 },
        { "dmu_tx_quota",               KSTAT_DATA_UINT64 },
 };
 
@@ -62,7 +62,7 @@ static kstat_t *dmu_tx_ksp;
 dmu_tx_t *
 dmu_tx_create_dd(dsl_dir_t *dd)
 {
-       dmu_tx_t *tx = kmem_zalloc(sizeof (dmu_tx_t), KM_PUSHPAGE);
+       dmu_tx_t *tx = kmem_zalloc(sizeof (dmu_tx_t), KM_SLEEP);
        tx->tx_dir = dd;
        if (dd != NULL)
                tx->tx_pool = dd->dd_pool;
@@ -70,10 +70,7 @@ dmu_tx_create_dd(dsl_dir_t *dd)
            offsetof(dmu_tx_hold_t, txh_node));
        list_create(&tx->tx_callbacks, sizeof (dmu_tx_callback_t),
            offsetof(dmu_tx_callback_t, dcb_node));
-#ifdef DEBUG_DMU_TX
-       refcount_create(&tx->tx_space_written);
-       refcount_create(&tx->tx_space_freed);
-#endif
+       tx->tx_start = gethrtime();
        return (tx);
 }
 
@@ -82,7 +79,6 @@ dmu_tx_create(objset_t *os)
 {
        dmu_tx_t *tx = dmu_tx_create_dd(os->os_dsl_dataset->ds_dir);
        tx->tx_objset = os;
-       tx->tx_lastsnap_txg = dsl_dataset_prev_snap_txg(os->os_dsl_dataset);
        return (tx);
 }
 
@@ -91,7 +87,7 @@ dmu_tx_create_assigned(struct dsl_pool *dp, uint64_t txg)
 {
        dmu_tx_t *tx = dmu_tx_create_dd(NULL);
 
-       ASSERT3U(txg, <=, dp->dp_tx.tx_open_txg);
+       txg_verify(dp->dp_spa, txg);
        tx->tx_pool = dp;
        tx->tx_txg = txg;
        tx->tx_anyobj = TRUE;
@@ -112,21 +108,14 @@ dmu_tx_private_ok(dmu_tx_t *tx)
 }
 
 static dmu_tx_hold_t *
-dmu_tx_hold_object_impl(dmu_tx_t *tx, objset_t *os, uint64_t object,
-    enum dmu_tx_hold_type type, uint64_t arg1, uint64_t arg2)
+dmu_tx_hold_dnode_impl(dmu_tx_t *tx, dnode_t *dn, enum dmu_tx_hold_type type,
+    uint64_t arg1, uint64_t arg2)
 {
        dmu_tx_hold_t *txh;
-       dnode_t *dn = NULL;
-       int err;
 
-       if (object != DMU_NEW_OBJECT) {
-               err = dnode_hold(os, object, tx, &dn);
-               if (err) {
-                       tx->tx_err = err;
-                       return (NULL);
-               }
-
-               if (err == 0 && tx->tx_txg != 0) {
+       if (dn != NULL) {
+               (void) refcount_add(&dn->dn_holds, tx);
+               if (tx->tx_txg != 0) {
                        mutex_enter(&dn->dn_mtx);
                        /*
                         * dn->dn_assigned_txg == tx->tx_txg doesn't pose a
@@ -140,32 +129,79 @@ dmu_tx_hold_object_impl(dmu_tx_t *tx, objset_t *os, uint64_t object,
                }
        }
 
-       txh = kmem_zalloc(sizeof (dmu_tx_hold_t), KM_PUSHPAGE);
+       txh = kmem_zalloc(sizeof (dmu_tx_hold_t), KM_SLEEP);
        txh->txh_tx = tx;
        txh->txh_dnode = dn;
-#ifdef DEBUG_DMU_TX
+       refcount_create(&txh->txh_space_towrite);
+       refcount_create(&txh->txh_memory_tohold);
        txh->txh_type = type;
        txh->txh_arg1 = arg1;
        txh->txh_arg2 = arg2;
-#endif
        list_insert_tail(&tx->tx_holds, txh);
 
        return (txh);
 }
 
+static dmu_tx_hold_t *
+dmu_tx_hold_object_impl(dmu_tx_t *tx, objset_t *os, uint64_t object,
+    enum dmu_tx_hold_type type, uint64_t arg1, uint64_t arg2)
+{
+       dnode_t *dn = NULL;
+       dmu_tx_hold_t *txh;
+       int err;
+
+       if (object != DMU_NEW_OBJECT) {
+               err = dnode_hold(os, object, FTAG, &dn);
+               if (err != 0) {
+                       tx->tx_err = err;
+                       return (NULL);
+               }
+       }
+       txh = dmu_tx_hold_dnode_impl(tx, dn, type, arg1, arg2);
+       if (dn != NULL)
+               dnode_rele(dn, FTAG);
+       return (txh);
+}
+
 void
-dmu_tx_add_new_object(dmu_tx_t *tx, objset_t *os, uint64_t object)
+dmu_tx_add_new_object(dmu_tx_t *tx, dnode_t *dn)
 {
        /*
         * If we're syncing, they can manipulate any object anyhow, and
         * the hold on the dnode_t can cause problems.
         */
-       if (!dmu_tx_is_syncing(tx)) {
-               (void) dmu_tx_hold_object_impl(tx, os,
-                   object, THT_NEWOBJECT, 0, 0);
-       }
+       if (!dmu_tx_is_syncing(tx))
+               (void) dmu_tx_hold_dnode_impl(tx, dn, THT_NEWOBJECT, 0, 0);
 }
 
+/*
+ * This function reads specified data from disk.  The specified data will
+ * be needed to perform the transaction -- i.e, it will be read after
+ * we do dmu_tx_assign().  There are two reasons that we read the data now
+ * (before dmu_tx_assign()):
+ *
+ * 1. Reading it now has potentially better performance.  The transaction
+ * has not yet been assigned, so the TXG is not held open, and also the
+ * caller typically has less locks held when calling dmu_tx_hold_*() than
+ * after the transaction has been assigned.  This reduces the lock (and txg)
+ * hold times, thus reducing lock contention.
+ *
+ * 2. It is easier for callers (primarily the ZPL) to handle i/o errors
+ * that are detected before they start making changes to the DMU state
+ * (i.e. now).  Once the transaction has been assigned, and some DMU
+ * state has been changed, it can be difficult to recover from an i/o
+ * error (e.g. to undo the changes already made in memory at the DMU
+ * layer).  Typically code to do so does not exist in the caller -- it
+ * assumes that the data has already been cached and thus i/o errors are
+ * not possible.
+ *
+ * It has been observed that the i/o initiated here can be a performance
+ * problem, and it appears to be optional, because we don't look at the
+ * data which is read.  However, removing this read would only serve to
+ * move the work elsewhere (after the dmu_tx_assign()), where it may
+ * have a greater impact on performance (in addition to the impact on
+ * fault tolerance noted above).
+ */
 static int
 dmu_tx_check_ioerr(zio_t *zio, dnode_t *dn, int level, uint64_t blkid)
 {
@@ -182,235 +218,84 @@ dmu_tx_check_ioerr(zio_t *zio, dnode_t *dn, int level, uint64_t blkid)
        return (err);
 }
 
-static void
-dmu_tx_count_twig(dmu_tx_hold_t *txh, dnode_t *dn, dmu_buf_impl_t *db,
-    int level, uint64_t blkid, boolean_t freeable, uint64_t *history)
-{
-       objset_t *os = dn->dn_objset;
-       dsl_dataset_t *ds = os->os_dsl_dataset;
-       int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
-       dmu_buf_impl_t *parent = NULL;
-       blkptr_t *bp = NULL;
-       uint64_t space;
-
-       if (level >= dn->dn_nlevels || history[level] == blkid)
-               return;
-
-       history[level] = blkid;
-
-       space = (level == 0) ? dn->dn_datablksz : (1ULL << dn->dn_indblkshift);
-
-       if (db == NULL || db == dn->dn_dbuf) {
-               ASSERT(level != 0);
-               db = NULL;
-       } else {
-               ASSERT(DB_DNODE(db) == dn);
-               ASSERT(db->db_level == level);
-               ASSERT(db->db.db_size == space);
-               ASSERT(db->db_blkid == blkid);
-               bp = db->db_blkptr;
-               parent = db->db_parent;
-       }
-
-       freeable = (bp && (freeable ||
-           dsl_dataset_block_freeable(ds, bp, bp->blk_birth)));
-
-       if (freeable)
-               txh->txh_space_tooverwrite += space;
-       else
-               txh->txh_space_towrite += space;
-       if (bp)
-               txh->txh_space_tounref += bp_get_dsize(os->os_spa, bp);
-
-       dmu_tx_count_twig(txh, dn, parent, level + 1,
-           blkid >> epbs, freeable, history);
-}
-
 /* ARGSUSED */
 static void
 dmu_tx_count_write(dmu_tx_hold_t *txh, uint64_t off, uint64_t len)
 {
        dnode_t *dn = txh->txh_dnode;
-       uint64_t start, end, i;
-       int min_bs, max_bs, min_ibs, max_ibs, epbs, bits;
        int err = 0;
-       int l;
 
        if (len == 0)
                return;
 
-       min_bs = SPA_MINBLOCKSHIFT;
-       max_bs = SPA_MAXBLOCKSHIFT;
-       min_ibs = DN_MIN_INDBLKSHIFT;
-       max_ibs = DN_MAX_INDBLKSHIFT;
+       (void) refcount_add_many(&txh->txh_space_towrite, len, FTAG);
 
-       if (dn) {
-               uint64_t history[DN_MAX_LEVELS];
-               int nlvls = dn->dn_nlevels;
-               int delta;
-
-               /*
-                * For i/o error checking, read the first and last level-0
-                * blocks (if they are not aligned), and all the level-1 blocks.
-                */
-               if (dn->dn_maxblkid == 0) {
-                       delta = dn->dn_datablksz;
-                       start = (off < dn->dn_datablksz) ? 0 : 1;
-                       end = (off+len <= dn->dn_datablksz) ? 0 : 1;
-                       if (start == 0 && (off > 0 || len < dn->dn_datablksz)) {
-                               err = dmu_tx_check_ioerr(NULL, dn, 0, 0);
-                               if (err)
-                                       goto out;
-                               delta -= off;
-                       }
-               } else {
-                       zio_t *zio = zio_root(dn->dn_objset->os_spa,
-                           NULL, NULL, ZIO_FLAG_CANFAIL);
-
-                       /* first level-0 block */
-                       start = off >> dn->dn_datablkshift;
-                       if (P2PHASE(off, dn->dn_datablksz) ||
-                           len < dn->dn_datablksz) {
-                               err = dmu_tx_check_ioerr(zio, dn, 0, start);
-                               if (err)
-                                       goto out;
-                       }
+       if (refcount_count(&txh->txh_space_towrite) > 2 * DMU_MAX_ACCESS)
+               err = SET_ERROR(EFBIG);
 
-                       /* last level-0 block */
-                       end = (off+len-1) >> dn->dn_datablkshift;
-                       if (end != start && end <= dn->dn_maxblkid &&
-                           P2PHASE(off+len, dn->dn_datablksz)) {
-                               err = dmu_tx_check_ioerr(zio, dn, 0, end);
-                               if (err)
-                                       goto out;
-                       }
+       if (dn == NULL)
+               return;
 
-                       /* level-1 blocks */
-                       if (nlvls > 1) {
-                               int shft = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
-                               for (i = (start>>shft)+1; i < end>>shft; i++) {
-                                       err = dmu_tx_check_ioerr(zio, dn, 1, i);
-                                       if (err)
-                                               goto out;
-                               }
+       /*
+        * For i/o error checking, read the blocks that will be needed
+        * to perform the write: the first and last level-0 blocks (if
+        * they are not aligned, i.e. if they are partial-block writes),
+        * and all the level-1 blocks.
+        */
+       if (dn->dn_maxblkid == 0) {
+               if (off < dn->dn_datablksz &&
+                   (off > 0 || len < dn->dn_datablksz)) {
+                       err = dmu_tx_check_ioerr(NULL, dn, 0, 0);
+                       if (err != 0) {
+                               txh->txh_tx->tx_err = err;
                        }
-
-                       err = zio_wait(zio);
-                       if (err)
-                               goto out;
-                       delta = P2NPHASE(off, dn->dn_datablksz);
-               }
-
-               min_ibs = max_ibs = dn->dn_indblkshift;
-               if (dn->dn_maxblkid > 0) {
-                       /*
-                        * The blocksize can't change,
-                        * so we can make a more precise estimate.
-                        */
-                       ASSERT(dn->dn_datablkshift != 0);
-                       min_bs = max_bs = dn->dn_datablkshift;
                }
+       } else {
+               zio_t *zio = zio_root(dn->dn_objset->os_spa,
+                   NULL, NULL, ZIO_FLAG_CANFAIL);
 
-               /*
-                * If this write is not off the end of the file
-                * we need to account for overwrites/unref.
-                */
-               if (start <= dn->dn_maxblkid) {
-                       for (l = 0; l < DN_MAX_LEVELS; l++)
-                               history[l] = -1ULL;
+               /* first level-0 block */
+               uint64_t start = off >> dn->dn_datablkshift;
+               if (P2PHASE(off, dn->dn_datablksz) || len < dn->dn_datablksz) {
+                       err = dmu_tx_check_ioerr(zio, dn, 0, start);
+                       if (err != 0) {
+                               txh->txh_tx->tx_err = err;
+                       }
                }
-               while (start <= dn->dn_maxblkid) {
-                       dmu_buf_impl_t *db;
 
-                       rw_enter(&dn->dn_struct_rwlock, RW_READER);
-                       err = dbuf_hold_impl(dn, 0, start, FALSE, FTAG, &db);
-                       rw_exit(&dn->dn_struct_rwlock);
-
-                       if (err) {
+               /* last level-0 block */
+               uint64_t end = (off + len - 1) >> dn->dn_datablkshift;
+               if (end != start && end <= dn->dn_maxblkid &&
+                   P2PHASE(off + len, dn->dn_datablksz)) {
+                       err = dmu_tx_check_ioerr(zio, dn, 0, end);
+                       if (err != 0) {
                                txh->txh_tx->tx_err = err;
-                               return;
                        }
+               }
 
-                       dmu_tx_count_twig(txh, dn, db, 0, start, B_FALSE,
-                           history);
-                       dbuf_rele(db, FTAG);
-                       if (++start > end) {
-                               /*
-                                * Account for new indirects appearing
-                                * before this IO gets assigned into a txg.
-                                */
-                               bits = 64 - min_bs;
-                               epbs = min_ibs - SPA_BLKPTRSHIFT;
-                               for (bits -= epbs * (nlvls - 1);
-                                   bits >= 0; bits -= epbs)
-                                       txh->txh_fudge += 1ULL << max_ibs;
-                               goto out;
+               /* level-1 blocks */
+               if (dn->dn_nlevels > 1) {
+                       int shft = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
+                       for (uint64_t i = (start >> shft) + 1;
+                           i < end >> shft; i++) {
+                               err = dmu_tx_check_ioerr(zio, dn, 1, i);
+                               if (err != 0) {
+                                       txh->txh_tx->tx_err = err;
+                               }
                        }
-                       off += delta;
-                       if (len >= delta)
-                               len -= delta;
-                       delta = dn->dn_datablksz;
                }
-       }
-
-       /*
-        * 'end' is the last thing we will access, not one past.
-        * This way we won't overflow when accessing the last byte.
-        */
-       start = P2ALIGN(off, 1ULL << max_bs);
-       end = P2ROUNDUP(off + len, 1ULL << max_bs) - 1;
-       txh->txh_space_towrite += end - start + 1;
 
-       start >>= min_bs;
-       end >>= min_bs;
-
-       epbs = min_ibs - SPA_BLKPTRSHIFT;
-
-       /*
-        * The object contains at most 2^(64 - min_bs) blocks,
-        * and each indirect level maps 2^epbs.
-        */
-       for (bits = 64 - min_bs; bits >= 0; bits -= epbs) {
-               start >>= epbs;
-               end >>= epbs;
-               ASSERT3U(end, >=, start);
-               txh->txh_space_towrite += (end - start + 1) << max_ibs;
-               if (start != 0) {
-                       /*
-                        * We also need a new blkid=0 indirect block
-                        * to reference any existing file data.
-                        */
-                       txh->txh_space_towrite += 1ULL << max_ibs;
+               err = zio_wait(zio);
+               if (err != 0) {
+                       txh->txh_tx->tx_err = err;
                }
        }
-
-out:
-       if (txh->txh_space_towrite + txh->txh_space_tooverwrite >
-           2 * DMU_MAX_ACCESS)
-               err = SET_ERROR(EFBIG);
-
-       if (err)
-               txh->txh_tx->tx_err = err;
 }
 
 static void
 dmu_tx_count_dnode(dmu_tx_hold_t *txh)
 {
-       dnode_t *dn = txh->txh_dnode;
-       dnode_t *mdn = DMU_META_DNODE(txh->txh_tx->tx_objset);
-       uint64_t space = mdn->dn_datablksz +
-           ((mdn->dn_nlevels-1) << mdn->dn_indblkshift);
-
-       if (dn && dn->dn_dbuf->db_blkptr &&
-           dsl_dataset_block_freeable(dn->dn_objset->os_dsl_dataset,
-           dn->dn_dbuf->db_blkptr, dn->dn_dbuf->db_blkptr->blk_birth)) {
-               txh->txh_space_tooverwrite += space;
-               txh->txh_space_tounref += space;
-       } else {
-               txh->txh_space_towrite += space;
-               if (dn && dn->dn_dbuf->db_blkptr)
-                       txh->txh_space_tounref += space;
-       }
+       (void) refcount_add_many(&txh->txh_space_towrite, DNODE_MIN_SIZE, FTAG);
 }
 
 void
@@ -418,342 +303,234 @@ dmu_tx_hold_write(dmu_tx_t *tx, uint64_t object, uint64_t off, int len)
 {
        dmu_tx_hold_t *txh;
 
-       ASSERT(tx->tx_txg == 0);
-       ASSERT(len < DMU_MAX_ACCESS);
+       ASSERT0(tx->tx_txg);
+       ASSERT3U(len, <=, DMU_MAX_ACCESS);
        ASSERT(len == 0 || UINT64_MAX - off >= len - 1);
 
        txh = dmu_tx_hold_object_impl(tx, tx->tx_objset,
            object, THT_WRITE, off, len);
-       if (txh == NULL)
-               return;
-
-       dmu_tx_count_write(txh, off, len);
-       dmu_tx_count_dnode(txh);
+       if (txh != NULL) {
+               dmu_tx_count_write(txh, off, len);
+               dmu_tx_count_dnode(txh);
+       }
 }
 
-static void
-dmu_tx_count_free(dmu_tx_hold_t *txh, uint64_t off, uint64_t len)
+void
+dmu_tx_hold_write_by_dnode(dmu_tx_t *tx, dnode_t *dn, uint64_t off, int len)
 {
-       uint64_t blkid, nblks, lastblk;
-       uint64_t space = 0, unref = 0, skipped = 0;
-       dnode_t *dn = txh->txh_dnode;
-       dsl_dataset_t *ds = dn->dn_objset->os_dsl_dataset;
-       spa_t *spa = txh->txh_tx->tx_pool->dp_spa;
-       int epbs;
-       uint64_t l0span = 0, nl1blks = 0;
-
-       if (dn->dn_nlevels == 0)
-               return;
-
-       /*
-        * The struct_rwlock protects us against dn_nlevels
-        * changing, in case (against all odds) we manage to dirty &
-        * sync out the changes after we check for being dirty.
-        * Also, dbuf_hold_impl() wants us to have the struct_rwlock.
-        */
-       rw_enter(&dn->dn_struct_rwlock, RW_READER);
-       epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
-       if (dn->dn_maxblkid == 0) {
-               if (off == 0 && len >= dn->dn_datablksz) {
-                       blkid = 0;
-                       nblks = 1;
-               } else {
-                       rw_exit(&dn->dn_struct_rwlock);
-                       return;
-               }
-       } else {
-               blkid = off >> dn->dn_datablkshift;
-               nblks = (len + dn->dn_datablksz - 1) >> dn->dn_datablkshift;
-
-               if (blkid >= dn->dn_maxblkid) {
-                       rw_exit(&dn->dn_struct_rwlock);
-                       return;
-               }
-               if (blkid + nblks > dn->dn_maxblkid)
-                       nblks = dn->dn_maxblkid - blkid;
-
-       }
-       l0span = nblks;    /* save for later use to calc level > 1 overhead */
-       if (dn->dn_nlevels == 1) {
-               int i;
-               for (i = 0; i < nblks; i++) {
-                       blkptr_t *bp = dn->dn_phys->dn_blkptr;
-                       ASSERT3U(blkid + i, <, dn->dn_nblkptr);
-                       bp += blkid + i;
-                       if (dsl_dataset_block_freeable(ds, bp, bp->blk_birth)) {
-                               dprintf_bp(bp, "can free old%s", "");
-                               space += bp_get_dsize(spa, bp);
-                       }
-                       unref += BP_GET_ASIZE(bp);
-               }
-               nl1blks = 1;
-               nblks = 0;
-       }
-
-       lastblk = blkid + nblks - 1;
-       while (nblks) {
-               dmu_buf_impl_t *dbuf;
-               uint64_t ibyte, new_blkid;
-               int epb = 1 << epbs;
-               int err, i, blkoff, tochk;
-               blkptr_t *bp;
-
-               ibyte = blkid << dn->dn_datablkshift;
-               err = dnode_next_offset(dn,
-                   DNODE_FIND_HAVELOCK, &ibyte, 2, 1, 0);
-               new_blkid = ibyte >> dn->dn_datablkshift;
-               if (err == ESRCH) {
-                       skipped += (lastblk >> epbs) - (blkid >> epbs) + 1;
-                       break;
-               }
-               if (err) {
-                       txh->txh_tx->tx_err = err;
-                       break;
-               }
-               if (new_blkid > lastblk) {
-                       skipped += (lastblk >> epbs) - (blkid >> epbs) + 1;
-                       break;
-               }
-
-               if (new_blkid > blkid) {
-                       ASSERT((new_blkid >> epbs) > (blkid >> epbs));
-                       skipped += (new_blkid >> epbs) - (blkid >> epbs) - 1;
-                       nblks -= new_blkid - blkid;
-                       blkid = new_blkid;
-               }
-               blkoff = P2PHASE(blkid, epb);
-               tochk = MIN(epb - blkoff, nblks);
-
-               err = dbuf_hold_impl(dn, 1, blkid >> epbs, FALSE, FTAG, &dbuf);
-               if (err) {
-                       txh->txh_tx->tx_err = err;
-                       break;
-               }
-
-               txh->txh_memory_tohold += dbuf->db.db_size;
-
-               /*
-                * We don't check memory_tohold against DMU_MAX_ACCESS because
-                * memory_tohold is an over-estimation (especially the >L1
-                * indirect blocks), so it could fail.  Callers should have
-                * already verified that they will not be holding too much
-                * memory.
-                */
-
-               err = dbuf_read(dbuf, NULL, DB_RF_HAVESTRUCT | DB_RF_CANFAIL);
-               if (err != 0) {
-                       txh->txh_tx->tx_err = err;
-                       dbuf_rele(dbuf, FTAG);
-                       break;
-               }
-
-               bp = dbuf->db.db_data;
-               bp += blkoff;
-
-               for (i = 0; i < tochk; i++) {
-                       if (dsl_dataset_block_freeable(ds, &bp[i],
-                           bp[i].blk_birth)) {
-                               dprintf_bp(&bp[i], "can free old%s", "");
-                               space += bp_get_dsize(spa, &bp[i]);
-                       }
-                       unref += BP_GET_ASIZE(bp);
-               }
-               dbuf_rele(dbuf, FTAG);
-
-               ++nl1blks;
-               blkid += tochk;
-               nblks -= tochk;
-       }
-       rw_exit(&dn->dn_struct_rwlock);
-
-       /*
-        * Add in memory requirements of higher-level indirects.
-        * This assumes a worst-possible scenario for dn_nlevels and a
-        * worst-possible distribution of l1-blocks over the region to free.
-        */
-       {
-               uint64_t blkcnt = 1 + ((l0span >> epbs) >> epbs);
-               int level = 2;
-               /*
-                * Here we don't use DN_MAX_LEVEL, but calculate it with the
-                * given datablkshift and indblkshift. This makes the
-                * difference between 19 and 8 on large files.
-                */
-               int maxlevel = 2 + (DN_MAX_OFFSET_SHIFT - dn->dn_datablkshift) /
-                   (dn->dn_indblkshift - SPA_BLKPTRSHIFT);
+       dmu_tx_hold_t *txh;
 
-               while (level++ < maxlevel) {
-                       txh->txh_memory_tohold += MAX(MIN(blkcnt, nl1blks), 1)
-                           << dn->dn_indblkshift;
-                       blkcnt = 1 + (blkcnt >> epbs);
-               }
-       }
+       ASSERT0(tx->tx_txg);
+       ASSERT3U(len, <=, DMU_MAX_ACCESS);
+       ASSERT(len == 0 || UINT64_MAX - off >= len - 1);
 
-       /* account for new level 1 indirect blocks that might show up */
-       if (skipped > 0) {
-               txh->txh_fudge += skipped << dn->dn_indblkshift;
-               skipped = MIN(skipped, DMU_MAX_DELETEBLKCNT >> epbs);
-               txh->txh_memory_tohold += skipped << dn->dn_indblkshift;
+       txh = dmu_tx_hold_dnode_impl(tx, dn, THT_WRITE, off, len);
+       if (txh != NULL) {
+               dmu_tx_count_write(txh, off, len);
+               dmu_tx_count_dnode(txh);
        }
-       txh->txh_space_tofree += space;
-       txh->txh_space_tounref += unref;
 }
 
+/*
+ * This function marks the transaction as being a "net free".  The end
+ * result is that refquotas will be disabled for this transaction, and
+ * this transaction will be able to use half of the pool space overhead
+ * (see dsl_pool_adjustedsize()).  Therefore this function should only
+ * be called for transactions that we expect will not cause a net increase
+ * in the amount of space used (but it's OK if that is occasionally not true).
+ */
 void
-dmu_tx_hold_free(dmu_tx_t *tx, uint64_t object, uint64_t off, uint64_t len)
+dmu_tx_mark_netfree(dmu_tx_t *tx)
 {
-       dmu_tx_hold_t *txh;
-       dnode_t *dn;
-       uint64_t start, end, i;
-       int err, shift;
-       zio_t *zio;
-
-       ASSERT(tx->tx_txg == 0);
+       tx->tx_netfree = B_TRUE;
+}
 
-       txh = dmu_tx_hold_object_impl(tx, tx->tx_objset,
-           object, THT_FREE, off, len);
-       if (txh == NULL)
-               return;
-       dn = txh->txh_dnode;
+static void
+dmu_tx_hold_free_impl(dmu_tx_hold_t *txh, uint64_t off, uint64_t len)
+{
+       dmu_tx_t *tx = txh->txh_tx;
+       dnode_t *dn = txh->txh_dnode;
+       int err;
 
-       /* first block */
-       if (off != 0)
-               dmu_tx_count_write(txh, off, 1);
-       /* last block */
-       if (len != DMU_OBJECT_END)
-               dmu_tx_count_write(txh, off+len, 1);
+       ASSERT(tx->tx_txg == 0);
 
        dmu_tx_count_dnode(txh);
 
-       if (off >= (dn->dn_maxblkid+1) * dn->dn_datablksz)
+       if (off >= (dn->dn_maxblkid + 1) * dn->dn_datablksz)
                return;
        if (len == DMU_OBJECT_END)
-               len = (dn->dn_maxblkid+1) * dn->dn_datablksz - off;
+               len = (dn->dn_maxblkid + 1) * dn->dn_datablksz - off;
+
+       dmu_tx_count_dnode(txh);
+
+       /*
+        * For i/o error checking, we read the first and last level-0
+        * blocks if they are not aligned, and all the level-1 blocks.
+        *
+        * Note:  dbuf_free_range() assumes that we have not instantiated
+        * any level-0 dbufs that will be completely freed.  Therefore we must
+        * exercise care to not read or count the first and last blocks
+        * if they are blocksize-aligned.
+        */
+       if (dn->dn_datablkshift == 0) {
+               if (off != 0 || len < dn->dn_datablksz)
+                       dmu_tx_count_write(txh, 0, dn->dn_datablksz);
+       } else {
+               /* first block will be modified if it is not aligned */
+               if (!IS_P2ALIGNED(off, 1 << dn->dn_datablkshift))
+                       dmu_tx_count_write(txh, off, 1);
+               /* last block will be modified if it is not aligned */
+               if (!IS_P2ALIGNED(off + len, 1 << dn->dn_datablkshift))
+                       dmu_tx_count_write(txh, off + len, 1);
+       }
 
        /*
-        * For i/o error checking, read the first and last level-0
-        * blocks, and all the level-1 blocks.  The above count_write's
-        * have already taken care of the level-0 blocks.
+        * Check level-1 blocks.
         */
        if (dn->dn_nlevels > 1) {
-               shift = dn->dn_datablkshift + dn->dn_indblkshift -
+               int shift = dn->dn_datablkshift + dn->dn_indblkshift -
                    SPA_BLKPTRSHIFT;
-               start = off >> shift;
-               end = dn->dn_datablkshift ? ((off+len) >> shift) : 0;
+               uint64_t start = off >> shift;
+               uint64_t end = (off + len) >> shift;
+               uint64_t i;
+
+               ASSERT(dn->dn_indblkshift != 0);
+
+               /*
+                * dnode_reallocate() can result in an object with indirect
+                * blocks having an odd data block size.  In this case,
+                * just check the single block.
+                */
+               if (dn->dn_datablkshift == 0)
+                       start = end = 0;
 
-               zio = zio_root(tx->tx_pool->dp_spa,
+               zio_t *zio = zio_root(tx->tx_pool->dp_spa,
                    NULL, NULL, ZIO_FLAG_CANFAIL);
                for (i = start; i <= end; i++) {
                        uint64_t ibyte = i << shift;
                        err = dnode_next_offset(dn, 0, &ibyte, 2, 1, 0);
                        i = ibyte >> shift;
-                       if (err == ESRCH)
+                       if (err == ESRCH || i > end)
                                break;
-                       if (err) {
+                       if (err != 0) {
                                tx->tx_err = err;
+                               (void) zio_wait(zio);
                                return;
                        }
 
+                       (void) refcount_add_many(&txh->txh_memory_tohold,
+                           1 << dn->dn_indblkshift, FTAG);
+
                        err = dmu_tx_check_ioerr(zio, dn, 1, i);
-                       if (err) {
+                       if (err != 0) {
                                tx->tx_err = err;
+                               (void) zio_wait(zio);
                                return;
                        }
                }
                err = zio_wait(zio);
-               if (err) {
+               if (err != 0) {
                        tx->tx_err = err;
                        return;
                }
        }
+}
+
+void
+dmu_tx_hold_free(dmu_tx_t *tx, uint64_t object, uint64_t off, uint64_t len)
+{
+       dmu_tx_hold_t *txh;
 
-       dmu_tx_count_free(txh, off, len);
+       txh = dmu_tx_hold_object_impl(tx, tx->tx_objset,
+           object, THT_FREE, off, len);
+       if (txh != NULL)
+               (void) dmu_tx_hold_free_impl(txh, off, len);
 }
 
 void
-dmu_tx_hold_zap(dmu_tx_t *tx, uint64_t object, int add, const char *name)
+dmu_tx_hold_free_by_dnode(dmu_tx_t *tx, dnode_t *dn, uint64_t off, uint64_t len)
 {
        dmu_tx_hold_t *txh;
-       dnode_t *dn;
-       uint64_t nblocks;
-       int epbs, err;
 
-       ASSERT(tx->tx_txg == 0);
+       txh = dmu_tx_hold_dnode_impl(tx, dn, THT_FREE, off, len);
+       if (txh != NULL)
+               (void) dmu_tx_hold_free_impl(txh, off, len);
+}
 
-       txh = dmu_tx_hold_object_impl(tx, tx->tx_objset,
-           object, THT_ZAP, add, (uintptr_t)name);
-       if (txh == NULL)
-               return;
-       dn = txh->txh_dnode;
+static void
+dmu_tx_hold_zap_impl(dmu_tx_hold_t *txh, const char *name)
+{
+       dmu_tx_t *tx = txh->txh_tx;
+       dnode_t *dn = txh->txh_dnode;
+       int err;
+
+       ASSERT(tx->tx_txg == 0);
 
        dmu_tx_count_dnode(txh);
 
-       if (dn == NULL) {
-               /*
-                * We will be able to fit a new object's entries into one leaf
-                * block.  So there will be at most 2 blocks total,
-                * including the header block.
-                */
-               dmu_tx_count_write(txh, 0, 2 << fzap_default_block_shift);
+       /*
+        * Modifying a almost-full microzap is around the worst case (128KB)
+        *
+        * If it is a fat zap, the worst case would be 7*16KB=112KB:
+        * - 3 blocks overwritten: target leaf, ptrtbl block, header block
+        * - 4 new blocks written if adding:
+        *    - 2 blocks for possibly split leaves,
+        *    - 2 grown ptrtbl blocks
+        */
+       (void) refcount_add_many(&txh->txh_space_towrite,
+           MZAP_MAX_BLKSZ, FTAG);
+
+       if (dn == NULL)
                return;
-       }
 
        ASSERT3U(DMU_OT_BYTESWAP(dn->dn_type), ==, DMU_BSWAP_ZAP);
 
-       if (dn->dn_maxblkid == 0 && !add) {
-               blkptr_t *bp;
-
+       if (dn->dn_maxblkid == 0 || name == NULL) {
                /*
-                * If there is only one block  (i.e. this is a micro-zap)
-                * and we are not adding anything, the accounting is simple.
+                * This is a microzap (only one block), or we don't know
+                * the name.  Check the first block for i/o errors.
                 */
                err = dmu_tx_check_ioerr(NULL, dn, 0, 0);
-               if (err) {
+               if (err != 0) {
                        tx->tx_err = err;
-                       return;
                }
-
-               /*
-                * Use max block size here, since we don't know how much
-                * the size will change between now and the dbuf dirty call.
-                */
-               bp = &dn->dn_phys->dn_blkptr[0];
-               if (dsl_dataset_block_freeable(dn->dn_objset->os_dsl_dataset,
-                   bp, bp->blk_birth))
-                       txh->txh_space_tooverwrite += SPA_MAXBLOCKSIZE;
-               else
-                       txh->txh_space_towrite += SPA_MAXBLOCKSIZE;
-               if (!BP_IS_HOLE(bp))
-                       txh->txh_space_tounref += SPA_MAXBLOCKSIZE;
-               return;
-       }
-
-       if (dn->dn_maxblkid > 0 && name) {
+       } else {
                /*
-                * access the name in this fat-zap so that we'll check
-                * for i/o errors to the leaf blocks, etc.
+                * Access the name so that we'll check for i/o errors to
+                * the leaf blocks, etc.  We ignore ENOENT, as this name
+                * may not yet exist.
                 */
-               err = zap_lookup(dn->dn_objset, dn->dn_object, name,
-                   8, 0, NULL);
-               if (err == EIO) {
+               err = zap_lookup_by_dnode(dn, name, 8, 0, NULL);
+               if (err == EIO || err == ECKSUM || err == ENXIO) {
                        tx->tx_err = err;
-                       return;
                }
        }
+}
 
-       err = zap_count_write(dn->dn_objset, dn->dn_object, name, add,
-           &txh->txh_space_towrite, &txh->txh_space_tooverwrite);
+void
+dmu_tx_hold_zap(dmu_tx_t *tx, uint64_t object, int add, const char *name)
+{
+       dmu_tx_hold_t *txh;
 
-       /*
-        * If the modified blocks are scattered to the four winds,
-        * we'll have to modify an indirect twig for each.
-        */
-       epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
-       for (nblocks = dn->dn_maxblkid >> epbs; nblocks != 0; nblocks >>= epbs)
-               if (dn->dn_objset->os_dsl_dataset->ds_phys->ds_prev_snap_obj)
-                       txh->txh_space_towrite += 3 << dn->dn_indblkshift;
-               else
-                       txh->txh_space_tooverwrite += 3 << dn->dn_indblkshift;
+       ASSERT0(tx->tx_txg);
+
+       txh = dmu_tx_hold_object_impl(tx, tx->tx_objset,
+           object, THT_ZAP, add, (uintptr_t)name);
+       if (txh != NULL)
+               dmu_tx_hold_zap_impl(txh, name);
+}
+
+void
+dmu_tx_hold_zap_by_dnode(dmu_tx_t *tx, dnode_t *dn, int add, const char *name)
+{
+       dmu_tx_hold_t *txh;
+
+       ASSERT0(tx->tx_txg);
+       ASSERT(dn != NULL);
+
+       txh = dmu_tx_hold_dnode_impl(tx, dn, THT_ZAP, add, (uintptr_t)name);
+       if (txh != NULL)
+               dmu_tx_hold_zap_impl(txh, name);
 }
 
 void
@@ -770,55 +547,39 @@ dmu_tx_hold_bonus(dmu_tx_t *tx, uint64_t object)
 }
 
 void
-dmu_tx_hold_space(dmu_tx_t *tx, uint64_t space)
+dmu_tx_hold_bonus_by_dnode(dmu_tx_t *tx, dnode_t *dn)
 {
        dmu_tx_hold_t *txh;
 
-       ASSERT(tx->tx_txg == 0);
+       ASSERT0(tx->tx_txg);
 
-       txh = dmu_tx_hold_object_impl(tx, tx->tx_objset,
-           DMU_NEW_OBJECT, THT_SPACE, space, 0);
+       txh = dmu_tx_hold_dnode_impl(tx, dn, THT_BONUS, 0, 0);
        if (txh)
-               txh->txh_space_towrite += space;
+               dmu_tx_count_dnode(txh);
 }
 
-int
-dmu_tx_holds(dmu_tx_t *tx, uint64_t object)
+void
+dmu_tx_hold_space(dmu_tx_t *tx, uint64_t space)
 {
        dmu_tx_hold_t *txh;
-       int holds = 0;
 
-       /*
-        * By asserting that the tx is assigned, we're counting the
-        * number of dn_tx_holds, which is the same as the number of
-        * dn_holds.  Otherwise, we'd be counting dn_holds, but
-        * dn_tx_holds could be 0.
-        */
-       ASSERT(tx->tx_txg != 0);
-
-       /* if (tx->tx_anyobj == TRUE) */
-               /* return (0); */
-
-       for (txh = list_head(&tx->tx_holds); txh;
-           txh = list_next(&tx->tx_holds, txh)) {
-               if (txh->txh_dnode && txh->txh_dnode->dn_object == object)
-                       holds++;
-       }
+       ASSERT(tx->tx_txg == 0);
 
-       return (holds);
+       txh = dmu_tx_hold_object_impl(tx, tx->tx_objset,
+           DMU_NEW_OBJECT, THT_SPACE, space, 0);
+       if (txh)
+               (void) refcount_add_many(&txh->txh_space_towrite, space, FTAG);
 }
 
-#ifdef DEBUG_DMU_TX
+#ifdef ZFS_DEBUG
 void
 dmu_tx_dirty_buf(dmu_tx_t *tx, dmu_buf_impl_t *db)
 {
-       dmu_tx_hold_t *txh;
-       int match_object = FALSE, match_offset = FALSE;
-       dnode_t *dn;
+       boolean_t match_object = B_FALSE;
+       boolean_t match_offset = B_FALSE;
 
        DB_DNODE_ENTER(db);
-       dn = DB_DNODE(db);
-       ASSERT(dn != NULL);
+       dnode_t *dn = DB_DNODE(db);
        ASSERT(tx->tx_txg != 0);
        ASSERT(tx->tx_objset == NULL || dn->dn_objset == tx->tx_objset);
        ASSERT3U(dn->dn_object, ==, db->db.db_object);
@@ -834,7 +595,7 @@ dmu_tx_dirty_buf(dmu_tx_t *tx, dmu_buf_impl_t *db)
                return;
        }
 
-       for (txh = list_head(&tx->tx_holds); txh;
+       for (dmu_tx_hold_t *txh = list_head(&tx->tx_holds); txh != NULL;
            txh = list_next(&tx->tx_holds, txh)) {
                ASSERT3U(dn->dn_assigned_txg, ==, tx->tx_txg);
                if (txh->txh_dnode == dn && txh->txh_type != THT_NEWOBJECT)
@@ -901,7 +662,8 @@ dmu_tx_dirty_buf(dmu_tx_t *tx, dmu_buf_impl_t *db)
                                match_object = TRUE;
                                break;
                        default:
-                               ASSERT(!"bad txh_type");
+                               cmn_err(CE_PANIC, "bad txh_type %d",
+                                   txh->txh_type);
                        }
                }
                if (match_object && match_offset) {
@@ -916,13 +678,185 @@ dmu_tx_dirty_buf(dmu_tx_t *tx, dmu_buf_impl_t *db)
 }
 #endif
 
+/*
+ * If we can't do 10 iops, something is wrong.  Let us go ahead
+ * and hit zfs_dirty_data_max.
+ */
+hrtime_t zfs_delay_max_ns = 100 * MICROSEC; /* 100 milliseconds */
+int zfs_delay_resolution_ns = 100 * 1000; /* 100 microseconds */
+
+/*
+ * We delay transactions when we've determined that the backend storage
+ * isn't able to accommodate the rate of incoming writes.
+ *
+ * If there is already a transaction waiting, we delay relative to when
+ * that transaction finishes waiting.  This way the calculated min_time
+ * is independent of the number of threads concurrently executing
+ * transactions.
+ *
+ * If we are the only waiter, wait relative to when the transaction
+ * started, rather than the current time.  This credits the transaction for
+ * "time already served", e.g. reading indirect blocks.
+ *
+ * The minimum time for a transaction to take is calculated as:
+ *     min_time = scale * (dirty - min) / (max - dirty)
+ *     min_time is then capped at zfs_delay_max_ns.
+ *
+ * The delay has two degrees of freedom that can be adjusted via tunables.
+ * The percentage of dirty data at which we start to delay is defined by
+ * zfs_delay_min_dirty_percent. This should typically be at or above
+ * zfs_vdev_async_write_active_max_dirty_percent so that we only start to
+ * delay after writing at full speed has failed to keep up with the incoming
+ * write rate. The scale of the curve is defined by zfs_delay_scale. Roughly
+ * speaking, this variable determines the amount of delay at the midpoint of
+ * the curve.
+ *
+ * delay
+ *  10ms +-------------------------------------------------------------*+
+ *       |                                                             *|
+ *   9ms +                                                             *+
+ *       |                                                             *|
+ *   8ms +                                                             *+
+ *       |                                                            * |
+ *   7ms +                                                            * +
+ *       |                                                            * |
+ *   6ms +                                                            * +
+ *       |                                                            * |
+ *   5ms +                                                           *  +
+ *       |                                                           *  |
+ *   4ms +                                                           *  +
+ *       |                                                           *  |
+ *   3ms +                                                          *   +
+ *       |                                                          *   |
+ *   2ms +                                              (midpoint) *    +
+ *       |                                                  |    **     |
+ *   1ms +                                                  v ***       +
+ *       |             zfs_delay_scale ---------->     ********         |
+ *     0 +-------------------------------------*********----------------+
+ *       0%                    <- zfs_dirty_data_max ->               100%
+ *
+ * Note that since the delay is added to the outstanding time remaining on the
+ * most recent transaction, the delay is effectively the inverse of IOPS.
+ * Here the midpoint of 500us translates to 2000 IOPS. The shape of the curve
+ * was chosen such that small changes in the amount of accumulated dirty data
+ * in the first 3/4 of the curve yield relatively small differences in the
+ * amount of delay.
+ *
+ * The effects can be easier to understand when the amount of delay is
+ * represented on a log scale:
+ *
+ * delay
+ * 100ms +-------------------------------------------------------------++
+ *       +                                                              +
+ *       |                                                              |
+ *       +                                                             *+
+ *  10ms +                                                             *+
+ *       +                                                           ** +
+ *       |                                              (midpoint)  **  |
+ *       +                                                  |     **    +
+ *   1ms +                                                  v ****      +
+ *       +             zfs_delay_scale ---------->        *****         +
+ *       |                                             ****             |
+ *       +                                          ****                +
+ * 100us +                                        **                    +
+ *       +                                       *                      +
+ *       |                                      *                       |
+ *       +                                     *                        +
+ *  10us +                                     *                        +
+ *       +                                                              +
+ *       |                                                              |
+ *       +                                                              +
+ *       +--------------------------------------------------------------+
+ *       0%                    <- zfs_dirty_data_max ->               100%
+ *
+ * Note here that only as the amount of dirty data approaches its limit does
+ * the delay start to increase rapidly. The goal of a properly tuned system
+ * should be to keep the amount of dirty data out of that range by first
+ * ensuring that the appropriate limits are set for the I/O scheduler to reach
+ * optimal throughput on the backend storage, and then by changing the value
+ * of zfs_delay_scale to increase the steepness of the curve.
+ */
+static void
+dmu_tx_delay(dmu_tx_t *tx, uint64_t dirty)
+{
+       dsl_pool_t *dp = tx->tx_pool;
+       uint64_t delay_min_bytes =
+           zfs_dirty_data_max * zfs_delay_min_dirty_percent / 100;
+       hrtime_t wakeup, min_tx_time, now;
+
+       if (dirty <= delay_min_bytes)
+               return;
+
+       /*
+        * The caller has already waited until we are under the max.
+        * We make them pass us the amount of dirty data so we don't
+        * have to handle the case of it being >= the max, which could
+        * cause a divide-by-zero if it's == the max.
+        */
+       ASSERT3U(dirty, <, zfs_dirty_data_max);
+
+       now = gethrtime();
+       min_tx_time = zfs_delay_scale *
+           (dirty - delay_min_bytes) / (zfs_dirty_data_max - dirty);
+       min_tx_time = MIN(min_tx_time, zfs_delay_max_ns);
+       if (now > tx->tx_start + min_tx_time)
+               return;
+
+       DTRACE_PROBE3(delay__mintime, dmu_tx_t *, tx, uint64_t, dirty,
+           uint64_t, min_tx_time);
+
+       mutex_enter(&dp->dp_lock);
+       wakeup = MAX(tx->tx_start + min_tx_time,
+           dp->dp_last_wakeup + min_tx_time);
+       dp->dp_last_wakeup = wakeup;
+       mutex_exit(&dp->dp_lock);
+
+       zfs_sleep_until(wakeup);
+}
+
+/*
+ * This routine attempts to assign the transaction to a transaction group.
+ * To do so, we must determine if there is sufficient free space on disk.
+ *
+ * If this is a "netfree" transaction (i.e. we called dmu_tx_mark_netfree()
+ * on it), then it is assumed that there is sufficient free space,
+ * unless there's insufficient slop space in the pool (see the comment
+ * above spa_slop_shift in spa_misc.c).
+ *
+ * If it is not a "netfree" transaction, then if the data already on disk
+ * is over the allowed usage (e.g. quota), this will fail with EDQUOT or
+ * ENOSPC.  Otherwise, if the current rough estimate of pending changes,
+ * plus the rough estimate of this transaction's changes, may exceed the
+ * allowed usage, then this will fail with ERESTART, which will cause the
+ * caller to wait for the pending changes to be written to disk (by waiting
+ * for the next TXG to open), and then check the space usage again.
+ *
+ * The rough estimate of pending changes is comprised of the sum of:
+ *
+ *  - this transaction's holds' txh_space_towrite
+ *
+ *  - dd_tempreserved[], which is the sum of in-flight transactions'
+ *    holds' txh_space_towrite (i.e. those transactions that have called
+ *    dmu_tx_assign() but not yet called dmu_tx_commit()).
+ *
+ *  - dd_space_towrite[], which is the amount of dirtied dbufs.
+ *
+ * Note that all of these values are inflated by spa_get_worst_case_asize(),
+ * which means that we may get ERESTART well before we are actually in danger
+ * of running out of space, but this also mitigates any small inaccuracies
+ * in the rough estimate (e.g. txh_space_towrite doesn't take into account
+ * indirect blocks, and dd_space_towrite[] doesn't take into account changes
+ * to the MOS).
+ *
+ * Note that due to this algorithm, it is possible to exceed the allowed
+ * usage by one transaction.  Also, as we approach the allowed usage,
+ * we will allow a very limited amount of changes into each TXG, thus
+ * decreasing performance.
+ */
 static int
-dmu_tx_try_assign(dmu_tx_t *tx, txg_how_t txg_how)
+dmu_tx_try_assign(dmu_tx_t *tx, uint64_t txg_how)
 {
-       dmu_tx_hold_t *txh;
        spa_t *spa = tx->tx_pool->dp_spa;
-       uint64_t memory, asize, fsize, usize;
-       uint64_t towrite, tofree, tooverwrite, tounref, tohold, fudge;
 
        ASSERT0(tx->tx_txg);
 
@@ -944,12 +878,19 @@ dmu_tx_try_assign(dmu_tx_t *tx, txg_how_t txg_how)
                 * of the failuremode setting.
                 */
                if (spa_get_failmode(spa) == ZIO_FAILURE_MODE_CONTINUE &&
-                   txg_how != TXG_WAIT)
+                   !(txg_how & TXG_WAIT))
                        return (SET_ERROR(EIO));
 
                return (SET_ERROR(ERESTART));
        }
 
+       if (!tx->tx_dirty_delayed &&
+           dsl_pool_need_dirty_delay(tx->tx_pool)) {
+               tx->tx_wait_dirty = B_TRUE;
+               DMU_TX_STAT_BUMP(dmu_tx_dirty_delay);
+               return (ERESTART);
+       }
+
        tx->tx_txg = txg_hold_open(tx->tx_pool, &tx->tx_txgh);
        tx->tx_needassign_txh = NULL;
 
@@ -959,8 +900,9 @@ dmu_tx_try_assign(dmu_tx_t *tx, txg_how_t txg_how)
         * dmu_tx_unassign() logic.
         */
 
-       towrite = tofree = tooverwrite = tounref = tohold = fudge = 0;
-       for (txh = list_head(&tx->tx_holds); txh;
+       uint64_t towrite = 0;
+       uint64_t tohold = 0;
+       for (dmu_tx_hold_t *txh = list_head(&tx->tx_holds); txh != NULL;
            txh = list_next(&tx->tx_holds, txh)) {
                dnode_t *dn = txh->txh_dnode;
                if (dn != NULL) {
@@ -977,51 +919,19 @@ dmu_tx_try_assign(dmu_tx_t *tx, txg_how_t txg_how)
                        (void) refcount_add(&dn->dn_tx_holds, tx);
                        mutex_exit(&dn->dn_mtx);
                }
-               towrite += txh->txh_space_towrite;
-               tofree += txh->txh_space_tofree;
-               tooverwrite += txh->txh_space_tooverwrite;
-               tounref += txh->txh_space_tounref;
-               tohold += txh->txh_memory_tohold;
-               fudge += txh->txh_fudge;
-       }
-
-       /*
-        * If a snapshot has been taken since we made our estimates,
-        * assume that we won't be able to free or overwrite anything.
-        */
-       if (tx->tx_objset &&
-           dsl_dataset_prev_snap_txg(tx->tx_objset->os_dsl_dataset) >
-           tx->tx_lastsnap_txg) {
-               towrite += tooverwrite;
-               tooverwrite = tofree = 0;
+               towrite += refcount_count(&txh->txh_space_towrite);
+               tohold += refcount_count(&txh->txh_memory_tohold);
        }
 
        /* needed allocation: worst-case estimate of write space */
-       asize = spa_get_asize(tx->tx_pool->dp_spa, towrite + tooverwrite);
-       /* freed space estimate: worst-case overwrite + free estimate */
-       fsize = spa_get_asize(tx->tx_pool->dp_spa, tooverwrite) + tofree;
-       /* convert unrefd space to worst-case estimate */
-       usize = spa_get_asize(tx->tx_pool->dp_spa, tounref);
+       uint64_t asize = spa_get_worst_case_asize(tx->tx_pool->dp_spa, towrite);
        /* calculate memory footprint estimate */
-       memory = towrite + tooverwrite + tohold;
-
-#ifdef DEBUG_DMU_TX
-       /*
-        * Add in 'tohold' to account for our dirty holds on this memory
-        * XXX - the "fudge" factor is to account for skipped blocks that
-        * we missed because dnode_next_offset() misses in-core-only blocks.
-        */
-       tx->tx_space_towrite = asize +
-           spa_get_asize(tx->tx_pool->dp_spa, tohold + fudge);
-       tx->tx_space_tofree = tofree;
-       tx->tx_space_tooverwrite = tooverwrite;
-       tx->tx_space_tounref = tounref;
-#endif
+       uint64_t memory = towrite + tohold;
 
-       if (tx->tx_dir && asize != 0) {
+       if (tx->tx_dir != NULL && asize != 0) {
                int err = dsl_dir_tempreserve_space(tx->tx_dir, memory,
-                   asize, fsize, usize, &tx->tx_tempreserve_cookie, tx);
-               if (err)
+                   asize, tx->tx_netfree, &tx->tx_tempreserve_cookie, tx);
+               if (err != 0)
                        return (err);
        }
 
@@ -1033,14 +943,17 @@ dmu_tx_try_assign(dmu_tx_t *tx, txg_how_t txg_how)
 static void
 dmu_tx_unassign(dmu_tx_t *tx)
 {
-       dmu_tx_hold_t *txh;
-
        if (tx->tx_txg == 0)
                return;
 
        txg_rele_to_quiesce(&tx->tx_txgh);
 
-       for (txh = list_head(&tx->tx_holds); txh != tx->tx_needassign_txh;
+       /*
+        * Walk the transaction's hold list, removing the hold on the
+        * associated dnode, and notifying waiters if the refcount drops to 0.
+        */
+       for (dmu_tx_hold_t *txh = list_head(&tx->tx_holds);
+           txh && txh != tx->tx_needassign_txh;
            txh = list_next(&tx->tx_holds, txh)) {
                dnode_t *dn = txh->txh_dnode;
 
@@ -1063,36 +976,44 @@ dmu_tx_unassign(dmu_tx_t *tx)
 }
 
 /*
- * Assign tx to a transaction group.  txg_how can be one of:
+ * Assign tx to a transaction group; txg_how is a bitmask:
+ *
+ * If TXG_WAIT is set and the currently open txg is full, this function
+ * will wait until there's a new txg. This should be used when no locks
+ * are being held. With this bit set, this function will only fail if
+ * we're truly out of space (or over quota).
  *
- * (1) TXG_WAIT.  If the current open txg is full, waits until there's
- *     a new one.  This should be used when you're not holding locks.
- *     It will only fail if we're truly out of space (or over quota).
+ * If TXG_WAIT is *not* set and we can't assign into the currently open
+ * txg without blocking, this function will return immediately with
+ * ERESTART. This should be used whenever locks are being held.  On an
+ * ERESTART error, the caller should drop all locks, call dmu_tx_wait(),
+ * and try again.
  *
- * (2) TXG_NOWAIT.  If we can't assign into the current open txg without
- *     blocking, returns immediately with ERESTART.  This should be used
- *     whenever you're holding locks.  On an ERESTART error, the caller
- *     should drop locks, do a dmu_tx_wait(tx), and try again.
+ * If TXG_NOTHROTTLE is set, this indicates that this tx should not be
+ * delayed due on the ZFS Write Throttle (see comments in dsl_pool.c for
+ * details on the throttle). This is used by the VFS operations, after
+ * they have already called dmu_tx_wait() (though most likely on a
+ * different tx).
  */
 int
-dmu_tx_assign(dmu_tx_t *tx, txg_how_t txg_how)
+dmu_tx_assign(dmu_tx_t *tx, uint64_t txg_how)
 {
-       hrtime_t before;
        int err;
 
        ASSERT(tx->tx_txg == 0);
-       ASSERT(txg_how == TXG_WAIT || txg_how == TXG_NOWAIT);
+       ASSERT0(txg_how & ~(TXG_WAIT | TXG_NOTHROTTLE));
        ASSERT(!dsl_pool_sync_context(tx->tx_pool));
 
-       before = gethrtime();
-
        /* If we might wait, we must not hold the config lock. */
-       ASSERT(txg_how != TXG_WAIT || !dsl_pool_config_held(tx->tx_pool));
+       IMPLY((txg_how & TXG_WAIT), !dsl_pool_config_held(tx->tx_pool));
+
+       if ((txg_how & TXG_NOTHROTTLE))
+               tx->tx_dirty_delayed = B_TRUE;
 
        while ((err = dmu_tx_try_assign(tx, txg_how)) != 0) {
                dmu_tx_unassign(tx);
 
-               if (err != ERESTART || txg_how != TXG_WAIT)
+               if (err != ERESTART || !(txg_how & TXG_WAIT))
                        return (err);
 
                dmu_tx_wait(tx);
@@ -1100,8 +1021,6 @@ dmu_tx_assign(dmu_tx_t *tx, txg_how_t txg_how)
 
        txg_rele_to_quiesce(&tx->tx_txgh);
 
-       spa_tx_assign_add_nsecs(tx->tx_pool->dp_spa, gethrtime() - before);
-
        return (0);
 }
 
@@ -1109,17 +1028,50 @@ void
 dmu_tx_wait(dmu_tx_t *tx)
 {
        spa_t *spa = tx->tx_pool->dp_spa;
+       dsl_pool_t *dp = tx->tx_pool;
+       hrtime_t before;
 
        ASSERT(tx->tx_txg == 0);
        ASSERT(!dsl_pool_config_held(tx->tx_pool));
 
-       /*
-        * It's possible that the pool has become active after this thread
-        * has tried to obtain a tx. If that's the case then his
-        * tx_lasttried_txg would not have been assigned.
-        */
-       if (spa_suspended(spa) || tx->tx_lasttried_txg == 0) {
-               txg_wait_synced(tx->tx_pool, spa_last_synced_txg(spa) + 1);
+       before = gethrtime();
+
+       if (tx->tx_wait_dirty) {
+               uint64_t dirty;
+
+               /*
+                * dmu_tx_try_assign() has determined that we need to wait
+                * because we've consumed much or all of the dirty buffer
+                * space.
+                */
+               mutex_enter(&dp->dp_lock);
+               if (dp->dp_dirty_total >= zfs_dirty_data_max)
+                       DMU_TX_STAT_BUMP(dmu_tx_dirty_over_max);
+               while (dp->dp_dirty_total >= zfs_dirty_data_max)
+                       cv_wait(&dp->dp_spaceavail_cv, &dp->dp_lock);
+               dirty = dp->dp_dirty_total;
+               mutex_exit(&dp->dp_lock);
+
+               dmu_tx_delay(tx, dirty);
+
+               tx->tx_wait_dirty = B_FALSE;
+
+               /*
+                * Note: setting tx_dirty_delayed only has effect if the
+                * caller used TX_WAIT.  Otherwise they are going to
+                * destroy this tx and try again.  The common case,
+                * zfs_write(), uses TX_WAIT.
+                */
+               tx->tx_dirty_delayed = B_TRUE;
+       } else if (spa_suspended(spa) || tx->tx_lasttried_txg == 0) {
+               /*
+                * If the pool is suspended we need to wait until it
+                * is resumed.  Note that it's possible that the pool
+                * has become active after this thread has tried to
+                * obtain a tx.  If that's the case then tx_lasttried_txg
+                * would not have been set.
+                */
+               txg_wait_synced(dp, spa_last_synced_txg(spa) + 1);
        } else if (tx->tx_needassign_txh) {
                dnode_t *dn = tx->tx_needassign_txh->txh_dnode;
 
@@ -1129,25 +1081,37 @@ dmu_tx_wait(dmu_tx_t *tx)
                mutex_exit(&dn->dn_mtx);
                tx->tx_needassign_txh = NULL;
        } else {
+               /*
+                * A dnode is assigned to the quiescing txg.  Wait for its
+                * transaction to complete.
+                */
                txg_wait_open(tx->tx_pool, tx->tx_lasttried_txg + 1);
        }
+
+       spa_tx_assign_add_nsecs(spa, gethrtime() - before);
 }
 
-void
-dmu_tx_willuse_space(dmu_tx_t *tx, int64_t delta)
+static void
+dmu_tx_destroy(dmu_tx_t *tx)
 {
-#ifdef DEBUG_DMU_TX
-       if (tx->tx_dir == NULL || delta == 0)
-               return;
+       dmu_tx_hold_t *txh;
 
-       if (delta > 0) {
-               ASSERT3U(refcount_count(&tx->tx_space_written) + delta, <=,
-                   tx->tx_space_towrite);
-               (void) refcount_add_many(&tx->tx_space_written, delta, NULL);
-       } else {
-               (void) refcount_add_many(&tx->tx_space_freed, -delta, NULL);
+       while ((txh = list_head(&tx->tx_holds)) != NULL) {
+               dnode_t *dn = txh->txh_dnode;
+
+               list_remove(&tx->tx_holds, txh);
+               refcount_destroy_many(&txh->txh_space_towrite,
+                   refcount_count(&txh->txh_space_towrite));
+               refcount_destroy_many(&txh->txh_memory_tohold,
+                   refcount_count(&txh->txh_memory_tohold));
+               kmem_free(txh, sizeof (dmu_tx_hold_t));
+               if (dn != NULL)
+                       dnode_rele(dn, tx);
        }
-#endif
+
+       list_destroy(&tx->tx_callbacks);
+       list_destroy(&tx->tx_holds);
+       kmem_free(tx, sizeof (dmu_tx_t));
 }
 
 void
@@ -1157,13 +1121,17 @@ dmu_tx_commit(dmu_tx_t *tx)
 
        ASSERT(tx->tx_txg != 0);
 
-       while ((txh = list_head(&tx->tx_holds))) {
+       /*
+        * Go through the transaction's hold list and remove holds on
+        * associated dnodes, notifying waiters if no holds remain.
+        */
+       for (txh = list_head(&tx->tx_holds); txh != NULL;
+           txh = list_next(&tx->tx_holds, txh)) {
                dnode_t *dn = txh->txh_dnode;
 
-               list_remove(&tx->tx_holds, txh);
-               kmem_free(txh, sizeof (dmu_tx_hold_t));
                if (dn == NULL)
                        continue;
+
                mutex_enter(&dn->dn_mtx);
                ASSERT3U(dn->dn_assigned_txg, ==, tx->tx_txg);
 
@@ -1172,7 +1140,6 @@ dmu_tx_commit(dmu_tx_t *tx)
                        cv_broadcast(&dn->dn_notxholds);
                }
                mutex_exit(&dn->dn_mtx);
-               dnode_rele(dn, tx);
        }
 
        if (tx->tx_tempreserve_cookie)
@@ -1184,51 +1151,21 @@ dmu_tx_commit(dmu_tx_t *tx)
        if (tx->tx_anyobj == FALSE)
                txg_rele_to_sync(&tx->tx_txgh);
 
-       list_destroy(&tx->tx_callbacks);
-       list_destroy(&tx->tx_holds);
-#ifdef DEBUG_DMU_TX
-       dprintf("towrite=%llu written=%llu tofree=%llu freed=%llu\n",
-           tx->tx_space_towrite, refcount_count(&tx->tx_space_written),
-           tx->tx_space_tofree, refcount_count(&tx->tx_space_freed));
-       refcount_destroy_many(&tx->tx_space_written,
-           refcount_count(&tx->tx_space_written));
-       refcount_destroy_many(&tx->tx_space_freed,
-           refcount_count(&tx->tx_space_freed));
-#endif
-       kmem_free(tx, sizeof (dmu_tx_t));
+       dmu_tx_destroy(tx);
 }
 
 void
 dmu_tx_abort(dmu_tx_t *tx)
 {
-       dmu_tx_hold_t *txh;
-
        ASSERT(tx->tx_txg == 0);
 
-       while ((txh = list_head(&tx->tx_holds))) {
-               dnode_t *dn = txh->txh_dnode;
-
-               list_remove(&tx->tx_holds, txh);
-               kmem_free(txh, sizeof (dmu_tx_hold_t));
-               if (dn != NULL)
-                       dnode_rele(dn, tx);
-       }
-
        /*
         * Call any registered callbacks with an error code.
         */
        if (!list_is_empty(&tx->tx_callbacks))
                dmu_tx_do_callbacks(&tx->tx_callbacks, ECANCELED);
 
-       list_destroy(&tx->tx_callbacks);
-       list_destroy(&tx->tx_holds);
-#ifdef DEBUG_DMU_TX
-       refcount_destroy_many(&tx->tx_space_written,
-           refcount_count(&tx->tx_space_written));
-       refcount_destroy_many(&tx->tx_space_freed,
-           refcount_count(&tx->tx_space_freed));
-#endif
-       kmem_free(tx, sizeof (dmu_tx_t));
+       dmu_tx_destroy(tx);
 }
 
 uint64_t
@@ -1245,13 +1182,12 @@ dmu_tx_pool(dmu_tx_t *tx)
        return (tx->tx_pool);
 }
 
-
 void
 dmu_tx_callback_register(dmu_tx_t *tx, dmu_tx_callback_func_t *func, void *data)
 {
        dmu_tx_callback_t *dcb;
 
-       dcb = kmem_alloc(sizeof (dmu_tx_callback_t), KM_PUSHPAGE);
+       dcb = kmem_alloc(sizeof (dmu_tx_callback_t), KM_SLEEP);
 
        dcb->dcb_func = func;
        dcb->dcb_data = data;
@@ -1267,7 +1203,7 @@ dmu_tx_do_callbacks(list_t *cb_list, int error)
 {
        dmu_tx_callback_t *dcb;
 
-       while ((dcb = list_head(cb_list))) {
+       while ((dcb = list_tail(cb_list)) != NULL) {
                list_remove(cb_list, dcb);
                dcb->dcb_func(dcb->dcb_data, error);
                kmem_free(dcb, sizeof (dmu_tx_callback_t));
@@ -1291,12 +1227,10 @@ dmu_tx_do_callbacks(list_t *cb_list, int error)
 static void
 dmu_tx_sa_registration_hold(sa_os_t *sa, dmu_tx_t *tx)
 {
-       int i;
-
        if (!sa->sa_need_attr_registration)
                return;
 
-       for (i = 0; i != sa->sa_num_attrs; i++) {
+       for (int i = 0; i != sa->sa_num_attrs; i++) {
                if (!sa->sa_attr_table[i].sa_registered) {
                        if (sa->sa_reg_attr_obj)
                                dmu_tx_hold_zap(tx, sa->sa_reg_attr_obj,
@@ -1308,38 +1242,16 @@ dmu_tx_sa_registration_hold(sa_os_t *sa, dmu_tx_t *tx)
        }
 }
 
-
 void
 dmu_tx_hold_spill(dmu_tx_t *tx, uint64_t object)
 {
-       dnode_t *dn;
        dmu_tx_hold_t *txh;
 
        txh = dmu_tx_hold_object_impl(tx, tx->tx_objset, object,
            THT_SPILL, 0, 0);
-       if (txh == NULL)
-               return;
-
-       dn = txh->txh_dnode;
-
-       if (dn == NULL)
-               return;
-
-       /* If blkptr doesn't exist then add space to towrite */
-       if (!(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR)) {
-               txh->txh_space_towrite += SPA_MAXBLOCKSIZE;
-       } else {
-               blkptr_t *bp;
-
-               bp = &dn->dn_phys->dn_spill;
-               if (dsl_dataset_block_freeable(dn->dn_objset->os_dsl_dataset,
-                   bp, bp->blk_birth))
-                       txh->txh_space_tooverwrite += SPA_MAXBLOCKSIZE;
-               else
-                       txh->txh_space_towrite += SPA_MAXBLOCKSIZE;
-               if (!BP_IS_HOLE(bp))
-                       txh->txh_space_tounref += SPA_MAXBLOCKSIZE;
-       }
+       if (txh != NULL)
+               (void) refcount_add_many(&txh->txh_space_towrite,
+                   SPA_OLD_MAXBLOCKSIZE, FTAG);
 }
 
 void
@@ -1352,9 +1264,9 @@ dmu_tx_hold_sa_create(dmu_tx_t *tx, int attrsize)
        if (tx->tx_objset->os_sa->sa_master_obj == 0)
                return;
 
-       if (tx->tx_objset->os_sa->sa_layout_attr_obj)
+       if (tx->tx_objset->os_sa->sa_layout_attr_obj) {
                dmu_tx_hold_zap(tx, sa->sa_layout_attr_obj, B_TRUE, NULL);
-       else {
+       else {
                dmu_tx_hold_zap(tx, sa->sa_master_obj, B_TRUE, SA_LAYOUTS);
                dmu_tx_hold_zap(tx, sa->sa_master_obj, B_TRUE, SA_REGISTRY);
                dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, B_TRUE, NULL);
@@ -1363,7 +1275,7 @@ dmu_tx_hold_sa_create(dmu_tx_t *tx, int attrsize)
 
        dmu_tx_sa_registration_hold(sa, tx);
 
-       if (attrsize <= DN_MAX_BONUSLEN && !sa->sa_force_spill)
+       if (attrsize <= DN_OLD_MAX_BONUSLEN && !sa->sa_force_spill)
                return;
 
        (void) dmu_tx_hold_object_impl(tx, tx->tx_objset, DMU_NEW_OBJECT,
@@ -1449,13 +1361,18 @@ dmu_tx_fini(void)
 #if defined(_KERNEL) && defined(HAVE_SPL)
 EXPORT_SYMBOL(dmu_tx_create);
 EXPORT_SYMBOL(dmu_tx_hold_write);
+EXPORT_SYMBOL(dmu_tx_hold_write_by_dnode);
 EXPORT_SYMBOL(dmu_tx_hold_free);
+EXPORT_SYMBOL(dmu_tx_hold_free_by_dnode);
 EXPORT_SYMBOL(dmu_tx_hold_zap);
+EXPORT_SYMBOL(dmu_tx_hold_zap_by_dnode);
 EXPORT_SYMBOL(dmu_tx_hold_bonus);
+EXPORT_SYMBOL(dmu_tx_hold_bonus_by_dnode);
 EXPORT_SYMBOL(dmu_tx_abort);
 EXPORT_SYMBOL(dmu_tx_assign);
 EXPORT_SYMBOL(dmu_tx_wait);
 EXPORT_SYMBOL(dmu_tx_commit);
+EXPORT_SYMBOL(dmu_tx_mark_netfree);
 EXPORT_SYMBOL(dmu_tx_get_txg);
 EXPORT_SYMBOL(dmu_tx_callback_register);
 EXPORT_SYMBOL(dmu_tx_do_callbacks);