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