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