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