xref: /illumos-gate/usr/src/uts/common/fs/zfs/dmu_tx.c (revision 79d728325e257b05859d2eef4a4dfbefdce05a76)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright 2011 Nexenta Systems, Inc.  All rights reserved.
24  * Copyright (c) 2012, 2016 by Delphix. All rights reserved.
25  * Copyright (c) 2014 Integros [integros.com]
26  */
27 
28 #include <sys/dmu.h>
29 #include <sys/dmu_impl.h>
30 #include <sys/dbuf.h>
31 #include <sys/dmu_tx.h>
32 #include <sys/dmu_objset.h>
33 #include <sys/dsl_dataset.h> /* for dsl_dataset_block_freeable() */
34 #include <sys/dsl_dir.h> /* for dsl_dir_tempreserve_*() */
35 #include <sys/dsl_pool.h>
36 #include <sys/zap_impl.h> /* for fzap_default_block_shift */
37 #include <sys/spa.h>
38 #include <sys/sa.h>
39 #include <sys/sa_impl.h>
40 #include <sys/zfs_context.h>
41 #include <sys/varargs.h>
42 
43 typedef void (*dmu_tx_hold_func_t)(dmu_tx_t *tx, struct dnode *dn,
44     uint64_t arg1, uint64_t arg2);
45 
46 
47 dmu_tx_t *
48 dmu_tx_create_dd(dsl_dir_t *dd)
49 {
50 	dmu_tx_t *tx = kmem_zalloc(sizeof (dmu_tx_t), KM_SLEEP);
51 	tx->tx_dir = dd;
52 	if (dd != NULL)
53 		tx->tx_pool = dd->dd_pool;
54 	list_create(&tx->tx_holds, sizeof (dmu_tx_hold_t),
55 	    offsetof(dmu_tx_hold_t, txh_node));
56 	list_create(&tx->tx_callbacks, sizeof (dmu_tx_callback_t),
57 	    offsetof(dmu_tx_callback_t, dcb_node));
58 	tx->tx_start = gethrtime();
59 #ifdef ZFS_DEBUG
60 	refcount_create(&tx->tx_space_written);
61 	refcount_create(&tx->tx_space_freed);
62 #endif
63 	return (tx);
64 }
65 
66 dmu_tx_t *
67 dmu_tx_create(objset_t *os)
68 {
69 	dmu_tx_t *tx = dmu_tx_create_dd(os->os_dsl_dataset->ds_dir);
70 	tx->tx_objset = os;
71 	tx->tx_lastsnap_txg = dsl_dataset_prev_snap_txg(os->os_dsl_dataset);
72 	return (tx);
73 }
74 
75 dmu_tx_t *
76 dmu_tx_create_assigned(struct dsl_pool *dp, uint64_t txg)
77 {
78 	dmu_tx_t *tx = dmu_tx_create_dd(NULL);
79 
80 	ASSERT3U(txg, <=, dp->dp_tx.tx_open_txg);
81 	tx->tx_pool = dp;
82 	tx->tx_txg = txg;
83 	tx->tx_anyobj = TRUE;
84 
85 	return (tx);
86 }
87 
88 int
89 dmu_tx_is_syncing(dmu_tx_t *tx)
90 {
91 	return (tx->tx_anyobj);
92 }
93 
94 int
95 dmu_tx_private_ok(dmu_tx_t *tx)
96 {
97 	return (tx->tx_anyobj);
98 }
99 
100 static dmu_tx_hold_t *
101 dmu_tx_hold_object_impl(dmu_tx_t *tx, objset_t *os, uint64_t object,
102     enum dmu_tx_hold_type type, uint64_t arg1, uint64_t arg2)
103 {
104 	dmu_tx_hold_t *txh;
105 	dnode_t *dn = NULL;
106 	int err;
107 
108 	if (object != DMU_NEW_OBJECT) {
109 		err = dnode_hold(os, object, tx, &dn);
110 		if (err) {
111 			tx->tx_err = err;
112 			return (NULL);
113 		}
114 
115 		if (err == 0 && tx->tx_txg != 0) {
116 			mutex_enter(&dn->dn_mtx);
117 			/*
118 			 * dn->dn_assigned_txg == tx->tx_txg doesn't pose a
119 			 * problem, but there's no way for it to happen (for
120 			 * now, at least).
121 			 */
122 			ASSERT(dn->dn_assigned_txg == 0);
123 			dn->dn_assigned_txg = tx->tx_txg;
124 			(void) refcount_add(&dn->dn_tx_holds, tx);
125 			mutex_exit(&dn->dn_mtx);
126 		}
127 	}
128 
129 	txh = kmem_zalloc(sizeof (dmu_tx_hold_t), KM_SLEEP);
130 	txh->txh_tx = tx;
131 	txh->txh_dnode = dn;
132 	refcount_create(&txh->txh_space_towrite);
133 	refcount_create(&txh->txh_space_tofree);
134 	refcount_create(&txh->txh_space_tooverwrite);
135 	refcount_create(&txh->txh_space_tounref);
136 	refcount_create(&txh->txh_memory_tohold);
137 	refcount_create(&txh->txh_fudge);
138 #ifdef ZFS_DEBUG
139 	txh->txh_type = type;
140 	txh->txh_arg1 = arg1;
141 	txh->txh_arg2 = arg2;
142 #endif
143 	list_insert_tail(&tx->tx_holds, txh);
144 
145 	return (txh);
146 }
147 
148 void
149 dmu_tx_add_new_object(dmu_tx_t *tx, objset_t *os, uint64_t object)
150 {
151 	/*
152 	 * If we're syncing, they can manipulate any object anyhow, and
153 	 * the hold on the dnode_t can cause problems.
154 	 */
155 	if (!dmu_tx_is_syncing(tx)) {
156 		(void) dmu_tx_hold_object_impl(tx, os,
157 		    object, THT_NEWOBJECT, 0, 0);
158 	}
159 }
160 
161 static int
162 dmu_tx_check_ioerr(zio_t *zio, dnode_t *dn, int level, uint64_t blkid)
163 {
164 	int err;
165 	dmu_buf_impl_t *db;
166 
167 	rw_enter(&dn->dn_struct_rwlock, RW_READER);
168 	db = dbuf_hold_level(dn, level, blkid, FTAG);
169 	rw_exit(&dn->dn_struct_rwlock);
170 	if (db == NULL)
171 		return (SET_ERROR(EIO));
172 	err = dbuf_read(db, zio, DB_RF_CANFAIL | DB_RF_NOPREFETCH);
173 	dbuf_rele(db, FTAG);
174 	return (err);
175 }
176 
177 static void
178 dmu_tx_count_twig(dmu_tx_hold_t *txh, dnode_t *dn, dmu_buf_impl_t *db,
179     int level, uint64_t blkid, boolean_t freeable, uint64_t *history)
180 {
181 	objset_t *os = dn->dn_objset;
182 	dsl_dataset_t *ds = os->os_dsl_dataset;
183 	int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
184 	dmu_buf_impl_t *parent = NULL;
185 	blkptr_t *bp = NULL;
186 	uint64_t space;
187 
188 	if (level >= dn->dn_nlevels || history[level] == blkid)
189 		return;
190 
191 	history[level] = blkid;
192 
193 	space = (level == 0) ? dn->dn_datablksz : (1ULL << dn->dn_indblkshift);
194 
195 	if (db == NULL || db == dn->dn_dbuf) {
196 		ASSERT(level != 0);
197 		db = NULL;
198 	} else {
199 		ASSERT(DB_DNODE(db) == dn);
200 		ASSERT(db->db_level == level);
201 		ASSERT(db->db.db_size == space);
202 		ASSERT(db->db_blkid == blkid);
203 		bp = db->db_blkptr;
204 		parent = db->db_parent;
205 	}
206 
207 	freeable = (bp && (freeable ||
208 	    dsl_dataset_block_freeable(ds, bp, bp->blk_birth)));
209 
210 	if (freeable) {
211 		(void) refcount_add_many(&txh->txh_space_tooverwrite,
212 		    space, FTAG);
213 	} else {
214 		(void) refcount_add_many(&txh->txh_space_towrite,
215 		    space, FTAG);
216 	}
217 
218 	if (bp) {
219 		(void) refcount_add_many(&txh->txh_space_tounref,
220 		    bp_get_dsize(os->os_spa, bp), FTAG);
221 	}
222 
223 	dmu_tx_count_twig(txh, dn, parent, level + 1,
224 	    blkid >> epbs, freeable, history);
225 }
226 
227 /* ARGSUSED */
228 static void
229 dmu_tx_count_write(dmu_tx_hold_t *txh, uint64_t off, uint64_t len)
230 {
231 	dnode_t *dn = txh->txh_dnode;
232 	uint64_t start, end, i;
233 	int min_bs, max_bs, min_ibs, max_ibs, epbs, bits;
234 	int err = 0;
235 
236 	if (len == 0)
237 		return;
238 
239 	min_bs = SPA_MINBLOCKSHIFT;
240 	max_bs = highbit64(txh->txh_tx->tx_objset->os_recordsize) - 1;
241 	min_ibs = DN_MIN_INDBLKSHIFT;
242 	max_ibs = DN_MAX_INDBLKSHIFT;
243 
244 	if (dn) {
245 		uint64_t history[DN_MAX_LEVELS];
246 		int nlvls = dn->dn_nlevels;
247 		int delta;
248 
249 		/*
250 		 * For i/o error checking, read the first and last level-0
251 		 * blocks (if they are not aligned), and all the level-1 blocks.
252 		 */
253 		if (dn->dn_maxblkid == 0) {
254 			delta = dn->dn_datablksz;
255 			start = (off < dn->dn_datablksz) ? 0 : 1;
256 			end = (off+len <= dn->dn_datablksz) ? 0 : 1;
257 			if (start == 0 && (off > 0 || len < dn->dn_datablksz)) {
258 				err = dmu_tx_check_ioerr(NULL, dn, 0, 0);
259 				if (err)
260 					goto out;
261 				delta -= off;
262 			}
263 		} else {
264 			zio_t *zio = zio_root(dn->dn_objset->os_spa,
265 			    NULL, NULL, ZIO_FLAG_CANFAIL);
266 
267 			/* first level-0 block */
268 			start = off >> dn->dn_datablkshift;
269 			if (P2PHASE(off, dn->dn_datablksz) ||
270 			    len < dn->dn_datablksz) {
271 				err = dmu_tx_check_ioerr(zio, dn, 0, start);
272 				if (err)
273 					goto out;
274 			}
275 
276 			/* last level-0 block */
277 			end = (off+len-1) >> dn->dn_datablkshift;
278 			if (end != start && end <= dn->dn_maxblkid &&
279 			    P2PHASE(off+len, dn->dn_datablksz)) {
280 				err = dmu_tx_check_ioerr(zio, dn, 0, end);
281 				if (err)
282 					goto out;
283 			}
284 
285 			/* level-1 blocks */
286 			if (nlvls > 1) {
287 				int shft = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
288 				for (i = (start>>shft)+1; i < end>>shft; i++) {
289 					err = dmu_tx_check_ioerr(zio, dn, 1, i);
290 					if (err)
291 						goto out;
292 				}
293 			}
294 
295 			err = zio_wait(zio);
296 			if (err)
297 				goto out;
298 			delta = P2NPHASE(off, dn->dn_datablksz);
299 		}
300 
301 		min_ibs = max_ibs = dn->dn_indblkshift;
302 		if (dn->dn_maxblkid > 0) {
303 			/*
304 			 * The blocksize can't change,
305 			 * so we can make a more precise estimate.
306 			 */
307 			ASSERT(dn->dn_datablkshift != 0);
308 			min_bs = max_bs = dn->dn_datablkshift;
309 		} else {
310 			/*
311 			 * The blocksize can increase up to the recordsize,
312 			 * or if it is already more than the recordsize,
313 			 * up to the next power of 2.
314 			 */
315 			min_bs = highbit64(dn->dn_datablksz - 1);
316 			max_bs = MAX(max_bs, highbit64(dn->dn_datablksz - 1));
317 		}
318 
319 		/*
320 		 * If this write is not off the end of the file
321 		 * we need to account for overwrites/unref.
322 		 */
323 		if (start <= dn->dn_maxblkid) {
324 			for (int l = 0; l < DN_MAX_LEVELS; l++)
325 				history[l] = -1ULL;
326 		}
327 		while (start <= dn->dn_maxblkid) {
328 			dmu_buf_impl_t *db;
329 
330 			rw_enter(&dn->dn_struct_rwlock, RW_READER);
331 			err = dbuf_hold_impl(dn, 0, start,
332 			    FALSE, FALSE, FTAG, &db);
333 			rw_exit(&dn->dn_struct_rwlock);
334 
335 			if (err) {
336 				txh->txh_tx->tx_err = err;
337 				return;
338 			}
339 
340 			dmu_tx_count_twig(txh, dn, db, 0, start, B_FALSE,
341 			    history);
342 			dbuf_rele(db, FTAG);
343 			if (++start > end) {
344 				/*
345 				 * Account for new indirects appearing
346 				 * before this IO gets assigned into a txg.
347 				 */
348 				bits = 64 - min_bs;
349 				epbs = min_ibs - SPA_BLKPTRSHIFT;
350 				for (bits -= epbs * (nlvls - 1);
351 				    bits >= 0; bits -= epbs) {
352 					(void) refcount_add_many(
353 					    &txh->txh_fudge,
354 					    1ULL << max_ibs, FTAG);
355 				}
356 				goto out;
357 			}
358 			off += delta;
359 			if (len >= delta)
360 				len -= delta;
361 			delta = dn->dn_datablksz;
362 		}
363 	}
364 
365 	/*
366 	 * 'end' is the last thing we will access, not one past.
367 	 * This way we won't overflow when accessing the last byte.
368 	 */
369 	start = P2ALIGN(off, 1ULL << max_bs);
370 	end = P2ROUNDUP(off + len, 1ULL << max_bs) - 1;
371 	(void) refcount_add_many(&txh->txh_space_towrite,
372 	    end - start + 1, FTAG);
373 
374 	start >>= min_bs;
375 	end >>= min_bs;
376 
377 	epbs = min_ibs - SPA_BLKPTRSHIFT;
378 
379 	/*
380 	 * The object contains at most 2^(64 - min_bs) blocks,
381 	 * and each indirect level maps 2^epbs.
382 	 */
383 	for (bits = 64 - min_bs; bits >= 0; bits -= epbs) {
384 		start >>= epbs;
385 		end >>= epbs;
386 		ASSERT3U(end, >=, start);
387 		(void) refcount_add_many(&txh->txh_space_towrite,
388 		    (end - start + 1) << max_ibs, FTAG);
389 		if (start != 0) {
390 			/*
391 			 * We also need a new blkid=0 indirect block
392 			 * to reference any existing file data.
393 			 */
394 			(void) refcount_add_many(&txh->txh_space_towrite,
395 			    1ULL << max_ibs, FTAG);
396 		}
397 	}
398 
399 out:
400 	if (refcount_count(&txh->txh_space_towrite) +
401 	    refcount_count(&txh->txh_space_tooverwrite) >
402 	    2 * DMU_MAX_ACCESS)
403 		err = SET_ERROR(EFBIG);
404 
405 	if (err)
406 		txh->txh_tx->tx_err = err;
407 }
408 
409 static void
410 dmu_tx_count_dnode(dmu_tx_hold_t *txh)
411 {
412 	dnode_t *dn = txh->txh_dnode;
413 	dnode_t *mdn = DMU_META_DNODE(txh->txh_tx->tx_objset);
414 	uint64_t space = mdn->dn_datablksz +
415 	    ((mdn->dn_nlevels-1) << mdn->dn_indblkshift);
416 
417 	if (dn && dn->dn_dbuf->db_blkptr &&
418 	    dsl_dataset_block_freeable(dn->dn_objset->os_dsl_dataset,
419 	    dn->dn_dbuf->db_blkptr, dn->dn_dbuf->db_blkptr->blk_birth)) {
420 		(void) refcount_add_many(&txh->txh_space_tooverwrite,
421 		    space, FTAG);
422 		(void) refcount_add_many(&txh->txh_space_tounref, space, FTAG);
423 	} else {
424 		(void) refcount_add_many(&txh->txh_space_towrite, space, FTAG);
425 		if (dn && dn->dn_dbuf->db_blkptr) {
426 			(void) refcount_add_many(&txh->txh_space_tounref,
427 			    space, FTAG);
428 		}
429 	}
430 }
431 
432 void
433 dmu_tx_hold_write(dmu_tx_t *tx, uint64_t object, uint64_t off, int len)
434 {
435 	dmu_tx_hold_t *txh;
436 
437 	ASSERT(tx->tx_txg == 0);
438 	ASSERT(len < DMU_MAX_ACCESS);
439 	ASSERT(len == 0 || UINT64_MAX - off >= len - 1);
440 
441 	txh = dmu_tx_hold_object_impl(tx, tx->tx_objset,
442 	    object, THT_WRITE, off, len);
443 	if (txh == NULL)
444 		return;
445 
446 	dmu_tx_count_write(txh, off, len);
447 	dmu_tx_count_dnode(txh);
448 }
449 
450 static void
451 dmu_tx_count_free(dmu_tx_hold_t *txh, uint64_t off, uint64_t len)
452 {
453 	uint64_t blkid, nblks, lastblk;
454 	uint64_t space = 0, unref = 0, skipped = 0;
455 	dnode_t *dn = txh->txh_dnode;
456 	dsl_dataset_t *ds = dn->dn_objset->os_dsl_dataset;
457 	spa_t *spa = txh->txh_tx->tx_pool->dp_spa;
458 	int epbs;
459 	uint64_t l0span = 0, nl1blks = 0;
460 
461 	if (dn->dn_nlevels == 0)
462 		return;
463 
464 	/*
465 	 * The struct_rwlock protects us against dn_nlevels
466 	 * changing, in case (against all odds) we manage to dirty &
467 	 * sync out the changes after we check for being dirty.
468 	 * Also, dbuf_hold_impl() wants us to have the struct_rwlock.
469 	 */
470 	rw_enter(&dn->dn_struct_rwlock, RW_READER);
471 	epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
472 	if (dn->dn_maxblkid == 0) {
473 		if (off == 0 && len >= dn->dn_datablksz) {
474 			blkid = 0;
475 			nblks = 1;
476 		} else {
477 			rw_exit(&dn->dn_struct_rwlock);
478 			return;
479 		}
480 	} else {
481 		blkid = off >> dn->dn_datablkshift;
482 		nblks = (len + dn->dn_datablksz - 1) >> dn->dn_datablkshift;
483 
484 		if (blkid > dn->dn_maxblkid) {
485 			rw_exit(&dn->dn_struct_rwlock);
486 			return;
487 		}
488 		if (blkid + nblks > dn->dn_maxblkid)
489 			nblks = dn->dn_maxblkid - blkid + 1;
490 
491 	}
492 	l0span = nblks;    /* save for later use to calc level > 1 overhead */
493 	if (dn->dn_nlevels == 1) {
494 		int i;
495 		for (i = 0; i < nblks; i++) {
496 			blkptr_t *bp = dn->dn_phys->dn_blkptr;
497 			ASSERT3U(blkid + i, <, dn->dn_nblkptr);
498 			bp += blkid + i;
499 			if (dsl_dataset_block_freeable(ds, bp, bp->blk_birth)) {
500 				dprintf_bp(bp, "can free old%s", "");
501 				space += bp_get_dsize(spa, bp);
502 			}
503 			unref += BP_GET_ASIZE(bp);
504 		}
505 		nl1blks = 1;
506 		nblks = 0;
507 	}
508 
509 	lastblk = blkid + nblks - 1;
510 	while (nblks) {
511 		dmu_buf_impl_t *dbuf;
512 		uint64_t ibyte, new_blkid;
513 		int epb = 1 << epbs;
514 		int err, i, blkoff, tochk;
515 		blkptr_t *bp;
516 
517 		ibyte = blkid << dn->dn_datablkshift;
518 		err = dnode_next_offset(dn,
519 		    DNODE_FIND_HAVELOCK, &ibyte, 2, 1, 0);
520 		new_blkid = ibyte >> dn->dn_datablkshift;
521 		if (err == ESRCH) {
522 			skipped += (lastblk >> epbs) - (blkid >> epbs) + 1;
523 			break;
524 		}
525 		if (err) {
526 			txh->txh_tx->tx_err = err;
527 			break;
528 		}
529 		if (new_blkid > lastblk) {
530 			skipped += (lastblk >> epbs) - (blkid >> epbs) + 1;
531 			break;
532 		}
533 
534 		if (new_blkid > blkid) {
535 			ASSERT((new_blkid >> epbs) > (blkid >> epbs));
536 			skipped += (new_blkid >> epbs) - (blkid >> epbs) - 1;
537 			nblks -= new_blkid - blkid;
538 			blkid = new_blkid;
539 		}
540 		blkoff = P2PHASE(blkid, epb);
541 		tochk = MIN(epb - blkoff, nblks);
542 
543 		err = dbuf_hold_impl(dn, 1, blkid >> epbs,
544 		    FALSE, FALSE, FTAG, &dbuf);
545 		if (err) {
546 			txh->txh_tx->tx_err = err;
547 			break;
548 		}
549 
550 		(void) refcount_add_many(&txh->txh_memory_tohold,
551 		    dbuf->db.db_size, FTAG);
552 
553 		/*
554 		 * We don't check memory_tohold against DMU_MAX_ACCESS because
555 		 * memory_tohold is an over-estimation (especially the >L1
556 		 * indirect blocks), so it could fail.  Callers should have
557 		 * already verified that they will not be holding too much
558 		 * memory.
559 		 */
560 
561 		err = dbuf_read(dbuf, NULL, DB_RF_HAVESTRUCT | DB_RF_CANFAIL);
562 		if (err != 0) {
563 			txh->txh_tx->tx_err = err;
564 			dbuf_rele(dbuf, FTAG);
565 			break;
566 		}
567 
568 		bp = dbuf->db.db_data;
569 		bp += blkoff;
570 
571 		for (i = 0; i < tochk; i++) {
572 			if (dsl_dataset_block_freeable(ds, &bp[i],
573 			    bp[i].blk_birth)) {
574 				dprintf_bp(&bp[i], "can free old%s", "");
575 				space += bp_get_dsize(spa, &bp[i]);
576 			}
577 			unref += BP_GET_ASIZE(bp);
578 		}
579 		dbuf_rele(dbuf, FTAG);
580 
581 		++nl1blks;
582 		blkid += tochk;
583 		nblks -= tochk;
584 	}
585 	rw_exit(&dn->dn_struct_rwlock);
586 
587 	/*
588 	 * Add in memory requirements of higher-level indirects.
589 	 * This assumes a worst-possible scenario for dn_nlevels and a
590 	 * worst-possible distribution of l1-blocks over the region to free.
591 	 */
592 	{
593 		uint64_t blkcnt = 1 + ((l0span >> epbs) >> epbs);
594 		int level = 2;
595 		/*
596 		 * Here we don't use DN_MAX_LEVEL, but calculate it with the
597 		 * given datablkshift and indblkshift. This makes the
598 		 * difference between 19 and 8 on large files.
599 		 */
600 		int maxlevel = 2 + (DN_MAX_OFFSET_SHIFT - dn->dn_datablkshift) /
601 		    (dn->dn_indblkshift - SPA_BLKPTRSHIFT);
602 
603 		while (level++ < maxlevel) {
604 			(void) refcount_add_many(&txh->txh_memory_tohold,
605 			    MAX(MIN(blkcnt, nl1blks), 1) << dn->dn_indblkshift,
606 			    FTAG);
607 			blkcnt = 1 + (blkcnt >> epbs);
608 		}
609 	}
610 
611 	/* account for new level 1 indirect blocks that might show up */
612 	if (skipped > 0) {
613 		(void) refcount_add_many(&txh->txh_fudge,
614 		    skipped << dn->dn_indblkshift, FTAG);
615 		skipped = MIN(skipped, DMU_MAX_DELETEBLKCNT >> epbs);
616 		(void) refcount_add_many(&txh->txh_memory_tohold,
617 		    skipped << dn->dn_indblkshift, FTAG);
618 	}
619 	(void) refcount_add_many(&txh->txh_space_tofree, space, FTAG);
620 	(void) refcount_add_many(&txh->txh_space_tounref, unref, FTAG);
621 }
622 
623 /*
624  * This function marks the transaction as being a "net free".  The end
625  * result is that refquotas will be disabled for this transaction, and
626  * this transaction will be able to use half of the pool space overhead
627  * (see dsl_pool_adjustedsize()).  Therefore this function should only
628  * be called for transactions that we expect will not cause a net increase
629  * in the amount of space used (but it's OK if that is occasionally not true).
630  */
631 void
632 dmu_tx_mark_netfree(dmu_tx_t *tx)
633 {
634 	dmu_tx_hold_t *txh;
635 
636 	txh = dmu_tx_hold_object_impl(tx, tx->tx_objset,
637 	    DMU_NEW_OBJECT, THT_FREE, 0, 0);
638 
639 	/*
640 	 * Pretend that this operation will free 1GB of space.  This
641 	 * should be large enough to cancel out the largest write.
642 	 * We don't want to use something like UINT64_MAX, because that would
643 	 * cause overflows when doing math with these values (e.g. in
644 	 * dmu_tx_try_assign()).
645 	 */
646 	(void) refcount_add_many(&txh->txh_space_tofree,
647 	    1024 * 1024 * 1024, FTAG);
648 	(void) refcount_add_many(&txh->txh_space_tounref,
649 	    1024 * 1024 * 1024, FTAG);
650 }
651 
652 void
653 dmu_tx_hold_free(dmu_tx_t *tx, uint64_t object, uint64_t off, uint64_t len)
654 {
655 	dmu_tx_hold_t *txh;
656 	dnode_t *dn;
657 	int err;
658 	zio_t *zio;
659 
660 	ASSERT(tx->tx_txg == 0);
661 
662 	txh = dmu_tx_hold_object_impl(tx, tx->tx_objset,
663 	    object, THT_FREE, off, len);
664 	if (txh == NULL)
665 		return;
666 	dn = txh->txh_dnode;
667 	dmu_tx_count_dnode(txh);
668 
669 	if (off >= (dn->dn_maxblkid+1) * dn->dn_datablksz)
670 		return;
671 	if (len == DMU_OBJECT_END)
672 		len = (dn->dn_maxblkid+1) * dn->dn_datablksz - off;
673 
674 	/*
675 	 * For i/o error checking, we read the first and last level-0
676 	 * blocks if they are not aligned, and all the level-1 blocks.
677 	 *
678 	 * Note:  dbuf_free_range() assumes that we have not instantiated
679 	 * any level-0 dbufs that will be completely freed.  Therefore we must
680 	 * exercise care to not read or count the first and last blocks
681 	 * if they are blocksize-aligned.
682 	 */
683 	if (dn->dn_datablkshift == 0) {
684 		if (off != 0 || len < dn->dn_datablksz)
685 			dmu_tx_count_write(txh, 0, dn->dn_datablksz);
686 	} else {
687 		/* first block will be modified if it is not aligned */
688 		if (!IS_P2ALIGNED(off, 1 << dn->dn_datablkshift))
689 			dmu_tx_count_write(txh, off, 1);
690 		/* last block will be modified if it is not aligned */
691 		if (!IS_P2ALIGNED(off + len, 1 << dn->dn_datablkshift))
692 			dmu_tx_count_write(txh, off+len, 1);
693 	}
694 
695 	/*
696 	 * Check level-1 blocks.
697 	 */
698 	if (dn->dn_nlevels > 1) {
699 		int shift = dn->dn_datablkshift + dn->dn_indblkshift -
700 		    SPA_BLKPTRSHIFT;
701 		uint64_t start = off >> shift;
702 		uint64_t end = (off + len) >> shift;
703 
704 		ASSERT(dn->dn_indblkshift != 0);
705 
706 		/*
707 		 * dnode_reallocate() can result in an object with indirect
708 		 * blocks having an odd data block size.  In this case,
709 		 * just check the single block.
710 		 */
711 		if (dn->dn_datablkshift == 0)
712 			start = end = 0;
713 
714 		zio = zio_root(tx->tx_pool->dp_spa,
715 		    NULL, NULL, ZIO_FLAG_CANFAIL);
716 		for (uint64_t i = start; i <= end; i++) {
717 			uint64_t ibyte = i << shift;
718 			err = dnode_next_offset(dn, 0, &ibyte, 2, 1, 0);
719 			i = ibyte >> shift;
720 			if (err == ESRCH || i > end)
721 				break;
722 			if (err) {
723 				tx->tx_err = err;
724 				return;
725 			}
726 
727 			err = dmu_tx_check_ioerr(zio, dn, 1, i);
728 			if (err) {
729 				tx->tx_err = err;
730 				return;
731 			}
732 		}
733 		err = zio_wait(zio);
734 		if (err) {
735 			tx->tx_err = err;
736 			return;
737 		}
738 	}
739 
740 	dmu_tx_count_free(txh, off, len);
741 }
742 
743 void
744 dmu_tx_hold_zap(dmu_tx_t *tx, uint64_t object, int add, const char *name)
745 {
746 	dmu_tx_hold_t *txh;
747 	dnode_t *dn;
748 	int err;
749 
750 	ASSERT(tx->tx_txg == 0);
751 
752 	txh = dmu_tx_hold_object_impl(tx, tx->tx_objset,
753 	    object, THT_ZAP, add, (uintptr_t)name);
754 	if (txh == NULL)
755 		return;
756 	dn = txh->txh_dnode;
757 
758 	dmu_tx_count_dnode(txh);
759 
760 	if (dn == NULL) {
761 		/*
762 		 * We will be able to fit a new object's entries into one leaf
763 		 * block.  So there will be at most 2 blocks total,
764 		 * including the header block.
765 		 */
766 		dmu_tx_count_write(txh, 0, 2 << fzap_default_block_shift);
767 		return;
768 	}
769 
770 	ASSERT3P(DMU_OT_BYTESWAP(dn->dn_type), ==, DMU_BSWAP_ZAP);
771 
772 	if (dn->dn_maxblkid == 0 && !add) {
773 		blkptr_t *bp;
774 
775 		/*
776 		 * If there is only one block  (i.e. this is a micro-zap)
777 		 * and we are not adding anything, the accounting is simple.
778 		 */
779 		err = dmu_tx_check_ioerr(NULL, dn, 0, 0);
780 		if (err) {
781 			tx->tx_err = err;
782 			return;
783 		}
784 
785 		/*
786 		 * Use max block size here, since we don't know how much
787 		 * the size will change between now and the dbuf dirty call.
788 		 */
789 		bp = &dn->dn_phys->dn_blkptr[0];
790 		if (dsl_dataset_block_freeable(dn->dn_objset->os_dsl_dataset,
791 		    bp, bp->blk_birth)) {
792 			(void) refcount_add_many(&txh->txh_space_tooverwrite,
793 			    MZAP_MAX_BLKSZ, FTAG);
794 		} else {
795 			(void) refcount_add_many(&txh->txh_space_towrite,
796 			    MZAP_MAX_BLKSZ, FTAG);
797 		}
798 		if (!BP_IS_HOLE(bp)) {
799 			(void) refcount_add_many(&txh->txh_space_tounref,
800 			    MZAP_MAX_BLKSZ, FTAG);
801 		}
802 		return;
803 	}
804 
805 	if (dn->dn_maxblkid > 0 && name) {
806 		/*
807 		 * access the name in this fat-zap so that we'll check
808 		 * for i/o errors to the leaf blocks, etc.
809 		 */
810 		err = zap_lookup_by_dnode(dn, name, 8, 0, NULL);
811 		if (err == EIO) {
812 			tx->tx_err = err;
813 			return;
814 		}
815 	}
816 
817 	err = zap_count_write_by_dnode(dn, name, add,
818 	    &txh->txh_space_towrite, &txh->txh_space_tooverwrite);
819 
820 	/*
821 	 * If the modified blocks are scattered to the four winds,
822 	 * we'll have to modify an indirect twig for each.  We can make
823 	 * modifications at up to 3 locations:
824 	 *  - header block at the beginning of the object
825 	 *  - target leaf block
826 	 *  - end of the object, where we might need to write:
827 	 *	- a new leaf block if the target block needs to be split
828 	 *	- the new pointer table, if it is growing
829 	 *	- the new cookie table, if it is growing
830 	 */
831 	int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
832 	dsl_dataset_phys_t *ds_phys =
833 	    dsl_dataset_phys(dn->dn_objset->os_dsl_dataset);
834 	for (int lvl = 1; lvl < dn->dn_nlevels; lvl++) {
835 		uint64_t num_indirects = 1 + (dn->dn_maxblkid >> (epbs * lvl));
836 		uint64_t spc = MIN(3, num_indirects) << dn->dn_indblkshift;
837 		if (ds_phys->ds_prev_snap_obj != 0) {
838 			(void) refcount_add_many(&txh->txh_space_towrite,
839 			    spc, FTAG);
840 		} else {
841 			(void) refcount_add_many(&txh->txh_space_tooverwrite,
842 			    spc, FTAG);
843 		}
844 	}
845 }
846 
847 void
848 dmu_tx_hold_bonus(dmu_tx_t *tx, uint64_t object)
849 {
850 	dmu_tx_hold_t *txh;
851 
852 	ASSERT(tx->tx_txg == 0);
853 
854 	txh = dmu_tx_hold_object_impl(tx, tx->tx_objset,
855 	    object, THT_BONUS, 0, 0);
856 	if (txh)
857 		dmu_tx_count_dnode(txh);
858 }
859 
860 void
861 dmu_tx_hold_space(dmu_tx_t *tx, uint64_t space)
862 {
863 	dmu_tx_hold_t *txh;
864 	ASSERT(tx->tx_txg == 0);
865 
866 	txh = dmu_tx_hold_object_impl(tx, tx->tx_objset,
867 	    DMU_NEW_OBJECT, THT_SPACE, space, 0);
868 
869 	(void) refcount_add_many(&txh->txh_space_towrite, space, FTAG);
870 }
871 
872 int
873 dmu_tx_holds(dmu_tx_t *tx, uint64_t object)
874 {
875 	dmu_tx_hold_t *txh;
876 	int holds = 0;
877 
878 	/*
879 	 * By asserting that the tx is assigned, we're counting the
880 	 * number of dn_tx_holds, which is the same as the number of
881 	 * dn_holds.  Otherwise, we'd be counting dn_holds, but
882 	 * dn_tx_holds could be 0.
883 	 */
884 	ASSERT(tx->tx_txg != 0);
885 
886 	/* if (tx->tx_anyobj == TRUE) */
887 		/* return (0); */
888 
889 	for (txh = list_head(&tx->tx_holds); txh;
890 	    txh = list_next(&tx->tx_holds, txh)) {
891 		if (txh->txh_dnode && txh->txh_dnode->dn_object == object)
892 			holds++;
893 	}
894 
895 	return (holds);
896 }
897 
898 #ifdef ZFS_DEBUG
899 void
900 dmu_tx_dirty_buf(dmu_tx_t *tx, dmu_buf_impl_t *db)
901 {
902 	dmu_tx_hold_t *txh;
903 	int match_object = FALSE, match_offset = FALSE;
904 	dnode_t *dn;
905 
906 	DB_DNODE_ENTER(db);
907 	dn = DB_DNODE(db);
908 	ASSERT(tx->tx_txg != 0);
909 	ASSERT(tx->tx_objset == NULL || dn->dn_objset == tx->tx_objset);
910 	ASSERT3U(dn->dn_object, ==, db->db.db_object);
911 
912 	if (tx->tx_anyobj) {
913 		DB_DNODE_EXIT(db);
914 		return;
915 	}
916 
917 	/* XXX No checking on the meta dnode for now */
918 	if (db->db.db_object == DMU_META_DNODE_OBJECT) {
919 		DB_DNODE_EXIT(db);
920 		return;
921 	}
922 
923 	for (txh = list_head(&tx->tx_holds); txh;
924 	    txh = list_next(&tx->tx_holds, txh)) {
925 		ASSERT(dn == NULL || dn->dn_assigned_txg == tx->tx_txg);
926 		if (txh->txh_dnode == dn && txh->txh_type != THT_NEWOBJECT)
927 			match_object = TRUE;
928 		if (txh->txh_dnode == NULL || txh->txh_dnode == dn) {
929 			int datablkshift = dn->dn_datablkshift ?
930 			    dn->dn_datablkshift : SPA_MAXBLOCKSHIFT;
931 			int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
932 			int shift = datablkshift + epbs * db->db_level;
933 			uint64_t beginblk = shift >= 64 ? 0 :
934 			    (txh->txh_arg1 >> shift);
935 			uint64_t endblk = shift >= 64 ? 0 :
936 			    ((txh->txh_arg1 + txh->txh_arg2 - 1) >> shift);
937 			uint64_t blkid = db->db_blkid;
938 
939 			/* XXX txh_arg2 better not be zero... */
940 
941 			dprintf("found txh type %x beginblk=%llx endblk=%llx\n",
942 			    txh->txh_type, beginblk, endblk);
943 
944 			switch (txh->txh_type) {
945 			case THT_WRITE:
946 				if (blkid >= beginblk && blkid <= endblk)
947 					match_offset = TRUE;
948 				/*
949 				 * We will let this hold work for the bonus
950 				 * or spill buffer so that we don't need to
951 				 * hold it when creating a new object.
952 				 */
953 				if (blkid == DMU_BONUS_BLKID ||
954 				    blkid == DMU_SPILL_BLKID)
955 					match_offset = TRUE;
956 				/*
957 				 * They might have to increase nlevels,
958 				 * thus dirtying the new TLIBs.  Or the
959 				 * might have to change the block size,
960 				 * thus dirying the new lvl=0 blk=0.
961 				 */
962 				if (blkid == 0)
963 					match_offset = TRUE;
964 				break;
965 			case THT_FREE:
966 				/*
967 				 * We will dirty all the level 1 blocks in
968 				 * the free range and perhaps the first and
969 				 * last level 0 block.
970 				 */
971 				if (blkid >= beginblk && (blkid <= endblk ||
972 				    txh->txh_arg2 == DMU_OBJECT_END))
973 					match_offset = TRUE;
974 				break;
975 			case THT_SPILL:
976 				if (blkid == DMU_SPILL_BLKID)
977 					match_offset = TRUE;
978 				break;
979 			case THT_BONUS:
980 				if (blkid == DMU_BONUS_BLKID)
981 					match_offset = TRUE;
982 				break;
983 			case THT_ZAP:
984 				match_offset = TRUE;
985 				break;
986 			case THT_NEWOBJECT:
987 				match_object = TRUE;
988 				break;
989 			default:
990 				ASSERT(!"bad txh_type");
991 			}
992 		}
993 		if (match_object && match_offset) {
994 			DB_DNODE_EXIT(db);
995 			return;
996 		}
997 	}
998 	DB_DNODE_EXIT(db);
999 	panic("dirtying dbuf obj=%llx lvl=%u blkid=%llx but not tx_held\n",
1000 	    (u_longlong_t)db->db.db_object, db->db_level,
1001 	    (u_longlong_t)db->db_blkid);
1002 }
1003 #endif
1004 
1005 /*
1006  * If we can't do 10 iops, something is wrong.  Let us go ahead
1007  * and hit zfs_dirty_data_max.
1008  */
1009 hrtime_t zfs_delay_max_ns = MSEC2NSEC(100);
1010 int zfs_delay_resolution_ns = 100 * 1000; /* 100 microseconds */
1011 
1012 /*
1013  * We delay transactions when we've determined that the backend storage
1014  * isn't able to accommodate the rate of incoming writes.
1015  *
1016  * If there is already a transaction waiting, we delay relative to when
1017  * that transaction finishes waiting.  This way the calculated min_time
1018  * is independent of the number of threads concurrently executing
1019  * transactions.
1020  *
1021  * If we are the only waiter, wait relative to when the transaction
1022  * started, rather than the current time.  This credits the transaction for
1023  * "time already served", e.g. reading indirect blocks.
1024  *
1025  * The minimum time for a transaction to take is calculated as:
1026  *     min_time = scale * (dirty - min) / (max - dirty)
1027  *     min_time is then capped at zfs_delay_max_ns.
1028  *
1029  * The delay has two degrees of freedom that can be adjusted via tunables.
1030  * The percentage of dirty data at which we start to delay is defined by
1031  * zfs_delay_min_dirty_percent. This should typically be at or above
1032  * zfs_vdev_async_write_active_max_dirty_percent so that we only start to
1033  * delay after writing at full speed has failed to keep up with the incoming
1034  * write rate. The scale of the curve is defined by zfs_delay_scale. Roughly
1035  * speaking, this variable determines the amount of delay at the midpoint of
1036  * the curve.
1037  *
1038  * delay
1039  *  10ms +-------------------------------------------------------------*+
1040  *       |                                                             *|
1041  *   9ms +                                                             *+
1042  *       |                                                             *|
1043  *   8ms +                                                             *+
1044  *       |                                                            * |
1045  *   7ms +                                                            * +
1046  *       |                                                            * |
1047  *   6ms +                                                            * +
1048  *       |                                                            * |
1049  *   5ms +                                                           *  +
1050  *       |                                                           *  |
1051  *   4ms +                                                           *  +
1052  *       |                                                           *  |
1053  *   3ms +                                                          *   +
1054  *       |                                                          *   |
1055  *   2ms +                                              (midpoint) *    +
1056  *       |                                                  |    **     |
1057  *   1ms +                                                  v ***       +
1058  *       |             zfs_delay_scale ---------->     ********         |
1059  *     0 +-------------------------------------*********----------------+
1060  *       0%                    <- zfs_dirty_data_max ->               100%
1061  *
1062  * Note that since the delay is added to the outstanding time remaining on the
1063  * most recent transaction, the delay is effectively the inverse of IOPS.
1064  * Here the midpoint of 500us translates to 2000 IOPS. The shape of the curve
1065  * was chosen such that small changes in the amount of accumulated dirty data
1066  * in the first 3/4 of the curve yield relatively small differences in the
1067  * amount of delay.
1068  *
1069  * The effects can be easier to understand when the amount of delay is
1070  * represented on a log scale:
1071  *
1072  * delay
1073  * 100ms +-------------------------------------------------------------++
1074  *       +                                                              +
1075  *       |                                                              |
1076  *       +                                                             *+
1077  *  10ms +                                                             *+
1078  *       +                                                           ** +
1079  *       |                                              (midpoint)  **  |
1080  *       +                                                  |     **    +
1081  *   1ms +                                                  v ****      +
1082  *       +             zfs_delay_scale ---------->        *****         +
1083  *       |                                             ****             |
1084  *       +                                          ****                +
1085  * 100us +                                        **                    +
1086  *       +                                       *                      +
1087  *       |                                      *                       |
1088  *       +                                     *                        +
1089  *  10us +                                     *                        +
1090  *       +                                                              +
1091  *       |                                                              |
1092  *       +                                                              +
1093  *       +--------------------------------------------------------------+
1094  *       0%                    <- zfs_dirty_data_max ->               100%
1095  *
1096  * Note here that only as the amount of dirty data approaches its limit does
1097  * the delay start to increase rapidly. The goal of a properly tuned system
1098  * should be to keep the amount of dirty data out of that range by first
1099  * ensuring that the appropriate limits are set for the I/O scheduler to reach
1100  * optimal throughput on the backend storage, and then by changing the value
1101  * of zfs_delay_scale to increase the steepness of the curve.
1102  */
1103 static void
1104 dmu_tx_delay(dmu_tx_t *tx, uint64_t dirty)
1105 {
1106 	dsl_pool_t *dp = tx->tx_pool;
1107 	uint64_t delay_min_bytes =
1108 	    zfs_dirty_data_max * zfs_delay_min_dirty_percent / 100;
1109 	hrtime_t wakeup, min_tx_time, now;
1110 
1111 	if (dirty <= delay_min_bytes)
1112 		return;
1113 
1114 	/*
1115 	 * The caller has already waited until we are under the max.
1116 	 * We make them pass us the amount of dirty data so we don't
1117 	 * have to handle the case of it being >= the max, which could
1118 	 * cause a divide-by-zero if it's == the max.
1119 	 */
1120 	ASSERT3U(dirty, <, zfs_dirty_data_max);
1121 
1122 	now = gethrtime();
1123 	min_tx_time = zfs_delay_scale *
1124 	    (dirty - delay_min_bytes) / (zfs_dirty_data_max - dirty);
1125 	if (now > tx->tx_start + min_tx_time)
1126 		return;
1127 
1128 	min_tx_time = MIN(min_tx_time, zfs_delay_max_ns);
1129 
1130 	DTRACE_PROBE3(delay__mintime, dmu_tx_t *, tx, uint64_t, dirty,
1131 	    uint64_t, min_tx_time);
1132 
1133 	mutex_enter(&dp->dp_lock);
1134 	wakeup = MAX(tx->tx_start + min_tx_time,
1135 	    dp->dp_last_wakeup + min_tx_time);
1136 	dp->dp_last_wakeup = wakeup;
1137 	mutex_exit(&dp->dp_lock);
1138 
1139 #ifdef _KERNEL
1140 	mutex_enter(&curthread->t_delay_lock);
1141 	while (cv_timedwait_hires(&curthread->t_delay_cv,
1142 	    &curthread->t_delay_lock, wakeup, zfs_delay_resolution_ns,
1143 	    CALLOUT_FLAG_ABSOLUTE | CALLOUT_FLAG_ROUNDUP) > 0)
1144 		continue;
1145 	mutex_exit(&curthread->t_delay_lock);
1146 #else
1147 	hrtime_t delta = wakeup - gethrtime();
1148 	struct timespec ts;
1149 	ts.tv_sec = delta / NANOSEC;
1150 	ts.tv_nsec = delta % NANOSEC;
1151 	(void) nanosleep(&ts, NULL);
1152 #endif
1153 }
1154 
1155 static int
1156 dmu_tx_try_assign(dmu_tx_t *tx, txg_how_t txg_how)
1157 {
1158 	dmu_tx_hold_t *txh;
1159 	spa_t *spa = tx->tx_pool->dp_spa;
1160 	uint64_t memory, asize, fsize, usize;
1161 	uint64_t towrite, tofree, tooverwrite, tounref, tohold, fudge;
1162 
1163 	ASSERT0(tx->tx_txg);
1164 
1165 	if (tx->tx_err)
1166 		return (tx->tx_err);
1167 
1168 	if (spa_suspended(spa)) {
1169 		/*
1170 		 * If the user has indicated a blocking failure mode
1171 		 * then return ERESTART which will block in dmu_tx_wait().
1172 		 * Otherwise, return EIO so that an error can get
1173 		 * propagated back to the VOP calls.
1174 		 *
1175 		 * Note that we always honor the txg_how flag regardless
1176 		 * of the failuremode setting.
1177 		 */
1178 		if (spa_get_failmode(spa) == ZIO_FAILURE_MODE_CONTINUE &&
1179 		    txg_how != TXG_WAIT)
1180 			return (SET_ERROR(EIO));
1181 
1182 		return (SET_ERROR(ERESTART));
1183 	}
1184 
1185 	if (!tx->tx_waited &&
1186 	    dsl_pool_need_dirty_delay(tx->tx_pool)) {
1187 		tx->tx_wait_dirty = B_TRUE;
1188 		return (SET_ERROR(ERESTART));
1189 	}
1190 
1191 	tx->tx_txg = txg_hold_open(tx->tx_pool, &tx->tx_txgh);
1192 	tx->tx_needassign_txh = NULL;
1193 
1194 	/*
1195 	 * NB: No error returns are allowed after txg_hold_open, but
1196 	 * before processing the dnode holds, due to the
1197 	 * dmu_tx_unassign() logic.
1198 	 */
1199 
1200 	towrite = tofree = tooverwrite = tounref = tohold = fudge = 0;
1201 	for (txh = list_head(&tx->tx_holds); txh;
1202 	    txh = list_next(&tx->tx_holds, txh)) {
1203 		dnode_t *dn = txh->txh_dnode;
1204 		if (dn != NULL) {
1205 			mutex_enter(&dn->dn_mtx);
1206 			if (dn->dn_assigned_txg == tx->tx_txg - 1) {
1207 				mutex_exit(&dn->dn_mtx);
1208 				tx->tx_needassign_txh = txh;
1209 				return (SET_ERROR(ERESTART));
1210 			}
1211 			if (dn->dn_assigned_txg == 0)
1212 				dn->dn_assigned_txg = tx->tx_txg;
1213 			ASSERT3U(dn->dn_assigned_txg, ==, tx->tx_txg);
1214 			(void) refcount_add(&dn->dn_tx_holds, tx);
1215 			mutex_exit(&dn->dn_mtx);
1216 		}
1217 		towrite += refcount_count(&txh->txh_space_towrite);
1218 		tofree += refcount_count(&txh->txh_space_tofree);
1219 		tooverwrite += refcount_count(&txh->txh_space_tooverwrite);
1220 		tounref += refcount_count(&txh->txh_space_tounref);
1221 		tohold += refcount_count(&txh->txh_memory_tohold);
1222 		fudge += refcount_count(&txh->txh_fudge);
1223 	}
1224 
1225 	/*
1226 	 * If a snapshot has been taken since we made our estimates,
1227 	 * assume that we won't be able to free or overwrite anything.
1228 	 */
1229 	if (tx->tx_objset &&
1230 	    dsl_dataset_prev_snap_txg(tx->tx_objset->os_dsl_dataset) >
1231 	    tx->tx_lastsnap_txg) {
1232 		towrite += tooverwrite;
1233 		tooverwrite = tofree = 0;
1234 	}
1235 
1236 	/* needed allocation: worst-case estimate of write space */
1237 	asize = spa_get_asize(tx->tx_pool->dp_spa, towrite + tooverwrite);
1238 	/* freed space estimate: worst-case overwrite + free estimate */
1239 	fsize = spa_get_asize(tx->tx_pool->dp_spa, tooverwrite) + tofree;
1240 	/* convert unrefd space to worst-case estimate */
1241 	usize = spa_get_asize(tx->tx_pool->dp_spa, tounref);
1242 	/* calculate memory footprint estimate */
1243 	memory = towrite + tooverwrite + tohold;
1244 
1245 #ifdef ZFS_DEBUG
1246 	/*
1247 	 * Add in 'tohold' to account for our dirty holds on this memory
1248 	 * XXX - the "fudge" factor is to account for skipped blocks that
1249 	 * we missed because dnode_next_offset() misses in-core-only blocks.
1250 	 */
1251 	tx->tx_space_towrite = asize +
1252 	    spa_get_asize(tx->tx_pool->dp_spa, tohold + fudge);
1253 	tx->tx_space_tofree = tofree;
1254 	tx->tx_space_tooverwrite = tooverwrite;
1255 	tx->tx_space_tounref = tounref;
1256 #endif
1257 
1258 	if (tx->tx_dir && asize != 0) {
1259 		int err = dsl_dir_tempreserve_space(tx->tx_dir, memory,
1260 		    asize, fsize, usize, &tx->tx_tempreserve_cookie, tx);
1261 		if (err)
1262 			return (err);
1263 	}
1264 
1265 	return (0);
1266 }
1267 
1268 static void
1269 dmu_tx_unassign(dmu_tx_t *tx)
1270 {
1271 	dmu_tx_hold_t *txh;
1272 
1273 	if (tx->tx_txg == 0)
1274 		return;
1275 
1276 	txg_rele_to_quiesce(&tx->tx_txgh);
1277 
1278 	/*
1279 	 * Walk the transaction's hold list, removing the hold on the
1280 	 * associated dnode, and notifying waiters if the refcount drops to 0.
1281 	 */
1282 	for (txh = list_head(&tx->tx_holds); txh != tx->tx_needassign_txh;
1283 	    txh = list_next(&tx->tx_holds, txh)) {
1284 		dnode_t *dn = txh->txh_dnode;
1285 
1286 		if (dn == NULL)
1287 			continue;
1288 		mutex_enter(&dn->dn_mtx);
1289 		ASSERT3U(dn->dn_assigned_txg, ==, tx->tx_txg);
1290 
1291 		if (refcount_remove(&dn->dn_tx_holds, tx) == 0) {
1292 			dn->dn_assigned_txg = 0;
1293 			cv_broadcast(&dn->dn_notxholds);
1294 		}
1295 		mutex_exit(&dn->dn_mtx);
1296 	}
1297 
1298 	txg_rele_to_sync(&tx->tx_txgh);
1299 
1300 	tx->tx_lasttried_txg = tx->tx_txg;
1301 	tx->tx_txg = 0;
1302 }
1303 
1304 /*
1305  * Assign tx to a transaction group.  txg_how can be one of:
1306  *
1307  * (1)	TXG_WAIT.  If the current open txg is full, waits until there's
1308  *	a new one.  This should be used when you're not holding locks.
1309  *	It will only fail if we're truly out of space (or over quota).
1310  *
1311  * (2)	TXG_NOWAIT.  If we can't assign into the current open txg without
1312  *	blocking, returns immediately with ERESTART.  This should be used
1313  *	whenever you're holding locks.  On an ERESTART error, the caller
1314  *	should drop locks, do a dmu_tx_wait(tx), and try again.
1315  *
1316  * (3)  TXG_WAITED.  Like TXG_NOWAIT, but indicates that dmu_tx_wait()
1317  *      has already been called on behalf of this operation (though
1318  *      most likely on a different tx).
1319  */
1320 int
1321 dmu_tx_assign(dmu_tx_t *tx, txg_how_t txg_how)
1322 {
1323 	int err;
1324 
1325 	ASSERT(tx->tx_txg == 0);
1326 	ASSERT(txg_how == TXG_WAIT || txg_how == TXG_NOWAIT ||
1327 	    txg_how == TXG_WAITED);
1328 	ASSERT(!dsl_pool_sync_context(tx->tx_pool));
1329 
1330 	/* If we might wait, we must not hold the config lock. */
1331 	ASSERT(txg_how != TXG_WAIT || !dsl_pool_config_held(tx->tx_pool));
1332 
1333 	if (txg_how == TXG_WAITED)
1334 		tx->tx_waited = B_TRUE;
1335 
1336 	while ((err = dmu_tx_try_assign(tx, txg_how)) != 0) {
1337 		dmu_tx_unassign(tx);
1338 
1339 		if (err != ERESTART || txg_how != TXG_WAIT)
1340 			return (err);
1341 
1342 		dmu_tx_wait(tx);
1343 	}
1344 
1345 	txg_rele_to_quiesce(&tx->tx_txgh);
1346 
1347 	return (0);
1348 }
1349 
1350 void
1351 dmu_tx_wait(dmu_tx_t *tx)
1352 {
1353 	spa_t *spa = tx->tx_pool->dp_spa;
1354 	dsl_pool_t *dp = tx->tx_pool;
1355 
1356 	ASSERT(tx->tx_txg == 0);
1357 	ASSERT(!dsl_pool_config_held(tx->tx_pool));
1358 
1359 	if (tx->tx_wait_dirty) {
1360 		/*
1361 		 * dmu_tx_try_assign() has determined that we need to wait
1362 		 * because we've consumed much or all of the dirty buffer
1363 		 * space.
1364 		 */
1365 		mutex_enter(&dp->dp_lock);
1366 		while (dp->dp_dirty_total >= zfs_dirty_data_max)
1367 			cv_wait(&dp->dp_spaceavail_cv, &dp->dp_lock);
1368 		uint64_t dirty = dp->dp_dirty_total;
1369 		mutex_exit(&dp->dp_lock);
1370 
1371 		dmu_tx_delay(tx, dirty);
1372 
1373 		tx->tx_wait_dirty = B_FALSE;
1374 
1375 		/*
1376 		 * Note: setting tx_waited only has effect if the caller
1377 		 * used TX_WAIT.  Otherwise they are going to destroy
1378 		 * this tx and try again.  The common case, zfs_write(),
1379 		 * uses TX_WAIT.
1380 		 */
1381 		tx->tx_waited = B_TRUE;
1382 	} else if (spa_suspended(spa) || tx->tx_lasttried_txg == 0) {
1383 		/*
1384 		 * If the pool is suspended we need to wait until it
1385 		 * is resumed.  Note that it's possible that the pool
1386 		 * has become active after this thread has tried to
1387 		 * obtain a tx.  If that's the case then tx_lasttried_txg
1388 		 * would not have been set.
1389 		 */
1390 		txg_wait_synced(dp, spa_last_synced_txg(spa) + 1);
1391 	} else if (tx->tx_needassign_txh) {
1392 		/*
1393 		 * A dnode is assigned to the quiescing txg.  Wait for its
1394 		 * transaction to complete.
1395 		 */
1396 		dnode_t *dn = tx->tx_needassign_txh->txh_dnode;
1397 
1398 		mutex_enter(&dn->dn_mtx);
1399 		while (dn->dn_assigned_txg == tx->tx_lasttried_txg - 1)
1400 			cv_wait(&dn->dn_notxholds, &dn->dn_mtx);
1401 		mutex_exit(&dn->dn_mtx);
1402 		tx->tx_needassign_txh = NULL;
1403 	} else {
1404 		txg_wait_open(tx->tx_pool, tx->tx_lasttried_txg + 1);
1405 	}
1406 }
1407 
1408 void
1409 dmu_tx_willuse_space(dmu_tx_t *tx, int64_t delta)
1410 {
1411 #ifdef ZFS_DEBUG
1412 	if (tx->tx_dir == NULL || delta == 0)
1413 		return;
1414 
1415 	if (delta > 0) {
1416 		ASSERT3U(refcount_count(&tx->tx_space_written) + delta, <=,
1417 		    tx->tx_space_towrite);
1418 		(void) refcount_add_many(&tx->tx_space_written, delta, NULL);
1419 	} else {
1420 		(void) refcount_add_many(&tx->tx_space_freed, -delta, NULL);
1421 	}
1422 #endif
1423 }
1424 
1425 static void
1426 dmu_tx_destroy(dmu_tx_t *tx)
1427 {
1428 	dmu_tx_hold_t *txh;
1429 
1430 	while ((txh = list_head(&tx->tx_holds)) != NULL) {
1431 		dnode_t *dn = txh->txh_dnode;
1432 
1433 		list_remove(&tx->tx_holds, txh);
1434 		refcount_destroy_many(&txh->txh_space_towrite,
1435 		    refcount_count(&txh->txh_space_towrite));
1436 		refcount_destroy_many(&txh->txh_space_tofree,
1437 		    refcount_count(&txh->txh_space_tofree));
1438 		refcount_destroy_many(&txh->txh_space_tooverwrite,
1439 		    refcount_count(&txh->txh_space_tooverwrite));
1440 		refcount_destroy_many(&txh->txh_space_tounref,
1441 		    refcount_count(&txh->txh_space_tounref));
1442 		refcount_destroy_many(&txh->txh_memory_tohold,
1443 		    refcount_count(&txh->txh_memory_tohold));
1444 		refcount_destroy_many(&txh->txh_fudge,
1445 		    refcount_count(&txh->txh_fudge));
1446 		kmem_free(txh, sizeof (dmu_tx_hold_t));
1447 		if (dn != NULL)
1448 			dnode_rele(dn, tx);
1449 	}
1450 
1451 	list_destroy(&tx->tx_callbacks);
1452 	list_destroy(&tx->tx_holds);
1453 #ifdef ZFS_DEBUG
1454 	refcount_destroy_many(&tx->tx_space_written,
1455 	    refcount_count(&tx->tx_space_written));
1456 	refcount_destroy_many(&tx->tx_space_freed,
1457 	    refcount_count(&tx->tx_space_freed));
1458 #endif
1459 	kmem_free(tx, sizeof (dmu_tx_t));
1460 }
1461 
1462 void
1463 dmu_tx_commit(dmu_tx_t *tx)
1464 {
1465 	ASSERT(tx->tx_txg != 0);
1466 
1467 	/*
1468 	 * Go through the transaction's hold list and remove holds on
1469 	 * associated dnodes, notifying waiters if no holds remain.
1470 	 */
1471 	for (dmu_tx_hold_t *txh = list_head(&tx->tx_holds); txh != NULL;
1472 	    txh = list_next(&tx->tx_holds, txh)) {
1473 		dnode_t *dn = txh->txh_dnode;
1474 
1475 		if (dn == NULL)
1476 			continue;
1477 
1478 		mutex_enter(&dn->dn_mtx);
1479 		ASSERT3U(dn->dn_assigned_txg, ==, tx->tx_txg);
1480 
1481 		if (refcount_remove(&dn->dn_tx_holds, tx) == 0) {
1482 			dn->dn_assigned_txg = 0;
1483 			cv_broadcast(&dn->dn_notxholds);
1484 		}
1485 		mutex_exit(&dn->dn_mtx);
1486 	}
1487 
1488 	if (tx->tx_tempreserve_cookie)
1489 		dsl_dir_tempreserve_clear(tx->tx_tempreserve_cookie, tx);
1490 
1491 	if (!list_is_empty(&tx->tx_callbacks))
1492 		txg_register_callbacks(&tx->tx_txgh, &tx->tx_callbacks);
1493 
1494 	if (tx->tx_anyobj == FALSE)
1495 		txg_rele_to_sync(&tx->tx_txgh);
1496 
1497 #ifdef ZFS_DEBUG
1498 	dprintf("towrite=%llu written=%llu tofree=%llu freed=%llu\n",
1499 	    tx->tx_space_towrite, refcount_count(&tx->tx_space_written),
1500 	    tx->tx_space_tofree, refcount_count(&tx->tx_space_freed));
1501 #endif
1502 	dmu_tx_destroy(tx);
1503 }
1504 
1505 void
1506 dmu_tx_abort(dmu_tx_t *tx)
1507 {
1508 	ASSERT(tx->tx_txg == 0);
1509 
1510 	/*
1511 	 * Call any registered callbacks with an error code.
1512 	 */
1513 	if (!list_is_empty(&tx->tx_callbacks))
1514 		dmu_tx_do_callbacks(&tx->tx_callbacks, ECANCELED);
1515 
1516 	dmu_tx_destroy(tx);
1517 }
1518 
1519 uint64_t
1520 dmu_tx_get_txg(dmu_tx_t *tx)
1521 {
1522 	ASSERT(tx->tx_txg != 0);
1523 	return (tx->tx_txg);
1524 }
1525 
1526 dsl_pool_t *
1527 dmu_tx_pool(dmu_tx_t *tx)
1528 {
1529 	ASSERT(tx->tx_pool != NULL);
1530 	return (tx->tx_pool);
1531 }
1532 
1533 
1534 void
1535 dmu_tx_callback_register(dmu_tx_t *tx, dmu_tx_callback_func_t *func, void *data)
1536 {
1537 	dmu_tx_callback_t *dcb;
1538 
1539 	dcb = kmem_alloc(sizeof (dmu_tx_callback_t), KM_SLEEP);
1540 
1541 	dcb->dcb_func = func;
1542 	dcb->dcb_data = data;
1543 
1544 	list_insert_tail(&tx->tx_callbacks, dcb);
1545 }
1546 
1547 /*
1548  * Call all the commit callbacks on a list, with a given error code.
1549  */
1550 void
1551 dmu_tx_do_callbacks(list_t *cb_list, int error)
1552 {
1553 	dmu_tx_callback_t *dcb;
1554 
1555 	while ((dcb = list_head(cb_list)) != NULL) {
1556 		list_remove(cb_list, dcb);
1557 		dcb->dcb_func(dcb->dcb_data, error);
1558 		kmem_free(dcb, sizeof (dmu_tx_callback_t));
1559 	}
1560 }
1561 
1562 /*
1563  * Interface to hold a bunch of attributes.
1564  * used for creating new files.
1565  * attrsize is the total size of all attributes
1566  * to be added during object creation
1567  *
1568  * For updating/adding a single attribute dmu_tx_hold_sa() should be used.
1569  */
1570 
1571 /*
1572  * hold necessary attribute name for attribute registration.
1573  * should be a very rare case where this is needed.  If it does
1574  * happen it would only happen on the first write to the file system.
1575  */
1576 static void
1577 dmu_tx_sa_registration_hold(sa_os_t *sa, dmu_tx_t *tx)
1578 {
1579 	int i;
1580 
1581 	if (!sa->sa_need_attr_registration)
1582 		return;
1583 
1584 	for (i = 0; i != sa->sa_num_attrs; i++) {
1585 		if (!sa->sa_attr_table[i].sa_registered) {
1586 			if (sa->sa_reg_attr_obj)
1587 				dmu_tx_hold_zap(tx, sa->sa_reg_attr_obj,
1588 				    B_TRUE, sa->sa_attr_table[i].sa_name);
1589 			else
1590 				dmu_tx_hold_zap(tx, DMU_NEW_OBJECT,
1591 				    B_TRUE, sa->sa_attr_table[i].sa_name);
1592 		}
1593 	}
1594 }
1595 
1596 
1597 void
1598 dmu_tx_hold_spill(dmu_tx_t *tx, uint64_t object)
1599 {
1600 	dnode_t *dn;
1601 	dmu_tx_hold_t *txh;
1602 
1603 	txh = dmu_tx_hold_object_impl(tx, tx->tx_objset, object,
1604 	    THT_SPILL, 0, 0);
1605 
1606 	dn = txh->txh_dnode;
1607 
1608 	if (dn == NULL)
1609 		return;
1610 
1611 	/* If blkptr doesn't exist then add space to towrite */
1612 	if (!(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR)) {
1613 		(void) refcount_add_many(&txh->txh_space_towrite,
1614 		    SPA_OLD_MAXBLOCKSIZE, FTAG);
1615 	} else {
1616 		blkptr_t *bp;
1617 
1618 		bp = &dn->dn_phys->dn_spill;
1619 		if (dsl_dataset_block_freeable(dn->dn_objset->os_dsl_dataset,
1620 		    bp, bp->blk_birth)) {
1621 			(void) refcount_add_many(&txh->txh_space_tooverwrite,
1622 			    SPA_OLD_MAXBLOCKSIZE, FTAG);
1623 		} else {
1624 			(void) refcount_add_many(&txh->txh_space_towrite,
1625 			    SPA_OLD_MAXBLOCKSIZE, FTAG);
1626 		}
1627 		if (!BP_IS_HOLE(bp)) {
1628 			(void) refcount_add_many(&txh->txh_space_tounref,
1629 			    SPA_OLD_MAXBLOCKSIZE, FTAG);
1630 		}
1631 	}
1632 }
1633 
1634 void
1635 dmu_tx_hold_sa_create(dmu_tx_t *tx, int attrsize)
1636 {
1637 	sa_os_t *sa = tx->tx_objset->os_sa;
1638 
1639 	dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
1640 
1641 	if (tx->tx_objset->os_sa->sa_master_obj == 0)
1642 		return;
1643 
1644 	if (tx->tx_objset->os_sa->sa_layout_attr_obj)
1645 		dmu_tx_hold_zap(tx, sa->sa_layout_attr_obj, B_TRUE, NULL);
1646 	else {
1647 		dmu_tx_hold_zap(tx, sa->sa_master_obj, B_TRUE, SA_LAYOUTS);
1648 		dmu_tx_hold_zap(tx, sa->sa_master_obj, B_TRUE, SA_REGISTRY);
1649 		dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, B_TRUE, NULL);
1650 		dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, B_TRUE, NULL);
1651 	}
1652 
1653 	dmu_tx_sa_registration_hold(sa, tx);
1654 
1655 	if (attrsize <= DN_MAX_BONUSLEN && !sa->sa_force_spill)
1656 		return;
1657 
1658 	(void) dmu_tx_hold_object_impl(tx, tx->tx_objset, DMU_NEW_OBJECT,
1659 	    THT_SPILL, 0, 0);
1660 }
1661 
1662 /*
1663  * Hold SA attribute
1664  *
1665  * dmu_tx_hold_sa(dmu_tx_t *tx, sa_handle_t *, attribute, add, size)
1666  *
1667  * variable_size is the total size of all variable sized attributes
1668  * passed to this function.  It is not the total size of all
1669  * variable size attributes that *may* exist on this object.
1670  */
1671 void
1672 dmu_tx_hold_sa(dmu_tx_t *tx, sa_handle_t *hdl, boolean_t may_grow)
1673 {
1674 	uint64_t object;
1675 	sa_os_t *sa = tx->tx_objset->os_sa;
1676 
1677 	ASSERT(hdl != NULL);
1678 
1679 	object = sa_handle_object(hdl);
1680 
1681 	dmu_tx_hold_bonus(tx, object);
1682 
1683 	if (tx->tx_objset->os_sa->sa_master_obj == 0)
1684 		return;
1685 
1686 	if (tx->tx_objset->os_sa->sa_reg_attr_obj == 0 ||
1687 	    tx->tx_objset->os_sa->sa_layout_attr_obj == 0) {
1688 		dmu_tx_hold_zap(tx, sa->sa_master_obj, B_TRUE, SA_LAYOUTS);
1689 		dmu_tx_hold_zap(tx, sa->sa_master_obj, B_TRUE, SA_REGISTRY);
1690 		dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, B_TRUE, NULL);
1691 		dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, B_TRUE, NULL);
1692 	}
1693 
1694 	dmu_tx_sa_registration_hold(sa, tx);
1695 
1696 	if (may_grow && tx->tx_objset->os_sa->sa_layout_attr_obj)
1697 		dmu_tx_hold_zap(tx, sa->sa_layout_attr_obj, B_TRUE, NULL);
1698 
1699 	if (sa->sa_force_spill || may_grow || hdl->sa_spill) {
1700 		ASSERT(tx->tx_txg == 0);
1701 		dmu_tx_hold_spill(tx, object);
1702 	} else {
1703 		dmu_buf_impl_t *db = (dmu_buf_impl_t *)hdl->sa_bonus;
1704 		dnode_t *dn;
1705 
1706 		DB_DNODE_ENTER(db);
1707 		dn = DB_DNODE(db);
1708 		if (dn->dn_have_spill) {
1709 			ASSERT(tx->tx_txg == 0);
1710 			dmu_tx_hold_spill(tx, object);
1711 		}
1712 		DB_DNODE_EXIT(db);
1713 	}
1714 }
1715