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