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