xref: /titanic_41/usr/src/uts/common/fs/zfs/dmu_tx.c (revision 99ebb4ca412cb0a19d77a3899a87c055b9c30fa8)
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 2006 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);
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 	}
298 }
299 
300 void
301 dmu_tx_hold_write(dmu_tx_t *tx, uint64_t object, uint64_t off, int len)
302 {
303 	dmu_tx_hold_t *txh;
304 
305 	ASSERT(tx->tx_txg == 0);
306 	ASSERT(len < DMU_MAX_ACCESS);
307 	ASSERT(len == 0 || UINT64_MAX - off >= len - 1);
308 
309 	txh = dmu_tx_hold_object_impl(tx, tx->tx_objset,
310 	    object, THT_WRITE, off, len);
311 	if (txh == NULL)
312 		return;
313 
314 	dmu_tx_count_write(txh, off, len);
315 	dmu_tx_count_dnode(txh);
316 }
317 
318 static void
319 dmu_tx_count_free(dmu_tx_hold_t *txh, uint64_t off, uint64_t len)
320 {
321 	uint64_t blkid, nblks;
322 	uint64_t space = 0;
323 	dnode_t *dn = txh->txh_dnode;
324 	dsl_dataset_t *ds = dn->dn_objset->os_dsl_dataset;
325 	spa_t *spa = txh->txh_tx->tx_pool->dp_spa;
326 	int dirty;
327 
328 	/*
329 	 * We don't need to use any locking to check for dirtyness
330 	 * because it's OK if we get stale data -- the dnode may become
331 	 * dirty immediately after our check anyway.  This is just a
332 	 * means to avoid the expensive count when we aren't sure we
333 	 * need it.  We need to be able to deal with a dirty dnode.
334 	 */
335 	dirty = list_link_active(&dn->dn_dirty_link[0]) |
336 	    list_link_active(&dn->dn_dirty_link[1]) |
337 	    list_link_active(&dn->dn_dirty_link[2]) |
338 	    list_link_active(&dn->dn_dirty_link[3]);
339 	if (dirty || dn->dn_assigned_txg || dn->dn_phys->dn_nlevels == 0)
340 		return;
341 
342 	/*
343 	 * the struct_rwlock protects us against dn_phys->dn_nlevels
344 	 * changing, in case (against all odds) we manage to dirty &
345 	 * sync out the changes after we check for being dirty.
346 	 * also, dbuf_hold_impl() wants us to have the struct_rwlock.
347 	 *
348 	 * It's fine to use dn_datablkshift rather than the dn_phys
349 	 * equivalent because if it is changing, maxblkid==0 and we will
350 	 * bail.
351 	 */
352 	rw_enter(&dn->dn_struct_rwlock, RW_READER);
353 	if (dn->dn_phys->dn_maxblkid == 0) {
354 		if (off == 0 && len >= dn->dn_datablksz) {
355 			blkid = 0;
356 			nblks = 1;
357 		} else {
358 			rw_exit(&dn->dn_struct_rwlock);
359 			return;
360 		}
361 	} else {
362 		blkid = off >> dn->dn_datablkshift;
363 		nblks = (off + len) >> dn->dn_datablkshift;
364 
365 		if (blkid >= dn->dn_phys->dn_maxblkid) {
366 			rw_exit(&dn->dn_struct_rwlock);
367 			return;
368 		}
369 		if (blkid + nblks > dn->dn_phys->dn_maxblkid)
370 			nblks = dn->dn_phys->dn_maxblkid - blkid;
371 
372 		/* don't bother after 128,000 blocks */
373 		nblks = MIN(nblks, 128*1024);
374 	}
375 
376 	if (dn->dn_phys->dn_nlevels == 1) {
377 		int i;
378 		for (i = 0; i < nblks; i++) {
379 			blkptr_t *bp = dn->dn_phys->dn_blkptr;
380 			ASSERT3U(blkid + i, <, dn->dn_phys->dn_nblkptr);
381 			bp += blkid + i;
382 			if (dsl_dataset_block_freeable(ds, bp->blk_birth)) {
383 				dprintf_bp(bp, "can free old%s", "");
384 				space += bp_get_dasize(spa, bp);
385 			}
386 		}
387 		nblks = 0;
388 	}
389 
390 	while (nblks) {
391 		dmu_buf_impl_t *dbuf;
392 		int err, epbs, blkoff, tochk;
393 
394 		epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
395 		blkoff = P2PHASE(blkid, 1<<epbs);
396 		tochk = MIN((1<<epbs) - blkoff, nblks);
397 
398 		err = dbuf_hold_impl(dn, 1, blkid >> epbs, TRUE, FTAG, &dbuf);
399 		if (err == 0) {
400 			int i;
401 			blkptr_t *bp;
402 
403 			err = dbuf_read(dbuf, NULL,
404 			    DB_RF_HAVESTRUCT | DB_RF_CANFAIL);
405 			if (err != 0) {
406 				txh->txh_tx->tx_err = err;
407 				dbuf_rele(dbuf, FTAG);
408 				break;
409 			}
410 
411 			bp = dbuf->db.db_data;
412 			bp += blkoff;
413 
414 			for (i = 0; i < tochk; i++) {
415 				if (dsl_dataset_block_freeable(ds,
416 				    bp[i].blk_birth)) {
417 					dprintf_bp(&bp[i],
418 					    "can free old%s", "");
419 					space += bp_get_dasize(spa, &bp[i]);
420 				}
421 			}
422 			dbuf_rele(dbuf, FTAG);
423 		}
424 		if (err && err != ENOENT) {
425 			txh->txh_tx->tx_err = err;
426 			break;
427 		}
428 
429 		blkid += tochk;
430 		nblks -= tochk;
431 	}
432 	rw_exit(&dn->dn_struct_rwlock);
433 
434 	txh->txh_space_tofree += space;
435 }
436 
437 void
438 dmu_tx_hold_free(dmu_tx_t *tx, uint64_t object, uint64_t off, uint64_t len)
439 {
440 	dmu_tx_hold_t *txh;
441 	dnode_t *dn;
442 	uint64_t start, end, i;
443 	int err, shift;
444 	zio_t *zio;
445 
446 	ASSERT(tx->tx_txg == 0);
447 
448 	txh = dmu_tx_hold_object_impl(tx, tx->tx_objset,
449 	    object, THT_FREE, off, len);
450 	if (txh == NULL)
451 		return;
452 	dn = txh->txh_dnode;
453 
454 	/* first block */
455 	if (off != 0)
456 		dmu_tx_count_write(txh, off, 1);
457 	/* last block */
458 	if (len != DMU_OBJECT_END)
459 		dmu_tx_count_write(txh, off+len, 1);
460 
461 	if (off >= (dn->dn_maxblkid+1) * dn->dn_datablksz)
462 		return;
463 	if (len == DMU_OBJECT_END)
464 		len = (dn->dn_maxblkid+1) * dn->dn_datablksz - off;
465 
466 	/*
467 	 * For i/o error checking, read the first and last level-0
468 	 * blocks, and all the level-1 blocks.  The above count_write's
469 	 * will take care of the level-0 blocks.
470 	 */
471 	if (dn->dn_nlevels > 1) {
472 		shift = dn->dn_datablkshift + dn->dn_indblkshift -
473 		    SPA_BLKPTRSHIFT;
474 		start = off >> shift;
475 		end = dn->dn_datablkshift ? ((off+len) >> shift) : 0;
476 
477 		zio = zio_root(tx->tx_pool->dp_spa,
478 		    NULL, NULL, ZIO_FLAG_CANFAIL);
479 		for (i = start; i <= end; i++) {
480 			uint64_t ibyte = i << shift;
481 			err = dnode_next_offset(dn, FALSE, &ibyte, 2, 1, 0);
482 			i = ibyte >> shift;
483 			if (err == ESRCH)
484 				break;
485 			if (err) {
486 				tx->tx_err = err;
487 				return;
488 			}
489 
490 			err = dmu_tx_check_ioerr(zio, dn, 1, i);
491 			if (err) {
492 				tx->tx_err = err;
493 				return;
494 			}
495 		}
496 		err = zio_wait(zio);
497 		if (err) {
498 			tx->tx_err = err;
499 			return;
500 		}
501 	}
502 
503 	dmu_tx_count_dnode(txh);
504 	dmu_tx_count_free(txh, off, len);
505 }
506 
507 void
508 dmu_tx_hold_zap(dmu_tx_t *tx, uint64_t object, int add, char *name)
509 {
510 	dmu_tx_hold_t *txh;
511 	dnode_t *dn;
512 	uint64_t nblocks;
513 	int epbs, err;
514 
515 	ASSERT(tx->tx_txg == 0);
516 
517 	txh = dmu_tx_hold_object_impl(tx, tx->tx_objset,
518 	    object, THT_ZAP, add, (uintptr_t)name);
519 	if (txh == NULL)
520 		return;
521 	dn = txh->txh_dnode;
522 
523 	dmu_tx_count_dnode(txh);
524 
525 	if (dn == NULL) {
526 		/*
527 		 * We will be able to fit a new object's entries into one leaf
528 		 * block.  So there will be at most 2 blocks total,
529 		 * including the header block.
530 		 */
531 		dmu_tx_count_write(txh, 0, 2 << fzap_default_block_shift);
532 		return;
533 	}
534 
535 	ASSERT3P(dmu_ot[dn->dn_type].ot_byteswap, ==, zap_byteswap);
536 
537 	if (dn->dn_maxblkid == 0 && !add) {
538 		/*
539 		 * If there is only one block  (i.e. this is a micro-zap)
540 		 * and we are not adding anything, the accounting is simple.
541 		 */
542 		err = dmu_tx_check_ioerr(NULL, dn, 0, 0);
543 		if (err) {
544 			tx->tx_err = err;
545 			return;
546 		}
547 
548 		if (dsl_dataset_block_freeable(dn->dn_objset->os_dsl_dataset,
549 		    dn->dn_phys->dn_blkptr[0].blk_birth))
550 			txh->txh_space_tooverwrite += dn->dn_datablksz;
551 		else
552 			txh->txh_space_towrite += dn->dn_datablksz;
553 		return;
554 	}
555 
556 	if (dn->dn_maxblkid > 0 && name) {
557 		/*
558 		 * access the name in this fat-zap so that we'll check
559 		 * for i/o errors to the leaf blocks, etc.
560 		 */
561 		err = zap_lookup(&dn->dn_objset->os, dn->dn_object, name,
562 		    8, 0, NULL);
563 		if (err == EIO) {
564 			tx->tx_err = err;
565 			return;
566 		}
567 	}
568 
569 	/*
570 	 * 3 blocks overwritten: target leaf, ptrtbl block, header block
571 	 * 3 new blocks written if adding: new split leaf, 2 grown ptrtbl blocks
572 	 */
573 	dmu_tx_count_write(txh, dn->dn_maxblkid * dn->dn_datablksz,
574 	    (3 + add ? 3 : 0) << dn->dn_datablkshift);
575 
576 	/*
577 	 * If the modified blocks are scattered to the four winds,
578 	 * we'll have to modify an indirect twig for each.
579 	 */
580 	epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
581 	for (nblocks = dn->dn_maxblkid >> epbs; nblocks != 0; nblocks >>= epbs)
582 		txh->txh_space_towrite += 3 << dn->dn_indblkshift;
583 }
584 
585 void
586 dmu_tx_hold_bonus(dmu_tx_t *tx, uint64_t object)
587 {
588 	dmu_tx_hold_t *txh;
589 
590 	ASSERT(tx->tx_txg == 0);
591 
592 	txh = dmu_tx_hold_object_impl(tx, tx->tx_objset,
593 	    object, THT_BONUS, 0, 0);
594 	if (txh)
595 		dmu_tx_count_dnode(txh);
596 }
597 
598 void
599 dmu_tx_hold_space(dmu_tx_t *tx, uint64_t space)
600 {
601 	dmu_tx_hold_t *txh;
602 	ASSERT(tx->tx_txg == 0);
603 
604 	txh = dmu_tx_hold_object_impl(tx, tx->tx_objset,
605 	    DMU_NEW_OBJECT, THT_SPACE, space, 0);
606 
607 	txh->txh_space_towrite += space;
608 }
609 
610 int
611 dmu_tx_holds(dmu_tx_t *tx, uint64_t object)
612 {
613 	dmu_tx_hold_t *txh;
614 	int holds = 0;
615 
616 	/*
617 	 * By asserting that the tx is assigned, we're counting the
618 	 * number of dn_tx_holds, which is the same as the number of
619 	 * dn_holds.  Otherwise, we'd be counting dn_holds, but
620 	 * dn_tx_holds could be 0.
621 	 */
622 	ASSERT(tx->tx_txg != 0);
623 
624 	/* if (tx->tx_anyobj == TRUE) */
625 		/* return (0); */
626 
627 	for (txh = list_head(&tx->tx_holds); txh;
628 	    txh = list_next(&tx->tx_holds, txh)) {
629 		if (txh->txh_dnode && txh->txh_dnode->dn_object == object)
630 			holds++;
631 	}
632 
633 	return (holds);
634 }
635 
636 #ifdef ZFS_DEBUG
637 void
638 dmu_tx_dirty_buf(dmu_tx_t *tx, dmu_buf_impl_t *db)
639 {
640 	dmu_tx_hold_t *txh;
641 	int match_object = FALSE, match_offset = FALSE;
642 	dnode_t *dn = db->db_dnode;
643 
644 	ASSERT(tx->tx_txg != 0);
645 	ASSERT(tx->tx_objset == NULL || dn->dn_objset == tx->tx_objset->os);
646 	ASSERT3U(dn->dn_object, ==, db->db.db_object);
647 
648 	if (tx->tx_anyobj)
649 		return;
650 
651 	/* XXX No checking on the meta dnode for now */
652 	if (db->db.db_object == DMU_META_DNODE_OBJECT)
653 		return;
654 
655 	for (txh = list_head(&tx->tx_holds); txh;
656 	    txh = list_next(&tx->tx_holds, txh)) {
657 		ASSERT(dn == NULL || dn->dn_assigned_txg == tx->tx_txg);
658 		if (txh->txh_dnode == dn && txh->txh_type != THT_NEWOBJECT)
659 			match_object = TRUE;
660 		if (txh->txh_dnode == NULL || txh->txh_dnode == dn) {
661 			int datablkshift = dn->dn_datablkshift ?
662 			    dn->dn_datablkshift : SPA_MAXBLOCKSHIFT;
663 			int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
664 			int shift = datablkshift + epbs * db->db_level;
665 			uint64_t beginblk = shift >= 64 ? 0 :
666 			    (txh->txh_arg1 >> shift);
667 			uint64_t endblk = shift >= 64 ? 0 :
668 			    ((txh->txh_arg1 + txh->txh_arg2 - 1) >> shift);
669 			uint64_t blkid = db->db_blkid;
670 
671 			/* XXX txh_arg2 better not be zero... */
672 
673 			dprintf("found txh type %x beginblk=%llx endblk=%llx\n",
674 			    txh->txh_type, beginblk, endblk);
675 
676 			switch (txh->txh_type) {
677 			case THT_WRITE:
678 				if (blkid >= beginblk && blkid <= endblk)
679 					match_offset = TRUE;
680 				/*
681 				 * We will let this hold work for the bonus
682 				 * buffer so that we don't need to hold it
683 				 * when creating a new object.
684 				 */
685 				if (blkid == DB_BONUS_BLKID)
686 					match_offset = TRUE;
687 				/*
688 				 * They might have to increase nlevels,
689 				 * thus dirtying the new TLIBs.  Or the
690 				 * might have to change the block size,
691 				 * thus dirying the new lvl=0 blk=0.
692 				 */
693 				if (blkid == 0)
694 					match_offset = TRUE;
695 				break;
696 			case THT_FREE:
697 				if (blkid == beginblk &&
698 				    (txh->txh_arg1 != 0 ||
699 				    dn->dn_maxblkid == 0))
700 					match_offset = TRUE;
701 				if (blkid == endblk &&
702 				    txh->txh_arg2 != DMU_OBJECT_END)
703 					match_offset = TRUE;
704 				break;
705 			case THT_BONUS:
706 				if (blkid == DB_BONUS_BLKID)
707 					match_offset = TRUE;
708 				break;
709 			case THT_ZAP:
710 				match_offset = TRUE;
711 				break;
712 			case THT_NEWOBJECT:
713 				match_object = TRUE;
714 				break;
715 			default:
716 				ASSERT(!"bad txh_type");
717 			}
718 		}
719 		if (match_object && match_offset)
720 			return;
721 	}
722 	panic("dirtying dbuf obj=%llx lvl=%u blkid=%llx but not tx_held\n",
723 	    (u_longlong_t)db->db.db_object, db->db_level,
724 	    (u_longlong_t)db->db_blkid);
725 }
726 #endif
727 
728 static int
729 dmu_tx_try_assign(dmu_tx_t *tx, uint64_t txg_how)
730 {
731 	dmu_tx_hold_t *txh;
732 	uint64_t lsize, asize, fsize, towrite, tofree, tooverwrite;
733 
734 	ASSERT3U(tx->tx_txg, ==, 0);
735 	if (tx->tx_err)
736 		return (tx->tx_err);
737 
738 	tx->tx_txg = txg_hold_open(tx->tx_pool, &tx->tx_txgh);
739 	tx->tx_needassign_txh = NULL;
740 
741 	/*
742 	 * NB: No error returns are allowed after txg_hold_open, but
743 	 * before processing the dnode holds, due to the
744 	 * dmu_tx_unassign() logic.
745 	 */
746 
747 	towrite = tofree = tooverwrite = 0;
748 	for (txh = list_head(&tx->tx_holds); txh;
749 	    txh = list_next(&tx->tx_holds, txh)) {
750 		dnode_t *dn = txh->txh_dnode;
751 		if (dn != NULL) {
752 			mutex_enter(&dn->dn_mtx);
753 			if (dn->dn_assigned_txg == tx->tx_txg - 1) {
754 				mutex_exit(&dn->dn_mtx);
755 				tx->tx_needassign_txh = txh;
756 				return (ERESTART);
757 			}
758 			if (dn->dn_assigned_txg == 0)
759 				dn->dn_assigned_txg = tx->tx_txg;
760 			ASSERT3U(dn->dn_assigned_txg, ==, tx->tx_txg);
761 			(void) refcount_add(&dn->dn_tx_holds, tx);
762 			mutex_exit(&dn->dn_mtx);
763 		}
764 		towrite += txh->txh_space_towrite;
765 		tofree += txh->txh_space_tofree;
766 		tooverwrite += txh->txh_space_tooverwrite;
767 	}
768 
769 	/*
770 	 * NB: This check must be after we've held the dnodes, so that
771 	 * the dmu_tx_unassign() logic will work properly
772 	 */
773 	if (txg_how >= TXG_INITIAL && txg_how != tx->tx_txg)
774 		return (ERESTART);
775 
776 	/*
777 	 * If a snapshot has been taken since we made our estimates,
778 	 * assume that we won't be able to free or overwrite anything.
779 	 */
780 	if (tx->tx_objset &&
781 	    dsl_dataset_prev_snap_txg(tx->tx_objset->os->os_dsl_dataset) >
782 	    tx->tx_lastsnap_txg) {
783 		towrite += tooverwrite;
784 		tooverwrite = tofree = 0;
785 	}
786 
787 	/*
788 	 * Convert logical size to worst-case allocated size.
789 	 */
790 	fsize = spa_get_asize(tx->tx_pool->dp_spa, tooverwrite) + tofree;
791 	lsize = towrite + tooverwrite;
792 	asize = spa_get_asize(tx->tx_pool->dp_spa, lsize);
793 
794 #ifdef ZFS_DEBUG
795 	tx->tx_space_towrite = asize;
796 	tx->tx_space_tofree = tofree;
797 	tx->tx_space_tooverwrite = tooverwrite;
798 #endif
799 
800 	if (tx->tx_dir && asize != 0) {
801 		int err = dsl_dir_tempreserve_space(tx->tx_dir,
802 		    lsize, asize, fsize, &tx->tx_tempreserve_cookie, tx);
803 		if (err)
804 			return (err);
805 	}
806 
807 	return (0);
808 }
809 
810 static void
811 dmu_tx_unassign(dmu_tx_t *tx)
812 {
813 	dmu_tx_hold_t *txh;
814 
815 	if (tx->tx_txg == 0)
816 		return;
817 
818 	txg_rele_to_quiesce(&tx->tx_txgh);
819 
820 	for (txh = list_head(&tx->tx_holds); txh != tx->tx_needassign_txh;
821 	    txh = list_next(&tx->tx_holds, txh)) {
822 		dnode_t *dn = txh->txh_dnode;
823 
824 		if (dn == NULL)
825 			continue;
826 		mutex_enter(&dn->dn_mtx);
827 		ASSERT3U(dn->dn_assigned_txg, ==, tx->tx_txg);
828 
829 		if (refcount_remove(&dn->dn_tx_holds, tx) == 0) {
830 			dn->dn_assigned_txg = 0;
831 			cv_broadcast(&dn->dn_notxholds);
832 		}
833 		mutex_exit(&dn->dn_mtx);
834 	}
835 
836 	txg_rele_to_sync(&tx->tx_txgh);
837 
838 	tx->tx_lasttried_txg = tx->tx_txg;
839 	tx->tx_txg = 0;
840 }
841 
842 /*
843  * Assign tx to a transaction group.  txg_how can be one of:
844  *
845  * (1)	TXG_WAIT.  If the current open txg is full, waits until there's
846  *	a new one.  This should be used when you're not holding locks.
847  *	If will only fail if we're truly out of space (or over quota).
848  *
849  * (2)	TXG_NOWAIT.  If we can't assign into the current open txg without
850  *	blocking, returns immediately with ERESTART.  This should be used
851  *	whenever you're holding locks.  On an ERESTART error, the caller
852  *	should drop locks, do a dmu_tx_wait(tx), and try again.
853  *
854  * (3)	A specific txg.  Use this if you need to ensure that multiple
855  *	transactions all sync in the same txg.  Like TXG_NOWAIT, it
856  *	returns ERESTART if it can't assign you into the requested txg.
857  */
858 int
859 dmu_tx_assign(dmu_tx_t *tx, uint64_t txg_how)
860 {
861 	int err;
862 
863 	ASSERT(tx->tx_txg == 0);
864 	ASSERT(txg_how != 0);
865 	ASSERT(!dsl_pool_sync_context(tx->tx_pool));
866 
867 	while ((err = dmu_tx_try_assign(tx, txg_how)) != 0) {
868 		dmu_tx_unassign(tx);
869 
870 		if (err != ERESTART || txg_how != TXG_WAIT)
871 			return (err);
872 
873 		dmu_tx_wait(tx);
874 	}
875 
876 	txg_rele_to_quiesce(&tx->tx_txgh);
877 
878 	return (0);
879 }
880 
881 void
882 dmu_tx_wait(dmu_tx_t *tx)
883 {
884 	ASSERT(tx->tx_txg == 0);
885 	ASSERT(tx->tx_lasttried_txg != 0);
886 
887 	if (tx->tx_needassign_txh) {
888 		dnode_t *dn = tx->tx_needassign_txh->txh_dnode;
889 
890 		mutex_enter(&dn->dn_mtx);
891 		while (dn->dn_assigned_txg == tx->tx_lasttried_txg - 1)
892 			cv_wait(&dn->dn_notxholds, &dn->dn_mtx);
893 		mutex_exit(&dn->dn_mtx);
894 		tx->tx_needassign_txh = NULL;
895 	} else {
896 		txg_wait_open(tx->tx_pool, tx->tx_lasttried_txg + 1);
897 	}
898 }
899 
900 void
901 dmu_tx_willuse_space(dmu_tx_t *tx, int64_t delta)
902 {
903 #ifdef ZFS_DEBUG
904 	if (tx->tx_dir == NULL || delta == 0)
905 		return;
906 
907 	if (delta > 0) {
908 		ASSERT3U(refcount_count(&tx->tx_space_written) + delta, <=,
909 		    tx->tx_space_towrite);
910 		(void) refcount_add_many(&tx->tx_space_written, delta, NULL);
911 	} else {
912 		(void) refcount_add_many(&tx->tx_space_freed, -delta, NULL);
913 	}
914 #endif
915 }
916 
917 void
918 dmu_tx_commit(dmu_tx_t *tx)
919 {
920 	dmu_tx_hold_t *txh;
921 
922 	ASSERT(tx->tx_txg != 0);
923 
924 	while (txh = list_head(&tx->tx_holds)) {
925 		dnode_t *dn = txh->txh_dnode;
926 
927 		list_remove(&tx->tx_holds, txh);
928 		kmem_free(txh, sizeof (dmu_tx_hold_t));
929 		if (dn == NULL)
930 			continue;
931 		mutex_enter(&dn->dn_mtx);
932 		ASSERT3U(dn->dn_assigned_txg, ==, tx->tx_txg);
933 
934 		if (refcount_remove(&dn->dn_tx_holds, tx) == 0) {
935 			dn->dn_assigned_txg = 0;
936 			cv_broadcast(&dn->dn_notxholds);
937 		}
938 		mutex_exit(&dn->dn_mtx);
939 		dnode_rele(dn, tx);
940 	}
941 
942 	if (tx->tx_tempreserve_cookie)
943 		dsl_dir_tempreserve_clear(tx->tx_tempreserve_cookie, tx);
944 
945 	if (tx->tx_anyobj == FALSE)
946 		txg_rele_to_sync(&tx->tx_txgh);
947 #ifdef ZFS_DEBUG
948 	dprintf("towrite=%llu written=%llu tofree=%llu freed=%llu\n",
949 	    tx->tx_space_towrite, refcount_count(&tx->tx_space_written),
950 	    tx->tx_space_tofree, refcount_count(&tx->tx_space_freed));
951 	refcount_destroy_many(&tx->tx_space_written,
952 	    refcount_count(&tx->tx_space_written));
953 	refcount_destroy_many(&tx->tx_space_freed,
954 	    refcount_count(&tx->tx_space_freed));
955 #endif
956 	kmem_free(tx, sizeof (dmu_tx_t));
957 }
958 
959 void
960 dmu_tx_abort(dmu_tx_t *tx)
961 {
962 	dmu_tx_hold_t *txh;
963 
964 	ASSERT(tx->tx_txg == 0);
965 
966 	while (txh = list_head(&tx->tx_holds)) {
967 		dnode_t *dn = txh->txh_dnode;
968 
969 		list_remove(&tx->tx_holds, txh);
970 		kmem_free(txh, sizeof (dmu_tx_hold_t));
971 		if (dn != NULL)
972 			dnode_rele(dn, tx);
973 	}
974 #ifdef ZFS_DEBUG
975 	refcount_destroy_many(&tx->tx_space_written,
976 	    refcount_count(&tx->tx_space_written));
977 	refcount_destroy_many(&tx->tx_space_freed,
978 	    refcount_count(&tx->tx_space_freed));
979 #endif
980 	kmem_free(tx, sizeof (dmu_tx_t));
981 }
982 
983 uint64_t
984 dmu_tx_get_txg(dmu_tx_t *tx)
985 {
986 	ASSERT(tx->tx_txg != 0);
987 	return (tx->tx_txg);
988 }
989