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