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