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