]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - module/zfs/dbuf.c
Prepare ks_data before calling kstat_install()
[FreeBSD/FreeBSD.git] / module / zfs / dbuf.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, 2019 by Delphix. All rights reserved.
25  * Copyright (c) 2013 by Saso Kiselkov. All rights reserved.
26  * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
27  */
28
29 #include <sys/zfs_context.h>
30 #include <sys/arc.h>
31 #include <sys/dmu.h>
32 #include <sys/dmu_send.h>
33 #include <sys/dmu_impl.h>
34 #include <sys/dbuf.h>
35 #include <sys/dmu_objset.h>
36 #include <sys/dsl_dataset.h>
37 #include <sys/dsl_dir.h>
38 #include <sys/dmu_tx.h>
39 #include <sys/spa.h>
40 #include <sys/zio.h>
41 #include <sys/dmu_zfetch.h>
42 #include <sys/sa.h>
43 #include <sys/sa_impl.h>
44 #include <sys/zfeature.h>
45 #include <sys/blkptr.h>
46 #include <sys/range_tree.h>
47 #include <sys/trace_zfs.h>
48 #include <sys/callb.h>
49 #include <sys/abd.h>
50 #include <sys/vdev.h>
51 #include <sys/cityhash.h>
52 #include <sys/spa_impl.h>
53
54 kstat_t *dbuf_ksp;
55
56 typedef struct dbuf_stats {
57         /*
58          * Various statistics about the size of the dbuf cache.
59          */
60         kstat_named_t cache_count;
61         kstat_named_t cache_size_bytes;
62         kstat_named_t cache_size_bytes_max;
63         /*
64          * Statistics regarding the bounds on the dbuf cache size.
65          */
66         kstat_named_t cache_target_bytes;
67         kstat_named_t cache_lowater_bytes;
68         kstat_named_t cache_hiwater_bytes;
69         /*
70          * Total number of dbuf cache evictions that have occurred.
71          */
72         kstat_named_t cache_total_evicts;
73         /*
74          * The distribution of dbuf levels in the dbuf cache and
75          * the total size of all dbufs at each level.
76          */
77         kstat_named_t cache_levels[DN_MAX_LEVELS];
78         kstat_named_t cache_levels_bytes[DN_MAX_LEVELS];
79         /*
80          * Statistics about the dbuf hash table.
81          */
82         kstat_named_t hash_hits;
83         kstat_named_t hash_misses;
84         kstat_named_t hash_collisions;
85         kstat_named_t hash_elements;
86         kstat_named_t hash_elements_max;
87         /*
88          * Number of sublists containing more than one dbuf in the dbuf
89          * hash table. Keep track of the longest hash chain.
90          */
91         kstat_named_t hash_chains;
92         kstat_named_t hash_chain_max;
93         /*
94          * Number of times a dbuf_create() discovers that a dbuf was
95          * already created and in the dbuf hash table.
96          */
97         kstat_named_t hash_insert_race;
98         /*
99          * Statistics about the size of the metadata dbuf cache.
100          */
101         kstat_named_t metadata_cache_count;
102         kstat_named_t metadata_cache_size_bytes;
103         kstat_named_t metadata_cache_size_bytes_max;
104         /*
105          * For diagnostic purposes, this is incremented whenever we can't add
106          * something to the metadata cache because it's full, and instead put
107          * the data in the regular dbuf cache.
108          */
109         kstat_named_t metadata_cache_overflow;
110 } dbuf_stats_t;
111
112 dbuf_stats_t dbuf_stats = {
113         { "cache_count",                        KSTAT_DATA_UINT64 },
114         { "cache_size_bytes",                   KSTAT_DATA_UINT64 },
115         { "cache_size_bytes_max",               KSTAT_DATA_UINT64 },
116         { "cache_target_bytes",                 KSTAT_DATA_UINT64 },
117         { "cache_lowater_bytes",                KSTAT_DATA_UINT64 },
118         { "cache_hiwater_bytes",                KSTAT_DATA_UINT64 },
119         { "cache_total_evicts",                 KSTAT_DATA_UINT64 },
120         { { "cache_levels_N",                   KSTAT_DATA_UINT64 } },
121         { { "cache_levels_bytes_N",             KSTAT_DATA_UINT64 } },
122         { "hash_hits",                          KSTAT_DATA_UINT64 },
123         { "hash_misses",                        KSTAT_DATA_UINT64 },
124         { "hash_collisions",                    KSTAT_DATA_UINT64 },
125         { "hash_elements",                      KSTAT_DATA_UINT64 },
126         { "hash_elements_max",                  KSTAT_DATA_UINT64 },
127         { "hash_chains",                        KSTAT_DATA_UINT64 },
128         { "hash_chain_max",                     KSTAT_DATA_UINT64 },
129         { "hash_insert_race",                   KSTAT_DATA_UINT64 },
130         { "metadata_cache_count",               KSTAT_DATA_UINT64 },
131         { "metadata_cache_size_bytes",          KSTAT_DATA_UINT64 },
132         { "metadata_cache_size_bytes_max",      KSTAT_DATA_UINT64 },
133         { "metadata_cache_overflow",            KSTAT_DATA_UINT64 }
134 };
135
136 #define DBUF_STAT_INCR(stat, val)       \
137         atomic_add_64(&dbuf_stats.stat.value.ui64, (val));
138 #define DBUF_STAT_DECR(stat, val)       \
139         DBUF_STAT_INCR(stat, -(val));
140 #define DBUF_STAT_BUMP(stat)            \
141         DBUF_STAT_INCR(stat, 1);
142 #define DBUF_STAT_BUMPDOWN(stat)        \
143         DBUF_STAT_INCR(stat, -1);
144 #define DBUF_STAT_MAX(stat, v) {                                        \
145         uint64_t _m;                                                    \
146         while ((v) > (_m = dbuf_stats.stat.value.ui64) &&               \
147             (_m != atomic_cas_64(&dbuf_stats.stat.value.ui64, _m, (v))))\
148                 continue;                                               \
149 }
150
151 static boolean_t dbuf_undirty(dmu_buf_impl_t *db, dmu_tx_t *tx);
152 static void dbuf_write(dbuf_dirty_record_t *dr, arc_buf_t *data, dmu_tx_t *tx);
153
154 extern inline void dmu_buf_init_user(dmu_buf_user_t *dbu,
155     dmu_buf_evict_func_t *evict_func_sync,
156     dmu_buf_evict_func_t *evict_func_async,
157     dmu_buf_t **clear_on_evict_dbufp);
158
159 /*
160  * Global data structures and functions for the dbuf cache.
161  */
162 static kmem_cache_t *dbuf_kmem_cache;
163 static taskq_t *dbu_evict_taskq;
164
165 static kthread_t *dbuf_cache_evict_thread;
166 static kmutex_t dbuf_evict_lock;
167 static kcondvar_t dbuf_evict_cv;
168 static boolean_t dbuf_evict_thread_exit;
169
170 /*
171  * There are two dbuf caches; each dbuf can only be in one of them at a time.
172  *
173  * 1. Cache of metadata dbufs, to help make read-heavy administrative commands
174  *    from /sbin/zfs run faster. The "metadata cache" specifically stores dbufs
175  *    that represent the metadata that describes filesystems/snapshots/
176  *    bookmarks/properties/etc. We only evict from this cache when we export a
177  *    pool, to short-circuit as much I/O as possible for all administrative
178  *    commands that need the metadata. There is no eviction policy for this
179  *    cache, because we try to only include types in it which would occupy a
180  *    very small amount of space per object but create a large impact on the
181  *    performance of these commands. Instead, after it reaches a maximum size
182  *    (which should only happen on very small memory systems with a very large
183  *    number of filesystem objects), we stop taking new dbufs into the
184  *    metadata cache, instead putting them in the normal dbuf cache.
185  *
186  * 2. LRU cache of dbufs. The dbuf cache maintains a list of dbufs that
187  *    are not currently held but have been recently released. These dbufs
188  *    are not eligible for arc eviction until they are aged out of the cache.
189  *    Dbufs that are aged out of the cache will be immediately destroyed and
190  *    become eligible for arc eviction.
191  *
192  * Dbufs are added to these caches once the last hold is released. If a dbuf is
193  * later accessed and still exists in the dbuf cache, then it will be removed
194  * from the cache and later re-added to the head of the cache.
195  *
196  * If a given dbuf meets the requirements for the metadata cache, it will go
197  * there, otherwise it will be considered for the generic LRU dbuf cache. The
198  * caches and the refcounts tracking their sizes are stored in an array indexed
199  * by those caches' matching enum values (from dbuf_cached_state_t).
200  */
201 typedef struct dbuf_cache {
202         multilist_t *cache;
203         zfs_refcount_t size;
204 } dbuf_cache_t;
205 dbuf_cache_t dbuf_caches[DB_CACHE_MAX];
206
207 /* Size limits for the caches */
208 unsigned long dbuf_cache_max_bytes = 0;
209 unsigned long dbuf_metadata_cache_max_bytes = 0;
210 /* Set the default sizes of the caches to log2 fraction of arc size */
211 int dbuf_cache_shift = 5;
212 int dbuf_metadata_cache_shift = 6;
213
214 /*
215  * The LRU dbuf cache uses a three-stage eviction policy:
216  *      - A low water marker designates when the dbuf eviction thread
217  *      should stop evicting from the dbuf cache.
218  *      - When we reach the maximum size (aka mid water mark), we
219  *      signal the eviction thread to run.
220  *      - The high water mark indicates when the eviction thread
221  *      is unable to keep up with the incoming load and eviction must
222  *      happen in the context of the calling thread.
223  *
224  * The dbuf cache:
225  *                                                 (max size)
226  *                                      low water   mid water   hi water
227  * +----------------------------------------+----------+----------+
228  * |                                        |          |          |
229  * |                                        |          |          |
230  * |                                        |          |          |
231  * |                                        |          |          |
232  * +----------------------------------------+----------+----------+
233  *                                        stop        signal     evict
234  *                                      evicting     eviction   directly
235  *                                                    thread
236  *
237  * The high and low water marks indicate the operating range for the eviction
238  * thread. The low water mark is, by default, 90% of the total size of the
239  * cache and the high water mark is at 110% (both of these percentages can be
240  * changed by setting dbuf_cache_lowater_pct and dbuf_cache_hiwater_pct,
241  * respectively). The eviction thread will try to ensure that the cache remains
242  * within this range by waking up every second and checking if the cache is
243  * above the low water mark. The thread can also be woken up by callers adding
244  * elements into the cache if the cache is larger than the mid water (i.e max
245  * cache size). Once the eviction thread is woken up and eviction is required,
246  * it will continue evicting buffers until it's able to reduce the cache size
247  * to the low water mark. If the cache size continues to grow and hits the high
248  * water mark, then callers adding elements to the cache will begin to evict
249  * directly from the cache until the cache is no longer above the high water
250  * mark.
251  */
252
253 /*
254  * The percentage above and below the maximum cache size.
255  */
256 uint_t dbuf_cache_hiwater_pct = 10;
257 uint_t dbuf_cache_lowater_pct = 10;
258
259 /* ARGSUSED */
260 static int
261 dbuf_cons(void *vdb, void *unused, int kmflag)
262 {
263         dmu_buf_impl_t *db = vdb;
264         bzero(db, sizeof (dmu_buf_impl_t));
265
266         mutex_init(&db->db_mtx, NULL, MUTEX_DEFAULT, NULL);
267         rw_init(&db->db_rwlock, NULL, RW_DEFAULT, NULL);
268         cv_init(&db->db_changed, NULL, CV_DEFAULT, NULL);
269         multilist_link_init(&db->db_cache_link);
270         zfs_refcount_create(&db->db_holds);
271
272         return (0);
273 }
274
275 /* ARGSUSED */
276 static void
277 dbuf_dest(void *vdb, void *unused)
278 {
279         dmu_buf_impl_t *db = vdb;
280         mutex_destroy(&db->db_mtx);
281         rw_destroy(&db->db_rwlock);
282         cv_destroy(&db->db_changed);
283         ASSERT(!multilist_link_active(&db->db_cache_link));
284         zfs_refcount_destroy(&db->db_holds);
285 }
286
287 /*
288  * dbuf hash table routines
289  */
290 static dbuf_hash_table_t dbuf_hash_table;
291
292 static uint64_t dbuf_hash_count;
293
294 /*
295  * We use Cityhash for this. It's fast, and has good hash properties without
296  * requiring any large static buffers.
297  */
298 static uint64_t
299 dbuf_hash(void *os, uint64_t obj, uint8_t lvl, uint64_t blkid)
300 {
301         return (cityhash4((uintptr_t)os, obj, (uint64_t)lvl, blkid));
302 }
303
304 #define DBUF_EQUAL(dbuf, os, obj, level, blkid)         \
305         ((dbuf)->db.db_object == (obj) &&               \
306         (dbuf)->db_objset == (os) &&                    \
307         (dbuf)->db_level == (level) &&                  \
308         (dbuf)->db_blkid == (blkid))
309
310 dmu_buf_impl_t *
311 dbuf_find(objset_t *os, uint64_t obj, uint8_t level, uint64_t blkid)
312 {
313         dbuf_hash_table_t *h = &dbuf_hash_table;
314         uint64_t hv;
315         uint64_t idx;
316         dmu_buf_impl_t *db;
317
318         hv = dbuf_hash(os, obj, level, blkid);
319         idx = hv & h->hash_table_mask;
320
321         mutex_enter(DBUF_HASH_MUTEX(h, idx));
322         for (db = h->hash_table[idx]; db != NULL; db = db->db_hash_next) {
323                 if (DBUF_EQUAL(db, os, obj, level, blkid)) {
324                         mutex_enter(&db->db_mtx);
325                         if (db->db_state != DB_EVICTING) {
326                                 mutex_exit(DBUF_HASH_MUTEX(h, idx));
327                                 return (db);
328                         }
329                         mutex_exit(&db->db_mtx);
330                 }
331         }
332         mutex_exit(DBUF_HASH_MUTEX(h, idx));
333         return (NULL);
334 }
335
336 static dmu_buf_impl_t *
337 dbuf_find_bonus(objset_t *os, uint64_t object)
338 {
339         dnode_t *dn;
340         dmu_buf_impl_t *db = NULL;
341
342         if (dnode_hold(os, object, FTAG, &dn) == 0) {
343                 rw_enter(&dn->dn_struct_rwlock, RW_READER);
344                 if (dn->dn_bonus != NULL) {
345                         db = dn->dn_bonus;
346                         mutex_enter(&db->db_mtx);
347                 }
348                 rw_exit(&dn->dn_struct_rwlock);
349                 dnode_rele(dn, FTAG);
350         }
351         return (db);
352 }
353
354 /*
355  * Insert an entry into the hash table.  If there is already an element
356  * equal to elem in the hash table, then the already existing element
357  * will be returned and the new element will not be inserted.
358  * Otherwise returns NULL.
359  */
360 static dmu_buf_impl_t *
361 dbuf_hash_insert(dmu_buf_impl_t *db)
362 {
363         dbuf_hash_table_t *h = &dbuf_hash_table;
364         objset_t *os = db->db_objset;
365         uint64_t obj = db->db.db_object;
366         int level = db->db_level;
367         uint64_t blkid, hv, idx;
368         dmu_buf_impl_t *dbf;
369         uint32_t i;
370
371         blkid = db->db_blkid;
372         hv = dbuf_hash(os, obj, level, blkid);
373         idx = hv & h->hash_table_mask;
374
375         mutex_enter(DBUF_HASH_MUTEX(h, idx));
376         for (dbf = h->hash_table[idx], i = 0; dbf != NULL;
377             dbf = dbf->db_hash_next, i++) {
378                 if (DBUF_EQUAL(dbf, os, obj, level, blkid)) {
379                         mutex_enter(&dbf->db_mtx);
380                         if (dbf->db_state != DB_EVICTING) {
381                                 mutex_exit(DBUF_HASH_MUTEX(h, idx));
382                                 return (dbf);
383                         }
384                         mutex_exit(&dbf->db_mtx);
385                 }
386         }
387
388         if (i > 0) {
389                 DBUF_STAT_BUMP(hash_collisions);
390                 if (i == 1)
391                         DBUF_STAT_BUMP(hash_chains);
392
393                 DBUF_STAT_MAX(hash_chain_max, i);
394         }
395
396         mutex_enter(&db->db_mtx);
397         db->db_hash_next = h->hash_table[idx];
398         h->hash_table[idx] = db;
399         mutex_exit(DBUF_HASH_MUTEX(h, idx));
400         atomic_inc_64(&dbuf_hash_count);
401         DBUF_STAT_MAX(hash_elements_max, dbuf_hash_count);
402
403         return (NULL);
404 }
405
406 /*
407  * This returns whether this dbuf should be stored in the metadata cache, which
408  * is based on whether it's from one of the dnode types that store data related
409  * to traversing dataset hierarchies.
410  */
411 static boolean_t
412 dbuf_include_in_metadata_cache(dmu_buf_impl_t *db)
413 {
414         DB_DNODE_ENTER(db);
415         dmu_object_type_t type = DB_DNODE(db)->dn_type;
416         DB_DNODE_EXIT(db);
417
418         /* Check if this dbuf is one of the types we care about */
419         if (DMU_OT_IS_METADATA_CACHED(type)) {
420                 /* If we hit this, then we set something up wrong in dmu_ot */
421                 ASSERT(DMU_OT_IS_METADATA(type));
422
423                 /*
424                  * Sanity check for small-memory systems: don't allocate too
425                  * much memory for this purpose.
426                  */
427                 if (zfs_refcount_count(
428                     &dbuf_caches[DB_DBUF_METADATA_CACHE].size) >
429                     dbuf_metadata_cache_max_bytes) {
430                         DBUF_STAT_BUMP(metadata_cache_overflow);
431                         return (B_FALSE);
432                 }
433
434                 return (B_TRUE);
435         }
436
437         return (B_FALSE);
438 }
439
440 /*
441  * Remove an entry from the hash table.  It must be in the EVICTING state.
442  */
443 static void
444 dbuf_hash_remove(dmu_buf_impl_t *db)
445 {
446         dbuf_hash_table_t *h = &dbuf_hash_table;
447         uint64_t hv, idx;
448         dmu_buf_impl_t *dbf, **dbp;
449
450         hv = dbuf_hash(db->db_objset, db->db.db_object,
451             db->db_level, db->db_blkid);
452         idx = hv & h->hash_table_mask;
453
454         /*
455          * We mustn't hold db_mtx to maintain lock ordering:
456          * DBUF_HASH_MUTEX > db_mtx.
457          */
458         ASSERT(zfs_refcount_is_zero(&db->db_holds));
459         ASSERT(db->db_state == DB_EVICTING);
460         ASSERT(!MUTEX_HELD(&db->db_mtx));
461
462         mutex_enter(DBUF_HASH_MUTEX(h, idx));
463         dbp = &h->hash_table[idx];
464         while ((dbf = *dbp) != db) {
465                 dbp = &dbf->db_hash_next;
466                 ASSERT(dbf != NULL);
467         }
468         *dbp = db->db_hash_next;
469         db->db_hash_next = NULL;
470         if (h->hash_table[idx] &&
471             h->hash_table[idx]->db_hash_next == NULL)
472                 DBUF_STAT_BUMPDOWN(hash_chains);
473         mutex_exit(DBUF_HASH_MUTEX(h, idx));
474         atomic_dec_64(&dbuf_hash_count);
475 }
476
477 typedef enum {
478         DBVU_EVICTING,
479         DBVU_NOT_EVICTING
480 } dbvu_verify_type_t;
481
482 static void
483 dbuf_verify_user(dmu_buf_impl_t *db, dbvu_verify_type_t verify_type)
484 {
485 #ifdef ZFS_DEBUG
486         int64_t holds;
487
488         if (db->db_user == NULL)
489                 return;
490
491         /* Only data blocks support the attachment of user data. */
492         ASSERT(db->db_level == 0);
493
494         /* Clients must resolve a dbuf before attaching user data. */
495         ASSERT(db->db.db_data != NULL);
496         ASSERT3U(db->db_state, ==, DB_CACHED);
497
498         holds = zfs_refcount_count(&db->db_holds);
499         if (verify_type == DBVU_EVICTING) {
500                 /*
501                  * Immediate eviction occurs when holds == dirtycnt.
502                  * For normal eviction buffers, holds is zero on
503                  * eviction, except when dbuf_fix_old_data() calls
504                  * dbuf_clear_data().  However, the hold count can grow
505                  * during eviction even though db_mtx is held (see
506                  * dmu_bonus_hold() for an example), so we can only
507                  * test the generic invariant that holds >= dirtycnt.
508                  */
509                 ASSERT3U(holds, >=, db->db_dirtycnt);
510         } else {
511                 if (db->db_user_immediate_evict == TRUE)
512                         ASSERT3U(holds, >=, db->db_dirtycnt);
513                 else
514                         ASSERT3U(holds, >, 0);
515         }
516 #endif
517 }
518
519 static void
520 dbuf_evict_user(dmu_buf_impl_t *db)
521 {
522         dmu_buf_user_t *dbu = db->db_user;
523
524         ASSERT(MUTEX_HELD(&db->db_mtx));
525
526         if (dbu == NULL)
527                 return;
528
529         dbuf_verify_user(db, DBVU_EVICTING);
530         db->db_user = NULL;
531
532 #ifdef ZFS_DEBUG
533         if (dbu->dbu_clear_on_evict_dbufp != NULL)
534                 *dbu->dbu_clear_on_evict_dbufp = NULL;
535 #endif
536
537         /*
538          * There are two eviction callbacks - one that we call synchronously
539          * and one that we invoke via a taskq.  The async one is useful for
540          * avoiding lock order reversals and limiting stack depth.
541          *
542          * Note that if we have a sync callback but no async callback,
543          * it's likely that the sync callback will free the structure
544          * containing the dbu.  In that case we need to take care to not
545          * dereference dbu after calling the sync evict func.
546          */
547         boolean_t has_async = (dbu->dbu_evict_func_async != NULL);
548
549         if (dbu->dbu_evict_func_sync != NULL)
550                 dbu->dbu_evict_func_sync(dbu);
551
552         if (has_async) {
553                 taskq_dispatch_ent(dbu_evict_taskq, dbu->dbu_evict_func_async,
554                     dbu, 0, &dbu->dbu_tqent);
555         }
556 }
557
558 boolean_t
559 dbuf_is_metadata(dmu_buf_impl_t *db)
560 {
561         /*
562          * Consider indirect blocks and spill blocks to be meta data.
563          */
564         if (db->db_level > 0 || db->db_blkid == DMU_SPILL_BLKID) {
565                 return (B_TRUE);
566         } else {
567                 boolean_t is_metadata;
568
569                 DB_DNODE_ENTER(db);
570                 is_metadata = DMU_OT_IS_METADATA(DB_DNODE(db)->dn_type);
571                 DB_DNODE_EXIT(db);
572
573                 return (is_metadata);
574         }
575 }
576
577
578 /*
579  * This function *must* return indices evenly distributed between all
580  * sublists of the multilist. This is needed due to how the dbuf eviction
581  * code is laid out; dbuf_evict_thread() assumes dbufs are evenly
582  * distributed between all sublists and uses this assumption when
583  * deciding which sublist to evict from and how much to evict from it.
584  */
585 unsigned int
586 dbuf_cache_multilist_index_func(multilist_t *ml, void *obj)
587 {
588         dmu_buf_impl_t *db = obj;
589
590         /*
591          * The assumption here, is the hash value for a given
592          * dmu_buf_impl_t will remain constant throughout it's lifetime
593          * (i.e. it's objset, object, level and blkid fields don't change).
594          * Thus, we don't need to store the dbuf's sublist index
595          * on insertion, as this index can be recalculated on removal.
596          *
597          * Also, the low order bits of the hash value are thought to be
598          * distributed evenly. Otherwise, in the case that the multilist
599          * has a power of two number of sublists, each sublists' usage
600          * would not be evenly distributed.
601          */
602         return (dbuf_hash(db->db_objset, db->db.db_object,
603             db->db_level, db->db_blkid) %
604             multilist_get_num_sublists(ml));
605 }
606
607 static inline unsigned long
608 dbuf_cache_target_bytes(void)
609 {
610         return MIN(dbuf_cache_max_bytes,
611             arc_target_bytes() >> dbuf_cache_shift);
612 }
613
614 static inline uint64_t
615 dbuf_cache_hiwater_bytes(void)
616 {
617         uint64_t dbuf_cache_target = dbuf_cache_target_bytes();
618         return (dbuf_cache_target +
619             (dbuf_cache_target * dbuf_cache_hiwater_pct) / 100);
620 }
621
622 static inline uint64_t
623 dbuf_cache_lowater_bytes(void)
624 {
625         uint64_t dbuf_cache_target = dbuf_cache_target_bytes();
626         return (dbuf_cache_target -
627             (dbuf_cache_target * dbuf_cache_lowater_pct) / 100);
628 }
629
630 static inline boolean_t
631 dbuf_cache_above_hiwater(void)
632 {
633         return (zfs_refcount_count(&dbuf_caches[DB_DBUF_CACHE].size) >
634             dbuf_cache_hiwater_bytes());
635 }
636
637 static inline boolean_t
638 dbuf_cache_above_lowater(void)
639 {
640         return (zfs_refcount_count(&dbuf_caches[DB_DBUF_CACHE].size) >
641             dbuf_cache_lowater_bytes());
642 }
643
644 /*
645  * Evict the oldest eligible dbuf from the dbuf cache.
646  */
647 static void
648 dbuf_evict_one(void)
649 {
650         int idx = multilist_get_random_index(dbuf_caches[DB_DBUF_CACHE].cache);
651         multilist_sublist_t *mls = multilist_sublist_lock(
652             dbuf_caches[DB_DBUF_CACHE].cache, idx);
653
654         ASSERT(!MUTEX_HELD(&dbuf_evict_lock));
655
656         dmu_buf_impl_t *db = multilist_sublist_tail(mls);
657         while (db != NULL && mutex_tryenter(&db->db_mtx) == 0) {
658                 db = multilist_sublist_prev(mls, db);
659         }
660
661         DTRACE_PROBE2(dbuf__evict__one, dmu_buf_impl_t *, db,
662             multilist_sublist_t *, mls);
663
664         if (db != NULL) {
665                 multilist_sublist_remove(mls, db);
666                 multilist_sublist_unlock(mls);
667                 (void) zfs_refcount_remove_many(
668                     &dbuf_caches[DB_DBUF_CACHE].size, db->db.db_size, db);
669                 DBUF_STAT_BUMPDOWN(cache_levels[db->db_level]);
670                 DBUF_STAT_BUMPDOWN(cache_count);
671                 DBUF_STAT_DECR(cache_levels_bytes[db->db_level],
672                     db->db.db_size);
673                 ASSERT3U(db->db_caching_status, ==, DB_DBUF_CACHE);
674                 db->db_caching_status = DB_NO_CACHE;
675                 dbuf_destroy(db);
676                 DBUF_STAT_MAX(cache_size_bytes_max,
677                     zfs_refcount_count(&dbuf_caches[DB_DBUF_CACHE].size));
678                 DBUF_STAT_BUMP(cache_total_evicts);
679         } else {
680                 multilist_sublist_unlock(mls);
681         }
682 }
683
684 /*
685  * The dbuf evict thread is responsible for aging out dbufs from the
686  * cache. Once the cache has reached it's maximum size, dbufs are removed
687  * and destroyed. The eviction thread will continue running until the size
688  * of the dbuf cache is at or below the maximum size. Once the dbuf is aged
689  * out of the cache it is destroyed and becomes eligible for arc eviction.
690  */
691 /* ARGSUSED */
692 static void
693 dbuf_evict_thread(void *unused)
694 {
695         callb_cpr_t cpr;
696
697         CALLB_CPR_INIT(&cpr, &dbuf_evict_lock, callb_generic_cpr, FTAG);
698
699         mutex_enter(&dbuf_evict_lock);
700         while (!dbuf_evict_thread_exit) {
701                 while (!dbuf_cache_above_lowater() && !dbuf_evict_thread_exit) {
702                         CALLB_CPR_SAFE_BEGIN(&cpr);
703                         (void) cv_timedwait_sig_hires(&dbuf_evict_cv,
704                             &dbuf_evict_lock, SEC2NSEC(1), MSEC2NSEC(1), 0);
705                         CALLB_CPR_SAFE_END(&cpr, &dbuf_evict_lock);
706                 }
707                 mutex_exit(&dbuf_evict_lock);
708
709                 /*
710                  * Keep evicting as long as we're above the low water mark
711                  * for the cache. We do this without holding the locks to
712                  * minimize lock contention.
713                  */
714                 while (dbuf_cache_above_lowater() && !dbuf_evict_thread_exit) {
715                         dbuf_evict_one();
716                 }
717
718                 mutex_enter(&dbuf_evict_lock);
719         }
720
721         dbuf_evict_thread_exit = B_FALSE;
722         cv_broadcast(&dbuf_evict_cv);
723         CALLB_CPR_EXIT(&cpr);   /* drops dbuf_evict_lock */
724         thread_exit();
725 }
726
727 /*
728  * Wake up the dbuf eviction thread if the dbuf cache is at its max size.
729  * If the dbuf cache is at its high water mark, then evict a dbuf from the
730  * dbuf cache using the callers context.
731  */
732 static void
733 dbuf_evict_notify(void)
734 {
735         /*
736          * We check if we should evict without holding the dbuf_evict_lock,
737          * because it's OK to occasionally make the wrong decision here,
738          * and grabbing the lock results in massive lock contention.
739          */
740         if (zfs_refcount_count(&dbuf_caches[DB_DBUF_CACHE].size) >
741             dbuf_cache_target_bytes()) {
742                 if (dbuf_cache_above_hiwater())
743                         dbuf_evict_one();
744                 cv_signal(&dbuf_evict_cv);
745         }
746 }
747
748 static int
749 dbuf_kstat_update(kstat_t *ksp, int rw)
750 {
751         dbuf_stats_t *ds = ksp->ks_data;
752
753         if (rw == KSTAT_WRITE) {
754                 return (SET_ERROR(EACCES));
755         } else {
756                 ds->metadata_cache_size_bytes.value.ui64 = zfs_refcount_count(
757                     &dbuf_caches[DB_DBUF_METADATA_CACHE].size);
758                 ds->cache_size_bytes.value.ui64 =
759                     zfs_refcount_count(&dbuf_caches[DB_DBUF_CACHE].size);
760                 ds->cache_target_bytes.value.ui64 = dbuf_cache_target_bytes();
761                 ds->cache_hiwater_bytes.value.ui64 = dbuf_cache_hiwater_bytes();
762                 ds->cache_lowater_bytes.value.ui64 = dbuf_cache_lowater_bytes();
763                 ds->hash_elements.value.ui64 = dbuf_hash_count;
764         }
765
766         return (0);
767 }
768
769 void
770 dbuf_init(void)
771 {
772         uint64_t hsize = 1ULL << 16;
773         dbuf_hash_table_t *h = &dbuf_hash_table;
774         int i;
775
776         /*
777          * The hash table is big enough to fill all of physical memory
778          * with an average block size of zfs_arc_average_blocksize (default 8K).
779          * By default, the table will take up
780          * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
781          */
782         while (hsize * zfs_arc_average_blocksize < physmem * PAGESIZE)
783                 hsize <<= 1;
784
785 retry:
786         h->hash_table_mask = hsize - 1;
787 #if defined(_KERNEL)
788         /*
789          * Large allocations which do not require contiguous pages
790          * should be using vmem_alloc() in the linux kernel
791          */
792         h->hash_table = vmem_zalloc(hsize * sizeof (void *), KM_SLEEP);
793 #else
794         h->hash_table = kmem_zalloc(hsize * sizeof (void *), KM_NOSLEEP);
795 #endif
796         if (h->hash_table == NULL) {
797                 /* XXX - we should really return an error instead of assert */
798                 ASSERT(hsize > (1ULL << 10));
799                 hsize >>= 1;
800                 goto retry;
801         }
802
803         dbuf_kmem_cache = kmem_cache_create("dmu_buf_impl_t",
804             sizeof (dmu_buf_impl_t),
805             0, dbuf_cons, dbuf_dest, NULL, NULL, NULL, 0);
806
807         for (i = 0; i < DBUF_MUTEXES; i++)
808                 mutex_init(&h->hash_mutexes[i], NULL, MUTEX_DEFAULT, NULL);
809
810         dbuf_stats_init(h);
811
812         /*
813          * Setup the parameters for the dbuf caches. We set the sizes of the
814          * dbuf cache and the metadata cache to 1/32nd and 1/16th (default)
815          * of the target size of the ARC. If the values has been specified as
816          * a module option and they're not greater than the target size of the
817          * ARC, then we honor that value.
818          */
819         if (dbuf_cache_max_bytes == 0 ||
820             dbuf_cache_max_bytes >= arc_target_bytes()) {
821                 dbuf_cache_max_bytes = arc_target_bytes() >> dbuf_cache_shift;
822         }
823         if (dbuf_metadata_cache_max_bytes == 0 ||
824             dbuf_metadata_cache_max_bytes >= arc_target_bytes()) {
825                 dbuf_metadata_cache_max_bytes =
826                     arc_target_bytes() >> dbuf_metadata_cache_shift;
827         }
828
829         /*
830          * All entries are queued via taskq_dispatch_ent(), so min/maxalloc
831          * configuration is not required.
832          */
833         dbu_evict_taskq = taskq_create("dbu_evict", 1, defclsyspri, 0, 0, 0);
834
835         for (dbuf_cached_state_t dcs = 0; dcs < DB_CACHE_MAX; dcs++) {
836                 dbuf_caches[dcs].cache =
837                     multilist_create(sizeof (dmu_buf_impl_t),
838                     offsetof(dmu_buf_impl_t, db_cache_link),
839                     dbuf_cache_multilist_index_func);
840                 zfs_refcount_create(&dbuf_caches[dcs].size);
841         }
842
843         dbuf_evict_thread_exit = B_FALSE;
844         mutex_init(&dbuf_evict_lock, NULL, MUTEX_DEFAULT, NULL);
845         cv_init(&dbuf_evict_cv, NULL, CV_DEFAULT, NULL);
846         dbuf_cache_evict_thread = thread_create(NULL, 0, dbuf_evict_thread,
847             NULL, 0, &p0, TS_RUN, minclsyspri);
848
849         dbuf_ksp = kstat_create("zfs", 0, "dbufstats", "misc",
850             KSTAT_TYPE_NAMED, sizeof (dbuf_stats) / sizeof (kstat_named_t),
851             KSTAT_FLAG_VIRTUAL);
852         if (dbuf_ksp != NULL) {
853                 for (i = 0; i < DN_MAX_LEVELS; i++) {
854                         snprintf(dbuf_stats.cache_levels[i].name,
855                             KSTAT_STRLEN, "cache_level_%d", i);
856                         dbuf_stats.cache_levels[i].data_type =
857                             KSTAT_DATA_UINT64;
858                         snprintf(dbuf_stats.cache_levels_bytes[i].name,
859                             KSTAT_STRLEN, "cache_level_%d_bytes", i);
860                         dbuf_stats.cache_levels_bytes[i].data_type =
861                             KSTAT_DATA_UINT64;
862                 }
863                 dbuf_ksp->ks_data = &dbuf_stats;
864                 dbuf_ksp->ks_update = dbuf_kstat_update;
865                 kstat_install(dbuf_ksp);
866         }
867 }
868
869 void
870 dbuf_fini(void)
871 {
872         dbuf_hash_table_t *h = &dbuf_hash_table;
873         int i;
874
875         dbuf_stats_destroy();
876
877         for (i = 0; i < DBUF_MUTEXES; i++)
878                 mutex_destroy(&h->hash_mutexes[i]);
879 #if defined(_KERNEL)
880         /*
881          * Large allocations which do not require contiguous pages
882          * should be using vmem_free() in the linux kernel
883          */
884         vmem_free(h->hash_table, (h->hash_table_mask + 1) * sizeof (void *));
885 #else
886         kmem_free(h->hash_table, (h->hash_table_mask + 1) * sizeof (void *));
887 #endif
888         kmem_cache_destroy(dbuf_kmem_cache);
889         taskq_destroy(dbu_evict_taskq);
890
891         mutex_enter(&dbuf_evict_lock);
892         dbuf_evict_thread_exit = B_TRUE;
893         while (dbuf_evict_thread_exit) {
894                 cv_signal(&dbuf_evict_cv);
895                 cv_wait(&dbuf_evict_cv, &dbuf_evict_lock);
896         }
897         mutex_exit(&dbuf_evict_lock);
898
899         mutex_destroy(&dbuf_evict_lock);
900         cv_destroy(&dbuf_evict_cv);
901
902         for (dbuf_cached_state_t dcs = 0; dcs < DB_CACHE_MAX; dcs++) {
903                 zfs_refcount_destroy(&dbuf_caches[dcs].size);
904                 multilist_destroy(dbuf_caches[dcs].cache);
905         }
906
907         if (dbuf_ksp != NULL) {
908                 kstat_delete(dbuf_ksp);
909                 dbuf_ksp = NULL;
910         }
911 }
912
913 /*
914  * Other stuff.
915  */
916
917 #ifdef ZFS_DEBUG
918 static void
919 dbuf_verify(dmu_buf_impl_t *db)
920 {
921         dnode_t *dn;
922         dbuf_dirty_record_t *dr;
923
924         ASSERT(MUTEX_HELD(&db->db_mtx));
925
926         if (!(zfs_flags & ZFS_DEBUG_DBUF_VERIFY))
927                 return;
928
929         ASSERT(db->db_objset != NULL);
930         DB_DNODE_ENTER(db);
931         dn = DB_DNODE(db);
932         if (dn == NULL) {
933                 ASSERT(db->db_parent == NULL);
934                 ASSERT(db->db_blkptr == NULL);
935         } else {
936                 ASSERT3U(db->db.db_object, ==, dn->dn_object);
937                 ASSERT3P(db->db_objset, ==, dn->dn_objset);
938                 ASSERT3U(db->db_level, <, dn->dn_nlevels);
939                 ASSERT(db->db_blkid == DMU_BONUS_BLKID ||
940                     db->db_blkid == DMU_SPILL_BLKID ||
941                     !avl_is_empty(&dn->dn_dbufs));
942         }
943         if (db->db_blkid == DMU_BONUS_BLKID) {
944                 ASSERT(dn != NULL);
945                 ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
946                 ASSERT3U(db->db.db_offset, ==, DMU_BONUS_BLKID);
947         } else if (db->db_blkid == DMU_SPILL_BLKID) {
948                 ASSERT(dn != NULL);
949                 ASSERT0(db->db.db_offset);
950         } else {
951                 ASSERT3U(db->db.db_offset, ==, db->db_blkid * db->db.db_size);
952         }
953
954         for (dr = db->db_data_pending; dr != NULL; dr = dr->dr_next)
955                 ASSERT(dr->dr_dbuf == db);
956
957         for (dr = db->db_last_dirty; dr != NULL; dr = dr->dr_next)
958                 ASSERT(dr->dr_dbuf == db);
959
960         /*
961          * We can't assert that db_size matches dn_datablksz because it
962          * can be momentarily different when another thread is doing
963          * dnode_set_blksz().
964          */
965         if (db->db_level == 0 && db->db.db_object == DMU_META_DNODE_OBJECT) {
966                 dr = db->db_data_pending;
967                 /*
968                  * It should only be modified in syncing context, so
969                  * make sure we only have one copy of the data.
970                  */
971                 ASSERT(dr == NULL || dr->dt.dl.dr_data == db->db_buf);
972         }
973
974         /* verify db->db_blkptr */
975         if (db->db_blkptr) {
976                 if (db->db_parent == dn->dn_dbuf) {
977                         /* db is pointed to by the dnode */
978                         /* ASSERT3U(db->db_blkid, <, dn->dn_nblkptr); */
979                         if (DMU_OBJECT_IS_SPECIAL(db->db.db_object))
980                                 ASSERT(db->db_parent == NULL);
981                         else
982                                 ASSERT(db->db_parent != NULL);
983                         if (db->db_blkid != DMU_SPILL_BLKID)
984                                 ASSERT3P(db->db_blkptr, ==,
985                                     &dn->dn_phys->dn_blkptr[db->db_blkid]);
986                 } else {
987                         /* db is pointed to by an indirect block */
988                         int epb __maybe_unused = db->db_parent->db.db_size >>
989                             SPA_BLKPTRSHIFT;
990                         ASSERT3U(db->db_parent->db_level, ==, db->db_level+1);
991                         ASSERT3U(db->db_parent->db.db_object, ==,
992                             db->db.db_object);
993                         /*
994                          * dnode_grow_indblksz() can make this fail if we don't
995                          * have the parent's rwlock.  XXX indblksz no longer
996                          * grows.  safe to do this now?
997                          */
998                         if (RW_LOCK_HELD(&db->db_parent->db_rwlock)) {
999                                 ASSERT3P(db->db_blkptr, ==,
1000                                     ((blkptr_t *)db->db_parent->db.db_data +
1001                                     db->db_blkid % epb));
1002                         }
1003                 }
1004         }
1005         if ((db->db_blkptr == NULL || BP_IS_HOLE(db->db_blkptr)) &&
1006             (db->db_buf == NULL || db->db_buf->b_data) &&
1007             db->db.db_data && db->db_blkid != DMU_BONUS_BLKID &&
1008             db->db_state != DB_FILL && !dn->dn_free_txg) {
1009                 /*
1010                  * If the blkptr isn't set but they have nonzero data,
1011                  * it had better be dirty, otherwise we'll lose that
1012                  * data when we evict this buffer.
1013                  *
1014                  * There is an exception to this rule for indirect blocks; in
1015                  * this case, if the indirect block is a hole, we fill in a few
1016                  * fields on each of the child blocks (importantly, birth time)
1017                  * to prevent hole birth times from being lost when you
1018                  * partially fill in a hole.
1019                  */
1020                 if (db->db_dirtycnt == 0) {
1021                         if (db->db_level == 0) {
1022                                 uint64_t *buf = db->db.db_data;
1023                                 int i;
1024
1025                                 for (i = 0; i < db->db.db_size >> 3; i++) {
1026                                         ASSERT(buf[i] == 0);
1027                                 }
1028                         } else {
1029                                 blkptr_t *bps = db->db.db_data;
1030                                 ASSERT3U(1 << DB_DNODE(db)->dn_indblkshift, ==,
1031                                     db->db.db_size);
1032                                 /*
1033                                  * We want to verify that all the blkptrs in the
1034                                  * indirect block are holes, but we may have
1035                                  * automatically set up a few fields for them.
1036                                  * We iterate through each blkptr and verify
1037                                  * they only have those fields set.
1038                                  */
1039                                 for (int i = 0;
1040                                     i < db->db.db_size / sizeof (blkptr_t);
1041                                     i++) {
1042                                         blkptr_t *bp = &bps[i];
1043                                         ASSERT(ZIO_CHECKSUM_IS_ZERO(
1044                                             &bp->blk_cksum));
1045                                         ASSERT(
1046                                             DVA_IS_EMPTY(&bp->blk_dva[0]) &&
1047                                             DVA_IS_EMPTY(&bp->blk_dva[1]) &&
1048                                             DVA_IS_EMPTY(&bp->blk_dva[2]));
1049                                         ASSERT0(bp->blk_fill);
1050                                         ASSERT0(bp->blk_pad[0]);
1051                                         ASSERT0(bp->blk_pad[1]);
1052                                         ASSERT(!BP_IS_EMBEDDED(bp));
1053                                         ASSERT(BP_IS_HOLE(bp));
1054                                         ASSERT0(bp->blk_phys_birth);
1055                                 }
1056                         }
1057                 }
1058         }
1059         DB_DNODE_EXIT(db);
1060 }
1061 #endif
1062
1063 static void
1064 dbuf_clear_data(dmu_buf_impl_t *db)
1065 {
1066         ASSERT(MUTEX_HELD(&db->db_mtx));
1067         dbuf_evict_user(db);
1068         ASSERT3P(db->db_buf, ==, NULL);
1069         db->db.db_data = NULL;
1070         if (db->db_state != DB_NOFILL)
1071                 db->db_state = DB_UNCACHED;
1072 }
1073
1074 static void
1075 dbuf_set_data(dmu_buf_impl_t *db, arc_buf_t *buf)
1076 {
1077         ASSERT(MUTEX_HELD(&db->db_mtx));
1078         ASSERT(buf != NULL);
1079
1080         db->db_buf = buf;
1081         ASSERT(buf->b_data != NULL);
1082         db->db.db_data = buf->b_data;
1083 }
1084
1085 /*
1086  * Loan out an arc_buf for read.  Return the loaned arc_buf.
1087  */
1088 arc_buf_t *
1089 dbuf_loan_arcbuf(dmu_buf_impl_t *db)
1090 {
1091         arc_buf_t *abuf;
1092
1093         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1094         mutex_enter(&db->db_mtx);
1095         if (arc_released(db->db_buf) || zfs_refcount_count(&db->db_holds) > 1) {
1096                 int blksz = db->db.db_size;
1097                 spa_t *spa = db->db_objset->os_spa;
1098
1099                 mutex_exit(&db->db_mtx);
1100                 abuf = arc_loan_buf(spa, B_FALSE, blksz);
1101                 bcopy(db->db.db_data, abuf->b_data, blksz);
1102         } else {
1103                 abuf = db->db_buf;
1104                 arc_loan_inuse_buf(abuf, db);
1105                 db->db_buf = NULL;
1106                 dbuf_clear_data(db);
1107                 mutex_exit(&db->db_mtx);
1108         }
1109         return (abuf);
1110 }
1111
1112 /*
1113  * Calculate which level n block references the data at the level 0 offset
1114  * provided.
1115  */
1116 uint64_t
1117 dbuf_whichblock(const dnode_t *dn, const int64_t level, const uint64_t offset)
1118 {
1119         if (dn->dn_datablkshift != 0 && dn->dn_indblkshift != 0) {
1120                 /*
1121                  * The level n blkid is equal to the level 0 blkid divided by
1122                  * the number of level 0s in a level n block.
1123                  *
1124                  * The level 0 blkid is offset >> datablkshift =
1125                  * offset / 2^datablkshift.
1126                  *
1127                  * The number of level 0s in a level n is the number of block
1128                  * pointers in an indirect block, raised to the power of level.
1129                  * This is 2^(indblkshift - SPA_BLKPTRSHIFT)^level =
1130                  * 2^(level*(indblkshift - SPA_BLKPTRSHIFT)).
1131                  *
1132                  * Thus, the level n blkid is: offset /
1133                  * ((2^datablkshift)*(2^(level*(indblkshift-SPA_BLKPTRSHIFT))))
1134                  * = offset / 2^(datablkshift + level *
1135                  *   (indblkshift - SPA_BLKPTRSHIFT))
1136                  * = offset >> (datablkshift + level *
1137                  *   (indblkshift - SPA_BLKPTRSHIFT))
1138                  */
1139
1140                 const unsigned exp = dn->dn_datablkshift +
1141                     level * (dn->dn_indblkshift - SPA_BLKPTRSHIFT);
1142
1143                 if (exp >= 8 * sizeof (offset)) {
1144                         /* This only happens on the highest indirection level */
1145                         ASSERT3U(level, ==, dn->dn_nlevels - 1);
1146                         return (0);
1147                 }
1148
1149                 ASSERT3U(exp, <, 8 * sizeof (offset));
1150
1151                 return (offset >> exp);
1152         } else {
1153                 ASSERT3U(offset, <, dn->dn_datablksz);
1154                 return (0);
1155         }
1156 }
1157
1158 /*
1159  * This function is used to lock the parent of the provided dbuf. This should be
1160  * used when modifying or reading db_blkptr.
1161  */
1162 db_lock_type_t
1163 dmu_buf_lock_parent(dmu_buf_impl_t *db, krw_t rw, void *tag)
1164 {
1165         enum db_lock_type ret = DLT_NONE;
1166         if (db->db_parent != NULL) {
1167                 rw_enter(&db->db_parent->db_rwlock, rw);
1168                 ret = DLT_PARENT;
1169         } else if (dmu_objset_ds(db->db_objset) != NULL) {
1170                 rrw_enter(&dmu_objset_ds(db->db_objset)->ds_bp_rwlock, rw,
1171                     tag);
1172                 ret = DLT_OBJSET;
1173         }
1174         /*
1175          * We only return a DLT_NONE lock when it's the top-most indirect block
1176          * of the meta-dnode of the MOS.
1177          */
1178         return (ret);
1179 }
1180
1181 /*
1182  * We need to pass the lock type in because it's possible that the block will
1183  * move from being the topmost indirect block in a dnode (and thus, have no
1184  * parent) to not the top-most via an indirection increase. This would cause a
1185  * panic if we didn't pass the lock type in.
1186  */
1187 void
1188 dmu_buf_unlock_parent(dmu_buf_impl_t *db, db_lock_type_t type, void *tag)
1189 {
1190         if (type == DLT_PARENT)
1191                 rw_exit(&db->db_parent->db_rwlock);
1192         else if (type == DLT_OBJSET)
1193                 rrw_exit(&dmu_objset_ds(db->db_objset)->ds_bp_rwlock, tag);
1194 }
1195
1196 static void
1197 dbuf_read_done(zio_t *zio, const zbookmark_phys_t *zb, const blkptr_t *bp,
1198     arc_buf_t *buf, void *vdb)
1199 {
1200         dmu_buf_impl_t *db = vdb;
1201
1202         mutex_enter(&db->db_mtx);
1203         ASSERT3U(db->db_state, ==, DB_READ);
1204         /*
1205          * All reads are synchronous, so we must have a hold on the dbuf
1206          */
1207         ASSERT(zfs_refcount_count(&db->db_holds) > 0);
1208         ASSERT(db->db_buf == NULL);
1209         ASSERT(db->db.db_data == NULL);
1210         if (buf == NULL) {
1211                 /* i/o error */
1212                 ASSERT(zio == NULL || zio->io_error != 0);
1213                 ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1214                 ASSERT3P(db->db_buf, ==, NULL);
1215                 db->db_state = DB_UNCACHED;
1216         } else if (db->db_level == 0 && db->db_freed_in_flight) {
1217                 /* freed in flight */
1218                 ASSERT(zio == NULL || zio->io_error == 0);
1219                 arc_release(buf, db);
1220                 bzero(buf->b_data, db->db.db_size);
1221                 arc_buf_freeze(buf);
1222                 db->db_freed_in_flight = FALSE;
1223                 dbuf_set_data(db, buf);
1224                 db->db_state = DB_CACHED;
1225         } else {
1226                 /* success */
1227                 ASSERT(zio == NULL || zio->io_error == 0);
1228                 dbuf_set_data(db, buf);
1229                 db->db_state = DB_CACHED;
1230         }
1231         cv_broadcast(&db->db_changed);
1232         dbuf_rele_and_unlock(db, NULL, B_FALSE);
1233 }
1234
1235
1236 /*
1237  * This function ensures that, when doing a decrypting read of a block,
1238  * we make sure we have decrypted the dnode associated with it. We must do
1239  * this so that we ensure we are fully authenticating the checksum-of-MACs
1240  * tree from the root of the objset down to this block. Indirect blocks are
1241  * always verified against their secure checksum-of-MACs assuming that the
1242  * dnode containing them is correct. Now that we are doing a decrypting read,
1243  * we can be sure that the key is loaded and verify that assumption. This is
1244  * especially important considering that we always read encrypted dnode
1245  * blocks as raw data (without verifying their MACs) to start, and
1246  * decrypt / authenticate them when we need to read an encrypted bonus buffer.
1247  */
1248 static int
1249 dbuf_read_verify_dnode_crypt(dmu_buf_impl_t *db, uint32_t flags)
1250 {
1251         int err = 0;
1252         objset_t *os = db->db_objset;
1253         arc_buf_t *dnode_abuf;
1254         dnode_t *dn;
1255         zbookmark_phys_t zb;
1256
1257         ASSERT(MUTEX_HELD(&db->db_mtx));
1258
1259         if (!os->os_encrypted || os->os_raw_receive ||
1260             (flags & DB_RF_NO_DECRYPT) != 0)
1261                 return (0);
1262
1263         DB_DNODE_ENTER(db);
1264         dn = DB_DNODE(db);
1265         dnode_abuf = (dn->dn_dbuf != NULL) ? dn->dn_dbuf->db_buf : NULL;
1266
1267         if (dnode_abuf == NULL || !arc_is_encrypted(dnode_abuf)) {
1268                 DB_DNODE_EXIT(db);
1269                 return (0);
1270         }
1271
1272         SET_BOOKMARK(&zb, dmu_objset_id(os),
1273             DMU_META_DNODE_OBJECT, 0, dn->dn_dbuf->db_blkid);
1274         err = arc_untransform(dnode_abuf, os->os_spa, &zb, B_TRUE);
1275
1276         /*
1277          * An error code of EACCES tells us that the key is still not
1278          * available. This is ok if we are only reading authenticated
1279          * (and therefore non-encrypted) blocks.
1280          */
1281         if (err == EACCES && ((db->db_blkid != DMU_BONUS_BLKID &&
1282             !DMU_OT_IS_ENCRYPTED(dn->dn_type)) ||
1283             (db->db_blkid == DMU_BONUS_BLKID &&
1284             !DMU_OT_IS_ENCRYPTED(dn->dn_bonustype))))
1285                 err = 0;
1286
1287         DB_DNODE_EXIT(db);
1288
1289         return (err);
1290 }
1291
1292 /*
1293  * Drops db_mtx and the parent lock specified by dblt and tag before
1294  * returning.
1295  */
1296 static int
1297 dbuf_read_impl(dmu_buf_impl_t *db, zio_t *zio, uint32_t flags,
1298     db_lock_type_t dblt, void *tag)
1299 {
1300         dnode_t *dn;
1301         zbookmark_phys_t zb;
1302         uint32_t aflags = ARC_FLAG_NOWAIT;
1303         int err, zio_flags = 0;
1304
1305         DB_DNODE_ENTER(db);
1306         dn = DB_DNODE(db);
1307         ASSERT(!zfs_refcount_is_zero(&db->db_holds));
1308         ASSERT(MUTEX_HELD(&db->db_mtx));
1309         ASSERT(db->db_state == DB_UNCACHED);
1310         ASSERT(db->db_buf == NULL);
1311         ASSERT(db->db_parent == NULL ||
1312             RW_LOCK_HELD(&db->db_parent->db_rwlock));
1313
1314         if (db->db_blkid == DMU_BONUS_BLKID) {
1315                 /*
1316                  * The bonus length stored in the dnode may be less than
1317                  * the maximum available space in the bonus buffer.
1318                  */
1319                 int bonuslen = MIN(dn->dn_bonuslen, dn->dn_phys->dn_bonuslen);
1320                 int max_bonuslen = DN_SLOTS_TO_BONUSLEN(dn->dn_num_slots);
1321
1322                 /* if the underlying dnode block is encrypted, decrypt it */
1323                 err = dbuf_read_verify_dnode_crypt(db, flags);
1324                 if (err != 0) {
1325                         DB_DNODE_EXIT(db);
1326                         mutex_exit(&db->db_mtx);
1327                         return (err);
1328                 }
1329
1330                 ASSERT3U(bonuslen, <=, db->db.db_size);
1331                 db->db.db_data = kmem_alloc(max_bonuslen, KM_SLEEP);
1332                 arc_space_consume(max_bonuslen, ARC_SPACE_BONUS);
1333                 if (bonuslen < max_bonuslen)
1334                         bzero(db->db.db_data, max_bonuslen);
1335                 if (bonuslen)
1336                         bcopy(DN_BONUS(dn->dn_phys), db->db.db_data, bonuslen);
1337                 DB_DNODE_EXIT(db);
1338                 db->db_state = DB_CACHED;
1339                 mutex_exit(&db->db_mtx);
1340                 dmu_buf_unlock_parent(db, dblt, tag);
1341                 return (0);
1342         }
1343
1344         /*
1345          * Recheck BP_IS_HOLE() after dnode_block_freed() in case dnode_sync()
1346          * processes the delete record and clears the bp while we are waiting
1347          * for the dn_mtx (resulting in a "no" from block_freed).
1348          */
1349         if (db->db_blkptr == NULL || BP_IS_HOLE(db->db_blkptr) ||
1350             (db->db_level == 0 && (dnode_block_freed(dn, db->db_blkid) ||
1351             BP_IS_HOLE(db->db_blkptr)))) {
1352                 arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1353
1354                 dbuf_set_data(db, arc_alloc_buf(db->db_objset->os_spa, db, type,
1355                     db->db.db_size));
1356                 bzero(db->db.db_data, db->db.db_size);
1357
1358                 if (db->db_blkptr != NULL && db->db_level > 0 &&
1359                     BP_IS_HOLE(db->db_blkptr) &&
1360                     db->db_blkptr->blk_birth != 0) {
1361                         blkptr_t *bps = db->db.db_data;
1362                         for (int i = 0; i < ((1 <<
1363                             DB_DNODE(db)->dn_indblkshift) / sizeof (blkptr_t));
1364                             i++) {
1365                                 blkptr_t *bp = &bps[i];
1366                                 ASSERT3U(BP_GET_LSIZE(db->db_blkptr), ==,
1367                                     1 << dn->dn_indblkshift);
1368                                 BP_SET_LSIZE(bp,
1369                                     BP_GET_LEVEL(db->db_blkptr) == 1 ?
1370                                     dn->dn_datablksz :
1371                                     BP_GET_LSIZE(db->db_blkptr));
1372                                 BP_SET_TYPE(bp, BP_GET_TYPE(db->db_blkptr));
1373                                 BP_SET_LEVEL(bp,
1374                                     BP_GET_LEVEL(db->db_blkptr) - 1);
1375                                 BP_SET_BIRTH(bp, db->db_blkptr->blk_birth, 0);
1376                         }
1377                 }
1378                 DB_DNODE_EXIT(db);
1379                 db->db_state = DB_CACHED;
1380                 mutex_exit(&db->db_mtx);
1381                 dmu_buf_unlock_parent(db, dblt, tag);
1382                 return (0);
1383         }
1384
1385         /*
1386          * Any attempt to read a redacted block should result in an error. This
1387          * will never happen under normal conditions, but can be useful for
1388          * debugging purposes.
1389          */
1390         if (BP_IS_REDACTED(db->db_blkptr)) {
1391                 ASSERT(dsl_dataset_feature_is_active(
1392                     db->db_objset->os_dsl_dataset,
1393                     SPA_FEATURE_REDACTED_DATASETS));
1394                 DB_DNODE_EXIT(db);
1395                 mutex_exit(&db->db_mtx);
1396                 return (SET_ERROR(EIO));
1397         }
1398
1399
1400         SET_BOOKMARK(&zb, dmu_objset_id(db->db_objset),
1401             db->db.db_object, db->db_level, db->db_blkid);
1402
1403         /*
1404          * All bps of an encrypted os should have the encryption bit set.
1405          * If this is not true it indicates tampering and we report an error.
1406          */
1407         if (db->db_objset->os_encrypted && !BP_USES_CRYPT(db->db_blkptr)) {
1408                 spa_log_error(db->db_objset->os_spa, &zb);
1409                 zfs_panic_recover("unencrypted block in encrypted "
1410                     "object set %llu", dmu_objset_id(db->db_objset));
1411                 DB_DNODE_EXIT(db);
1412                 mutex_exit(&db->db_mtx);
1413                 dmu_buf_unlock_parent(db, dblt, tag);
1414                 return (SET_ERROR(EIO));
1415         }
1416
1417         err = dbuf_read_verify_dnode_crypt(db, flags);
1418         if (err != 0) {
1419                 DB_DNODE_EXIT(db);
1420                 dmu_buf_unlock_parent(db, dblt, tag);
1421                 mutex_exit(&db->db_mtx);
1422                 return (err);
1423         }
1424
1425         DB_DNODE_EXIT(db);
1426
1427         db->db_state = DB_READ;
1428         mutex_exit(&db->db_mtx);
1429
1430         if (DBUF_IS_L2CACHEABLE(db))
1431                 aflags |= ARC_FLAG_L2CACHE;
1432
1433         dbuf_add_ref(db, NULL);
1434
1435         zio_flags = (flags & DB_RF_CANFAIL) ?
1436             ZIO_FLAG_CANFAIL : ZIO_FLAG_MUSTSUCCEED;
1437
1438         if ((flags & DB_RF_NO_DECRYPT) && BP_IS_PROTECTED(db->db_blkptr))
1439                 zio_flags |= ZIO_FLAG_RAW;
1440         /*
1441          * The zio layer will copy the provided blkptr later, but we need to
1442          * do this now so that we can release the parent's rwlock. We have to
1443          * do that now so that if dbuf_read_done is called synchronously (on
1444          * an l1 cache hit) we don't acquire the db_mtx while holding the
1445          * parent's rwlock, which would be a lock ordering violation.
1446          */
1447         blkptr_t bp = *db->db_blkptr;
1448         dmu_buf_unlock_parent(db, dblt, tag);
1449         (void) arc_read(zio, db->db_objset->os_spa, &bp,
1450             dbuf_read_done, db, ZIO_PRIORITY_SYNC_READ, zio_flags,
1451             &aflags, &zb);
1452         return (err);
1453 }
1454
1455 /*
1456  * This is our just-in-time copy function.  It makes a copy of buffers that
1457  * have been modified in a previous transaction group before we access them in
1458  * the current active group.
1459  *
1460  * This function is used in three places: when we are dirtying a buffer for the
1461  * first time in a txg, when we are freeing a range in a dnode that includes
1462  * this buffer, and when we are accessing a buffer which was received compressed
1463  * and later referenced in a WRITE_BYREF record.
1464  *
1465  * Note that when we are called from dbuf_free_range() we do not put a hold on
1466  * the buffer, we just traverse the active dbuf list for the dnode.
1467  */
1468 static void
1469 dbuf_fix_old_data(dmu_buf_impl_t *db, uint64_t txg)
1470 {
1471         dbuf_dirty_record_t *dr = db->db_last_dirty;
1472
1473         ASSERT(MUTEX_HELD(&db->db_mtx));
1474         ASSERT(db->db.db_data != NULL);
1475         ASSERT(db->db_level == 0);
1476         ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT);
1477
1478         if (dr == NULL ||
1479             (dr->dt.dl.dr_data !=
1480             ((db->db_blkid  == DMU_BONUS_BLKID) ? db->db.db_data : db->db_buf)))
1481                 return;
1482
1483         /*
1484          * If the last dirty record for this dbuf has not yet synced
1485          * and its referencing the dbuf data, either:
1486          *      reset the reference to point to a new copy,
1487          * or (if there a no active holders)
1488          *      just null out the current db_data pointer.
1489          */
1490         ASSERT3U(dr->dr_txg, >=, txg - 2);
1491         if (db->db_blkid == DMU_BONUS_BLKID) {
1492                 dnode_t *dn = DB_DNODE(db);
1493                 int bonuslen = DN_SLOTS_TO_BONUSLEN(dn->dn_num_slots);
1494                 dr->dt.dl.dr_data = kmem_alloc(bonuslen, KM_SLEEP);
1495                 arc_space_consume(bonuslen, ARC_SPACE_BONUS);
1496                 bcopy(db->db.db_data, dr->dt.dl.dr_data, bonuslen);
1497         } else if (zfs_refcount_count(&db->db_holds) > db->db_dirtycnt) {
1498                 dnode_t *dn = DB_DNODE(db);
1499                 int size = arc_buf_size(db->db_buf);
1500                 arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1501                 spa_t *spa = db->db_objset->os_spa;
1502                 enum zio_compress compress_type =
1503                     arc_get_compression(db->db_buf);
1504
1505                 if (arc_is_encrypted(db->db_buf)) {
1506                         boolean_t byteorder;
1507                         uint8_t salt[ZIO_DATA_SALT_LEN];
1508                         uint8_t iv[ZIO_DATA_IV_LEN];
1509                         uint8_t mac[ZIO_DATA_MAC_LEN];
1510
1511                         arc_get_raw_params(db->db_buf, &byteorder, salt,
1512                             iv, mac);
1513                         dr->dt.dl.dr_data = arc_alloc_raw_buf(spa, db,
1514                             dmu_objset_id(dn->dn_objset), byteorder, salt, iv,
1515                             mac, dn->dn_type, size, arc_buf_lsize(db->db_buf),
1516                             compress_type);
1517                 } else if (compress_type != ZIO_COMPRESS_OFF) {
1518                         ASSERT3U(type, ==, ARC_BUFC_DATA);
1519                         dr->dt.dl.dr_data = arc_alloc_compressed_buf(spa, db,
1520                             size, arc_buf_lsize(db->db_buf), compress_type);
1521                 } else {
1522                         dr->dt.dl.dr_data = arc_alloc_buf(spa, db, type, size);
1523                 }
1524                 bcopy(db->db.db_data, dr->dt.dl.dr_data->b_data, size);
1525         } else {
1526                 db->db_buf = NULL;
1527                 dbuf_clear_data(db);
1528         }
1529 }
1530
1531 int
1532 dbuf_read(dmu_buf_impl_t *db, zio_t *zio, uint32_t flags)
1533 {
1534         int err = 0;
1535         boolean_t prefetch;
1536         dnode_t *dn;
1537
1538         /*
1539          * We don't have to hold the mutex to check db_state because it
1540          * can't be freed while we have a hold on the buffer.
1541          */
1542         ASSERT(!zfs_refcount_is_zero(&db->db_holds));
1543
1544         if (db->db_state == DB_NOFILL)
1545                 return (SET_ERROR(EIO));
1546
1547         DB_DNODE_ENTER(db);
1548         dn = DB_DNODE(db);
1549
1550         prefetch = db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
1551             (flags & DB_RF_NOPREFETCH) == 0 && dn != NULL &&
1552             DBUF_IS_CACHEABLE(db);
1553
1554         mutex_enter(&db->db_mtx);
1555         if (db->db_state == DB_CACHED) {
1556                 spa_t *spa = dn->dn_objset->os_spa;
1557
1558                 /*
1559                  * Ensure that this block's dnode has been decrypted if
1560                  * the caller has requested decrypted data.
1561                  */
1562                 err = dbuf_read_verify_dnode_crypt(db, flags);
1563
1564                 /*
1565                  * If the arc buf is compressed or encrypted and the caller
1566                  * requested uncompressed data, we need to untransform it
1567                  * before returning. We also call arc_untransform() on any
1568                  * unauthenticated blocks, which will verify their MAC if
1569                  * the key is now available.
1570                  */
1571                 if (err == 0 && db->db_buf != NULL &&
1572                     (flags & DB_RF_NO_DECRYPT) == 0 &&
1573                     (arc_is_encrypted(db->db_buf) ||
1574                     arc_is_unauthenticated(db->db_buf) ||
1575                     arc_get_compression(db->db_buf) != ZIO_COMPRESS_OFF)) {
1576                         zbookmark_phys_t zb;
1577
1578                         SET_BOOKMARK(&zb, dmu_objset_id(db->db_objset),
1579                             db->db.db_object, db->db_level, db->db_blkid);
1580                         dbuf_fix_old_data(db, spa_syncing_txg(spa));
1581                         err = arc_untransform(db->db_buf, spa, &zb, B_FALSE);
1582                         dbuf_set_data(db, db->db_buf);
1583                 }
1584                 mutex_exit(&db->db_mtx);
1585                 if (err == 0 && prefetch) {
1586                         dmu_zfetch(&dn->dn_zfetch, db->db_blkid, 1, B_TRUE,
1587                             flags & DB_RF_HAVESTRUCT);
1588                 }
1589                 DB_DNODE_EXIT(db);
1590                 DBUF_STAT_BUMP(hash_hits);
1591         } else if (db->db_state == DB_UNCACHED) {
1592                 spa_t *spa = dn->dn_objset->os_spa;
1593                 boolean_t need_wait = B_FALSE;
1594
1595                 db_lock_type_t dblt = dmu_buf_lock_parent(db, RW_READER, FTAG);
1596
1597                 if (zio == NULL &&
1598                     db->db_blkptr != NULL && !BP_IS_HOLE(db->db_blkptr)) {
1599                         zio = zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL);
1600                         need_wait = B_TRUE;
1601                 }
1602                 err = dbuf_read_impl(db, zio, flags, dblt, FTAG);
1603                 /*
1604                  * dbuf_read_impl has dropped db_mtx and our parent's rwlock
1605                  * for us
1606                  */
1607                 if (!err && prefetch) {
1608                         dmu_zfetch(&dn->dn_zfetch, db->db_blkid, 1, B_TRUE,
1609                             flags & DB_RF_HAVESTRUCT);
1610                 }
1611
1612                 DB_DNODE_EXIT(db);
1613                 DBUF_STAT_BUMP(hash_misses);
1614
1615                 /*
1616                  * If we created a zio_root we must execute it to avoid
1617                  * leaking it, even if it isn't attached to any work due
1618                  * to an error in dbuf_read_impl().
1619                  */
1620                 if (need_wait) {
1621                         if (err == 0)
1622                                 err = zio_wait(zio);
1623                         else
1624                                 VERIFY0(zio_wait(zio));
1625                 }
1626         } else {
1627                 /*
1628                  * Another reader came in while the dbuf was in flight
1629                  * between UNCACHED and CACHED.  Either a writer will finish
1630                  * writing the buffer (sending the dbuf to CACHED) or the
1631                  * first reader's request will reach the read_done callback
1632                  * and send the dbuf to CACHED.  Otherwise, a failure
1633                  * occurred and the dbuf went to UNCACHED.
1634                  */
1635                 mutex_exit(&db->db_mtx);
1636                 if (prefetch) {
1637                         dmu_zfetch(&dn->dn_zfetch, db->db_blkid, 1, B_TRUE,
1638                             flags & DB_RF_HAVESTRUCT);
1639                 }
1640                 DB_DNODE_EXIT(db);
1641                 DBUF_STAT_BUMP(hash_misses);
1642
1643                 /* Skip the wait per the caller's request. */
1644                 mutex_enter(&db->db_mtx);
1645                 if ((flags & DB_RF_NEVERWAIT) == 0) {
1646                         while (db->db_state == DB_READ ||
1647                             db->db_state == DB_FILL) {
1648                                 ASSERT(db->db_state == DB_READ ||
1649                                     (flags & DB_RF_HAVESTRUCT) == 0);
1650                                 DTRACE_PROBE2(blocked__read, dmu_buf_impl_t *,
1651                                     db, zio_t *, zio);
1652                                 cv_wait(&db->db_changed, &db->db_mtx);
1653                         }
1654                         if (db->db_state == DB_UNCACHED)
1655                                 err = SET_ERROR(EIO);
1656                 }
1657                 mutex_exit(&db->db_mtx);
1658         }
1659
1660         return (err);
1661 }
1662
1663 static void
1664 dbuf_noread(dmu_buf_impl_t *db)
1665 {
1666         ASSERT(!zfs_refcount_is_zero(&db->db_holds));
1667         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1668         mutex_enter(&db->db_mtx);
1669         while (db->db_state == DB_READ || db->db_state == DB_FILL)
1670                 cv_wait(&db->db_changed, &db->db_mtx);
1671         if (db->db_state == DB_UNCACHED) {
1672                 arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1673                 spa_t *spa = db->db_objset->os_spa;
1674
1675                 ASSERT(db->db_buf == NULL);
1676                 ASSERT(db->db.db_data == NULL);
1677                 dbuf_set_data(db, arc_alloc_buf(spa, db, type, db->db.db_size));
1678                 db->db_state = DB_FILL;
1679         } else if (db->db_state == DB_NOFILL) {
1680                 dbuf_clear_data(db);
1681         } else {
1682                 ASSERT3U(db->db_state, ==, DB_CACHED);
1683         }
1684         mutex_exit(&db->db_mtx);
1685 }
1686
1687 void
1688 dbuf_unoverride(dbuf_dirty_record_t *dr)
1689 {
1690         dmu_buf_impl_t *db = dr->dr_dbuf;
1691         blkptr_t *bp = &dr->dt.dl.dr_overridden_by;
1692         uint64_t txg = dr->dr_txg;
1693
1694         ASSERT(MUTEX_HELD(&db->db_mtx));
1695         /*
1696          * This assert is valid because dmu_sync() expects to be called by
1697          * a zilog's get_data while holding a range lock.  This call only
1698          * comes from dbuf_dirty() callers who must also hold a range lock.
1699          */
1700         ASSERT(dr->dt.dl.dr_override_state != DR_IN_DMU_SYNC);
1701         ASSERT(db->db_level == 0);
1702
1703         if (db->db_blkid == DMU_BONUS_BLKID ||
1704             dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN)
1705                 return;
1706
1707         ASSERT(db->db_data_pending != dr);
1708
1709         /* free this block */
1710         if (!BP_IS_HOLE(bp) && !dr->dt.dl.dr_nopwrite)
1711                 zio_free(db->db_objset->os_spa, txg, bp);
1712
1713         dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
1714         dr->dt.dl.dr_nopwrite = B_FALSE;
1715         dr->dt.dl.dr_has_raw_params = B_FALSE;
1716
1717         /*
1718          * Release the already-written buffer, so we leave it in
1719          * a consistent dirty state.  Note that all callers are
1720          * modifying the buffer, so they will immediately do
1721          * another (redundant) arc_release().  Therefore, leave
1722          * the buf thawed to save the effort of freezing &
1723          * immediately re-thawing it.
1724          */
1725         arc_release(dr->dt.dl.dr_data, db);
1726 }
1727
1728 /*
1729  * Evict (if its unreferenced) or clear (if its referenced) any level-0
1730  * data blocks in the free range, so that any future readers will find
1731  * empty blocks.
1732  */
1733 void
1734 dbuf_free_range(dnode_t *dn, uint64_t start_blkid, uint64_t end_blkid,
1735     dmu_tx_t *tx)
1736 {
1737         dmu_buf_impl_t *db_search;
1738         dmu_buf_impl_t *db, *db_next;
1739         uint64_t txg = tx->tx_txg;
1740         avl_index_t where;
1741
1742         if (end_blkid > dn->dn_maxblkid &&
1743             !(start_blkid == DMU_SPILL_BLKID || end_blkid == DMU_SPILL_BLKID))
1744                 end_blkid = dn->dn_maxblkid;
1745         dprintf_dnode(dn, "start=%llu end=%llu\n", start_blkid, end_blkid);
1746
1747         db_search = kmem_alloc(sizeof (dmu_buf_impl_t), KM_SLEEP);
1748         db_search->db_level = 0;
1749         db_search->db_blkid = start_blkid;
1750         db_search->db_state = DB_SEARCH;
1751
1752         mutex_enter(&dn->dn_dbufs_mtx);
1753         db = avl_find(&dn->dn_dbufs, db_search, &where);
1754         ASSERT3P(db, ==, NULL);
1755
1756         db = avl_nearest(&dn->dn_dbufs, where, AVL_AFTER);
1757
1758         for (; db != NULL; db = db_next) {
1759                 db_next = AVL_NEXT(&dn->dn_dbufs, db);
1760                 ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1761
1762                 if (db->db_level != 0 || db->db_blkid > end_blkid) {
1763                         break;
1764                 }
1765                 ASSERT3U(db->db_blkid, >=, start_blkid);
1766
1767                 /* found a level 0 buffer in the range */
1768                 mutex_enter(&db->db_mtx);
1769                 if (dbuf_undirty(db, tx)) {
1770                         /* mutex has been dropped and dbuf destroyed */
1771                         continue;
1772                 }
1773
1774                 if (db->db_state == DB_UNCACHED ||
1775                     db->db_state == DB_NOFILL ||
1776                     db->db_state == DB_EVICTING) {
1777                         ASSERT(db->db.db_data == NULL);
1778                         mutex_exit(&db->db_mtx);
1779                         continue;
1780                 }
1781                 if (db->db_state == DB_READ || db->db_state == DB_FILL) {
1782                         /* will be handled in dbuf_read_done or dbuf_rele */
1783                         db->db_freed_in_flight = TRUE;
1784                         mutex_exit(&db->db_mtx);
1785                         continue;
1786                 }
1787                 if (zfs_refcount_count(&db->db_holds) == 0) {
1788                         ASSERT(db->db_buf);
1789                         dbuf_destroy(db);
1790                         continue;
1791                 }
1792                 /* The dbuf is referenced */
1793
1794                 if (db->db_last_dirty != NULL) {
1795                         dbuf_dirty_record_t *dr = db->db_last_dirty;
1796
1797                         if (dr->dr_txg == txg) {
1798                                 /*
1799                                  * This buffer is "in-use", re-adjust the file
1800                                  * size to reflect that this buffer may
1801                                  * contain new data when we sync.
1802                                  */
1803                                 if (db->db_blkid != DMU_SPILL_BLKID &&
1804                                     db->db_blkid > dn->dn_maxblkid)
1805                                         dn->dn_maxblkid = db->db_blkid;
1806                                 dbuf_unoverride(dr);
1807                         } else {
1808                                 /*
1809                                  * This dbuf is not dirty in the open context.
1810                                  * Either uncache it (if its not referenced in
1811                                  * the open context) or reset its contents to
1812                                  * empty.
1813                                  */
1814                                 dbuf_fix_old_data(db, txg);
1815                         }
1816                 }
1817                 /* clear the contents if its cached */
1818                 if (db->db_state == DB_CACHED) {
1819                         ASSERT(db->db.db_data != NULL);
1820                         arc_release(db->db_buf, db);
1821                         rw_enter(&db->db_rwlock, RW_WRITER);
1822                         bzero(db->db.db_data, db->db.db_size);
1823                         rw_exit(&db->db_rwlock);
1824                         arc_buf_freeze(db->db_buf);
1825                 }
1826
1827                 mutex_exit(&db->db_mtx);
1828         }
1829
1830         kmem_free(db_search, sizeof (dmu_buf_impl_t));
1831         mutex_exit(&dn->dn_dbufs_mtx);
1832 }
1833
1834 void
1835 dbuf_new_size(dmu_buf_impl_t *db, int size, dmu_tx_t *tx)
1836 {
1837         arc_buf_t *buf, *obuf;
1838         int osize = db->db.db_size;
1839         arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1840         dnode_t *dn;
1841
1842         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1843
1844         DB_DNODE_ENTER(db);
1845         dn = DB_DNODE(db);
1846
1847         /*
1848          * XXX we should be doing a dbuf_read, checking the return
1849          * value and returning that up to our callers
1850          */
1851         dmu_buf_will_dirty(&db->db, tx);
1852
1853         /* create the data buffer for the new block */
1854         buf = arc_alloc_buf(dn->dn_objset->os_spa, db, type, size);
1855
1856         /* copy old block data to the new block */
1857         obuf = db->db_buf;
1858         bcopy(obuf->b_data, buf->b_data, MIN(osize, size));
1859         /* zero the remainder */
1860         if (size > osize)
1861                 bzero((uint8_t *)buf->b_data + osize, size - osize);
1862
1863         mutex_enter(&db->db_mtx);
1864         dbuf_set_data(db, buf);
1865         arc_buf_destroy(obuf, db);
1866         db->db.db_size = size;
1867
1868         if (db->db_level == 0) {
1869                 db->db_last_dirty->dt.dl.dr_data = buf;
1870         }
1871         ASSERT3U(db->db_last_dirty->dr_txg, ==, tx->tx_txg);
1872         ASSERT3U(db->db_last_dirty->dr_accounted, ==, osize);
1873         db->db_last_dirty->dr_accounted = size;
1874         mutex_exit(&db->db_mtx);
1875
1876         dmu_objset_willuse_space(dn->dn_objset, size - osize, tx);
1877         DB_DNODE_EXIT(db);
1878 }
1879
1880 void
1881 dbuf_release_bp(dmu_buf_impl_t *db)
1882 {
1883         objset_t *os __maybe_unused = db->db_objset;
1884
1885         ASSERT(dsl_pool_sync_context(dmu_objset_pool(os)));
1886         ASSERT(arc_released(os->os_phys_buf) ||
1887             list_link_active(&os->os_dsl_dataset->ds_synced_link));
1888         ASSERT(db->db_parent == NULL || arc_released(db->db_parent->db_buf));
1889
1890         (void) arc_release(db->db_buf, db);
1891 }
1892
1893 /*
1894  * We already have a dirty record for this TXG, and we are being
1895  * dirtied again.
1896  */
1897 static void
1898 dbuf_redirty(dbuf_dirty_record_t *dr)
1899 {
1900         dmu_buf_impl_t *db = dr->dr_dbuf;
1901
1902         ASSERT(MUTEX_HELD(&db->db_mtx));
1903
1904         if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID) {
1905                 /*
1906                  * If this buffer has already been written out,
1907                  * we now need to reset its state.
1908                  */
1909                 dbuf_unoverride(dr);
1910                 if (db->db.db_object != DMU_META_DNODE_OBJECT &&
1911                     db->db_state != DB_NOFILL) {
1912                         /* Already released on initial dirty, so just thaw. */
1913                         ASSERT(arc_released(db->db_buf));
1914                         arc_buf_thaw(db->db_buf);
1915                 }
1916         }
1917 }
1918
1919 dbuf_dirty_record_t *
1920 dbuf_dirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
1921 {
1922         dnode_t *dn;
1923         objset_t *os;
1924         dbuf_dirty_record_t **drp, *dr;
1925         int txgoff = tx->tx_txg & TXG_MASK;
1926         boolean_t drop_struct_rwlock = B_FALSE;
1927
1928         ASSERT(tx->tx_txg != 0);
1929         ASSERT(!zfs_refcount_is_zero(&db->db_holds));
1930         DMU_TX_DIRTY_BUF(tx, db);
1931
1932         DB_DNODE_ENTER(db);
1933         dn = DB_DNODE(db);
1934         /*
1935          * Shouldn't dirty a regular buffer in syncing context.  Private
1936          * objects may be dirtied in syncing context, but only if they
1937          * were already pre-dirtied in open context.
1938          */
1939 #ifdef DEBUG
1940         if (dn->dn_objset->os_dsl_dataset != NULL) {
1941                 rrw_enter(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock,
1942                     RW_READER, FTAG);
1943         }
1944         ASSERT(!dmu_tx_is_syncing(tx) ||
1945             BP_IS_HOLE(dn->dn_objset->os_rootbp) ||
1946             DMU_OBJECT_IS_SPECIAL(dn->dn_object) ||
1947             dn->dn_objset->os_dsl_dataset == NULL);
1948         if (dn->dn_objset->os_dsl_dataset != NULL)
1949                 rrw_exit(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock, FTAG);
1950 #endif
1951         /*
1952          * We make this assert for private objects as well, but after we
1953          * check if we're already dirty.  They are allowed to re-dirty
1954          * in syncing context.
1955          */
1956         ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
1957             dn->dn_dirtyctx == DN_UNDIRTIED || dn->dn_dirtyctx ==
1958             (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN));
1959
1960         mutex_enter(&db->db_mtx);
1961         /*
1962          * XXX make this true for indirects too?  The problem is that
1963          * transactions created with dmu_tx_create_assigned() from
1964          * syncing context don't bother holding ahead.
1965          */
1966         ASSERT(db->db_level != 0 ||
1967             db->db_state == DB_CACHED || db->db_state == DB_FILL ||
1968             db->db_state == DB_NOFILL);
1969
1970         mutex_enter(&dn->dn_mtx);
1971         /*
1972          * Don't set dirtyctx to SYNC if we're just modifying this as we
1973          * initialize the objset.
1974          */
1975         if (dn->dn_dirtyctx == DN_UNDIRTIED) {
1976                 if (dn->dn_objset->os_dsl_dataset != NULL) {
1977                         rrw_enter(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock,
1978                             RW_READER, FTAG);
1979                 }
1980                 if (!BP_IS_HOLE(dn->dn_objset->os_rootbp)) {
1981                         dn->dn_dirtyctx = (dmu_tx_is_syncing(tx) ?
1982                             DN_DIRTY_SYNC : DN_DIRTY_OPEN);
1983                         ASSERT(dn->dn_dirtyctx_firstset == NULL);
1984                         dn->dn_dirtyctx_firstset = kmem_alloc(1, KM_SLEEP);
1985                 }
1986                 if (dn->dn_objset->os_dsl_dataset != NULL) {
1987                         rrw_exit(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock,
1988                             FTAG);
1989                 }
1990         }
1991
1992         if (tx->tx_txg > dn->dn_dirty_txg)
1993                 dn->dn_dirty_txg = tx->tx_txg;
1994         mutex_exit(&dn->dn_mtx);
1995
1996         if (db->db_blkid == DMU_SPILL_BLKID)
1997                 dn->dn_have_spill = B_TRUE;
1998
1999         /*
2000          * If this buffer is already dirty, we're done.
2001          */
2002         drp = &db->db_last_dirty;
2003         ASSERT(*drp == NULL || (*drp)->dr_txg <= tx->tx_txg ||
2004             db->db.db_object == DMU_META_DNODE_OBJECT);
2005         while ((dr = *drp) != NULL && dr->dr_txg > tx->tx_txg)
2006                 drp = &dr->dr_next;
2007         if (dr && dr->dr_txg == tx->tx_txg) {
2008                 DB_DNODE_EXIT(db);
2009
2010                 dbuf_redirty(dr);
2011                 mutex_exit(&db->db_mtx);
2012                 return (dr);
2013         }
2014
2015         /*
2016          * Only valid if not already dirty.
2017          */
2018         ASSERT(dn->dn_object == 0 ||
2019             dn->dn_dirtyctx == DN_UNDIRTIED || dn->dn_dirtyctx ==
2020             (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN));
2021
2022         ASSERT3U(dn->dn_nlevels, >, db->db_level);
2023
2024         /*
2025          * We should only be dirtying in syncing context if it's the
2026          * mos or we're initializing the os or it's a special object.
2027          * However, we are allowed to dirty in syncing context provided
2028          * we already dirtied it in open context.  Hence we must make
2029          * this assertion only if we're not already dirty.
2030          */
2031         os = dn->dn_objset;
2032         VERIFY3U(tx->tx_txg, <=, spa_final_dirty_txg(os->os_spa));
2033 #ifdef DEBUG
2034         if (dn->dn_objset->os_dsl_dataset != NULL)
2035                 rrw_enter(&os->os_dsl_dataset->ds_bp_rwlock, RW_READER, FTAG);
2036         ASSERT(!dmu_tx_is_syncing(tx) || DMU_OBJECT_IS_SPECIAL(dn->dn_object) ||
2037             os->os_dsl_dataset == NULL || BP_IS_HOLE(os->os_rootbp));
2038         if (dn->dn_objset->os_dsl_dataset != NULL)
2039                 rrw_exit(&os->os_dsl_dataset->ds_bp_rwlock, FTAG);
2040 #endif
2041         ASSERT(db->db.db_size != 0);
2042
2043         dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
2044
2045         if (db->db_blkid != DMU_BONUS_BLKID) {
2046                 dmu_objset_willuse_space(os, db->db.db_size, tx);
2047         }
2048
2049         /*
2050          * If this buffer is dirty in an old transaction group we need
2051          * to make a copy of it so that the changes we make in this
2052          * transaction group won't leak out when we sync the older txg.
2053          */
2054         dr = kmem_zalloc(sizeof (dbuf_dirty_record_t), KM_SLEEP);
2055         list_link_init(&dr->dr_dirty_node);
2056         if (db->db_level == 0) {
2057                 void *data_old = db->db_buf;
2058
2059                 if (db->db_state != DB_NOFILL) {
2060                         if (db->db_blkid == DMU_BONUS_BLKID) {
2061                                 dbuf_fix_old_data(db, tx->tx_txg);
2062                                 data_old = db->db.db_data;
2063                         } else if (db->db.db_object != DMU_META_DNODE_OBJECT) {
2064                                 /*
2065                                  * Release the data buffer from the cache so
2066                                  * that we can modify it without impacting
2067                                  * possible other users of this cached data
2068                                  * block.  Note that indirect blocks and
2069                                  * private objects are not released until the
2070                                  * syncing state (since they are only modified
2071                                  * then).
2072                                  */
2073                                 arc_release(db->db_buf, db);
2074                                 dbuf_fix_old_data(db, tx->tx_txg);
2075                                 data_old = db->db_buf;
2076                         }
2077                         ASSERT(data_old != NULL);
2078                 }
2079                 dr->dt.dl.dr_data = data_old;
2080         } else {
2081                 mutex_init(&dr->dt.di.dr_mtx, NULL, MUTEX_NOLOCKDEP, NULL);
2082                 list_create(&dr->dt.di.dr_children,
2083                     sizeof (dbuf_dirty_record_t),
2084                     offsetof(dbuf_dirty_record_t, dr_dirty_node));
2085         }
2086         if (db->db_blkid != DMU_BONUS_BLKID)
2087                 dr->dr_accounted = db->db.db_size;
2088         dr->dr_dbuf = db;
2089         dr->dr_txg = tx->tx_txg;
2090         dr->dr_next = *drp;
2091         *drp = dr;
2092
2093         /*
2094          * We could have been freed_in_flight between the dbuf_noread
2095          * and dbuf_dirty.  We win, as though the dbuf_noread() had
2096          * happened after the free.
2097          */
2098         if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
2099             db->db_blkid != DMU_SPILL_BLKID) {
2100                 mutex_enter(&dn->dn_mtx);
2101                 if (dn->dn_free_ranges[txgoff] != NULL) {
2102                         range_tree_clear(dn->dn_free_ranges[txgoff],
2103                             db->db_blkid, 1);
2104                 }
2105                 mutex_exit(&dn->dn_mtx);
2106                 db->db_freed_in_flight = FALSE;
2107         }
2108
2109         /*
2110          * This buffer is now part of this txg
2111          */
2112         dbuf_add_ref(db, (void *)(uintptr_t)tx->tx_txg);
2113         db->db_dirtycnt += 1;
2114         ASSERT3U(db->db_dirtycnt, <=, 3);
2115
2116         mutex_exit(&db->db_mtx);
2117
2118         if (db->db_blkid == DMU_BONUS_BLKID ||
2119             db->db_blkid == DMU_SPILL_BLKID) {
2120                 mutex_enter(&dn->dn_mtx);
2121                 ASSERT(!list_link_active(&dr->dr_dirty_node));
2122                 list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
2123                 mutex_exit(&dn->dn_mtx);
2124                 dnode_setdirty(dn, tx);
2125                 DB_DNODE_EXIT(db);
2126                 return (dr);
2127         }
2128
2129         if (!RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
2130                 rw_enter(&dn->dn_struct_rwlock, RW_READER);
2131                 drop_struct_rwlock = B_TRUE;
2132         }
2133
2134         /*
2135          * If we are overwriting a dedup BP, then unless it is snapshotted,
2136          * when we get to syncing context we will need to decrement its
2137          * refcount in the DDT.  Prefetch the relevant DDT block so that
2138          * syncing context won't have to wait for the i/o.
2139          */
2140         if (db->db_blkptr != NULL) {
2141                 db_lock_type_t dblt = dmu_buf_lock_parent(db, RW_READER, FTAG);
2142                 ddt_prefetch(os->os_spa, db->db_blkptr);
2143                 dmu_buf_unlock_parent(db, dblt, FTAG);
2144         }
2145
2146         /*
2147          * We need to hold the dn_struct_rwlock to make this assertion,
2148          * because it protects dn_phys / dn_next_nlevels from changing.
2149          */
2150         ASSERT((dn->dn_phys->dn_nlevels == 0 && db->db_level == 0) ||
2151             dn->dn_phys->dn_nlevels > db->db_level ||
2152             dn->dn_next_nlevels[txgoff] > db->db_level ||
2153             dn->dn_next_nlevels[(tx->tx_txg-1) & TXG_MASK] > db->db_level ||
2154             dn->dn_next_nlevels[(tx->tx_txg-2) & TXG_MASK] > db->db_level);
2155
2156
2157         if (db->db_level == 0) {
2158                 ASSERT(!db->db_objset->os_raw_receive ||
2159                     dn->dn_maxblkid >= db->db_blkid);
2160                 dnode_new_blkid(dn, db->db_blkid, tx,
2161                     drop_struct_rwlock, B_FALSE);
2162                 ASSERT(dn->dn_maxblkid >= db->db_blkid);
2163         }
2164
2165         if (db->db_level+1 < dn->dn_nlevels) {
2166                 dmu_buf_impl_t *parent = db->db_parent;
2167                 dbuf_dirty_record_t *di;
2168                 int parent_held = FALSE;
2169
2170                 if (db->db_parent == NULL || db->db_parent == dn->dn_dbuf) {
2171                         int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
2172                         parent = dbuf_hold_level(dn, db->db_level + 1,
2173                             db->db_blkid >> epbs, FTAG);
2174                         ASSERT(parent != NULL);
2175                         parent_held = TRUE;
2176                 }
2177                 if (drop_struct_rwlock)
2178                         rw_exit(&dn->dn_struct_rwlock);
2179                 ASSERT3U(db->db_level + 1, ==, parent->db_level);
2180                 di = dbuf_dirty(parent, tx);
2181                 if (parent_held)
2182                         dbuf_rele(parent, FTAG);
2183
2184                 mutex_enter(&db->db_mtx);
2185                 /*
2186                  * Since we've dropped the mutex, it's possible that
2187                  * dbuf_undirty() might have changed this out from under us.
2188                  */
2189                 if (db->db_last_dirty == dr ||
2190                     dn->dn_object == DMU_META_DNODE_OBJECT) {
2191                         mutex_enter(&di->dt.di.dr_mtx);
2192                         ASSERT3U(di->dr_txg, ==, tx->tx_txg);
2193                         ASSERT(!list_link_active(&dr->dr_dirty_node));
2194                         list_insert_tail(&di->dt.di.dr_children, dr);
2195                         mutex_exit(&di->dt.di.dr_mtx);
2196                         dr->dr_parent = di;
2197                 }
2198                 mutex_exit(&db->db_mtx);
2199         } else {
2200                 ASSERT(db->db_level + 1 == dn->dn_nlevels);
2201                 ASSERT(db->db_blkid < dn->dn_nblkptr);
2202                 ASSERT(db->db_parent == NULL || db->db_parent == dn->dn_dbuf);
2203                 mutex_enter(&dn->dn_mtx);
2204                 ASSERT(!list_link_active(&dr->dr_dirty_node));
2205                 list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
2206                 mutex_exit(&dn->dn_mtx);
2207                 if (drop_struct_rwlock)
2208                         rw_exit(&dn->dn_struct_rwlock);
2209         }
2210
2211         dnode_setdirty(dn, tx);
2212         DB_DNODE_EXIT(db);
2213         return (dr);
2214 }
2215
2216 /*
2217  * Undirty a buffer in the transaction group referenced by the given
2218  * transaction.  Return whether this evicted the dbuf.
2219  */
2220 static boolean_t
2221 dbuf_undirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
2222 {
2223         dnode_t *dn;
2224         uint64_t txg = tx->tx_txg;
2225         dbuf_dirty_record_t *dr, **drp;
2226
2227         ASSERT(txg != 0);
2228
2229         /*
2230          * Due to our use of dn_nlevels below, this can only be called
2231          * in open context, unless we are operating on the MOS.
2232          * From syncing context, dn_nlevels may be different from the
2233          * dn_nlevels used when dbuf was dirtied.
2234          */
2235         ASSERT(db->db_objset ==
2236             dmu_objset_pool(db->db_objset)->dp_meta_objset ||
2237             txg != spa_syncing_txg(dmu_objset_spa(db->db_objset)));
2238         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2239         ASSERT0(db->db_level);
2240         ASSERT(MUTEX_HELD(&db->db_mtx));
2241
2242         /*
2243          * If this buffer is not dirty, we're done.
2244          */
2245         for (drp = &db->db_last_dirty; (dr = *drp) != NULL; drp = &dr->dr_next)
2246                 if (dr->dr_txg <= txg)
2247                         break;
2248         if (dr == NULL || dr->dr_txg < txg)
2249                 return (B_FALSE);
2250         ASSERT(dr->dr_txg == txg);
2251         ASSERT(dr->dr_dbuf == db);
2252
2253         DB_DNODE_ENTER(db);
2254         dn = DB_DNODE(db);
2255
2256         dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
2257
2258         ASSERT(db->db.db_size != 0);
2259
2260         dsl_pool_undirty_space(dmu_objset_pool(dn->dn_objset),
2261             dr->dr_accounted, txg);
2262
2263         *drp = dr->dr_next;
2264
2265         /*
2266          * Note that there are three places in dbuf_dirty()
2267          * where this dirty record may be put on a list.
2268          * Make sure to do a list_remove corresponding to
2269          * every one of those list_insert calls.
2270          */
2271         if (dr->dr_parent) {
2272                 mutex_enter(&dr->dr_parent->dt.di.dr_mtx);
2273                 list_remove(&dr->dr_parent->dt.di.dr_children, dr);
2274                 mutex_exit(&dr->dr_parent->dt.di.dr_mtx);
2275         } else if (db->db_blkid == DMU_SPILL_BLKID ||
2276             db->db_level + 1 == dn->dn_nlevels) {
2277                 ASSERT(db->db_blkptr == NULL || db->db_parent == dn->dn_dbuf);
2278                 mutex_enter(&dn->dn_mtx);
2279                 list_remove(&dn->dn_dirty_records[txg & TXG_MASK], dr);
2280                 mutex_exit(&dn->dn_mtx);
2281         }
2282         DB_DNODE_EXIT(db);
2283
2284         if (db->db_state != DB_NOFILL) {
2285                 dbuf_unoverride(dr);
2286
2287                 ASSERT(db->db_buf != NULL);
2288                 ASSERT(dr->dt.dl.dr_data != NULL);
2289                 if (dr->dt.dl.dr_data != db->db_buf)
2290                         arc_buf_destroy(dr->dt.dl.dr_data, db);
2291         }
2292
2293         kmem_free(dr, sizeof (dbuf_dirty_record_t));
2294
2295         ASSERT(db->db_dirtycnt > 0);
2296         db->db_dirtycnt -= 1;
2297
2298         if (zfs_refcount_remove(&db->db_holds, (void *)(uintptr_t)txg) == 0) {
2299                 ASSERT(db->db_state == DB_NOFILL || arc_released(db->db_buf));
2300                 dbuf_destroy(db);
2301                 return (B_TRUE);
2302         }
2303
2304         return (B_FALSE);
2305 }
2306
2307 static void
2308 dmu_buf_will_dirty_impl(dmu_buf_t *db_fake, int flags, dmu_tx_t *tx)
2309 {
2310         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2311
2312         ASSERT(tx->tx_txg != 0);
2313         ASSERT(!zfs_refcount_is_zero(&db->db_holds));
2314
2315         /*
2316          * Quick check for dirtiness.  For already dirty blocks, this
2317          * reduces runtime of this function by >90%, and overall performance
2318          * by 50% for some workloads (e.g. file deletion with indirect blocks
2319          * cached).
2320          */
2321         mutex_enter(&db->db_mtx);
2322
2323         dbuf_dirty_record_t *dr;
2324         for (dr = db->db_last_dirty;
2325             dr != NULL && dr->dr_txg >= tx->tx_txg; dr = dr->dr_next) {
2326                 /*
2327                  * It's possible that it is already dirty but not cached,
2328                  * because there are some calls to dbuf_dirty() that don't
2329                  * go through dmu_buf_will_dirty().
2330                  */
2331                 if (dr->dr_txg == tx->tx_txg && db->db_state == DB_CACHED) {
2332                         /* This dbuf is already dirty and cached. */
2333                         dbuf_redirty(dr);
2334                         mutex_exit(&db->db_mtx);
2335                         return;
2336                 }
2337         }
2338         mutex_exit(&db->db_mtx);
2339
2340         DB_DNODE_ENTER(db);
2341         if (RW_WRITE_HELD(&DB_DNODE(db)->dn_struct_rwlock))
2342                 flags |= DB_RF_HAVESTRUCT;
2343         DB_DNODE_EXIT(db);
2344         (void) dbuf_read(db, NULL, flags);
2345         (void) dbuf_dirty(db, tx);
2346 }
2347
2348 void
2349 dmu_buf_will_dirty(dmu_buf_t *db_fake, dmu_tx_t *tx)
2350 {
2351         dmu_buf_will_dirty_impl(db_fake,
2352             DB_RF_MUST_SUCCEED | DB_RF_NOPREFETCH, tx);
2353 }
2354
2355 boolean_t
2356 dmu_buf_is_dirty(dmu_buf_t *db_fake, dmu_tx_t *tx)
2357 {
2358         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2359
2360         mutex_enter(&db->db_mtx);
2361         for (dbuf_dirty_record_t *dr = db->db_last_dirty;
2362             dr != NULL && dr->dr_txg >= tx->tx_txg; dr = dr->dr_next) {
2363                 if (dr->dr_txg == tx->tx_txg) {
2364                         mutex_exit(&db->db_mtx);
2365                         return (B_TRUE);
2366                 }
2367         }
2368         mutex_exit(&db->db_mtx);
2369         return (B_FALSE);
2370 }
2371
2372 void
2373 dmu_buf_will_not_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
2374 {
2375         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2376
2377         db->db_state = DB_NOFILL;
2378
2379         dmu_buf_will_fill(db_fake, tx);
2380 }
2381
2382 void
2383 dmu_buf_will_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
2384 {
2385         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2386
2387         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2388         ASSERT(tx->tx_txg != 0);
2389         ASSERT(db->db_level == 0);
2390         ASSERT(!zfs_refcount_is_zero(&db->db_holds));
2391
2392         ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT ||
2393             dmu_tx_private_ok(tx));
2394
2395         dbuf_noread(db);
2396         (void) dbuf_dirty(db, tx);
2397 }
2398
2399 /*
2400  * This function is effectively the same as dmu_buf_will_dirty(), but
2401  * indicates the caller expects raw encrypted data in the db, and provides
2402  * the crypt params (byteorder, salt, iv, mac) which should be stored in the
2403  * blkptr_t when this dbuf is written.  This is only used for blocks of
2404  * dnodes, during raw receive.
2405  */
2406 void
2407 dmu_buf_set_crypt_params(dmu_buf_t *db_fake, boolean_t byteorder,
2408     const uint8_t *salt, const uint8_t *iv, const uint8_t *mac, dmu_tx_t *tx)
2409 {
2410         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2411         dbuf_dirty_record_t *dr;
2412
2413         /*
2414          * dr_has_raw_params is only processed for blocks of dnodes
2415          * (see dbuf_sync_dnode_leaf_crypt()).
2416          */
2417         ASSERT3U(db->db.db_object, ==, DMU_META_DNODE_OBJECT);
2418         ASSERT3U(db->db_level, ==, 0);
2419         ASSERT(db->db_objset->os_raw_receive);
2420
2421         dmu_buf_will_dirty_impl(db_fake,
2422             DB_RF_MUST_SUCCEED | DB_RF_NOPREFETCH | DB_RF_NO_DECRYPT, tx);
2423
2424         dr = db->db_last_dirty;
2425         while (dr != NULL && dr->dr_txg > tx->tx_txg)
2426                 dr = dr->dr_next;
2427
2428         ASSERT3P(dr, !=, NULL);
2429         ASSERT3U(dr->dr_txg, ==, tx->tx_txg);
2430
2431         dr->dt.dl.dr_has_raw_params = B_TRUE;
2432         dr->dt.dl.dr_byteorder = byteorder;
2433         bcopy(salt, dr->dt.dl.dr_salt, ZIO_DATA_SALT_LEN);
2434         bcopy(iv, dr->dt.dl.dr_iv, ZIO_DATA_IV_LEN);
2435         bcopy(mac, dr->dt.dl.dr_mac, ZIO_DATA_MAC_LEN);
2436 }
2437
2438 static void
2439 dbuf_override_impl(dmu_buf_impl_t *db, const blkptr_t *bp, dmu_tx_t *tx)
2440 {
2441         struct dirty_leaf *dl;
2442
2443         ASSERT3U(db->db_last_dirty->dr_txg, ==, tx->tx_txg);
2444         dl = &db->db_last_dirty->dt.dl;
2445         dl->dr_overridden_by = *bp;
2446         dl->dr_override_state = DR_OVERRIDDEN;
2447         dl->dr_overridden_by.blk_birth = db->db_last_dirty->dr_txg;
2448 }
2449
2450 /* ARGSUSED */
2451 void
2452 dmu_buf_fill_done(dmu_buf_t *dbuf, dmu_tx_t *tx)
2453 {
2454         dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbuf;
2455         mutex_enter(&db->db_mtx);
2456         DBUF_VERIFY(db);
2457
2458         if (db->db_state == DB_FILL) {
2459                 if (db->db_level == 0 && db->db_freed_in_flight) {
2460                         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2461                         /* we were freed while filling */
2462                         /* XXX dbuf_undirty? */
2463                         bzero(db->db.db_data, db->db.db_size);
2464                         db->db_freed_in_flight = FALSE;
2465                 }
2466                 db->db_state = DB_CACHED;
2467                 cv_broadcast(&db->db_changed);
2468         }
2469         mutex_exit(&db->db_mtx);
2470 }
2471
2472 void
2473 dmu_buf_write_embedded(dmu_buf_t *dbuf, void *data,
2474     bp_embedded_type_t etype, enum zio_compress comp,
2475     int uncompressed_size, int compressed_size, int byteorder,
2476     dmu_tx_t *tx)
2477 {
2478         dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbuf;
2479         struct dirty_leaf *dl;
2480         dmu_object_type_t type;
2481
2482         if (etype == BP_EMBEDDED_TYPE_DATA) {
2483                 ASSERT(spa_feature_is_active(dmu_objset_spa(db->db_objset),
2484                     SPA_FEATURE_EMBEDDED_DATA));
2485         }
2486
2487         DB_DNODE_ENTER(db);
2488         type = DB_DNODE(db)->dn_type;
2489         DB_DNODE_EXIT(db);
2490
2491         ASSERT0(db->db_level);
2492         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2493
2494         dmu_buf_will_not_fill(dbuf, tx);
2495
2496         ASSERT3U(db->db_last_dirty->dr_txg, ==, tx->tx_txg);
2497         dl = &db->db_last_dirty->dt.dl;
2498         encode_embedded_bp_compressed(&dl->dr_overridden_by,
2499             data, comp, uncompressed_size, compressed_size);
2500         BPE_SET_ETYPE(&dl->dr_overridden_by, etype);
2501         BP_SET_TYPE(&dl->dr_overridden_by, type);
2502         BP_SET_LEVEL(&dl->dr_overridden_by, 0);
2503         BP_SET_BYTEORDER(&dl->dr_overridden_by, byteorder);
2504
2505         dl->dr_override_state = DR_OVERRIDDEN;
2506         dl->dr_overridden_by.blk_birth = db->db_last_dirty->dr_txg;
2507 }
2508
2509 void
2510 dmu_buf_redact(dmu_buf_t *dbuf, dmu_tx_t *tx)
2511 {
2512         dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbuf;
2513         dmu_object_type_t type;
2514         ASSERT(dsl_dataset_feature_is_active(db->db_objset->os_dsl_dataset,
2515             SPA_FEATURE_REDACTED_DATASETS));
2516
2517         DB_DNODE_ENTER(db);
2518         type = DB_DNODE(db)->dn_type;
2519         DB_DNODE_EXIT(db);
2520
2521         ASSERT0(db->db_level);
2522         dmu_buf_will_not_fill(dbuf, tx);
2523
2524         blkptr_t bp = { { { {0} } } };
2525         BP_SET_TYPE(&bp, type);
2526         BP_SET_LEVEL(&bp, 0);
2527         BP_SET_BIRTH(&bp, tx->tx_txg, 0);
2528         BP_SET_REDACTED(&bp);
2529         BPE_SET_LSIZE(&bp, dbuf->db_size);
2530
2531         dbuf_override_impl(db, &bp, tx);
2532 }
2533
2534 /*
2535  * Directly assign a provided arc buf to a given dbuf if it's not referenced
2536  * by anybody except our caller. Otherwise copy arcbuf's contents to dbuf.
2537  */
2538 void
2539 dbuf_assign_arcbuf(dmu_buf_impl_t *db, arc_buf_t *buf, dmu_tx_t *tx)
2540 {
2541         ASSERT(!zfs_refcount_is_zero(&db->db_holds));
2542         ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2543         ASSERT(db->db_level == 0);
2544         ASSERT3U(dbuf_is_metadata(db), ==, arc_is_metadata(buf));
2545         ASSERT(buf != NULL);
2546         ASSERT3U(arc_buf_lsize(buf), ==, db->db.db_size);
2547         ASSERT(tx->tx_txg != 0);
2548
2549         arc_return_buf(buf, db);
2550         ASSERT(arc_released(buf));
2551
2552         mutex_enter(&db->db_mtx);
2553
2554         while (db->db_state == DB_READ || db->db_state == DB_FILL)
2555                 cv_wait(&db->db_changed, &db->db_mtx);
2556
2557         ASSERT(db->db_state == DB_CACHED || db->db_state == DB_UNCACHED);
2558
2559         if (db->db_state == DB_CACHED &&
2560             zfs_refcount_count(&db->db_holds) - 1 > db->db_dirtycnt) {
2561                 /*
2562                  * In practice, we will never have a case where we have an
2563                  * encrypted arc buffer while additional holds exist on the
2564                  * dbuf. We don't handle this here so we simply assert that
2565                  * fact instead.
2566                  */
2567                 ASSERT(!arc_is_encrypted(buf));
2568                 mutex_exit(&db->db_mtx);
2569                 (void) dbuf_dirty(db, tx);
2570                 bcopy(buf->b_data, db->db.db_data, db->db.db_size);
2571                 arc_buf_destroy(buf, db);
2572                 xuio_stat_wbuf_copied();
2573                 return;
2574         }
2575
2576         xuio_stat_wbuf_nocopy();
2577         if (db->db_state == DB_CACHED) {
2578                 dbuf_dirty_record_t *dr = db->db_last_dirty;
2579
2580                 ASSERT(db->db_buf != NULL);
2581                 if (dr != NULL && dr->dr_txg == tx->tx_txg) {
2582                         ASSERT(dr->dt.dl.dr_data == db->db_buf);
2583
2584                         if (!arc_released(db->db_buf)) {
2585                                 ASSERT(dr->dt.dl.dr_override_state ==
2586                                     DR_OVERRIDDEN);
2587                                 arc_release(db->db_buf, db);
2588                         }
2589                         dr->dt.dl.dr_data = buf;
2590                         arc_buf_destroy(db->db_buf, db);
2591                 } else if (dr == NULL || dr->dt.dl.dr_data != db->db_buf) {
2592                         arc_release(db->db_buf, db);
2593                         arc_buf_destroy(db->db_buf, db);
2594                 }
2595                 db->db_buf = NULL;
2596         }
2597         ASSERT(db->db_buf == NULL);
2598         dbuf_set_data(db, buf);
2599         db->db_state = DB_FILL;
2600         mutex_exit(&db->db_mtx);
2601         (void) dbuf_dirty(db, tx);
2602         dmu_buf_fill_done(&db->db, tx);
2603 }
2604
2605 void
2606 dbuf_destroy(dmu_buf_impl_t *db)
2607 {
2608         dnode_t *dn;
2609         dmu_buf_impl_t *parent = db->db_parent;
2610         dmu_buf_impl_t *dndb;
2611
2612         ASSERT(MUTEX_HELD(&db->db_mtx));
2613         ASSERT(zfs_refcount_is_zero(&db->db_holds));
2614
2615         if (db->db_buf != NULL) {
2616                 arc_buf_destroy(db->db_buf, db);
2617                 db->db_buf = NULL;
2618         }
2619
2620         if (db->db_blkid == DMU_BONUS_BLKID) {
2621                 int slots = DB_DNODE(db)->dn_num_slots;
2622                 int bonuslen = DN_SLOTS_TO_BONUSLEN(slots);
2623                 if (db->db.db_data != NULL) {
2624                         kmem_free(db->db.db_data, bonuslen);
2625                         arc_space_return(bonuslen, ARC_SPACE_BONUS);
2626                         db->db_state = DB_UNCACHED;
2627                 }
2628         }
2629
2630         dbuf_clear_data(db);
2631
2632         if (multilist_link_active(&db->db_cache_link)) {
2633                 ASSERT(db->db_caching_status == DB_DBUF_CACHE ||
2634                     db->db_caching_status == DB_DBUF_METADATA_CACHE);
2635
2636                 multilist_remove(dbuf_caches[db->db_caching_status].cache, db);
2637                 (void) zfs_refcount_remove_many(
2638                     &dbuf_caches[db->db_caching_status].size,
2639                     db->db.db_size, db);
2640
2641                 if (db->db_caching_status == DB_DBUF_METADATA_CACHE) {
2642                         DBUF_STAT_BUMPDOWN(metadata_cache_count);
2643                 } else {
2644                         DBUF_STAT_BUMPDOWN(cache_levels[db->db_level]);
2645                         DBUF_STAT_BUMPDOWN(cache_count);
2646                         DBUF_STAT_DECR(cache_levels_bytes[db->db_level],
2647                             db->db.db_size);
2648                 }
2649                 db->db_caching_status = DB_NO_CACHE;
2650         }
2651
2652         ASSERT(db->db_state == DB_UNCACHED || db->db_state == DB_NOFILL);
2653         ASSERT(db->db_data_pending == NULL);
2654
2655         db->db_state = DB_EVICTING;
2656         db->db_blkptr = NULL;
2657
2658         /*
2659          * Now that db_state is DB_EVICTING, nobody else can find this via
2660          * the hash table.  We can now drop db_mtx, which allows us to
2661          * acquire the dn_dbufs_mtx.
2662          */
2663         mutex_exit(&db->db_mtx);
2664
2665         DB_DNODE_ENTER(db);
2666         dn = DB_DNODE(db);
2667         dndb = dn->dn_dbuf;
2668         if (db->db_blkid != DMU_BONUS_BLKID) {
2669                 boolean_t needlock = !MUTEX_HELD(&dn->dn_dbufs_mtx);
2670                 if (needlock)
2671                         mutex_enter_nested(&dn->dn_dbufs_mtx,
2672                             NESTED_SINGLE);
2673                 avl_remove(&dn->dn_dbufs, db);
2674                 atomic_dec_32(&dn->dn_dbufs_count);
2675                 membar_producer();
2676                 DB_DNODE_EXIT(db);
2677                 if (needlock)
2678                         mutex_exit(&dn->dn_dbufs_mtx);
2679                 /*
2680                  * Decrementing the dbuf count means that the hold corresponding
2681                  * to the removed dbuf is no longer discounted in dnode_move(),
2682                  * so the dnode cannot be moved until after we release the hold.
2683                  * The membar_producer() ensures visibility of the decremented
2684                  * value in dnode_move(), since DB_DNODE_EXIT doesn't actually
2685                  * release any lock.
2686                  */
2687                 mutex_enter(&dn->dn_mtx);
2688                 dnode_rele_and_unlock(dn, db, B_TRUE);
2689                 db->db_dnode_handle = NULL;
2690
2691                 dbuf_hash_remove(db);
2692         } else {
2693                 DB_DNODE_EXIT(db);
2694         }
2695
2696         ASSERT(zfs_refcount_is_zero(&db->db_holds));
2697
2698         db->db_parent = NULL;
2699
2700         ASSERT(db->db_buf == NULL);
2701         ASSERT(db->db.db_data == NULL);
2702         ASSERT(db->db_hash_next == NULL);
2703         ASSERT(db->db_blkptr == NULL);
2704         ASSERT(db->db_data_pending == NULL);
2705         ASSERT3U(db->db_caching_status, ==, DB_NO_CACHE);
2706         ASSERT(!multilist_link_active(&db->db_cache_link));
2707
2708         kmem_cache_free(dbuf_kmem_cache, db);
2709         arc_space_return(sizeof (dmu_buf_impl_t), ARC_SPACE_DBUF);
2710
2711         /*
2712          * If this dbuf is referenced from an indirect dbuf,
2713          * decrement the ref count on the indirect dbuf.
2714          */
2715         if (parent && parent != dndb) {
2716                 mutex_enter(&parent->db_mtx);
2717                 dbuf_rele_and_unlock(parent, db, B_TRUE);
2718         }
2719 }
2720
2721 /*
2722  * Note: While bpp will always be updated if the function returns success,
2723  * parentp will not be updated if the dnode does not have dn_dbuf filled in;
2724  * this happens when the dnode is the meta-dnode, or {user|group|project}used
2725  * object.
2726  */
2727 __attribute__((always_inline))
2728 static inline int
2729 dbuf_findbp(dnode_t *dn, int level, uint64_t blkid, int fail_sparse,
2730     dmu_buf_impl_t **parentp, blkptr_t **bpp)
2731 {
2732         *parentp = NULL;
2733         *bpp = NULL;
2734
2735         ASSERT(blkid != DMU_BONUS_BLKID);
2736
2737         if (blkid == DMU_SPILL_BLKID) {
2738                 mutex_enter(&dn->dn_mtx);
2739                 if (dn->dn_have_spill &&
2740                     (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR))
2741                         *bpp = DN_SPILL_BLKPTR(dn->dn_phys);
2742                 else
2743                         *bpp = NULL;
2744                 dbuf_add_ref(dn->dn_dbuf, NULL);
2745                 *parentp = dn->dn_dbuf;
2746                 mutex_exit(&dn->dn_mtx);
2747                 return (0);
2748         }
2749
2750         int nlevels =
2751             (dn->dn_phys->dn_nlevels == 0) ? 1 : dn->dn_phys->dn_nlevels;
2752         int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
2753
2754         ASSERT3U(level * epbs, <, 64);
2755         ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2756         /*
2757          * This assertion shouldn't trip as long as the max indirect block size
2758          * is less than 1M.  The reason for this is that up to that point,
2759          * the number of levels required to address an entire object with blocks
2760          * of size SPA_MINBLOCKSIZE satisfies nlevels * epbs + 1 <= 64.  In
2761          * other words, if N * epbs + 1 > 64, then if (N-1) * epbs + 1 > 55
2762          * (i.e. we can address the entire object), objects will all use at most
2763          * N-1 levels and the assertion won't overflow.  However, once epbs is
2764          * 13, 4 * 13 + 1 = 53, but 5 * 13 + 1 = 66.  Then, 4 levels will not be
2765          * enough to address an entire object, so objects will have 5 levels,
2766          * but then this assertion will overflow.
2767          *
2768          * All this is to say that if we ever increase DN_MAX_INDBLKSHIFT, we
2769          * need to redo this logic to handle overflows.
2770          */
2771         ASSERT(level >= nlevels ||
2772             ((nlevels - level - 1) * epbs) +
2773             highbit64(dn->dn_phys->dn_nblkptr) <= 64);
2774         if (level >= nlevels ||
2775             blkid >= ((uint64_t)dn->dn_phys->dn_nblkptr <<
2776             ((nlevels - level - 1) * epbs)) ||
2777             (fail_sparse &&
2778             blkid > (dn->dn_phys->dn_maxblkid >> (level * epbs)))) {
2779                 /* the buffer has no parent yet */
2780                 return (SET_ERROR(ENOENT));
2781         } else if (level < nlevels-1) {
2782                 /* this block is referenced from an indirect block */
2783                 int err;
2784
2785                 err = dbuf_hold_impl(dn, level + 1,
2786                     blkid >> epbs, fail_sparse, FALSE, NULL, parentp);
2787
2788                 if (err)
2789                         return (err);
2790                 err = dbuf_read(*parentp, NULL,
2791                     (DB_RF_HAVESTRUCT | DB_RF_NOPREFETCH | DB_RF_CANFAIL));
2792                 if (err) {
2793                         dbuf_rele(*parentp, NULL);
2794                         *parentp = NULL;
2795                         return (err);
2796                 }
2797                 rw_enter(&(*parentp)->db_rwlock, RW_READER);
2798                 *bpp = ((blkptr_t *)(*parentp)->db.db_data) +
2799                     (blkid & ((1ULL << epbs) - 1));
2800                 if (blkid > (dn->dn_phys->dn_maxblkid >> (level * epbs)))
2801                         ASSERT(BP_IS_HOLE(*bpp));
2802                 rw_exit(&(*parentp)->db_rwlock);
2803                 return (0);
2804         } else {
2805                 /* the block is referenced from the dnode */
2806                 ASSERT3U(level, ==, nlevels-1);
2807                 ASSERT(dn->dn_phys->dn_nblkptr == 0 ||
2808                     blkid < dn->dn_phys->dn_nblkptr);
2809                 if (dn->dn_dbuf) {
2810                         dbuf_add_ref(dn->dn_dbuf, NULL);
2811                         *parentp = dn->dn_dbuf;
2812                 }
2813                 *bpp = &dn->dn_phys->dn_blkptr[blkid];
2814                 return (0);
2815         }
2816 }
2817
2818 static dmu_buf_impl_t *
2819 dbuf_create(dnode_t *dn, uint8_t level, uint64_t blkid,
2820     dmu_buf_impl_t *parent, blkptr_t *blkptr)
2821 {
2822         objset_t *os = dn->dn_objset;
2823         dmu_buf_impl_t *db, *odb;
2824
2825         ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2826         ASSERT(dn->dn_type != DMU_OT_NONE);
2827
2828         db = kmem_cache_alloc(dbuf_kmem_cache, KM_SLEEP);
2829
2830         db->db_objset = os;
2831         db->db.db_object = dn->dn_object;
2832         db->db_level = level;
2833         db->db_blkid = blkid;
2834         db->db_last_dirty = NULL;
2835         db->db_dirtycnt = 0;
2836         db->db_dnode_handle = dn->dn_handle;
2837         db->db_parent = parent;
2838         db->db_blkptr = blkptr;
2839
2840         db->db_user = NULL;
2841         db->db_user_immediate_evict = FALSE;
2842         db->db_freed_in_flight = FALSE;
2843         db->db_pending_evict = FALSE;
2844
2845         if (blkid == DMU_BONUS_BLKID) {
2846                 ASSERT3P(parent, ==, dn->dn_dbuf);
2847                 db->db.db_size = DN_SLOTS_TO_BONUSLEN(dn->dn_num_slots) -
2848                     (dn->dn_nblkptr-1) * sizeof (blkptr_t);
2849                 ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
2850                 db->db.db_offset = DMU_BONUS_BLKID;
2851                 db->db_state = DB_UNCACHED;
2852                 db->db_caching_status = DB_NO_CACHE;
2853                 /* the bonus dbuf is not placed in the hash table */
2854                 arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_DBUF);
2855                 return (db);
2856         } else if (blkid == DMU_SPILL_BLKID) {
2857                 db->db.db_size = (blkptr != NULL) ?
2858                     BP_GET_LSIZE(blkptr) : SPA_MINBLOCKSIZE;
2859                 db->db.db_offset = 0;
2860         } else {
2861                 int blocksize =
2862                     db->db_level ? 1 << dn->dn_indblkshift : dn->dn_datablksz;
2863                 db->db.db_size = blocksize;
2864                 db->db.db_offset = db->db_blkid * blocksize;
2865         }
2866
2867         /*
2868          * Hold the dn_dbufs_mtx while we get the new dbuf
2869          * in the hash table *and* added to the dbufs list.
2870          * This prevents a possible deadlock with someone
2871          * trying to look up this dbuf before it's added to the
2872          * dn_dbufs list.
2873          */
2874         mutex_enter(&dn->dn_dbufs_mtx);
2875         db->db_state = DB_EVICTING;
2876         if ((odb = dbuf_hash_insert(db)) != NULL) {
2877                 /* someone else inserted it first */
2878                 kmem_cache_free(dbuf_kmem_cache, db);
2879                 mutex_exit(&dn->dn_dbufs_mtx);
2880                 DBUF_STAT_BUMP(hash_insert_race);
2881                 return (odb);
2882         }
2883         avl_add(&dn->dn_dbufs, db);
2884
2885         db->db_state = DB_UNCACHED;
2886         db->db_caching_status = DB_NO_CACHE;
2887         mutex_exit(&dn->dn_dbufs_mtx);
2888         arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_DBUF);
2889
2890         if (parent && parent != dn->dn_dbuf)
2891                 dbuf_add_ref(parent, db);
2892
2893         ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
2894             zfs_refcount_count(&dn->dn_holds) > 0);
2895         (void) zfs_refcount_add(&dn->dn_holds, db);
2896         atomic_inc_32(&dn->dn_dbufs_count);
2897
2898         dprintf_dbuf(db, "db=%p\n", db);
2899
2900         return (db);
2901 }
2902
2903 /*
2904  * This function returns a block pointer and information about the object,
2905  * given a dnode and a block.  This is a publicly accessible version of
2906  * dbuf_findbp that only returns some information, rather than the
2907  * dbuf.  Note that the dnode passed in must be held, and the dn_struct_rwlock
2908  * should be locked as (at least) a reader.
2909  */
2910 int
2911 dbuf_dnode_findbp(dnode_t *dn, uint64_t level, uint64_t blkid,
2912     blkptr_t *bp, uint16_t *datablkszsec, uint8_t *indblkshift)
2913 {
2914         dmu_buf_impl_t *dbp = NULL;
2915         blkptr_t *bp2;
2916         int err = 0;
2917         ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2918
2919         err = dbuf_findbp(dn, level, blkid, B_FALSE, &dbp, &bp2);
2920         if (err == 0) {
2921                 *bp = *bp2;
2922                 if (dbp != NULL)
2923                         dbuf_rele(dbp, NULL);
2924                 if (datablkszsec != NULL)
2925                         *datablkszsec = dn->dn_phys->dn_datablkszsec;
2926                 if (indblkshift != NULL)
2927                         *indblkshift = dn->dn_phys->dn_indblkshift;
2928         }
2929
2930         return (err);
2931 }
2932
2933 typedef struct dbuf_prefetch_arg {
2934         spa_t *dpa_spa; /* The spa to issue the prefetch in. */
2935         zbookmark_phys_t dpa_zb; /* The target block to prefetch. */
2936         int dpa_epbs; /* Entries (blkptr_t's) Per Block Shift. */
2937         int dpa_curlevel; /* The current level that we're reading */
2938         dnode_t *dpa_dnode; /* The dnode associated with the prefetch */
2939         zio_priority_t dpa_prio; /* The priority I/Os should be issued at. */
2940         zio_t *dpa_zio; /* The parent zio_t for all prefetches. */
2941         arc_flags_t dpa_aflags; /* Flags to pass to the final prefetch. */
2942 } dbuf_prefetch_arg_t;
2943
2944 /*
2945  * Actually issue the prefetch read for the block given.
2946  */
2947 static void
2948 dbuf_issue_final_prefetch(dbuf_prefetch_arg_t *dpa, blkptr_t *bp)
2949 {
2950         ASSERT(!BP_IS_REDACTED(bp) ||
2951             dsl_dataset_feature_is_active(
2952             dpa->dpa_dnode->dn_objset->os_dsl_dataset,
2953             SPA_FEATURE_REDACTED_DATASETS));
2954
2955         if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp) || BP_IS_REDACTED(bp))
2956                 return;
2957
2958         int zio_flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE;
2959         arc_flags_t aflags =
2960             dpa->dpa_aflags | ARC_FLAG_NOWAIT | ARC_FLAG_PREFETCH;
2961
2962         /* dnodes are always read as raw and then converted later */
2963         if (BP_GET_TYPE(bp) == DMU_OT_DNODE && BP_IS_PROTECTED(bp) &&
2964             dpa->dpa_curlevel == 0)
2965                 zio_flags |= ZIO_FLAG_RAW;
2966
2967         ASSERT3U(dpa->dpa_curlevel, ==, BP_GET_LEVEL(bp));
2968         ASSERT3U(dpa->dpa_curlevel, ==, dpa->dpa_zb.zb_level);
2969         ASSERT(dpa->dpa_zio != NULL);
2970         (void) arc_read(dpa->dpa_zio, dpa->dpa_spa, bp, NULL, NULL,
2971             dpa->dpa_prio, zio_flags, &aflags, &dpa->dpa_zb);
2972 }
2973
2974 /*
2975  * Called when an indirect block above our prefetch target is read in.  This
2976  * will either read in the next indirect block down the tree or issue the actual
2977  * prefetch if the next block down is our target.
2978  */
2979 static void
2980 dbuf_prefetch_indirect_done(zio_t *zio, const zbookmark_phys_t *zb,
2981     const blkptr_t *iobp, arc_buf_t *abuf, void *private)
2982 {
2983         dbuf_prefetch_arg_t *dpa = private;
2984
2985         ASSERT3S(dpa->dpa_zb.zb_level, <, dpa->dpa_curlevel);
2986         ASSERT3S(dpa->dpa_curlevel, >, 0);
2987
2988         if (abuf == NULL) {
2989                 ASSERT(zio == NULL || zio->io_error != 0);
2990                 kmem_free(dpa, sizeof (*dpa));
2991                 return;
2992         }
2993         ASSERT(zio == NULL || zio->io_error == 0);
2994
2995         /*
2996          * The dpa_dnode is only valid if we are called with a NULL
2997          * zio. This indicates that the arc_read() returned without
2998          * first calling zio_read() to issue a physical read. Once
2999          * a physical read is made the dpa_dnode must be invalidated
3000          * as the locks guarding it may have been dropped. If the
3001          * dpa_dnode is still valid, then we want to add it to the dbuf
3002          * cache. To do so, we must hold the dbuf associated with the block
3003          * we just prefetched, read its contents so that we associate it
3004          * with an arc_buf_t, and then release it.
3005          */
3006         if (zio != NULL) {
3007                 ASSERT3S(BP_GET_LEVEL(zio->io_bp), ==, dpa->dpa_curlevel);
3008                 if (zio->io_flags & ZIO_FLAG_RAW_COMPRESS) {
3009                         ASSERT3U(BP_GET_PSIZE(zio->io_bp), ==, zio->io_size);
3010                 } else {
3011                         ASSERT3U(BP_GET_LSIZE(zio->io_bp), ==, zio->io_size);
3012                 }
3013                 ASSERT3P(zio->io_spa, ==, dpa->dpa_spa);
3014
3015                 dpa->dpa_dnode = NULL;
3016         } else if (dpa->dpa_dnode != NULL) {
3017                 uint64_t curblkid = dpa->dpa_zb.zb_blkid >>
3018                     (dpa->dpa_epbs * (dpa->dpa_curlevel -
3019                     dpa->dpa_zb.zb_level));
3020                 dmu_buf_impl_t *db = dbuf_hold_level(dpa->dpa_dnode,
3021                     dpa->dpa_curlevel, curblkid, FTAG);
3022                 if (db == NULL) {
3023                         kmem_free(dpa, sizeof (*dpa));
3024                         arc_buf_destroy(abuf, private);
3025                         return;
3026                 }
3027
3028                 (void) dbuf_read(db, NULL,
3029                     DB_RF_MUST_SUCCEED | DB_RF_NOPREFETCH | DB_RF_HAVESTRUCT);
3030                 dbuf_rele(db, FTAG);
3031         }
3032
3033         dpa->dpa_curlevel--;
3034         uint64_t nextblkid = dpa->dpa_zb.zb_blkid >>
3035             (dpa->dpa_epbs * (dpa->dpa_curlevel - dpa->dpa_zb.zb_level));
3036         blkptr_t *bp = ((blkptr_t *)abuf->b_data) +
3037             P2PHASE(nextblkid, 1ULL << dpa->dpa_epbs);
3038
3039         ASSERT(!BP_IS_REDACTED(bp) ||
3040             dsl_dataset_feature_is_active(
3041             dpa->dpa_dnode->dn_objset->os_dsl_dataset,
3042             SPA_FEATURE_REDACTED_DATASETS));
3043         if (BP_IS_HOLE(bp) || BP_IS_REDACTED(bp)) {
3044                 kmem_free(dpa, sizeof (*dpa));
3045         } else if (dpa->dpa_curlevel == dpa->dpa_zb.zb_level) {
3046                 ASSERT3U(nextblkid, ==, dpa->dpa_zb.zb_blkid);
3047                 dbuf_issue_final_prefetch(dpa, bp);
3048                 kmem_free(dpa, sizeof (*dpa));
3049         } else {
3050                 arc_flags_t iter_aflags = ARC_FLAG_NOWAIT;
3051                 zbookmark_phys_t zb;
3052
3053                 /* flag if L2ARC eligible, l2arc_noprefetch then decides */
3054                 if (dpa->dpa_aflags & ARC_FLAG_L2CACHE)
3055                         iter_aflags |= ARC_FLAG_L2CACHE;
3056
3057                 ASSERT3U(dpa->dpa_curlevel, ==, BP_GET_LEVEL(bp));
3058
3059                 SET_BOOKMARK(&zb, dpa->dpa_zb.zb_objset,
3060                     dpa->dpa_zb.zb_object, dpa->dpa_curlevel, nextblkid);
3061
3062                 (void) arc_read(dpa->dpa_zio, dpa->dpa_spa,
3063                     bp, dbuf_prefetch_indirect_done, dpa, dpa->dpa_prio,
3064                     ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
3065                     &iter_aflags, &zb);
3066         }
3067
3068         arc_buf_destroy(abuf, private);
3069 }
3070
3071 /*
3072  * Issue prefetch reads for the given block on the given level.  If the indirect
3073  * blocks above that block are not in memory, we will read them in
3074  * asynchronously.  As a result, this call never blocks waiting for a read to
3075  * complete. Note that the prefetch might fail if the dataset is encrypted and
3076  * the encryption key is unmapped before the IO completes.
3077  */
3078 void
3079 dbuf_prefetch(dnode_t *dn, int64_t level, uint64_t blkid, zio_priority_t prio,
3080     arc_flags_t aflags)
3081 {
3082         blkptr_t bp;
3083         int epbs, nlevels, curlevel;
3084         uint64_t curblkid;
3085
3086         ASSERT(blkid != DMU_BONUS_BLKID);
3087         ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
3088
3089         if (blkid > dn->dn_maxblkid)
3090                 return;
3091
3092         if (level == 0 && dnode_block_freed(dn, blkid))
3093                 return;
3094
3095         /*
3096          * This dnode hasn't been written to disk yet, so there's nothing to
3097          * prefetch.
3098          */
3099         nlevels = dn->dn_phys->dn_nlevels;
3100         if (level >= nlevels || dn->dn_phys->dn_nblkptr == 0)
3101                 return;
3102
3103         epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
3104         if (dn->dn_phys->dn_maxblkid < blkid << (epbs * level))
3105                 return;
3106
3107         dmu_buf_impl_t *db = dbuf_find(dn->dn_objset, dn->dn_object,
3108             level, blkid);
3109         if (db != NULL) {
3110                 mutex_exit(&db->db_mtx);
3111                 /*
3112                  * This dbuf already exists.  It is either CACHED, or
3113                  * (we assume) about to be read or filled.
3114                  */
3115                 return;
3116         }
3117
3118         /*
3119          * Find the closest ancestor (indirect block) of the target block
3120          * that is present in the cache.  In this indirect block, we will
3121          * find the bp that is at curlevel, curblkid.
3122          */
3123         curlevel = level;
3124         curblkid = blkid;
3125         while (curlevel < nlevels - 1) {
3126                 int parent_level = curlevel + 1;
3127                 uint64_t parent_blkid = curblkid >> epbs;
3128                 dmu_buf_impl_t *db;
3129
3130                 if (dbuf_hold_impl(dn, parent_level, parent_blkid,
3131                     FALSE, TRUE, FTAG, &db) == 0) {
3132                         blkptr_t *bpp = db->db_buf->b_data;
3133                         bp = bpp[P2PHASE(curblkid, 1 << epbs)];
3134                         dbuf_rele(db, FTAG);
3135                         break;
3136                 }
3137
3138                 curlevel = parent_level;
3139                 curblkid = parent_blkid;
3140         }
3141
3142         if (curlevel == nlevels - 1) {
3143                 /* No cached indirect blocks found. */
3144                 ASSERT3U(curblkid, <, dn->dn_phys->dn_nblkptr);
3145                 bp = dn->dn_phys->dn_blkptr[curblkid];
3146         }
3147         ASSERT(!BP_IS_REDACTED(&bp) ||
3148             dsl_dataset_feature_is_active(dn->dn_objset->os_dsl_dataset,
3149             SPA_FEATURE_REDACTED_DATASETS));
3150         if (BP_IS_HOLE(&bp) || BP_IS_REDACTED(&bp))
3151                 return;
3152
3153         ASSERT3U(curlevel, ==, BP_GET_LEVEL(&bp));
3154
3155         zio_t *pio = zio_root(dmu_objset_spa(dn->dn_objset), NULL, NULL,
3156             ZIO_FLAG_CANFAIL);
3157
3158         dbuf_prefetch_arg_t *dpa = kmem_zalloc(sizeof (*dpa), KM_SLEEP);
3159         dsl_dataset_t *ds = dn->dn_objset->os_dsl_dataset;
3160         SET_BOOKMARK(&dpa->dpa_zb, ds != NULL ? ds->ds_object : DMU_META_OBJSET,
3161             dn->dn_object, level, blkid);
3162         dpa->dpa_curlevel = curlevel;
3163         dpa->dpa_prio = prio;
3164         dpa->dpa_aflags = aflags;
3165         dpa->dpa_spa = dn->dn_objset->os_spa;
3166         dpa->dpa_dnode = dn;
3167         dpa->dpa_epbs = epbs;
3168         dpa->dpa_zio = pio;
3169
3170         /* flag if L2ARC eligible, l2arc_noprefetch then decides */
3171         if (DNODE_LEVEL_IS_L2CACHEABLE(dn, level))
3172                 dpa->dpa_aflags |= ARC_FLAG_L2CACHE;
3173
3174         /*
3175          * If we have the indirect just above us, no need to do the asynchronous
3176          * prefetch chain; we'll just run the last step ourselves.  If we're at
3177          * a higher level, though, we want to issue the prefetches for all the
3178          * indirect blocks asynchronously, so we can go on with whatever we were
3179          * doing.
3180          */
3181         if (curlevel == level) {
3182                 ASSERT3U(curblkid, ==, blkid);
3183                 dbuf_issue_final_prefetch(dpa, &bp);
3184                 kmem_free(dpa, sizeof (*dpa));
3185         } else {
3186                 arc_flags_t iter_aflags = ARC_FLAG_NOWAIT;
3187                 zbookmark_phys_t zb;
3188
3189                 /* flag if L2ARC eligible, l2arc_noprefetch then decides */
3190                 if (DNODE_LEVEL_IS_L2CACHEABLE(dn, level))
3191                         iter_aflags |= ARC_FLAG_L2CACHE;
3192
3193                 SET_BOOKMARK(&zb, ds != NULL ? ds->ds_object : DMU_META_OBJSET,
3194                     dn->dn_object, curlevel, curblkid);
3195                 (void) arc_read(dpa->dpa_zio, dpa->dpa_spa,
3196                     &bp, dbuf_prefetch_indirect_done, dpa, prio,
3197                     ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
3198                     &iter_aflags, &zb);
3199         }
3200         /*
3201          * We use pio here instead of dpa_zio since it's possible that
3202          * dpa may have already been freed.
3203          */
3204         zio_nowait(pio);
3205 }
3206
3207 /*
3208  * Helper function for dbuf_hold_impl() to copy a buffer. Handles
3209  * the case of encrypted, compressed and uncompressed buffers by
3210  * allocating the new buffer, respectively, with arc_alloc_raw_buf(),
3211  * arc_alloc_compressed_buf() or arc_alloc_buf().*
3212  *
3213  * NOTE: Declared noinline to avoid stack bloat in dbuf_hold_impl().
3214  */
3215 noinline static void
3216 dbuf_hold_copy(dnode_t *dn, dmu_buf_impl_t *db)
3217 {
3218         dbuf_dirty_record_t *dr = db->db_data_pending;
3219         arc_buf_t *data = dr->dt.dl.dr_data;
3220         enum zio_compress compress_type = arc_get_compression(data);
3221
3222         if (arc_is_encrypted(data)) {
3223                 boolean_t byteorder;
3224                 uint8_t salt[ZIO_DATA_SALT_LEN];
3225                 uint8_t iv[ZIO_DATA_IV_LEN];
3226                 uint8_t mac[ZIO_DATA_MAC_LEN];
3227
3228                 arc_get_raw_params(data, &byteorder, salt, iv, mac);
3229                 dbuf_set_data(db, arc_alloc_raw_buf(dn->dn_objset->os_spa, db,
3230                     dmu_objset_id(dn->dn_objset), byteorder, salt, iv, mac,
3231                     dn->dn_type, arc_buf_size(data), arc_buf_lsize(data),
3232                     compress_type));
3233         } else if (compress_type != ZIO_COMPRESS_OFF) {
3234                 dbuf_set_data(db, arc_alloc_compressed_buf(
3235                     dn->dn_objset->os_spa, db, arc_buf_size(data),
3236                     arc_buf_lsize(data), compress_type));
3237         } else {
3238                 dbuf_set_data(db, arc_alloc_buf(dn->dn_objset->os_spa, db,
3239                     DBUF_GET_BUFC_TYPE(db), db->db.db_size));
3240         }
3241
3242         rw_enter(&db->db_rwlock, RW_WRITER);
3243         bcopy(data->b_data, db->db.db_data, arc_buf_size(data));
3244         rw_exit(&db->db_rwlock);
3245 }
3246
3247 /*
3248  * Returns with db_holds incremented, and db_mtx not held.
3249  * Note: dn_struct_rwlock must be held.
3250  */
3251 int
3252 dbuf_hold_impl(dnode_t *dn, uint8_t level, uint64_t blkid,
3253     boolean_t fail_sparse, boolean_t fail_uncached,
3254     void *tag, dmu_buf_impl_t **dbp)
3255 {
3256         dmu_buf_impl_t *db, *parent = NULL;
3257
3258         /* If the pool has been created, verify the tx_sync_lock is not held */
3259         spa_t *spa = dn->dn_objset->os_spa;
3260         dsl_pool_t *dp = spa->spa_dsl_pool;
3261         if (dp != NULL) {
3262                 ASSERT(!MUTEX_HELD(&dp->dp_tx.tx_sync_lock));
3263         }
3264
3265         ASSERT(blkid != DMU_BONUS_BLKID);
3266         ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
3267         ASSERT3U(dn->dn_nlevels, >, level);
3268
3269         *dbp = NULL;
3270
3271         /* dbuf_find() returns with db_mtx held */
3272         db = dbuf_find(dn->dn_objset, dn->dn_object, level, blkid);
3273
3274         if (db == NULL) {
3275                 blkptr_t *bp = NULL;
3276                 int err;
3277
3278                 if (fail_uncached)
3279                         return (SET_ERROR(ENOENT));
3280
3281                 ASSERT3P(parent, ==, NULL);
3282                 err = dbuf_findbp(dn, level, blkid, fail_sparse, &parent, &bp);
3283                 if (fail_sparse) {
3284                         if (err == 0 && bp && BP_IS_HOLE(bp))
3285                                 err = SET_ERROR(ENOENT);
3286                         if (err) {
3287                                 if (parent)
3288                                         dbuf_rele(parent, NULL);
3289                                 return (err);
3290                         }
3291                 }
3292                 if (err && err != ENOENT)
3293                         return (err);
3294                 db = dbuf_create(dn, level, blkid, parent, bp);
3295         }
3296
3297         if (fail_uncached && db->db_state != DB_CACHED) {
3298                 mutex_exit(&db->db_mtx);
3299                 return (SET_ERROR(ENOENT));
3300         }
3301
3302         if (db->db_buf != NULL) {
3303                 arc_buf_access(db->db_buf);
3304                 ASSERT3P(db->db.db_data, ==, db->db_buf->b_data);
3305         }
3306
3307         ASSERT(db->db_buf == NULL || arc_referenced(db->db_buf));
3308
3309         /*
3310          * If this buffer is currently syncing out, and we are
3311          * still referencing it from db_data, we need to make a copy
3312          * of it in case we decide we want to dirty it again in this txg.
3313          */
3314         if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
3315             dn->dn_object != DMU_META_DNODE_OBJECT &&
3316             db->db_state == DB_CACHED && db->db_data_pending) {
3317                 dbuf_dirty_record_t *dr = db->db_data_pending;
3318                 if (dr->dt.dl.dr_data == db->db_buf)
3319                         dbuf_hold_copy(dn, db);
3320         }
3321
3322         if (multilist_link_active(&db->db_cache_link)) {
3323                 ASSERT(zfs_refcount_is_zero(&db->db_holds));
3324                 ASSERT(db->db_caching_status == DB_DBUF_CACHE ||
3325                     db->db_caching_status == DB_DBUF_METADATA_CACHE);
3326
3327                 multilist_remove(dbuf_caches[db->db_caching_status].cache, db);
3328                 (void) zfs_refcount_remove_many(
3329                     &dbuf_caches[db->db_caching_status].size,
3330                     db->db.db_size, db);
3331
3332                 if (db->db_caching_status == DB_DBUF_METADATA_CACHE) {
3333                         DBUF_STAT_BUMPDOWN(metadata_cache_count);
3334                 } else {
3335                         DBUF_STAT_BUMPDOWN(cache_levels[db->db_level]);
3336                         DBUF_STAT_BUMPDOWN(cache_count);
3337                         DBUF_STAT_DECR(cache_levels_bytes[db->db_level],
3338                             db->db.db_size);
3339                 }
3340                 db->db_caching_status = DB_NO_CACHE;
3341         }
3342         (void) zfs_refcount_add(&db->db_holds, tag);
3343         DBUF_VERIFY(db);
3344         mutex_exit(&db->db_mtx);
3345
3346         /* NOTE: we can't rele the parent until after we drop the db_mtx */
3347         if (parent)
3348                 dbuf_rele(parent, NULL);
3349
3350         ASSERT3P(DB_DNODE(db), ==, dn);
3351         ASSERT3U(db->db_blkid, ==, blkid);
3352         ASSERT3U(db->db_level, ==, level);
3353         *dbp = db;
3354
3355         return (0);
3356 }
3357
3358 dmu_buf_impl_t *
3359 dbuf_hold(dnode_t *dn, uint64_t blkid, void *tag)
3360 {
3361         return (dbuf_hold_level(dn, 0, blkid, tag));
3362 }
3363
3364 dmu_buf_impl_t *
3365 dbuf_hold_level(dnode_t *dn, int level, uint64_t blkid, void *tag)
3366 {
3367         dmu_buf_impl_t *db;
3368         int err = dbuf_hold_impl(dn, level, blkid, FALSE, FALSE, tag, &db);
3369         return (err ? NULL : db);
3370 }
3371
3372 void
3373 dbuf_create_bonus(dnode_t *dn)
3374 {
3375         ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
3376
3377         ASSERT(dn->dn_bonus == NULL);
3378         dn->dn_bonus = dbuf_create(dn, 0, DMU_BONUS_BLKID, dn->dn_dbuf, NULL);
3379 }
3380
3381 int
3382 dbuf_spill_set_blksz(dmu_buf_t *db_fake, uint64_t blksz, dmu_tx_t *tx)
3383 {
3384         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
3385
3386         if (db->db_blkid != DMU_SPILL_BLKID)
3387                 return (SET_ERROR(ENOTSUP));
3388         if (blksz == 0)
3389                 blksz = SPA_MINBLOCKSIZE;
3390         ASSERT3U(blksz, <=, spa_maxblocksize(dmu_objset_spa(db->db_objset)));
3391         blksz = P2ROUNDUP(blksz, SPA_MINBLOCKSIZE);
3392
3393         dbuf_new_size(db, blksz, tx);
3394
3395         return (0);
3396 }
3397
3398 void
3399 dbuf_rm_spill(dnode_t *dn, dmu_tx_t *tx)
3400 {
3401         dbuf_free_range(dn, DMU_SPILL_BLKID, DMU_SPILL_BLKID, tx);
3402 }
3403
3404 #pragma weak dmu_buf_add_ref = dbuf_add_ref
3405 void
3406 dbuf_add_ref(dmu_buf_impl_t *db, void *tag)
3407 {
3408         int64_t holds = zfs_refcount_add(&db->db_holds, tag);
3409         VERIFY3S(holds, >, 1);
3410 }
3411
3412 #pragma weak dmu_buf_try_add_ref = dbuf_try_add_ref
3413 boolean_t
3414 dbuf_try_add_ref(dmu_buf_t *db_fake, objset_t *os, uint64_t obj, uint64_t blkid,
3415     void *tag)
3416 {
3417         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
3418         dmu_buf_impl_t *found_db;
3419         boolean_t result = B_FALSE;
3420
3421         if (blkid == DMU_BONUS_BLKID)
3422                 found_db = dbuf_find_bonus(os, obj);
3423         else
3424                 found_db = dbuf_find(os, obj, 0, blkid);
3425
3426         if (found_db != NULL) {
3427                 if (db == found_db && dbuf_refcount(db) > db->db_dirtycnt) {
3428                         (void) zfs_refcount_add(&db->db_holds, tag);
3429                         result = B_TRUE;
3430                 }
3431                 mutex_exit(&found_db->db_mtx);
3432         }
3433         return (result);
3434 }
3435
3436 /*
3437  * If you call dbuf_rele() you had better not be referencing the dnode handle
3438  * unless you have some other direct or indirect hold on the dnode. (An indirect
3439  * hold is a hold on one of the dnode's dbufs, including the bonus buffer.)
3440  * Without that, the dbuf_rele() could lead to a dnode_rele() followed by the
3441  * dnode's parent dbuf evicting its dnode handles.
3442  */
3443 void
3444 dbuf_rele(dmu_buf_impl_t *db, void *tag)
3445 {
3446         mutex_enter(&db->db_mtx);
3447         dbuf_rele_and_unlock(db, tag, B_FALSE);
3448 }
3449
3450 void
3451 dmu_buf_rele(dmu_buf_t *db, void *tag)
3452 {
3453         dbuf_rele((dmu_buf_impl_t *)db, tag);
3454 }
3455
3456 /*
3457  * dbuf_rele() for an already-locked dbuf.  This is necessary to allow
3458  * db_dirtycnt and db_holds to be updated atomically.  The 'evicting'
3459  * argument should be set if we are already in the dbuf-evicting code
3460  * path, in which case we don't want to recursively evict.  This allows us to
3461  * avoid deeply nested stacks that would have a call flow similar to this:
3462  *
3463  * dbuf_rele()-->dbuf_rele_and_unlock()-->dbuf_evict_notify()
3464  *      ^                                               |
3465  *      |                                               |
3466  *      +-----dbuf_destroy()<--dbuf_evict_one()<--------+
3467  *
3468  */
3469 void
3470 dbuf_rele_and_unlock(dmu_buf_impl_t *db, void *tag, boolean_t evicting)
3471 {
3472         int64_t holds;
3473
3474         ASSERT(MUTEX_HELD(&db->db_mtx));
3475         DBUF_VERIFY(db);
3476
3477         /*
3478          * Remove the reference to the dbuf before removing its hold on the
3479          * dnode so we can guarantee in dnode_move() that a referenced bonus
3480          * buffer has a corresponding dnode hold.
3481          */
3482         holds = zfs_refcount_remove(&db->db_holds, tag);
3483         ASSERT(holds >= 0);
3484
3485         /*
3486          * We can't freeze indirects if there is a possibility that they
3487          * may be modified in the current syncing context.
3488          */
3489         if (db->db_buf != NULL &&
3490             holds == (db->db_level == 0 ? db->db_dirtycnt : 0)) {
3491                 arc_buf_freeze(db->db_buf);
3492         }
3493
3494         if (holds == db->db_dirtycnt &&
3495             db->db_level == 0 && db->db_user_immediate_evict)
3496                 dbuf_evict_user(db);
3497
3498         if (holds == 0) {
3499                 if (db->db_blkid == DMU_BONUS_BLKID) {
3500                         dnode_t *dn;
3501                         boolean_t evict_dbuf = db->db_pending_evict;
3502
3503                         /*
3504                          * If the dnode moves here, we cannot cross this
3505                          * barrier until the move completes.
3506                          */
3507                         DB_DNODE_ENTER(db);
3508
3509                         dn = DB_DNODE(db);
3510                         atomic_dec_32(&dn->dn_dbufs_count);
3511
3512                         /*
3513                          * Decrementing the dbuf count means that the bonus
3514                          * buffer's dnode hold is no longer discounted in
3515                          * dnode_move(). The dnode cannot move until after
3516                          * the dnode_rele() below.
3517                          */
3518                         DB_DNODE_EXIT(db);
3519
3520                         /*
3521                          * Do not reference db after its lock is dropped.
3522                          * Another thread may evict it.
3523                          */
3524                         mutex_exit(&db->db_mtx);
3525
3526                         if (evict_dbuf)
3527                                 dnode_evict_bonus(dn);
3528
3529                         dnode_rele(dn, db);
3530                 } else if (db->db_buf == NULL) {
3531                         /*
3532                          * This is a special case: we never associated this
3533                          * dbuf with any data allocated from the ARC.
3534                          */
3535                         ASSERT(db->db_state == DB_UNCACHED ||
3536                             db->db_state == DB_NOFILL);
3537                         dbuf_destroy(db);
3538                 } else if (arc_released(db->db_buf)) {
3539                         /*
3540                          * This dbuf has anonymous data associated with it.
3541                          */
3542                         dbuf_destroy(db);
3543                 } else {
3544                         boolean_t do_arc_evict = B_FALSE;
3545                         blkptr_t bp;
3546                         spa_t *spa = dmu_objset_spa(db->db_objset);
3547
3548                         if (!DBUF_IS_CACHEABLE(db) &&
3549                             db->db_blkptr != NULL &&
3550                             !BP_IS_HOLE(db->db_blkptr) &&
3551                             !BP_IS_EMBEDDED(db->db_blkptr)) {
3552                                 do_arc_evict = B_TRUE;
3553                                 bp = *db->db_blkptr;
3554                         }
3555
3556                         if (!DBUF_IS_CACHEABLE(db) ||
3557                             db->db_pending_evict) {
3558                                 dbuf_destroy(db);
3559                         } else if (!multilist_link_active(&db->db_cache_link)) {
3560                                 ASSERT3U(db->db_caching_status, ==,
3561                                     DB_NO_CACHE);
3562
3563                                 dbuf_cached_state_t dcs =
3564                                     dbuf_include_in_metadata_cache(db) ?
3565                                     DB_DBUF_METADATA_CACHE : DB_DBUF_CACHE;
3566                                 db->db_caching_status = dcs;
3567
3568                                 multilist_insert(dbuf_caches[dcs].cache, db);
3569                                 (void) zfs_refcount_add_many(
3570                                     &dbuf_caches[dcs].size,
3571                                     db->db.db_size, db);
3572
3573                                 if (dcs == DB_DBUF_METADATA_CACHE) {
3574                                         DBUF_STAT_BUMP(metadata_cache_count);
3575                                         DBUF_STAT_MAX(
3576                                             metadata_cache_size_bytes_max,
3577                                             zfs_refcount_count(
3578                                             &dbuf_caches[dcs].size));
3579                                 } else {
3580                                         DBUF_STAT_BUMP(
3581                                             cache_levels[db->db_level]);
3582                                         DBUF_STAT_BUMP(cache_count);
3583                                         DBUF_STAT_INCR(
3584                                             cache_levels_bytes[db->db_level],
3585                                             db->db.db_size);
3586                                         DBUF_STAT_MAX(cache_size_bytes_max,
3587                                             zfs_refcount_count(
3588                                             &dbuf_caches[dcs].size));
3589                                 }
3590                                 mutex_exit(&db->db_mtx);
3591
3592                                 if (db->db_caching_status == DB_DBUF_CACHE &&
3593                                     !evicting) {
3594                                         dbuf_evict_notify();
3595                                 }
3596                         }
3597
3598                         if (do_arc_evict)
3599                                 arc_freed(spa, &bp);
3600                 }
3601         } else {
3602                 mutex_exit(&db->db_mtx);
3603         }
3604
3605 }
3606
3607 #pragma weak dmu_buf_refcount = dbuf_refcount
3608 uint64_t
3609 dbuf_refcount(dmu_buf_impl_t *db)
3610 {
3611         return (zfs_refcount_count(&db->db_holds));
3612 }
3613
3614 uint64_t
3615 dmu_buf_user_refcount(dmu_buf_t *db_fake)
3616 {
3617         uint64_t holds;
3618         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
3619
3620         mutex_enter(&db->db_mtx);
3621         ASSERT3U(zfs_refcount_count(&db->db_holds), >=, db->db_dirtycnt);
3622         holds = zfs_refcount_count(&db->db_holds) - db->db_dirtycnt;
3623         mutex_exit(&db->db_mtx);
3624
3625         return (holds);
3626 }
3627
3628 void *
3629 dmu_buf_replace_user(dmu_buf_t *db_fake, dmu_buf_user_t *old_user,
3630     dmu_buf_user_t *new_user)
3631 {
3632         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
3633
3634         mutex_enter(&db->db_mtx);
3635         dbuf_verify_user(db, DBVU_NOT_EVICTING);
3636         if (db->db_user == old_user)
3637                 db->db_user = new_user;
3638         else
3639                 old_user = db->db_user;
3640         dbuf_verify_user(db, DBVU_NOT_EVICTING);
3641         mutex_exit(&db->db_mtx);
3642
3643         return (old_user);
3644 }
3645
3646 void *
3647 dmu_buf_set_user(dmu_buf_t *db_fake, dmu_buf_user_t *user)
3648 {
3649         return (dmu_buf_replace_user(db_fake, NULL, user));
3650 }
3651
3652 void *
3653 dmu_buf_set_user_ie(dmu_buf_t *db_fake, dmu_buf_user_t *user)
3654 {
3655         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
3656
3657         db->db_user_immediate_evict = TRUE;
3658         return (dmu_buf_set_user(db_fake, user));
3659 }
3660
3661 void *
3662 dmu_buf_remove_user(dmu_buf_t *db_fake, dmu_buf_user_t *user)
3663 {
3664         return (dmu_buf_replace_user(db_fake, user, NULL));
3665 }
3666
3667 void *
3668 dmu_buf_get_user(dmu_buf_t *db_fake)
3669 {
3670         dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
3671
3672         dbuf_verify_user(db, DBVU_NOT_EVICTING);
3673         return (db->db_user);
3674 }
3675
3676 void
3677 dmu_buf_user_evict_wait()
3678 {
3679         taskq_wait(dbu_evict_taskq);
3680 }
3681
3682 blkptr_t *
3683 dmu_buf_get_blkptr(dmu_buf_t *db)
3684 {
3685         dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
3686         return (dbi->db_blkptr);
3687 }
3688
3689 objset_t *
3690 dmu_buf_get_objset(dmu_buf_t *db)
3691 {
3692         dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
3693         return (dbi->db_objset);
3694 }
3695
3696 dnode_t *
3697 dmu_buf_dnode_enter(dmu_buf_t *db)
3698 {
3699         dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
3700         DB_DNODE_ENTER(dbi);
3701         return (DB_DNODE(dbi));
3702 }
3703
3704 void
3705 dmu_buf_dnode_exit(dmu_buf_t *db)
3706 {
3707         dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
3708         DB_DNODE_EXIT(dbi);
3709 }
3710
3711 static void
3712 dbuf_check_blkptr(dnode_t *dn, dmu_buf_impl_t *db)
3713 {
3714         /* ASSERT(dmu_tx_is_syncing(tx) */
3715         ASSERT(MUTEX_HELD(&db->db_mtx));
3716
3717         if (db->db_blkptr != NULL)
3718                 return;
3719
3720         if (db->db_blkid == DMU_SPILL_BLKID) {
3721                 db->db_blkptr = DN_SPILL_BLKPTR(dn->dn_phys);
3722                 BP_ZERO(db->db_blkptr);
3723                 return;
3724         }
3725         if (db->db_level == dn->dn_phys->dn_nlevels-1) {
3726                 /*
3727                  * This buffer was allocated at a time when there was
3728                  * no available blkptrs from the dnode, or it was
3729                  * inappropriate to hook it in (i.e., nlevels mismatch).
3730                  */
3731                 ASSERT(db->db_blkid < dn->dn_phys->dn_nblkptr);
3732                 ASSERT(db->db_parent == NULL);
3733                 db->db_parent = dn->dn_dbuf;
3734                 db->db_blkptr = &dn->dn_phys->dn_blkptr[db->db_blkid];
3735                 DBUF_VERIFY(db);
3736         } else {
3737                 dmu_buf_impl_t *parent = db->db_parent;
3738                 int epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
3739
3740                 ASSERT(dn->dn_phys->dn_nlevels > 1);
3741                 if (parent == NULL) {
3742                         mutex_exit(&db->db_mtx);
3743                         rw_enter(&dn->dn_struct_rwlock, RW_READER);
3744                         parent = dbuf_hold_level(dn, db->db_level + 1,
3745                             db->db_blkid >> epbs, db);
3746                         rw_exit(&dn->dn_struct_rwlock);
3747                         mutex_enter(&db->db_mtx);
3748                         db->db_parent = parent;
3749                 }
3750                 db->db_blkptr = (blkptr_t *)parent->db.db_data +
3751                     (db->db_blkid & ((1ULL << epbs) - 1));
3752                 DBUF_VERIFY(db);
3753         }
3754 }
3755
3756 /*
3757  * When syncing out a blocks of dnodes, adjust the block to deal with
3758  * encryption.  Normally, we make sure the block is decrypted before writing
3759  * it.  If we have crypt params, then we are writing a raw (encrypted) block,
3760  * from a raw receive.  In this case, set the ARC buf's crypt params so
3761  * that the BP will be filled with the correct byteorder, salt, iv, and mac.
3762  */
3763 static void
3764 dbuf_prepare_encrypted_dnode_leaf(dbuf_dirty_record_t *dr)
3765 {
3766         int err;
3767         dmu_buf_impl_t *db = dr->dr_dbuf;
3768
3769         ASSERT(MUTEX_HELD(&db->db_mtx));
3770         ASSERT3U(db->db.db_object, ==, DMU_META_DNODE_OBJECT);
3771         ASSERT3U(db->db_level, ==, 0);
3772
3773         if (!db->db_objset->os_raw_receive && arc_is_encrypted(db->db_buf)) {
3774                 zbookmark_phys_t zb;
3775
3776                 /*
3777                  * Unfortunately, there is currently no mechanism for
3778                  * syncing context to handle decryption errors. An error
3779                  * here is only possible if an attacker maliciously
3780                  * changed a dnode block and updated the associated
3781                  * checksums going up the block tree.
3782                  */
3783                 SET_BOOKMARK(&zb, dmu_objset_id(db->db_objset),
3784                     db->db.db_object, db->db_level, db->db_blkid);
3785                 err = arc_untransform(db->db_buf, db->db_objset->os_spa,
3786                     &zb, B_TRUE);
3787                 if (err)
3788                         panic("Invalid dnode block MAC");
3789         } else if (dr->dt.dl.dr_has_raw_params) {
3790                 (void) arc_release(dr->dt.dl.dr_data, db);
3791                 arc_convert_to_raw(dr->dt.dl.dr_data,
3792                     dmu_objset_id(db->db_objset),
3793                     dr->dt.dl.dr_byteorder, DMU_OT_DNODE,
3794                     dr->dt.dl.dr_salt, dr->dt.dl.dr_iv, dr->dt.dl.dr_mac);
3795         }
3796 }
3797
3798 /*
3799  * dbuf_sync_indirect() is called recursively from dbuf_sync_list() so it
3800  * is critical the we not allow the compiler to inline this function in to
3801  * dbuf_sync_list() thereby drastically bloating the stack usage.
3802  */
3803 noinline static void
3804 dbuf_sync_indirect(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
3805 {
3806         dmu_buf_impl_t *db = dr->dr_dbuf;
3807         dnode_t *dn;
3808         zio_t *zio;
3809
3810         ASSERT(dmu_tx_is_syncing(tx));
3811
3812         dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
3813
3814         mutex_enter(&db->db_mtx);
3815
3816         ASSERT(db->db_level > 0);
3817         DBUF_VERIFY(db);
3818
3819         /* Read the block if it hasn't been read yet. */
3820         if (db->db_buf == NULL) {
3821                 mutex_exit(&db->db_mtx);
3822                 (void) dbuf_read(db, NULL, DB_RF_MUST_SUCCEED);
3823                 mutex_enter(&db->db_mtx);
3824         }
3825         ASSERT3U(db->db_state, ==, DB_CACHED);
3826         ASSERT(db->db_buf != NULL);
3827
3828         DB_DNODE_ENTER(db);
3829         dn = DB_DNODE(db);
3830         /* Indirect block size must match what the dnode thinks it is. */
3831         ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
3832         dbuf_check_blkptr(dn, db);
3833         DB_DNODE_EXIT(db);
3834
3835         /* Provide the pending dirty record to child dbufs */
3836         db->db_data_pending = dr;
3837
3838         mutex_exit(&db->db_mtx);
3839
3840         dbuf_write(dr, db->db_buf, tx);
3841
3842         zio = dr->dr_zio;
3843         mutex_enter(&dr->dt.di.dr_mtx);
3844         dbuf_sync_list(&dr->dt.di.dr_children, db->db_level - 1, tx);
3845         ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
3846         mutex_exit(&dr->dt.di.dr_mtx);
3847         zio_nowait(zio);
3848 }
3849
3850 #ifdef ZFS_DEBUG
3851 /*
3852  * Verify that the size of the data in our bonus buffer does not exceed
3853  * its recorded size.
3854  *
3855  * The purpose of this verification is to catch any cases in development
3856  * where the size of a phys structure (i.e space_map_phys_t) grows and,
3857  * due to incorrect feature management, older pools expect to read more
3858  * data even though they didn't actually write it to begin with.
3859  *
3860  * For a example, this would catch an error in the feature logic where we
3861  * open an older pool and we expect to write the space map histogram of
3862  * a space map with size SPACE_MAP_SIZE_V0.
3863  */
3864 static void
3865 dbuf_sync_leaf_verify_bonus_dnode(dbuf_dirty_record_t *dr)
3866 {
3867         dnode_t *dn = DB_DNODE(dr->dr_dbuf);
3868
3869         /*
3870          * Encrypted bonus buffers can have data past their bonuslen.
3871          * Skip the verification of these blocks.
3872          */
3873         if (DMU_OT_IS_ENCRYPTED(dn->dn_bonustype))
3874                 return;
3875
3876         uint16_t bonuslen = dn->dn_phys->dn_bonuslen;
3877         uint16_t maxbonuslen = DN_SLOTS_TO_BONUSLEN(dn->dn_num_slots);
3878         ASSERT3U(bonuslen, <=, maxbonuslen);
3879
3880         arc_buf_t *datap = dr->dt.dl.dr_data;
3881         char *datap_end = ((char *)datap) + bonuslen;
3882         char *datap_max = ((char *)datap) + maxbonuslen;
3883
3884         /* ensure that everything is zero after our data */
3885         for (; datap_end < datap_max; datap_end++)
3886                 ASSERT(*datap_end == 0);
3887 }
3888 #endif
3889
3890 /*
3891  * dbuf_sync_leaf() is called recursively from dbuf_sync_list() so it is
3892  * critical the we not allow the compiler to inline this function in to
3893  * dbuf_sync_list() thereby drastically bloating the stack usage.
3894  */
3895 noinline static void
3896 dbuf_sync_leaf(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
3897 {
3898         arc_buf_t **datap = &dr->dt.dl.dr_data;
3899         dmu_buf_impl_t *db = dr->dr_dbuf;
3900         dnode_t *dn;
3901         objset_t *os;
3902         uint64_t txg = tx->tx_txg;
3903
3904         ASSERT(dmu_tx_is_syncing(tx));
3905
3906         dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
3907
3908         mutex_enter(&db->db_mtx);
3909         /*
3910          * To be synced, we must be dirtied.  But we
3911          * might have been freed after the dirty.
3912          */
3913         if (db->db_state == DB_UNCACHED) {
3914                 /* This buffer has been freed since it was dirtied */
3915                 ASSERT(db->db.db_data == NULL);
3916         } else if (db->db_state == DB_FILL) {
3917                 /* This buffer was freed and is now being re-filled */
3918                 ASSERT(db->db.db_data != dr->dt.dl.dr_data);
3919         } else {
3920                 ASSERT(db->db_state == DB_CACHED || db->db_state == DB_NOFILL);
3921         }
3922         DBUF_VERIFY(db);
3923
3924         DB_DNODE_ENTER(db);
3925         dn = DB_DNODE(db);
3926
3927         if (db->db_blkid == DMU_SPILL_BLKID) {
3928                 mutex_enter(&dn->dn_mtx);
3929                 if (!(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR)) {
3930                         /*
3931                          * In the previous transaction group, the bonus buffer
3932                          * was entirely used to store the attributes for the
3933                          * dnode which overrode the dn_spill field.  However,
3934                          * when adding more attributes to the file a spill
3935                          * block was required to hold the extra attributes.
3936                          *
3937                          * Make sure to clear the garbage left in the dn_spill
3938                          * field from the previous attributes in the bonus
3939                          * buffer.  Otherwise, after writing out the spill
3940                          * block to the new allocated dva, it will free
3941                          * the old block pointed to by the invalid dn_spill.
3942                          */
3943                         db->db_blkptr = NULL;
3944                 }
3945                 dn->dn_phys->dn_flags |= DNODE_FLAG_SPILL_BLKPTR;
3946                 mutex_exit(&dn->dn_mtx);
3947         }
3948
3949         /*
3950          * If this is a bonus buffer, simply copy the bonus data into the
3951          * dnode.  It will be written out when the dnode is synced (and it
3952          * will be synced, since it must have been dirty for dbuf_sync to
3953          * be called).
3954          */
3955         if (db->db_blkid == DMU_BONUS_BLKID) {
3956                 dbuf_dirty_record_t **drp;
3957
3958                 ASSERT(*datap != NULL);
3959                 ASSERT0(db->db_level);
3960                 ASSERT3U(DN_MAX_BONUS_LEN(dn->dn_phys), <=,
3961                     DN_SLOTS_TO_BONUSLEN(dn->dn_phys->dn_extra_slots + 1));
3962                 bcopy(*datap, DN_BONUS(dn->dn_phys),
3963                     DN_MAX_BONUS_LEN(dn->dn_phys));
3964                 DB_DNODE_EXIT(db);
3965
3966 #ifdef ZFS_DEBUG
3967                 dbuf_sync_leaf_verify_bonus_dnode(dr);
3968 #endif
3969
3970                 if (*datap != db->db.db_data) {
3971                         int slots = DB_DNODE(db)->dn_num_slots;
3972                         int bonuslen = DN_SLOTS_TO_BONUSLEN(slots);
3973                         kmem_free(*datap, bonuslen);
3974                         arc_space_return(bonuslen, ARC_SPACE_BONUS);
3975                 }
3976                 db->db_data_pending = NULL;
3977                 drp = &db->db_last_dirty;
3978                 while (*drp != dr)
3979                         drp = &(*drp)->dr_next;
3980                 ASSERT(dr->dr_next == NULL);
3981                 ASSERT(dr->dr_dbuf == db);
3982                 *drp = dr->dr_next;
3983                 if (dr->dr_dbuf->db_level != 0) {
3984                         mutex_destroy(&dr->dt.di.dr_mtx);
3985                         list_destroy(&dr->dt.di.dr_children);
3986                 }
3987                 kmem_free(dr, sizeof (dbuf_dirty_record_t));
3988                 ASSERT(db->db_dirtycnt > 0);
3989                 db->db_dirtycnt -= 1;
3990                 dbuf_rele_and_unlock(db, (void *)(uintptr_t)txg, B_FALSE);
3991                 return;
3992         }
3993
3994         os = dn->dn_objset;
3995
3996         /*
3997          * This function may have dropped the db_mtx lock allowing a dmu_sync
3998          * operation to sneak in. As a result, we need to ensure that we
3999          * don't check the dr_override_state until we have returned from
4000          * dbuf_check_blkptr.
4001          */
4002         dbuf_check_blkptr(dn, db);
4003
4004         /*
4005          * If this buffer is in the middle of an immediate write,
4006          * wait for the synchronous IO to complete.
4007          */
4008         while (dr->dt.dl.dr_override_state == DR_IN_DMU_SYNC) {
4009                 ASSERT(dn->dn_object != DMU_META_DNODE_OBJECT);
4010                 cv_wait(&db->db_changed, &db->db_mtx);
4011                 ASSERT(dr->dt.dl.dr_override_state != DR_NOT_OVERRIDDEN);
4012         }
4013
4014         /*
4015          * If this is a dnode block, ensure it is appropriately encrypted
4016          * or decrypted, depending on what we are writing to it this txg.
4017          */
4018         if (os->os_encrypted && dn->dn_object == DMU_META_DNODE_OBJECT)
4019                 dbuf_prepare_encrypted_dnode_leaf(dr);
4020
4021         if (db->db_state != DB_NOFILL &&
4022             dn->dn_object != DMU_META_DNODE_OBJECT &&
4023             zfs_refcount_count(&db->db_holds) > 1 &&
4024             dr->dt.dl.dr_override_state != DR_OVERRIDDEN &&
4025             *datap == db->db_buf) {
4026                 /*
4027                  * If this buffer is currently "in use" (i.e., there
4028                  * are active holds and db_data still references it),
4029                  * then make a copy before we start the write so that
4030                  * any modifications from the open txg will not leak
4031                  * into this write.
4032                  *
4033                  * NOTE: this copy does not need to be made for
4034                  * objects only modified in the syncing context (e.g.
4035                  * DNONE_DNODE blocks).
4036                  */
4037                 int psize = arc_buf_size(*datap);
4038                 int lsize = arc_buf_lsize(*datap);
4039                 arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
4040                 enum zio_compress compress_type = arc_get_compression(*datap);
4041
4042                 if (arc_is_encrypted(*datap)) {
4043                         boolean_t byteorder;
4044                         uint8_t salt[ZIO_DATA_SALT_LEN];
4045                         uint8_t iv[ZIO_DATA_IV_LEN];
4046                         uint8_t mac[ZIO_DATA_MAC_LEN];
4047
4048                         arc_get_raw_params(*datap, &byteorder, salt, iv, mac);
4049                         *datap = arc_alloc_raw_buf(os->os_spa, db,
4050                             dmu_objset_id(os), byteorder, salt, iv, mac,
4051                             dn->dn_type, psize, lsize, compress_type);
4052                 } else if (compress_type != ZIO_COMPRESS_OFF) {
4053                         ASSERT3U(type, ==, ARC_BUFC_DATA);
4054                         *datap = arc_alloc_compressed_buf(os->os_spa, db,
4055                             psize, lsize, compress_type);
4056                 } else {
4057                         *datap = arc_alloc_buf(os->os_spa, db, type, psize);
4058                 }
4059                 bcopy(db->db.db_data, (*datap)->b_data, psize);
4060         }
4061         db->db_data_pending = dr;
4062
4063         mutex_exit(&db->db_mtx);
4064
4065         dbuf_write(dr, *datap, tx);
4066
4067         ASSERT(!list_link_active(&dr->dr_dirty_node));
4068         if (dn->dn_object == DMU_META_DNODE_OBJECT) {
4069                 list_insert_tail(&dn->dn_dirty_records[txg & TXG_MASK], dr);
4070                 DB_DNODE_EXIT(db);
4071         } else {
4072                 /*
4073                  * Although zio_nowait() does not "wait for an IO", it does
4074                  * initiate the IO. If this is an empty write it seems plausible
4075                  * that the IO could actually be completed before the nowait
4076                  * returns. We need to DB_DNODE_EXIT() first in case
4077                  * zio_nowait() invalidates the dbuf.
4078                  */
4079                 DB_DNODE_EXIT(db);
4080                 zio_nowait(dr->dr_zio);
4081         }
4082 }
4083
4084 void
4085 dbuf_sync_list(list_t *list, int level, dmu_tx_t *tx)
4086 {
4087         dbuf_dirty_record_t *dr;
4088
4089         while ((dr = list_head(list))) {
4090                 if (dr->dr_zio != NULL) {
4091                         /*
4092                          * If we find an already initialized zio then we
4093                          * are processing the meta-dnode, and we have finished.
4094                          * The dbufs for all dnodes are put back on the list
4095                          * during processing, so that we can zio_wait()
4096                          * these IOs after initiating all child IOs.
4097                          */
4098                         ASSERT3U(dr->dr_dbuf->db.db_object, ==,
4099                             DMU_META_DNODE_OBJECT);
4100                         break;
4101                 }
4102                 if (dr->dr_dbuf->db_blkid != DMU_BONUS_BLKID &&
4103                     dr->dr_dbuf->db_blkid != DMU_SPILL_BLKID) {
4104                         VERIFY3U(dr->dr_dbuf->db_level, ==, level);
4105                 }
4106                 list_remove(list, dr);
4107                 if (dr->dr_dbuf->db_level > 0)
4108                         dbuf_sync_indirect(dr, tx);
4109                 else
4110                         dbuf_sync_leaf(dr, tx);
4111         }
4112 }
4113
4114 /* ARGSUSED */
4115 static void
4116 dbuf_write_ready(zio_t *zio, arc_buf_t *buf, void *vdb)
4117 {
4118         dmu_buf_impl_t *db = vdb;
4119         dnode_t *dn;
4120         blkptr_t *bp = zio->io_bp;
4121         blkptr_t *bp_orig = &zio->io_bp_orig;
4122         spa_t *spa = zio->io_spa;
4123         int64_t delta;
4124         uint64_t fill = 0;
4125         int i;
4126
4127         ASSERT3P(db->db_blkptr, !=, NULL);
4128         ASSERT3P(&db->db_data_pending->dr_bp_copy, ==, bp);
4129
4130         DB_DNODE_ENTER(db);
4131         dn = DB_DNODE(db);
4132         delta = bp_get_dsize_sync(spa, bp) - bp_get_dsize_sync(spa, bp_orig);
4133         dnode_diduse_space(dn, delta - zio->io_prev_space_delta);
4134         zio->io_prev_space_delta = delta;
4135
4136         if (bp->blk_birth != 0) {
4137                 ASSERT((db->db_blkid != DMU_SPILL_BLKID &&
4138                     BP_GET_TYPE(bp) == dn->dn_type) ||
4139                     (db->db_blkid == DMU_SPILL_BLKID &&
4140                     BP_GET_TYPE(bp) == dn->dn_bonustype) ||
4141                     BP_IS_EMBEDDED(bp));
4142                 ASSERT(BP_GET_LEVEL(bp) == db->db_level);
4143         }
4144
4145         mutex_enter(&db->db_mtx);
4146
4147 #ifdef ZFS_DEBUG
4148         if (db->db_blkid == DMU_SPILL_BLKID) {
4149                 ASSERT(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR);
4150                 ASSERT(!(BP_IS_HOLE(bp)) &&
4151                     db->db_blkptr == DN_SPILL_BLKPTR(dn->dn_phys));
4152         }
4153 #endif
4154
4155         if (db->db_level == 0) {
4156                 mutex_enter(&dn->dn_mtx);
4157                 if (db->db_blkid > dn->dn_phys->dn_maxblkid &&
4158                     db->db_blkid != DMU_SPILL_BLKID) {
4159                         ASSERT0(db->db_objset->os_raw_receive);
4160                         dn->dn_phys->dn_maxblkid = db->db_blkid;
4161                 }
4162                 mutex_exit(&dn->dn_mtx);
4163
4164                 if (dn->dn_type == DMU_OT_DNODE) {
4165                         i = 0;
4166                         while (i < db->db.db_size) {
4167                                 dnode_phys_t *dnp =
4168                                     (void *)(((char *)db->db.db_data) + i);
4169
4170                                 i += DNODE_MIN_SIZE;
4171                                 if (dnp->dn_type != DMU_OT_NONE) {
4172                                         fill++;
4173                                         i += dnp->dn_extra_slots *
4174                                             DNODE_MIN_SIZE;
4175                                 }
4176                         }
4177                 } else {
4178                         if (BP_IS_HOLE(bp)) {
4179                                 fill = 0;
4180                         } else {
4181                                 fill = 1;
4182                         }
4183                 }
4184         } else {
4185                 blkptr_t *ibp = db->db.db_data;
4186                 ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
4187                 for (i = db->db.db_size >> SPA_BLKPTRSHIFT; i > 0; i--, ibp++) {
4188                         if (BP_IS_HOLE(ibp))
4189                                 continue;
4190                         fill += BP_GET_FILL(ibp);
4191                 }
4192         }
4193         DB_DNODE_EXIT(db);
4194
4195         if (!BP_IS_EMBEDDED(bp))
4196                 BP_SET_FILL(bp, fill);
4197
4198         mutex_exit(&db->db_mtx);
4199
4200         db_lock_type_t dblt = dmu_buf_lock_parent(db, RW_WRITER, FTAG);
4201         *db->db_blkptr = *bp;
4202         dmu_buf_unlock_parent(db, dblt, FTAG);
4203 }
4204
4205 /* ARGSUSED */
4206 /*
4207  * This function gets called just prior to running through the compression
4208  * stage of the zio pipeline. If we're an indirect block comprised of only
4209  * holes, then we want this indirect to be compressed away to a hole. In
4210  * order to do that we must zero out any information about the holes that
4211  * this indirect points to prior to before we try to compress it.
4212  */
4213 static void
4214 dbuf_write_children_ready(zio_t *zio, arc_buf_t *buf, void *vdb)
4215 {
4216         dmu_buf_impl_t *db = vdb;
4217         dnode_t *dn;
4218         blkptr_t *bp;
4219         unsigned int epbs, i;
4220
4221         ASSERT3U(db->db_level, >, 0);
4222         DB_DNODE_ENTER(db);
4223         dn = DB_DNODE(db);
4224         epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
4225         ASSERT3U(epbs, <, 31);
4226
4227         /* Determine if all our children are holes */
4228         for (i = 0, bp = db->db.db_data; i < 1ULL << epbs; i++, bp++) {
4229                 if (!BP_IS_HOLE(bp))
4230                         break;
4231         }
4232
4233         /*
4234          * If all the children are holes, then zero them all out so that
4235          * we may get compressed away.
4236          */
4237         if (i == 1ULL << epbs) {
4238                 /*
4239                  * We only found holes. Grab the rwlock to prevent
4240                  * anybody from reading the blocks we're about to
4241                  * zero out.
4242                  */
4243                 rw_enter(&db->db_rwlock, RW_WRITER);
4244                 bzero(db->db.db_data, db->db.db_size);
4245                 rw_exit(&db->db_rwlock);
4246         }
4247         DB_DNODE_EXIT(db);
4248 }
4249
4250 /*
4251  * The SPA will call this callback several times for each zio - once
4252  * for every physical child i/o (zio->io_phys_children times).  This
4253  * allows the DMU to monitor the progress of each logical i/o.  For example,
4254  * there may be 2 copies of an indirect block, or many fragments of a RAID-Z
4255  * block.  There may be a long delay before all copies/fragments are completed,
4256  * so this callback allows us to retire dirty space gradually, as the physical
4257  * i/os complete.
4258  */
4259 /* ARGSUSED */
4260 static void
4261 dbuf_write_physdone(zio_t *zio, arc_buf_t *buf, void *arg)
4262 {
4263         dmu_buf_impl_t *db = arg;
4264         objset_t *os = db->db_objset;
4265         dsl_pool_t *dp = dmu_objset_pool(os);
4266         dbuf_dirty_record_t *dr;
4267         int delta = 0;
4268
4269         dr = db->db_data_pending;
4270         ASSERT3U(dr->dr_txg, ==, zio->io_txg);
4271
4272         /*
4273          * The callback will be called io_phys_children times.  Retire one
4274          * portion of our dirty space each time we are called.  Any rounding
4275          * error will be cleaned up by dbuf_write_done().
4276          */
4277         delta = dr->dr_accounted / zio->io_phys_children;
4278         dsl_pool_undirty_space(dp, delta, zio->io_txg);
4279 }
4280
4281 /* ARGSUSED */
4282 static void
4283 dbuf_write_done(zio_t *zio, arc_buf_t *buf, void *vdb)
4284 {
4285         dmu_buf_impl_t *db = vdb;
4286         blkptr_t *bp_orig = &zio->io_bp_orig;
4287         blkptr_t *bp = db->db_blkptr;
4288         objset_t *os = db->db_objset;
4289         dmu_tx_t *tx = os->os_synctx;
4290         dbuf_dirty_record_t **drp, *dr;
4291
4292         ASSERT0(zio->io_error);
4293         ASSERT(db->db_blkptr == bp);
4294
4295         /*
4296          * For nopwrites and rewrites we ensure that the bp matches our
4297          * original and bypass all the accounting.
4298          */
4299         if (zio->io_flags & (ZIO_FLAG_IO_REWRITE | ZIO_FLAG_NOPWRITE)) {
4300                 ASSERT(BP_EQUAL(bp, bp_orig));
4301         } else {
4302                 dsl_dataset_t *ds = os->os_dsl_dataset;
4303                 (void) dsl_dataset_block_kill(ds, bp_orig, tx, B_TRUE);
4304                 dsl_dataset_block_born(ds, bp, tx);
4305         }
4306
4307         mutex_enter(&db->db_mtx);
4308
4309         DBUF_VERIFY(db);
4310
4311         drp = &db->db_last_dirty;
4312         while ((dr = *drp) != db->db_data_pending)
4313                 drp = &dr->dr_next;
4314         ASSERT(!list_link_active(&dr->dr_dirty_node));
4315         ASSERT(dr->dr_dbuf == db);
4316         ASSERT(dr->dr_next == NULL);
4317         *drp = dr->dr_next;
4318
4319 #ifdef ZFS_DEBUG
4320         if (db->db_blkid == DMU_SPILL_BLKID) {
4321                 dnode_t *dn;
4322
4323                 DB_DNODE_ENTER(db);
4324                 dn = DB_DNODE(db);
4325                 ASSERT(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR);
4326                 ASSERT(!(BP_IS_HOLE(db->db_blkptr)) &&
4327                     db->db_blkptr == DN_SPILL_BLKPTR(dn->dn_phys));
4328                 DB_DNODE_EXIT(db);
4329         }
4330 #endif
4331
4332         if (db->db_level == 0) {
4333                 ASSERT(db->db_blkid != DMU_BONUS_BLKID);
4334                 ASSERT(dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN);
4335                 if (db->db_state != DB_NOFILL) {
4336                         if (dr->dt.dl.dr_data != db->db_buf)
4337                                 arc_buf_destroy(dr->dt.dl.dr_data, db);
4338                 }
4339         } else {
4340                 dnode_t *dn;
4341
4342                 DB_DNODE_ENTER(db);
4343                 dn = DB_DNODE(db);
4344                 ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
4345                 ASSERT3U(db->db.db_size, ==, 1 << dn->dn_phys->dn_indblkshift);
4346                 if (!BP_IS_HOLE(db->db_blkptr)) {
4347                         int epbs __maybe_unused = dn->dn_phys->dn_indblkshift -
4348                             SPA_BLKPTRSHIFT;
4349                         ASSERT3U(db->db_blkid, <=,
4350                             dn->dn_phys->dn_maxblkid >> (db->db_level * epbs));
4351                         ASSERT3U(BP_GET_LSIZE(db->db_blkptr), ==,
4352                             db->db.db_size);
4353                 }
4354                 DB_DNODE_EXIT(db);
4355                 mutex_destroy(&dr->dt.di.dr_mtx);
4356                 list_destroy(&dr->dt.di.dr_children);
4357         }
4358
4359         cv_broadcast(&db->db_changed);
4360         ASSERT(db->db_dirtycnt > 0);
4361         db->db_dirtycnt -= 1;
4362         db->db_data_pending = NULL;
4363         dbuf_rele_and_unlock(db, (void *)(uintptr_t)tx->tx_txg, B_FALSE);
4364
4365         /*
4366          * If we didn't do a physical write in this ZIO and we
4367          * still ended up here, it means that the space of the
4368          * dbuf that we just released (and undirtied) above hasn't
4369          * been marked as undirtied in the pool's accounting.
4370          *
4371          * Thus, we undirty that space in the pool's view of the
4372          * world here. For physical writes this type of update
4373          * happens in dbuf_write_physdone().
4374          *
4375          * If we did a physical write, cleanup any rounding errors
4376          * that came up due to writing multiple copies of a block
4377          * on disk [see dbuf_write_physdone()].
4378          */
4379         if (zio->io_phys_children == 0) {
4380                 dsl_pool_undirty_space(dmu_objset_pool(os),
4381                     dr->dr_accounted, zio->io_txg);
4382         } else {
4383                 dsl_pool_undirty_space(dmu_objset_pool(os),
4384                     dr->dr_accounted % zio->io_phys_children, zio->io_txg);
4385         }
4386
4387         kmem_free(dr, sizeof (dbuf_dirty_record_t));
4388 }
4389
4390 static void
4391 dbuf_write_nofill_ready(zio_t *zio)
4392 {
4393         dbuf_write_ready(zio, NULL, zio->io_private);
4394 }
4395
4396 static void
4397 dbuf_write_nofill_done(zio_t *zio)
4398 {
4399         dbuf_write_done(zio, NULL, zio->io_private);
4400 }
4401
4402 static void
4403 dbuf_write_override_ready(zio_t *zio)
4404 {
4405         dbuf_dirty_record_t *dr = zio->io_private;
4406         dmu_buf_impl_t *db = dr->dr_dbuf;
4407
4408         dbuf_write_ready(zio, NULL, db);
4409 }
4410
4411 static void
4412 dbuf_write_override_done(zio_t *zio)
4413 {
4414         dbuf_dirty_record_t *dr = zio->io_private;
4415         dmu_buf_impl_t *db = dr->dr_dbuf;
4416         blkptr_t *obp = &dr->dt.dl.dr_overridden_by;
4417
4418         mutex_enter(&db->db_mtx);
4419         if (!BP_EQUAL(zio->io_bp, obp)) {
4420                 if (!BP_IS_HOLE(obp))
4421                         dsl_free(spa_get_dsl(zio->io_spa), zio->io_txg, obp);
4422                 arc_release(dr->dt.dl.dr_data, db);
4423         }
4424         mutex_exit(&db->db_mtx);
4425
4426         dbuf_write_done(zio, NULL, db);
4427
4428         if (zio->io_abd != NULL)
4429                 abd_put(zio->io_abd);
4430 }
4431
4432 typedef struct dbuf_remap_impl_callback_arg {
4433         objset_t        *drica_os;
4434         uint64_t        drica_blk_birth;
4435         dmu_tx_t        *drica_tx;
4436 } dbuf_remap_impl_callback_arg_t;
4437
4438 static void
4439 dbuf_remap_impl_callback(uint64_t vdev, uint64_t offset, uint64_t size,
4440     void *arg)
4441 {
4442         dbuf_remap_impl_callback_arg_t *drica = arg;
4443         objset_t *os = drica->drica_os;
4444         spa_t *spa = dmu_objset_spa(os);
4445         dmu_tx_t *tx = drica->drica_tx;
4446
4447         ASSERT(dsl_pool_sync_context(spa_get_dsl(spa)));
4448
4449         if (os == spa_meta_objset(spa)) {
4450                 spa_vdev_indirect_mark_obsolete(spa, vdev, offset, size, tx);
4451         } else {
4452                 dsl_dataset_block_remapped(dmu_objset_ds(os), vdev, offset,
4453                     size, drica->drica_blk_birth, tx);
4454         }
4455 }
4456
4457 static void
4458 dbuf_remap_impl(dnode_t *dn, blkptr_t *bp, krwlock_t *rw, dmu_tx_t *tx)
4459 {
4460         blkptr_t bp_copy = *bp;
4461         spa_t *spa = dmu_objset_spa(dn->dn_objset);
4462         dbuf_remap_impl_callback_arg_t drica;
4463
4464         ASSERT(dsl_pool_sync_context(spa_get_dsl(spa)));
4465
4466         drica.drica_os = dn->dn_objset;
4467         drica.drica_blk_birth = bp->blk_birth;
4468         drica.drica_tx = tx;
4469         if (spa_remap_blkptr(spa, &bp_copy, dbuf_remap_impl_callback,
4470             &drica)) {
4471                 /*
4472                  * If the blkptr being remapped is tracked by a livelist,
4473                  * then we need to make sure the livelist reflects the update.
4474                  * First, cancel out the old blkptr by appending a 'FREE'
4475                  * entry. Next, add an 'ALLOC' to track the new version. This
4476                  * way we avoid trying to free an inaccurate blkptr at delete.
4477                  * Note that embedded blkptrs are not tracked in livelists.
4478                  */
4479                 if (dn->dn_objset != spa_meta_objset(spa)) {
4480                         dsl_dataset_t *ds = dmu_objset_ds(dn->dn_objset);
4481                         if (dsl_deadlist_is_open(&ds->ds_dir->dd_livelist) &&
4482                             bp->blk_birth > ds->ds_dir->dd_origin_txg) {
4483                                 ASSERT(!BP_IS_EMBEDDED(bp));
4484                                 ASSERT(dsl_dir_is_clone(ds->ds_dir));
4485                                 ASSERT(spa_feature_is_enabled(spa,
4486                                     SPA_FEATURE_LIVELIST));
4487                                 bplist_append(&ds->ds_dir->dd_pending_frees,
4488                                     bp);
4489                                 bplist_append(&ds->ds_dir->dd_pending_allocs,
4490                                     &bp_copy);
4491                         }
4492                 }
4493
4494                 /*
4495                  * The db_rwlock prevents dbuf_read_impl() from
4496                  * dereferencing the BP while we are changing it.  To
4497                  * avoid lock contention, only grab it when we are actually
4498                  * changing the BP.
4499                  */
4500                 if (rw != NULL)
4501                         rw_enter(rw, RW_WRITER);
4502                 *bp = bp_copy;
4503                 if (rw != NULL)
4504                         rw_exit(rw);
4505         }
4506 }
4507
4508 /*
4509  * Remap any existing BP's to concrete vdevs, if possible.
4510  */
4511 static void
4512 dbuf_remap(dnode_t *dn, dmu_buf_impl_t *db, dmu_tx_t *tx)
4513 {
4514         spa_t *spa = dmu_objset_spa(db->db_objset);
4515         ASSERT(dsl_pool_sync_context(spa_get_dsl(spa)));
4516
4517         if (!spa_feature_is_active(spa, SPA_FEATURE_DEVICE_REMOVAL))
4518                 return;
4519
4520         if (db->db_level > 0) {
4521                 blkptr_t *bp = db->db.db_data;
4522                 for (int i = 0; i < db->db.db_size >> SPA_BLKPTRSHIFT; i++) {
4523                         dbuf_remap_impl(dn, &bp[i], &db->db_rwlock, tx);
4524                 }
4525         } else if (db->db.db_object == DMU_META_DNODE_OBJECT) {
4526                 dnode_phys_t *dnp = db->db.db_data;
4527                 ASSERT3U(db->db_dnode_handle->dnh_dnode->dn_type, ==,
4528                     DMU_OT_DNODE);
4529                 for (int i = 0; i < db->db.db_size >> DNODE_SHIFT;
4530                     i += dnp[i].dn_extra_slots + 1) {
4531                         for (int j = 0; j < dnp[i].dn_nblkptr; j++) {
4532                                 krwlock_t *lock = (dn->dn_dbuf == NULL ? NULL :
4533                                     &dn->dn_dbuf->db_rwlock);
4534                                 dbuf_remap_impl(dn, &dnp[i].dn_blkptr[j], lock,
4535                                     tx);
4536                         }
4537                 }
4538         }
4539 }
4540
4541
4542 /* Issue I/O to commit a dirty buffer to disk. */
4543 static void
4544 dbuf_write(dbuf_dirty_record_t *dr, arc_buf_t *data, dmu_tx_t *tx)
4545 {
4546         dmu_buf_impl_t *db = dr->dr_dbuf;
4547         dnode_t *dn;
4548         objset_t *os;
4549         dmu_buf_impl_t *parent = db->db_parent;
4550         uint64_t txg = tx->tx_txg;
4551         zbookmark_phys_t zb;
4552         zio_prop_t zp;
4553         zio_t *zio;
4554         int wp_flag = 0;
4555
4556         ASSERT(dmu_tx_is_syncing(tx));
4557
4558         DB_DNODE_ENTER(db);
4559         dn = DB_DNODE(db);
4560         os = dn->dn_objset;
4561
4562         if (db->db_state != DB_NOFILL) {
4563                 if (db->db_level > 0 || dn->dn_type == DMU_OT_DNODE) {
4564                         /*
4565                          * Private object buffers are released here rather
4566                          * than in dbuf_dirty() since they are only modified
4567                          * in the syncing context and we don't want the
4568                          * overhead of making multiple copies of the data.
4569                          */
4570                         if (BP_IS_HOLE(db->db_blkptr)) {
4571                                 arc_buf_thaw(data);
4572                         } else {
4573                                 dbuf_release_bp(db);
4574                         }
4575                         dbuf_remap(dn, db, tx);
4576                 }
4577         }
4578
4579         if (parent != dn->dn_dbuf) {
4580                 /* Our parent is an indirect block. */
4581                 /* We have a dirty parent that has been scheduled for write. */
4582                 ASSERT(parent && parent->db_data_pending);
4583                 /* Our parent's buffer is one level closer to the dnode. */
4584                 ASSERT(db->db_level == parent->db_level-1);
4585                 /*
4586                  * We're about to modify our parent's db_data by modifying
4587                  * our block pointer, so the parent must be released.
4588                  */
4589                 ASSERT(arc_released(parent->db_buf));
4590                 zio = parent->db_data_pending->dr_zio;
4591         } else {
4592                 /* Our parent is the dnode itself. */
4593                 ASSERT((db->db_level == dn->dn_phys->dn_nlevels-1 &&
4594                     db->db_blkid != DMU_SPILL_BLKID) ||
4595                     (db->db_blkid == DMU_SPILL_BLKID && db->db_level == 0));
4596                 if (db->db_blkid != DMU_SPILL_BLKID)
4597                         ASSERT3P(db->db_blkptr, ==,
4598                             &dn->dn_phys->dn_blkptr[db->db_blkid]);
4599                 zio = dn->dn_zio;
4600         }
4601
4602         ASSERT(db->db_level == 0 || data == db->db_buf);
4603         ASSERT3U(db->db_blkptr->blk_birth, <=, txg);
4604         ASSERT(zio);
4605
4606         SET_BOOKMARK(&zb, os->os_dsl_dataset ?
4607             os->os_dsl_dataset->ds_object : DMU_META_OBJSET,
4608             db->db.db_object, db->db_level, db->db_blkid);
4609
4610         if (db->db_blkid == DMU_SPILL_BLKID)
4611                 wp_flag = WP_SPILL;
4612         wp_flag |= (db->db_state == DB_NOFILL) ? WP_NOFILL : 0;
4613
4614         dmu_write_policy(os, dn, db->db_level, wp_flag, &zp);
4615         DB_DNODE_EXIT(db);
4616
4617         /*
4618          * We copy the blkptr now (rather than when we instantiate the dirty
4619          * record), because its value can change between open context and
4620          * syncing context. We do not need to hold dn_struct_rwlock to read
4621          * db_blkptr because we are in syncing context.
4622          */
4623         dr->dr_bp_copy = *db->db_blkptr;
4624
4625         if (db->db_level == 0 &&
4626             dr->dt.dl.dr_override_state == DR_OVERRIDDEN) {
4627                 /*
4628                  * The BP for this block has been provided by open context
4629                  * (by dmu_sync() or dmu_buf_write_embedded()).
4630                  */
4631                 abd_t *contents = (data != NULL) ?
4632                     abd_get_from_buf(data->b_data, arc_buf_size(data)) : NULL;
4633
4634                 dr->dr_zio = zio_write(zio, os->os_spa, txg,
4635                     &dr->dr_bp_copy, contents, db->db.db_size, db->db.db_size,
4636                     &zp, dbuf_write_override_ready, NULL, NULL,
4637                     dbuf_write_override_done,
4638                     dr, ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
4639                 mutex_enter(&db->db_mtx);
4640                 dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
4641                 zio_write_override(dr->dr_zio, &dr->dt.dl.dr_overridden_by,
4642                     dr->dt.dl.dr_copies, dr->dt.dl.dr_nopwrite);
4643                 mutex_exit(&db->db_mtx);
4644         } else if (db->db_state == DB_NOFILL) {
4645                 ASSERT(zp.zp_checksum == ZIO_CHECKSUM_OFF ||
4646                     zp.zp_checksum == ZIO_CHECKSUM_NOPARITY);
4647                 dr->dr_zio = zio_write(zio, os->os_spa, txg,
4648                     &dr->dr_bp_copy, NULL, db->db.db_size, db->db.db_size, &zp,
4649                     dbuf_write_nofill_ready, NULL, NULL,
4650                     dbuf_write_nofill_done, db,
4651                     ZIO_PRIORITY_ASYNC_WRITE,
4652                     ZIO_FLAG_MUSTSUCCEED | ZIO_FLAG_NODATA, &zb);
4653         } else {
4654                 ASSERT(arc_released(data));
4655
4656                 /*
4657                  * For indirect blocks, we want to setup the children
4658                  * ready callback so that we can properly handle an indirect
4659                  * block that only contains holes.
4660                  */
4661                 arc_write_done_func_t *children_ready_cb = NULL;
4662                 if (db->db_level != 0)
4663                         children_ready_cb = dbuf_write_children_ready;
4664
4665                 dr->dr_zio = arc_write(zio, os->os_spa, txg,
4666                     &dr->dr_bp_copy, data, DBUF_IS_L2CACHEABLE(db),
4667                     &zp, dbuf_write_ready,
4668                     children_ready_cb, dbuf_write_physdone,
4669                     dbuf_write_done, db, ZIO_PRIORITY_ASYNC_WRITE,
4670                     ZIO_FLAG_MUSTSUCCEED, &zb);
4671         }
4672 }
4673
4674 EXPORT_SYMBOL(dbuf_find);
4675 EXPORT_SYMBOL(dbuf_is_metadata);
4676 EXPORT_SYMBOL(dbuf_destroy);
4677 EXPORT_SYMBOL(dbuf_loan_arcbuf);
4678 EXPORT_SYMBOL(dbuf_whichblock);
4679 EXPORT_SYMBOL(dbuf_read);
4680 EXPORT_SYMBOL(dbuf_unoverride);
4681 EXPORT_SYMBOL(dbuf_free_range);
4682 EXPORT_SYMBOL(dbuf_new_size);
4683 EXPORT_SYMBOL(dbuf_release_bp);
4684 EXPORT_SYMBOL(dbuf_dirty);
4685 EXPORT_SYMBOL(dmu_buf_set_crypt_params);
4686 EXPORT_SYMBOL(dmu_buf_will_dirty);
4687 EXPORT_SYMBOL(dmu_buf_is_dirty);
4688 EXPORT_SYMBOL(dmu_buf_will_not_fill);
4689 EXPORT_SYMBOL(dmu_buf_will_fill);
4690 EXPORT_SYMBOL(dmu_buf_fill_done);
4691 EXPORT_SYMBOL(dmu_buf_rele);
4692 EXPORT_SYMBOL(dbuf_assign_arcbuf);
4693 EXPORT_SYMBOL(dbuf_prefetch);
4694 EXPORT_SYMBOL(dbuf_hold_impl);
4695 EXPORT_SYMBOL(dbuf_hold);
4696 EXPORT_SYMBOL(dbuf_hold_level);
4697 EXPORT_SYMBOL(dbuf_create_bonus);
4698 EXPORT_SYMBOL(dbuf_spill_set_blksz);
4699 EXPORT_SYMBOL(dbuf_rm_spill);
4700 EXPORT_SYMBOL(dbuf_add_ref);
4701 EXPORT_SYMBOL(dbuf_rele);
4702 EXPORT_SYMBOL(dbuf_rele_and_unlock);
4703 EXPORT_SYMBOL(dbuf_refcount);
4704 EXPORT_SYMBOL(dbuf_sync_list);
4705 EXPORT_SYMBOL(dmu_buf_set_user);
4706 EXPORT_SYMBOL(dmu_buf_set_user_ie);
4707 EXPORT_SYMBOL(dmu_buf_get_user);
4708 EXPORT_SYMBOL(dmu_buf_get_blkptr);
4709
4710 /* BEGIN CSTYLED */
4711 ZFS_MODULE_PARAM(zfs_dbuf_cache, dbuf_cache_, max_bytes, ULONG, ZMOD_RW,
4712         "Maximum size in bytes of the dbuf cache.");
4713
4714 ZFS_MODULE_PARAM(zfs_dbuf_cache, dbuf_cache_, hiwater_pct, UINT, ZMOD_RW,
4715         "Percentage over dbuf_cache_max_bytes when dbufs must be evicted "
4716         "directly.");
4717
4718 ZFS_MODULE_PARAM(zfs_dbuf_cache, dbuf_cache_, lowater_pct, UINT, ZMOD_RW,
4719         "Percentage below dbuf_cache_max_bytes when the evict thread stops "
4720         "evicting dbufs.");
4721
4722 ZFS_MODULE_PARAM(zfs_dbuf, dbuf_, metadata_cache_max_bytes, ULONG, ZMOD_RW,
4723         "Maximum size in bytes of the dbuf metadata cache.");
4724
4725 ZFS_MODULE_PARAM(zfs_dbuf, dbuf_, cache_shift, INT, ZMOD_RW,
4726         "Set the size of the dbuf cache to a log2 fraction of arc size.");
4727
4728 ZFS_MODULE_PARAM(zfs_dbuf, dbuf_, metadata_cache_shift, INT, ZMOD_RW,
4729         "Set the size of the dbuf metadata cache to a log2 fraction of arc "
4730         "size.");
4731 /* END CSTYLED */