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