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 		brt_pending_remove(dmu_objset_spa(db->db_objset),
2547 		    &dr->dt.dl.dr_overridden_by, tx);
2548 	}
2549 
2550 	dnode_t *dn = dr->dr_dnode;
2551 
2552 	dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
2553 
2554 	ASSERT(db->db.db_size != 0);
2555 
2556 	dsl_pool_undirty_space(dmu_objset_pool(dn->dn_objset),
2557 	    dr->dr_accounted, txg);
2558 
2559 	list_remove(&db->db_dirty_records, dr);
2560 
2561 	/*
2562 	 * Note that there are three places in dbuf_dirty()
2563 	 * where this dirty record may be put on a list.
2564 	 * Make sure to do a list_remove corresponding to
2565 	 * every one of those list_insert calls.
2566 	 */
2567 	if (dr->dr_parent) {
2568 		mutex_enter(&dr->dr_parent->dt.di.dr_mtx);
2569 		list_remove(&dr->dr_parent->dt.di.dr_children, dr);
2570 		mutex_exit(&dr->dr_parent->dt.di.dr_mtx);
2571 	} else if (db->db_blkid == DMU_SPILL_BLKID ||
2572 	    db->db_level + 1 == dn->dn_nlevels) {
2573 		ASSERT(db->db_blkptr == NULL || db->db_parent == dn->dn_dbuf);
2574 		mutex_enter(&dn->dn_mtx);
2575 		list_remove(&dn->dn_dirty_records[txg & TXG_MASK], dr);
2576 		mutex_exit(&dn->dn_mtx);
2577 	}
2578 
2579 	if (db->db_state != DB_NOFILL && !brtwrite) {
2580 		dbuf_unoverride(dr);
2581 
2582 		ASSERT(db->db_buf != NULL);
2583 		ASSERT(dr->dt.dl.dr_data != NULL);
2584 		if (dr->dt.dl.dr_data != db->db_buf)
2585 			arc_buf_destroy(dr->dt.dl.dr_data, db);
2586 	}
2587 
2588 	kmem_free(dr, sizeof (dbuf_dirty_record_t));
2589 
2590 	ASSERT(db->db_dirtycnt > 0);
2591 	db->db_dirtycnt -= 1;
2592 
2593 	if (zfs_refcount_remove(&db->db_holds, (void *)(uintptr_t)txg) == 0) {
2594 		ASSERT(db->db_state == DB_NOFILL || brtwrite ||
2595 		    arc_released(db->db_buf));
2596 		dbuf_destroy(db);
2597 		return (B_TRUE);
2598 	}
2599 
2600 	return (B_FALSE);
2601 }
2602 
2603 static void
dmu_buf_will_dirty_impl(dmu_buf_t * db_fake,int flags,dmu_tx_t * tx)2604 dmu_buf_will_dirty_impl(dmu_buf_t *db_fake, int flags, dmu_tx_t *tx)
2605 {
2606 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2607 	boolean_t undirty = B_FALSE;
2608 
2609 	ASSERT(tx->tx_txg != 0);
2610 	ASSERT(!zfs_refcount_is_zero(&db->db_holds));
2611 
2612 	/*
2613 	 * Quick check for dirtiness to improve performance for some workloads
2614 	 * (e.g. file deletion with indirect blocks cached).
2615 	 */
2616 	mutex_enter(&db->db_mtx);
2617 	if (db->db_state == DB_CACHED || db->db_state == DB_NOFILL) {
2618 		/*
2619 		 * It's possible that the dbuf is already dirty but not cached,
2620 		 * because there are some calls to dbuf_dirty() that don't
2621 		 * go through dmu_buf_will_dirty().
2622 		 */
2623 		dbuf_dirty_record_t *dr = dbuf_find_dirty_eq(db, tx->tx_txg);
2624 		if (dr != NULL) {
2625 			if (db->db_level == 0 &&
2626 			    dr->dt.dl.dr_brtwrite) {
2627 				/*
2628 				 * Block cloning: If we are dirtying a cloned
2629 				 * level 0 block, we cannot simply redirty it,
2630 				 * because this dr has no associated data.
2631 				 * We will go through a full undirtying below,
2632 				 * before dirtying it again.
2633 				 */
2634 				undirty = B_TRUE;
2635 			} else {
2636 				/* This dbuf is already dirty and cached. */
2637 				dbuf_redirty(dr);
2638 				mutex_exit(&db->db_mtx);
2639 				return;
2640 			}
2641 		}
2642 	}
2643 	mutex_exit(&db->db_mtx);
2644 
2645 	DB_DNODE_ENTER(db);
2646 	if (RW_WRITE_HELD(&DB_DNODE(db)->dn_struct_rwlock))
2647 		flags |= DB_RF_HAVESTRUCT;
2648 	DB_DNODE_EXIT(db);
2649 
2650 	/*
2651 	 * Block cloning: Do the dbuf_read() before undirtying the dbuf, as we
2652 	 * want to make sure dbuf_read() will read the pending cloned block and
2653 	 * not the uderlying block that is being replaced. dbuf_undirty() will
2654 	 * do dbuf_unoverride(), so we will end up with cloned block content,
2655 	 * without overridden BP.
2656 	 */
2657 	(void) dbuf_read(db, NULL, flags);
2658 	if (undirty) {
2659 		mutex_enter(&db->db_mtx);
2660 		VERIFY(!dbuf_undirty(db, tx));
2661 		mutex_exit(&db->db_mtx);
2662 	}
2663 	(void) dbuf_dirty(db, tx);
2664 }
2665 
2666 void
dmu_buf_will_dirty(dmu_buf_t * db_fake,dmu_tx_t * tx)2667 dmu_buf_will_dirty(dmu_buf_t *db_fake, dmu_tx_t *tx)
2668 {
2669 	dmu_buf_will_dirty_impl(db_fake,
2670 	    DB_RF_MUST_SUCCEED | DB_RF_NOPREFETCH, tx);
2671 }
2672 
2673 boolean_t
dmu_buf_is_dirty(dmu_buf_t * db_fake,dmu_tx_t * tx)2674 dmu_buf_is_dirty(dmu_buf_t *db_fake, dmu_tx_t *tx)
2675 {
2676 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2677 	dbuf_dirty_record_t *dr;
2678 
2679 	mutex_enter(&db->db_mtx);
2680 	dr = dbuf_find_dirty_eq(db, tx->tx_txg);
2681 	mutex_exit(&db->db_mtx);
2682 	return (dr != NULL);
2683 }
2684 
2685 void
dmu_buf_will_clone(dmu_buf_t * db_fake,dmu_tx_t * tx)2686 dmu_buf_will_clone(dmu_buf_t *db_fake, dmu_tx_t *tx)
2687 {
2688 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2689 
2690 	/*
2691 	 * Block cloning: We are going to clone into this block, so undirty
2692 	 * modifications done to this block so far in this txg. This includes
2693 	 * writes and clones into this block.
2694 	 */
2695 	mutex_enter(&db->db_mtx);
2696 	DBUF_VERIFY(db);
2697 	VERIFY(!dbuf_undirty(db, tx));
2698 	ASSERT0P(dbuf_find_dirty_eq(db, tx->tx_txg));
2699 	if (db->db_buf != NULL) {
2700 		arc_buf_destroy(db->db_buf, db);
2701 		db->db_buf = NULL;
2702 		dbuf_clear_data(db);
2703 	}
2704 
2705 	db->db_state = DB_NOFILL;
2706 	DTRACE_SET_STATE(db, "allocating NOFILL buffer for clone");
2707 
2708 	DBUF_VERIFY(db);
2709 	mutex_exit(&db->db_mtx);
2710 
2711 	dbuf_noread(db);
2712 	(void) dbuf_dirty(db, tx);
2713 }
2714 
2715 void
dmu_buf_will_not_fill(dmu_buf_t * db_fake,dmu_tx_t * tx)2716 dmu_buf_will_not_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
2717 {
2718 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2719 
2720 	mutex_enter(&db->db_mtx);
2721 	db->db_state = DB_NOFILL;
2722 	DTRACE_SET_STATE(db, "allocating NOFILL buffer");
2723 	mutex_exit(&db->db_mtx);
2724 
2725 	dbuf_noread(db);
2726 	(void) dbuf_dirty(db, tx);
2727 }
2728 
2729 void
dmu_buf_will_fill(dmu_buf_t * db_fake,dmu_tx_t * tx,boolean_t canfail)2730 dmu_buf_will_fill(dmu_buf_t *db_fake, dmu_tx_t *tx, boolean_t canfail)
2731 {
2732 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2733 
2734 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2735 	ASSERT(tx->tx_txg != 0);
2736 	ASSERT(db->db_level == 0);
2737 	ASSERT(!zfs_refcount_is_zero(&db->db_holds));
2738 
2739 	ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT ||
2740 	    dmu_tx_private_ok(tx));
2741 
2742 	mutex_enter(&db->db_mtx);
2743 	if (db->db_state == DB_NOFILL) {
2744 		/*
2745 		 * Block cloning: We will be completely overwriting a block
2746 		 * cloned in this transaction group, so let's undirty the
2747 		 * pending clone and mark the block as uncached. This will be
2748 		 * as if the clone was never done.  But if the fill can fail
2749 		 * we should have a way to return back to the cloned data.
2750 		 */
2751 		if (canfail && dbuf_find_dirty_eq(db, tx->tx_txg) != NULL) {
2752 			mutex_exit(&db->db_mtx);
2753 			dmu_buf_will_dirty(db_fake, tx);
2754 			return;
2755 		}
2756 		VERIFY(!dbuf_undirty(db, tx));
2757 		db->db_state = DB_UNCACHED;
2758 	}
2759 	mutex_exit(&db->db_mtx);
2760 
2761 	dbuf_noread(db);
2762 	(void) dbuf_dirty(db, tx);
2763 }
2764 
2765 /*
2766  * This function is effectively the same as dmu_buf_will_dirty(), but
2767  * indicates the caller expects raw encrypted data in the db, and provides
2768  * the crypt params (byteorder, salt, iv, mac) which should be stored in the
2769  * blkptr_t when this dbuf is written.  This is only used for blocks of
2770  * dnodes, during raw receive.
2771  */
2772 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)2773 dmu_buf_set_crypt_params(dmu_buf_t *db_fake, boolean_t byteorder,
2774     const uint8_t *salt, const uint8_t *iv, const uint8_t *mac, dmu_tx_t *tx)
2775 {
2776 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2777 	dbuf_dirty_record_t *dr;
2778 
2779 	/*
2780 	 * dr_has_raw_params is only processed for blocks of dnodes
2781 	 * (see dbuf_sync_dnode_leaf_crypt()).
2782 	 */
2783 	ASSERT3U(db->db.db_object, ==, DMU_META_DNODE_OBJECT);
2784 	ASSERT3U(db->db_level, ==, 0);
2785 	ASSERT(db->db_objset->os_raw_receive);
2786 
2787 	dmu_buf_will_dirty_impl(db_fake,
2788 	    DB_RF_MUST_SUCCEED | DB_RF_NOPREFETCH | DB_RF_NO_DECRYPT, tx);
2789 
2790 	dr = dbuf_find_dirty_eq(db, tx->tx_txg);
2791 
2792 	ASSERT3P(dr, !=, NULL);
2793 
2794 	dr->dt.dl.dr_has_raw_params = B_TRUE;
2795 	dr->dt.dl.dr_byteorder = byteorder;
2796 	memcpy(dr->dt.dl.dr_salt, salt, ZIO_DATA_SALT_LEN);
2797 	memcpy(dr->dt.dl.dr_iv, iv, ZIO_DATA_IV_LEN);
2798 	memcpy(dr->dt.dl.dr_mac, mac, ZIO_DATA_MAC_LEN);
2799 }
2800 
2801 static void
dbuf_override_impl(dmu_buf_impl_t * db,const blkptr_t * bp,dmu_tx_t * tx)2802 dbuf_override_impl(dmu_buf_impl_t *db, const blkptr_t *bp, dmu_tx_t *tx)
2803 {
2804 	struct dirty_leaf *dl;
2805 	dbuf_dirty_record_t *dr;
2806 
2807 	dr = list_head(&db->db_dirty_records);
2808 	ASSERT3P(dr, !=, NULL);
2809 	ASSERT3U(dr->dr_txg, ==, tx->tx_txg);
2810 	dl = &dr->dt.dl;
2811 	dl->dr_overridden_by = *bp;
2812 	dl->dr_override_state = DR_OVERRIDDEN;
2813 	dl->dr_overridden_by.blk_birth = dr->dr_txg;
2814 }
2815 
2816 boolean_t
dmu_buf_fill_done(dmu_buf_t * dbuf,dmu_tx_t * tx,boolean_t failed)2817 dmu_buf_fill_done(dmu_buf_t *dbuf, dmu_tx_t *tx, boolean_t failed)
2818 {
2819 	(void) tx;
2820 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbuf;
2821 	mutex_enter(&db->db_mtx);
2822 	DBUF_VERIFY(db);
2823 
2824 	if (db->db_state == DB_FILL) {
2825 		if (db->db_level == 0 && db->db_freed_in_flight) {
2826 			ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2827 			/* we were freed while filling */
2828 			/* XXX dbuf_undirty? */
2829 			memset(db->db.db_data, 0, db->db.db_size);
2830 			db->db_freed_in_flight = FALSE;
2831 			db->db_state = DB_CACHED;
2832 			DTRACE_SET_STATE(db,
2833 			    "fill done handling freed in flight");
2834 			failed = B_FALSE;
2835 		} else if (failed) {
2836 			VERIFY(!dbuf_undirty(db, tx));
2837 			arc_buf_destroy(db->db_buf, db);
2838 			db->db_buf = NULL;
2839 			dbuf_clear_data(db);
2840 			DTRACE_SET_STATE(db, "fill failed");
2841 		} else {
2842 			db->db_state = DB_CACHED;
2843 			DTRACE_SET_STATE(db, "fill done");
2844 		}
2845 		cv_broadcast(&db->db_changed);
2846 	} else {
2847 		db->db_state = DB_CACHED;
2848 		failed = B_FALSE;
2849 	}
2850 	mutex_exit(&db->db_mtx);
2851 	return (failed);
2852 }
2853 
2854 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)2855 dmu_buf_write_embedded(dmu_buf_t *dbuf, void *data,
2856     bp_embedded_type_t etype, enum zio_compress comp,
2857     int uncompressed_size, int compressed_size, int byteorder,
2858     dmu_tx_t *tx)
2859 {
2860 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbuf;
2861 	struct dirty_leaf *dl;
2862 	dmu_object_type_t type;
2863 	dbuf_dirty_record_t *dr;
2864 
2865 	if (etype == BP_EMBEDDED_TYPE_DATA) {
2866 		ASSERT(spa_feature_is_active(dmu_objset_spa(db->db_objset),
2867 		    SPA_FEATURE_EMBEDDED_DATA));
2868 	}
2869 
2870 	DB_DNODE_ENTER(db);
2871 	type = DB_DNODE(db)->dn_type;
2872 	DB_DNODE_EXIT(db);
2873 
2874 	ASSERT0(db->db_level);
2875 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2876 
2877 	dmu_buf_will_not_fill(dbuf, tx);
2878 
2879 	dr = list_head(&db->db_dirty_records);
2880 	ASSERT3P(dr, !=, NULL);
2881 	ASSERT3U(dr->dr_txg, ==, tx->tx_txg);
2882 	dl = &dr->dt.dl;
2883 	encode_embedded_bp_compressed(&dl->dr_overridden_by,
2884 	    data, comp, uncompressed_size, compressed_size);
2885 	BPE_SET_ETYPE(&dl->dr_overridden_by, etype);
2886 	BP_SET_TYPE(&dl->dr_overridden_by, type);
2887 	BP_SET_LEVEL(&dl->dr_overridden_by, 0);
2888 	BP_SET_BYTEORDER(&dl->dr_overridden_by, byteorder);
2889 
2890 	dl->dr_override_state = DR_OVERRIDDEN;
2891 	dl->dr_overridden_by.blk_birth = dr->dr_txg;
2892 }
2893 
2894 void
dmu_buf_redact(dmu_buf_t * dbuf,dmu_tx_t * tx)2895 dmu_buf_redact(dmu_buf_t *dbuf, dmu_tx_t *tx)
2896 {
2897 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbuf;
2898 	dmu_object_type_t type;
2899 	ASSERT(dsl_dataset_feature_is_active(db->db_objset->os_dsl_dataset,
2900 	    SPA_FEATURE_REDACTED_DATASETS));
2901 
2902 	DB_DNODE_ENTER(db);
2903 	type = DB_DNODE(db)->dn_type;
2904 	DB_DNODE_EXIT(db);
2905 
2906 	ASSERT0(db->db_level);
2907 	dmu_buf_will_not_fill(dbuf, tx);
2908 
2909 	blkptr_t bp = { { { {0} } } };
2910 	BP_SET_TYPE(&bp, type);
2911 	BP_SET_LEVEL(&bp, 0);
2912 	BP_SET_BIRTH(&bp, tx->tx_txg, 0);
2913 	BP_SET_REDACTED(&bp);
2914 	BPE_SET_LSIZE(&bp, dbuf->db_size);
2915 
2916 	dbuf_override_impl(db, &bp, tx);
2917 }
2918 
2919 /*
2920  * Directly assign a provided arc buf to a given dbuf if it's not referenced
2921  * by anybody except our caller. Otherwise copy arcbuf's contents to dbuf.
2922  */
2923 void
dbuf_assign_arcbuf(dmu_buf_impl_t * db,arc_buf_t * buf,dmu_tx_t * tx)2924 dbuf_assign_arcbuf(dmu_buf_impl_t *db, arc_buf_t *buf, dmu_tx_t *tx)
2925 {
2926 	ASSERT(!zfs_refcount_is_zero(&db->db_holds));
2927 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2928 	ASSERT(db->db_level == 0);
2929 	ASSERT3U(dbuf_is_metadata(db), ==, arc_is_metadata(buf));
2930 	ASSERT(buf != NULL);
2931 	ASSERT3U(arc_buf_lsize(buf), ==, db->db.db_size);
2932 	ASSERT(tx->tx_txg != 0);
2933 
2934 	arc_return_buf(buf, db);
2935 	ASSERT(arc_released(buf));
2936 
2937 	mutex_enter(&db->db_mtx);
2938 
2939 	while (db->db_state == DB_READ || db->db_state == DB_FILL)
2940 		cv_wait(&db->db_changed, &db->db_mtx);
2941 
2942 	ASSERT(db->db_state == DB_CACHED || db->db_state == DB_UNCACHED ||
2943 	    db->db_state == DB_NOFILL);
2944 
2945 	if (db->db_state == DB_CACHED &&
2946 	    zfs_refcount_count(&db->db_holds) - 1 > db->db_dirtycnt) {
2947 		/*
2948 		 * In practice, we will never have a case where we have an
2949 		 * encrypted arc buffer while additional holds exist on the
2950 		 * dbuf. We don't handle this here so we simply assert that
2951 		 * fact instead.
2952 		 */
2953 		ASSERT(!arc_is_encrypted(buf));
2954 		mutex_exit(&db->db_mtx);
2955 		(void) dbuf_dirty(db, tx);
2956 		memcpy(db->db.db_data, buf->b_data, db->db.db_size);
2957 		arc_buf_destroy(buf, db);
2958 		return;
2959 	}
2960 
2961 	if (db->db_state == DB_CACHED) {
2962 		dbuf_dirty_record_t *dr = list_head(&db->db_dirty_records);
2963 
2964 		ASSERT(db->db_buf != NULL);
2965 		if (dr != NULL && dr->dr_txg == tx->tx_txg) {
2966 			ASSERT(dr->dt.dl.dr_data == db->db_buf);
2967 
2968 			if (!arc_released(db->db_buf)) {
2969 				ASSERT(dr->dt.dl.dr_override_state ==
2970 				    DR_OVERRIDDEN);
2971 				arc_release(db->db_buf, db);
2972 			}
2973 			dr->dt.dl.dr_data = buf;
2974 			arc_buf_destroy(db->db_buf, db);
2975 		} else if (dr == NULL || dr->dt.dl.dr_data != db->db_buf) {
2976 			arc_release(db->db_buf, db);
2977 			arc_buf_destroy(db->db_buf, db);
2978 		}
2979 		db->db_buf = NULL;
2980 	} else if (db->db_state == DB_NOFILL) {
2981 		/*
2982 		 * We will be completely replacing the cloned block.  In case
2983 		 * it was cloned in this transaction group, let's undirty the
2984 		 * pending clone and mark the block as uncached. This will be
2985 		 * as if the clone was never done.
2986 		 */
2987 		VERIFY(!dbuf_undirty(db, tx));
2988 		db->db_state = DB_UNCACHED;
2989 	}
2990 	ASSERT(db->db_buf == NULL);
2991 	dbuf_set_data(db, buf);
2992 	db->db_state = DB_FILL;
2993 	DTRACE_SET_STATE(db, "filling assigned arcbuf");
2994 	mutex_exit(&db->db_mtx);
2995 	(void) dbuf_dirty(db, tx);
2996 	dmu_buf_fill_done(&db->db, tx, B_FALSE);
2997 }
2998 
2999 void
dbuf_destroy(dmu_buf_impl_t * db)3000 dbuf_destroy(dmu_buf_impl_t *db)
3001 {
3002 	dnode_t *dn;
3003 	dmu_buf_impl_t *parent = db->db_parent;
3004 	dmu_buf_impl_t *dndb;
3005 
3006 	ASSERT(MUTEX_HELD(&db->db_mtx));
3007 	ASSERT(zfs_refcount_is_zero(&db->db_holds));
3008 
3009 	if (db->db_buf != NULL) {
3010 		arc_buf_destroy(db->db_buf, db);
3011 		db->db_buf = NULL;
3012 	}
3013 
3014 	if (db->db_blkid == DMU_BONUS_BLKID) {
3015 		int slots = DB_DNODE(db)->dn_num_slots;
3016 		int bonuslen = DN_SLOTS_TO_BONUSLEN(slots);
3017 		if (db->db.db_data != NULL) {
3018 			kmem_free(db->db.db_data, bonuslen);
3019 			arc_space_return(bonuslen, ARC_SPACE_BONUS);
3020 			db->db_state = DB_UNCACHED;
3021 			DTRACE_SET_STATE(db, "buffer cleared");
3022 		}
3023 	}
3024 
3025 	dbuf_clear_data(db);
3026 
3027 	if (multilist_link_active(&db->db_cache_link)) {
3028 		ASSERT(db->db_caching_status == DB_DBUF_CACHE ||
3029 		    db->db_caching_status == DB_DBUF_METADATA_CACHE);
3030 
3031 		multilist_remove(&dbuf_caches[db->db_caching_status].cache, db);
3032 		(void) zfs_refcount_remove_many(
3033 		    &dbuf_caches[db->db_caching_status].size,
3034 		    db->db.db_size, db);
3035 
3036 		if (db->db_caching_status == DB_DBUF_METADATA_CACHE) {
3037 			DBUF_STAT_BUMPDOWN(metadata_cache_count);
3038 		} else {
3039 			DBUF_STAT_BUMPDOWN(cache_levels[db->db_level]);
3040 			DBUF_STAT_BUMPDOWN(cache_count);
3041 			DBUF_STAT_DECR(cache_levels_bytes[db->db_level],
3042 			    db->db.db_size);
3043 		}
3044 		db->db_caching_status = DB_NO_CACHE;
3045 	}
3046 
3047 	ASSERT(db->db_state == DB_UNCACHED || db->db_state == DB_NOFILL);
3048 	ASSERT(db->db_data_pending == NULL);
3049 	ASSERT(list_is_empty(&db->db_dirty_records));
3050 
3051 	db->db_state = DB_EVICTING;
3052 	DTRACE_SET_STATE(db, "buffer eviction started");
3053 	db->db_blkptr = NULL;
3054 
3055 	/*
3056 	 * Now that db_state is DB_EVICTING, nobody else can find this via
3057 	 * the hash table.  We can now drop db_mtx, which allows us to
3058 	 * acquire the dn_dbufs_mtx.
3059 	 */
3060 	mutex_exit(&db->db_mtx);
3061 
3062 	DB_DNODE_ENTER(db);
3063 	dn = DB_DNODE(db);
3064 	dndb = dn->dn_dbuf;
3065 	if (db->db_blkid != DMU_BONUS_BLKID) {
3066 		boolean_t needlock = !MUTEX_HELD(&dn->dn_dbufs_mtx);
3067 		if (needlock)
3068 			mutex_enter_nested(&dn->dn_dbufs_mtx,
3069 			    NESTED_SINGLE);
3070 		avl_remove(&dn->dn_dbufs, db);
3071 		membar_producer();
3072 		DB_DNODE_EXIT(db);
3073 		if (needlock)
3074 			mutex_exit(&dn->dn_dbufs_mtx);
3075 		/*
3076 		 * Decrementing the dbuf count means that the hold corresponding
3077 		 * to the removed dbuf is no longer discounted in dnode_move(),
3078 		 * so the dnode cannot be moved until after we release the hold.
3079 		 * The membar_producer() ensures visibility of the decremented
3080 		 * value in dnode_move(), since DB_DNODE_EXIT doesn't actually
3081 		 * release any lock.
3082 		 */
3083 		mutex_enter(&dn->dn_mtx);
3084 		dnode_rele_and_unlock(dn, db, B_TRUE);
3085 		db->db_dnode_handle = NULL;
3086 
3087 		dbuf_hash_remove(db);
3088 	} else {
3089 		DB_DNODE_EXIT(db);
3090 	}
3091 
3092 	ASSERT(zfs_refcount_is_zero(&db->db_holds));
3093 
3094 	db->db_parent = NULL;
3095 
3096 	ASSERT(db->db_buf == NULL);
3097 	ASSERT(db->db.db_data == NULL);
3098 	ASSERT(db->db_hash_next == NULL);
3099 	ASSERT(db->db_blkptr == NULL);
3100 	ASSERT(db->db_data_pending == NULL);
3101 	ASSERT3U(db->db_caching_status, ==, DB_NO_CACHE);
3102 	ASSERT(!multilist_link_active(&db->db_cache_link));
3103 
3104 	/*
3105 	 * If this dbuf is referenced from an indirect dbuf,
3106 	 * decrement the ref count on the indirect dbuf.
3107 	 */
3108 	if (parent && parent != dndb) {
3109 		mutex_enter(&parent->db_mtx);
3110 		dbuf_rele_and_unlock(parent, db, B_TRUE);
3111 	}
3112 
3113 	kmem_cache_free(dbuf_kmem_cache, db);
3114 	arc_space_return(sizeof (dmu_buf_impl_t), ARC_SPACE_DBUF);
3115 }
3116 
3117 /*
3118  * Note: While bpp will always be updated if the function returns success,
3119  * parentp will not be updated if the dnode does not have dn_dbuf filled in;
3120  * this happens when the dnode is the meta-dnode, or {user|group|project}used
3121  * object.
3122  */
3123 __attribute__((always_inline))
3124 static inline int
dbuf_findbp(dnode_t * dn,int level,uint64_t blkid,int fail_sparse,dmu_buf_impl_t ** parentp,blkptr_t ** bpp)3125 dbuf_findbp(dnode_t *dn, int level, uint64_t blkid, int fail_sparse,
3126     dmu_buf_impl_t **parentp, blkptr_t **bpp)
3127 {
3128 	*parentp = NULL;
3129 	*bpp = NULL;
3130 
3131 	ASSERT(blkid != DMU_BONUS_BLKID);
3132 
3133 	if (blkid == DMU_SPILL_BLKID) {
3134 		mutex_enter(&dn->dn_mtx);
3135 		if (dn->dn_have_spill &&
3136 		    (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR))
3137 			*bpp = DN_SPILL_BLKPTR(dn->dn_phys);
3138 		else
3139 			*bpp = NULL;
3140 		dbuf_add_ref(dn->dn_dbuf, NULL);
3141 		*parentp = dn->dn_dbuf;
3142 		mutex_exit(&dn->dn_mtx);
3143 		return (0);
3144 	}
3145 
3146 	int nlevels =
3147 	    (dn->dn_phys->dn_nlevels == 0) ? 1 : dn->dn_phys->dn_nlevels;
3148 	int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
3149 
3150 	ASSERT3U(level * epbs, <, 64);
3151 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
3152 	/*
3153 	 * This assertion shouldn't trip as long as the max indirect block size
3154 	 * is less than 1M.  The reason for this is that up to that point,
3155 	 * the number of levels required to address an entire object with blocks
3156 	 * of size SPA_MINBLOCKSIZE satisfies nlevels * epbs + 1 <= 64.	 In
3157 	 * other words, if N * epbs + 1 > 64, then if (N-1) * epbs + 1 > 55
3158 	 * (i.e. we can address the entire object), objects will all use at most
3159 	 * N-1 levels and the assertion won't overflow.	 However, once epbs is
3160 	 * 13, 4 * 13 + 1 = 53, but 5 * 13 + 1 = 66.  Then, 4 levels will not be
3161 	 * enough to address an entire object, so objects will have 5 levels,
3162 	 * but then this assertion will overflow.
3163 	 *
3164 	 * All this is to say that if we ever increase DN_MAX_INDBLKSHIFT, we
3165 	 * need to redo this logic to handle overflows.
3166 	 */
3167 	ASSERT(level >= nlevels ||
3168 	    ((nlevels - level - 1) * epbs) +
3169 	    highbit64(dn->dn_phys->dn_nblkptr) <= 64);
3170 	if (level >= nlevels ||
3171 	    blkid >= ((uint64_t)dn->dn_phys->dn_nblkptr <<
3172 	    ((nlevels - level - 1) * epbs)) ||
3173 	    (fail_sparse &&
3174 	    blkid > (dn->dn_phys->dn_maxblkid >> (level * epbs)))) {
3175 		/* the buffer has no parent yet */
3176 		return (SET_ERROR(ENOENT));
3177 	} else if (level < nlevels-1) {
3178 		/* this block is referenced from an indirect block */
3179 		int err;
3180 
3181 		err = dbuf_hold_impl(dn, level + 1,
3182 		    blkid >> epbs, fail_sparse, FALSE, NULL, parentp);
3183 
3184 		if (err)
3185 			return (err);
3186 		err = dbuf_read(*parentp, NULL,
3187 		    (DB_RF_HAVESTRUCT | DB_RF_NOPREFETCH | DB_RF_CANFAIL));
3188 		if (err) {
3189 			dbuf_rele(*parentp, NULL);
3190 			*parentp = NULL;
3191 			return (err);
3192 		}
3193 		rw_enter(&(*parentp)->db_rwlock, RW_READER);
3194 		*bpp = ((blkptr_t *)(*parentp)->db.db_data) +
3195 		    (blkid & ((1ULL << epbs) - 1));
3196 		if (blkid > (dn->dn_phys->dn_maxblkid >> (level * epbs)))
3197 			ASSERT(BP_IS_HOLE(*bpp));
3198 		rw_exit(&(*parentp)->db_rwlock);
3199 		return (0);
3200 	} else {
3201 		/* the block is referenced from the dnode */
3202 		ASSERT3U(level, ==, nlevels-1);
3203 		ASSERT(dn->dn_phys->dn_nblkptr == 0 ||
3204 		    blkid < dn->dn_phys->dn_nblkptr);
3205 		if (dn->dn_dbuf) {
3206 			dbuf_add_ref(dn->dn_dbuf, NULL);
3207 			*parentp = dn->dn_dbuf;
3208 		}
3209 		*bpp = &dn->dn_phys->dn_blkptr[blkid];
3210 		return (0);
3211 	}
3212 }
3213 
3214 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)3215 dbuf_create(dnode_t *dn, uint8_t level, uint64_t blkid,
3216     dmu_buf_impl_t *parent, blkptr_t *blkptr, uint64_t hash)
3217 {
3218 	objset_t *os = dn->dn_objset;
3219 	dmu_buf_impl_t *db, *odb;
3220 
3221 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
3222 	ASSERT(dn->dn_type != DMU_OT_NONE);
3223 
3224 	db = kmem_cache_alloc(dbuf_kmem_cache, KM_SLEEP);
3225 
3226 	list_create(&db->db_dirty_records, sizeof (dbuf_dirty_record_t),
3227 	    offsetof(dbuf_dirty_record_t, dr_dbuf_node));
3228 
3229 	db->db_objset = os;
3230 	db->db.db_object = dn->dn_object;
3231 	db->db_level = level;
3232 	db->db_blkid = blkid;
3233 	db->db_dirtycnt = 0;
3234 	db->db_dnode_handle = dn->dn_handle;
3235 	db->db_parent = parent;
3236 	db->db_blkptr = blkptr;
3237 	db->db_hash = hash;
3238 
3239 	db->db_user = NULL;
3240 	db->db_user_immediate_evict = FALSE;
3241 	db->db_freed_in_flight = FALSE;
3242 	db->db_pending_evict = FALSE;
3243 
3244 	if (blkid == DMU_BONUS_BLKID) {
3245 		ASSERT3P(parent, ==, dn->dn_dbuf);
3246 		db->db.db_size = DN_SLOTS_TO_BONUSLEN(dn->dn_num_slots) -
3247 		    (dn->dn_nblkptr-1) * sizeof (blkptr_t);
3248 		ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
3249 		db->db.db_offset = DMU_BONUS_BLKID;
3250 		db->db_state = DB_UNCACHED;
3251 		DTRACE_SET_STATE(db, "bonus buffer created");
3252 		db->db_caching_status = DB_NO_CACHE;
3253 		/* the bonus dbuf is not placed in the hash table */
3254 		arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_DBUF);
3255 		return (db);
3256 	} else if (blkid == DMU_SPILL_BLKID) {
3257 		db->db.db_size = (blkptr != NULL) ?
3258 		    BP_GET_LSIZE(blkptr) : SPA_MINBLOCKSIZE;
3259 		db->db.db_offset = 0;
3260 	} else {
3261 		int blocksize =
3262 		    db->db_level ? 1 << dn->dn_indblkshift : dn->dn_datablksz;
3263 		db->db.db_size = blocksize;
3264 		db->db.db_offset = db->db_blkid * blocksize;
3265 	}
3266 
3267 	/*
3268 	 * Hold the dn_dbufs_mtx while we get the new dbuf
3269 	 * in the hash table *and* added to the dbufs list.
3270 	 * This prevents a possible deadlock with someone
3271 	 * trying to look up this dbuf before it's added to the
3272 	 * dn_dbufs list.
3273 	 */
3274 	mutex_enter(&dn->dn_dbufs_mtx);
3275 	db->db_state = DB_EVICTING; /* not worth logging this state change */
3276 	if ((odb = dbuf_hash_insert(db)) != NULL) {
3277 		/* someone else inserted it first */
3278 		mutex_exit(&dn->dn_dbufs_mtx);
3279 		kmem_cache_free(dbuf_kmem_cache, db);
3280 		DBUF_STAT_BUMP(hash_insert_race);
3281 		return (odb);
3282 	}
3283 	avl_add(&dn->dn_dbufs, db);
3284 
3285 	db->db_state = DB_UNCACHED;
3286 	DTRACE_SET_STATE(db, "regular buffer created");
3287 	db->db_caching_status = DB_NO_CACHE;
3288 	mutex_exit(&dn->dn_dbufs_mtx);
3289 	arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_DBUF);
3290 
3291 	if (parent && parent != dn->dn_dbuf)
3292 		dbuf_add_ref(parent, db);
3293 
3294 	ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
3295 	    zfs_refcount_count(&dn->dn_holds) > 0);
3296 	(void) zfs_refcount_add(&dn->dn_holds, db);
3297 
3298 	dprintf_dbuf(db, "db=%p\n", db);
3299 
3300 	return (db);
3301 }
3302 
3303 /*
3304  * This function returns a block pointer and information about the object,
3305  * given a dnode and a block.  This is a publicly accessible version of
3306  * dbuf_findbp that only returns some information, rather than the
3307  * dbuf.  Note that the dnode passed in must be held, and the dn_struct_rwlock
3308  * should be locked as (at least) a reader.
3309  */
3310 int
dbuf_dnode_findbp(dnode_t * dn,uint64_t level,uint64_t blkid,blkptr_t * bp,uint16_t * datablkszsec,uint8_t * indblkshift)3311 dbuf_dnode_findbp(dnode_t *dn, uint64_t level, uint64_t blkid,
3312     blkptr_t *bp, uint16_t *datablkszsec, uint8_t *indblkshift)
3313 {
3314 	dmu_buf_impl_t *dbp = NULL;
3315 	blkptr_t *bp2;
3316 	int err = 0;
3317 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
3318 
3319 	err = dbuf_findbp(dn, level, blkid, B_FALSE, &dbp, &bp2);
3320 	if (err == 0) {
3321 		ASSERT3P(bp2, !=, NULL);
3322 		*bp = *bp2;
3323 		if (dbp != NULL)
3324 			dbuf_rele(dbp, NULL);
3325 		if (datablkszsec != NULL)
3326 			*datablkszsec = dn->dn_phys->dn_datablkszsec;
3327 		if (indblkshift != NULL)
3328 			*indblkshift = dn->dn_phys->dn_indblkshift;
3329 	}
3330 
3331 	return (err);
3332 }
3333 
3334 typedef struct dbuf_prefetch_arg {
3335 	spa_t *dpa_spa;	/* The spa to issue the prefetch in. */
3336 	zbookmark_phys_t dpa_zb; /* The target block to prefetch. */
3337 	int dpa_epbs; /* Entries (blkptr_t's) Per Block Shift. */
3338 	int dpa_curlevel; /* The current level that we're reading */
3339 	dnode_t *dpa_dnode; /* The dnode associated with the prefetch */
3340 	zio_priority_t dpa_prio; /* The priority I/Os should be issued at. */
3341 	zio_t *dpa_zio; /* The parent zio_t for all prefetches. */
3342 	arc_flags_t dpa_aflags; /* Flags to pass to the final prefetch. */
3343 	dbuf_prefetch_fn dpa_cb; /* prefetch completion callback */
3344 	void *dpa_arg; /* prefetch completion arg */
3345 } dbuf_prefetch_arg_t;
3346 
3347 static void
dbuf_prefetch_fini(dbuf_prefetch_arg_t * dpa,boolean_t io_done)3348 dbuf_prefetch_fini(dbuf_prefetch_arg_t *dpa, boolean_t io_done)
3349 {
3350 	if (dpa->dpa_cb != NULL) {
3351 		dpa->dpa_cb(dpa->dpa_arg, dpa->dpa_zb.zb_level,
3352 		    dpa->dpa_zb.zb_blkid, io_done);
3353 	}
3354 	kmem_free(dpa, sizeof (*dpa));
3355 }
3356 
3357 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)3358 dbuf_issue_final_prefetch_done(zio_t *zio, const zbookmark_phys_t *zb,
3359     const blkptr_t *iobp, arc_buf_t *abuf, void *private)
3360 {
3361 	(void) zio, (void) zb, (void) iobp;
3362 	dbuf_prefetch_arg_t *dpa = private;
3363 
3364 	if (abuf != NULL)
3365 		arc_buf_destroy(abuf, private);
3366 
3367 	dbuf_prefetch_fini(dpa, B_TRUE);
3368 }
3369 
3370 /*
3371  * Actually issue the prefetch read for the block given.
3372  */
3373 static void
dbuf_issue_final_prefetch(dbuf_prefetch_arg_t * dpa,blkptr_t * bp)3374 dbuf_issue_final_prefetch(dbuf_prefetch_arg_t *dpa, blkptr_t *bp)
3375 {
3376 	ASSERT(!BP_IS_REDACTED(bp) ||
3377 	    dsl_dataset_feature_is_active(
3378 	    dpa->dpa_dnode->dn_objset->os_dsl_dataset,
3379 	    SPA_FEATURE_REDACTED_DATASETS));
3380 
3381 	if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp) || BP_IS_REDACTED(bp))
3382 		return (dbuf_prefetch_fini(dpa, B_FALSE));
3383 
3384 	int zio_flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE;
3385 	arc_flags_t aflags =
3386 	    dpa->dpa_aflags | ARC_FLAG_NOWAIT | ARC_FLAG_PREFETCH |
3387 	    ARC_FLAG_NO_BUF;
3388 
3389 	/* dnodes are always read as raw and then converted later */
3390 	if (BP_GET_TYPE(bp) == DMU_OT_DNODE && BP_IS_PROTECTED(bp) &&
3391 	    dpa->dpa_curlevel == 0)
3392 		zio_flags |= ZIO_FLAG_RAW;
3393 
3394 	ASSERT3U(dpa->dpa_curlevel, ==, BP_GET_LEVEL(bp));
3395 	ASSERT3U(dpa->dpa_curlevel, ==, dpa->dpa_zb.zb_level);
3396 	ASSERT(dpa->dpa_zio != NULL);
3397 	(void) arc_read(dpa->dpa_zio, dpa->dpa_spa, bp,
3398 	    dbuf_issue_final_prefetch_done, dpa,
3399 	    dpa->dpa_prio, zio_flags, &aflags, &dpa->dpa_zb);
3400 }
3401 
3402 /*
3403  * Called when an indirect block above our prefetch target is read in.  This
3404  * will either read in the next indirect block down the tree or issue the actual
3405  * prefetch if the next block down is our target.
3406  */
3407 static void
dbuf_prefetch_indirect_done(zio_t * zio,const zbookmark_phys_t * zb,const blkptr_t * iobp,arc_buf_t * abuf,void * private)3408 dbuf_prefetch_indirect_done(zio_t *zio, const zbookmark_phys_t *zb,
3409     const blkptr_t *iobp, arc_buf_t *abuf, void *private)
3410 {
3411 	(void) zb, (void) iobp;
3412 	dbuf_prefetch_arg_t *dpa = private;
3413 
3414 	ASSERT3S(dpa->dpa_zb.zb_level, <, dpa->dpa_curlevel);
3415 	ASSERT3S(dpa->dpa_curlevel, >, 0);
3416 
3417 	if (abuf == NULL) {
3418 		ASSERT(zio == NULL || zio->io_error != 0);
3419 		dbuf_prefetch_fini(dpa, B_TRUE);
3420 		return;
3421 	}
3422 	ASSERT(zio == NULL || zio->io_error == 0);
3423 
3424 	/*
3425 	 * The dpa_dnode is only valid if we are called with a NULL
3426 	 * zio. This indicates that the arc_read() returned without
3427 	 * first calling zio_read() to issue a physical read. Once
3428 	 * a physical read is made the dpa_dnode must be invalidated
3429 	 * as the locks guarding it may have been dropped. If the
3430 	 * dpa_dnode is still valid, then we want to add it to the dbuf
3431 	 * cache. To do so, we must hold the dbuf associated with the block
3432 	 * we just prefetched, read its contents so that we associate it
3433 	 * with an arc_buf_t, and then release it.
3434 	 */
3435 	if (zio != NULL) {
3436 		ASSERT3S(BP_GET_LEVEL(zio->io_bp), ==, dpa->dpa_curlevel);
3437 		if (zio->io_flags & ZIO_FLAG_RAW_COMPRESS) {
3438 			ASSERT3U(BP_GET_PSIZE(zio->io_bp), ==, zio->io_size);
3439 		} else {
3440 			ASSERT3U(BP_GET_LSIZE(zio->io_bp), ==, zio->io_size);
3441 		}
3442 		ASSERT3P(zio->io_spa, ==, dpa->dpa_spa);
3443 
3444 		dpa->dpa_dnode = NULL;
3445 	} else if (dpa->dpa_dnode != NULL) {
3446 		uint64_t curblkid = dpa->dpa_zb.zb_blkid >>
3447 		    (dpa->dpa_epbs * (dpa->dpa_curlevel -
3448 		    dpa->dpa_zb.zb_level));
3449 		dmu_buf_impl_t *db = dbuf_hold_level(dpa->dpa_dnode,
3450 		    dpa->dpa_curlevel, curblkid, FTAG);
3451 		if (db == NULL) {
3452 			arc_buf_destroy(abuf, private);
3453 			dbuf_prefetch_fini(dpa, B_TRUE);
3454 			return;
3455 		}
3456 		(void) dbuf_read(db, NULL,
3457 		    DB_RF_MUST_SUCCEED | DB_RF_NOPREFETCH | DB_RF_HAVESTRUCT);
3458 		dbuf_rele(db, FTAG);
3459 	}
3460 
3461 	dpa->dpa_curlevel--;
3462 	uint64_t nextblkid = dpa->dpa_zb.zb_blkid >>
3463 	    (dpa->dpa_epbs * (dpa->dpa_curlevel - dpa->dpa_zb.zb_level));
3464 	blkptr_t *bp = ((blkptr_t *)abuf->b_data) +
3465 	    P2PHASE(nextblkid, 1ULL << dpa->dpa_epbs);
3466 
3467 	ASSERT(!BP_IS_REDACTED(bp) || (dpa->dpa_dnode &&
3468 	    dsl_dataset_feature_is_active(
3469 	    dpa->dpa_dnode->dn_objset->os_dsl_dataset,
3470 	    SPA_FEATURE_REDACTED_DATASETS)));
3471 	if (BP_IS_HOLE(bp) || BP_IS_REDACTED(bp)) {
3472 		arc_buf_destroy(abuf, private);
3473 		dbuf_prefetch_fini(dpa, B_TRUE);
3474 		return;
3475 	} else if (dpa->dpa_curlevel == dpa->dpa_zb.zb_level) {
3476 		ASSERT3U(nextblkid, ==, dpa->dpa_zb.zb_blkid);
3477 		dbuf_issue_final_prefetch(dpa, bp);
3478 	} else {
3479 		arc_flags_t iter_aflags = ARC_FLAG_NOWAIT;
3480 		zbookmark_phys_t zb;
3481 
3482 		/* flag if L2ARC eligible, l2arc_noprefetch then decides */
3483 		if (dpa->dpa_aflags & ARC_FLAG_L2CACHE)
3484 			iter_aflags |= ARC_FLAG_L2CACHE;
3485 
3486 		ASSERT3U(dpa->dpa_curlevel, ==, BP_GET_LEVEL(bp));
3487 
3488 		SET_BOOKMARK(&zb, dpa->dpa_zb.zb_objset,
3489 		    dpa->dpa_zb.zb_object, dpa->dpa_curlevel, nextblkid);
3490 
3491 		(void) arc_read(dpa->dpa_zio, dpa->dpa_spa,
3492 		    bp, dbuf_prefetch_indirect_done, dpa,
3493 		    ZIO_PRIORITY_SYNC_READ,
3494 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
3495 		    &iter_aflags, &zb);
3496 	}
3497 
3498 	arc_buf_destroy(abuf, private);
3499 }
3500 
3501 /*
3502  * Issue prefetch reads for the given block on the given level.  If the indirect
3503  * blocks above that block are not in memory, we will read them in
3504  * asynchronously.  As a result, this call never blocks waiting for a read to
3505  * complete. Note that the prefetch might fail if the dataset is encrypted and
3506  * the encryption key is unmapped before the IO completes.
3507  */
3508 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)3509 dbuf_prefetch_impl(dnode_t *dn, int64_t level, uint64_t blkid,
3510     zio_priority_t prio, arc_flags_t aflags, dbuf_prefetch_fn cb,
3511     void *arg)
3512 {
3513 	blkptr_t bp;
3514 	int epbs, nlevels, curlevel;
3515 	uint64_t curblkid;
3516 
3517 	ASSERT(blkid != DMU_BONUS_BLKID);
3518 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
3519 
3520 	if (blkid > dn->dn_maxblkid)
3521 		goto no_issue;
3522 
3523 	if (level == 0 && dnode_block_freed(dn, blkid))
3524 		goto no_issue;
3525 
3526 	/*
3527 	 * This dnode hasn't been written to disk yet, so there's nothing to
3528 	 * prefetch.
3529 	 */
3530 	nlevels = dn->dn_phys->dn_nlevels;
3531 	if (level >= nlevels || dn->dn_phys->dn_nblkptr == 0)
3532 		goto no_issue;
3533 
3534 	epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
3535 	if (dn->dn_phys->dn_maxblkid < blkid << (epbs * level))
3536 		goto no_issue;
3537 
3538 	dmu_buf_impl_t *db = dbuf_find(dn->dn_objset, dn->dn_object,
3539 	    level, blkid, NULL);
3540 	if (db != NULL) {
3541 		mutex_exit(&db->db_mtx);
3542 		/*
3543 		 * This dbuf already exists.  It is either CACHED, or
3544 		 * (we assume) about to be read or filled.
3545 		 */
3546 		goto no_issue;
3547 	}
3548 
3549 	/*
3550 	 * Find the closest ancestor (indirect block) of the target block
3551 	 * that is present in the cache.  In this indirect block, we will
3552 	 * find the bp that is at curlevel, curblkid.
3553 	 */
3554 	curlevel = level;
3555 	curblkid = blkid;
3556 	while (curlevel < nlevels - 1) {
3557 		int parent_level = curlevel + 1;
3558 		uint64_t parent_blkid = curblkid >> epbs;
3559 		dmu_buf_impl_t *db;
3560 
3561 		if (dbuf_hold_impl(dn, parent_level, parent_blkid,
3562 		    FALSE, TRUE, FTAG, &db) == 0) {
3563 			blkptr_t *bpp = db->db_buf->b_data;
3564 			bp = bpp[P2PHASE(curblkid, 1 << epbs)];
3565 			dbuf_rele(db, FTAG);
3566 			break;
3567 		}
3568 
3569 		curlevel = parent_level;
3570 		curblkid = parent_blkid;
3571 	}
3572 
3573 	if (curlevel == nlevels - 1) {
3574 		/* No cached indirect blocks found. */
3575 		ASSERT3U(curblkid, <, dn->dn_phys->dn_nblkptr);
3576 		bp = dn->dn_phys->dn_blkptr[curblkid];
3577 	}
3578 	ASSERT(!BP_IS_REDACTED(&bp) ||
3579 	    dsl_dataset_feature_is_active(dn->dn_objset->os_dsl_dataset,
3580 	    SPA_FEATURE_REDACTED_DATASETS));
3581 	if (BP_IS_HOLE(&bp) || BP_IS_REDACTED(&bp))
3582 		goto no_issue;
3583 
3584 	ASSERT3U(curlevel, ==, BP_GET_LEVEL(&bp));
3585 
3586 	zio_t *pio = zio_root(dmu_objset_spa(dn->dn_objset), NULL, NULL,
3587 	    ZIO_FLAG_CANFAIL);
3588 
3589 	dbuf_prefetch_arg_t *dpa = kmem_zalloc(sizeof (*dpa), KM_SLEEP);
3590 	dsl_dataset_t *ds = dn->dn_objset->os_dsl_dataset;
3591 	SET_BOOKMARK(&dpa->dpa_zb, ds != NULL ? ds->ds_object : DMU_META_OBJSET,
3592 	    dn->dn_object, level, blkid);
3593 	dpa->dpa_curlevel = curlevel;
3594 	dpa->dpa_prio = prio;
3595 	dpa->dpa_aflags = aflags;
3596 	dpa->dpa_spa = dn->dn_objset->os_spa;
3597 	dpa->dpa_dnode = dn;
3598 	dpa->dpa_epbs = epbs;
3599 	dpa->dpa_zio = pio;
3600 	dpa->dpa_cb = cb;
3601 	dpa->dpa_arg = arg;
3602 
3603 	if (!DNODE_LEVEL_IS_CACHEABLE(dn, level))
3604 		dpa->dpa_aflags |= ARC_FLAG_UNCACHED;
3605 	else if (dnode_level_is_l2cacheable(&bp, dn, level))
3606 		dpa->dpa_aflags |= ARC_FLAG_L2CACHE;
3607 
3608 	/*
3609 	 * If we have the indirect just above us, no need to do the asynchronous
3610 	 * prefetch chain; we'll just run the last step ourselves.  If we're at
3611 	 * a higher level, though, we want to issue the prefetches for all the
3612 	 * indirect blocks asynchronously, so we can go on with whatever we were
3613 	 * doing.
3614 	 */
3615 	if (curlevel == level) {
3616 		ASSERT3U(curblkid, ==, blkid);
3617 		dbuf_issue_final_prefetch(dpa, &bp);
3618 	} else {
3619 		arc_flags_t iter_aflags = ARC_FLAG_NOWAIT;
3620 		zbookmark_phys_t zb;
3621 
3622 		/* flag if L2ARC eligible, l2arc_noprefetch then decides */
3623 		if (dnode_level_is_l2cacheable(&bp, dn, level))
3624 			iter_aflags |= ARC_FLAG_L2CACHE;
3625 
3626 		SET_BOOKMARK(&zb, ds != NULL ? ds->ds_object : DMU_META_OBJSET,
3627 		    dn->dn_object, curlevel, curblkid);
3628 		(void) arc_read(dpa->dpa_zio, dpa->dpa_spa,
3629 		    &bp, dbuf_prefetch_indirect_done, dpa,
3630 		    ZIO_PRIORITY_SYNC_READ,
3631 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
3632 		    &iter_aflags, &zb);
3633 	}
3634 	/*
3635 	 * We use pio here instead of dpa_zio since it's possible that
3636 	 * dpa may have already been freed.
3637 	 */
3638 	zio_nowait(pio);
3639 	return (1);
3640 no_issue:
3641 	if (cb != NULL)
3642 		cb(arg, level, blkid, B_FALSE);
3643 	return (0);
3644 }
3645 
3646 int
dbuf_prefetch(dnode_t * dn,int64_t level,uint64_t blkid,zio_priority_t prio,arc_flags_t aflags)3647 dbuf_prefetch(dnode_t *dn, int64_t level, uint64_t blkid, zio_priority_t prio,
3648     arc_flags_t aflags)
3649 {
3650 
3651 	return (dbuf_prefetch_impl(dn, level, blkid, prio, aflags, NULL, NULL));
3652 }
3653 
3654 /*
3655  * Helper function for dbuf_hold_impl() to copy a buffer. Handles
3656  * the case of encrypted, compressed and uncompressed buffers by
3657  * allocating the new buffer, respectively, with arc_alloc_raw_buf(),
3658  * arc_alloc_compressed_buf() or arc_alloc_buf().*
3659  *
3660  * NOTE: Declared noinline to avoid stack bloat in dbuf_hold_impl().
3661  */
3662 noinline static void
dbuf_hold_copy(dnode_t * dn,dmu_buf_impl_t * db)3663 dbuf_hold_copy(dnode_t *dn, dmu_buf_impl_t *db)
3664 {
3665 	dbuf_dirty_record_t *dr = db->db_data_pending;
3666 	arc_buf_t *data = dr->dt.dl.dr_data;
3667 	enum zio_compress compress_type = arc_get_compression(data);
3668 	uint8_t complevel = arc_get_complevel(data);
3669 
3670 	if (arc_is_encrypted(data)) {
3671 		boolean_t byteorder;
3672 		uint8_t salt[ZIO_DATA_SALT_LEN];
3673 		uint8_t iv[ZIO_DATA_IV_LEN];
3674 		uint8_t mac[ZIO_DATA_MAC_LEN];
3675 
3676 		arc_get_raw_params(data, &byteorder, salt, iv, mac);
3677 		dbuf_set_data(db, arc_alloc_raw_buf(dn->dn_objset->os_spa, db,
3678 		    dmu_objset_id(dn->dn_objset), byteorder, salt, iv, mac,
3679 		    dn->dn_type, arc_buf_size(data), arc_buf_lsize(data),
3680 		    compress_type, complevel));
3681 	} else if (compress_type != ZIO_COMPRESS_OFF) {
3682 		dbuf_set_data(db, arc_alloc_compressed_buf(
3683 		    dn->dn_objset->os_spa, db, arc_buf_size(data),
3684 		    arc_buf_lsize(data), compress_type, complevel));
3685 	} else {
3686 		dbuf_set_data(db, arc_alloc_buf(dn->dn_objset->os_spa, db,
3687 		    DBUF_GET_BUFC_TYPE(db), db->db.db_size));
3688 	}
3689 
3690 	rw_enter(&db->db_rwlock, RW_WRITER);
3691 	memcpy(db->db.db_data, data->b_data, arc_buf_size(data));
3692 	rw_exit(&db->db_rwlock);
3693 }
3694 
3695 /*
3696  * Returns with db_holds incremented, and db_mtx not held.
3697  * Note: dn_struct_rwlock must be held.
3698  */
3699 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)3700 dbuf_hold_impl(dnode_t *dn, uint8_t level, uint64_t blkid,
3701     boolean_t fail_sparse, boolean_t fail_uncached,
3702     const void *tag, dmu_buf_impl_t **dbp)
3703 {
3704 	dmu_buf_impl_t *db, *parent = NULL;
3705 	uint64_t hv;
3706 
3707 	/* If the pool has been created, verify the tx_sync_lock is not held */
3708 	spa_t *spa = dn->dn_objset->os_spa;
3709 	dsl_pool_t *dp = spa->spa_dsl_pool;
3710 	if (dp != NULL) {
3711 		ASSERT(!MUTEX_HELD(&dp->dp_tx.tx_sync_lock));
3712 	}
3713 
3714 	ASSERT(blkid != DMU_BONUS_BLKID);
3715 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
3716 	ASSERT3U(dn->dn_nlevels, >, level);
3717 
3718 	*dbp = NULL;
3719 
3720 	/* dbuf_find() returns with db_mtx held */
3721 	db = dbuf_find(dn->dn_objset, dn->dn_object, level, blkid, &hv);
3722 
3723 	if (db == NULL) {
3724 		blkptr_t *bp = NULL;
3725 		int err;
3726 
3727 		if (fail_uncached)
3728 			return (SET_ERROR(ENOENT));
3729 
3730 		ASSERT3P(parent, ==, NULL);
3731 		err = dbuf_findbp(dn, level, blkid, fail_sparse, &parent, &bp);
3732 		if (fail_sparse) {
3733 			if (err == 0 && bp && BP_IS_HOLE(bp))
3734 				err = SET_ERROR(ENOENT);
3735 			if (err) {
3736 				if (parent)
3737 					dbuf_rele(parent, NULL);
3738 				return (err);
3739 			}
3740 		}
3741 		if (err && err != ENOENT)
3742 			return (err);
3743 		db = dbuf_create(dn, level, blkid, parent, bp, hv);
3744 	}
3745 
3746 	if (fail_uncached && db->db_state != DB_CACHED) {
3747 		mutex_exit(&db->db_mtx);
3748 		return (SET_ERROR(ENOENT));
3749 	}
3750 
3751 	if (db->db_buf != NULL) {
3752 		arc_buf_access(db->db_buf);
3753 		ASSERT3P(db->db.db_data, ==, db->db_buf->b_data);
3754 	}
3755 
3756 	ASSERT(db->db_buf == NULL || arc_referenced(db->db_buf));
3757 
3758 	/*
3759 	 * If this buffer is currently syncing out, and we are
3760 	 * still referencing it from db_data, we need to make a copy
3761 	 * of it in case we decide we want to dirty it again in this txg.
3762 	 */
3763 	if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
3764 	    dn->dn_object != DMU_META_DNODE_OBJECT &&
3765 	    db->db_state == DB_CACHED && db->db_data_pending) {
3766 		dbuf_dirty_record_t *dr = db->db_data_pending;
3767 		if (dr->dt.dl.dr_data == db->db_buf) {
3768 			ASSERT3P(db->db_buf, !=, NULL);
3769 			dbuf_hold_copy(dn, db);
3770 		}
3771 	}
3772 
3773 	if (multilist_link_active(&db->db_cache_link)) {
3774 		ASSERT(zfs_refcount_is_zero(&db->db_holds));
3775 		ASSERT(db->db_caching_status == DB_DBUF_CACHE ||
3776 		    db->db_caching_status == DB_DBUF_METADATA_CACHE);
3777 
3778 		multilist_remove(&dbuf_caches[db->db_caching_status].cache, db);
3779 		(void) zfs_refcount_remove_many(
3780 		    &dbuf_caches[db->db_caching_status].size,
3781 		    db->db.db_size, db);
3782 
3783 		if (db->db_caching_status == DB_DBUF_METADATA_CACHE) {
3784 			DBUF_STAT_BUMPDOWN(metadata_cache_count);
3785 		} else {
3786 			DBUF_STAT_BUMPDOWN(cache_levels[db->db_level]);
3787 			DBUF_STAT_BUMPDOWN(cache_count);
3788 			DBUF_STAT_DECR(cache_levels_bytes[db->db_level],
3789 			    db->db.db_size);
3790 		}
3791 		db->db_caching_status = DB_NO_CACHE;
3792 	}
3793 	(void) zfs_refcount_add(&db->db_holds, tag);
3794 	DBUF_VERIFY(db);
3795 	mutex_exit(&db->db_mtx);
3796 
3797 	/* NOTE: we can't rele the parent until after we drop the db_mtx */
3798 	if (parent)
3799 		dbuf_rele(parent, NULL);
3800 
3801 	ASSERT3P(DB_DNODE(db), ==, dn);
3802 	ASSERT3U(db->db_blkid, ==, blkid);
3803 	ASSERT3U(db->db_level, ==, level);
3804 	*dbp = db;
3805 
3806 	return (0);
3807 }
3808 
3809 dmu_buf_impl_t *
dbuf_hold(dnode_t * dn,uint64_t blkid,const void * tag)3810 dbuf_hold(dnode_t *dn, uint64_t blkid, const void *tag)
3811 {
3812 	return (dbuf_hold_level(dn, 0, blkid, tag));
3813 }
3814 
3815 dmu_buf_impl_t *
dbuf_hold_level(dnode_t * dn,int level,uint64_t blkid,const void * tag)3816 dbuf_hold_level(dnode_t *dn, int level, uint64_t blkid, const void *tag)
3817 {
3818 	dmu_buf_impl_t *db;
3819 	int err = dbuf_hold_impl(dn, level, blkid, FALSE, FALSE, tag, &db);
3820 	return (err ? NULL : db);
3821 }
3822 
3823 void
dbuf_create_bonus(dnode_t * dn)3824 dbuf_create_bonus(dnode_t *dn)
3825 {
3826 	ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
3827 
3828 	ASSERT(dn->dn_bonus == NULL);
3829 	dn->dn_bonus = dbuf_create(dn, 0, DMU_BONUS_BLKID, dn->dn_dbuf, NULL,
3830 	    dbuf_hash(dn->dn_objset, dn->dn_object, 0, DMU_BONUS_BLKID));
3831 }
3832 
3833 int
dbuf_spill_set_blksz(dmu_buf_t * db_fake,uint64_t blksz,dmu_tx_t * tx)3834 dbuf_spill_set_blksz(dmu_buf_t *db_fake, uint64_t blksz, dmu_tx_t *tx)
3835 {
3836 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
3837 
3838 	if (db->db_blkid != DMU_SPILL_BLKID)
3839 		return (SET_ERROR(ENOTSUP));
3840 	if (blksz == 0)
3841 		blksz = SPA_MINBLOCKSIZE;
3842 	ASSERT3U(blksz, <=, spa_maxblocksize(dmu_objset_spa(db->db_objset)));
3843 	blksz = P2ROUNDUP(blksz, SPA_MINBLOCKSIZE);
3844 
3845 	dbuf_new_size(db, blksz, tx);
3846 
3847 	return (0);
3848 }
3849 
3850 void
dbuf_rm_spill(dnode_t * dn,dmu_tx_t * tx)3851 dbuf_rm_spill(dnode_t *dn, dmu_tx_t *tx)
3852 {
3853 	dbuf_free_range(dn, DMU_SPILL_BLKID, DMU_SPILL_BLKID, tx);
3854 }
3855 
3856 #pragma weak dmu_buf_add_ref = dbuf_add_ref
3857 void
dbuf_add_ref(dmu_buf_impl_t * db,const void * tag)3858 dbuf_add_ref(dmu_buf_impl_t *db, const void *tag)
3859 {
3860 	int64_t holds = zfs_refcount_add(&db->db_holds, tag);
3861 	VERIFY3S(holds, >, 1);
3862 }
3863 
3864 #pragma weak dmu_buf_try_add_ref = dbuf_try_add_ref
3865 boolean_t
dbuf_try_add_ref(dmu_buf_t * db_fake,objset_t * os,uint64_t obj,uint64_t blkid,const void * tag)3866 dbuf_try_add_ref(dmu_buf_t *db_fake, objset_t *os, uint64_t obj, uint64_t blkid,
3867     const void *tag)
3868 {
3869 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
3870 	dmu_buf_impl_t *found_db;
3871 	boolean_t result = B_FALSE;
3872 
3873 	if (blkid == DMU_BONUS_BLKID)
3874 		found_db = dbuf_find_bonus(os, obj);
3875 	else
3876 		found_db = dbuf_find(os, obj, 0, blkid, NULL);
3877 
3878 	if (found_db != NULL) {
3879 		if (db == found_db && dbuf_refcount(db) > db->db_dirtycnt) {
3880 			(void) zfs_refcount_add(&db->db_holds, tag);
3881 			result = B_TRUE;
3882 		}
3883 		mutex_exit(&found_db->db_mtx);
3884 	}
3885 	return (result);
3886 }
3887 
3888 /*
3889  * If you call dbuf_rele() you had better not be referencing the dnode handle
3890  * unless you have some other direct or indirect hold on the dnode. (An indirect
3891  * hold is a hold on one of the dnode's dbufs, including the bonus buffer.)
3892  * Without that, the dbuf_rele() could lead to a dnode_rele() followed by the
3893  * dnode's parent dbuf evicting its dnode handles.
3894  */
3895 void
dbuf_rele(dmu_buf_impl_t * db,const void * tag)3896 dbuf_rele(dmu_buf_impl_t *db, const void *tag)
3897 {
3898 	mutex_enter(&db->db_mtx);
3899 	dbuf_rele_and_unlock(db, tag, B_FALSE);
3900 }
3901 
3902 void
dmu_buf_rele(dmu_buf_t * db,const void * tag)3903 dmu_buf_rele(dmu_buf_t *db, const void *tag)
3904 {
3905 	dbuf_rele((dmu_buf_impl_t *)db, tag);
3906 }
3907 
3908 /*
3909  * dbuf_rele() for an already-locked dbuf.  This is necessary to allow
3910  * db_dirtycnt and db_holds to be updated atomically.  The 'evicting'
3911  * argument should be set if we are already in the dbuf-evicting code
3912  * path, in which case we don't want to recursively evict.  This allows us to
3913  * avoid deeply nested stacks that would have a call flow similar to this:
3914  *
3915  * dbuf_rele()-->dbuf_rele_and_unlock()-->dbuf_evict_notify()
3916  *	^						|
3917  *	|						|
3918  *	+-----dbuf_destroy()<--dbuf_evict_one()<--------+
3919  *
3920  */
3921 void
dbuf_rele_and_unlock(dmu_buf_impl_t * db,const void * tag,boolean_t evicting)3922 dbuf_rele_and_unlock(dmu_buf_impl_t *db, const void *tag, boolean_t evicting)
3923 {
3924 	int64_t holds;
3925 	uint64_t size;
3926 
3927 	ASSERT(MUTEX_HELD(&db->db_mtx));
3928 	DBUF_VERIFY(db);
3929 
3930 	/*
3931 	 * Remove the reference to the dbuf before removing its hold on the
3932 	 * dnode so we can guarantee in dnode_move() that a referenced bonus
3933 	 * buffer has a corresponding dnode hold.
3934 	 */
3935 	holds = zfs_refcount_remove(&db->db_holds, tag);
3936 	ASSERT(holds >= 0);
3937 
3938 	/*
3939 	 * We can't freeze indirects if there is a possibility that they
3940 	 * may be modified in the current syncing context.
3941 	 */
3942 	if (db->db_buf != NULL &&
3943 	    holds == (db->db_level == 0 ? db->db_dirtycnt : 0)) {
3944 		arc_buf_freeze(db->db_buf);
3945 	}
3946 
3947 	if (holds == db->db_dirtycnt &&
3948 	    db->db_level == 0 && db->db_user_immediate_evict)
3949 		dbuf_evict_user(db);
3950 
3951 	if (holds == 0) {
3952 		if (db->db_blkid == DMU_BONUS_BLKID) {
3953 			dnode_t *dn;
3954 			boolean_t evict_dbuf = db->db_pending_evict;
3955 
3956 			/*
3957 			 * If the dnode moves here, we cannot cross this
3958 			 * barrier until the move completes.
3959 			 */
3960 			DB_DNODE_ENTER(db);
3961 
3962 			dn = DB_DNODE(db);
3963 			atomic_dec_32(&dn->dn_dbufs_count);
3964 
3965 			/*
3966 			 * Decrementing the dbuf count means that the bonus
3967 			 * buffer's dnode hold is no longer discounted in
3968 			 * dnode_move(). The dnode cannot move until after
3969 			 * the dnode_rele() below.
3970 			 */
3971 			DB_DNODE_EXIT(db);
3972 
3973 			/*
3974 			 * Do not reference db after its lock is dropped.
3975 			 * Another thread may evict it.
3976 			 */
3977 			mutex_exit(&db->db_mtx);
3978 
3979 			if (evict_dbuf)
3980 				dnode_evict_bonus(dn);
3981 
3982 			dnode_rele(dn, db);
3983 		} else if (db->db_buf == NULL) {
3984 			/*
3985 			 * This is a special case: we never associated this
3986 			 * dbuf with any data allocated from the ARC.
3987 			 */
3988 			ASSERT(db->db_state == DB_UNCACHED ||
3989 			    db->db_state == DB_NOFILL);
3990 			dbuf_destroy(db);
3991 		} else if (arc_released(db->db_buf)) {
3992 			/*
3993 			 * This dbuf has anonymous data associated with it.
3994 			 */
3995 			dbuf_destroy(db);
3996 		} else if (!(DBUF_IS_CACHEABLE(db) || db->db_partial_read) ||
3997 		    db->db_pending_evict) {
3998 			dbuf_destroy(db);
3999 		} else if (!multilist_link_active(&db->db_cache_link)) {
4000 			ASSERT3U(db->db_caching_status, ==, DB_NO_CACHE);
4001 
4002 			dbuf_cached_state_t dcs =
4003 			    dbuf_include_in_metadata_cache(db) ?
4004 			    DB_DBUF_METADATA_CACHE : DB_DBUF_CACHE;
4005 			db->db_caching_status = dcs;
4006 
4007 			multilist_insert(&dbuf_caches[dcs].cache, db);
4008 			uint64_t db_size = db->db.db_size;
4009 			size = zfs_refcount_add_many(
4010 			    &dbuf_caches[dcs].size, db_size, db);
4011 			uint8_t db_level = db->db_level;
4012 			mutex_exit(&db->db_mtx);
4013 
4014 			if (dcs == DB_DBUF_METADATA_CACHE) {
4015 				DBUF_STAT_BUMP(metadata_cache_count);
4016 				DBUF_STAT_MAX(metadata_cache_size_bytes_max,
4017 				    size);
4018 			} else {
4019 				DBUF_STAT_BUMP(cache_count);
4020 				DBUF_STAT_MAX(cache_size_bytes_max, size);
4021 				DBUF_STAT_BUMP(cache_levels[db_level]);
4022 				DBUF_STAT_INCR(cache_levels_bytes[db_level],
4023 				    db_size);
4024 			}
4025 
4026 			if (dcs == DB_DBUF_CACHE && !evicting)
4027 				dbuf_evict_notify(size);
4028 		}
4029 	} else {
4030 		mutex_exit(&db->db_mtx);
4031 	}
4032 
4033 }
4034 
4035 #pragma weak dmu_buf_refcount = dbuf_refcount
4036 uint64_t
dbuf_refcount(dmu_buf_impl_t * db)4037 dbuf_refcount(dmu_buf_impl_t *db)
4038 {
4039 	return (zfs_refcount_count(&db->db_holds));
4040 }
4041 
4042 uint64_t
dmu_buf_user_refcount(dmu_buf_t * db_fake)4043 dmu_buf_user_refcount(dmu_buf_t *db_fake)
4044 {
4045 	uint64_t holds;
4046 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
4047 
4048 	mutex_enter(&db->db_mtx);
4049 	ASSERT3U(zfs_refcount_count(&db->db_holds), >=, db->db_dirtycnt);
4050 	holds = zfs_refcount_count(&db->db_holds) - db->db_dirtycnt;
4051 	mutex_exit(&db->db_mtx);
4052 
4053 	return (holds);
4054 }
4055 
4056 void *
dmu_buf_replace_user(dmu_buf_t * db_fake,dmu_buf_user_t * old_user,dmu_buf_user_t * new_user)4057 dmu_buf_replace_user(dmu_buf_t *db_fake, dmu_buf_user_t *old_user,
4058     dmu_buf_user_t *new_user)
4059 {
4060 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
4061 
4062 	mutex_enter(&db->db_mtx);
4063 	dbuf_verify_user(db, DBVU_NOT_EVICTING);
4064 	if (db->db_user == old_user)
4065 		db->db_user = new_user;
4066 	else
4067 		old_user = db->db_user;
4068 	dbuf_verify_user(db, DBVU_NOT_EVICTING);
4069 	mutex_exit(&db->db_mtx);
4070 
4071 	return (old_user);
4072 }
4073 
4074 void *
dmu_buf_set_user(dmu_buf_t * db_fake,dmu_buf_user_t * user)4075 dmu_buf_set_user(dmu_buf_t *db_fake, dmu_buf_user_t *user)
4076 {
4077 	return (dmu_buf_replace_user(db_fake, NULL, user));
4078 }
4079 
4080 void *
dmu_buf_set_user_ie(dmu_buf_t * db_fake,dmu_buf_user_t * user)4081 dmu_buf_set_user_ie(dmu_buf_t *db_fake, dmu_buf_user_t *user)
4082 {
4083 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
4084 
4085 	db->db_user_immediate_evict = TRUE;
4086 	return (dmu_buf_set_user(db_fake, user));
4087 }
4088 
4089 void *
dmu_buf_remove_user(dmu_buf_t * db_fake,dmu_buf_user_t * user)4090 dmu_buf_remove_user(dmu_buf_t *db_fake, dmu_buf_user_t *user)
4091 {
4092 	return (dmu_buf_replace_user(db_fake, user, NULL));
4093 }
4094 
4095 void *
dmu_buf_get_user(dmu_buf_t * db_fake)4096 dmu_buf_get_user(dmu_buf_t *db_fake)
4097 {
4098 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
4099 
4100 	dbuf_verify_user(db, DBVU_NOT_EVICTING);
4101 	return (db->db_user);
4102 }
4103 
4104 void
dmu_buf_user_evict_wait(void)4105 dmu_buf_user_evict_wait(void)
4106 {
4107 	taskq_wait(dbu_evict_taskq);
4108 }
4109 
4110 blkptr_t *
dmu_buf_get_blkptr(dmu_buf_t * db)4111 dmu_buf_get_blkptr(dmu_buf_t *db)
4112 {
4113 	dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
4114 	return (dbi->db_blkptr);
4115 }
4116 
4117 objset_t *
dmu_buf_get_objset(dmu_buf_t * db)4118 dmu_buf_get_objset(dmu_buf_t *db)
4119 {
4120 	dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
4121 	return (dbi->db_objset);
4122 }
4123 
4124 static void
dbuf_check_blkptr(dnode_t * dn,dmu_buf_impl_t * db)4125 dbuf_check_blkptr(dnode_t *dn, dmu_buf_impl_t *db)
4126 {
4127 	/* ASSERT(dmu_tx_is_syncing(tx) */
4128 	ASSERT(MUTEX_HELD(&db->db_mtx));
4129 
4130 	if (db->db_blkptr != NULL)
4131 		return;
4132 
4133 	if (db->db_blkid == DMU_SPILL_BLKID) {
4134 		db->db_blkptr = DN_SPILL_BLKPTR(dn->dn_phys);
4135 		BP_ZERO(db->db_blkptr);
4136 		return;
4137 	}
4138 	if (db->db_level == dn->dn_phys->dn_nlevels-1) {
4139 		/*
4140 		 * This buffer was allocated at a time when there was
4141 		 * no available blkptrs from the dnode, or it was
4142 		 * inappropriate to hook it in (i.e., nlevels mismatch).
4143 		 */
4144 		ASSERT(db->db_blkid < dn->dn_phys->dn_nblkptr);
4145 		ASSERT(db->db_parent == NULL);
4146 		db->db_parent = dn->dn_dbuf;
4147 		db->db_blkptr = &dn->dn_phys->dn_blkptr[db->db_blkid];
4148 		DBUF_VERIFY(db);
4149 	} else {
4150 		dmu_buf_impl_t *parent = db->db_parent;
4151 		int epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
4152 
4153 		ASSERT(dn->dn_phys->dn_nlevels > 1);
4154 		if (parent == NULL) {
4155 			mutex_exit(&db->db_mtx);
4156 			rw_enter(&dn->dn_struct_rwlock, RW_READER);
4157 			parent = dbuf_hold_level(dn, db->db_level + 1,
4158 			    db->db_blkid >> epbs, db);
4159 			rw_exit(&dn->dn_struct_rwlock);
4160 			mutex_enter(&db->db_mtx);
4161 			db->db_parent = parent;
4162 		}
4163 		db->db_blkptr = (blkptr_t *)parent->db.db_data +
4164 		    (db->db_blkid & ((1ULL << epbs) - 1));
4165 		DBUF_VERIFY(db);
4166 	}
4167 }
4168 
4169 static void
dbuf_sync_bonus(dbuf_dirty_record_t * dr,dmu_tx_t * tx)4170 dbuf_sync_bonus(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
4171 {
4172 	dmu_buf_impl_t *db = dr->dr_dbuf;
4173 	void *data = dr->dt.dl.dr_data;
4174 
4175 	ASSERT0(db->db_level);
4176 	ASSERT(MUTEX_HELD(&db->db_mtx));
4177 	ASSERT(db->db_blkid == DMU_BONUS_BLKID);
4178 	ASSERT(data != NULL);
4179 
4180 	dnode_t *dn = dr->dr_dnode;
4181 	ASSERT3U(DN_MAX_BONUS_LEN(dn->dn_phys), <=,
4182 	    DN_SLOTS_TO_BONUSLEN(dn->dn_phys->dn_extra_slots + 1));
4183 	memcpy(DN_BONUS(dn->dn_phys), data, DN_MAX_BONUS_LEN(dn->dn_phys));
4184 
4185 	dbuf_sync_leaf_verify_bonus_dnode(dr);
4186 
4187 	dbuf_undirty_bonus(dr);
4188 	dbuf_rele_and_unlock(db, (void *)(uintptr_t)tx->tx_txg, B_FALSE);
4189 }
4190 
4191 /*
4192  * When syncing out a blocks of dnodes, adjust the block to deal with
4193  * encryption.  Normally, we make sure the block is decrypted before writing
4194  * it.  If we have crypt params, then we are writing a raw (encrypted) block,
4195  * from a raw receive.  In this case, set the ARC buf's crypt params so
4196  * that the BP will be filled with the correct byteorder, salt, iv, and mac.
4197  */
4198 static void
dbuf_prepare_encrypted_dnode_leaf(dbuf_dirty_record_t * dr)4199 dbuf_prepare_encrypted_dnode_leaf(dbuf_dirty_record_t *dr)
4200 {
4201 	int err;
4202 	dmu_buf_impl_t *db = dr->dr_dbuf;
4203 
4204 	ASSERT(MUTEX_HELD(&db->db_mtx));
4205 	ASSERT3U(db->db.db_object, ==, DMU_META_DNODE_OBJECT);
4206 	ASSERT3U(db->db_level, ==, 0);
4207 
4208 	if (!db->db_objset->os_raw_receive && arc_is_encrypted(db->db_buf)) {
4209 		zbookmark_phys_t zb;
4210 
4211 		/*
4212 		 * Unfortunately, there is currently no mechanism for
4213 		 * syncing context to handle decryption errors. An error
4214 		 * here is only possible if an attacker maliciously
4215 		 * changed a dnode block and updated the associated
4216 		 * checksums going up the block tree.
4217 		 */
4218 		SET_BOOKMARK(&zb, dmu_objset_id(db->db_objset),
4219 		    db->db.db_object, db->db_level, db->db_blkid);
4220 		err = arc_untransform(db->db_buf, db->db_objset->os_spa,
4221 		    &zb, B_TRUE);
4222 		if (err)
4223 			panic("Invalid dnode block MAC");
4224 	} else if (dr->dt.dl.dr_has_raw_params) {
4225 		(void) arc_release(dr->dt.dl.dr_data, db);
4226 		arc_convert_to_raw(dr->dt.dl.dr_data,
4227 		    dmu_objset_id(db->db_objset),
4228 		    dr->dt.dl.dr_byteorder, DMU_OT_DNODE,
4229 		    dr->dt.dl.dr_salt, dr->dt.dl.dr_iv, dr->dt.dl.dr_mac);
4230 	}
4231 }
4232 
4233 /*
4234  * dbuf_sync_indirect() is called recursively from dbuf_sync_list() so it
4235  * is critical the we not allow the compiler to inline this function in to
4236  * dbuf_sync_list() thereby drastically bloating the stack usage.
4237  */
4238 noinline static void
dbuf_sync_indirect(dbuf_dirty_record_t * dr,dmu_tx_t * tx)4239 dbuf_sync_indirect(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
4240 {
4241 	dmu_buf_impl_t *db = dr->dr_dbuf;
4242 	dnode_t *dn = dr->dr_dnode;
4243 
4244 	ASSERT(dmu_tx_is_syncing(tx));
4245 
4246 	dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
4247 
4248 	mutex_enter(&db->db_mtx);
4249 
4250 	ASSERT(db->db_level > 0);
4251 	DBUF_VERIFY(db);
4252 
4253 	/* Read the block if it hasn't been read yet. */
4254 	if (db->db_buf == NULL) {
4255 		mutex_exit(&db->db_mtx);
4256 		(void) dbuf_read(db, NULL, DB_RF_MUST_SUCCEED);
4257 		mutex_enter(&db->db_mtx);
4258 	}
4259 	ASSERT3U(db->db_state, ==, DB_CACHED);
4260 	ASSERT(db->db_buf != NULL);
4261 
4262 	/* Indirect block size must match what the dnode thinks it is. */
4263 	ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
4264 	dbuf_check_blkptr(dn, db);
4265 
4266 	/* Provide the pending dirty record to child dbufs */
4267 	db->db_data_pending = dr;
4268 
4269 	mutex_exit(&db->db_mtx);
4270 
4271 	dbuf_write(dr, db->db_buf, tx);
4272 
4273 	zio_t *zio = dr->dr_zio;
4274 	mutex_enter(&dr->dt.di.dr_mtx);
4275 	dbuf_sync_list(&dr->dt.di.dr_children, db->db_level - 1, tx);
4276 	ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
4277 	mutex_exit(&dr->dt.di.dr_mtx);
4278 	zio_nowait(zio);
4279 }
4280 
4281 /*
4282  * Verify that the size of the data in our bonus buffer does not exceed
4283  * its recorded size.
4284  *
4285  * The purpose of this verification is to catch any cases in development
4286  * where the size of a phys structure (i.e space_map_phys_t) grows and,
4287  * due to incorrect feature management, older pools expect to read more
4288  * data even though they didn't actually write it to begin with.
4289  *
4290  * For a example, this would catch an error in the feature logic where we
4291  * open an older pool and we expect to write the space map histogram of
4292  * a space map with size SPACE_MAP_SIZE_V0.
4293  */
4294 static void
dbuf_sync_leaf_verify_bonus_dnode(dbuf_dirty_record_t * dr)4295 dbuf_sync_leaf_verify_bonus_dnode(dbuf_dirty_record_t *dr)
4296 {
4297 #ifdef ZFS_DEBUG
4298 	dnode_t *dn = dr->dr_dnode;
4299 
4300 	/*
4301 	 * Encrypted bonus buffers can have data past their bonuslen.
4302 	 * Skip the verification of these blocks.
4303 	 */
4304 	if (DMU_OT_IS_ENCRYPTED(dn->dn_bonustype))
4305 		return;
4306 
4307 	uint16_t bonuslen = dn->dn_phys->dn_bonuslen;
4308 	uint16_t maxbonuslen = DN_SLOTS_TO_BONUSLEN(dn->dn_num_slots);
4309 	ASSERT3U(bonuslen, <=, maxbonuslen);
4310 
4311 	arc_buf_t *datap = dr->dt.dl.dr_data;
4312 	char *datap_end = ((char *)datap) + bonuslen;
4313 	char *datap_max = ((char *)datap) + maxbonuslen;
4314 
4315 	/* ensure that everything is zero after our data */
4316 	for (; datap_end < datap_max; datap_end++)
4317 		ASSERT(*datap_end == 0);
4318 #endif
4319 }
4320 
4321 static blkptr_t *
dbuf_lightweight_bp(dbuf_dirty_record_t * dr)4322 dbuf_lightweight_bp(dbuf_dirty_record_t *dr)
4323 {
4324 	/* This must be a lightweight dirty record. */
4325 	ASSERT3P(dr->dr_dbuf, ==, NULL);
4326 	dnode_t *dn = dr->dr_dnode;
4327 
4328 	if (dn->dn_phys->dn_nlevels == 1) {
4329 		VERIFY3U(dr->dt.dll.dr_blkid, <, dn->dn_phys->dn_nblkptr);
4330 		return (&dn->dn_phys->dn_blkptr[dr->dt.dll.dr_blkid]);
4331 	} else {
4332 		dmu_buf_impl_t *parent_db = dr->dr_parent->dr_dbuf;
4333 		int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
4334 		VERIFY3U(parent_db->db_level, ==, 1);
4335 		VERIFY3P(parent_db->db_dnode_handle->dnh_dnode, ==, dn);
4336 		VERIFY3U(dr->dt.dll.dr_blkid >> epbs, ==, parent_db->db_blkid);
4337 		blkptr_t *bp = parent_db->db.db_data;
4338 		return (&bp[dr->dt.dll.dr_blkid & ((1 << epbs) - 1)]);
4339 	}
4340 }
4341 
4342 static void
dbuf_lightweight_ready(zio_t * zio)4343 dbuf_lightweight_ready(zio_t *zio)
4344 {
4345 	dbuf_dirty_record_t *dr = zio->io_private;
4346 	blkptr_t *bp = zio->io_bp;
4347 
4348 	if (zio->io_error != 0)
4349 		return;
4350 
4351 	dnode_t *dn = dr->dr_dnode;
4352 
4353 	blkptr_t *bp_orig = dbuf_lightweight_bp(dr);
4354 	spa_t *spa = dmu_objset_spa(dn->dn_objset);
4355 	int64_t delta = bp_get_dsize_sync(spa, bp) -
4356 	    bp_get_dsize_sync(spa, bp_orig);
4357 	dnode_diduse_space(dn, delta);
4358 
4359 	uint64_t blkid = dr->dt.dll.dr_blkid;
4360 	mutex_enter(&dn->dn_mtx);
4361 	if (blkid > dn->dn_phys->dn_maxblkid) {
4362 		ASSERT0(dn->dn_objset->os_raw_receive);
4363 		dn->dn_phys->dn_maxblkid = blkid;
4364 	}
4365 	mutex_exit(&dn->dn_mtx);
4366 
4367 	if (!BP_IS_EMBEDDED(bp)) {
4368 		uint64_t fill = BP_IS_HOLE(bp) ? 0 : 1;
4369 		BP_SET_FILL(bp, fill);
4370 	}
4371 
4372 	dmu_buf_impl_t *parent_db;
4373 	EQUIV(dr->dr_parent == NULL, dn->dn_phys->dn_nlevels == 1);
4374 	if (dr->dr_parent == NULL) {
4375 		parent_db = dn->dn_dbuf;
4376 	} else {
4377 		parent_db = dr->dr_parent->dr_dbuf;
4378 	}
4379 	rw_enter(&parent_db->db_rwlock, RW_WRITER);
4380 	*bp_orig = *bp;
4381 	rw_exit(&parent_db->db_rwlock);
4382 }
4383 
4384 static void
dbuf_lightweight_done(zio_t * zio)4385 dbuf_lightweight_done(zio_t *zio)
4386 {
4387 	dbuf_dirty_record_t *dr = zio->io_private;
4388 
4389 	VERIFY0(zio->io_error);
4390 
4391 	objset_t *os = dr->dr_dnode->dn_objset;
4392 	dmu_tx_t *tx = os->os_synctx;
4393 
4394 	if (zio->io_flags & (ZIO_FLAG_IO_REWRITE | ZIO_FLAG_NOPWRITE)) {
4395 		ASSERT(BP_EQUAL(zio->io_bp, &zio->io_bp_orig));
4396 	} else {
4397 		dsl_dataset_t *ds = os->os_dsl_dataset;
4398 		(void) dsl_dataset_block_kill(ds, &zio->io_bp_orig, tx, B_TRUE);
4399 		dsl_dataset_block_born(ds, zio->io_bp, tx);
4400 	}
4401 
4402 	dsl_pool_undirty_space(dmu_objset_pool(os), dr->dr_accounted,
4403 	    zio->io_txg);
4404 
4405 	abd_free(dr->dt.dll.dr_abd);
4406 	kmem_free(dr, sizeof (*dr));
4407 }
4408 
4409 noinline static void
dbuf_sync_lightweight(dbuf_dirty_record_t * dr,dmu_tx_t * tx)4410 dbuf_sync_lightweight(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
4411 {
4412 	dnode_t *dn = dr->dr_dnode;
4413 	zio_t *pio;
4414 	if (dn->dn_phys->dn_nlevels == 1) {
4415 		pio = dn->dn_zio;
4416 	} else {
4417 		pio = dr->dr_parent->dr_zio;
4418 	}
4419 
4420 	zbookmark_phys_t zb = {
4421 		.zb_objset = dmu_objset_id(dn->dn_objset),
4422 		.zb_object = dn->dn_object,
4423 		.zb_level = 0,
4424 		.zb_blkid = dr->dt.dll.dr_blkid,
4425 	};
4426 
4427 	/*
4428 	 * See comment in dbuf_write().  This is so that zio->io_bp_orig
4429 	 * will have the old BP in dbuf_lightweight_done().
4430 	 */
4431 	dr->dr_bp_copy = *dbuf_lightweight_bp(dr);
4432 
4433 	dr->dr_zio = zio_write(pio, dmu_objset_spa(dn->dn_objset),
4434 	    dmu_tx_get_txg(tx), &dr->dr_bp_copy, dr->dt.dll.dr_abd,
4435 	    dn->dn_datablksz, abd_get_size(dr->dt.dll.dr_abd),
4436 	    &dr->dt.dll.dr_props, dbuf_lightweight_ready, NULL,
4437 	    dbuf_lightweight_done, dr, ZIO_PRIORITY_ASYNC_WRITE,
4438 	    ZIO_FLAG_MUSTSUCCEED | dr->dt.dll.dr_flags, &zb);
4439 
4440 	zio_nowait(dr->dr_zio);
4441 }
4442 
4443 /*
4444  * dbuf_sync_leaf() is called recursively from dbuf_sync_list() so it is
4445  * critical the we not allow the compiler to inline this function in to
4446  * dbuf_sync_list() thereby drastically bloating the stack usage.
4447  */
4448 noinline static void
dbuf_sync_leaf(dbuf_dirty_record_t * dr,dmu_tx_t * tx)4449 dbuf_sync_leaf(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
4450 {
4451 	arc_buf_t **datap = &dr->dt.dl.dr_data;
4452 	dmu_buf_impl_t *db = dr->dr_dbuf;
4453 	dnode_t *dn = dr->dr_dnode;
4454 	objset_t *os;
4455 	uint64_t txg = tx->tx_txg;
4456 
4457 	ASSERT(dmu_tx_is_syncing(tx));
4458 
4459 	dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
4460 
4461 	mutex_enter(&db->db_mtx);
4462 	/*
4463 	 * To be synced, we must be dirtied.  But we
4464 	 * might have been freed after the dirty.
4465 	 */
4466 	if (db->db_state == DB_UNCACHED) {
4467 		/* This buffer has been freed since it was dirtied */
4468 		ASSERT(db->db.db_data == NULL);
4469 	} else if (db->db_state == DB_FILL) {
4470 		/* This buffer was freed and is now being re-filled */
4471 		ASSERT(db->db.db_data != dr->dt.dl.dr_data);
4472 	} else if (db->db_state == DB_READ) {
4473 		/*
4474 		 * This buffer has a clone we need to write, and an in-flight
4475 		 * read on the BP we're about to clone. Its safe to issue the
4476 		 * write here because the read has already been issued and the
4477 		 * contents won't change.
4478 		 */
4479 		ASSERT(dr->dt.dl.dr_brtwrite &&
4480 		    dr->dt.dl.dr_override_state == DR_OVERRIDDEN);
4481 	} else {
4482 		ASSERT(db->db_state == DB_CACHED || db->db_state == DB_NOFILL);
4483 	}
4484 	DBUF_VERIFY(db);
4485 
4486 	if (db->db_blkid == DMU_SPILL_BLKID) {
4487 		mutex_enter(&dn->dn_mtx);
4488 		if (!(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR)) {
4489 			/*
4490 			 * In the previous transaction group, the bonus buffer
4491 			 * was entirely used to store the attributes for the
4492 			 * dnode which overrode the dn_spill field.  However,
4493 			 * when adding more attributes to the file a spill
4494 			 * block was required to hold the extra attributes.
4495 			 *
4496 			 * Make sure to clear the garbage left in the dn_spill
4497 			 * field from the previous attributes in the bonus
4498 			 * buffer.  Otherwise, after writing out the spill
4499 			 * block to the new allocated dva, it will free
4500 			 * the old block pointed to by the invalid dn_spill.
4501 			 */
4502 			db->db_blkptr = NULL;
4503 		}
4504 		dn->dn_phys->dn_flags |= DNODE_FLAG_SPILL_BLKPTR;
4505 		mutex_exit(&dn->dn_mtx);
4506 	}
4507 
4508 	/*
4509 	 * If this is a bonus buffer, simply copy the bonus data into the
4510 	 * dnode.  It will be written out when the dnode is synced (and it
4511 	 * will be synced, since it must have been dirty for dbuf_sync to
4512 	 * be called).
4513 	 */
4514 	if (db->db_blkid == DMU_BONUS_BLKID) {
4515 		ASSERT(dr->dr_dbuf == db);
4516 		dbuf_sync_bonus(dr, tx);
4517 		return;
4518 	}
4519 
4520 	os = dn->dn_objset;
4521 
4522 	/*
4523 	 * This function may have dropped the db_mtx lock allowing a dmu_sync
4524 	 * operation to sneak in. As a result, we need to ensure that we
4525 	 * don't check the dr_override_state until we have returned from
4526 	 * dbuf_check_blkptr.
4527 	 */
4528 	dbuf_check_blkptr(dn, db);
4529 
4530 	/*
4531 	 * If this buffer is in the middle of an immediate write,
4532 	 * wait for the synchronous IO to complete.
4533 	 */
4534 	while (dr->dt.dl.dr_override_state == DR_IN_DMU_SYNC) {
4535 		ASSERT(dn->dn_object != DMU_META_DNODE_OBJECT);
4536 		cv_wait(&db->db_changed, &db->db_mtx);
4537 	}
4538 
4539 	/*
4540 	 * If this is a dnode block, ensure it is appropriately encrypted
4541 	 * or decrypted, depending on what we are writing to it this txg.
4542 	 */
4543 	if (os->os_encrypted && dn->dn_object == DMU_META_DNODE_OBJECT)
4544 		dbuf_prepare_encrypted_dnode_leaf(dr);
4545 
4546 	if (*datap != NULL && *datap == db->db_buf &&
4547 	    dn->dn_object != DMU_META_DNODE_OBJECT &&
4548 	    zfs_refcount_count(&db->db_holds) > 1 &&
4549 	    dr->dt.dl.dr_override_state != DR_OVERRIDDEN) {
4550 		/*
4551 		 * If this buffer is currently "in use" (i.e., there
4552 		 * are active holds and db_data still references it),
4553 		 * then make a copy before we start the write so that
4554 		 * any modifications from the open txg will not leak
4555 		 * into this write.
4556 		 *
4557 		 * NOTE: this copy does not need to be made for
4558 		 * objects only modified in the syncing context (e.g.
4559 		 * DNONE_DNODE blocks).
4560 		 */
4561 		int psize = arc_buf_size(*datap);
4562 		int lsize = arc_buf_lsize(*datap);
4563 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
4564 		enum zio_compress compress_type = arc_get_compression(*datap);
4565 		uint8_t complevel = arc_get_complevel(*datap);
4566 
4567 		if (arc_is_encrypted(*datap)) {
4568 			boolean_t byteorder;
4569 			uint8_t salt[ZIO_DATA_SALT_LEN];
4570 			uint8_t iv[ZIO_DATA_IV_LEN];
4571 			uint8_t mac[ZIO_DATA_MAC_LEN];
4572 
4573 			arc_get_raw_params(*datap, &byteorder, salt, iv, mac);
4574 			*datap = arc_alloc_raw_buf(os->os_spa, db,
4575 			    dmu_objset_id(os), byteorder, salt, iv, mac,
4576 			    dn->dn_type, psize, lsize, compress_type,
4577 			    complevel);
4578 		} else if (compress_type != ZIO_COMPRESS_OFF) {
4579 			ASSERT3U(type, ==, ARC_BUFC_DATA);
4580 			*datap = arc_alloc_compressed_buf(os->os_spa, db,
4581 			    psize, lsize, compress_type, complevel);
4582 		} else {
4583 			*datap = arc_alloc_buf(os->os_spa, db, type, psize);
4584 		}
4585 		memcpy((*datap)->b_data, db->db.db_data, psize);
4586 	}
4587 	db->db_data_pending = dr;
4588 
4589 	mutex_exit(&db->db_mtx);
4590 
4591 	dbuf_write(dr, *datap, tx);
4592 
4593 	ASSERT(!list_link_active(&dr->dr_dirty_node));
4594 	if (dn->dn_object == DMU_META_DNODE_OBJECT) {
4595 		list_insert_tail(&dn->dn_dirty_records[txg & TXG_MASK], dr);
4596 	} else {
4597 		zio_nowait(dr->dr_zio);
4598 	}
4599 }
4600 
4601 void
dbuf_sync_list(list_t * list,int level,dmu_tx_t * tx)4602 dbuf_sync_list(list_t *list, int level, dmu_tx_t *tx)
4603 {
4604 	dbuf_dirty_record_t *dr;
4605 
4606 	while ((dr = list_head(list))) {
4607 		if (dr->dr_zio != NULL) {
4608 			/*
4609 			 * If we find an already initialized zio then we
4610 			 * are processing the meta-dnode, and we have finished.
4611 			 * The dbufs for all dnodes are put back on the list
4612 			 * during processing, so that we can zio_wait()
4613 			 * these IOs after initiating all child IOs.
4614 			 */
4615 			ASSERT3U(dr->dr_dbuf->db.db_object, ==,
4616 			    DMU_META_DNODE_OBJECT);
4617 			break;
4618 		}
4619 		list_remove(list, dr);
4620 		if (dr->dr_dbuf == NULL) {
4621 			dbuf_sync_lightweight(dr, tx);
4622 		} else {
4623 			if (dr->dr_dbuf->db_blkid != DMU_BONUS_BLKID &&
4624 			    dr->dr_dbuf->db_blkid != DMU_SPILL_BLKID) {
4625 				VERIFY3U(dr->dr_dbuf->db_level, ==, level);
4626 			}
4627 			if (dr->dr_dbuf->db_level > 0)
4628 				dbuf_sync_indirect(dr, tx);
4629 			else
4630 				dbuf_sync_leaf(dr, tx);
4631 		}
4632 	}
4633 }
4634 
4635 static void
dbuf_write_ready(zio_t * zio,arc_buf_t * buf,void * vdb)4636 dbuf_write_ready(zio_t *zio, arc_buf_t *buf, void *vdb)
4637 {
4638 	(void) buf;
4639 	dmu_buf_impl_t *db = vdb;
4640 	dnode_t *dn;
4641 	blkptr_t *bp = zio->io_bp;
4642 	blkptr_t *bp_orig = &zio->io_bp_orig;
4643 	spa_t *spa = zio->io_spa;
4644 	int64_t delta;
4645 	uint64_t fill = 0;
4646 	int i;
4647 
4648 	ASSERT3P(db->db_blkptr, !=, NULL);
4649 	ASSERT3P(&db->db_data_pending->dr_bp_copy, ==, bp);
4650 
4651 	DB_DNODE_ENTER(db);
4652 	dn = DB_DNODE(db);
4653 	delta = bp_get_dsize_sync(spa, bp) - bp_get_dsize_sync(spa, bp_orig);
4654 	dnode_diduse_space(dn, delta - zio->io_prev_space_delta);
4655 	zio->io_prev_space_delta = delta;
4656 
4657 	if (bp->blk_birth != 0) {
4658 		ASSERT((db->db_blkid != DMU_SPILL_BLKID &&
4659 		    BP_GET_TYPE(bp) == dn->dn_type) ||
4660 		    (db->db_blkid == DMU_SPILL_BLKID &&
4661 		    BP_GET_TYPE(bp) == dn->dn_bonustype) ||
4662 		    BP_IS_EMBEDDED(bp));
4663 		ASSERT(BP_GET_LEVEL(bp) == db->db_level);
4664 	}
4665 
4666 	mutex_enter(&db->db_mtx);
4667 
4668 #ifdef ZFS_DEBUG
4669 	if (db->db_blkid == DMU_SPILL_BLKID) {
4670 		ASSERT(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR);
4671 		ASSERT(!(BP_IS_HOLE(bp)) &&
4672 		    db->db_blkptr == DN_SPILL_BLKPTR(dn->dn_phys));
4673 	}
4674 #endif
4675 
4676 	if (db->db_level == 0) {
4677 		mutex_enter(&dn->dn_mtx);
4678 		if (db->db_blkid > dn->dn_phys->dn_maxblkid &&
4679 		    db->db_blkid != DMU_SPILL_BLKID) {
4680 			ASSERT0(db->db_objset->os_raw_receive);
4681 			dn->dn_phys->dn_maxblkid = db->db_blkid;
4682 		}
4683 		mutex_exit(&dn->dn_mtx);
4684 
4685 		if (dn->dn_type == DMU_OT_DNODE) {
4686 			i = 0;
4687 			while (i < db->db.db_size) {
4688 				dnode_phys_t *dnp =
4689 				    (void *)(((char *)db->db.db_data) + i);
4690 
4691 				i += DNODE_MIN_SIZE;
4692 				if (dnp->dn_type != DMU_OT_NONE) {
4693 					fill++;
4694 					for (int j = 0; j < dnp->dn_nblkptr;
4695 					    j++) {
4696 						(void) zfs_blkptr_verify(spa,
4697 						    &dnp->dn_blkptr[j],
4698 						    BLK_CONFIG_SKIP,
4699 						    BLK_VERIFY_HALT);
4700 					}
4701 					if (dnp->dn_flags &
4702 					    DNODE_FLAG_SPILL_BLKPTR) {
4703 						(void) zfs_blkptr_verify(spa,
4704 						    DN_SPILL_BLKPTR(dnp),
4705 						    BLK_CONFIG_SKIP,
4706 						    BLK_VERIFY_HALT);
4707 					}
4708 					i += dnp->dn_extra_slots *
4709 					    DNODE_MIN_SIZE;
4710 				}
4711 			}
4712 		} else {
4713 			if (BP_IS_HOLE(bp)) {
4714 				fill = 0;
4715 			} else {
4716 				fill = 1;
4717 			}
4718 		}
4719 	} else {
4720 		blkptr_t *ibp = db->db.db_data;
4721 		ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
4722 		for (i = db->db.db_size >> SPA_BLKPTRSHIFT; i > 0; i--, ibp++) {
4723 			if (BP_IS_HOLE(ibp))
4724 				continue;
4725 			(void) zfs_blkptr_verify(spa, ibp,
4726 			    BLK_CONFIG_SKIP, BLK_VERIFY_HALT);
4727 			fill += BP_GET_FILL(ibp);
4728 		}
4729 	}
4730 	DB_DNODE_EXIT(db);
4731 
4732 	if (!BP_IS_EMBEDDED(bp))
4733 		BP_SET_FILL(bp, fill);
4734 
4735 	mutex_exit(&db->db_mtx);
4736 
4737 	db_lock_type_t dblt = dmu_buf_lock_parent(db, RW_WRITER, FTAG);
4738 	*db->db_blkptr = *bp;
4739 	dmu_buf_unlock_parent(db, dblt, FTAG);
4740 }
4741 
4742 /*
4743  * This function gets called just prior to running through the compression
4744  * stage of the zio pipeline. If we're an indirect block comprised of only
4745  * holes, then we want this indirect to be compressed away to a hole. In
4746  * order to do that we must zero out any information about the holes that
4747  * this indirect points to prior to before we try to compress it.
4748  */
4749 static void
dbuf_write_children_ready(zio_t * zio,arc_buf_t * buf,void * vdb)4750 dbuf_write_children_ready(zio_t *zio, arc_buf_t *buf, void *vdb)
4751 {
4752 	(void) zio, (void) buf;
4753 	dmu_buf_impl_t *db = vdb;
4754 	dnode_t *dn;
4755 	blkptr_t *bp;
4756 	unsigned int epbs, i;
4757 
4758 	ASSERT3U(db->db_level, >, 0);
4759 	DB_DNODE_ENTER(db);
4760 	dn = DB_DNODE(db);
4761 	epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
4762 	ASSERT3U(epbs, <, 31);
4763 
4764 	/* Determine if all our children are holes */
4765 	for (i = 0, bp = db->db.db_data; i < 1ULL << epbs; i++, bp++) {
4766 		if (!BP_IS_HOLE(bp))
4767 			break;
4768 	}
4769 
4770 	/*
4771 	 * If all the children are holes, then zero them all out so that
4772 	 * we may get compressed away.
4773 	 */
4774 	if (i == 1ULL << epbs) {
4775 		/*
4776 		 * We only found holes. Grab the rwlock to prevent
4777 		 * anybody from reading the blocks we're about to
4778 		 * zero out.
4779 		 */
4780 		rw_enter(&db->db_rwlock, RW_WRITER);
4781 		memset(db->db.db_data, 0, db->db.db_size);
4782 		rw_exit(&db->db_rwlock);
4783 	}
4784 	DB_DNODE_EXIT(db);
4785 }
4786 
4787 static void
dbuf_write_done(zio_t * zio,arc_buf_t * buf,void * vdb)4788 dbuf_write_done(zio_t *zio, arc_buf_t *buf, void *vdb)
4789 {
4790 	(void) buf;
4791 	dmu_buf_impl_t *db = vdb;
4792 	blkptr_t *bp_orig = &zio->io_bp_orig;
4793 	blkptr_t *bp = db->db_blkptr;
4794 	objset_t *os = db->db_objset;
4795 	dmu_tx_t *tx = os->os_synctx;
4796 
4797 	ASSERT0(zio->io_error);
4798 	ASSERT(db->db_blkptr == bp);
4799 
4800 	/*
4801 	 * For nopwrites and rewrites we ensure that the bp matches our
4802 	 * original and bypass all the accounting.
4803 	 */
4804 	if (zio->io_flags & (ZIO_FLAG_IO_REWRITE | ZIO_FLAG_NOPWRITE)) {
4805 		ASSERT(BP_EQUAL(bp, bp_orig));
4806 	} else {
4807 		dsl_dataset_t *ds = os->os_dsl_dataset;
4808 		(void) dsl_dataset_block_kill(ds, bp_orig, tx, B_TRUE);
4809 		dsl_dataset_block_born(ds, bp, tx);
4810 	}
4811 
4812 	mutex_enter(&db->db_mtx);
4813 
4814 	DBUF_VERIFY(db);
4815 
4816 	dbuf_dirty_record_t *dr = db->db_data_pending;
4817 	dnode_t *dn = dr->dr_dnode;
4818 	ASSERT(!list_link_active(&dr->dr_dirty_node));
4819 	ASSERT(dr->dr_dbuf == db);
4820 	ASSERT(list_next(&db->db_dirty_records, dr) == NULL);
4821 	list_remove(&db->db_dirty_records, dr);
4822 
4823 #ifdef ZFS_DEBUG
4824 	if (db->db_blkid == DMU_SPILL_BLKID) {
4825 		ASSERT(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR);
4826 		ASSERT(!(BP_IS_HOLE(db->db_blkptr)) &&
4827 		    db->db_blkptr == DN_SPILL_BLKPTR(dn->dn_phys));
4828 	}
4829 #endif
4830 
4831 	if (db->db_level == 0) {
4832 		ASSERT(db->db_blkid != DMU_BONUS_BLKID);
4833 		ASSERT(dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN);
4834 		if (dr->dt.dl.dr_data != NULL &&
4835 		    dr->dt.dl.dr_data != db->db_buf) {
4836 			arc_buf_destroy(dr->dt.dl.dr_data, db);
4837 		}
4838 	} else {
4839 		ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
4840 		ASSERT3U(db->db.db_size, ==, 1 << dn->dn_phys->dn_indblkshift);
4841 		if (!BP_IS_HOLE(db->db_blkptr)) {
4842 			int epbs __maybe_unused = dn->dn_phys->dn_indblkshift -
4843 			    SPA_BLKPTRSHIFT;
4844 			ASSERT3U(db->db_blkid, <=,
4845 			    dn->dn_phys->dn_maxblkid >> (db->db_level * epbs));
4846 			ASSERT3U(BP_GET_LSIZE(db->db_blkptr), ==,
4847 			    db->db.db_size);
4848 		}
4849 		mutex_destroy(&dr->dt.di.dr_mtx);
4850 		list_destroy(&dr->dt.di.dr_children);
4851 	}
4852 
4853 	cv_broadcast(&db->db_changed);
4854 	ASSERT(db->db_dirtycnt > 0);
4855 	db->db_dirtycnt -= 1;
4856 	db->db_data_pending = NULL;
4857 	dbuf_rele_and_unlock(db, (void *)(uintptr_t)tx->tx_txg, B_FALSE);
4858 
4859 	dsl_pool_undirty_space(dmu_objset_pool(os), dr->dr_accounted,
4860 	    zio->io_txg);
4861 
4862 	kmem_free(dr, sizeof (dbuf_dirty_record_t));
4863 }
4864 
4865 static void
dbuf_write_nofill_ready(zio_t * zio)4866 dbuf_write_nofill_ready(zio_t *zio)
4867 {
4868 	dbuf_write_ready(zio, NULL, zio->io_private);
4869 }
4870 
4871 static void
dbuf_write_nofill_done(zio_t * zio)4872 dbuf_write_nofill_done(zio_t *zio)
4873 {
4874 	dbuf_write_done(zio, NULL, zio->io_private);
4875 }
4876 
4877 static void
dbuf_write_override_ready(zio_t * zio)4878 dbuf_write_override_ready(zio_t *zio)
4879 {
4880 	dbuf_dirty_record_t *dr = zio->io_private;
4881 	dmu_buf_impl_t *db = dr->dr_dbuf;
4882 
4883 	dbuf_write_ready(zio, NULL, db);
4884 }
4885 
4886 static void
dbuf_write_override_done(zio_t * zio)4887 dbuf_write_override_done(zio_t *zio)
4888 {
4889 	dbuf_dirty_record_t *dr = zio->io_private;
4890 	dmu_buf_impl_t *db = dr->dr_dbuf;
4891 	blkptr_t *obp = &dr->dt.dl.dr_overridden_by;
4892 
4893 	mutex_enter(&db->db_mtx);
4894 	if (!BP_EQUAL(zio->io_bp, obp)) {
4895 		if (!BP_IS_HOLE(obp))
4896 			dsl_free(spa_get_dsl(zio->io_spa), zio->io_txg, obp);
4897 		arc_release(dr->dt.dl.dr_data, db);
4898 	}
4899 	mutex_exit(&db->db_mtx);
4900 
4901 	dbuf_write_done(zio, NULL, db);
4902 
4903 	if (zio->io_abd != NULL)
4904 		abd_free(zio->io_abd);
4905 }
4906 
4907 typedef struct dbuf_remap_impl_callback_arg {
4908 	objset_t	*drica_os;
4909 	uint64_t	drica_blk_birth;
4910 	dmu_tx_t	*drica_tx;
4911 } dbuf_remap_impl_callback_arg_t;
4912 
4913 static void
dbuf_remap_impl_callback(uint64_t vdev,uint64_t offset,uint64_t size,void * arg)4914 dbuf_remap_impl_callback(uint64_t vdev, uint64_t offset, uint64_t size,
4915     void *arg)
4916 {
4917 	dbuf_remap_impl_callback_arg_t *drica = arg;
4918 	objset_t *os = drica->drica_os;
4919 	spa_t *spa = dmu_objset_spa(os);
4920 	dmu_tx_t *tx = drica->drica_tx;
4921 
4922 	ASSERT(dsl_pool_sync_context(spa_get_dsl(spa)));
4923 
4924 	if (os == spa_meta_objset(spa)) {
4925 		spa_vdev_indirect_mark_obsolete(spa, vdev, offset, size, tx);
4926 	} else {
4927 		dsl_dataset_block_remapped(dmu_objset_ds(os), vdev, offset,
4928 		    size, drica->drica_blk_birth, tx);
4929 	}
4930 }
4931 
4932 static void
dbuf_remap_impl(dnode_t * dn,blkptr_t * bp,krwlock_t * rw,dmu_tx_t * tx)4933 dbuf_remap_impl(dnode_t *dn, blkptr_t *bp, krwlock_t *rw, dmu_tx_t *tx)
4934 {
4935 	blkptr_t bp_copy = *bp;
4936 	spa_t *spa = dmu_objset_spa(dn->dn_objset);
4937 	dbuf_remap_impl_callback_arg_t drica;
4938 
4939 	ASSERT(dsl_pool_sync_context(spa_get_dsl(spa)));
4940 
4941 	drica.drica_os = dn->dn_objset;
4942 	drica.drica_blk_birth = bp->blk_birth;
4943 	drica.drica_tx = tx;
4944 	if (spa_remap_blkptr(spa, &bp_copy, dbuf_remap_impl_callback,
4945 	    &drica)) {
4946 		/*
4947 		 * If the blkptr being remapped is tracked by a livelist,
4948 		 * then we need to make sure the livelist reflects the update.
4949 		 * First, cancel out the old blkptr by appending a 'FREE'
4950 		 * entry. Next, add an 'ALLOC' to track the new version. This
4951 		 * way we avoid trying to free an inaccurate blkptr at delete.
4952 		 * Note that embedded blkptrs are not tracked in livelists.
4953 		 */
4954 		if (dn->dn_objset != spa_meta_objset(spa)) {
4955 			dsl_dataset_t *ds = dmu_objset_ds(dn->dn_objset);
4956 			if (dsl_deadlist_is_open(&ds->ds_dir->dd_livelist) &&
4957 			    bp->blk_birth > ds->ds_dir->dd_origin_txg) {
4958 				ASSERT(!BP_IS_EMBEDDED(bp));
4959 				ASSERT(dsl_dir_is_clone(ds->ds_dir));
4960 				ASSERT(spa_feature_is_enabled(spa,
4961 				    SPA_FEATURE_LIVELIST));
4962 				bplist_append(&ds->ds_dir->dd_pending_frees,
4963 				    bp);
4964 				bplist_append(&ds->ds_dir->dd_pending_allocs,
4965 				    &bp_copy);
4966 			}
4967 		}
4968 
4969 		/*
4970 		 * The db_rwlock prevents dbuf_read_impl() from
4971 		 * dereferencing the BP while we are changing it.  To
4972 		 * avoid lock contention, only grab it when we are actually
4973 		 * changing the BP.
4974 		 */
4975 		if (rw != NULL)
4976 			rw_enter(rw, RW_WRITER);
4977 		*bp = bp_copy;
4978 		if (rw != NULL)
4979 			rw_exit(rw);
4980 	}
4981 }
4982 
4983 /*
4984  * Remap any existing BP's to concrete vdevs, if possible.
4985  */
4986 static void
dbuf_remap(dnode_t * dn,dmu_buf_impl_t * db,dmu_tx_t * tx)4987 dbuf_remap(dnode_t *dn, dmu_buf_impl_t *db, dmu_tx_t *tx)
4988 {
4989 	spa_t *spa = dmu_objset_spa(db->db_objset);
4990 	ASSERT(dsl_pool_sync_context(spa_get_dsl(spa)));
4991 
4992 	if (!spa_feature_is_active(spa, SPA_FEATURE_DEVICE_REMOVAL))
4993 		return;
4994 
4995 	if (db->db_level > 0) {
4996 		blkptr_t *bp = db->db.db_data;
4997 		for (int i = 0; i < db->db.db_size >> SPA_BLKPTRSHIFT; i++) {
4998 			dbuf_remap_impl(dn, &bp[i], &db->db_rwlock, tx);
4999 		}
5000 	} else if (db->db.db_object == DMU_META_DNODE_OBJECT) {
5001 		dnode_phys_t *dnp = db->db.db_data;
5002 		ASSERT3U(db->db_dnode_handle->dnh_dnode->dn_type, ==,
5003 		    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