1/*
2 * CDDL HEADER START
3 *
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
7 *
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
12 *
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
18 *
19 * CDDL HEADER END
20 */
21/*
22 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23 * Copyright 2011 Nexenta Systems, Inc.  All rights reserved.
24 * Copyright (c) 2012, 2017 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>
33#include <sys/dsl_dir.h>
34#include <sys/dsl_pool.h>
35#include <sys/zap_impl.h>
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/trace_zfs.h>
41
42typedef void (*dmu_tx_hold_func_t)(dmu_tx_t *tx, struct dnode *dn,
43    uint64_t arg1, uint64_t arg2);
44
45dmu_tx_stats_t dmu_tx_stats = {
46	{ "dmu_tx_assigned",		KSTAT_DATA_UINT64 },
47	{ "dmu_tx_delay",		KSTAT_DATA_UINT64 },
48	{ "dmu_tx_error",		KSTAT_DATA_UINT64 },
49	{ "dmu_tx_suspended",		KSTAT_DATA_UINT64 },
50	{ "dmu_tx_group",		KSTAT_DATA_UINT64 },
51	{ "dmu_tx_memory_reserve",	KSTAT_DATA_UINT64 },
52	{ "dmu_tx_memory_reclaim",	KSTAT_DATA_UINT64 },
53	{ "dmu_tx_dirty_throttle",	KSTAT_DATA_UINT64 },
54	{ "dmu_tx_dirty_delay",		KSTAT_DATA_UINT64 },
55	{ "dmu_tx_dirty_over_max",	KSTAT_DATA_UINT64 },
56	{ "dmu_tx_dirty_frees_delay",	KSTAT_DATA_UINT64 },
57	{ "dmu_tx_quota",		KSTAT_DATA_UINT64 },
58};
59
60static kstat_t *dmu_tx_ksp;
61
62dmu_tx_t *
63dmu_tx_create_dd(dsl_dir_t *dd)
64{
65	dmu_tx_t *tx = kmem_zalloc(sizeof (dmu_tx_t), KM_SLEEP);
66	tx->tx_dir = dd;
67	if (dd != NULL)
68		tx->tx_pool = dd->dd_pool;
69	list_create(&tx->tx_holds, sizeof (dmu_tx_hold_t),
70	    offsetof(dmu_tx_hold_t, txh_node));
71	list_create(&tx->tx_callbacks, sizeof (dmu_tx_callback_t),
72	    offsetof(dmu_tx_callback_t, dcb_node));
73	tx->tx_start = gethrtime();
74	return (tx);
75}
76
77dmu_tx_t *
78dmu_tx_create(objset_t *os)
79{
80	dmu_tx_t *tx = dmu_tx_create_dd(os->os_dsl_dataset->ds_dir);
81	tx->tx_objset = os;
82	return (tx);
83}
84
85dmu_tx_t *
86dmu_tx_create_assigned(struct dsl_pool *dp, uint64_t txg)
87{
88	dmu_tx_t *tx = dmu_tx_create_dd(NULL);
89
90	TXG_VERIFY(dp->dp_spa, txg);
91	tx->tx_pool = dp;
92	tx->tx_txg = txg;
93	tx->tx_anyobj = TRUE;
94
95	return (tx);
96}
97
98int
99dmu_tx_is_syncing(dmu_tx_t *tx)
100{
101	return (tx->tx_anyobj);
102}
103
104int
105dmu_tx_private_ok(dmu_tx_t *tx)
106{
107	return (tx->tx_anyobj);
108}
109
110static dmu_tx_hold_t *
111dmu_tx_hold_dnode_impl(dmu_tx_t *tx, dnode_t *dn, enum dmu_tx_hold_type type,
112    uint64_t arg1, uint64_t arg2)
113{
114	dmu_tx_hold_t *txh;
115
116	if (dn != NULL) {
117		(void) zfs_refcount_add(&dn->dn_holds, tx);
118		if (tx->tx_txg != 0) {
119			mutex_enter(&dn->dn_mtx);
120			/*
121			 * dn->dn_assigned_txg == tx->tx_txg doesn't pose a
122			 * problem, but there's no way for it to happen (for
123			 * now, at least).
124			 */
125			ASSERT(dn->dn_assigned_txg == 0);
126			dn->dn_assigned_txg = tx->tx_txg;
127			(void) zfs_refcount_add(&dn->dn_tx_holds, tx);
128			mutex_exit(&dn->dn_mtx);
129		}
130	}
131
132	txh = kmem_zalloc(sizeof (dmu_tx_hold_t), KM_SLEEP);
133	txh->txh_tx = tx;
134	txh->txh_dnode = dn;
135	zfs_refcount_create(&txh->txh_space_towrite);
136	zfs_refcount_create(&txh->txh_memory_tohold);
137	txh->txh_type = type;
138	txh->txh_arg1 = arg1;
139	txh->txh_arg2 = arg2;
140	list_insert_tail(&tx->tx_holds, txh);
141
142	return (txh);
143}
144
145static dmu_tx_hold_t *
146dmu_tx_hold_object_impl(dmu_tx_t *tx, objset_t *os, uint64_t object,
147    enum dmu_tx_hold_type type, uint64_t arg1, uint64_t arg2)
148{
149	dnode_t *dn = NULL;
150	dmu_tx_hold_t *txh;
151	int err;
152
153	if (object != DMU_NEW_OBJECT) {
154		err = dnode_hold(os, object, FTAG, &dn);
155		if (err != 0) {
156			tx->tx_err = err;
157			return (NULL);
158		}
159	}
160	txh = dmu_tx_hold_dnode_impl(tx, dn, type, arg1, arg2);
161	if (dn != NULL)
162		dnode_rele(dn, FTAG);
163	return (txh);
164}
165
166void
167dmu_tx_add_new_object(dmu_tx_t *tx, dnode_t *dn)
168{
169	/*
170	 * If we're syncing, they can manipulate any object anyhow, and
171	 * the hold on the dnode_t can cause problems.
172	 */
173	if (!dmu_tx_is_syncing(tx))
174		(void) dmu_tx_hold_dnode_impl(tx, dn, THT_NEWOBJECT, 0, 0);
175}
176
177/*
178 * This function reads specified data from disk.  The specified data will
179 * be needed to perform the transaction -- i.e, it will be read after
180 * we do dmu_tx_assign().  There are two reasons that we read the data now
181 * (before dmu_tx_assign()):
182 *
183 * 1. Reading it now has potentially better performance.  The transaction
184 * has not yet been assigned, so the TXG is not held open, and also the
185 * caller typically has less locks held when calling dmu_tx_hold_*() than
186 * after the transaction has been assigned.  This reduces the lock (and txg)
187 * hold times, thus reducing lock contention.
188 *
189 * 2. It is easier for callers (primarily the ZPL) to handle i/o errors
190 * that are detected before they start making changes to the DMU state
191 * (i.e. now).  Once the transaction has been assigned, and some DMU
192 * state has been changed, it can be difficult to recover from an i/o
193 * error (e.g. to undo the changes already made in memory at the DMU
194 * layer).  Typically code to do so does not exist in the caller -- it
195 * assumes that the data has already been cached and thus i/o errors are
196 * not possible.
197 *
198 * It has been observed that the i/o initiated here can be a performance
199 * problem, and it appears to be optional, because we don't look at the
200 * data which is read.  However, removing this read would only serve to
201 * move the work elsewhere (after the dmu_tx_assign()), where it may
202 * have a greater impact on performance (in addition to the impact on
203 * fault tolerance noted above).
204 */
205static int
206dmu_tx_check_ioerr(zio_t *zio, dnode_t *dn, int level, uint64_t blkid)
207{
208	int err;
209	dmu_buf_impl_t *db;
210
211	rw_enter(&dn->dn_struct_rwlock, RW_READER);
212	db = dbuf_hold_level(dn, level, blkid, FTAG);
213	rw_exit(&dn->dn_struct_rwlock);
214	if (db == NULL)
215		return (SET_ERROR(EIO));
216	err = dbuf_read(db, zio, DB_RF_CANFAIL | DB_RF_NOPREFETCH);
217	dbuf_rele(db, FTAG);
218	return (err);
219}
220
221/* ARGSUSED */
222static void
223dmu_tx_count_write(dmu_tx_hold_t *txh, uint64_t off, uint64_t len)
224{
225	dnode_t *dn = txh->txh_dnode;
226	int err = 0;
227
228	if (len == 0)
229		return;
230
231	(void) zfs_refcount_add_many(&txh->txh_space_towrite, len, FTAG);
232
233	if (dn == NULL)
234		return;
235
236	/*
237	 * For i/o error checking, read the blocks that will be needed
238	 * to perform the write: the first and last level-0 blocks (if
239	 * they are not aligned, i.e. if they are partial-block writes),
240	 * and all the level-1 blocks.
241	 */
242	if (dn->dn_maxblkid == 0) {
243		if (off < dn->dn_datablksz &&
244		    (off > 0 || len < dn->dn_datablksz)) {
245			err = dmu_tx_check_ioerr(NULL, dn, 0, 0);
246			if (err != 0) {
247				txh->txh_tx->tx_err = err;
248			}
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		uint64_t start = off >> dn->dn_datablkshift;
256		if (P2PHASE(off, dn->dn_datablksz) || len < dn->dn_datablksz) {
257			err = dmu_tx_check_ioerr(zio, dn, 0, start);
258			if (err != 0) {
259				txh->txh_tx->tx_err = err;
260			}
261		}
262
263		/* last level-0 block */
264		uint64_t 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 != 0) {
269				txh->txh_tx->tx_err = err;
270			}
271		}
272
273		/* level-1 blocks */
274		if (dn->dn_nlevels > 1) {
275			int shft = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
276			for (uint64_t i = (start >> shft) + 1;
277			    i < end >> shft; i++) {
278				err = dmu_tx_check_ioerr(zio, dn, 1, i);
279				if (err != 0) {
280					txh->txh_tx->tx_err = err;
281				}
282			}
283		}
284
285		err = zio_wait(zio);
286		if (err != 0) {
287			txh->txh_tx->tx_err = err;
288		}
289	}
290}
291
292static void
293dmu_tx_count_dnode(dmu_tx_hold_t *txh)
294{
295	(void) zfs_refcount_add_many(&txh->txh_space_towrite,
296	    DNODE_MIN_SIZE, FTAG);
297}
298
299void
300dmu_tx_hold_write(dmu_tx_t *tx, uint64_t object, uint64_t off, int len)
301{
302	dmu_tx_hold_t *txh;
303
304	ASSERT0(tx->tx_txg);
305	ASSERT3U(len, <=, DMU_MAX_ACCESS);
306	ASSERT(len == 0 || UINT64_MAX - off >= len - 1);
307
308	txh = dmu_tx_hold_object_impl(tx, tx->tx_objset,
309	    object, THT_WRITE, off, len);
310	if (txh != NULL) {
311		dmu_tx_count_write(txh, off, len);
312		dmu_tx_count_dnode(txh);
313	}
314}
315
316void
317dmu_tx_hold_write_by_dnode(dmu_tx_t *tx, dnode_t *dn, uint64_t off, int len)
318{
319	dmu_tx_hold_t *txh;
320
321	ASSERT0(tx->tx_txg);
322	ASSERT3U(len, <=, DMU_MAX_ACCESS);
323	ASSERT(len == 0 || UINT64_MAX - off >= len - 1);
324
325	txh = dmu_tx_hold_dnode_impl(tx, dn, THT_WRITE, off, len);
326	if (txh != NULL) {
327		dmu_tx_count_write(txh, off, len);
328		dmu_tx_count_dnode(txh);
329	}
330}
331
332/*
333 * This function marks the transaction as being a "net free".  The end
334 * result is that refquotas will be disabled for this transaction, and
335 * this transaction will be able to use half of the pool space overhead
336 * (see dsl_pool_adjustedsize()).  Therefore this function should only
337 * be called for transactions that we expect will not cause a net increase
338 * in the amount of space used (but it's OK if that is occasionally not true).
339 */
340void
341dmu_tx_mark_netfree(dmu_tx_t *tx)
342{
343	tx->tx_netfree = B_TRUE;
344}
345
346static void
347dmu_tx_hold_free_impl(dmu_tx_hold_t *txh, uint64_t off, uint64_t len)
348{
349	dmu_tx_t *tx = txh->txh_tx;
350	dnode_t *dn = txh->txh_dnode;
351	int err;
352
353	ASSERT(tx->tx_txg == 0);
354
355	dmu_tx_count_dnode(txh);
356
357	if (off >= (dn->dn_maxblkid + 1) * dn->dn_datablksz)
358		return;
359	if (len == DMU_OBJECT_END)
360		len = (dn->dn_maxblkid + 1) * dn->dn_datablksz - off;
361
362	dmu_tx_count_dnode(txh);
363
364	/*
365	 * For i/o error checking, we read the first and last level-0
366	 * blocks if they are not aligned, and all the level-1 blocks.
367	 *
368	 * Note:  dbuf_free_range() assumes that we have not instantiated
369	 * any level-0 dbufs that will be completely freed.  Therefore we must
370	 * exercise care to not read or count the first and last blocks
371	 * if they are blocksize-aligned.
372	 */
373	if (dn->dn_datablkshift == 0) {
374		if (off != 0 || len < dn->dn_datablksz)
375			dmu_tx_count_write(txh, 0, dn->dn_datablksz);
376	} else {
377		/* first block will be modified if it is not aligned */
378		if (!IS_P2ALIGNED(off, 1 << dn->dn_datablkshift))
379			dmu_tx_count_write(txh, off, 1);
380		/* last block will be modified if it is not aligned */
381		if (!IS_P2ALIGNED(off + len, 1 << dn->dn_datablkshift))
382			dmu_tx_count_write(txh, off + len, 1);
383	}
384
385	/*
386	 * Check level-1 blocks.
387	 */
388	if (dn->dn_nlevels > 1) {
389		int shift = dn->dn_datablkshift + dn->dn_indblkshift -
390		    SPA_BLKPTRSHIFT;
391		uint64_t start = off >> shift;
392		uint64_t end = (off + len) >> shift;
393
394		ASSERT(dn->dn_indblkshift != 0);
395
396		/*
397		 * dnode_reallocate() can result in an object with indirect
398		 * blocks having an odd data block size.  In this case,
399		 * just check the single block.
400		 */
401		if (dn->dn_datablkshift == 0)
402			start = end = 0;
403
404		zio_t *zio = zio_root(tx->tx_pool->dp_spa,
405		    NULL, NULL, ZIO_FLAG_CANFAIL);
406		for (uint64_t i = start; i <= end; i++) {
407			uint64_t ibyte = i << shift;
408			err = dnode_next_offset(dn, 0, &ibyte, 2, 1, 0);
409			i = ibyte >> shift;
410			if (err == ESRCH || i > end)
411				break;
412			if (err != 0) {
413				tx->tx_err = err;
414				(void) zio_wait(zio);
415				return;
416			}
417
418			(void) zfs_refcount_add_many(&txh->txh_memory_tohold,
419			    1 << dn->dn_indblkshift, FTAG);
420
421			err = dmu_tx_check_ioerr(zio, dn, 1, i);
422			if (err != 0) {
423				tx->tx_err = err;
424				(void) zio_wait(zio);
425				return;
426			}
427		}
428		err = zio_wait(zio);
429		if (err != 0) {
430			tx->tx_err = err;
431			return;
432		}
433	}
434}
435
436void
437dmu_tx_hold_free(dmu_tx_t *tx, uint64_t object, uint64_t off, uint64_t len)
438{
439	dmu_tx_hold_t *txh;
440
441	txh = dmu_tx_hold_object_impl(tx, tx->tx_objset,
442	    object, THT_FREE, off, len);
443	if (txh != NULL)
444		(void) dmu_tx_hold_free_impl(txh, off, len);
445}
446
447void
448dmu_tx_hold_free_by_dnode(dmu_tx_t *tx, dnode_t *dn, uint64_t off, uint64_t len)
449{
450	dmu_tx_hold_t *txh;
451
452	txh = dmu_tx_hold_dnode_impl(tx, dn, THT_FREE, off, len);
453	if (txh != NULL)
454		(void) dmu_tx_hold_free_impl(txh, off, len);
455}
456
457static void
458dmu_tx_hold_zap_impl(dmu_tx_hold_t *txh, const char *name)
459{
460	dmu_tx_t *tx = txh->txh_tx;
461	dnode_t *dn = txh->txh_dnode;
462	int err;
463
464	ASSERT(tx->tx_txg == 0);
465
466	dmu_tx_count_dnode(txh);
467
468	/*
469	 * Modifying a almost-full microzap is around the worst case (128KB)
470	 *
471	 * If it is a fat zap, the worst case would be 7*16KB=112KB:
472	 * - 3 blocks overwritten: target leaf, ptrtbl block, header block
473	 * - 4 new blocks written if adding:
474	 *    - 2 blocks for possibly split leaves,
475	 *    - 2 grown ptrtbl blocks
476	 */
477	(void) zfs_refcount_add_many(&txh->txh_space_towrite,
478	    MZAP_MAX_BLKSZ, FTAG);
479
480	if (dn == NULL)
481		return;
482
483	ASSERT3U(DMU_OT_BYTESWAP(dn->dn_type), ==, DMU_BSWAP_ZAP);
484
485	if (dn->dn_maxblkid == 0 || name == NULL) {
486		/*
487		 * This is a microzap (only one block), or we don't know
488		 * the name.  Check the first block for i/o errors.
489		 */
490		err = dmu_tx_check_ioerr(NULL, dn, 0, 0);
491		if (err != 0) {
492			tx->tx_err = err;
493		}
494	} else {
495		/*
496		 * Access the name so that we'll check for i/o errors to
497		 * the leaf blocks, etc.  We ignore ENOENT, as this name
498		 * may not yet exist.
499		 */
500		err = zap_lookup_by_dnode(dn, name, 8, 0, NULL);
501		if (err == EIO || err == ECKSUM || err == ENXIO) {
502			tx->tx_err = err;
503		}
504	}
505}
506
507void
508dmu_tx_hold_zap(dmu_tx_t *tx, uint64_t object, int add, const char *name)
509{
510	dmu_tx_hold_t *txh;
511
512	ASSERT0(tx->tx_txg);
513
514	txh = dmu_tx_hold_object_impl(tx, tx->tx_objset,
515	    object, THT_ZAP, add, (uintptr_t)name);
516	if (txh != NULL)
517		dmu_tx_hold_zap_impl(txh, name);
518}
519
520void
521dmu_tx_hold_zap_by_dnode(dmu_tx_t *tx, dnode_t *dn, int add, const char *name)
522{
523	dmu_tx_hold_t *txh;
524
525	ASSERT0(tx->tx_txg);
526	ASSERT(dn != NULL);
527
528	txh = dmu_tx_hold_dnode_impl(tx, dn, THT_ZAP, add, (uintptr_t)name);
529	if (txh != NULL)
530		dmu_tx_hold_zap_impl(txh, name);
531}
532
533void
534dmu_tx_hold_bonus(dmu_tx_t *tx, uint64_t object)
535{
536	dmu_tx_hold_t *txh;
537
538	ASSERT(tx->tx_txg == 0);
539
540	txh = dmu_tx_hold_object_impl(tx, tx->tx_objset,
541	    object, THT_BONUS, 0, 0);
542	if (txh)
543		dmu_tx_count_dnode(txh);
544}
545
546void
547dmu_tx_hold_bonus_by_dnode(dmu_tx_t *tx, dnode_t *dn)
548{
549	dmu_tx_hold_t *txh;
550
551	ASSERT0(tx->tx_txg);
552
553	txh = dmu_tx_hold_dnode_impl(tx, dn, THT_BONUS, 0, 0);
554	if (txh)
555		dmu_tx_count_dnode(txh);
556}
557
558void
559dmu_tx_hold_space(dmu_tx_t *tx, uint64_t space)
560{
561	dmu_tx_hold_t *txh;
562
563	ASSERT(tx->tx_txg == 0);
564
565	txh = dmu_tx_hold_object_impl(tx, tx->tx_objset,
566	    DMU_NEW_OBJECT, THT_SPACE, space, 0);
567	if (txh) {
568		(void) zfs_refcount_add_many(
569		    &txh->txh_space_towrite, space, FTAG);
570	}
571}
572
573#ifdef ZFS_DEBUG
574void
575dmu_tx_dirty_buf(dmu_tx_t *tx, dmu_buf_impl_t *db)
576{
577	boolean_t match_object = B_FALSE;
578	boolean_t match_offset = B_FALSE;
579
580	DB_DNODE_ENTER(db);
581	dnode_t *dn = DB_DNODE(db);
582	ASSERT(tx->tx_txg != 0);
583	ASSERT(tx->tx_objset == NULL || dn->dn_objset == tx->tx_objset);
584	ASSERT3U(dn->dn_object, ==, db->db.db_object);
585
586	if (tx->tx_anyobj) {
587		DB_DNODE_EXIT(db);
588		return;
589	}
590
591	/* XXX No checking on the meta dnode for now */
592	if (db->db.db_object == DMU_META_DNODE_OBJECT) {
593		DB_DNODE_EXIT(db);
594		return;
595	}
596
597	for (dmu_tx_hold_t *txh = list_head(&tx->tx_holds); txh != NULL;
598	    txh = list_next(&tx->tx_holds, txh)) {
599		ASSERT3U(dn->dn_assigned_txg, ==, tx->tx_txg);
600		if (txh->txh_dnode == dn && txh->txh_type != THT_NEWOBJECT)
601			match_object = TRUE;
602		if (txh->txh_dnode == NULL || txh->txh_dnode == dn) {
603			int datablkshift = dn->dn_datablkshift ?
604			    dn->dn_datablkshift : SPA_MAXBLOCKSHIFT;
605			int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
606			int shift = datablkshift + epbs * db->db_level;
607			uint64_t beginblk = shift >= 64 ? 0 :
608			    (txh->txh_arg1 >> shift);
609			uint64_t endblk = shift >= 64 ? 0 :
610			    ((txh->txh_arg1 + txh->txh_arg2 - 1) >> shift);
611			uint64_t blkid = db->db_blkid;
612
613			/* XXX txh_arg2 better not be zero... */
614
615			dprintf("found txh type %x beginblk=%llx endblk=%llx\n",
616			    txh->txh_type, beginblk, endblk);
617
618			switch (txh->txh_type) {
619			case THT_WRITE:
620				if (blkid >= beginblk && blkid <= endblk)
621					match_offset = TRUE;
622				/*
623				 * We will let this hold work for the bonus
624				 * or spill buffer so that we don't need to
625				 * hold it when creating a new object.
626				 */
627				if (blkid == DMU_BONUS_BLKID ||
628				    blkid == DMU_SPILL_BLKID)
629					match_offset = TRUE;
630				/*
631				 * They might have to increase nlevels,
632				 * thus dirtying the new TLIBs.  Or the
633				 * might have to change the block size,
634				 * thus dirying the new lvl=0 blk=0.
635				 */
636				if (blkid == 0)
637					match_offset = TRUE;
638				break;
639			case THT_FREE:
640				/*
641				 * We will dirty all the level 1 blocks in
642				 * the free range and perhaps the first and
643				 * last level 0 block.
644				 */
645				if (blkid >= beginblk && (blkid <= endblk ||
646				    txh->txh_arg2 == DMU_OBJECT_END))
647					match_offset = TRUE;
648				break;
649			case THT_SPILL:
650				if (blkid == DMU_SPILL_BLKID)
651					match_offset = TRUE;
652				break;
653			case THT_BONUS:
654				if (blkid == DMU_BONUS_BLKID)
655					match_offset = TRUE;
656				break;
657			case THT_ZAP:
658				match_offset = TRUE;
659				break;
660			case THT_NEWOBJECT:
661				match_object = TRUE;
662				break;
663			default:
664				cmn_err(CE_PANIC, "bad txh_type %d",
665				    txh->txh_type);
666			}
667		}
668		if (match_object && match_offset) {
669			DB_DNODE_EXIT(db);
670			return;
671		}
672	}
673	DB_DNODE_EXIT(db);
674	panic("dirtying dbuf obj=%llx lvl=%u blkid=%llx but not tx_held\n",
675	    (u_longlong_t)db->db.db_object, db->db_level,
676	    (u_longlong_t)db->db_blkid);
677}
678#endif
679
680/*
681 * If we can't do 10 iops, something is wrong.  Let us go ahead
682 * and hit zfs_dirty_data_max.
683 */
684hrtime_t zfs_delay_max_ns = 100 * MICROSEC; /* 100 milliseconds */
685int zfs_delay_resolution_ns = 100 * 1000; /* 100 microseconds */
686
687/*
688 * We delay transactions when we've determined that the backend storage
689 * isn't able to accommodate the rate of incoming writes.
690 *
691 * If there is already a transaction waiting, we delay relative to when
692 * that transaction finishes waiting.  This way the calculated min_time
693 * is independent of the number of threads concurrently executing
694 * transactions.
695 *
696 * If we are the only waiter, wait relative to when the transaction
697 * started, rather than the current time.  This credits the transaction for
698 * "time already served", e.g. reading indirect blocks.
699 *
700 * The minimum time for a transaction to take is calculated as:
701 *     min_time = scale * (dirty - min) / (max - dirty)
702 *     min_time is then capped at zfs_delay_max_ns.
703 *
704 * The delay has two degrees of freedom that can be adjusted via tunables.
705 * The percentage of dirty data at which we start to delay is defined by
706 * zfs_delay_min_dirty_percent. This should typically be at or above
707 * zfs_vdev_async_write_active_max_dirty_percent so that we only start to
708 * delay after writing at full speed has failed to keep up with the incoming
709 * write rate. The scale of the curve is defined by zfs_delay_scale. Roughly
710 * speaking, this variable determines the amount of delay at the midpoint of
711 * the curve.
712 *
713 * delay
714 *  10ms +-------------------------------------------------------------*+
715 *       |                                                             *|
716 *   9ms +                                                             *+
717 *       |                                                             *|
718 *   8ms +                                                             *+
719 *       |                                                            * |
720 *   7ms +                                                            * +
721 *       |                                                            * |
722 *   6ms +                                                            * +
723 *       |                                                            * |
724 *   5ms +                                                           *  +
725 *       |                                                           *  |
726 *   4ms +                                                           *  +
727 *       |                                                           *  |
728 *   3ms +                                                          *   +
729 *       |                                                          *   |
730 *   2ms +                                              (midpoint) *    +
731 *       |                                                  |    **     |
732 *   1ms +                                                  v ***       +
733 *       |             zfs_delay_scale ---------->     ********         |
734 *     0 +-------------------------------------*********----------------+
735 *       0%                    <- zfs_dirty_data_max ->               100%
736 *
737 * Note that since the delay is added to the outstanding time remaining on the
738 * most recent transaction, the delay is effectively the inverse of IOPS.
739 * Here the midpoint of 500us translates to 2000 IOPS. The shape of the curve
740 * was chosen such that small changes in the amount of accumulated dirty data
741 * in the first 3/4 of the curve yield relatively small differences in the
742 * amount of delay.
743 *
744 * The effects can be easier to understand when the amount of delay is
745 * represented on a log scale:
746 *
747 * delay
748 * 100ms +-------------------------------------------------------------++
749 *       +                                                              +
750 *       |                                                              |
751 *       +                                                             *+
752 *  10ms +                                                             *+
753 *       +                                                           ** +
754 *       |                                              (midpoint)  **  |
755 *       +                                                  |     **    +
756 *   1ms +                                                  v ****      +
757 *       +             zfs_delay_scale ---------->        *****         +
758 *       |                                             ****             |
759 *       +                                          ****                +
760 * 100us +                                        **                    +
761 *       +                                       *                      +
762 *       |                                      *                       |
763 *       +                                     *                        +
764 *  10us +                                     *                        +
765 *       +                                                              +
766 *       |                                                              |
767 *       +                                                              +
768 *       +--------------------------------------------------------------+
769 *       0%                    <- zfs_dirty_data_max ->               100%
770 *
771 * Note here that only as the amount of dirty data approaches its limit does
772 * the delay start to increase rapidly. The goal of a properly tuned system
773 * should be to keep the amount of dirty data out of that range by first
774 * ensuring that the appropriate limits are set for the I/O scheduler to reach
775 * optimal throughput on the backend storage, and then by changing the value
776 * of zfs_delay_scale to increase the steepness of the curve.
777 */
778static void
779dmu_tx_delay(dmu_tx_t *tx, uint64_t dirty)
780{
781	dsl_pool_t *dp = tx->tx_pool;
782	uint64_t delay_min_bytes =
783	    zfs_dirty_data_max * zfs_delay_min_dirty_percent / 100;
784	hrtime_t wakeup, min_tx_time, now;
785
786	if (dirty <= delay_min_bytes)
787		return;
788
789	/*
790	 * The caller has already waited until we are under the max.
791	 * We make them pass us the amount of dirty data so we don't
792	 * have to handle the case of it being >= the max, which could
793	 * cause a divide-by-zero if it's == the max.
794	 */
795	ASSERT3U(dirty, <, zfs_dirty_data_max);
796
797	now = gethrtime();
798	min_tx_time = zfs_delay_scale *
799	    (dirty - delay_min_bytes) / (zfs_dirty_data_max - dirty);
800	min_tx_time = MIN(min_tx_time, zfs_delay_max_ns);
801	if (now > tx->tx_start + min_tx_time)
802		return;
803
804	DTRACE_PROBE3(delay__mintime, dmu_tx_t *, tx, uint64_t, dirty,
805	    uint64_t, min_tx_time);
806
807	mutex_enter(&dp->dp_lock);
808	wakeup = MAX(tx->tx_start + min_tx_time,
809	    dp->dp_last_wakeup + min_tx_time);
810	dp->dp_last_wakeup = wakeup;
811	mutex_exit(&dp->dp_lock);
812
813	zfs_sleep_until(wakeup);
814}
815
816/*
817 * This routine attempts to assign the transaction to a transaction group.
818 * To do so, we must determine if there is sufficient free space on disk.
819 *
820 * If this is a "netfree" transaction (i.e. we called dmu_tx_mark_netfree()
821 * on it), then it is assumed that there is sufficient free space,
822 * unless there's insufficient slop space in the pool (see the comment
823 * above spa_slop_shift in spa_misc.c).
824 *
825 * If it is not a "netfree" transaction, then if the data already on disk
826 * is over the allowed usage (e.g. quota), this will fail with EDQUOT or
827 * ENOSPC.  Otherwise, if the current rough estimate of pending changes,
828 * plus the rough estimate of this transaction's changes, may exceed the
829 * allowed usage, then this will fail with ERESTART, which will cause the
830 * caller to wait for the pending changes to be written to disk (by waiting
831 * for the next TXG to open), and then check the space usage again.
832 *
833 * The rough estimate of pending changes is comprised of the sum of:
834 *
835 *  - this transaction's holds' txh_space_towrite
836 *
837 *  - dd_tempreserved[], which is the sum of in-flight transactions'
838 *    holds' txh_space_towrite (i.e. those transactions that have called
839 *    dmu_tx_assign() but not yet called dmu_tx_commit()).
840 *
841 *  - dd_space_towrite[], which is the amount of dirtied dbufs.
842 *
843 * Note that all of these values are inflated by spa_get_worst_case_asize(),
844 * which means that we may get ERESTART well before we are actually in danger
845 * of running out of space, but this also mitigates any small inaccuracies
846 * in the rough estimate (e.g. txh_space_towrite doesn't take into account
847 * indirect blocks, and dd_space_towrite[] doesn't take into account changes
848 * to the MOS).
849 *
850 * Note that due to this algorithm, it is possible to exceed the allowed
851 * usage by one transaction.  Also, as we approach the allowed usage,
852 * we will allow a very limited amount of changes into each TXG, thus
853 * decreasing performance.
854 */
855static int
856dmu_tx_try_assign(dmu_tx_t *tx, uint64_t txg_how)
857{
858	spa_t *spa = tx->tx_pool->dp_spa;
859
860	ASSERT0(tx->tx_txg);
861
862	if (tx->tx_err) {
863		DMU_TX_STAT_BUMP(dmu_tx_error);
864		return (tx->tx_err);
865	}
866
867	if (spa_suspended(spa)) {
868		DMU_TX_STAT_BUMP(dmu_tx_suspended);
869
870		/*
871		 * If the user has indicated a blocking failure mode
872		 * then return ERESTART which will block in dmu_tx_wait().
873		 * Otherwise, return EIO so that an error can get
874		 * propagated back to the VOP calls.
875		 *
876		 * Note that we always honor the txg_how flag regardless
877		 * of the failuremode setting.
878		 */
879		if (spa_get_failmode(spa) == ZIO_FAILURE_MODE_CONTINUE &&
880		    !(txg_how & TXG_WAIT))
881			return (SET_ERROR(EIO));
882
883		return (SET_ERROR(ERESTART));
884	}
885
886	if (!tx->tx_dirty_delayed &&
887	    dsl_pool_need_dirty_delay(tx->tx_pool)) {
888		tx->tx_wait_dirty = B_TRUE;
889		DMU_TX_STAT_BUMP(dmu_tx_dirty_delay);
890		return (SET_ERROR(ERESTART));
891	}
892
893	tx->tx_txg = txg_hold_open(tx->tx_pool, &tx->tx_txgh);
894	tx->tx_needassign_txh = NULL;
895
896	/*
897	 * NB: No error returns are allowed after txg_hold_open, but
898	 * before processing the dnode holds, due to the
899	 * dmu_tx_unassign() logic.
900	 */
901
902	uint64_t towrite = 0;
903	uint64_t tohold = 0;
904	for (dmu_tx_hold_t *txh = list_head(&tx->tx_holds); txh != NULL;
905	    txh = list_next(&tx->tx_holds, txh)) {
906		dnode_t *dn = txh->txh_dnode;
907		if (dn != NULL) {
908			/*
909			 * This thread can't hold the dn_struct_rwlock
910			 * while assigning the tx, because this can lead to
911			 * deadlock. Specifically, if this dnode is already
912			 * assigned to an earlier txg, this thread may need
913			 * to wait for that txg to sync (the ERESTART case
914			 * below).  The other thread that has assigned this
915			 * dnode to an earlier txg prevents this txg from
916			 * syncing until its tx can complete (calling
917			 * dmu_tx_commit()), but it may need to acquire the
918			 * dn_struct_rwlock to do so (e.g. via
919			 * dmu_buf_hold*()).
920			 *
921			 * Note that this thread can't hold the lock for
922			 * read either, but the rwlock doesn't record
923			 * enough information to make that assertion.
924			 */
925			ASSERT(!RW_WRITE_HELD(&dn->dn_struct_rwlock));
926
927			mutex_enter(&dn->dn_mtx);
928			if (dn->dn_assigned_txg == tx->tx_txg - 1) {
929				mutex_exit(&dn->dn_mtx);
930				tx->tx_needassign_txh = txh;
931				DMU_TX_STAT_BUMP(dmu_tx_group);
932				return (SET_ERROR(ERESTART));
933			}
934			if (dn->dn_assigned_txg == 0)
935				dn->dn_assigned_txg = tx->tx_txg;
936			ASSERT3U(dn->dn_assigned_txg, ==, tx->tx_txg);
937			(void) zfs_refcount_add(&dn->dn_tx_holds, tx);
938			mutex_exit(&dn->dn_mtx);
939		}
940		towrite += zfs_refcount_count(&txh->txh_space_towrite);
941		tohold += zfs_refcount_count(&txh->txh_memory_tohold);
942	}
943
944	/* needed allocation: worst-case estimate of write space */
945	uint64_t asize = spa_get_worst_case_asize(tx->tx_pool->dp_spa, towrite);
946	/* calculate memory footprint estimate */
947	uint64_t memory = towrite + tohold;
948
949	if (tx->tx_dir != NULL && asize != 0) {
950		int err = dsl_dir_tempreserve_space(tx->tx_dir, memory,
951		    asize, tx->tx_netfree, &tx->tx_tempreserve_cookie, tx);
952		if (err != 0)
953			return (err);
954	}
955
956	DMU_TX_STAT_BUMP(dmu_tx_assigned);
957
958	return (0);
959}
960
961static void
962dmu_tx_unassign(dmu_tx_t *tx)
963{
964	if (tx->tx_txg == 0)
965		return;
966
967	txg_rele_to_quiesce(&tx->tx_txgh);
968
969	/*
970	 * Walk the transaction's hold list, removing the hold on the
971	 * associated dnode, and notifying waiters if the refcount drops to 0.
972	 */
973	for (dmu_tx_hold_t *txh = list_head(&tx->tx_holds);
974	    txh && txh != tx->tx_needassign_txh;
975	    txh = list_next(&tx->tx_holds, txh)) {
976		dnode_t *dn = txh->txh_dnode;
977
978		if (dn == NULL)
979			continue;
980		mutex_enter(&dn->dn_mtx);
981		ASSERT3U(dn->dn_assigned_txg, ==, tx->tx_txg);
982
983		if (zfs_refcount_remove(&dn->dn_tx_holds, tx) == 0) {
984			dn->dn_assigned_txg = 0;
985			cv_broadcast(&dn->dn_notxholds);
986		}
987		mutex_exit(&dn->dn_mtx);
988	}
989
990	txg_rele_to_sync(&tx->tx_txgh);
991
992	tx->tx_lasttried_txg = tx->tx_txg;
993	tx->tx_txg = 0;
994}
995
996/*
997 * Assign tx to a transaction group; txg_how is a bitmask:
998 *
999 * If TXG_WAIT is set and the currently open txg is full, this function
1000 * will wait until there's a new txg. This should be used when no locks
1001 * are being held. With this bit set, this function will only fail if
1002 * we're truly out of space (or over quota).
1003 *
1004 * If TXG_WAIT is *not* set and we can't assign into the currently open
1005 * txg without blocking, this function will return immediately with
1006 * ERESTART. This should be used whenever locks are being held.  On an
1007 * ERESTART error, the caller should drop all locks, call dmu_tx_wait(),
1008 * and try again.
1009 *
1010 * If TXG_NOTHROTTLE is set, this indicates that this tx should not be
1011 * delayed due on the ZFS Write Throttle (see comments in dsl_pool.c for
1012 * details on the throttle). This is used by the VFS operations, after
1013 * they have already called dmu_tx_wait() (though most likely on a
1014 * different tx).
1015 *
1016 * It is guaranteed that subsequent successful calls to dmu_tx_assign()
1017 * will assign the tx to monotonically increasing txgs. Of course this is
1018 * not strong monotonicity, because the same txg can be returned multiple
1019 * times in a row. This guarantee holds both for subsequent calls from
1020 * one thread and for multiple threads. For example, it is impossible to
1021 * observe the following sequence of events:
1022 *
1023 *          Thread 1                            Thread 2
1024 *
1025 *     dmu_tx_assign(T1, ...)
1026 *     1 <- dmu_tx_get_txg(T1)
1027 *                                       dmu_tx_assign(T2, ...)
1028 *                                       2 <- dmu_tx_get_txg(T2)
1029 *     dmu_tx_assign(T3, ...)
1030 *     1 <- dmu_tx_get_txg(T3)
1031 */
1032int
1033dmu_tx_assign(dmu_tx_t *tx, uint64_t txg_how)
1034{
1035	int err;
1036
1037	ASSERT(tx->tx_txg == 0);
1038	ASSERT0(txg_how & ~(TXG_WAIT | TXG_NOTHROTTLE));
1039	ASSERT(!dsl_pool_sync_context(tx->tx_pool));
1040
1041	/* If we might wait, we must not hold the config lock. */
1042	IMPLY((txg_how & TXG_WAIT), !dsl_pool_config_held(tx->tx_pool));
1043
1044	if ((txg_how & TXG_NOTHROTTLE))
1045		tx->tx_dirty_delayed = B_TRUE;
1046
1047	while ((err = dmu_tx_try_assign(tx, txg_how)) != 0) {
1048		dmu_tx_unassign(tx);
1049
1050		if (err != ERESTART || !(txg_how & TXG_WAIT))
1051			return (err);
1052
1053		dmu_tx_wait(tx);
1054	}
1055
1056	txg_rele_to_quiesce(&tx->tx_txgh);
1057
1058	return (0);
1059}
1060
1061void
1062dmu_tx_wait(dmu_tx_t *tx)
1063{
1064	spa_t *spa = tx->tx_pool->dp_spa;
1065	dsl_pool_t *dp = tx->tx_pool;
1066	hrtime_t before;
1067
1068	ASSERT(tx->tx_txg == 0);
1069	ASSERT(!dsl_pool_config_held(tx->tx_pool));
1070
1071	before = gethrtime();
1072
1073	if (tx->tx_wait_dirty) {
1074		uint64_t dirty;
1075
1076		/*
1077		 * dmu_tx_try_assign() has determined that we need to wait
1078		 * because we've consumed much or all of the dirty buffer
1079		 * space.
1080		 */
1081		mutex_enter(&dp->dp_lock);
1082		if (dp->dp_dirty_total >= zfs_dirty_data_max)
1083			DMU_TX_STAT_BUMP(dmu_tx_dirty_over_max);
1084		while (dp->dp_dirty_total >= zfs_dirty_data_max)
1085			cv_wait(&dp->dp_spaceavail_cv, &dp->dp_lock);
1086		dirty = dp->dp_dirty_total;
1087		mutex_exit(&dp->dp_lock);
1088
1089		dmu_tx_delay(tx, dirty);
1090
1091		tx->tx_wait_dirty = B_FALSE;
1092
1093		/*
1094		 * Note: setting tx_dirty_delayed only has effect if the
1095		 * caller used TX_WAIT.  Otherwise they are going to
1096		 * destroy this tx and try again.  The common case,
1097		 * zfs_write(), uses TX_WAIT.
1098		 */
1099		tx->tx_dirty_delayed = B_TRUE;
1100	} else if (spa_suspended(spa) || tx->tx_lasttried_txg == 0) {
1101		/*
1102		 * If the pool is suspended we need to wait until it
1103		 * is resumed.  Note that it's possible that the pool
1104		 * has become active after this thread has tried to
1105		 * obtain a tx.  If that's the case then tx_lasttried_txg
1106		 * would not have been set.
1107		 */
1108		txg_wait_synced(dp, spa_last_synced_txg(spa) + 1);
1109	} else if (tx->tx_needassign_txh) {
1110		dnode_t *dn = tx->tx_needassign_txh->txh_dnode;
1111
1112		mutex_enter(&dn->dn_mtx);
1113		while (dn->dn_assigned_txg == tx->tx_lasttried_txg - 1)
1114			cv_wait(&dn->dn_notxholds, &dn->dn_mtx);
1115		mutex_exit(&dn->dn_mtx);
1116		tx->tx_needassign_txh = NULL;
1117	} else {
1118		/*
1119		 * If we have a lot of dirty data just wait until we sync
1120		 * out a TXG at which point we'll hopefully have synced
1121		 * a portion of the changes.
1122		 */
1123		txg_wait_synced(dp, spa_last_synced_txg(spa) + 1);
1124	}
1125
1126	spa_tx_assign_add_nsecs(spa, gethrtime() - before);
1127}
1128
1129static void
1130dmu_tx_destroy(dmu_tx_t *tx)
1131{
1132	dmu_tx_hold_t *txh;
1133
1134	while ((txh = list_head(&tx->tx_holds)) != NULL) {
1135		dnode_t *dn = txh->txh_dnode;
1136
1137		list_remove(&tx->tx_holds, txh);
1138		zfs_refcount_destroy_many(&txh->txh_space_towrite,
1139		    zfs_refcount_count(&txh->txh_space_towrite));
1140		zfs_refcount_destroy_many(&txh->txh_memory_tohold,
1141		    zfs_refcount_count(&txh->txh_memory_tohold));
1142		kmem_free(txh, sizeof (dmu_tx_hold_t));
1143		if (dn != NULL)
1144			dnode_rele(dn, tx);
1145	}
1146
1147	list_destroy(&tx->tx_callbacks);
1148	list_destroy(&tx->tx_holds);
1149	kmem_free(tx, sizeof (dmu_tx_t));
1150}
1151
1152void
1153dmu_tx_commit(dmu_tx_t *tx)
1154{
1155	ASSERT(tx->tx_txg != 0);
1156
1157	/*
1158	 * Go through the transaction's hold list and remove holds on
1159	 * associated dnodes, notifying waiters if no holds remain.
1160	 */
1161	for (dmu_tx_hold_t *txh = list_head(&tx->tx_holds); txh != NULL;
1162	    txh = list_next(&tx->tx_holds, txh)) {
1163		dnode_t *dn = txh->txh_dnode;
1164
1165		if (dn == NULL)
1166			continue;
1167
1168		mutex_enter(&dn->dn_mtx);
1169		ASSERT3U(dn->dn_assigned_txg, ==, tx->tx_txg);
1170
1171		if (zfs_refcount_remove(&dn->dn_tx_holds, tx) == 0) {
1172			dn->dn_assigned_txg = 0;
1173			cv_broadcast(&dn->dn_notxholds);
1174		}
1175		mutex_exit(&dn->dn_mtx);
1176	}
1177
1178	if (tx->tx_tempreserve_cookie)
1179		dsl_dir_tempreserve_clear(tx->tx_tempreserve_cookie, tx);
1180
1181	if (!list_is_empty(&tx->tx_callbacks))
1182		txg_register_callbacks(&tx->tx_txgh, &tx->tx_callbacks);
1183
1184	if (tx->tx_anyobj == FALSE)
1185		txg_rele_to_sync(&tx->tx_txgh);
1186
1187	dmu_tx_destroy(tx);
1188}
1189
1190void
1191dmu_tx_abort(dmu_tx_t *tx)
1192{
1193	ASSERT(tx->tx_txg == 0);
1194
1195	/*
1196	 * Call any registered callbacks with an error code.
1197	 */
1198	if (!list_is_empty(&tx->tx_callbacks))
1199		dmu_tx_do_callbacks(&tx->tx_callbacks, SET_ERROR(ECANCELED));
1200
1201	dmu_tx_destroy(tx);
1202}
1203
1204uint64_t
1205dmu_tx_get_txg(dmu_tx_t *tx)
1206{
1207	ASSERT(tx->tx_txg != 0);
1208	return (tx->tx_txg);
1209}
1210
1211dsl_pool_t *
1212dmu_tx_pool(dmu_tx_t *tx)
1213{
1214	ASSERT(tx->tx_pool != NULL);
1215	return (tx->tx_pool);
1216}
1217
1218void
1219dmu_tx_callback_register(dmu_tx_t *tx, dmu_tx_callback_func_t *func, void *data)
1220{
1221	dmu_tx_callback_t *dcb;
1222
1223	dcb = kmem_alloc(sizeof (dmu_tx_callback_t), KM_SLEEP);
1224
1225	dcb->dcb_func = func;
1226	dcb->dcb_data = data;
1227
1228	list_insert_tail(&tx->tx_callbacks, dcb);
1229}
1230
1231/*
1232 * Call all the commit callbacks on a list, with a given error code.
1233 */
1234void
1235dmu_tx_do_callbacks(list_t *cb_list, int error)
1236{
1237	dmu_tx_callback_t *dcb;
1238
1239	while ((dcb = list_tail(cb_list)) != NULL) {
1240		list_remove(cb_list, dcb);
1241		dcb->dcb_func(dcb->dcb_data, error);
1242		kmem_free(dcb, sizeof (dmu_tx_callback_t));
1243	}
1244}
1245
1246/*
1247 * Interface to hold a bunch of attributes.
1248 * used for creating new files.
1249 * attrsize is the total size of all attributes
1250 * to be added during object creation
1251 *
1252 * For updating/adding a single attribute dmu_tx_hold_sa() should be used.
1253 */
1254
1255/*
1256 * hold necessary attribute name for attribute registration.
1257 * should be a very rare case where this is needed.  If it does
1258 * happen it would only happen on the first write to the file system.
1259 */
1260static void
1261dmu_tx_sa_registration_hold(sa_os_t *sa, dmu_tx_t *tx)
1262{
1263	if (!sa->sa_need_attr_registration)
1264		return;
1265
1266	for (int i = 0; i != sa->sa_num_attrs; i++) {
1267		if (!sa->sa_attr_table[i].sa_registered) {
1268			if (sa->sa_reg_attr_obj)
1269				dmu_tx_hold_zap(tx, sa->sa_reg_attr_obj,
1270				    B_TRUE, sa->sa_attr_table[i].sa_name);
1271			else
1272				dmu_tx_hold_zap(tx, DMU_NEW_OBJECT,
1273				    B_TRUE, sa->sa_attr_table[i].sa_name);
1274		}
1275	}
1276}
1277
1278void
1279dmu_tx_hold_spill(dmu_tx_t *tx, uint64_t object)
1280{
1281	dmu_tx_hold_t *txh;
1282
1283	txh = dmu_tx_hold_object_impl(tx, tx->tx_objset, object,
1284	    THT_SPILL, 0, 0);
1285	if (txh != NULL)
1286		(void) zfs_refcount_add_many(&txh->txh_space_towrite,
1287		    SPA_OLD_MAXBLOCKSIZE, FTAG);
1288}
1289
1290void
1291dmu_tx_hold_sa_create(dmu_tx_t *tx, int attrsize)
1292{
1293	sa_os_t *sa = tx->tx_objset->os_sa;
1294
1295	dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
1296
1297	if (tx->tx_objset->os_sa->sa_master_obj == 0)
1298		return;
1299
1300	if (tx->tx_objset->os_sa->sa_layout_attr_obj) {
1301		dmu_tx_hold_zap(tx, sa->sa_layout_attr_obj, B_TRUE, NULL);
1302	} else {
1303		dmu_tx_hold_zap(tx, sa->sa_master_obj, B_TRUE, SA_LAYOUTS);
1304		dmu_tx_hold_zap(tx, sa->sa_master_obj, B_TRUE, SA_REGISTRY);
1305		dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, B_TRUE, NULL);
1306		dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, B_TRUE, NULL);
1307	}
1308
1309	dmu_tx_sa_registration_hold(sa, tx);
1310
1311	if (attrsize <= DN_OLD_MAX_BONUSLEN && !sa->sa_force_spill)
1312		return;
1313
1314	(void) dmu_tx_hold_object_impl(tx, tx->tx_objset, DMU_NEW_OBJECT,
1315	    THT_SPILL, 0, 0);
1316}
1317
1318/*
1319 * Hold SA attribute
1320 *
1321 * dmu_tx_hold_sa(dmu_tx_t *tx, sa_handle_t *, attribute, add, size)
1322 *
1323 * variable_size is the total size of all variable sized attributes
1324 * passed to this function.  It is not the total size of all
1325 * variable size attributes that *may* exist on this object.
1326 */
1327void
1328dmu_tx_hold_sa(dmu_tx_t *tx, sa_handle_t *hdl, boolean_t may_grow)
1329{
1330	uint64_t object;
1331	sa_os_t *sa = tx->tx_objset->os_sa;
1332
1333	ASSERT(hdl != NULL);
1334
1335	object = sa_handle_object(hdl);
1336
1337	dmu_buf_impl_t *db = (dmu_buf_impl_t *)hdl->sa_bonus;
1338	DB_DNODE_ENTER(db);
1339	dmu_tx_hold_bonus_by_dnode(tx, DB_DNODE(db));
1340	DB_DNODE_EXIT(db);
1341
1342	if (tx->tx_objset->os_sa->sa_master_obj == 0)
1343		return;
1344
1345	if (tx->tx_objset->os_sa->sa_reg_attr_obj == 0 ||
1346	    tx->tx_objset->os_sa->sa_layout_attr_obj == 0) {
1347		dmu_tx_hold_zap(tx, sa->sa_master_obj, B_TRUE, SA_LAYOUTS);
1348		dmu_tx_hold_zap(tx, sa->sa_master_obj, B_TRUE, SA_REGISTRY);
1349		dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, B_TRUE, NULL);
1350		dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, B_TRUE, NULL);
1351	}
1352
1353	dmu_tx_sa_registration_hold(sa, tx);
1354
1355	if (may_grow && tx->tx_objset->os_sa->sa_layout_attr_obj)
1356		dmu_tx_hold_zap(tx, sa->sa_layout_attr_obj, B_TRUE, NULL);
1357
1358	if (sa->sa_force_spill || may_grow || hdl->sa_spill) {
1359		ASSERT(tx->tx_txg == 0);
1360		dmu_tx_hold_spill(tx, object);
1361	} else {
1362		dnode_t *dn;
1363
1364		DB_DNODE_ENTER(db);
1365		dn = DB_DNODE(db);
1366		if (dn->dn_have_spill) {
1367			ASSERT(tx->tx_txg == 0);
1368			dmu_tx_hold_spill(tx, object);
1369		}
1370		DB_DNODE_EXIT(db);
1371	}
1372}
1373
1374void
1375dmu_tx_init(void)
1376{
1377	dmu_tx_ksp = kstat_create("zfs", 0, "dmu_tx", "misc",
1378	    KSTAT_TYPE_NAMED, sizeof (dmu_tx_stats) / sizeof (kstat_named_t),
1379	    KSTAT_FLAG_VIRTUAL);
1380
1381	if (dmu_tx_ksp != NULL) {
1382		dmu_tx_ksp->ks_data = &dmu_tx_stats;
1383		kstat_install(dmu_tx_ksp);
1384	}
1385}
1386
1387void
1388dmu_tx_fini(void)
1389{
1390	if (dmu_tx_ksp != NULL) {
1391		kstat_delete(dmu_tx_ksp);
1392		dmu_tx_ksp = NULL;
1393	}
1394}
1395
1396#if defined(_KERNEL)
1397EXPORT_SYMBOL(dmu_tx_create);
1398EXPORT_SYMBOL(dmu_tx_hold_write);
1399EXPORT_SYMBOL(dmu_tx_hold_write_by_dnode);
1400EXPORT_SYMBOL(dmu_tx_hold_free);
1401EXPORT_SYMBOL(dmu_tx_hold_free_by_dnode);
1402EXPORT_SYMBOL(dmu_tx_hold_zap);
1403EXPORT_SYMBOL(dmu_tx_hold_zap_by_dnode);
1404EXPORT_SYMBOL(dmu_tx_hold_bonus);
1405EXPORT_SYMBOL(dmu_tx_hold_bonus_by_dnode);
1406EXPORT_SYMBOL(dmu_tx_abort);
1407EXPORT_SYMBOL(dmu_tx_assign);
1408EXPORT_SYMBOL(dmu_tx_wait);
1409EXPORT_SYMBOL(dmu_tx_commit);
1410EXPORT_SYMBOL(dmu_tx_mark_netfree);
1411EXPORT_SYMBOL(dmu_tx_get_txg);
1412EXPORT_SYMBOL(dmu_tx_callback_register);
1413EXPORT_SYMBOL(dmu_tx_do_callbacks);
1414EXPORT_SYMBOL(dmu_tx_hold_spill);
1415EXPORT_SYMBOL(dmu_tx_hold_sa_create);
1416EXPORT_SYMBOL(dmu_tx_hold_sa);
1417#endif
1418