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