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