xref: /illumos-gate/usr/src/uts/common/fs/zfs/dmu_tx.c (revision cdb0ab79ea1af7b8fc339a04d4bf7426dc77ec4e)
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 2008 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
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/zfs_context.h>
39 
40 typedef void (*dmu_tx_hold_func_t)(dmu_tx_t *tx, struct dnode *dn,
41     uint64_t arg1, uint64_t arg2);
42 
43 
44 dmu_tx_t *
45 dmu_tx_create_dd(dsl_dir_t *dd)
46 {
47 	dmu_tx_t *tx = kmem_zalloc(sizeof (dmu_tx_t), KM_SLEEP);
48 	tx->tx_dir = dd;
49 	if (dd)
50 		tx->tx_pool = dd->dd_pool;
51 	list_create(&tx->tx_holds, sizeof (dmu_tx_hold_t),
52 	    offsetof(dmu_tx_hold_t, txh_node));
53 #ifdef ZFS_DEBUG
54 	refcount_create(&tx->tx_space_written);
55 	refcount_create(&tx->tx_space_freed);
56 #endif
57 	return (tx);
58 }
59 
60 dmu_tx_t *
61 dmu_tx_create(objset_t *os)
62 {
63 	dmu_tx_t *tx = dmu_tx_create_dd(os->os->os_dsl_dataset->ds_dir);
64 	tx->tx_objset = os;
65 	tx->tx_lastsnap_txg = dsl_dataset_prev_snap_txg(os->os->os_dsl_dataset);
66 	return (tx);
67 }
68 
69 dmu_tx_t *
70 dmu_tx_create_assigned(struct dsl_pool *dp, uint64_t txg)
71 {
72 	dmu_tx_t *tx = dmu_tx_create_dd(NULL);
73 
74 	ASSERT3U(txg, <=, dp->dp_tx.tx_open_txg);
75 	tx->tx_pool = dp;
76 	tx->tx_txg = txg;
77 	tx->tx_anyobj = TRUE;
78 
79 	return (tx);
80 }
81 
82 int
83 dmu_tx_is_syncing(dmu_tx_t *tx)
84 {
85 	return (tx->tx_anyobj);
86 }
87 
88 int
89 dmu_tx_private_ok(dmu_tx_t *tx)
90 {
91 	return (tx->tx_anyobj);
92 }
93 
94 static dmu_tx_hold_t *
95 dmu_tx_hold_object_impl(dmu_tx_t *tx, objset_t *os, uint64_t object,
96     enum dmu_tx_hold_type type, uint64_t arg1, uint64_t arg2)
97 {
98 	dmu_tx_hold_t *txh;
99 	dnode_t *dn = NULL;
100 	int err;
101 
102 	if (object != DMU_NEW_OBJECT) {
103 		err = dnode_hold(os->os, object, tx, &dn);
104 		if (err) {
105 			tx->tx_err = err;
106 			return (NULL);
107 		}
108 
109 		if (err == 0 && tx->tx_txg != 0) {
110 			mutex_enter(&dn->dn_mtx);
111 			/*
112 			 * dn->dn_assigned_txg == tx->tx_txg doesn't pose a
113 			 * problem, but there's no way for it to happen (for
114 			 * now, at least).
115 			 */
116 			ASSERT(dn->dn_assigned_txg == 0);
117 			dn->dn_assigned_txg = tx->tx_txg;
118 			(void) refcount_add(&dn->dn_tx_holds, tx);
119 			mutex_exit(&dn->dn_mtx);
120 		}
121 	}
122 
123 	txh = kmem_zalloc(sizeof (dmu_tx_hold_t), KM_SLEEP);
124 	txh->txh_tx = tx;
125 	txh->txh_dnode = dn;
126 #ifdef ZFS_DEBUG
127 	txh->txh_type = type;
128 	txh->txh_arg1 = arg1;
129 	txh->txh_arg2 = arg2;
130 #endif
131 	list_insert_tail(&tx->tx_holds, txh);
132 
133 	return (txh);
134 }
135 
136 void
137 dmu_tx_add_new_object(dmu_tx_t *tx, objset_t *os, uint64_t object)
138 {
139 	/*
140 	 * If we're syncing, they can manipulate any object anyhow, and
141 	 * the hold on the dnode_t can cause problems.
142 	 */
143 	if (!dmu_tx_is_syncing(tx)) {
144 		(void) dmu_tx_hold_object_impl(tx, os,
145 		    object, THT_NEWOBJECT, 0, 0);
146 	}
147 }
148 
149 static int
150 dmu_tx_check_ioerr(zio_t *zio, dnode_t *dn, int level, uint64_t blkid)
151 {
152 	int err;
153 	dmu_buf_impl_t *db;
154 
155 	rw_enter(&dn->dn_struct_rwlock, RW_READER);
156 	db = dbuf_hold_level(dn, level, blkid, FTAG);
157 	rw_exit(&dn->dn_struct_rwlock);
158 	if (db == NULL)
159 		return (EIO);
160 	err = dbuf_read(db, zio, DB_RF_CANFAIL | DB_RF_NOPREFETCH);
161 	dbuf_rele(db, FTAG);
162 	return (err);
163 }
164 
165 /* ARGSUSED */
166 static void
167 dmu_tx_count_write(dmu_tx_hold_t *txh, uint64_t off, uint64_t len)
168 {
169 	dnode_t *dn = txh->txh_dnode;
170 	uint64_t start, end, i;
171 	int min_bs, max_bs, min_ibs, max_ibs, epbs, bits;
172 	int err = 0;
173 
174 	if (len == 0)
175 		return;
176 
177 	min_bs = SPA_MINBLOCKSHIFT;
178 	max_bs = SPA_MAXBLOCKSHIFT;
179 	min_ibs = DN_MIN_INDBLKSHIFT;
180 	max_ibs = DN_MAX_INDBLKSHIFT;
181 
182 
183 	/*
184 	 * For i/o error checking, read the first and last level-0
185 	 * blocks (if they are not aligned), and all the level-1 blocks.
186 	 */
187 
188 	if (dn) {
189 		if (dn->dn_maxblkid == 0) {
190 			err = dmu_tx_check_ioerr(NULL, dn, 0, 0);
191 			if (err)
192 				goto out;
193 		} else {
194 			zio_t *zio = zio_root(dn->dn_objset->os_spa,
195 			    NULL, NULL, ZIO_FLAG_CANFAIL);
196 
197 			/* first level-0 block */
198 			start = off >> dn->dn_datablkshift;
199 			if (P2PHASE(off, dn->dn_datablksz) ||
200 			    len < dn->dn_datablksz) {
201 				err = dmu_tx_check_ioerr(zio, dn, 0, start);
202 				if (err)
203 					goto out;
204 			}
205 
206 			/* last level-0 block */
207 			end = (off+len-1) >> dn->dn_datablkshift;
208 			if (end != start &&
209 			    P2PHASE(off+len, dn->dn_datablksz)) {
210 				err = dmu_tx_check_ioerr(zio, dn, 0, end);
211 				if (err)
212 					goto out;
213 			}
214 
215 			/* level-1 blocks */
216 			if (dn->dn_nlevels > 1) {
217 				start >>= dn->dn_indblkshift - SPA_BLKPTRSHIFT;
218 				end >>= dn->dn_indblkshift - SPA_BLKPTRSHIFT;
219 				for (i = start+1; i < end; i++) {
220 					err = dmu_tx_check_ioerr(zio, dn, 1, i);
221 					if (err)
222 						goto out;
223 				}
224 			}
225 
226 			err = zio_wait(zio);
227 			if (err)
228 				goto out;
229 		}
230 	}
231 
232 	/*
233 	 * If there's more than one block, the blocksize can't change,
234 	 * so we can make a more precise estimate.  Alternatively,
235 	 * if the dnode's ibs is larger than max_ibs, always use that.
236 	 * This ensures that if we reduce DN_MAX_INDBLKSHIFT,
237 	 * the code will still work correctly on existing pools.
238 	 */
239 	if (dn && (dn->dn_maxblkid != 0 || dn->dn_indblkshift > max_ibs)) {
240 		min_ibs = max_ibs = dn->dn_indblkshift;
241 		if (dn->dn_datablkshift != 0)
242 			min_bs = max_bs = dn->dn_datablkshift;
243 	}
244 
245 	/*
246 	 * 'end' is the last thing we will access, not one past.
247 	 * This way we won't overflow when accessing the last byte.
248 	 */
249 	start = P2ALIGN(off, 1ULL << max_bs);
250 	end = P2ROUNDUP(off + len, 1ULL << max_bs) - 1;
251 	txh->txh_space_towrite += end - start + 1;
252 
253 	start >>= min_bs;
254 	end >>= min_bs;
255 
256 	epbs = min_ibs - SPA_BLKPTRSHIFT;
257 
258 	/*
259 	 * The object contains at most 2^(64 - min_bs) blocks,
260 	 * and each indirect level maps 2^epbs.
261 	 */
262 	for (bits = 64 - min_bs; bits >= 0; bits -= epbs) {
263 		start >>= epbs;
264 		end >>= epbs;
265 		/*
266 		 * If we increase the number of levels of indirection,
267 		 * we'll need new blkid=0 indirect blocks.  If start == 0,
268 		 * we're already accounting for that blocks; and if end == 0,
269 		 * we can't increase the number of levels beyond that.
270 		 */
271 		if (start != 0 && end != 0)
272 			txh->txh_space_towrite += 1ULL << max_ibs;
273 		txh->txh_space_towrite += (end - start + 1) << max_ibs;
274 	}
275 
276 	ASSERT(txh->txh_space_towrite < 2 * DMU_MAX_ACCESS);
277 
278 out:
279 	if (err)
280 		txh->txh_tx->tx_err = err;
281 }
282 
283 static void
284 dmu_tx_count_dnode(dmu_tx_hold_t *txh)
285 {
286 	dnode_t *dn = txh->txh_dnode;
287 	dnode_t *mdn = txh->txh_tx->tx_objset->os->os_meta_dnode;
288 	uint64_t space = mdn->dn_datablksz +
289 	    ((mdn->dn_nlevels-1) << mdn->dn_indblkshift);
290 
291 	if (dn && dn->dn_dbuf->db_blkptr &&
292 	    dsl_dataset_block_freeable(dn->dn_objset->os_dsl_dataset,
293 	    dn->dn_dbuf->db_blkptr->blk_birth)) {
294 		txh->txh_space_tooverwrite += space;
295 	} else {
296 		txh->txh_space_towrite += space;
297 		if (dn && dn->dn_dbuf->db_blkptr)
298 			txh->txh_space_tounref += space;
299 	}
300 }
301 
302 void
303 dmu_tx_hold_write(dmu_tx_t *tx, uint64_t object, uint64_t off, int len)
304 {
305 	dmu_tx_hold_t *txh;
306 
307 	ASSERT(tx->tx_txg == 0);
308 	ASSERT(len < DMU_MAX_ACCESS);
309 	ASSERT(len == 0 || UINT64_MAX - off >= len - 1);
310 
311 	txh = dmu_tx_hold_object_impl(tx, tx->tx_objset,
312 	    object, THT_WRITE, off, len);
313 	if (txh == NULL)
314 		return;
315 
316 	dmu_tx_count_write(txh, off, len);
317 	dmu_tx_count_dnode(txh);
318 }
319 
320 static void
321 dmu_tx_count_free(dmu_tx_hold_t *txh, uint64_t off, uint64_t len)
322 {
323 	uint64_t blkid, nblks, lastblk;
324 	uint64_t space = 0, unref = 0, skipped = 0;
325 	dnode_t *dn = txh->txh_dnode;
326 	dsl_dataset_t *ds = dn->dn_objset->os_dsl_dataset;
327 	spa_t *spa = txh->txh_tx->tx_pool->dp_spa;
328 	int epbs;
329 
330 	if (dn->dn_nlevels == 0)
331 		return;
332 
333 	/*
334 	 * The struct_rwlock protects us against dn_nlevels
335 	 * changing, in case (against all odds) we manage to dirty &
336 	 * sync out the changes after we check for being dirty.
337 	 * Also, dbuf_hold_level() wants us to have the struct_rwlock.
338 	 */
339 	rw_enter(&dn->dn_struct_rwlock, RW_READER);
340 	epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
341 	if (dn->dn_maxblkid == 0) {
342 		if (off == 0 && len >= dn->dn_datablksz) {
343 			blkid = 0;
344 			nblks = 1;
345 		} else {
346 			rw_exit(&dn->dn_struct_rwlock);
347 			return;
348 		}
349 	} else {
350 		blkid = off >> dn->dn_datablkshift;
351 		nblks = (len + dn->dn_datablksz - 1) >> dn->dn_datablkshift;
352 
353 		if (blkid >= dn->dn_maxblkid) {
354 			rw_exit(&dn->dn_struct_rwlock);
355 			return;
356 		}
357 		if (blkid + nblks > dn->dn_maxblkid)
358 			nblks = dn->dn_maxblkid - blkid;
359 
360 	}
361 	if (dn->dn_nlevels == 1) {
362 		int i;
363 		for (i = 0; i < nblks; i++) {
364 			blkptr_t *bp = dn->dn_phys->dn_blkptr;
365 			ASSERT3U(blkid + i, <, dn->dn_nblkptr);
366 			bp += blkid + i;
367 			if (dsl_dataset_block_freeable(ds, bp->blk_birth)) {
368 				dprintf_bp(bp, "can free old%s", "");
369 				space += bp_get_dasize(spa, bp);
370 			}
371 			unref += BP_GET_ASIZE(bp);
372 		}
373 		nblks = 0;
374 	}
375 
376 	/*
377 	 * Add in memory requirements of higher-level indirects
378 	 */
379 	if (nblks && dn->dn_nlevels > 2) {
380 		uint64_t blkcnt = 1 + ((nblks >> epbs) >> epbs);
381 		int level = 2;
382 
383 		while (level++ < dn->dn_nlevels) {
384 			txh->txh_memory_tohold += blkcnt << dn->dn_indblkshift;
385 			blkcnt = 1 + (blkcnt >> epbs);
386 		}
387 		ASSERT(blkcnt <= dn->dn_nblkptr);
388 	}
389 
390 	lastblk = blkid + nblks - 1;
391 	while (nblks) {
392 		dmu_buf_impl_t *dbuf;
393 		uint64_t ibyte, new_blkid;
394 		int epb = 1 << epbs;
395 		int err, i, blkoff, tochk;
396 		blkptr_t *bp;
397 
398 		ibyte = blkid << dn->dn_datablkshift;
399 		err = dnode_next_offset(dn,
400 		    DNODE_FIND_HAVELOCK, &ibyte, 2, 1, 0);
401 		new_blkid = ibyte >> dn->dn_datablkshift;
402 		if (err == ESRCH)
403 			break;
404 		if (err) {
405 			txh->txh_tx->tx_err = err;
406 			break;
407 		}
408 		if (new_blkid > lastblk)
409 			break;
410 
411 		if (new_blkid > blkid) {
412 			skipped += new_blkid - blkid - 1;
413 			nblks -= new_blkid - blkid;
414 			blkid = new_blkid;
415 		}
416 		blkoff = P2PHASE(blkid, epb);
417 		tochk = MIN(epb - blkoff, nblks);
418 
419 		dbuf = dbuf_hold_level(dn, 1, blkid >> epbs, FTAG);
420 
421 		txh->txh_memory_tohold += dbuf->db.db_size;
422 		if (txh->txh_memory_tohold > DMU_MAX_ACCESS) {
423 			txh->txh_tx->tx_err = E2BIG;
424 			dbuf_rele(dbuf, FTAG);
425 			break;
426 		}
427 		err = dbuf_read(dbuf, NULL, DB_RF_HAVESTRUCT | DB_RF_CANFAIL);
428 		if (err != 0) {
429 			txh->txh_tx->tx_err = err;
430 			dbuf_rele(dbuf, FTAG);
431 			break;
432 		}
433 
434 		bp = dbuf->db.db_data;
435 		bp += blkoff;
436 
437 		for (i = 0; i < tochk; i++) {
438 			if (dsl_dataset_block_freeable(ds, bp[i].blk_birth)) {
439 				dprintf_bp(&bp[i], "can free old%s", "");
440 				space += bp_get_dasize(spa, &bp[i]);
441 			}
442 			unref += BP_GET_ASIZE(bp);
443 		}
444 		dbuf_rele(dbuf, FTAG);
445 
446 		blkid += tochk;
447 		nblks -= tochk;
448 	}
449 	rw_exit(&dn->dn_struct_rwlock);
450 
451 	/* account for new level 1 indirect blocks that might show up */
452 	if (skipped) {
453 		skipped = MIN(skipped, DMU_MAX_DELETEBLKCNT >> epbs);
454 		txh->txh_memory_tohold += skipped << dn->dn_indblkshift;
455 	}
456 	txh->txh_space_tofree += space;
457 	txh->txh_space_tounref += unref;
458 }
459 
460 void
461 dmu_tx_hold_free(dmu_tx_t *tx, uint64_t object, uint64_t off, uint64_t len)
462 {
463 	dmu_tx_hold_t *txh;
464 	dnode_t *dn;
465 	uint64_t start, end, i;
466 	int err, shift;
467 	zio_t *zio;
468 
469 	ASSERT(tx->tx_txg == 0);
470 
471 	txh = dmu_tx_hold_object_impl(tx, tx->tx_objset,
472 	    object, THT_FREE, off, len);
473 	if (txh == NULL)
474 		return;
475 	dn = txh->txh_dnode;
476 
477 	/* first block */
478 	if (off != 0)
479 		dmu_tx_count_write(txh, off, 1);
480 	/* last block */
481 	if (len != DMU_OBJECT_END)
482 		dmu_tx_count_write(txh, off+len, 1);
483 
484 	if (off >= (dn->dn_maxblkid+1) * dn->dn_datablksz)
485 		return;
486 	if (len == DMU_OBJECT_END)
487 		len = (dn->dn_maxblkid+1) * dn->dn_datablksz - off;
488 
489 	/*
490 	 * For i/o error checking, read the first and last level-0
491 	 * blocks, and all the level-1 blocks.  The above count_write's
492 	 * have already taken care of the level-0 blocks.
493 	 */
494 	if (dn->dn_nlevels > 1) {
495 		shift = dn->dn_datablkshift + dn->dn_indblkshift -
496 		    SPA_BLKPTRSHIFT;
497 		start = off >> shift;
498 		end = dn->dn_datablkshift ? ((off+len) >> shift) : 0;
499 
500 		zio = zio_root(tx->tx_pool->dp_spa,
501 		    NULL, NULL, ZIO_FLAG_CANFAIL);
502 		for (i = start; i <= end; i++) {
503 			uint64_t ibyte = i << shift;
504 			err = dnode_next_offset(dn, 0, &ibyte, 2, 1, 0);
505 			i = ibyte >> shift;
506 			if (err == ESRCH)
507 				break;
508 			if (err) {
509 				tx->tx_err = err;
510 				return;
511 			}
512 
513 			err = dmu_tx_check_ioerr(zio, dn, 1, i);
514 			if (err) {
515 				tx->tx_err = err;
516 				return;
517 			}
518 		}
519 		err = zio_wait(zio);
520 		if (err) {
521 			tx->tx_err = err;
522 			return;
523 		}
524 	}
525 
526 	dmu_tx_count_dnode(txh);
527 	dmu_tx_count_free(txh, off, len);
528 }
529 
530 void
531 dmu_tx_hold_zap(dmu_tx_t *tx, uint64_t object, int add, char *name)
532 {
533 	dmu_tx_hold_t *txh;
534 	dnode_t *dn;
535 	uint64_t nblocks;
536 	int epbs, err;
537 
538 	ASSERT(tx->tx_txg == 0);
539 
540 	txh = dmu_tx_hold_object_impl(tx, tx->tx_objset,
541 	    object, THT_ZAP, add, (uintptr_t)name);
542 	if (txh == NULL)
543 		return;
544 	dn = txh->txh_dnode;
545 
546 	dmu_tx_count_dnode(txh);
547 
548 	if (dn == NULL) {
549 		/*
550 		 * We will be able to fit a new object's entries into one leaf
551 		 * block.  So there will be at most 2 blocks total,
552 		 * including the header block.
553 		 */
554 		dmu_tx_count_write(txh, 0, 2 << fzap_default_block_shift);
555 		return;
556 	}
557 
558 	ASSERT3P(dmu_ot[dn->dn_type].ot_byteswap, ==, zap_byteswap);
559 
560 	if (dn->dn_maxblkid == 0 && !add) {
561 		/*
562 		 * If there is only one block  (i.e. this is a micro-zap)
563 		 * and we are not adding anything, the accounting is simple.
564 		 */
565 		err = dmu_tx_check_ioerr(NULL, dn, 0, 0);
566 		if (err) {
567 			tx->tx_err = err;
568 			return;
569 		}
570 
571 		/*
572 		 * Use max block size here, since we don't know how much
573 		 * the size will change between now and the dbuf dirty call.
574 		 */
575 		if (dsl_dataset_block_freeable(dn->dn_objset->os_dsl_dataset,
576 		    dn->dn_phys->dn_blkptr[0].blk_birth)) {
577 			txh->txh_space_tooverwrite += SPA_MAXBLOCKSIZE;
578 		} else {
579 			txh->txh_space_towrite += SPA_MAXBLOCKSIZE;
580 			txh->txh_space_tounref +=
581 			    BP_GET_ASIZE(dn->dn_phys->dn_blkptr);
582 		}
583 		return;
584 	}
585 
586 	if (dn->dn_maxblkid > 0 && name) {
587 		/*
588 		 * access the name in this fat-zap so that we'll check
589 		 * for i/o errors to the leaf blocks, etc.
590 		 */
591 		err = zap_lookup(&dn->dn_objset->os, dn->dn_object, name,
592 		    8, 0, NULL);
593 		if (err == EIO) {
594 			tx->tx_err = err;
595 			return;
596 		}
597 	}
598 
599 	/*
600 	 * 3 blocks overwritten: target leaf, ptrtbl block, header block
601 	 * 3 new blocks written if adding: new split leaf, 2 grown ptrtbl blocks
602 	 */
603 	dmu_tx_count_write(txh, dn->dn_maxblkid * dn->dn_datablksz,
604 	    (3 + add ? 3 : 0) << dn->dn_datablkshift);
605 
606 	/*
607 	 * If the modified blocks are scattered to the four winds,
608 	 * we'll have to modify an indirect twig for each.
609 	 */
610 	epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
611 	for (nblocks = dn->dn_maxblkid >> epbs; nblocks != 0; nblocks >>= epbs)
612 		txh->txh_space_towrite += 3 << dn->dn_indblkshift;
613 }
614 
615 void
616 dmu_tx_hold_bonus(dmu_tx_t *tx, uint64_t object)
617 {
618 	dmu_tx_hold_t *txh;
619 
620 	ASSERT(tx->tx_txg == 0);
621 
622 	txh = dmu_tx_hold_object_impl(tx, tx->tx_objset,
623 	    object, THT_BONUS, 0, 0);
624 	if (txh)
625 		dmu_tx_count_dnode(txh);
626 }
627 
628 void
629 dmu_tx_hold_space(dmu_tx_t *tx, uint64_t space)
630 {
631 	dmu_tx_hold_t *txh;
632 	ASSERT(tx->tx_txg == 0);
633 
634 	txh = dmu_tx_hold_object_impl(tx, tx->tx_objset,
635 	    DMU_NEW_OBJECT, THT_SPACE, space, 0);
636 
637 	txh->txh_space_towrite += space;
638 }
639 
640 int
641 dmu_tx_holds(dmu_tx_t *tx, uint64_t object)
642 {
643 	dmu_tx_hold_t *txh;
644 	int holds = 0;
645 
646 	/*
647 	 * By asserting that the tx is assigned, we're counting the
648 	 * number of dn_tx_holds, which is the same as the number of
649 	 * dn_holds.  Otherwise, we'd be counting dn_holds, but
650 	 * dn_tx_holds could be 0.
651 	 */
652 	ASSERT(tx->tx_txg != 0);
653 
654 	/* if (tx->tx_anyobj == TRUE) */
655 		/* return (0); */
656 
657 	for (txh = list_head(&tx->tx_holds); txh;
658 	    txh = list_next(&tx->tx_holds, txh)) {
659 		if (txh->txh_dnode && txh->txh_dnode->dn_object == object)
660 			holds++;
661 	}
662 
663 	return (holds);
664 }
665 
666 #ifdef ZFS_DEBUG
667 void
668 dmu_tx_dirty_buf(dmu_tx_t *tx, dmu_buf_impl_t *db)
669 {
670 	dmu_tx_hold_t *txh;
671 	int match_object = FALSE, match_offset = FALSE;
672 	dnode_t *dn = db->db_dnode;
673 
674 	ASSERT(tx->tx_txg != 0);
675 	ASSERT(tx->tx_objset == NULL || dn->dn_objset == tx->tx_objset->os);
676 	ASSERT3U(dn->dn_object, ==, db->db.db_object);
677 
678 	if (tx->tx_anyobj)
679 		return;
680 
681 	/* XXX No checking on the meta dnode for now */
682 	if (db->db.db_object == DMU_META_DNODE_OBJECT)
683 		return;
684 
685 	for (txh = list_head(&tx->tx_holds); txh;
686 	    txh = list_next(&tx->tx_holds, txh)) {
687 		ASSERT(dn == NULL || dn->dn_assigned_txg == tx->tx_txg);
688 		if (txh->txh_dnode == dn && txh->txh_type != THT_NEWOBJECT)
689 			match_object = TRUE;
690 		if (txh->txh_dnode == NULL || txh->txh_dnode == dn) {
691 			int datablkshift = dn->dn_datablkshift ?
692 			    dn->dn_datablkshift : SPA_MAXBLOCKSHIFT;
693 			int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
694 			int shift = datablkshift + epbs * db->db_level;
695 			uint64_t beginblk = shift >= 64 ? 0 :
696 			    (txh->txh_arg1 >> shift);
697 			uint64_t endblk = shift >= 64 ? 0 :
698 			    ((txh->txh_arg1 + txh->txh_arg2 - 1) >> shift);
699 			uint64_t blkid = db->db_blkid;
700 
701 			/* XXX txh_arg2 better not be zero... */
702 
703 			dprintf("found txh type %x beginblk=%llx endblk=%llx\n",
704 			    txh->txh_type, beginblk, endblk);
705 
706 			switch (txh->txh_type) {
707 			case THT_WRITE:
708 				if (blkid >= beginblk && blkid <= endblk)
709 					match_offset = TRUE;
710 				/*
711 				 * We will let this hold work for the bonus
712 				 * buffer so that we don't need to hold it
713 				 * when creating a new object.
714 				 */
715 				if (blkid == DB_BONUS_BLKID)
716 					match_offset = TRUE;
717 				/*
718 				 * They might have to increase nlevels,
719 				 * thus dirtying the new TLIBs.  Or the
720 				 * might have to change the block size,
721 				 * thus dirying the new lvl=0 blk=0.
722 				 */
723 				if (blkid == 0)
724 					match_offset = TRUE;
725 				break;
726 			case THT_FREE:
727 				/*
728 				 * We will dirty all the level 1 blocks in
729 				 * the free range and perhaps the first and
730 				 * last level 0 block.
731 				 */
732 				if (blkid >= beginblk && (blkid <= endblk ||
733 				    txh->txh_arg2 == DMU_OBJECT_END))
734 					match_offset = TRUE;
735 				break;
736 			case THT_BONUS:
737 				if (blkid == DB_BONUS_BLKID)
738 					match_offset = TRUE;
739 				break;
740 			case THT_ZAP:
741 				match_offset = TRUE;
742 				break;
743 			case THT_NEWOBJECT:
744 				match_object = TRUE;
745 				break;
746 			default:
747 				ASSERT(!"bad txh_type");
748 			}
749 		}
750 		if (match_object && match_offset)
751 			return;
752 	}
753 	panic("dirtying dbuf obj=%llx lvl=%u blkid=%llx but not tx_held\n",
754 	    (u_longlong_t)db->db.db_object, db->db_level,
755 	    (u_longlong_t)db->db_blkid);
756 }
757 #endif
758 
759 static int
760 dmu_tx_try_assign(dmu_tx_t *tx, uint64_t txg_how)
761 {
762 	dmu_tx_hold_t *txh;
763 	spa_t *spa = tx->tx_pool->dp_spa;
764 	uint64_t memory, asize, fsize, usize;
765 	uint64_t towrite, tofree, tooverwrite, tounref, tohold;
766 
767 	ASSERT3U(tx->tx_txg, ==, 0);
768 
769 	if (tx->tx_err)
770 		return (tx->tx_err);
771 
772 	if (spa_state(spa) == POOL_STATE_IO_FAILURE) {
773 		/*
774 		 * If the user has indicated a blocking failure mode
775 		 * then return ERESTART which will block in dmu_tx_wait().
776 		 * Otherwise, return EIO so that an error can get
777 		 * propagated back to the VOP calls.
778 		 *
779 		 * Note that we always honor the txg_how flag regardless
780 		 * of the failuremode setting.
781 		 */
782 		if (spa_get_failmode(spa) == ZIO_FAILURE_MODE_CONTINUE &&
783 		    txg_how != TXG_WAIT)
784 			return (EIO);
785 
786 		return (ERESTART);
787 	}
788 
789 	tx->tx_txg = txg_hold_open(tx->tx_pool, &tx->tx_txgh);
790 	tx->tx_needassign_txh = NULL;
791 
792 	/*
793 	 * NB: No error returns are allowed after txg_hold_open, but
794 	 * before processing the dnode holds, due to the
795 	 * dmu_tx_unassign() logic.
796 	 */
797 
798 	towrite = tofree = tooverwrite = tounref = tohold = 0;
799 	for (txh = list_head(&tx->tx_holds); txh;
800 	    txh = list_next(&tx->tx_holds, txh)) {
801 		dnode_t *dn = txh->txh_dnode;
802 		if (dn != NULL) {
803 			mutex_enter(&dn->dn_mtx);
804 			if (dn->dn_assigned_txg == tx->tx_txg - 1) {
805 				mutex_exit(&dn->dn_mtx);
806 				tx->tx_needassign_txh = txh;
807 				return (ERESTART);
808 			}
809 			if (dn->dn_assigned_txg == 0)
810 				dn->dn_assigned_txg = tx->tx_txg;
811 			ASSERT3U(dn->dn_assigned_txg, ==, tx->tx_txg);
812 			(void) refcount_add(&dn->dn_tx_holds, tx);
813 			mutex_exit(&dn->dn_mtx);
814 		}
815 		towrite += txh->txh_space_towrite;
816 		tofree += txh->txh_space_tofree;
817 		tooverwrite += txh->txh_space_tooverwrite;
818 		tounref += txh->txh_space_tounref;
819 		tohold += txh->txh_memory_tohold;
820 	}
821 
822 	/*
823 	 * NB: This check must be after we've held the dnodes, so that
824 	 * the dmu_tx_unassign() logic will work properly
825 	 */
826 	if (txg_how >= TXG_INITIAL && txg_how != tx->tx_txg)
827 		return (ERESTART);
828 
829 	/*
830 	 * If a snapshot has been taken since we made our estimates,
831 	 * assume that we won't be able to free or overwrite anything.
832 	 */
833 	if (tx->tx_objset &&
834 	    dsl_dataset_prev_snap_txg(tx->tx_objset->os->os_dsl_dataset) >
835 	    tx->tx_lastsnap_txg) {
836 		towrite += tooverwrite;
837 		tooverwrite = tofree = 0;
838 	}
839 
840 	/* needed allocation: worst-case estimate of write space */
841 	asize = spa_get_asize(tx->tx_pool->dp_spa, towrite + tooverwrite);
842 	/* freed space estimate: worst-case overwrite + free estimate */
843 	fsize = spa_get_asize(tx->tx_pool->dp_spa, tooverwrite) + tofree;
844 	/* convert unrefd space to worst-case estimate */
845 	usize = spa_get_asize(tx->tx_pool->dp_spa, tounref);
846 	/* calculate memory footprint estimate */
847 	memory = towrite + tooverwrite + tohold;
848 
849 #ifdef ZFS_DEBUG
850 	/* add in 'tohold' to account for our dirty holds on this memory */
851 	tx->tx_space_towrite = asize +
852 	    spa_get_asize(tx->tx_pool->dp_spa, tohold);
853 	tx->tx_space_tofree = tofree;
854 	tx->tx_space_tooverwrite = tooverwrite;
855 	tx->tx_space_tounref = tounref;
856 #endif
857 
858 	if (tx->tx_dir && asize != 0) {
859 		int err = dsl_dir_tempreserve_space(tx->tx_dir, memory,
860 		    asize, fsize, usize, &tx->tx_tempreserve_cookie, tx);
861 		if (err)
862 			return (err);
863 	}
864 
865 	return (0);
866 }
867 
868 static void
869 dmu_tx_unassign(dmu_tx_t *tx)
870 {
871 	dmu_tx_hold_t *txh;
872 
873 	if (tx->tx_txg == 0)
874 		return;
875 
876 	txg_rele_to_quiesce(&tx->tx_txgh);
877 
878 	for (txh = list_head(&tx->tx_holds); txh != tx->tx_needassign_txh;
879 	    txh = list_next(&tx->tx_holds, txh)) {
880 		dnode_t *dn = txh->txh_dnode;
881 
882 		if (dn == NULL)
883 			continue;
884 		mutex_enter(&dn->dn_mtx);
885 		ASSERT3U(dn->dn_assigned_txg, ==, tx->tx_txg);
886 
887 		if (refcount_remove(&dn->dn_tx_holds, tx) == 0) {
888 			dn->dn_assigned_txg = 0;
889 			cv_broadcast(&dn->dn_notxholds);
890 		}
891 		mutex_exit(&dn->dn_mtx);
892 	}
893 
894 	txg_rele_to_sync(&tx->tx_txgh);
895 
896 	tx->tx_lasttried_txg = tx->tx_txg;
897 	tx->tx_txg = 0;
898 }
899 
900 /*
901  * Assign tx to a transaction group.  txg_how can be one of:
902  *
903  * (1)	TXG_WAIT.  If the current open txg is full, waits until there's
904  *	a new one.  This should be used when you're not holding locks.
905  *	If will only fail if we're truly out of space (or over quota).
906  *
907  * (2)	TXG_NOWAIT.  If we can't assign into the current open txg without
908  *	blocking, returns immediately with ERESTART.  This should be used
909  *	whenever you're holding locks.  On an ERESTART error, the caller
910  *	should drop locks, do a dmu_tx_wait(tx), and try again.
911  *
912  * (3)	A specific txg.  Use this if you need to ensure that multiple
913  *	transactions all sync in the same txg.  Like TXG_NOWAIT, it
914  *	returns ERESTART if it can't assign you into the requested txg.
915  */
916 int
917 dmu_tx_assign(dmu_tx_t *tx, uint64_t txg_how)
918 {
919 	int err;
920 
921 	ASSERT(tx->tx_txg == 0);
922 	ASSERT(txg_how != 0);
923 	ASSERT(!dsl_pool_sync_context(tx->tx_pool));
924 
925 	while ((err = dmu_tx_try_assign(tx, txg_how)) != 0) {
926 		dmu_tx_unassign(tx);
927 
928 		if (err != ERESTART || txg_how != TXG_WAIT)
929 			return (err);
930 
931 		dmu_tx_wait(tx);
932 	}
933 
934 	txg_rele_to_quiesce(&tx->tx_txgh);
935 
936 	return (0);
937 }
938 
939 void
940 dmu_tx_wait(dmu_tx_t *tx)
941 {
942 	spa_t *spa = tx->tx_pool->dp_spa;
943 
944 	ASSERT(tx->tx_txg == 0);
945 
946 	/*
947 	 * It's possible that the pool has become active after this thread
948 	 * has tried to obtain a tx. If that's the case then his
949 	 * tx_lasttried_txg would not have been assigned.
950 	 */
951 	if (spa_state(spa) == POOL_STATE_IO_FAILURE ||
952 	    tx->tx_lasttried_txg == 0) {
953 		txg_wait_synced(tx->tx_pool, spa_last_synced_txg(spa) + 1);
954 	} else if (tx->tx_needassign_txh) {
955 		dnode_t *dn = tx->tx_needassign_txh->txh_dnode;
956 
957 		mutex_enter(&dn->dn_mtx);
958 		while (dn->dn_assigned_txg == tx->tx_lasttried_txg - 1)
959 			cv_wait(&dn->dn_notxholds, &dn->dn_mtx);
960 		mutex_exit(&dn->dn_mtx);
961 		tx->tx_needassign_txh = NULL;
962 	} else {
963 		txg_wait_open(tx->tx_pool, tx->tx_lasttried_txg + 1);
964 	}
965 }
966 
967 void
968 dmu_tx_willuse_space(dmu_tx_t *tx, int64_t delta)
969 {
970 #ifdef ZFS_DEBUG
971 	if (tx->tx_dir == NULL || delta == 0)
972 		return;
973 
974 	if (delta > 0) {
975 		ASSERT3U(refcount_count(&tx->tx_space_written) + delta, <=,
976 		    tx->tx_space_towrite);
977 		(void) refcount_add_many(&tx->tx_space_written, delta, NULL);
978 	} else {
979 		(void) refcount_add_many(&tx->tx_space_freed, -delta, NULL);
980 	}
981 #endif
982 }
983 
984 void
985 dmu_tx_commit(dmu_tx_t *tx)
986 {
987 	dmu_tx_hold_t *txh;
988 
989 	ASSERT(tx->tx_txg != 0);
990 
991 	while (txh = list_head(&tx->tx_holds)) {
992 		dnode_t *dn = txh->txh_dnode;
993 
994 		list_remove(&tx->tx_holds, txh);
995 		kmem_free(txh, sizeof (dmu_tx_hold_t));
996 		if (dn == NULL)
997 			continue;
998 		mutex_enter(&dn->dn_mtx);
999 		ASSERT3U(dn->dn_assigned_txg, ==, tx->tx_txg);
1000 
1001 		if (refcount_remove(&dn->dn_tx_holds, tx) == 0) {
1002 			dn->dn_assigned_txg = 0;
1003 			cv_broadcast(&dn->dn_notxholds);
1004 		}
1005 		mutex_exit(&dn->dn_mtx);
1006 		dnode_rele(dn, tx);
1007 	}
1008 
1009 	if (tx->tx_tempreserve_cookie)
1010 		dsl_dir_tempreserve_clear(tx->tx_tempreserve_cookie, tx);
1011 
1012 	if (tx->tx_anyobj == FALSE)
1013 		txg_rele_to_sync(&tx->tx_txgh);
1014 	list_destroy(&tx->tx_holds);
1015 #ifdef ZFS_DEBUG
1016 	dprintf("towrite=%llu written=%llu tofree=%llu freed=%llu\n",
1017 	    tx->tx_space_towrite, refcount_count(&tx->tx_space_written),
1018 	    tx->tx_space_tofree, refcount_count(&tx->tx_space_freed));
1019 	refcount_destroy_many(&tx->tx_space_written,
1020 	    refcount_count(&tx->tx_space_written));
1021 	refcount_destroy_many(&tx->tx_space_freed,
1022 	    refcount_count(&tx->tx_space_freed));
1023 #endif
1024 	kmem_free(tx, sizeof (dmu_tx_t));
1025 }
1026 
1027 void
1028 dmu_tx_abort(dmu_tx_t *tx)
1029 {
1030 	dmu_tx_hold_t *txh;
1031 
1032 	ASSERT(tx->tx_txg == 0);
1033 
1034 	while (txh = list_head(&tx->tx_holds)) {
1035 		dnode_t *dn = txh->txh_dnode;
1036 
1037 		list_remove(&tx->tx_holds, txh);
1038 		kmem_free(txh, sizeof (dmu_tx_hold_t));
1039 		if (dn != NULL)
1040 			dnode_rele(dn, tx);
1041 	}
1042 	list_destroy(&tx->tx_holds);
1043 #ifdef ZFS_DEBUG
1044 	refcount_destroy_many(&tx->tx_space_written,
1045 	    refcount_count(&tx->tx_space_written));
1046 	refcount_destroy_many(&tx->tx_space_freed,
1047 	    refcount_count(&tx->tx_space_freed));
1048 #endif
1049 	kmem_free(tx, sizeof (dmu_tx_t));
1050 }
1051 
1052 uint64_t
1053 dmu_tx_get_txg(dmu_tx_t *tx)
1054 {
1055 	ASSERT(tx->tx_txg != 0);
1056 	return (tx->tx_txg);
1057 }
1058