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