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 (!is_hole && db->db_level == 0)
1485 is_hole = dnode_block_freed(dn, db->db_blkid) || BP_IS_HOLE(bp);
1486
1487 if (is_hole) {
1488 db_data = dbuf_alloc_arcbuf(db);
1489 memset(db_data->b_data, 0, db->db.db_size);
1490
1491 if (bp != NULL && db->db_level > 0 && BP_IS_HOLE(bp) &&
1492 BP_GET_LOGICAL_BIRTH(bp) != 0) {
1493 dbuf_handle_indirect_hole(db_data->b_data, dn, bp);
1494 }
1495 dbuf_set_data(db, db_data);
1496 db->db_state = DB_CACHED;
1497 DTRACE_SET_STATE(db, "hole read satisfied");
1498 return (0);
1499 }
1500 return (ENOENT);
1501 }
1502
1503 /*
1504 * This function ensures that, when doing a decrypting read of a block,
1505 * we make sure we have decrypted the dnode associated with it. We must do
1506 * this so that we ensure we are fully authenticating the checksum-of-MACs
1507 * tree from the root of the objset down to this block. Indirect blocks are
1508 * always verified against their secure checksum-of-MACs assuming that the
1509 * dnode containing them is correct. Now that we are doing a decrypting read,
1510 * we can be sure that the key is loaded and verify that assumption. This is
1511 * especially important considering that we always read encrypted dnode
1512 * blocks as raw data (without verifying their MACs) to start, and
1513 * decrypt / authenticate them when we need to read an encrypted bonus buffer.
1514 */
1515 static int
dbuf_read_verify_dnode_crypt(dmu_buf_impl_t * db,dnode_t * dn,dmu_flags_t flags)1516 dbuf_read_verify_dnode_crypt(dmu_buf_impl_t *db, dnode_t *dn,
1517 dmu_flags_t flags)
1518 {
1519 objset_t *os = db->db_objset;
1520 dmu_buf_impl_t *dndb;
1521 arc_buf_t *dnbuf;
1522 zbookmark_phys_t zb;
1523 int err;
1524
1525 if ((flags & DMU_READ_NO_DECRYPT) != 0 ||
1526 !os->os_encrypted || os->os_raw_receive ||
1527 (dndb = dn->dn_dbuf) == NULL)
1528 return (0);
1529
1530 dnbuf = dndb->db_buf;
1531 if (!arc_is_encrypted(dnbuf))
1532 return (0);
1533
1534 mutex_enter(&dndb->db_mtx);
1535
1536 /*
1537 * Since dnode buffer is modified by sync process, there can be only
1538 * one copy of it. It means we can not modify (decrypt) it while it
1539 * is being written. I don't see how this may happen now, since
1540 * encrypted dnode writes by receive should be completed before any
1541 * plain-text reads due to txg wait, but better be safe than sorry.
1542 */
1543 while (1) {
1544 if (!arc_is_encrypted(dnbuf)) {
1545 mutex_exit(&dndb->db_mtx);
1546 return (0);
1547 }
1548 dbuf_dirty_record_t *dr = dndb->db_data_pending;
1549 if (dr == NULL || dr->dt.dl.dr_data != dnbuf)
1550 break;
1551 cv_wait(&dndb->db_changed, &dndb->db_mtx);
1552 };
1553
1554 SET_BOOKMARK(&zb, dmu_objset_id(os),
1555 DMU_META_DNODE_OBJECT, 0, dndb->db_blkid);
1556 err = arc_untransform(dnbuf, os->os_spa, &zb, B_TRUE);
1557
1558 /*
1559 * An error code of EACCES tells us that the key is still not
1560 * available. This is ok if we are only reading authenticated
1561 * (and therefore non-encrypted) blocks.
1562 */
1563 if (err == EACCES && ((db->db_blkid != DMU_BONUS_BLKID &&
1564 !DMU_OT_IS_ENCRYPTED(dn->dn_type)) ||
1565 (db->db_blkid == DMU_BONUS_BLKID &&
1566 !DMU_OT_IS_ENCRYPTED(dn->dn_bonustype))))
1567 err = 0;
1568
1569 mutex_exit(&dndb->db_mtx);
1570
1571 return (err);
1572 }
1573
1574 /*
1575 * Drops db_mtx and the parent lock specified by dblt and tag before
1576 * returning.
1577 */
1578 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)1579 dbuf_read_impl(dmu_buf_impl_t *db, dnode_t *dn, zio_t *zio, dmu_flags_t flags,
1580 db_lock_type_t dblt, blkptr_t *bp, const void *tag)
1581 {
1582 zbookmark_phys_t zb;
1583 uint32_t aflags = ARC_FLAG_NOWAIT;
1584 int err, zio_flags;
1585
1586 ASSERT(!zfs_refcount_is_zero(&db->db_holds));
1587 ASSERT(MUTEX_HELD(&db->db_mtx));
1588 ASSERT(db->db_state == DB_UNCACHED || db->db_state == DB_NOFILL);
1589 ASSERT0P(db->db_buf);
1590 ASSERT(db->db_parent == NULL ||
1591 RW_LOCK_HELD(&db->db_parent->db_rwlock));
1592
1593 if (db->db_blkid == DMU_BONUS_BLKID) {
1594 err = dbuf_read_bonus(db, dn);
1595 goto early_unlock;
1596 }
1597
1598 err = dbuf_read_hole(db, dn, bp);
1599 if (err == 0)
1600 goto early_unlock;
1601
1602 ASSERT(bp != NULL);
1603
1604 /*
1605 * Any attempt to read a redacted block should result in an error. This
1606 * will never happen under normal conditions, but can be useful for
1607 * debugging purposes.
1608 */
1609 if (BP_IS_REDACTED(bp)) {
1610 ASSERT(dsl_dataset_feature_is_active(
1611 db->db_objset->os_dsl_dataset,
1612 SPA_FEATURE_REDACTED_DATASETS));
1613 err = SET_ERROR(EIO);
1614 goto early_unlock;
1615 }
1616
1617 SET_BOOKMARK(&zb, dmu_objset_id(db->db_objset),
1618 db->db.db_object, db->db_level, db->db_blkid);
1619
1620 /*
1621 * All bps of an encrypted os should have the encryption bit set.
1622 * If this is not true it indicates tampering and we report an error.
1623 */
1624 if (db->db_objset->os_encrypted && !BP_USES_CRYPT(bp)) {
1625 spa_log_error(db->db_objset->os_spa, &zb,
1626 BP_GET_PHYSICAL_BIRTH(bp));
1627 err = SET_ERROR(EIO);
1628 goto early_unlock;
1629 }
1630
1631 db->db_state = DB_READ;
1632 DTRACE_SET_STATE(db, "read issued");
1633 mutex_exit(&db->db_mtx);
1634
1635 if (!DBUF_IS_CACHEABLE(db))
1636 aflags |= ARC_FLAG_UNCACHED;
1637 else if (dbuf_is_l2cacheable(db, bp))
1638 aflags |= ARC_FLAG_L2CACHE;
1639 if (flags & DMU_IS_PREFETCH)
1640 aflags |= ARC_FLAG_PREFETCH | ARC_FLAG_PRESCIENT_PREFETCH;
1641
1642 dbuf_add_ref(db, NULL);
1643
1644 zio_flags = (flags & DB_RF_CANFAIL) ?
1645 ZIO_FLAG_CANFAIL : ZIO_FLAG_MUSTSUCCEED;
1646
1647 if ((flags & DMU_READ_NO_DECRYPT) && BP_IS_PROTECTED(bp))
1648 zio_flags |= ZIO_FLAG_RAW;
1649
1650 /*
1651 * The zio layer will copy the provided blkptr later, but we need to
1652 * do this now so that we can release the parent's rwlock. We have to
1653 * do that now so that if dbuf_read_done is called synchronously (on
1654 * an l1 cache hit) we don't acquire the db_mtx while holding the
1655 * parent's rwlock, which would be a lock ordering violation.
1656 */
1657 blkptr_t copy = *bp;
1658 dmu_buf_unlock_parent(db, dblt, tag);
1659 return (arc_read(zio, db->db_objset->os_spa, ©,
1660 dbuf_read_done, db, ZIO_PRIORITY_SYNC_READ, zio_flags,
1661 &aflags, &zb));
1662
1663 early_unlock:
1664 mutex_exit(&db->db_mtx);
1665 dmu_buf_unlock_parent(db, dblt, tag);
1666 return (err);
1667 }
1668
1669 /*
1670 * This is our just-in-time copy function. It makes a copy of buffers that
1671 * have been modified in a previous transaction group before we access them in
1672 * the current active group.
1673 *
1674 * This function is used in three places: when we are dirtying a buffer for the
1675 * first time in a txg, when we are freeing a range in a dnode that includes
1676 * this buffer, and when we are accessing a buffer which was received compressed
1677 * and later referenced in a WRITE_BYREF record.
1678 *
1679 * Note that when we are called from dbuf_free_range() we do not put a hold on
1680 * the buffer, we just traverse the active dbuf list for the dnode.
1681 */
1682 static void
dbuf_fix_old_data(dmu_buf_impl_t * db,uint64_t txg)1683 dbuf_fix_old_data(dmu_buf_impl_t *db, uint64_t txg)
1684 {
1685 dbuf_dirty_record_t *dr = list_head(&db->db_dirty_records);
1686
1687 ASSERT(MUTEX_HELD(&db->db_mtx));
1688 ASSERT(db->db.db_data != NULL);
1689 ASSERT0(db->db_level);
1690 ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT);
1691
1692 if (dr == NULL ||
1693 (dr->dt.dl.dr_data !=
1694 ((db->db_blkid == DMU_BONUS_BLKID) ? db->db.db_data : db->db_buf)))
1695 return;
1696
1697 /*
1698 * If the last dirty record for this dbuf has not yet synced
1699 * and its referencing the dbuf data, either:
1700 * reset the reference to point to a new copy,
1701 * or (if there a no active holders)
1702 * just null out the current db_data pointer.
1703 */
1704 ASSERT3U(dr->dr_txg, >=, txg - 2);
1705 if (db->db_blkid == DMU_BONUS_BLKID) {
1706 dnode_t *dn = DB_DNODE(db);
1707 int bonuslen = DN_SLOTS_TO_BONUSLEN(dn->dn_num_slots);
1708 dr->dt.dl.dr_data = kmem_alloc(bonuslen, KM_SLEEP);
1709 arc_space_consume(bonuslen, ARC_SPACE_BONUS);
1710 memcpy(dr->dt.dl.dr_data, db->db.db_data, bonuslen);
1711 } else if (zfs_refcount_count(&db->db_holds) > db->db_dirtycnt) {
1712 dnode_t *dn = DB_DNODE(db);
1713 int size = arc_buf_size(db->db_buf);
1714 arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1715 spa_t *spa = db->db_objset->os_spa;
1716 enum zio_compress compress_type =
1717 arc_get_compression(db->db_buf);
1718 uint8_t complevel = arc_get_complevel(db->db_buf);
1719
1720 if (arc_is_encrypted(db->db_buf)) {
1721 boolean_t byteorder;
1722 uint8_t salt[ZIO_DATA_SALT_LEN];
1723 uint8_t iv[ZIO_DATA_IV_LEN];
1724 uint8_t mac[ZIO_DATA_MAC_LEN];
1725
1726 arc_get_raw_params(db->db_buf, &byteorder, salt,
1727 iv, mac);
1728 dr->dt.dl.dr_data = arc_alloc_raw_buf(spa, db,
1729 dmu_objset_id(dn->dn_objset), byteorder, salt, iv,
1730 mac, dn->dn_type, size, arc_buf_lsize(db->db_buf),
1731 compress_type, complevel);
1732 } else if (compress_type != ZIO_COMPRESS_OFF) {
1733 ASSERT3U(type, ==, ARC_BUFC_DATA);
1734 dr->dt.dl.dr_data = arc_alloc_compressed_buf(spa, db,
1735 size, arc_buf_lsize(db->db_buf), compress_type,
1736 complevel);
1737 } else {
1738 dr->dt.dl.dr_data = arc_alloc_buf(spa, db, type, size);
1739 }
1740 memcpy(dr->dt.dl.dr_data->b_data, db->db.db_data, size);
1741 } else {
1742 db->db_buf = NULL;
1743 dbuf_clear_data(db);
1744 }
1745 }
1746
1747 int
dbuf_read(dmu_buf_impl_t * db,zio_t * pio,dmu_flags_t flags)1748 dbuf_read(dmu_buf_impl_t *db, zio_t *pio, dmu_flags_t flags)
1749 {
1750 dnode_t *dn;
1751 boolean_t miss = B_TRUE, need_wait = B_FALSE, prefetch;
1752 int err;
1753
1754 ASSERT(!zfs_refcount_is_zero(&db->db_holds));
1755
1756 DB_DNODE_ENTER(db);
1757 dn = DB_DNODE(db);
1758
1759 /*
1760 * Ensure that this block's dnode has been decrypted if the caller
1761 * has requested decrypted data.
1762 */
1763 err = dbuf_read_verify_dnode_crypt(db, dn, flags);
1764 if (err != 0)
1765 goto done;
1766
1767 prefetch = db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
1768 (flags & DMU_READ_NO_PREFETCH) == 0;
1769
1770 mutex_enter(&db->db_mtx);
1771 if (!(flags & (DMU_UNCACHEDIO | DMU_KEEP_CACHING)))
1772 db->db_pending_evict = B_FALSE;
1773 if (flags & (DMU_PARTIAL_FIRST | DMU_IS_PREFETCH))
1774 db->db_partial_read = B_TRUE;
1775 else if (!(flags & (DMU_PARTIAL_MORE | DMU_KEEP_CACHING)))
1776 db->db_partial_read = B_FALSE;
1777 miss = (db->db_state != DB_CACHED);
1778
1779 if (db->db_state == DB_READ || db->db_state == DB_FILL) {
1780 /*
1781 * Another reader came in while the dbuf was in flight between
1782 * UNCACHED and CACHED. Either a writer will finish filling
1783 * the buffer, sending the dbuf to CACHED, or the first reader's
1784 * request will reach the read_done callback and send the dbuf
1785 * to CACHED. Otherwise, a failure occurred and the dbuf will
1786 * be sent to UNCACHED.
1787 */
1788 if (flags & DB_RF_NEVERWAIT) {
1789 mutex_exit(&db->db_mtx);
1790 DB_DNODE_EXIT(db);
1791 goto done;
1792 }
1793 do {
1794 ASSERT(db->db_state == DB_READ ||
1795 (flags & DB_RF_HAVESTRUCT) == 0);
1796 DTRACE_PROBE2(blocked__read, dmu_buf_impl_t *, db,
1797 zio_t *, pio);
1798 cv_wait(&db->db_changed, &db->db_mtx);
1799 } while (db->db_state == DB_READ || db->db_state == DB_FILL);
1800 if (db->db_state == DB_UNCACHED) {
1801 err = SET_ERROR(EIO);
1802 mutex_exit(&db->db_mtx);
1803 DB_DNODE_EXIT(db);
1804 goto done;
1805 }
1806 }
1807
1808 if (db->db_state == DB_CACHED) {
1809 /*
1810 * If the arc buf is compressed or encrypted and the caller
1811 * requested uncompressed data, we need to untransform it
1812 * before returning. We also call arc_untransform() on any
1813 * unauthenticated blocks, which will verify their MAC if
1814 * the key is now available.
1815 */
1816 if ((flags & DMU_READ_NO_DECRYPT) == 0 && db->db_buf != NULL &&
1817 (arc_is_encrypted(db->db_buf) ||
1818 arc_is_unauthenticated(db->db_buf) ||
1819 arc_get_compression(db->db_buf) != ZIO_COMPRESS_OFF)) {
1820 spa_t *spa = dn->dn_objset->os_spa;
1821 zbookmark_phys_t zb;
1822
1823 SET_BOOKMARK(&zb, dmu_objset_id(db->db_objset),
1824 db->db.db_object, db->db_level, db->db_blkid);
1825 dbuf_fix_old_data(db, spa_syncing_txg(spa));
1826 err = arc_untransform(db->db_buf, spa, &zb, B_FALSE);
1827 dbuf_set_data(db, db->db_buf);
1828 }
1829 mutex_exit(&db->db_mtx);
1830 } else {
1831 ASSERT(db->db_state == DB_UNCACHED ||
1832 db->db_state == DB_NOFILL);
1833 db_lock_type_t dblt = dmu_buf_lock_parent(db, RW_READER, FTAG);
1834 blkptr_t *bp;
1835
1836 /*
1837 * If a block clone or Direct I/O write has occurred we will
1838 * get the dirty records overridden BP so we get the most
1839 * recent data.
1840 */
1841 err = dmu_buf_get_bp_from_dbuf(db, &bp);
1842
1843 if (!err) {
1844 if (pio == NULL && (db->db_state == DB_NOFILL ||
1845 (bp != NULL && !BP_IS_HOLE(bp)))) {
1846 spa_t *spa = dn->dn_objset->os_spa;
1847 pio =
1848 zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL);
1849 need_wait = B_TRUE;
1850 }
1851
1852 err =
1853 dbuf_read_impl(db, dn, pio, flags, dblt, bp, FTAG);
1854 } else {
1855 mutex_exit(&db->db_mtx);
1856 dmu_buf_unlock_parent(db, dblt, FTAG);
1857 }
1858 /* dbuf_read_impl drops db_mtx and parent's rwlock. */
1859 miss = (db->db_state != DB_CACHED);
1860 }
1861
1862 if (err == 0 && prefetch) {
1863 dmu_zfetch(&dn->dn_zfetch, db->db_blkid, 1, B_TRUE, miss,
1864 flags & DB_RF_HAVESTRUCT, (flags & DMU_UNCACHEDIO) ||
1865 db->db_pending_evict);
1866 }
1867 DB_DNODE_EXIT(db);
1868
1869 /*
1870 * If we created a zio we must execute it to avoid leaking it, even if
1871 * it isn't attached to any work due to an error in dbuf_read_impl().
1872 */
1873 if (need_wait) {
1874 if (err == 0)
1875 err = zio_wait(pio);
1876 else
1877 (void) zio_wait(pio);
1878 pio = NULL;
1879 }
1880
1881 done:
1882 if (miss)
1883 DBUF_STAT_BUMP(hash_misses);
1884 else
1885 DBUF_STAT_BUMP(hash_hits);
1886 if (pio && err != 0) {
1887 zio_t *zio = zio_null(pio, pio->io_spa, NULL, NULL, NULL,
1888 ZIO_FLAG_CANFAIL);
1889 zio->io_error = err;
1890 zio_nowait(zio);
1891 }
1892
1893 return (err);
1894 }
1895
1896 static void
dbuf_noread(dmu_buf_impl_t * db,dmu_flags_t flags)1897 dbuf_noread(dmu_buf_impl_t *db, dmu_flags_t flags)
1898 {
1899 ASSERT(!zfs_refcount_is_zero(&db->db_holds));
1900 ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1901 mutex_enter(&db->db_mtx);
1902 if (!(flags & (DMU_UNCACHEDIO | DMU_KEEP_CACHING)))
1903 db->db_pending_evict = B_FALSE;
1904 db->db_partial_read = B_FALSE;
1905 while (db->db_state == DB_READ || db->db_state == DB_FILL)
1906 cv_wait(&db->db_changed, &db->db_mtx);
1907 if (db->db_state == DB_UNCACHED) {
1908 ASSERT0P(db->db_buf);
1909 ASSERT0P(db->db.db_data);
1910 dbuf_set_data(db, dbuf_alloc_arcbuf(db));
1911 db->db_state = DB_FILL;
1912 DTRACE_SET_STATE(db, "assigning filled buffer");
1913 } else if (db->db_state == DB_NOFILL) {
1914 dbuf_clear_data(db);
1915 } else {
1916 ASSERT3U(db->db_state, ==, DB_CACHED);
1917 }
1918 mutex_exit(&db->db_mtx);
1919 }
1920
1921 void
dbuf_unoverride(dbuf_dirty_record_t * dr)1922 dbuf_unoverride(dbuf_dirty_record_t *dr)
1923 {
1924 dmu_buf_impl_t *db = dr->dr_dbuf;
1925 blkptr_t *bp = &dr->dt.dl.dr_overridden_by;
1926 uint64_t txg = dr->dr_txg;
1927
1928 ASSERT(MUTEX_HELD(&db->db_mtx));
1929
1930 /*
1931 * This assert is valid because dmu_sync() expects to be called by
1932 * a zilog's get_data while holding a range lock. This call only
1933 * comes from dbuf_dirty() callers who must also hold a range lock.
1934 */
1935 ASSERT(dr->dt.dl.dr_override_state != DR_IN_DMU_SYNC);
1936 ASSERT0(db->db_level);
1937
1938 if (db->db_blkid == DMU_BONUS_BLKID ||
1939 dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN)
1940 return;
1941
1942 ASSERT(db->db_data_pending != dr);
1943
1944 /* free this block */
1945 if (!BP_IS_HOLE(bp) && !dr->dt.dl.dr_nopwrite)
1946 zio_free(db->db_objset->os_spa, txg, bp);
1947
1948 if (dr->dt.dl.dr_brtwrite || dr->dt.dl.dr_diowrite) {
1949 ASSERT0P(dr->dt.dl.dr_data);
1950 dr->dt.dl.dr_data = db->db_buf;
1951 }
1952 dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
1953 dr->dt.dl.dr_nopwrite = B_FALSE;
1954 dr->dt.dl.dr_brtwrite = B_FALSE;
1955 dr->dt.dl.dr_diowrite = B_FALSE;
1956 dr->dt.dl.dr_has_raw_params = B_FALSE;
1957
1958 /*
1959 * In the event that Direct I/O was used, we do not
1960 * need to release the buffer from the ARC.
1961 *
1962 * Release the already-written buffer, so we leave it in
1963 * a consistent dirty state. Note that all callers are
1964 * modifying the buffer, so they will immediately do
1965 * another (redundant) arc_release(). Therefore, leave
1966 * the buf thawed to save the effort of freezing &
1967 * immediately re-thawing it.
1968 */
1969 if (dr->dt.dl.dr_data)
1970 arc_release(dr->dt.dl.dr_data, db);
1971 }
1972
1973 /*
1974 * Evict (if its unreferenced) or clear (if its referenced) any level-0
1975 * data blocks in the free range, so that any future readers will find
1976 * empty blocks.
1977 */
1978 void
dbuf_free_range(dnode_t * dn,uint64_t start_blkid,uint64_t end_blkid,dmu_tx_t * tx)1979 dbuf_free_range(dnode_t *dn, uint64_t start_blkid, uint64_t end_blkid,
1980 dmu_tx_t *tx)
1981 {
1982 dmu_buf_impl_t *db_search;
1983 dmu_buf_impl_t *db, *db_next;
1984 uint64_t txg = tx->tx_txg;
1985 avl_index_t where;
1986 dbuf_dirty_record_t *dr;
1987
1988 if (end_blkid > dn->dn_maxblkid &&
1989 !(start_blkid == DMU_SPILL_BLKID || end_blkid == DMU_SPILL_BLKID))
1990 end_blkid = dn->dn_maxblkid;
1991 dprintf_dnode(dn, "start=%llu end=%llu\n", (u_longlong_t)start_blkid,
1992 (u_longlong_t)end_blkid);
1993
1994 db_search = kmem_alloc(sizeof (dmu_buf_impl_t), KM_SLEEP);
1995 db_search->db_level = 0;
1996 db_search->db_blkid = start_blkid;
1997 db_search->db_state = DB_SEARCH;
1998
1999 mutex_enter(&dn->dn_dbufs_mtx);
2000 db = avl_find(&dn->dn_dbufs, db_search, &where);
2001 ASSERT0P(db);
2002
2003 db = avl_nearest(&dn->dn_dbufs, where, AVL_AFTER);
2004
2005 for (; db != NULL; db = db_next) {
2006 db_next = AVL_NEXT(&dn->dn_dbufs, db);
2007 ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2008
2009 if (db->db_level != 0 || db->db_blkid > end_blkid) {
2010 break;
2011 }
2012 ASSERT3U(db->db_blkid, >=, start_blkid);
2013
2014 /* found a level 0 buffer in the range */
2015 mutex_enter(&db->db_mtx);
2016 if (dbuf_undirty(db, tx)) {
2017 /* mutex has been dropped and dbuf destroyed */
2018 continue;
2019 }
2020
2021 if (db->db_state == DB_UNCACHED ||
2022 db->db_state == DB_NOFILL ||
2023 db->db_state == DB_EVICTING) {
2024 ASSERT0P(db->db.db_data);
2025 mutex_exit(&db->db_mtx);
2026 continue;
2027 }
2028 if (db->db_state == DB_READ || db->db_state == DB_FILL) {
2029 /* will be handled in dbuf_read_done or dbuf_rele */
2030 db->db_freed_in_flight = TRUE;
2031 mutex_exit(&db->db_mtx);
2032 continue;
2033 }
2034 if (zfs_refcount_count(&db->db_holds) == 0) {
2035 ASSERT(db->db_buf);
2036 dbuf_destroy(db);
2037 continue;
2038 }
2039 /* The dbuf is referenced */
2040
2041 dr = list_head(&db->db_dirty_records);
2042 if (dr != NULL) {
2043 if (dr->dr_txg == txg) {
2044 /*
2045 * This buffer is "in-use", re-adjust the file
2046 * size to reflect that this buffer may
2047 * contain new data when we sync.
2048 */
2049 if (db->db_blkid != DMU_SPILL_BLKID &&
2050 db->db_blkid > dn->dn_maxblkid)
2051 dn->dn_maxblkid = db->db_blkid;
2052 dbuf_unoverride(dr);
2053 } else {
2054 /*
2055 * This dbuf is not dirty in the open context.
2056 * Either uncache it (if its not referenced in
2057 * the open context) or reset its contents to
2058 * empty.
2059 */
2060 dbuf_fix_old_data(db, txg);
2061 }
2062 }
2063 /* clear the contents if its cached */
2064 if (db->db_state == DB_CACHED) {
2065 ASSERT(db->db.db_data != NULL);
2066 arc_release(db->db_buf, db);
2067 rw_enter(&db->db_rwlock, RW_WRITER);
2068 memset(db->db.db_data, 0, db->db.db_size);
2069 rw_exit(&db->db_rwlock);
2070 arc_buf_freeze(db->db_buf);
2071 }
2072
2073 mutex_exit(&db->db_mtx);
2074 }
2075
2076 mutex_exit(&dn->dn_dbufs_mtx);
2077 kmem_free(db_search, sizeof (dmu_buf_impl_t));
2078 }
2079
2080 void
dbuf_new_size(dmu_buf_impl_t * db,int size,dmu_tx_t * tx)2081 dbuf_new_size(dmu_buf_impl_t *db, int size, dmu_tx_t *tx)
2082 {
2083 arc_buf_t *buf, *old_buf;
2084 dbuf_dirty_record_t *dr;
2085 int osize = db->db.db_size;
2086 arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
2087 dnode_t *dn;
2088
2089 ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2090
2091 DB_DNODE_ENTER(db);
2092 dn = DB_DNODE(db);
2093
2094 /*
2095 * XXX we should be doing a dbuf_read, checking the return
2096 * value and returning that up to our callers
2097 */
2098 dmu_buf_will_dirty(&db->db, tx);
2099
2100 VERIFY3P(db->db_buf, !=, NULL);
2101
2102 /* create the data buffer for the new block */
2103 buf = arc_alloc_buf(dn->dn_objset->os_spa, db, type, size);
2104
2105 /* copy old block data to the new block */
2106 old_buf = db->db_buf;
2107 memcpy(buf->b_data, old_buf->b_data, MIN(osize, size));
2108 /* zero the remainder */
2109 if (size > osize)
2110 memset((uint8_t *)buf->b_data + osize, 0, size - osize);
2111
2112 mutex_enter(&db->db_mtx);
2113 dbuf_set_data(db, buf);
2114 arc_buf_destroy(old_buf, db);
2115 db->db.db_size = size;
2116
2117 dr = list_head(&db->db_dirty_records);
2118 /* dirty record added by dmu_buf_will_dirty() */
2119 VERIFY(dr != NULL);
2120 if (db->db_level == 0)
2121 dr->dt.dl.dr_data = buf;
2122 ASSERT3U(dr->dr_txg, ==, tx->tx_txg);
2123 ASSERT3U(dr->dr_accounted, ==, osize);
2124 dr->dr_accounted = size;
2125 mutex_exit(&db->db_mtx);
2126
2127 dmu_objset_willuse_space(dn->dn_objset, size - osize, tx);
2128 DB_DNODE_EXIT(db);
2129 }
2130
2131 void
dbuf_release_bp(dmu_buf_impl_t * db)2132 dbuf_release_bp(dmu_buf_impl_t *db)
2133 {
2134 objset_t *os __maybe_unused = db->db_objset;
2135
2136 ASSERT(dsl_pool_sync_context(dmu_objset_pool(os)));
2137 ASSERT(arc_released(os->os_phys_buf) ||
2138 list_link_active(&os->os_dsl_dataset->ds_synced_link));
2139 ASSERT(db->db_parent == NULL || arc_released(db->db_parent->db_buf));
2140
2141 mutex_enter(&db->db_mtx);
2142 (void) arc_release(db->db_buf, db);
2143 mutex_exit(&db->db_mtx);
2144 }
2145
2146 /*
2147 * We already have a dirty record for this TXG, and we are being
2148 * dirtied again.
2149 */
2150 static void
dbuf_redirty(dbuf_dirty_record_t * dr)2151 dbuf_redirty(dbuf_dirty_record_t *dr)
2152 {
2153 dmu_buf_impl_t *db = dr->dr_dbuf;
2154
2155 ASSERT(MUTEX_HELD(&db->db_mtx));
2156
2157 if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID) {
2158 /*
2159 * If this buffer has already been written out,
2160 * we now need to reset its state.
2161 */
2162 dbuf_unoverride(dr);
2163 if (db->db.db_object != DMU_META_DNODE_OBJECT &&
2164 db->db_state != DB_NOFILL) {
2165 /* Already released on initial dirty, so just thaw. */
2166 ASSERT(arc_released(db->db_buf));
2167 arc_buf_thaw(db->db_buf);
2168 }
2169
2170 /*
2171 * Clear the rewrite flag since this is now a logical
2172 * modification.
2173 */
2174 dr->dt.dl.dr_rewrite = B_FALSE;
2175 }
2176 }
2177
2178 dbuf_dirty_record_t *
dbuf_dirty_lightweight(dnode_t * dn,uint64_t blkid,dmu_tx_t * tx)2179 dbuf_dirty_lightweight(dnode_t *dn, uint64_t blkid, dmu_tx_t *tx)
2180 {
2181 rw_enter(&dn->dn_struct_rwlock, RW_READER);
2182 IMPLY(dn->dn_objset->os_raw_receive, dn->dn_maxblkid >= blkid);
2183 dnode_new_blkid(dn, blkid, tx, B_TRUE, B_FALSE);
2184 ASSERT(dn->dn_maxblkid >= blkid);
2185
2186 dbuf_dirty_record_t *dr = kmem_zalloc(sizeof (*dr), KM_SLEEP);
2187 list_link_init(&dr->dr_dirty_node);
2188 list_link_init(&dr->dr_dbuf_node);
2189 dr->dr_dnode = dn;
2190 dr->dr_txg = tx->tx_txg;
2191 dr->dt.dll.dr_blkid = blkid;
2192 dr->dr_accounted = dn->dn_datablksz;
2193
2194 /*
2195 * There should not be any dbuf for the block that we're dirtying.
2196 * Otherwise the buffer contents could be inconsistent between the
2197 * dbuf and the lightweight dirty record.
2198 */
2199 ASSERT3P(NULL, ==, dbuf_find(dn->dn_objset, dn->dn_object, 0, blkid,
2200 NULL));
2201
2202 mutex_enter(&dn->dn_mtx);
2203 int txgoff = tx->tx_txg & TXG_MASK;
2204 if (dn->dn_free_ranges[txgoff] != NULL) {
2205 zfs_range_tree_clear(dn->dn_free_ranges[txgoff], blkid, 1);
2206 }
2207
2208 if (dn->dn_nlevels == 1) {
2209 ASSERT3U(blkid, <, dn->dn_nblkptr);
2210 list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
2211 mutex_exit(&dn->dn_mtx);
2212 rw_exit(&dn->dn_struct_rwlock);
2213 dnode_setdirty(dn, tx);
2214 } else {
2215 mutex_exit(&dn->dn_mtx);
2216
2217 int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
2218 dmu_buf_impl_t *parent_db = dbuf_hold_level(dn,
2219 1, blkid >> epbs, FTAG);
2220 rw_exit(&dn->dn_struct_rwlock);
2221 if (parent_db == NULL) {
2222 kmem_free(dr, sizeof (*dr));
2223 return (NULL);
2224 }
2225 int err = dbuf_read(parent_db, NULL, DB_RF_CANFAIL |
2226 DMU_READ_NO_PREFETCH);
2227 if (err != 0) {
2228 dbuf_rele(parent_db, FTAG);
2229 kmem_free(dr, sizeof (*dr));
2230 return (NULL);
2231 }
2232
2233 dbuf_dirty_record_t *parent_dr = dbuf_dirty(parent_db, tx);
2234 dbuf_rele(parent_db, FTAG);
2235 mutex_enter(&parent_dr->dt.di.dr_mtx);
2236 ASSERT3U(parent_dr->dr_txg, ==, tx->tx_txg);
2237 list_insert_tail(&parent_dr->dt.di.dr_children, dr);
2238 mutex_exit(&parent_dr->dt.di.dr_mtx);
2239 dr->dr_parent = parent_dr;
2240 }
2241
2242 dmu_objset_willuse_space(dn->dn_objset, dr->dr_accounted, tx);
2243
2244 return (dr);
2245 }
2246
2247 dbuf_dirty_record_t *
dbuf_dirty(dmu_buf_impl_t * db,dmu_tx_t * tx)2248 dbuf_dirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
2249 {
2250 dnode_t *dn;
2251 objset_t *os;
2252 dbuf_dirty_record_t *dr, *dr_next, *dr_head;
2253 int txgoff = tx->tx_txg & TXG_MASK;
2254 boolean_t drop_struct_rwlock = B_FALSE;
2255
2256 ASSERT(tx->tx_txg != 0);
2257 ASSERT(!zfs_refcount_is_zero(&db->db_holds));
2258 DMU_TX_DIRTY_BUF(tx, db);
2259
2260 DB_DNODE_ENTER(db);
2261 dn = DB_DNODE(db);
2262 /*
2263 * Shouldn't dirty a regular buffer in syncing context. Private
2264 * objects may be dirtied in syncing context, but only if they
2265 * were already pre-dirtied in open context.
2266 */
2267 #ifdef ZFS_DEBUG
2268 if (dn->dn_objset->os_dsl_dataset != NULL) {
2269 rrw_enter(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock,
2270 RW_READER, FTAG);
2271 }
2272 ASSERT(!dmu_tx_is_syncing(tx) ||
2273 BP_IS_HOLE(dn->dn_objset->os_rootbp) ||
2274 DMU_OBJECT_IS_SPECIAL(dn->dn_object) ||
2275 dn->dn_objset->os_dsl_dataset == NULL);
2276 if (dn->dn_objset->os_dsl_dataset != NULL)
2277 rrw_exit(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock, FTAG);
2278 #endif
2279
2280 mutex_enter(&db->db_mtx);
2281 /*
2282 * XXX make this true for indirects too? The problem is that
2283 * transactions created with dmu_tx_create_assigned() from
2284 * syncing context don't bother holding ahead.
2285 */
2286 ASSERT(db->db_level != 0 ||
2287 db->db_state == DB_CACHED || db->db_state == DB_FILL ||
2288 db->db_state == DB_NOFILL);
2289
2290 if (db->db_blkid == DMU_SPILL_BLKID)
2291 dn->dn_have_spill = B_TRUE;
2292
2293 /*
2294 * If this buffer is already dirty, we're done.
2295 */
2296 dr_head = list_head(&db->db_dirty_records);
2297 ASSERT(dr_head == NULL || dr_head->dr_txg <= tx->tx_txg ||
2298 db->db.db_object == DMU_META_DNODE_OBJECT);
2299 dr_next = dbuf_find_dirty_lte(db, tx->tx_txg);
2300 if (dr_next && dr_next->dr_txg == tx->tx_txg) {
2301 DB_DNODE_EXIT(db);
2302
2303 dbuf_redirty(dr_next);
2304 mutex_exit(&db->db_mtx);
2305 return (dr_next);
2306 }
2307
2308 ASSERT3U(dn->dn_nlevels, >, db->db_level);
2309
2310 /*
2311 * We should only be dirtying in syncing context if it's the
2312 * mos or we're initializing the os or it's a special object.
2313 * However, we are allowed to dirty in syncing context provided
2314 * we already dirtied it in open context. Hence we must make
2315 * this assertion only if we're not already dirty.
2316 */
2317 os = dn->dn_objset;
2318 VERIFY3U(tx->tx_txg, <=, spa_final_dirty_txg(os->os_spa));
2319 #ifdef ZFS_DEBUG
2320 if (dn->dn_objset->os_dsl_dataset != NULL)
2321 rrw_enter(&os->os_dsl_dataset->ds_bp_rwlock, RW_READER, FTAG);
2322 ASSERT(!dmu_tx_is_syncing(tx) || DMU_OBJECT_IS_SPECIAL(dn->dn_object) ||
2323 os->os_dsl_dataset == NULL || BP_IS_HOLE(os->os_rootbp));
2324 if (dn->dn_objset->os_dsl_dataset != NULL)
2325 rrw_exit(&os->os_dsl_dataset->ds_bp_rwlock, FTAG);
2326 #endif
2327 ASSERT(db->db.db_size != 0);
2328
2329 dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
2330
2331 if (db->db_blkid != DMU_BONUS_BLKID && db->db_state != DB_NOFILL) {
2332 dmu_objset_willuse_space(os, db->db.db_size, tx);
2333 }
2334
2335 /*
2336 * If this buffer is dirty in an old transaction group we need
2337 * to make a copy of it so that the changes we make in this
2338 * transaction group won't leak out when we sync the older txg.
2339 */
2340 dr = kmem_cache_alloc(dbuf_dirty_kmem_cache, KM_SLEEP);
2341 memset(dr, 0, sizeof (*dr));
2342 list_link_init(&dr->dr_dirty_node);
2343 list_link_init(&dr->dr_dbuf_node);
2344 dr->dr_dnode = dn;
2345 if (db->db_level == 0) {
2346 void *data_old = db->db_buf;
2347
2348 if (db->db_state != DB_NOFILL) {
2349 if (db->db_blkid == DMU_BONUS_BLKID) {
2350 dbuf_fix_old_data(db, tx->tx_txg);
2351 data_old = db->db.db_data;
2352 } else if (db->db.db_object != DMU_META_DNODE_OBJECT) {
2353 /*
2354 * Release the data buffer from the cache so
2355 * that we can modify it without impacting
2356 * possible other users of this cached data
2357 * block. Note that indirect blocks and
2358 * private objects are not released until the
2359 * syncing state (since they are only modified
2360 * then).
2361 */
2362 arc_release(db->db_buf, db);
2363 dbuf_fix_old_data(db, tx->tx_txg);
2364 data_old = db->db_buf;
2365 }
2366 ASSERT(data_old != NULL);
2367 }
2368 dr->dt.dl.dr_data = data_old;
2369 } else {
2370 mutex_init(&dr->dt.di.dr_mtx, NULL, MUTEX_NOLOCKDEP, NULL);
2371 list_create(&dr->dt.di.dr_children,
2372 sizeof (dbuf_dirty_record_t),
2373 offsetof(dbuf_dirty_record_t, dr_dirty_node));
2374 }
2375 if (db->db_blkid != DMU_BONUS_BLKID && db->db_state != DB_NOFILL) {
2376 dr->dr_accounted = db->db.db_size;
2377 }
2378 dr->dr_dbuf = db;
2379 dr->dr_txg = tx->tx_txg;
2380 list_insert_before(&db->db_dirty_records, dr_next, dr);
2381
2382 /*
2383 * We could have been freed_in_flight between the dbuf_noread
2384 * and dbuf_dirty. We win, as though the dbuf_noread() had
2385 * happened after the free.
2386 */
2387 if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
2388 db->db_blkid != DMU_SPILL_BLKID) {
2389 mutex_enter(&dn->dn_mtx);
2390 if (dn->dn_free_ranges[txgoff] != NULL) {
2391 zfs_range_tree_clear(dn->dn_free_ranges[txgoff],
2392 db->db_blkid, 1);
2393 }
2394 mutex_exit(&dn->dn_mtx);
2395 db->db_freed_in_flight = FALSE;
2396 }
2397
2398 /*
2399 * This buffer is now part of this txg
2400 */
2401 dbuf_add_ref(db, (void *)(uintptr_t)tx->tx_txg);
2402 db->db_dirtycnt += 1;
2403 ASSERT3U(db->db_dirtycnt, <=, 3);
2404
2405 mutex_exit(&db->db_mtx);
2406
2407 if (db->db_blkid == DMU_BONUS_BLKID ||
2408 db->db_blkid == DMU_SPILL_BLKID) {
2409 mutex_enter(&dn->dn_mtx);
2410 ASSERT(!list_link_active(&dr->dr_dirty_node));
2411 list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
2412 mutex_exit(&dn->dn_mtx);
2413 dnode_setdirty(dn, tx);
2414 DB_DNODE_EXIT(db);
2415 return (dr);
2416 }
2417
2418 if (!RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
2419 rw_enter(&dn->dn_struct_rwlock, RW_READER);
2420 drop_struct_rwlock = B_TRUE;
2421 }
2422
2423 /*
2424 * If we are overwriting a dedup BP, then unless it is snapshotted,
2425 * when we get to syncing context we will need to decrement its
2426 * refcount in the DDT. Prefetch the relevant DDT block so that
2427 * syncing context won't have to wait for the i/o.
2428 */
2429 if (db->db_blkptr != NULL) {
2430 db_lock_type_t dblt = dmu_buf_lock_parent(db, RW_READER, FTAG);
2431 ddt_prefetch(os->os_spa, db->db_blkptr);
2432 dmu_buf_unlock_parent(db, dblt, FTAG);
2433 }
2434
2435 /*
2436 * We need to hold the dn_struct_rwlock to make this assertion,
2437 * because it protects dn_phys / dn_next_nlevels from changing.
2438 */
2439 ASSERT((dn->dn_phys->dn_nlevels == 0 && db->db_level == 0) ||
2440 dn->dn_phys->dn_nlevels > db->db_level ||
2441 dn->dn_next_nlevels[txgoff] > db->db_level ||
2442 dn->dn_next_nlevels[(tx->tx_txg-1) & TXG_MASK] > db->db_level ||
2443 dn->dn_next_nlevels[(tx->tx_txg-2) & TXG_MASK] > db->db_level);
2444
2445
2446 if (db->db_level == 0) {
2447 ASSERT(!db->db_objset->os_raw_receive ||
2448 dn->dn_maxblkid >= db->db_blkid);
2449 dnode_new_blkid(dn, db->db_blkid, tx,
2450 drop_struct_rwlock, B_FALSE);
2451 ASSERT(dn->dn_maxblkid >= db->db_blkid);
2452 }
2453
2454 if (db->db_level+1 < dn->dn_nlevels) {
2455 dmu_buf_impl_t *parent = db->db_parent;
2456 dbuf_dirty_record_t *di;
2457 int parent_held = FALSE;
2458
2459 if (db->db_parent == NULL || db->db_parent == dn->dn_dbuf) {
2460 int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
2461 parent = dbuf_hold_level(dn, db->db_level + 1,
2462 db->db_blkid >> epbs, FTAG);
2463 ASSERT(parent != NULL);
2464 parent_held = TRUE;
2465 }
2466 if (drop_struct_rwlock)
2467 rw_exit(&dn->dn_struct_rwlock);
2468 ASSERT3U(db->db_level + 1, ==, parent->db_level);
2469 di = dbuf_dirty(parent, tx);
2470 if (parent_held)
2471 dbuf_rele(parent, FTAG);
2472
2473 mutex_enter(&db->db_mtx);
2474 /*
2475 * Since we've dropped the mutex, it's possible that
2476 * dbuf_undirty() might have changed this out from under us.
2477 */
2478 if (list_head(&db->db_dirty_records) == dr ||
2479 dn->dn_object == DMU_META_DNODE_OBJECT) {
2480 mutex_enter(&di->dt.di.dr_mtx);
2481 ASSERT3U(di->dr_txg, ==, tx->tx_txg);
2482 ASSERT(!list_link_active(&dr->dr_dirty_node));
2483 list_insert_tail(&di->dt.di.dr_children, dr);
2484 mutex_exit(&di->dt.di.dr_mtx);
2485 dr->dr_parent = di;
2486 }
2487 mutex_exit(&db->db_mtx);
2488 } else {
2489 ASSERT(db->db_level + 1 == dn->dn_nlevels);
2490 ASSERT(db->db_blkid < dn->dn_nblkptr);
2491 ASSERT(db->db_parent == NULL || db->db_parent == dn->dn_dbuf);
2492 mutex_enter(&dn->dn_mtx);
2493 ASSERT(!list_link_active(&dr->dr_dirty_node));
2494 list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
2495 mutex_exit(&dn->dn_mtx);
2496 if (drop_struct_rwlock)
2497 rw_exit(&dn->dn_struct_rwlock);
2498 }
2499
2500 dnode_setdirty(dn, tx);
2501 DB_DNODE_EXIT(db);
2502 return (dr);
2503 }
2504
2505 static void
dbuf_undirty_bonus(dbuf_dirty_record_t * dr)2506 dbuf_undirty_bonus(dbuf_dirty_record_t *dr)
2507 {
2508 dmu_buf_impl_t *db = dr->dr_dbuf;
2509
2510 ASSERT(MUTEX_HELD(&db->db_mtx));
2511 if (dr->dt.dl.dr_data != db->db.db_data) {
2512 struct dnode *dn = dr->dr_dnode;
2513 int max_bonuslen = DN_SLOTS_TO_BONUSLEN(dn->dn_num_slots);
2514
2515 kmem_free(dr->dt.dl.dr_data, max_bonuslen);
2516 arc_space_return(max_bonuslen, ARC_SPACE_BONUS);
2517 }
2518 db->db_data_pending = NULL;
2519 ASSERT(list_next(&db->db_dirty_records, dr) == NULL);
2520 list_remove(&db->db_dirty_records, dr);
2521 if (dr->dr_dbuf->db_level != 0) {
2522 mutex_destroy(&dr->dt.di.dr_mtx);
2523 list_destroy(&dr->dt.di.dr_children);
2524 }
2525 kmem_cache_free(dbuf_dirty_kmem_cache, dr);
2526 ASSERT3U(db->db_dirtycnt, >, 0);
2527 db->db_dirtycnt -= 1;
2528 }
2529
2530 /*
2531 * Undirty a buffer in the transaction group referenced by the given
2532 * transaction. Return whether this evicted the dbuf.
2533 */
2534 boolean_t
dbuf_undirty(dmu_buf_impl_t * db,dmu_tx_t * tx)2535 dbuf_undirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
2536 {
2537 uint64_t txg = tx->tx_txg;
2538 boolean_t brtwrite;
2539 boolean_t diowrite;
2540
2541 ASSERT(txg != 0);
2542
2543 /*
2544 * Due to our use of dn_nlevels below, this can only be called
2545 * in open context, unless we are operating on the MOS or it's
2546 * a special object. From syncing context, dn_nlevels may be
2547 * different from the dn_nlevels used when dbuf was dirtied.
2548 */
2549 ASSERT(db->db_objset ==
2550 dmu_objset_pool(db->db_objset)->dp_meta_objset ||
2551 DMU_OBJECT_IS_SPECIAL(db->db.db_object) ||
2552 txg != spa_syncing_txg(dmu_objset_spa(db->db_objset)));
2553 ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2554 ASSERT0(db->db_level);
2555 ASSERT(MUTEX_HELD(&db->db_mtx));
2556
2557 /*
2558 * If this buffer is not dirty, we're done.
2559 */
2560 dbuf_dirty_record_t *dr = dbuf_find_dirty_eq(db, txg);
2561 if (dr == NULL)
2562 return (B_FALSE);
2563 ASSERT(dr->dr_dbuf == db);
2564
2565 brtwrite = dr->dt.dl.dr_brtwrite;
2566 diowrite = dr->dt.dl.dr_diowrite;
2567 if (brtwrite) {
2568 ASSERT3B(diowrite, ==, B_FALSE);
2569 /*
2570 * We are freeing a block that we cloned in the same
2571 * transaction group.
2572 */
2573 blkptr_t *bp = &dr->dt.dl.dr_overridden_by;
2574 if (!BP_IS_HOLE(bp) && !BP_IS_EMBEDDED(bp)) {
2575 brt_pending_remove(dmu_objset_spa(db->db_objset),
2576 bp, tx);
2577 }
2578 }
2579
2580 dnode_t *dn = dr->dr_dnode;
2581
2582 dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
2583
2584 ASSERT(db->db.db_size != 0);
2585
2586 dsl_pool_undirty_space(dmu_objset_pool(dn->dn_objset),
2587 dr->dr_accounted, txg);
2588
2589 list_remove(&db->db_dirty_records, dr);
2590
2591 /*
2592 * Note that there are three places in dbuf_dirty()
2593 * where this dirty record may be put on a list.
2594 * Make sure to do a list_remove corresponding to
2595 * every one of those list_insert calls.
2596 */
2597 if (dr->dr_parent) {
2598 mutex_enter(&dr->dr_parent->dt.di.dr_mtx);
2599 list_remove(&dr->dr_parent->dt.di.dr_children, dr);
2600 mutex_exit(&dr->dr_parent->dt.di.dr_mtx);
2601 } else if (db->db_blkid == DMU_SPILL_BLKID ||
2602 db->db_level + 1 == dn->dn_nlevels) {
2603 ASSERT(db->db_blkptr == NULL || db->db_parent == dn->dn_dbuf);
2604 mutex_enter(&dn->dn_mtx);
2605 list_remove(&dn->dn_dirty_records[txg & TXG_MASK], dr);
2606 mutex_exit(&dn->dn_mtx);
2607 }
2608
2609 if (db->db_state != DB_NOFILL && !brtwrite) {
2610 dbuf_unoverride(dr);
2611
2612 if (dr->dt.dl.dr_data != db->db_buf) {
2613 ASSERT(db->db_buf != NULL);
2614 ASSERT(dr->dt.dl.dr_data != NULL);
2615 arc_buf_destroy(dr->dt.dl.dr_data, db);
2616 }
2617 }
2618
2619 kmem_cache_free(dbuf_dirty_kmem_cache, dr);
2620
2621 ASSERT(db->db_dirtycnt > 0);
2622 db->db_dirtycnt -= 1;
2623
2624 if (zfs_refcount_remove(&db->db_holds, (void *)(uintptr_t)txg) == 0) {
2625 ASSERT(db->db_state == DB_NOFILL || brtwrite || diowrite ||
2626 arc_released(db->db_buf));
2627 dbuf_destroy(db);
2628 return (B_TRUE);
2629 }
2630
2631 return (B_FALSE);
2632 }
2633
2634 void
dmu_buf_will_dirty_flags(dmu_buf_t * db_fake,dmu_tx_t * tx,dmu_flags_t flags)2635 dmu_buf_will_dirty_flags(dmu_buf_t *db_fake, dmu_tx_t *tx, dmu_flags_t flags)
2636 {
2637 dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2638 boolean_t undirty = B_FALSE;
2639
2640 ASSERT(tx->tx_txg != 0);
2641 ASSERT(!zfs_refcount_is_zero(&db->db_holds));
2642
2643 /*
2644 * Quick check for dirtiness to improve performance for some workloads
2645 * (e.g. file deletion with indirect blocks cached).
2646 */
2647 mutex_enter(&db->db_mtx);
2648 if (db->db_state == DB_CACHED || db->db_state == DB_NOFILL) {
2649 /*
2650 * It's possible that the dbuf is already dirty but not cached,
2651 * because there are some calls to dbuf_dirty() that don't
2652 * go through dmu_buf_will_dirty().
2653 */
2654 dbuf_dirty_record_t *dr = dbuf_find_dirty_eq(db, tx->tx_txg);
2655 if (dr != NULL) {
2656 if (db->db_level == 0 &&
2657 dr->dt.dl.dr_brtwrite) {
2658 /*
2659 * Block cloning: If we are dirtying a cloned
2660 * level 0 block, we cannot simply redirty it,
2661 * because this dr has no associated data.
2662 * We will go through a full undirtying below,
2663 * before dirtying it again.
2664 */
2665 undirty = B_TRUE;
2666 } else {
2667 /* This dbuf is already dirty and cached. */
2668 dbuf_redirty(dr);
2669 mutex_exit(&db->db_mtx);
2670 return;
2671 }
2672 }
2673 }
2674 mutex_exit(&db->db_mtx);
2675
2676 DB_DNODE_ENTER(db);
2677 if (RW_WRITE_HELD(&DB_DNODE(db)->dn_struct_rwlock))
2678 flags |= DB_RF_HAVESTRUCT;
2679 DB_DNODE_EXIT(db);
2680
2681 /*
2682 * Block cloning: Do the dbuf_read() before undirtying the dbuf, as we
2683 * want to make sure dbuf_read() will read the pending cloned block and
2684 * not the uderlying block that is being replaced. dbuf_undirty() will
2685 * do brt_pending_remove() before removing the dirty record.
2686 */
2687 (void) dbuf_read(db, NULL, flags | DB_RF_MUST_SUCCEED);
2688 if (undirty) {
2689 mutex_enter(&db->db_mtx);
2690 VERIFY(!dbuf_undirty(db, tx));
2691 mutex_exit(&db->db_mtx);
2692 }
2693 (void) dbuf_dirty(db, tx);
2694 }
2695
2696 void
dmu_buf_will_dirty(dmu_buf_t * db_fake,dmu_tx_t * tx)2697 dmu_buf_will_dirty(dmu_buf_t *db_fake, dmu_tx_t *tx)
2698 {
2699 dmu_buf_will_dirty_flags(db_fake, tx, DMU_READ_NO_PREFETCH);
2700 }
2701
2702 void
dmu_buf_will_rewrite(dmu_buf_t * db_fake,dmu_tx_t * tx)2703 dmu_buf_will_rewrite(dmu_buf_t *db_fake, dmu_tx_t *tx)
2704 {
2705 dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2706
2707 ASSERT(tx->tx_txg != 0);
2708 ASSERT(!zfs_refcount_is_zero(&db->db_holds));
2709
2710 /*
2711 * If the dbuf is already dirty in this txg, it will be written
2712 * anyway, so there's nothing to do.
2713 */
2714 mutex_enter(&db->db_mtx);
2715 if (dbuf_find_dirty_eq(db, tx->tx_txg) != NULL) {
2716 mutex_exit(&db->db_mtx);
2717 return;
2718 }
2719 mutex_exit(&db->db_mtx);
2720
2721 /*
2722 * The dbuf is not dirty, so we need to make it dirty and
2723 * mark it for rewrite (preserve logical birth time).
2724 */
2725 dmu_buf_will_dirty_flags(db_fake, tx, DMU_READ_NO_PREFETCH);
2726
2727 mutex_enter(&db->db_mtx);
2728 dbuf_dirty_record_t *dr = dbuf_find_dirty_eq(db, tx->tx_txg);
2729 if (dr != NULL && db->db_level == 0)
2730 dr->dt.dl.dr_rewrite = B_TRUE;
2731 mutex_exit(&db->db_mtx);
2732 }
2733
2734 boolean_t
dmu_buf_is_dirty(dmu_buf_t * db_fake,dmu_tx_t * tx)2735 dmu_buf_is_dirty(dmu_buf_t *db_fake, dmu_tx_t *tx)
2736 {
2737 dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2738 dbuf_dirty_record_t *dr;
2739
2740 mutex_enter(&db->db_mtx);
2741 dr = dbuf_find_dirty_eq(db, tx->tx_txg);
2742 mutex_exit(&db->db_mtx);
2743 return (dr != NULL);
2744 }
2745
2746 /*
2747 * Normally the db_blkptr points to the most recent on-disk content for the
2748 * dbuf (and anything newer will be cached in the dbuf). However, a pending
2749 * block clone or not yet synced Direct I/O write will have a dirty record BP
2750 * pointing to the most recent data.
2751 */
2752 int
dmu_buf_get_bp_from_dbuf(dmu_buf_impl_t * db,blkptr_t ** bp)2753 dmu_buf_get_bp_from_dbuf(dmu_buf_impl_t *db, blkptr_t **bp)
2754 {
2755 ASSERT(MUTEX_HELD(&db->db_mtx));
2756 int error = 0;
2757
2758 if (db->db_level != 0) {
2759 *bp = db->db_blkptr;
2760 return (0);
2761 }
2762
2763 *bp = db->db_blkptr;
2764 dbuf_dirty_record_t *dr = list_head(&db->db_dirty_records);
2765 if (dr && db->db_state == DB_NOFILL) {
2766 /* Block clone */
2767 if (!dr->dt.dl.dr_brtwrite)
2768 error = EIO;
2769 else
2770 *bp = &dr->dt.dl.dr_overridden_by;
2771 } else if (dr && db->db_state == DB_UNCACHED) {
2772 /* Direct I/O write */
2773 if (dr->dt.dl.dr_diowrite)
2774 *bp = &dr->dt.dl.dr_overridden_by;
2775 }
2776
2777 return (error);
2778 }
2779
2780 /*
2781 * Direct I/O reads can read directly from the ARC, but the data has
2782 * to be untransformed in order to copy it over into user pages.
2783 */
2784 int
dmu_buf_untransform_direct(dmu_buf_impl_t * db,spa_t * spa)2785 dmu_buf_untransform_direct(dmu_buf_impl_t *db, spa_t *spa)
2786 {
2787 int err = 0;
2788 DB_DNODE_ENTER(db);
2789 dnode_t *dn = DB_DNODE(db);
2790
2791 ASSERT3S(db->db_state, ==, DB_CACHED);
2792 ASSERT(MUTEX_HELD(&db->db_mtx));
2793
2794 /*
2795 * Ensure that this block's dnode has been decrypted if
2796 * the caller has requested decrypted data.
2797 */
2798 err = dbuf_read_verify_dnode_crypt(db, dn, 0);
2799
2800 /*
2801 * If the arc buf is compressed or encrypted and the caller
2802 * requested uncompressed data, we need to untransform it
2803 * before returning. We also call arc_untransform() on any
2804 * unauthenticated blocks, which will verify their MAC if
2805 * the key is now available.
2806 */
2807 if (err == 0 && db->db_buf != NULL &&
2808 (arc_is_encrypted(db->db_buf) ||
2809 arc_is_unauthenticated(db->db_buf) ||
2810 arc_get_compression(db->db_buf) != ZIO_COMPRESS_OFF)) {
2811 zbookmark_phys_t zb;
2812
2813 SET_BOOKMARK(&zb, dmu_objset_id(db->db_objset),
2814 db->db.db_object, db->db_level, db->db_blkid);
2815 dbuf_fix_old_data(db, spa_syncing_txg(spa));
2816 err = arc_untransform(db->db_buf, spa, &zb, B_FALSE);
2817 dbuf_set_data(db, db->db_buf);
2818 }
2819 DB_DNODE_EXIT(db);
2820 DBUF_STAT_BUMP(hash_hits);
2821
2822 return (err);
2823 }
2824
2825 void
dmu_buf_will_clone_or_dio(dmu_buf_t * db_fake,dmu_tx_t * tx)2826 dmu_buf_will_clone_or_dio(dmu_buf_t *db_fake, dmu_tx_t *tx)
2827 {
2828 /*
2829 * Block clones and Direct I/O writes always happen in open-context.
2830 */
2831 dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2832 ASSERT0(db->db_level);
2833 ASSERT(!dmu_tx_is_syncing(tx));
2834 ASSERT0(db->db_level);
2835 ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2836 ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT);
2837
2838 mutex_enter(&db->db_mtx);
2839 DBUF_VERIFY(db);
2840
2841 /*
2842 * We are going to clone or issue a Direct I/O write on this block, so
2843 * undirty modifications done to this block so far in this txg. This
2844 * includes writes and clones into this block.
2845 *
2846 * If there dirty record associated with this txg from a previous Direct
2847 * I/O write then space accounting cleanup takes place. It is important
2848 * to go ahead free up the space accounting through dbuf_undirty() ->
2849 * dbuf_unoverride() -> zio_free(). Space accountiung for determining
2850 * if a write can occur in zfs_write() happens through dmu_tx_assign().
2851 * This can cause an issue with Direct I/O writes in the case of
2852 * overwriting the same block, because all DVA allocations are being
2853 * done in open-context. Constantly allowing Direct I/O overwrites to
2854 * the same block can exhaust the pools available space leading to
2855 * ENOSPC errors at the DVA allocation part of the ZIO pipeline, which
2856 * will eventually suspend the pool. By cleaning up sapce acccounting
2857 * now, the ENOSPC error can be avoided.
2858 *
2859 * Since we are undirtying the record in open-context, we must have a
2860 * hold on the db, so it should never be evicted after calling
2861 * dbuf_undirty().
2862 */
2863 VERIFY3B(dbuf_undirty(db, tx), ==, B_FALSE);
2864 ASSERT0P(dbuf_find_dirty_eq(db, tx->tx_txg));
2865
2866 if (db->db_buf != NULL) {
2867 /*
2868 * If there is an associated ARC buffer with this dbuf we can
2869 * only destroy it if the previous dirty record does not
2870 * reference it.
2871 */
2872 dbuf_dirty_record_t *dr = list_head(&db->db_dirty_records);
2873 if (dr == NULL || dr->dt.dl.dr_data != db->db_buf)
2874 arc_buf_destroy(db->db_buf, db);
2875
2876 /*
2877 * Setting the dbuf's data pointers to NULL will force all
2878 * future reads down to the devices to get the most up to date
2879 * version of the data after a Direct I/O write has completed.
2880 */
2881 db->db_buf = NULL;
2882 dbuf_clear_data(db);
2883 }
2884
2885 ASSERT0P(db->db_buf);
2886 ASSERT0P(db->db.db_data);
2887
2888 db->db_state = DB_NOFILL;
2889 DTRACE_SET_STATE(db,
2890 "allocating NOFILL buffer for clone or direct I/O write");
2891
2892 DBUF_VERIFY(db);
2893 mutex_exit(&db->db_mtx);
2894
2895 dbuf_noread(db, DMU_KEEP_CACHING);
2896 (void) dbuf_dirty(db, tx);
2897 }
2898
2899 void
dmu_buf_will_not_fill(dmu_buf_t * db_fake,dmu_tx_t * tx)2900 dmu_buf_will_not_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
2901 {
2902 dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2903
2904 mutex_enter(&db->db_mtx);
2905 db->db_state = DB_NOFILL;
2906 DTRACE_SET_STATE(db, "allocating NOFILL buffer");
2907 mutex_exit(&db->db_mtx);
2908
2909 dbuf_noread(db, DMU_KEEP_CACHING);
2910 (void) dbuf_dirty(db, tx);
2911 }
2912
2913 void
dmu_buf_will_fill_flags(dmu_buf_t * db_fake,dmu_tx_t * tx,boolean_t canfail,dmu_flags_t flags)2914 dmu_buf_will_fill_flags(dmu_buf_t *db_fake, dmu_tx_t *tx, boolean_t canfail,
2915 dmu_flags_t flags)
2916 {
2917 dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2918
2919 ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2920 ASSERT(tx->tx_txg != 0);
2921 ASSERT0(db->db_level);
2922 ASSERT(!zfs_refcount_is_zero(&db->db_holds));
2923
2924 ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT ||
2925 dmu_tx_private_ok(tx));
2926
2927 mutex_enter(&db->db_mtx);
2928 dbuf_dirty_record_t *dr = dbuf_find_dirty_eq(db, tx->tx_txg);
2929 if (db->db_state == DB_NOFILL ||
2930 (db->db_state == DB_UNCACHED && dr && dr->dt.dl.dr_diowrite)) {
2931 /*
2932 * If the fill can fail we should have a way to return back to
2933 * the cloned or Direct I/O write data.
2934 */
2935 if (canfail && dr) {
2936 mutex_exit(&db->db_mtx);
2937 dmu_buf_will_dirty_flags(db_fake, tx, flags);
2938 return;
2939 }
2940 /*
2941 * Block cloning: We will be completely overwriting a block
2942 * cloned in this transaction group, so let's undirty the
2943 * pending clone and mark the block as uncached. This will be
2944 * as if the clone was never done.
2945 */
2946 if (db->db_state == DB_NOFILL) {
2947 VERIFY(!dbuf_undirty(db, tx));
2948 db->db_state = DB_UNCACHED;
2949 }
2950 }
2951 mutex_exit(&db->db_mtx);
2952
2953 dbuf_noread(db, flags);
2954 (void) dbuf_dirty(db, tx);
2955 }
2956
2957 void
dmu_buf_will_fill(dmu_buf_t * db_fake,dmu_tx_t * tx,boolean_t canfail)2958 dmu_buf_will_fill(dmu_buf_t *db_fake, dmu_tx_t *tx, boolean_t canfail)
2959 {
2960 dmu_buf_will_fill_flags(db_fake, tx, canfail, DMU_READ_NO_PREFETCH);
2961 }
2962
2963 /*
2964 * This function is effectively the same as dmu_buf_will_dirty(), but
2965 * indicates the caller expects raw encrypted data in the db, and provides
2966 * the crypt params (byteorder, salt, iv, mac) which should be stored in the
2967 * blkptr_t when this dbuf is written. This is only used for blocks of
2968 * dnodes, during raw receive.
2969 */
2970 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)2971 dmu_buf_set_crypt_params(dmu_buf_t *db_fake, boolean_t byteorder,
2972 const uint8_t *salt, const uint8_t *iv, const uint8_t *mac, dmu_tx_t *tx)
2973 {
2974 dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2975 dbuf_dirty_record_t *dr;
2976
2977 /*
2978 * dr_has_raw_params is only processed for blocks of dnodes
2979 * (see dbuf_sync_dnode_leaf_crypt()).
2980 */
2981 ASSERT3U(db->db.db_object, ==, DMU_META_DNODE_OBJECT);
2982 ASSERT0(db->db_level);
2983 ASSERT(db->db_objset->os_raw_receive);
2984
2985 dmu_buf_will_dirty_flags(db_fake, tx,
2986 DMU_READ_NO_PREFETCH | DMU_READ_NO_DECRYPT);
2987
2988 dr = dbuf_find_dirty_eq(db, tx->tx_txg);
2989
2990 ASSERT3P(dr, !=, NULL);
2991 ASSERT3U(dr->dt.dl.dr_override_state, ==, DR_NOT_OVERRIDDEN);
2992
2993 dr->dt.dl.dr_has_raw_params = B_TRUE;
2994 dr->dt.dl.dr_byteorder = byteorder;
2995 memcpy(dr->dt.dl.dr_salt, salt, ZIO_DATA_SALT_LEN);
2996 memcpy(dr->dt.dl.dr_iv, iv, ZIO_DATA_IV_LEN);
2997 memcpy(dr->dt.dl.dr_mac, mac, ZIO_DATA_MAC_LEN);
2998 }
2999
3000 static void
dbuf_override_impl(dmu_buf_impl_t * db,const blkptr_t * bp,dmu_tx_t * tx)3001 dbuf_override_impl(dmu_buf_impl_t *db, const blkptr_t *bp, dmu_tx_t *tx)
3002 {
3003 struct dirty_leaf *dl;
3004 dbuf_dirty_record_t *dr;
3005
3006 ASSERT3U(db->db.db_object, !=, DMU_META_DNODE_OBJECT);
3007 ASSERT0(db->db_level);
3008
3009 dr = list_head(&db->db_dirty_records);
3010 ASSERT3P(dr, !=, NULL);
3011 ASSERT3U(dr->dr_txg, ==, tx->tx_txg);
3012 dl = &dr->dt.dl;
3013 ASSERT0(dl->dr_has_raw_params);
3014 dl->dr_overridden_by = *bp;
3015 dl->dr_override_state = DR_OVERRIDDEN;
3016 BP_SET_LOGICAL_BIRTH(&dl->dr_overridden_by, dr->dr_txg);
3017 }
3018
3019 boolean_t
dmu_buf_fill_done(dmu_buf_t * dbuf,dmu_tx_t * tx,boolean_t failed)3020 dmu_buf_fill_done(dmu_buf_t *dbuf, dmu_tx_t *tx, boolean_t failed)
3021 {
3022 (void) tx;
3023 dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbuf;
3024 mutex_enter(&db->db_mtx);
3025 DBUF_VERIFY(db);
3026
3027 if (db->db_state == DB_FILL) {
3028 if (db->db_level == 0 && db->db_freed_in_flight) {
3029 ASSERT(db->db_blkid != DMU_BONUS_BLKID);
3030 /* we were freed while filling */
3031 /* XXX dbuf_undirty? */
3032 memset(db->db.db_data, 0, db->db.db_size);
3033 db->db_freed_in_flight = FALSE;
3034 db->db_state = DB_CACHED;
3035 DTRACE_SET_STATE(db,
3036 "fill done handling freed in flight");
3037 failed = B_FALSE;
3038 } else if (failed) {
3039 VERIFY(!dbuf_undirty(db, tx));
3040 arc_buf_destroy(db->db_buf, db);
3041 db->db_buf = NULL;
3042 dbuf_clear_data(db);
3043 DTRACE_SET_STATE(db, "fill failed");
3044 } else {
3045 db->db_state = DB_CACHED;
3046 DTRACE_SET_STATE(db, "fill done");
3047 }
3048 cv_broadcast(&db->db_changed);
3049 } else {
3050 db->db_state = DB_CACHED;
3051 failed = B_FALSE;
3052 }
3053 mutex_exit(&db->db_mtx);
3054 return (failed);
3055 }
3056
3057 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)3058 dmu_buf_write_embedded(dmu_buf_t *dbuf, void *data,
3059 bp_embedded_type_t etype, enum zio_compress comp,
3060 int uncompressed_size, int compressed_size, int byteorder,
3061 dmu_tx_t *tx)
3062 {
3063 dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbuf;
3064 struct dirty_leaf *dl;
3065 dmu_object_type_t type;
3066 dbuf_dirty_record_t *dr;
3067
3068 if (etype == BP_EMBEDDED_TYPE_DATA) {
3069 ASSERT(spa_feature_is_active(dmu_objset_spa(db->db_objset),
3070 SPA_FEATURE_EMBEDDED_DATA));
3071 }
3072
3073 DB_DNODE_ENTER(db);
3074 type = DB_DNODE(db)->dn_type;
3075 DB_DNODE_EXIT(db);
3076
3077 ASSERT0(db->db_level);
3078 ASSERT(db->db_blkid != DMU_BONUS_BLKID);
3079
3080 dmu_buf_will_not_fill(dbuf, tx);
3081
3082 dr = list_head(&db->db_dirty_records);
3083 ASSERT3P(dr, !=, NULL);
3084 ASSERT3U(dr->dr_txg, ==, tx->tx_txg);
3085 dl = &dr->dt.dl;
3086 ASSERT0(dl->dr_has_raw_params);
3087 encode_embedded_bp_compressed(&dl->dr_overridden_by,
3088 data, comp, uncompressed_size, compressed_size);
3089 BPE_SET_ETYPE(&dl->dr_overridden_by, etype);
3090 BP_SET_TYPE(&dl->dr_overridden_by, type);
3091 BP_SET_LEVEL(&dl->dr_overridden_by, 0);
3092 BP_SET_BYTEORDER(&dl->dr_overridden_by, byteorder);
3093
3094 dl->dr_override_state = DR_OVERRIDDEN;
3095 BP_SET_LOGICAL_BIRTH(&dl->dr_overridden_by, dr->dr_txg);
3096 }
3097
3098 void
dmu_buf_redact(dmu_buf_t * dbuf,dmu_tx_t * tx)3099 dmu_buf_redact(dmu_buf_t *dbuf, dmu_tx_t *tx)
3100 {
3101 dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbuf;
3102 dmu_object_type_t type;
3103 ASSERT(dsl_dataset_feature_is_active(db->db_objset->os_dsl_dataset,
3104 SPA_FEATURE_REDACTED_DATASETS));
3105
3106 DB_DNODE_ENTER(db);
3107 type = DB_DNODE(db)->dn_type;
3108 DB_DNODE_EXIT(db);
3109
3110 ASSERT0(db->db_level);
3111 dmu_buf_will_not_fill(dbuf, tx);
3112
3113 blkptr_t bp = { { { {0} } } };
3114 BP_SET_TYPE(&bp, type);
3115 BP_SET_LEVEL(&bp, 0);
3116 BP_SET_BIRTH(&bp, tx->tx_txg, 0);
3117 BP_SET_REDACTED(&bp);
3118 BPE_SET_LSIZE(&bp, dbuf->db_size);
3119
3120 dbuf_override_impl(db, &bp, tx);
3121 }
3122
3123 /*
3124 * Directly assign a provided arc buf to a given dbuf if it's not referenced
3125 * by anybody except our caller. Otherwise copy arcbuf's contents to dbuf.
3126 */
3127 void
dbuf_assign_arcbuf(dmu_buf_impl_t * db,arc_buf_t * buf,dmu_tx_t * tx,dmu_flags_t flags)3128 dbuf_assign_arcbuf(dmu_buf_impl_t *db, arc_buf_t *buf, dmu_tx_t *tx,
3129 dmu_flags_t flags)
3130 {
3131 ASSERT(!zfs_refcount_is_zero(&db->db_holds));
3132 ASSERT(db->db_blkid != DMU_BONUS_BLKID);
3133 ASSERT0(db->db_level);
3134 ASSERT3U(dbuf_is_metadata(db), ==, arc_is_metadata(buf));
3135 ASSERT(buf != NULL);
3136 ASSERT3U(arc_buf_lsize(buf), ==, db->db.db_size);
3137 ASSERT(tx->tx_txg != 0);
3138
3139 arc_return_buf(buf, db);
3140 ASSERT(arc_released(buf));
3141
3142 mutex_enter(&db->db_mtx);
3143 if (!(flags & (DMU_UNCACHEDIO | DMU_KEEP_CACHING)))
3144 db->db_pending_evict = B_FALSE;
3145 db->db_partial_read = B_FALSE;
3146
3147 while (db->db_state == DB_READ || db->db_state == DB_FILL)
3148 cv_wait(&db->db_changed, &db->db_mtx);
3149
3150 ASSERT(db->db_state == DB_CACHED || db->db_state == DB_UNCACHED ||
3151 db->db_state == DB_NOFILL);
3152
3153 if (db->db_state == DB_CACHED &&
3154 zfs_refcount_count(&db->db_holds) - 1 > db->db_dirtycnt) {
3155 /*
3156 * In practice, we will never have a case where we have an
3157 * encrypted arc buffer while additional holds exist on the
3158 * dbuf. We don't handle this here so we simply assert that
3159 * fact instead.
3160 */
3161 ASSERT(!arc_is_encrypted(buf));
3162 mutex_exit(&db->db_mtx);
3163 (void) dbuf_dirty(db, tx);
3164 memcpy(db->db.db_data, buf->b_data, db->db.db_size);
3165 arc_buf_destroy(buf, db);
3166 return;
3167 }
3168
3169 if (db->db_state == DB_CACHED) {
3170 dbuf_dirty_record_t *dr = list_head(&db->db_dirty_records);
3171
3172 ASSERT(db->db_buf != NULL);
3173 if (dr != NULL && dr->dr_txg == tx->tx_txg) {
3174 ASSERT(dr->dt.dl.dr_data == db->db_buf);
3175
3176 if (!arc_released(db->db_buf)) {
3177 ASSERT(dr->dt.dl.dr_override_state ==
3178 DR_OVERRIDDEN);
3179 arc_release(db->db_buf, db);
3180 }
3181 dr->dt.dl.dr_data = buf;
3182 arc_buf_destroy(db->db_buf, db);
3183 } else if (dr == NULL || dr->dt.dl.dr_data != db->db_buf) {
3184 arc_release(db->db_buf, db);
3185 arc_buf_destroy(db->db_buf, db);
3186 }
3187 db->db_buf = NULL;
3188 } else if (db->db_state == DB_NOFILL) {
3189 /*
3190 * We will be completely replacing the cloned block. In case
3191 * it was cloned in this transaction group, let's undirty the
3192 * pending clone and mark the block as uncached. This will be
3193 * as if the clone was never done.
3194 */
3195 VERIFY(!dbuf_undirty(db, tx));
3196 db->db_state = DB_UNCACHED;
3197 }
3198 ASSERT0P(db->db_buf);
3199 dbuf_set_data(db, buf);
3200 db->db_state = DB_FILL;
3201 DTRACE_SET_STATE(db, "filling assigned arcbuf");
3202 mutex_exit(&db->db_mtx);
3203 (void) dbuf_dirty(db, tx);
3204 dmu_buf_fill_done(&db->db, tx, B_FALSE);
3205 }
3206
3207 void
dbuf_destroy(dmu_buf_impl_t * db)3208 dbuf_destroy(dmu_buf_impl_t *db)
3209 {
3210 dnode_t *dn;
3211 dmu_buf_impl_t *parent = db->db_parent;
3212 dmu_buf_impl_t *dndb;
3213
3214 ASSERT(MUTEX_HELD(&db->db_mtx));
3215 ASSERT(zfs_refcount_is_zero(&db->db_holds));
3216
3217 if (db->db_buf != NULL) {
3218 arc_buf_destroy(db->db_buf, db);
3219 db->db_buf = NULL;
3220 }
3221
3222 if (db->db_blkid == DMU_BONUS_BLKID) {
3223 int slots = DB_DNODE(db)->dn_num_slots;
3224 int bonuslen = DN_SLOTS_TO_BONUSLEN(slots);
3225 if (db->db.db_data != NULL) {
3226 kmem_free(db->db.db_data, bonuslen);
3227 arc_space_return(bonuslen, ARC_SPACE_BONUS);
3228 db->db_state = DB_UNCACHED;
3229 DTRACE_SET_STATE(db, "buffer cleared");
3230 }
3231 }
3232
3233 dbuf_clear_data(db);
3234
3235 if (multilist_link_active(&db->db_cache_link)) {
3236 ASSERT(db->db_caching_status == DB_DBUF_CACHE ||
3237 db->db_caching_status == DB_DBUF_METADATA_CACHE);
3238
3239 multilist_remove(&dbuf_caches[db->db_caching_status].cache, db);
3240
3241 ASSERT0(dmu_buf_user_size(&db->db));
3242 (void) zfs_refcount_remove_many(
3243 &dbuf_caches[db->db_caching_status].size,
3244 db->db.db_size, db);
3245
3246 if (db->db_caching_status == DB_DBUF_METADATA_CACHE) {
3247 DBUF_STAT_BUMPDOWN(metadata_cache_count);
3248 } else {
3249 DBUF_STAT_BUMPDOWN(cache_levels[db->db_level]);
3250 DBUF_STAT_BUMPDOWN(cache_count);
3251 DBUF_STAT_DECR(cache_levels_bytes[db->db_level],
3252 db->db.db_size);
3253 }
3254 db->db_caching_status = DB_NO_CACHE;
3255 }
3256
3257 ASSERT(db->db_state == DB_UNCACHED || db->db_state == DB_NOFILL);
3258 ASSERT0P(db->db_data_pending);
3259 ASSERT(list_is_empty(&db->db_dirty_records));
3260
3261 db->db_state = DB_EVICTING;
3262 DTRACE_SET_STATE(db, "buffer eviction started");
3263 db->db_blkptr = NULL;
3264
3265 /*
3266 * Now that db_state is DB_EVICTING, nobody else can find this via
3267 * the hash table. We can now drop db_mtx, which allows us to
3268 * acquire the dn_dbufs_mtx.
3269 */
3270 mutex_exit(&db->db_mtx);
3271
3272 DB_DNODE_ENTER(db);
3273 dn = DB_DNODE(db);
3274 dndb = dn->dn_dbuf;
3275 if (db->db_blkid != DMU_BONUS_BLKID) {
3276 boolean_t needlock = !MUTEX_HELD(&dn->dn_dbufs_mtx);
3277 if (needlock)
3278 mutex_enter_nested(&dn->dn_dbufs_mtx,
3279 NESTED_SINGLE);
3280 avl_remove(&dn->dn_dbufs, db);
3281 membar_producer();
3282 DB_DNODE_EXIT(db);
3283 if (needlock)
3284 mutex_exit(&dn->dn_dbufs_mtx);
3285 /*
3286 * Decrementing the dbuf count means that the hold corresponding
3287 * to the removed dbuf is no longer discounted in dnode_move(),
3288 * so the dnode cannot be moved until after we release the hold.
3289 * The membar_producer() ensures visibility of the decremented
3290 * value in dnode_move(), since DB_DNODE_EXIT doesn't actually
3291 * release any lock.
3292 */
3293 mutex_enter(&dn->dn_mtx);
3294 dnode_rele_and_unlock(dn, db, B_TRUE);
3295 #ifdef USE_DNODE_HANDLE
3296 db->db_dnode_handle = NULL;
3297 #else
3298 db->db_dnode = NULL;
3299 #endif
3300
3301 dbuf_hash_remove(db);
3302 } else {
3303 DB_DNODE_EXIT(db);
3304 }
3305
3306 ASSERT(zfs_refcount_is_zero(&db->db_holds));
3307
3308 db->db_parent = NULL;
3309
3310 ASSERT0P(db->db_buf);
3311 ASSERT0P(db->db.db_data);
3312 ASSERT0P(db->db_hash_next);
3313 ASSERT0P(db->db_blkptr);
3314 ASSERT0P(db->db_data_pending);
3315 ASSERT3U(db->db_caching_status, ==, DB_NO_CACHE);
3316 ASSERT(!multilist_link_active(&db->db_cache_link));
3317
3318 /*
3319 * If this dbuf is referenced from an indirect dbuf,
3320 * decrement the ref count on the indirect dbuf.
3321 */
3322 if (parent && parent != dndb) {
3323 mutex_enter(&parent->db_mtx);
3324 dbuf_rele_and_unlock(parent, db, B_TRUE);
3325 }
3326
3327 kmem_cache_free(dbuf_kmem_cache, db);
3328 arc_space_return(sizeof (dmu_buf_impl_t), ARC_SPACE_DBUF);
3329 }
3330
3331 /*
3332 * Note: While bpp will always be updated if the function returns success,
3333 * parentp will not be updated if the dnode does not have dn_dbuf filled in;
3334 * this happens when the dnode is the meta-dnode, or {user|group|project}used
3335 * object.
3336 */
3337 __attribute__((always_inline))
3338 static inline int
dbuf_findbp(dnode_t * dn,int level,uint64_t blkid,int fail_sparse,dmu_buf_impl_t ** parentp,blkptr_t ** bpp)3339 dbuf_findbp(dnode_t *dn, int level, uint64_t blkid, int fail_sparse,
3340 dmu_buf_impl_t **parentp, blkptr_t **bpp)
3341 {
3342 *parentp = NULL;
3343 *bpp = NULL;
3344
3345 ASSERT(blkid != DMU_BONUS_BLKID);
3346
3347 if (blkid == DMU_SPILL_BLKID) {
3348 mutex_enter(&dn->dn_mtx);
3349 if (dn->dn_have_spill &&
3350 (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR))
3351 *bpp = DN_SPILL_BLKPTR(dn->dn_phys);
3352 else
3353 *bpp = NULL;
3354 dbuf_add_ref(dn->dn_dbuf, NULL);
3355 *parentp = dn->dn_dbuf;
3356 mutex_exit(&dn->dn_mtx);
3357 return (0);
3358 }
3359
3360 int nlevels =
3361 (dn->dn_phys->dn_nlevels == 0) ? 1 : dn->dn_phys->dn_nlevels;
3362 int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
3363
3364 ASSERT3U(level * epbs, <, 64);
3365 ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
3366 /*
3367 * This assertion shouldn't trip as long as the max indirect block size
3368 * is less than 1M. The reason for this is that up to that point,
3369 * the number of levels required to address an entire object with blocks
3370 * of size SPA_MINBLOCKSIZE satisfies nlevels * epbs + 1 <= 64. In
3371 * other words, if N * epbs + 1 > 64, then if (N-1) * epbs + 1 > 55
3372 * (i.e. we can address the entire object), objects will all use at most
3373 * N-1 levels and the assertion won't overflow. However, once epbs is
3374 * 13, 4 * 13 + 1 = 53, but 5 * 13 + 1 = 66. Then, 4 levels will not be
3375 * enough to address an entire object, so objects will have 5 levels,
3376 * but then this assertion will overflow.
3377 *
3378 * All this is to say that if we ever increase DN_MAX_INDBLKSHIFT, we
3379 * need to redo this logic to handle overflows.
3380 */
3381 ASSERT(level >= nlevels ||
3382 ((nlevels - level - 1) * epbs) +
3383 highbit64(dn->dn_phys->dn_nblkptr) <= 64);
3384 if (level >= nlevels ||
3385 blkid >= ((uint64_t)dn->dn_phys->dn_nblkptr <<
3386 ((nlevels - level - 1) * epbs)) ||
3387 (fail_sparse &&
3388 blkid > (dn->dn_phys->dn_maxblkid >> (level * epbs)))) {
3389 /* the buffer has no parent yet */
3390 return (SET_ERROR(ENOENT));
3391 } else if (level < nlevels-1) {
3392 /* this block is referenced from an indirect block */
3393 int err;
3394
3395 err = dbuf_hold_impl(dn, level + 1,
3396 blkid >> epbs, fail_sparse, FALSE, NULL, parentp);
3397
3398 if (err)
3399 return (err);
3400 err = dbuf_read(*parentp, NULL, DB_RF_CANFAIL |
3401 DB_RF_HAVESTRUCT | DMU_READ_NO_PREFETCH);
3402 if (err) {
3403 dbuf_rele(*parentp, NULL);
3404 *parentp = NULL;
3405 return (err);
3406 }
3407 *bpp = ((blkptr_t *)(*parentp)->db.db_data) +
3408 (blkid & ((1ULL << epbs) - 1));
3409 return (0);
3410 } else {
3411 /* the block is referenced from the dnode */
3412 ASSERT3U(level, ==, nlevels-1);
3413 ASSERT(dn->dn_phys->dn_nblkptr == 0 ||
3414 blkid < dn->dn_phys->dn_nblkptr);
3415 if (dn->dn_dbuf) {
3416 dbuf_add_ref(dn->dn_dbuf, NULL);
3417 *parentp = dn->dn_dbuf;
3418 }
3419 *bpp = &dn->dn_phys->dn_blkptr[blkid];
3420 return (0);
3421 }
3422 }
3423
3424 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)3425 dbuf_create(dnode_t *dn, uint8_t level, uint64_t blkid,
3426 dmu_buf_impl_t *parent, blkptr_t *blkptr, uint64_t hash)
3427 {
3428 objset_t *os = dn->dn_objset;
3429 dmu_buf_impl_t *db, *odb;
3430
3431 ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
3432 ASSERT(dn->dn_type != DMU_OT_NONE);
3433
3434 db = kmem_cache_alloc(dbuf_kmem_cache, KM_SLEEP);
3435
3436 list_create(&db->db_dirty_records, sizeof (dbuf_dirty_record_t),
3437 offsetof(dbuf_dirty_record_t, dr_dbuf_node));
3438
3439 db->db_objset = os;
3440 db->db.db_object = dn->dn_object;
3441 db->db_level = level;
3442 db->db_blkid = blkid;
3443 db->db_dirtycnt = 0;
3444 #ifdef USE_DNODE_HANDLE
3445 db->db_dnode_handle = dn->dn_handle;
3446 #else
3447 db->db_dnode = dn;
3448 #endif
3449 db->db_parent = parent;
3450 db->db_blkptr = blkptr;
3451 db->db_hash = hash;
3452
3453 db->db_user = NULL;
3454 db->db_user_immediate_evict = FALSE;
3455 db->db_freed_in_flight = FALSE;
3456 db->db_pending_evict = TRUE;
3457 db->db_partial_read = FALSE;
3458
3459 if (blkid == DMU_BONUS_BLKID) {
3460 ASSERT3P(parent, ==, dn->dn_dbuf);
3461 db->db.db_size = DN_SLOTS_TO_BONUSLEN(dn->dn_num_slots) -
3462 (dn->dn_nblkptr-1) * sizeof (blkptr_t);
3463 ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
3464 db->db.db_offset = DMU_BONUS_BLKID;
3465 db->db_state = DB_UNCACHED;
3466 DTRACE_SET_STATE(db, "bonus buffer created");
3467 db->db_caching_status = DB_NO_CACHE;
3468 /* the bonus dbuf is not placed in the hash table */
3469 arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_DBUF);
3470 return (db);
3471 } else if (blkid == DMU_SPILL_BLKID) {
3472 db->db.db_size = (blkptr != NULL) ?
3473 BP_GET_LSIZE(blkptr) : SPA_MINBLOCKSIZE;
3474 db->db.db_offset = 0;
3475 } else {
3476 int blocksize =
3477 db->db_level ? 1 << dn->dn_indblkshift : dn->dn_datablksz;
3478 db->db.db_size = blocksize;
3479 db->db.db_offset = db->db_blkid * blocksize;
3480 }
3481
3482 /*
3483 * Hold the dn_dbufs_mtx while we get the new dbuf
3484 * in the hash table *and* added to the dbufs list.
3485 * This prevents a possible deadlock with someone
3486 * trying to look up this dbuf before it's added to the
3487 * dn_dbufs list.
3488 */
3489 mutex_enter(&dn->dn_dbufs_mtx);
3490 db->db_state = DB_EVICTING; /* not worth logging this state change */
3491 if ((odb = dbuf_hash_insert(db)) != NULL) {
3492 /* someone else inserted it first */
3493 mutex_exit(&dn->dn_dbufs_mtx);
3494 kmem_cache_free(dbuf_kmem_cache, db);
3495 DBUF_STAT_BUMP(hash_insert_race);
3496 return (odb);
3497 }
3498 avl_add(&dn->dn_dbufs, db);
3499
3500 db->db_state = DB_UNCACHED;
3501 DTRACE_SET_STATE(db, "regular buffer created");
3502 db->db_caching_status = DB_NO_CACHE;
3503 mutex_exit(&dn->dn_dbufs_mtx);
3504 arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_DBUF);
3505
3506 if (parent && parent != dn->dn_dbuf)
3507 dbuf_add_ref(parent, db);
3508
3509 ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
3510 zfs_refcount_count(&dn->dn_holds) > 0);
3511 (void) zfs_refcount_add(&dn->dn_holds, db);
3512
3513 dprintf_dbuf(db, "db=%p\n", db);
3514
3515 return (db);
3516 }
3517
3518 /*
3519 * This function returns a block pointer and information about the object,
3520 * given a dnode and a block. This is a publicly accessible version of
3521 * dbuf_findbp that only returns some information, rather than the
3522 * dbuf. Note that the dnode passed in must be held, and the dn_struct_rwlock
3523 * should be locked as (at least) a reader.
3524 */
3525 int
dbuf_dnode_findbp(dnode_t * dn,uint64_t level,uint64_t blkid,blkptr_t * bp,uint16_t * datablkszsec,uint8_t * indblkshift)3526 dbuf_dnode_findbp(dnode_t *dn, uint64_t level, uint64_t blkid,
3527 blkptr_t *bp, uint16_t *datablkszsec, uint8_t *indblkshift)
3528 {
3529 dmu_buf_impl_t *dbp = NULL;
3530 blkptr_t *bp2;
3531 int err = 0;
3532 ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
3533
3534 err = dbuf_findbp(dn, level, blkid, B_FALSE, &dbp, &bp2);
3535 if (err == 0) {
3536 ASSERT3P(bp2, !=, NULL);
3537 *bp = *bp2;
3538 if (dbp != NULL)
3539 dbuf_rele(dbp, NULL);
3540 if (datablkszsec != NULL)
3541 *datablkszsec = dn->dn_phys->dn_datablkszsec;
3542 if (indblkshift != NULL)
3543 *indblkshift = dn->dn_phys->dn_indblkshift;
3544 }
3545
3546 return (err);
3547 }
3548
3549 typedef struct dbuf_prefetch_arg {
3550 spa_t *dpa_spa; /* The spa to issue the prefetch in. */
3551 zbookmark_phys_t dpa_zb; /* The target block to prefetch. */
3552 int dpa_epbs; /* Entries (blkptr_t's) Per Block Shift. */
3553 int dpa_curlevel; /* The current level that we're reading */
3554 dnode_t *dpa_dnode; /* The dnode associated with the prefetch */
3555 zio_priority_t dpa_prio; /* The priority I/Os should be issued at. */
3556 arc_flags_t dpa_aflags; /* Flags to pass to the final prefetch. */
3557 dbuf_prefetch_fn dpa_cb; /* prefetch completion callback */
3558 void *dpa_arg; /* prefetch completion arg */
3559 } dbuf_prefetch_arg_t;
3560
3561 static void
dbuf_prefetch_fini(dbuf_prefetch_arg_t * dpa,boolean_t io_done)3562 dbuf_prefetch_fini(dbuf_prefetch_arg_t *dpa, boolean_t io_done)
3563 {
3564 if (dpa->dpa_cb != NULL) {
3565 dpa->dpa_cb(dpa->dpa_arg, dpa->dpa_zb.zb_level,
3566 dpa->dpa_zb.zb_blkid, io_done);
3567 }
3568 kmem_free(dpa, sizeof (*dpa));
3569 }
3570
3571 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)3572 dbuf_issue_final_prefetch_done(zio_t *zio, const zbookmark_phys_t *zb,
3573 const blkptr_t *iobp, arc_buf_t *abuf, void *private)
3574 {
3575 (void) zio, (void) zb, (void) iobp;
3576 dbuf_prefetch_arg_t *dpa = private;
3577
3578 if (abuf != NULL)
3579 arc_buf_destroy(abuf, private);
3580
3581 dbuf_prefetch_fini(dpa, B_TRUE);
3582 }
3583
3584 /*
3585 * Actually issue the prefetch read for the block given.
3586 */
3587 static void
dbuf_issue_final_prefetch(dbuf_prefetch_arg_t * dpa,blkptr_t * bp)3588 dbuf_issue_final_prefetch(dbuf_prefetch_arg_t *dpa, blkptr_t *bp)
3589 {
3590 ASSERT(!BP_IS_HOLE(bp));
3591 ASSERT(!BP_IS_REDACTED(bp));
3592 if (BP_IS_EMBEDDED(bp))
3593 return (dbuf_prefetch_fini(dpa, B_FALSE));
3594
3595 int zio_flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE;
3596 arc_flags_t aflags =
3597 dpa->dpa_aflags | ARC_FLAG_NOWAIT | ARC_FLAG_PREFETCH |
3598 ARC_FLAG_NO_BUF;
3599
3600 /* dnodes are always read as raw and then converted later */
3601 if (BP_GET_TYPE(bp) == DMU_OT_DNODE && BP_IS_PROTECTED(bp) &&
3602 dpa->dpa_curlevel == 0)
3603 zio_flags |= ZIO_FLAG_RAW;
3604
3605 ASSERT3U(dpa->dpa_curlevel, ==, BP_GET_LEVEL(bp));
3606 ASSERT3U(dpa->dpa_curlevel, ==, dpa->dpa_zb.zb_level);
3607 (void) arc_read(NULL, dpa->dpa_spa, bp,
3608 dbuf_issue_final_prefetch_done, dpa,
3609 dpa->dpa_prio, zio_flags, &aflags, &dpa->dpa_zb);
3610 }
3611
3612 /*
3613 * Called when an indirect block above our prefetch target is read in. This
3614 * will either read in the next indirect block down the tree or issue the actual
3615 * prefetch if the next block down is our target.
3616 */
3617 static void
dbuf_prefetch_indirect_done(zio_t * zio,const zbookmark_phys_t * zb,const blkptr_t * iobp,arc_buf_t * abuf,void * private)3618 dbuf_prefetch_indirect_done(zio_t *zio, const zbookmark_phys_t *zb,
3619 const blkptr_t *iobp, arc_buf_t *abuf, void *private)
3620 {
3621 (void) zb, (void) iobp;
3622 dbuf_prefetch_arg_t *dpa = private;
3623
3624 ASSERT3S(dpa->dpa_zb.zb_level, <, dpa->dpa_curlevel);
3625 ASSERT3S(dpa->dpa_curlevel, >, 0);
3626
3627 if (abuf == NULL) {
3628 ASSERT(zio == NULL || zio->io_error != 0);
3629 dbuf_prefetch_fini(dpa, B_TRUE);
3630 return;
3631 }
3632 ASSERT(zio == NULL || zio->io_error == 0);
3633
3634 /*
3635 * The dpa_dnode is only valid if we are called with a NULL
3636 * zio. This indicates that the arc_read() returned without
3637 * first calling zio_read() to issue a physical read. Once
3638 * a physical read is made the dpa_dnode must be invalidated
3639 * as the locks guarding it may have been dropped. If the
3640 * dpa_dnode is still valid, then we want to add it to the dbuf
3641 * cache. To do so, we must hold the dbuf associated with the block
3642 * we just prefetched, read its contents so that we associate it
3643 * with an arc_buf_t, and then release it.
3644 */
3645 if (zio != NULL) {
3646 ASSERT3S(BP_GET_LEVEL(zio->io_bp), ==, dpa->dpa_curlevel);
3647 if (zio->io_flags & ZIO_FLAG_RAW_COMPRESS) {
3648 ASSERT3U(BP_GET_PSIZE(zio->io_bp), ==, zio->io_size);
3649 } else {
3650 ASSERT3U(BP_GET_LSIZE(zio->io_bp), ==, zio->io_size);
3651 }
3652 ASSERT3P(zio->io_spa, ==, dpa->dpa_spa);
3653
3654 dpa->dpa_dnode = NULL;
3655 } else if (dpa->dpa_dnode != NULL) {
3656 uint64_t curblkid = dpa->dpa_zb.zb_blkid >>
3657 (dpa->dpa_epbs * (dpa->dpa_curlevel -
3658 dpa->dpa_zb.zb_level));
3659 dmu_buf_impl_t *db = dbuf_hold_level(dpa->dpa_dnode,
3660 dpa->dpa_curlevel, curblkid, FTAG);
3661 if (db == NULL) {
3662 arc_buf_destroy(abuf, private);
3663 dbuf_prefetch_fini(dpa, B_TRUE);
3664 return;
3665 }
3666 (void) dbuf_read(db, NULL, DB_RF_CANFAIL | DB_RF_HAVESTRUCT |
3667 DMU_READ_NO_PREFETCH);
3668 dbuf_rele(db, FTAG);
3669 }
3670
3671 dpa->dpa_curlevel--;
3672 uint64_t nextblkid = dpa->dpa_zb.zb_blkid >>
3673 (dpa->dpa_epbs * (dpa->dpa_curlevel - dpa->dpa_zb.zb_level));
3674 blkptr_t *bp = ((blkptr_t *)abuf->b_data) +
3675 P2PHASE(nextblkid, 1ULL << dpa->dpa_epbs);
3676
3677 ASSERT(!BP_IS_REDACTED(bp) || dpa->dpa_dnode == NULL ||
3678 dsl_dataset_feature_is_active(
3679 dpa->dpa_dnode->dn_objset->os_dsl_dataset,
3680 SPA_FEATURE_REDACTED_DATASETS));
3681 if (BP_IS_HOLE(bp) || BP_IS_REDACTED(bp)) {
3682 arc_buf_destroy(abuf, private);
3683 dbuf_prefetch_fini(dpa, B_TRUE);
3684 return;
3685 } else if (dpa->dpa_curlevel == dpa->dpa_zb.zb_level) {
3686 ASSERT3U(nextblkid, ==, dpa->dpa_zb.zb_blkid);
3687 dbuf_issue_final_prefetch(dpa, bp);
3688 } else {
3689 arc_flags_t iter_aflags = ARC_FLAG_NOWAIT;
3690 zbookmark_phys_t zb;
3691
3692 /* flag if L2ARC eligible, l2arc_noprefetch then decides */
3693 if (dpa->dpa_dnode) {
3694 if (dnode_level_is_l2cacheable(bp, dpa->dpa_dnode,
3695 dpa->dpa_curlevel))
3696 iter_aflags |= ARC_FLAG_L2CACHE;
3697 } else {
3698 if (dpa->dpa_aflags & ARC_FLAG_L2CACHE)
3699 iter_aflags |= ARC_FLAG_L2CACHE;
3700 }
3701
3702 ASSERT3U(dpa->dpa_curlevel, ==, BP_GET_LEVEL(bp));
3703
3704 SET_BOOKMARK(&zb, dpa->dpa_zb.zb_objset,
3705 dpa->dpa_zb.zb_object, dpa->dpa_curlevel, nextblkid);
3706
3707 (void) arc_read(NULL, dpa->dpa_spa,
3708 bp, dbuf_prefetch_indirect_done, dpa,
3709 ZIO_PRIORITY_SYNC_READ,
3710 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
3711 &iter_aflags, &zb);
3712 }
3713
3714 arc_buf_destroy(abuf, private);
3715 }
3716
3717 /*
3718 * Issue prefetch reads for the given block on the given level. If the indirect
3719 * blocks above that block are not in memory, we will read them in
3720 * asynchronously. As a result, this call never blocks waiting for a read to
3721 * complete. Note that the prefetch might fail if the dataset is encrypted and
3722 * the encryption key is unmapped before the IO completes.
3723 */
3724 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)3725 dbuf_prefetch_impl(dnode_t *dn, int64_t level, uint64_t blkid,
3726 zio_priority_t prio, arc_flags_t aflags, dbuf_prefetch_fn cb,
3727 void *arg)
3728 {
3729 blkptr_t bp;
3730 int epbs, nlevels, curlevel;
3731 uint64_t curblkid;
3732
3733 ASSERT(blkid != DMU_BONUS_BLKID);
3734 ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
3735
3736 if (blkid > dn->dn_maxblkid)
3737 goto no_issue;
3738
3739 if (level == 0 && dnode_block_freed(dn, blkid))
3740 goto no_issue;
3741
3742 /*
3743 * This dnode hasn't been written to disk yet, so there's nothing to
3744 * prefetch.
3745 */
3746 nlevels = dn->dn_phys->dn_nlevels;
3747 if (level >= nlevels || dn->dn_phys->dn_nblkptr == 0)
3748 goto no_issue;
3749
3750 epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
3751 if (dn->dn_phys->dn_maxblkid < blkid << (epbs * level))
3752 goto no_issue;
3753
3754 dmu_buf_impl_t *db = dbuf_find(dn->dn_objset, dn->dn_object,
3755 level, blkid, NULL);
3756 if (db != NULL) {
3757 mutex_exit(&db->db_mtx);
3758 /*
3759 * This dbuf already exists. It is either CACHED, or
3760 * (we assume) about to be read or filled.
3761 */
3762 goto no_issue;
3763 }
3764
3765 /*
3766 * Find the closest ancestor (indirect block) of the target block
3767 * that is present in the cache. In this indirect block, we will
3768 * find the bp that is at curlevel, curblkid.
3769 */
3770 curlevel = level;
3771 curblkid = blkid;
3772 while (curlevel < nlevels - 1) {
3773 int parent_level = curlevel + 1;
3774 uint64_t parent_blkid = curblkid >> epbs;
3775 dmu_buf_impl_t *db;
3776
3777 if (dbuf_hold_impl(dn, parent_level, parent_blkid,
3778 FALSE, TRUE, FTAG, &db) == 0) {
3779 blkptr_t *bpp = db->db_buf->b_data;
3780 bp = bpp[P2PHASE(curblkid, 1 << epbs)];
3781 dbuf_rele(db, FTAG);
3782 break;
3783 }
3784
3785 curlevel = parent_level;
3786 curblkid = parent_blkid;
3787 }
3788
3789 if (curlevel == nlevels - 1) {
3790 /* No cached indirect blocks found. */
3791 ASSERT3U(curblkid, <, dn->dn_phys->dn_nblkptr);
3792 bp = dn->dn_phys->dn_blkptr[curblkid];
3793 }
3794 ASSERT(!BP_IS_REDACTED(&bp) ||
3795 dsl_dataset_feature_is_active(dn->dn_objset->os_dsl_dataset,
3796 SPA_FEATURE_REDACTED_DATASETS));
3797 if (BP_IS_HOLE(&bp) || BP_IS_REDACTED(&bp))
3798 goto no_issue;
3799
3800 ASSERT3U(curlevel, ==, BP_GET_LEVEL(&bp));
3801
3802 dbuf_prefetch_arg_t *dpa = kmem_zalloc(sizeof (*dpa), KM_SLEEP);
3803 dsl_dataset_t *ds = dn->dn_objset->os_dsl_dataset;
3804 SET_BOOKMARK(&dpa->dpa_zb, ds != NULL ? ds->ds_object : DMU_META_OBJSET,
3805 dn->dn_object, level, blkid);
3806 dpa->dpa_curlevel = curlevel;
3807 dpa->dpa_prio = prio;
3808 dpa->dpa_aflags = aflags;
3809 dpa->dpa_spa = dn->dn_objset->os_spa;
3810 dpa->dpa_dnode = dn;
3811 dpa->dpa_epbs = epbs;
3812 dpa->dpa_cb = cb;
3813 dpa->dpa_arg = arg;
3814
3815 if (!DNODE_LEVEL_IS_CACHEABLE(dn, level))
3816 dpa->dpa_aflags |= ARC_FLAG_UNCACHED;
3817 else if (dnode_level_is_l2cacheable(&bp, dn, level))
3818 dpa->dpa_aflags |= ARC_FLAG_L2CACHE;
3819
3820 /*
3821 * If we have the indirect just above us, no need to do the asynchronous
3822 * prefetch chain; we'll just run the last step ourselves. If we're at
3823 * a higher level, though, we want to issue the prefetches for all the
3824 * indirect blocks asynchronously, so we can go on with whatever we were
3825 * doing.
3826 */
3827 if (curlevel == level) {
3828 ASSERT3U(curblkid, ==, blkid);
3829 dbuf_issue_final_prefetch(dpa, &bp);
3830 } else {
3831 arc_flags_t iter_aflags = ARC_FLAG_NOWAIT;
3832 zbookmark_phys_t zb;
3833
3834 /* flag if L2ARC eligible, l2arc_noprefetch then decides */
3835 if (dnode_level_is_l2cacheable(&bp, dn, curlevel))
3836 iter_aflags |= ARC_FLAG_L2CACHE;
3837
3838 SET_BOOKMARK(&zb, ds != NULL ? ds->ds_object : DMU_META_OBJSET,
3839 dn->dn_object, curlevel, curblkid);
3840 (void) arc_read(NULL, dpa->dpa_spa,
3841 &bp, dbuf_prefetch_indirect_done, dpa,
3842 ZIO_PRIORITY_SYNC_READ,
3843 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
3844 &iter_aflags, &zb);
3845 }
3846 return (1);
3847 no_issue:
3848 if (cb != NULL)
3849 cb(arg, level, blkid, B_FALSE);
3850 return (0);
3851 }
3852
3853 int
dbuf_prefetch(dnode_t * dn,int64_t level,uint64_t blkid,zio_priority_t prio,arc_flags_t aflags)3854 dbuf_prefetch(dnode_t *dn, int64_t level, uint64_t blkid, zio_priority_t prio,
3855 arc_flags_t aflags)
3856 {
3857
3858 return (dbuf_prefetch_impl(dn, level, blkid, prio, aflags, NULL, NULL));
3859 }
3860
3861 /*
3862 * Helper function for dbuf_hold_impl() to copy a buffer. Handles
3863 * the case of encrypted, compressed and uncompressed buffers by
3864 * allocating the new buffer, respectively, with arc_alloc_raw_buf(),
3865 * arc_alloc_compressed_buf() or arc_alloc_buf().*
3866 *
3867 * NOTE: Declared noinline to avoid stack bloat in dbuf_hold_impl().
3868 */
3869 noinline static void
dbuf_hold_copy(dnode_t * dn,dmu_buf_impl_t * db)3870 dbuf_hold_copy(dnode_t *dn, dmu_buf_impl_t *db)
3871 {
3872 dbuf_dirty_record_t *dr = db->db_data_pending;
3873 arc_buf_t *data = dr->dt.dl.dr_data;
3874 arc_buf_t *db_data;
3875 enum zio_compress compress_type = arc_get_compression(data);
3876 uint8_t complevel = arc_get_complevel(data);
3877
3878 if (arc_is_encrypted(data)) {
3879 boolean_t byteorder;
3880 uint8_t salt[ZIO_DATA_SALT_LEN];
3881 uint8_t iv[ZIO_DATA_IV_LEN];
3882 uint8_t mac[ZIO_DATA_MAC_LEN];
3883
3884 arc_get_raw_params(data, &byteorder, salt, iv, mac);
3885 db_data = arc_alloc_raw_buf(dn->dn_objset->os_spa, db,
3886 dmu_objset_id(dn->dn_objset), byteorder, salt, iv, mac,
3887 dn->dn_type, arc_buf_size(data), arc_buf_lsize(data),
3888 compress_type, complevel);
3889 } else if (compress_type != ZIO_COMPRESS_OFF) {
3890 db_data = arc_alloc_compressed_buf(
3891 dn->dn_objset->os_spa, db, arc_buf_size(data),
3892 arc_buf_lsize(data), compress_type, complevel);
3893 } else {
3894 db_data = arc_alloc_buf(dn->dn_objset->os_spa, db,
3895 DBUF_GET_BUFC_TYPE(db), db->db.db_size);
3896 }
3897 memcpy(db_data->b_data, data->b_data, arc_buf_size(data));
3898
3899 dbuf_set_data(db, db_data);
3900 }
3901
3902 /*
3903 * Returns with db_holds incremented, and db_mtx not held.
3904 * Note: dn_struct_rwlock must be held.
3905 */
3906 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)3907 dbuf_hold_impl(dnode_t *dn, uint8_t level, uint64_t blkid,
3908 boolean_t fail_sparse, boolean_t fail_uncached,
3909 const void *tag, dmu_buf_impl_t **dbp)
3910 {
3911 dmu_buf_impl_t *db, *parent = NULL;
3912 uint64_t hv;
3913
3914 /* If the pool has been created, verify the tx_sync_lock is not held */
3915 spa_t *spa = dn->dn_objset->os_spa;
3916 dsl_pool_t *dp = spa->spa_dsl_pool;
3917 if (dp != NULL) {
3918 ASSERT(!MUTEX_HELD(&dp->dp_tx.tx_sync_lock));
3919 }
3920
3921 ASSERT(blkid != DMU_BONUS_BLKID);
3922 ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
3923 if (!fail_sparse)
3924 ASSERT3U(dn->dn_nlevels, >, level);
3925
3926 *dbp = NULL;
3927
3928 /* dbuf_find() returns with db_mtx held */
3929 db = dbuf_find(dn->dn_objset, dn->dn_object, level, blkid, &hv);
3930
3931 if (db == NULL) {
3932 blkptr_t *bp = NULL;
3933 int err;
3934
3935 if (fail_uncached)
3936 return (SET_ERROR(ENOENT));
3937
3938 ASSERT0P(parent);
3939 err = dbuf_findbp(dn, level, blkid, fail_sparse, &parent, &bp);
3940 if (fail_sparse) {
3941 if (err == 0 && bp && BP_IS_HOLE(bp))
3942 err = SET_ERROR(ENOENT);
3943 if (err) {
3944 if (parent)
3945 dbuf_rele(parent, NULL);
3946 return (err);
3947 }
3948 }
3949 if (err && err != ENOENT)
3950 return (err);
3951 db = dbuf_create(dn, level, blkid, parent, bp, hv);
3952 }
3953
3954 if (fail_uncached && db->db_state != DB_CACHED) {
3955 mutex_exit(&db->db_mtx);
3956 return (SET_ERROR(ENOENT));
3957 }
3958
3959 if (db->db_buf != NULL) {
3960 arc_buf_access(db->db_buf);
3961 ASSERT(MUTEX_HELD(&db->db_mtx));
3962 ASSERT3P(db->db.db_data, ==, db->db_buf->b_data);
3963 }
3964
3965 ASSERT(db->db_buf == NULL || arc_referenced(db->db_buf));
3966
3967 /*
3968 * If this buffer is currently syncing out, and we are
3969 * still referencing it from db_data, we need to make a copy
3970 * of it in case we decide we want to dirty it again in this txg.
3971 */
3972 if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
3973 dn->dn_object != DMU_META_DNODE_OBJECT &&
3974 db->db_state == DB_CACHED && db->db_data_pending) {
3975 dbuf_dirty_record_t *dr = db->db_data_pending;
3976 if (dr->dt.dl.dr_data == db->db_buf) {
3977 ASSERT3P(db->db_buf, !=, NULL);
3978 dbuf_hold_copy(dn, db);
3979 }
3980 }
3981
3982 if (multilist_link_active(&db->db_cache_link)) {
3983 ASSERT(zfs_refcount_is_zero(&db->db_holds));
3984 ASSERT(db->db_caching_status == DB_DBUF_CACHE ||
3985 db->db_caching_status == DB_DBUF_METADATA_CACHE);
3986
3987 multilist_remove(&dbuf_caches[db->db_caching_status].cache, db);
3988
3989 uint64_t size = db->db.db_size;
3990 uint64_t usize = dmu_buf_user_size(&db->db);
3991 (void) zfs_refcount_remove_many(
3992 &dbuf_caches[db->db_caching_status].size, size, db);
3993 (void) zfs_refcount_remove_many(
3994 &dbuf_caches[db->db_caching_status].size, usize,
3995 db->db_user);
3996
3997 if (db->db_caching_status == DB_DBUF_METADATA_CACHE) {
3998 DBUF_STAT_BUMPDOWN(metadata_cache_count);
3999 } else {
4000 DBUF_STAT_BUMPDOWN(cache_levels[db->db_level]);
4001 DBUF_STAT_BUMPDOWN(cache_count);
4002 DBUF_STAT_DECR(cache_levels_bytes[db->db_level],
4003 size + usize);
4004 }
4005 db->db_caching_status = DB_NO_CACHE;
4006 }
4007 (void) zfs_refcount_add(&db->db_holds, tag);
4008 DBUF_VERIFY(db);
4009 mutex_exit(&db->db_mtx);
4010
4011 /* NOTE: we can't rele the parent until after we drop the db_mtx */
4012 if (parent)
4013 dbuf_rele(parent, NULL);
4014
4015 ASSERT3P(DB_DNODE(db), ==, dn);
4016 ASSERT3U(db->db_blkid, ==, blkid);
4017 ASSERT3U(db->db_level, ==, level);
4018 *dbp = db;
4019
4020 return (0);
4021 }
4022
4023 dmu_buf_impl_t *
dbuf_hold(dnode_t * dn,uint64_t blkid,const void * tag)4024 dbuf_hold(dnode_t *dn, uint64_t blkid, const void *tag)
4025 {
4026 return (dbuf_hold_level(dn, 0, blkid, tag));
4027 }
4028
4029 dmu_buf_impl_t *
dbuf_hold_level(dnode_t * dn,int level,uint64_t blkid,const void * tag)4030 dbuf_hold_level(dnode_t *dn, int level, uint64_t blkid, const void *tag)
4031 {
4032 dmu_buf_impl_t *db;
4033 int err = dbuf_hold_impl(dn, level, blkid, FALSE, FALSE, tag, &db);
4034 return (err ? NULL : db);
4035 }
4036
4037 void
dbuf_create_bonus(dnode_t * dn)4038 dbuf_create_bonus(dnode_t *dn)
4039 {
4040 ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
4041
4042 ASSERT0P(dn->dn_bonus);
4043 dn->dn_bonus = dbuf_create(dn, 0, DMU_BONUS_BLKID, dn->dn_dbuf, NULL,
4044 dbuf_hash(dn->dn_objset, dn->dn_object, 0, DMU_BONUS_BLKID));
4045 dn->dn_bonus->db_pending_evict = FALSE;
4046 }
4047
4048 int
dbuf_spill_set_blksz(dmu_buf_t * db_fake,uint64_t blksz,dmu_tx_t * tx)4049 dbuf_spill_set_blksz(dmu_buf_t *db_fake, uint64_t blksz, dmu_tx_t *tx)
4050 {
4051 dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
4052
4053 if (db->db_blkid != DMU_SPILL_BLKID)
4054 return (SET_ERROR(ENOTSUP));
4055 if (blksz == 0)
4056 blksz = SPA_MINBLOCKSIZE;
4057 ASSERT3U(blksz, <=, spa_maxblocksize(dmu_objset_spa(db->db_objset)));
4058 blksz = P2ROUNDUP(blksz, SPA_MINBLOCKSIZE);
4059
4060 dbuf_new_size(db, blksz, tx);
4061
4062 return (0);
4063 }
4064
4065 void
dbuf_rm_spill(dnode_t * dn,dmu_tx_t * tx)4066 dbuf_rm_spill(dnode_t *dn, dmu_tx_t *tx)
4067 {
4068 dbuf_free_range(dn, DMU_SPILL_BLKID, DMU_SPILL_BLKID, tx);
4069 }
4070
4071 #pragma weak dmu_buf_add_ref = dbuf_add_ref
4072 void
dbuf_add_ref(dmu_buf_impl_t * db,const void * tag)4073 dbuf_add_ref(dmu_buf_impl_t *db, const void *tag)
4074 {
4075 int64_t holds = zfs_refcount_add(&db->db_holds, tag);
4076 VERIFY3S(holds, >, 1);
4077 }
4078
4079 #pragma weak dmu_buf_try_add_ref = dbuf_try_add_ref
4080 boolean_t
dbuf_try_add_ref(dmu_buf_t * db_fake,objset_t * os,uint64_t obj,uint64_t blkid,const void * tag)4081 dbuf_try_add_ref(dmu_buf_t *db_fake, objset_t *os, uint64_t obj, uint64_t blkid,
4082 const void *tag)
4083 {
4084 dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
4085 dmu_buf_impl_t *found_db;
4086 boolean_t result = B_FALSE;
4087
4088 if (blkid == DMU_BONUS_BLKID)
4089 found_db = dbuf_find_bonus(os, obj);
4090 else
4091 found_db = dbuf_find(os, obj, 0, blkid, NULL);
4092
4093 if (found_db != NULL) {
4094 if (db == found_db && dbuf_refcount(db) > db->db_dirtycnt) {
4095 (void) zfs_refcount_add(&db->db_holds, tag);
4096 result = B_TRUE;
4097 }
4098 mutex_exit(&found_db->db_mtx);
4099 }
4100 return (result);
4101 }
4102
4103 /*
4104 * If you call dbuf_rele() you had better not be referencing the dnode handle
4105 * unless you have some other direct or indirect hold on the dnode. (An indirect
4106 * hold is a hold on one of the dnode's dbufs, including the bonus buffer.)
4107 * Without that, the dbuf_rele() could lead to a dnode_rele() followed by the
4108 * dnode's parent dbuf evicting its dnode handles.
4109 */
4110 void
dbuf_rele(dmu_buf_impl_t * db,const void * tag)4111 dbuf_rele(dmu_buf_impl_t *db, const void *tag)
4112 {
4113 mutex_enter(&db->db_mtx);
4114 dbuf_rele_and_unlock(db, tag, B_FALSE);
4115 }
4116
4117 void
dmu_buf_rele(dmu_buf_t * db,const void * tag)4118 dmu_buf_rele(dmu_buf_t *db, const void *tag)
4119 {
4120 dbuf_rele((dmu_buf_impl_t *)db, tag);
4121 }
4122
4123 /*
4124 * dbuf_rele() for an already-locked dbuf. This is necessary to allow
4125 * db_dirtycnt and db_holds to be updated atomically. The 'evicting'
4126 * argument should be set if we are already in the dbuf-evicting code
4127 * path, in which case we don't want to recursively evict. This allows us to
4128 * avoid deeply nested stacks that would have a call flow similar to this:
4129 *
4130 * dbuf_rele()-->dbuf_rele_and_unlock()-->dbuf_evict_notify()
4131 * ^ |
4132 * | |
4133 * +-----dbuf_destroy()<--dbuf_evict_one()<--------+
4134 *
4135 */
4136 void
dbuf_rele_and_unlock(dmu_buf_impl_t * db,const void * tag,boolean_t evicting)4137 dbuf_rele_and_unlock(dmu_buf_impl_t *db, const void *tag, boolean_t evicting)
4138 {
4139 int64_t holds;
4140 uint64_t size;
4141
4142 ASSERT(MUTEX_HELD(&db->db_mtx));
4143 DBUF_VERIFY(db);
4144
4145 /*
4146 * Remove the reference to the dbuf before removing its hold on the
4147 * dnode so we can guarantee in dnode_move() that a referenced bonus
4148 * buffer has a corresponding dnode hold.
4149 */
4150 holds = zfs_refcount_remove(&db->db_holds, tag);
4151 ASSERT(holds >= 0);
4152
4153 /*
4154 * We can't freeze indirects if there is a possibility that they
4155 * may be modified in the current syncing context.
4156 */
4157 if (db->db_buf != NULL &&
4158 holds == (db->db_level == 0 ? db->db_dirtycnt : 0)) {
4159 arc_buf_freeze(db->db_buf);
4160 }
4161
4162 if (holds == db->db_dirtycnt &&
4163 db->db_level == 0 && db->db_user_immediate_evict)
4164 dbuf_evict_user(db);
4165
4166 if (holds == 0) {
4167 if (db->db_blkid == DMU_BONUS_BLKID) {
4168 dnode_t *dn;
4169 boolean_t evict_dbuf = db->db_pending_evict;
4170
4171 /*
4172 * If the dnode moves here, we cannot cross this
4173 * barrier until the move completes.
4174 */
4175 DB_DNODE_ENTER(db);
4176
4177 dn = DB_DNODE(db);
4178 atomic_dec_32(&dn->dn_dbufs_count);
4179
4180 /*
4181 * Decrementing the dbuf count means that the bonus
4182 * buffer's dnode hold is no longer discounted in
4183 * dnode_move(). The dnode cannot move until after
4184 * the dnode_rele() below.
4185 */
4186 DB_DNODE_EXIT(db);
4187
4188 /*
4189 * Do not reference db after its lock is dropped.
4190 * Another thread may evict it.
4191 */
4192 mutex_exit(&db->db_mtx);
4193
4194 if (evict_dbuf)
4195 dnode_evict_bonus(dn);
4196
4197 dnode_rele(dn, db);
4198 } else if (db->db_buf == NULL) {
4199 /*
4200 * This is a special case: we never associated this
4201 * dbuf with any data allocated from the ARC.
4202 */
4203 ASSERT(db->db_state == DB_UNCACHED ||
4204 db->db_state == DB_NOFILL);
4205 dbuf_destroy(db);
4206 } else if (arc_released(db->db_buf)) {
4207 /*
4208 * This dbuf has anonymous data associated with it.
4209 */
4210 dbuf_destroy(db);
4211 } else if (!db->db_partial_read && !DBUF_IS_CACHEABLE(db)) {
4212 /*
4213 * We don't expect more accesses to the dbuf, and it
4214 * is either not cacheable or was marked for eviction.
4215 */
4216 dbuf_destroy(db);
4217 } else if (!multilist_link_active(&db->db_cache_link)) {
4218 ASSERT3U(db->db_caching_status, ==, DB_NO_CACHE);
4219
4220 dbuf_cached_state_t dcs =
4221 dbuf_include_in_metadata_cache(db) ?
4222 DB_DBUF_METADATA_CACHE : DB_DBUF_CACHE;
4223 db->db_caching_status = dcs;
4224
4225 multilist_insert(&dbuf_caches[dcs].cache, db);
4226 uint64_t db_size = db->db.db_size;
4227 uint64_t dbu_size = dmu_buf_user_size(&db->db);
4228 (void) zfs_refcount_add_many(
4229 &dbuf_caches[dcs].size, db_size, db);
4230 size = zfs_refcount_add_many(
4231 &dbuf_caches[dcs].size, dbu_size, db->db_user);
4232 uint8_t db_level = db->db_level;
4233 mutex_exit(&db->db_mtx);
4234
4235 if (dcs == DB_DBUF_METADATA_CACHE) {
4236 DBUF_STAT_BUMP(metadata_cache_count);
4237 DBUF_STAT_MAX(metadata_cache_size_bytes_max,
4238 size);
4239 } else {
4240 DBUF_STAT_BUMP(cache_count);
4241 DBUF_STAT_MAX(cache_size_bytes_max, size);
4242 DBUF_STAT_BUMP(cache_levels[db_level]);
4243 DBUF_STAT_INCR(cache_levels_bytes[db_level],
4244 db_size + dbu_size);
4245 }
4246
4247 if (dcs == DB_DBUF_CACHE && !evicting)
4248 dbuf_evict_notify(size);
4249 }
4250 } else {
4251 mutex_exit(&db->db_mtx);
4252 }
4253 }
4254
4255 #pragma weak dmu_buf_refcount = dbuf_refcount
4256 uint64_t
dbuf_refcount(dmu_buf_impl_t * db)4257 dbuf_refcount(dmu_buf_impl_t *db)
4258 {
4259 return (zfs_refcount_count(&db->db_holds));
4260 }
4261
4262 uint64_t
dmu_buf_user_refcount(dmu_buf_t * db_fake)4263 dmu_buf_user_refcount(dmu_buf_t *db_fake)
4264 {
4265 uint64_t holds;
4266 dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
4267
4268 mutex_enter(&db->db_mtx);
4269 ASSERT3U(zfs_refcount_count(&db->db_holds), >=, db->db_dirtycnt);
4270 holds = zfs_refcount_count(&db->db_holds) - db->db_dirtycnt;
4271 mutex_exit(&db->db_mtx);
4272
4273 return (holds);
4274 }
4275
4276 void *
dmu_buf_replace_user(dmu_buf_t * db_fake,dmu_buf_user_t * old_user,dmu_buf_user_t * new_user)4277 dmu_buf_replace_user(dmu_buf_t *db_fake, dmu_buf_user_t *old_user,
4278 dmu_buf_user_t *new_user)
4279 {
4280 dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
4281
4282 mutex_enter(&db->db_mtx);
4283 dbuf_verify_user(db, DBVU_NOT_EVICTING);
4284 if (db->db_user == old_user)
4285 db->db_user = new_user;
4286 else
4287 old_user = db->db_user;
4288 dbuf_verify_user(db, DBVU_NOT_EVICTING);
4289 mutex_exit(&db->db_mtx);
4290
4291 return (old_user);
4292 }
4293
4294 void *
dmu_buf_set_user(dmu_buf_t * db_fake,dmu_buf_user_t * user)4295 dmu_buf_set_user(dmu_buf_t *db_fake, dmu_buf_user_t *user)
4296 {
4297 return (dmu_buf_replace_user(db_fake, NULL, user));
4298 }
4299
4300 void *
dmu_buf_set_user_ie(dmu_buf_t * db_fake,dmu_buf_user_t * user)4301 dmu_buf_set_user_ie(dmu_buf_t *db_fake, dmu_buf_user_t *user)
4302 {
4303 dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
4304
4305 db->db_user_immediate_evict = TRUE;
4306 return (dmu_buf_set_user(db_fake, user));
4307 }
4308
4309 void *
dmu_buf_remove_user(dmu_buf_t * db_fake,dmu_buf_user_t * user)4310 dmu_buf_remove_user(dmu_buf_t *db_fake, dmu_buf_user_t *user)
4311 {
4312 return (dmu_buf_replace_user(db_fake, user, NULL));
4313 }
4314
4315 void *
dmu_buf_get_user(dmu_buf_t * db_fake)4316 dmu_buf_get_user(dmu_buf_t *db_fake)
4317 {
4318 dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
4319
4320 dbuf_verify_user(db, DBVU_NOT_EVICTING);
4321 return (db->db_user);
4322 }
4323
4324 uint64_t
dmu_buf_user_size(dmu_buf_t * db_fake)4325 dmu_buf_user_size(dmu_buf_t *db_fake)
4326 {
4327 dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
4328 if (db->db_user == NULL)
4329 return (0);
4330 return (atomic_load_64(&db->db_user->dbu_size));
4331 }
4332
4333 void
dmu_buf_add_user_size(dmu_buf_t * db_fake,uint64_t nadd)4334 dmu_buf_add_user_size(dmu_buf_t *db_fake, uint64_t nadd)
4335 {
4336 dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
4337 ASSERT3U(db->db_caching_status, ==, DB_NO_CACHE);
4338 ASSERT3P(db->db_user, !=, NULL);
4339 ASSERT3U(atomic_load_64(&db->db_user->dbu_size), <, UINT64_MAX - nadd);
4340 atomic_add_64(&db->db_user->dbu_size, nadd);
4341 }
4342
4343 void
dmu_buf_sub_user_size(dmu_buf_t * db_fake,uint64_t nsub)4344 dmu_buf_sub_user_size(dmu_buf_t *db_fake, uint64_t nsub)
4345 {
4346 dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
4347 ASSERT3U(db->db_caching_status, ==, DB_NO_CACHE);
4348 ASSERT3P(db->db_user, !=, NULL);
4349 ASSERT3U(atomic_load_64(&db->db_user->dbu_size), >=, nsub);
4350 atomic_sub_64(&db->db_user->dbu_size, nsub);
4351 }
4352
4353 void
dmu_buf_user_evict_wait(void)4354 dmu_buf_user_evict_wait(void)
4355 {
4356 taskq_wait(dbu_evict_taskq);
4357 }
4358
4359 blkptr_t *
dmu_buf_get_blkptr(dmu_buf_t * db)4360 dmu_buf_get_blkptr(dmu_buf_t *db)
4361 {
4362 dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
4363 return (dbi->db_blkptr);
4364 }
4365
4366 objset_t *
dmu_buf_get_objset(dmu_buf_t * db)4367 dmu_buf_get_objset(dmu_buf_t *db)
4368 {
4369 dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
4370 return (dbi->db_objset);
4371 }
4372
4373 static void
dbuf_check_blkptr(dnode_t * dn,dmu_buf_impl_t * db)4374 dbuf_check_blkptr(dnode_t *dn, dmu_buf_impl_t *db)
4375 {
4376 /* ASSERT(dmu_tx_is_syncing(tx) */
4377 ASSERT(MUTEX_HELD(&db->db_mtx));
4378
4379 if (db->db_blkptr != NULL)
4380 return;
4381
4382 if (db->db_blkid == DMU_SPILL_BLKID) {
4383 db->db_blkptr = DN_SPILL_BLKPTR(dn->dn_phys);
4384 BP_ZERO(db->db_blkptr);
4385 return;
4386 }
4387 if (db->db_level == dn->dn_phys->dn_nlevels-1) {
4388 /*
4389 * This buffer was allocated at a time when there was
4390 * no available blkptrs from the dnode, or it was
4391 * inappropriate to hook it in (i.e., nlevels mismatch).
4392 */
4393 ASSERT(db->db_blkid < dn->dn_phys->dn_nblkptr);
4394 ASSERT0P(db->db_parent);
4395 db->db_parent = dn->dn_dbuf;
4396 db->db_blkptr = &dn->dn_phys->dn_blkptr[db->db_blkid];
4397 DBUF_VERIFY(db);
4398 } else {
4399 dmu_buf_impl_t *parent = db->db_parent;
4400 int epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
4401
4402 ASSERT(dn->dn_phys->dn_nlevels > 1);
4403 if (parent == NULL) {
4404 mutex_exit(&db->db_mtx);
4405 rw_enter(&dn->dn_struct_rwlock, RW_READER);
4406 parent = dbuf_hold_level(dn, db->db_level + 1,
4407 db->db_blkid >> epbs, db);
4408 rw_exit(&dn->dn_struct_rwlock);
4409 mutex_enter(&db->db_mtx);
4410 db->db_parent = parent;
4411 }
4412 db->db_blkptr = (blkptr_t *)parent->db.db_data +
4413 (db->db_blkid & ((1ULL << epbs) - 1));
4414 DBUF_VERIFY(db);
4415 }
4416 }
4417
4418 static void
dbuf_sync_bonus(dbuf_dirty_record_t * dr,dmu_tx_t * tx)4419 dbuf_sync_bonus(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
4420 {
4421 dmu_buf_impl_t *db = dr->dr_dbuf;
4422 void *data = dr->dt.dl.dr_data;
4423
4424 ASSERT0(db->db_level);
4425 ASSERT(MUTEX_HELD(&db->db_mtx));
4426 ASSERT(db->db_blkid == DMU_BONUS_BLKID);
4427 ASSERT(data != NULL);
4428
4429 dnode_t *dn = dr->dr_dnode;
4430 ASSERT3U(DN_MAX_BONUS_LEN(dn->dn_phys), <=,
4431 DN_SLOTS_TO_BONUSLEN(dn->dn_phys->dn_extra_slots + 1));
4432 memcpy(DN_BONUS(dn->dn_phys), data, DN_MAX_BONUS_LEN(dn->dn_phys));
4433
4434 dbuf_sync_leaf_verify_bonus_dnode(dr);
4435
4436 dbuf_undirty_bonus(dr);
4437 dbuf_rele_and_unlock(db, (void *)(uintptr_t)tx->tx_txg, B_FALSE);
4438 }
4439
4440 /*
4441 * When syncing out a blocks of dnodes, adjust the block to deal with
4442 * encryption. Normally, we make sure the block is decrypted before writing
4443 * it. If we have crypt params, then we are writing a raw (encrypted) block,
4444 * from a raw receive. In this case, set the ARC buf's crypt params so
4445 * that the BP will be filled with the correct byteorder, salt, iv, and mac.
4446 */
4447 static void
dbuf_prepare_encrypted_dnode_leaf(dbuf_dirty_record_t * dr)4448 dbuf_prepare_encrypted_dnode_leaf(dbuf_dirty_record_t *dr)
4449 {
4450 int err;
4451 dmu_buf_impl_t *db = dr->dr_dbuf;
4452
4453 ASSERT(MUTEX_HELD(&db->db_mtx));
4454 ASSERT3U(db->db.db_object, ==, DMU_META_DNODE_OBJECT);
4455 ASSERT0(db->db_level);
4456
4457 if (!db->db_objset->os_raw_receive && arc_is_encrypted(db->db_buf)) {
4458 zbookmark_phys_t zb;
4459
4460 /*
4461 * Unfortunately, there is currently no mechanism for
4462 * syncing context to handle decryption errors. An error
4463 * here is only possible if an attacker maliciously
4464 * changed a dnode block and updated the associated
4465 * checksums going up the block tree.
4466 */
4467 SET_BOOKMARK(&zb, dmu_objset_id(db->db_objset),
4468 db->db.db_object, db->db_level, db->db_blkid);
4469 err = arc_untransform(db->db_buf, db->db_objset->os_spa,
4470 &zb, B_TRUE);
4471 if (err)
4472 panic("Invalid dnode block MAC");
4473 } else if (dr->dt.dl.dr_has_raw_params) {
4474 (void) arc_release(dr->dt.dl.dr_data, db);
4475 arc_convert_to_raw(dr->dt.dl.dr_data,
4476 dmu_objset_id(db->db_objset),
4477 dr->dt.dl.dr_byteorder, DMU_OT_DNODE,
4478 dr->dt.dl.dr_salt, dr->dt.dl.dr_iv, dr->dt.dl.dr_mac);
4479 }
4480 }
4481
4482 /*
4483 * dbuf_sync_indirect() is called recursively from dbuf_sync_list() so it
4484 * is critical the we not allow the compiler to inline this function in to
4485 * dbuf_sync_list() thereby drastically bloating the stack usage.
4486 */
4487 noinline static void
dbuf_sync_indirect(dbuf_dirty_record_t * dr,dmu_tx_t * tx)4488 dbuf_sync_indirect(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
4489 {
4490 dmu_buf_impl_t *db = dr->dr_dbuf;
4491 dnode_t *dn = dr->dr_dnode;
4492
4493 ASSERT(dmu_tx_is_syncing(tx));
4494
4495 dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
4496
4497 mutex_enter(&db->db_mtx);
4498
4499 ASSERT(db->db_level > 0);
4500 DBUF_VERIFY(db);
4501
4502 /* Read the block if it hasn't been read yet. */
4503 if (db->db_buf == NULL) {
4504 mutex_exit(&db->db_mtx);
4505 (void) dbuf_read(db, NULL, DB_RF_MUST_SUCCEED);
4506 mutex_enter(&db->db_mtx);
4507 }
4508 ASSERT3U(db->db_state, ==, DB_CACHED);
4509 ASSERT(db->db_buf != NULL);
4510
4511 /* Indirect block size must match what the dnode thinks it is. */
4512 ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
4513 dbuf_check_blkptr(dn, db);
4514
4515 /* Provide the pending dirty record to child dbufs */
4516 db->db_data_pending = dr;
4517
4518 mutex_exit(&db->db_mtx);
4519
4520 dbuf_write(dr, db->db_buf, tx);
4521
4522 zio_t *zio = dr->dr_zio;
4523 mutex_enter(&dr->dt.di.dr_mtx);
4524 dbuf_sync_list(&dr->dt.di.dr_children, db->db_level - 1, tx);
4525 ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
4526 mutex_exit(&dr->dt.di.dr_mtx);
4527 zio_nowait(zio);
4528 }
4529
4530 /*
4531 * Verify that the size of the data in our bonus buffer does not exceed
4532 * its recorded size.
4533 *
4534 * The purpose of this verification is to catch any cases in development
4535 * where the size of a phys structure (i.e space_map_phys_t) grows and,
4536 * due to incorrect feature management, older pools expect to read more
4537 * data even though they didn't actually write it to begin with.
4538 *
4539 * For a example, this would catch an error in the feature logic where we
4540 * open an older pool and we expect to write the space map histogram of
4541 * a space map with size SPACE_MAP_SIZE_V0.
4542 */
4543 static void
dbuf_sync_leaf_verify_bonus_dnode(dbuf_dirty_record_t * dr)4544 dbuf_sync_leaf_verify_bonus_dnode(dbuf_dirty_record_t *dr)
4545 {
4546 #ifdef ZFS_DEBUG
4547 dnode_t *dn = dr->dr_dnode;
4548
4549 /*
4550 * Encrypted bonus buffers can have data past their bonuslen.
4551 * Skip the verification of these blocks.
4552 */
4553 if (DMU_OT_IS_ENCRYPTED(dn->dn_bonustype))
4554 return;
4555
4556 uint16_t bonuslen = dn->dn_phys->dn_bonuslen;
4557 uint16_t maxbonuslen = DN_SLOTS_TO_BONUSLEN(dn->dn_num_slots);
4558 ASSERT3U(bonuslen, <=, maxbonuslen);
4559
4560 arc_buf_t *datap = dr->dt.dl.dr_data;
4561 char *datap_end = ((char *)datap) + bonuslen;
4562 char *datap_max = ((char *)datap) + maxbonuslen;
4563
4564 /* ensure that everything is zero after our data */
4565 for (; datap_end < datap_max; datap_end++)
4566 ASSERT0(*datap_end);
4567 #endif
4568 }
4569
4570 static blkptr_t *
dbuf_lightweight_bp(dbuf_dirty_record_t * dr)4571 dbuf_lightweight_bp(dbuf_dirty_record_t *dr)
4572 {
4573 /* This must be a lightweight dirty record. */
4574 ASSERT0P(dr->dr_dbuf);
4575 dnode_t *dn = dr->dr_dnode;
4576
4577 if (dn->dn_phys->dn_nlevels == 1) {
4578 VERIFY3U(dr->dt.dll.dr_blkid, <, dn->dn_phys->dn_nblkptr);
4579 return (&dn->dn_phys->dn_blkptr[dr->dt.dll.dr_blkid]);
4580 } else {
4581 dmu_buf_impl_t *parent_db = dr->dr_parent->dr_dbuf;
4582 int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
4583 VERIFY3U(parent_db->db_level, ==, 1);
4584 VERIFY3P(DB_DNODE(parent_db), ==, dn);
4585 VERIFY3U(dr->dt.dll.dr_blkid >> epbs, ==, parent_db->db_blkid);
4586 blkptr_t *bp = parent_db->db.db_data;
4587 return (&bp[dr->dt.dll.dr_blkid & ((1 << epbs) - 1)]);
4588 }
4589 }
4590
4591 static void
dbuf_lightweight_ready(zio_t * zio)4592 dbuf_lightweight_ready(zio_t *zio)
4593 {
4594 dbuf_dirty_record_t *dr = zio->io_private;
4595 blkptr_t *bp = zio->io_bp;
4596
4597 if (zio->io_error != 0)
4598 return;
4599
4600 dnode_t *dn = dr->dr_dnode;
4601
4602 blkptr_t *bp_orig = dbuf_lightweight_bp(dr);
4603 spa_t *spa = dmu_objset_spa(dn->dn_objset);
4604 int64_t delta = bp_get_dsize_sync(spa, bp) -
4605 bp_get_dsize_sync(spa, bp_orig);
4606 dnode_diduse_space(dn, delta);
4607
4608 uint64_t blkid = dr->dt.dll.dr_blkid;
4609 mutex_enter(&dn->dn_mtx);
4610 if (blkid > dn->dn_phys->dn_maxblkid) {
4611 ASSERT0(dn->dn_objset->os_raw_receive);
4612 dn->dn_phys->dn_maxblkid = blkid;
4613 }
4614 mutex_exit(&dn->dn_mtx);
4615
4616 if (!BP_IS_EMBEDDED(bp)) {
4617 uint64_t fill = BP_IS_HOLE(bp) ? 0 : 1;
4618 BP_SET_FILL(bp, fill);
4619 }
4620
4621 dmu_buf_impl_t *parent_db;
4622 EQUIV(dr->dr_parent == NULL, dn->dn_phys->dn_nlevels == 1);
4623 if (dr->dr_parent == NULL) {
4624 parent_db = dn->dn_dbuf;
4625 } else {
4626 parent_db = dr->dr_parent->dr_dbuf;
4627 }
4628 rw_enter(&parent_db->db_rwlock, RW_WRITER);
4629 *bp_orig = *bp;
4630 rw_exit(&parent_db->db_rwlock);
4631 }
4632
4633 static void
dbuf_lightweight_done(zio_t * zio)4634 dbuf_lightweight_done(zio_t *zio)
4635 {
4636 dbuf_dirty_record_t *dr = zio->io_private;
4637
4638 VERIFY0(zio->io_error);
4639
4640 objset_t *os = dr->dr_dnode->dn_objset;
4641 dmu_tx_t *tx = os->os_synctx;
4642
4643 if (zio->io_flags & (ZIO_FLAG_IO_REWRITE | ZIO_FLAG_NOPWRITE)) {
4644 ASSERT(BP_EQUAL(zio->io_bp, &zio->io_bp_orig));
4645 } else {
4646 dsl_dataset_t *ds = os->os_dsl_dataset;
4647 (void) dsl_dataset_block_kill(ds, &zio->io_bp_orig, tx, B_TRUE);
4648 dsl_dataset_block_born(ds, zio->io_bp, tx);
4649 }
4650
4651 dsl_pool_undirty_space(dmu_objset_pool(os), dr->dr_accounted,
4652 zio->io_txg);
4653
4654 abd_free(dr->dt.dll.dr_abd);
4655 kmem_free(dr, sizeof (*dr));
4656 }
4657
4658 noinline static void
dbuf_sync_lightweight(dbuf_dirty_record_t * dr,dmu_tx_t * tx)4659 dbuf_sync_lightweight(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
4660 {
4661 dnode_t *dn = dr->dr_dnode;
4662 zio_t *pio;
4663 if (dn->dn_phys->dn_nlevels == 1) {
4664 pio = dn->dn_zio;
4665 } else {
4666 pio = dr->dr_parent->dr_zio;
4667 }
4668
4669 zbookmark_phys_t zb = {
4670 .zb_objset = dmu_objset_id(dn->dn_objset),
4671 .zb_object = dn->dn_object,
4672 .zb_level = 0,
4673 .zb_blkid = dr->dt.dll.dr_blkid,
4674 };
4675
4676 /*
4677 * See comment in dbuf_write(). This is so that zio->io_bp_orig
4678 * will have the old BP in dbuf_lightweight_done().
4679 */
4680 dr->dr_bp_copy = *dbuf_lightweight_bp(dr);
4681
4682 dr->dr_zio = zio_write(pio, dmu_objset_spa(dn->dn_objset),
4683 dmu_tx_get_txg(tx), &dr->dr_bp_copy, dr->dt.dll.dr_abd,
4684 dn->dn_datablksz, abd_get_size(dr->dt.dll.dr_abd),
4685 &dr->dt.dll.dr_props, dbuf_lightweight_ready, NULL,
4686 dbuf_lightweight_done, dr, ZIO_PRIORITY_ASYNC_WRITE,
4687 ZIO_FLAG_MUSTSUCCEED | dr->dt.dll.dr_flags, &zb);
4688
4689 zio_nowait(dr->dr_zio);
4690 }
4691
4692 /*
4693 * dbuf_sync_leaf() is called recursively from dbuf_sync_list() so it is
4694 * critical the we not allow the compiler to inline this function in to
4695 * dbuf_sync_list() thereby drastically bloating the stack usage.
4696 */
4697 noinline static void
dbuf_sync_leaf(dbuf_dirty_record_t * dr,dmu_tx_t * tx)4698 dbuf_sync_leaf(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
4699 {
4700 arc_buf_t **datap = &dr->dt.dl.dr_data;
4701 dmu_buf_impl_t *db = dr->dr_dbuf;
4702 dnode_t *dn = dr->dr_dnode;
4703 objset_t *os;
4704 uint64_t txg = tx->tx_txg;
4705
4706 ASSERT(dmu_tx_is_syncing(tx));
4707
4708 dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
4709
4710 mutex_enter(&db->db_mtx);
4711 /*
4712 * To be synced, we must be dirtied. But we might have been freed
4713 * after the dirty.
4714 */
4715 if (db->db_state == DB_UNCACHED) {
4716 /* This buffer has been freed since it was dirtied */
4717 ASSERT0P(db->db.db_data);
4718 } else if (db->db_state == DB_FILL) {
4719 /* This buffer was freed and is now being re-filled */
4720 ASSERT(db->db.db_data != dr->dt.dl.dr_data);
4721 } else if (db->db_state == DB_READ) {
4722 /*
4723 * This buffer was either cloned or had a Direct I/O write
4724 * occur and has an in-flgiht read on the BP. It is safe to
4725 * issue the write here, because the read has already been
4726 * issued and the contents won't change.
4727 *
4728 * We can verify the case of both the clone and Direct I/O
4729 * write by making sure the first dirty record for the dbuf
4730 * has no ARC buffer associated with it.
4731 */
4732 dbuf_dirty_record_t *dr_head =
4733 list_head(&db->db_dirty_records);
4734 ASSERT0P(db->db_buf);
4735 ASSERT0P(db->db.db_data);
4736 ASSERT0P(dr_head->dt.dl.dr_data);
4737 ASSERT3U(dr_head->dt.dl.dr_override_state, ==, DR_OVERRIDDEN);
4738 } else {
4739 ASSERT(db->db_state == DB_CACHED || db->db_state == DB_NOFILL);
4740 }
4741 DBUF_VERIFY(db);
4742
4743 if (db->db_blkid == DMU_SPILL_BLKID) {
4744 mutex_enter(&dn->dn_mtx);
4745 if (!(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR)) {
4746 /*
4747 * In the previous transaction group, the bonus buffer
4748 * was entirely used to store the attributes for the
4749 * dnode which overrode the dn_spill field. However,
4750 * when adding more attributes to the file a spill
4751 * block was required to hold the extra attributes.
4752 *
4753 * Make sure to clear the garbage left in the dn_spill
4754 * field from the previous attributes in the bonus
4755 * buffer. Otherwise, after writing out the spill
4756 * block to the new allocated dva, it will free
4757 * the old block pointed to by the invalid dn_spill.
4758 */
4759 db->db_blkptr = NULL;
4760 }
4761 dn->dn_phys->dn_flags |= DNODE_FLAG_SPILL_BLKPTR;
4762 mutex_exit(&dn->dn_mtx);
4763 }
4764
4765 /*
4766 * If this is a bonus buffer, simply copy the bonus data into the
4767 * dnode. It will be written out when the dnode is synced (and it
4768 * will be synced, since it must have been dirty for dbuf_sync to
4769 * be called).
4770 */
4771 if (db->db_blkid == DMU_BONUS_BLKID) {
4772 ASSERT(dr->dr_dbuf == db);
4773 dbuf_sync_bonus(dr, tx);
4774 return;
4775 }
4776
4777 os = dn->dn_objset;
4778
4779 /*
4780 * This function may have dropped the db_mtx lock allowing a dmu_sync
4781 * operation to sneak in. As a result, we need to ensure that we
4782 * don't check the dr_override_state until we have returned from
4783 * dbuf_check_blkptr.
4784 */
4785 dbuf_check_blkptr(dn, db);
4786
4787 /*
4788 * If this buffer is in the middle of an immediate write, wait for the
4789 * synchronous IO to complete.
4790 *
4791 * This is also valid even with Direct I/O writes setting a dirty
4792 * records override state into DR_IN_DMU_SYNC, because all
4793 * Direct I/O writes happen in open-context.
4794 */
4795 while (dr->dt.dl.dr_override_state == DR_IN_DMU_SYNC) {
4796 ASSERT(dn->dn_object != DMU_META_DNODE_OBJECT);
4797 cv_wait(&db->db_changed, &db->db_mtx);
4798 }
4799
4800 /*
4801 * If this is a dnode block, ensure it is appropriately encrypted
4802 * or decrypted, depending on what we are writing to it this txg.
4803 */
4804 if (os->os_encrypted && dn->dn_object == DMU_META_DNODE_OBJECT)
4805 dbuf_prepare_encrypted_dnode_leaf(dr);
4806
4807 if (*datap != NULL && *datap == db->db_buf &&
4808 dn->dn_object != DMU_META_DNODE_OBJECT &&
4809 zfs_refcount_count(&db->db_holds) > 1) {
4810 /*
4811 * If this buffer is currently "in use" (i.e., there
4812 * are active holds and db_data still references it),
4813 * then make a copy before we start the write so that
4814 * any modifications from the open txg will not leak
4815 * into this write.
4816 *
4817 * NOTE: this copy does not need to be made for
4818 * objects only modified in the syncing context (e.g.
4819 * DNONE_DNODE blocks).
4820 */
4821 int psize = arc_buf_size(*datap);
4822 int lsize = arc_buf_lsize(*datap);
4823 arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
4824 enum zio_compress compress_type = arc_get_compression(*datap);
4825 uint8_t complevel = arc_get_complevel(*datap);
4826
4827 if (arc_is_encrypted(*datap)) {
4828 boolean_t byteorder;
4829 uint8_t salt[ZIO_DATA_SALT_LEN];
4830 uint8_t iv[ZIO_DATA_IV_LEN];
4831 uint8_t mac[ZIO_DATA_MAC_LEN];
4832
4833 arc_get_raw_params(*datap, &byteorder, salt, iv, mac);
4834 *datap = arc_alloc_raw_buf(os->os_spa, db,
4835 dmu_objset_id(os), byteorder, salt, iv, mac,
4836 dn->dn_type, psize, lsize, compress_type,
4837 complevel);
4838 } else if (compress_type != ZIO_COMPRESS_OFF) {
4839 ASSERT3U(type, ==, ARC_BUFC_DATA);
4840 *datap = arc_alloc_compressed_buf(os->os_spa, db,
4841 psize, lsize, compress_type, complevel);
4842 } else {
4843 *datap = arc_alloc_buf(os->os_spa, db, type, psize);
4844 }
4845 memcpy((*datap)->b_data, db->db.db_data, psize);
4846 }
4847 db->db_data_pending = dr;
4848
4849 mutex_exit(&db->db_mtx);
4850
4851 dbuf_write(dr, *datap, tx);
4852
4853 ASSERT(!list_link_active(&dr->dr_dirty_node));
4854 if (dn->dn_object == DMU_META_DNODE_OBJECT) {
4855 list_insert_tail(&dn->dn_dirty_records[txg & TXG_MASK], dr);
4856 } else {
4857 zio_nowait(dr->dr_zio);
4858 }
4859 }
4860
4861 /*
4862 * Syncs out a range of dirty records for indirect or leaf dbufs. May be
4863 * called recursively from dbuf_sync_indirect().
4864 */
4865 void
dbuf_sync_list(list_t * list,int level,dmu_tx_t * tx)4866 dbuf_sync_list(list_t *list, int level, dmu_tx_t *tx)
4867 {
4868 dbuf_dirty_record_t *dr;
4869
4870 while ((dr = list_head(list))) {
4871 if (dr->dr_zio != NULL) {
4872 /*
4873 * If we find an already initialized zio then we
4874 * are processing the meta-dnode, and we have finished.
4875 * The dbufs for all dnodes are put back on the list
4876 * during processing, so that we can zio_wait()
4877 * these IOs after initiating all child IOs.
4878 */
4879 ASSERT3U(dr->dr_dbuf->db.db_object, ==,
4880 DMU_META_DNODE_OBJECT);
4881 break;
4882 }
4883 list_remove(list, dr);
4884 if (dr->dr_dbuf == NULL) {
4885 dbuf_sync_lightweight(dr, tx);
4886 } else {
4887 if (dr->dr_dbuf->db_blkid != DMU_BONUS_BLKID &&
4888 dr->dr_dbuf->db_blkid != DMU_SPILL_BLKID) {
4889 VERIFY3U(dr->dr_dbuf->db_level, ==, level);
4890 }
4891 if (dr->dr_dbuf->db_level > 0)
4892 dbuf_sync_indirect(dr, tx);
4893 else
4894 dbuf_sync_leaf(dr, tx);
4895 }
4896 }
4897 }
4898
4899 static void
dbuf_write_ready(zio_t * zio,arc_buf_t * buf,void * vdb)4900 dbuf_write_ready(zio_t *zio, arc_buf_t *buf, void *vdb)
4901 {
4902 (void) buf;
4903 dmu_buf_impl_t *db = vdb;
4904 dnode_t *dn;
4905 blkptr_t *bp = zio->io_bp;
4906 blkptr_t *bp_orig = &zio->io_bp_orig;
4907 spa_t *spa = zio->io_spa;
4908 int64_t delta;
4909 uint64_t fill = 0;
4910 int i;
4911
4912 ASSERT3P(db->db_blkptr, !=, NULL);
4913 ASSERT3P(&db->db_data_pending->dr_bp_copy, ==, bp);
4914
4915 DB_DNODE_ENTER(db);
4916 dn = DB_DNODE(db);
4917 delta = bp_get_dsize_sync(spa, bp) - bp_get_dsize_sync(spa, bp_orig);
4918 dnode_diduse_space(dn, delta - zio->io_prev_space_delta);
4919 zio->io_prev_space_delta = delta;
4920
4921 if (BP_GET_BIRTH(bp) != 0) {
4922 ASSERT((db->db_blkid != DMU_SPILL_BLKID &&
4923 BP_GET_TYPE(bp) == dn->dn_type) ||
4924 (db->db_blkid == DMU_SPILL_BLKID &&
4925 BP_GET_TYPE(bp) == dn->dn_bonustype) ||
4926 BP_IS_EMBEDDED(bp));
4927 ASSERT(BP_GET_LEVEL(bp) == db->db_level);
4928 }
4929
4930 mutex_enter(&db->db_mtx);
4931
4932 #ifdef ZFS_DEBUG
4933 if (db->db_blkid == DMU_SPILL_BLKID) {
4934 ASSERT(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR);
4935 ASSERT(!(BP_IS_HOLE(bp)) &&
4936 db->db_blkptr == DN_SPILL_BLKPTR(dn->dn_phys));
4937 }
4938 #endif
4939
4940 if (db->db_level == 0) {
4941 mutex_enter(&dn->dn_mtx);
4942 if (db->db_blkid > dn->dn_phys->dn_maxblkid &&
4943 db->db_blkid != DMU_SPILL_BLKID) {
4944 ASSERT0(db->db_objset->os_raw_receive);
4945 dn->dn_phys->dn_maxblkid = db->db_blkid;
4946 }
4947 mutex_exit(&dn->dn_mtx);
4948
4949 if (dn->dn_type == DMU_OT_DNODE) {
4950 i = 0;
4951 while (i < db->db.db_size) {
4952 dnode_phys_t *dnp =
4953 (void *)(((char *)db->db.db_data) + i);
4954
4955 i += DNODE_MIN_SIZE;
4956 if (dnp->dn_type != DMU_OT_NONE) {
4957 fill++;
4958 for (int j = 0; j < dnp->dn_nblkptr;
4959 j++) {
4960 (void) zfs_blkptr_verify(spa,
4961 &dnp->dn_blkptr[j],
4962 BLK_CONFIG_SKIP,
4963 BLK_VERIFY_HALT);
4964 }
4965 if (dnp->dn_flags &
4966 DNODE_FLAG_SPILL_BLKPTR) {
4967 (void) zfs_blkptr_verify(spa,
4968 DN_SPILL_BLKPTR(dnp),
4969 BLK_CONFIG_SKIP,
4970 BLK_VERIFY_HALT);
4971 }
4972 i += dnp->dn_extra_slots *
4973 DNODE_MIN_SIZE;
4974 }
4975 }
4976 } else {
4977 if (BP_IS_HOLE(bp)) {
4978 fill = 0;
4979 } else {
4980 fill = 1;
4981 }
4982 }
4983 } else {
4984 blkptr_t *ibp = db->db.db_data;
4985 ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
4986 for (i = db->db.db_size >> SPA_BLKPTRSHIFT; i > 0; i--, ibp++) {
4987 if (BP_IS_HOLE(ibp))
4988 continue;
4989 (void) zfs_blkptr_verify(spa, ibp,
4990 BLK_CONFIG_SKIP, BLK_VERIFY_HALT);
4991 fill += BP_GET_FILL(ibp);
4992 }
4993 }
4994 DB_DNODE_EXIT(db);
4995
4996 if (!BP_IS_EMBEDDED(bp))
4997 BP_SET_FILL(bp, fill);
4998
4999 mutex_exit(&db->db_mtx);
5000
5001 db_lock_type_t dblt = dmu_buf_lock_parent(db, RW_WRITER, FTAG);
5002 *db->db_blkptr = *bp;
5003 dmu_buf_unlock_parent(db, dblt, FTAG);
5004 }
5005
5006 /*
5007 * This function gets called just prior to running through the compression
5008 * stage of the zio pipeline. If we're an indirect block comprised of only
5009 * holes, then we want this indirect to be compressed away to a hole. In
5010 * order to do that we must zero out any information about the holes that
5011 * this indirect points to prior to before we try to compress it.
5012 */
5013 static void
dbuf_write_children_ready(zio_t * zio,arc_buf_t * buf,void * vdb)5014 dbuf_write_children_ready(zio_t *zio, arc_buf_t *buf, void *vdb)
5015 {
5016 (void) zio, (void) buf;
5017 dmu_buf_impl_t *db = vdb;
5018 blkptr_t *bp;
5019 unsigned int epbs, i;
5020
5021 ASSERT3U(db->db_level, >, 0);
5022 DB_DNODE_ENTER(db);
5023 epbs = DB_DNODE(db)->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
5024 DB_DNODE_EXIT(db);
5025 ASSERT3U(epbs, <, 31);
5026
5027 /* Determine if all our children are holes */
5028 for (i = 0, bp = db->db.db_data; i < 1ULL << epbs; i++, bp++) {
5029 if (!BP_IS_HOLE(bp))
5030 break;
5031 }
5032
5033 /*
5034 * If all the children are holes, then zero them all out so that
5035 * we may get compressed away.
5036 */
5037 if (i == 1ULL << epbs) {
5038 /*
5039 * We only found holes. Grab the rwlock to prevent
5040 * anybody from reading the blocks we're about to
5041 * zero out.
5042 */
5043 rw_enter(&db->db_rwlock, RW_WRITER);
5044 memset(db->db.db_data, 0, db->db.db_size);
5045 rw_exit(&db->db_rwlock);
5046 }
5047 }
5048
5049 static void
dbuf_write_done(zio_t * zio,arc_buf_t * buf,void * vdb)5050 dbuf_write_done(zio_t *zio, arc_buf_t *buf, void *vdb)
5051 {
5052 (void) buf;
5053 dmu_buf_impl_t *db = vdb;
5054 blkptr_t *bp_orig = &zio->io_bp_orig;
5055 blkptr_t *bp = db->db_blkptr;
5056 objset_t *os = db->db_objset;
5057 dmu_tx_t *tx = os->os_synctx;
5058
5059 ASSERT0(zio->io_error);
5060 ASSERT(db->db_blkptr == bp);
5061
5062 /*
5063 * For nopwrites and rewrites we ensure that the bp matches our
5064 * original and bypass all the accounting.
5065 */
5066 if (zio->io_flags & (ZIO_FLAG_IO_REWRITE | ZIO_FLAG_NOPWRITE)) {
5067 ASSERT(BP_EQUAL(bp, bp_orig));
5068 } else {
5069 dsl_dataset_t *ds = os->os_dsl_dataset;
5070 (void) dsl_dataset_block_kill(ds, bp_orig, tx, B_TRUE);
5071 dsl_dataset_block_born(ds, bp, tx);
5072 }
5073
5074 mutex_enter(&db->db_mtx);
5075
5076 DBUF_VERIFY(db);
5077
5078 dbuf_dirty_record_t *dr = db->db_data_pending;
5079 dnode_t *dn = dr->dr_dnode;
5080 ASSERT(!list_link_active(&dr->dr_dirty_node));
5081 ASSERT(dr->dr_dbuf == db);
5082 ASSERT(list_next(&db->db_dirty_records, dr) == NULL);
5083 list_remove(&db->db_dirty_records, dr);
5084
5085 #ifdef ZFS_DEBUG
5086 if (db->db_blkid == DMU_SPILL_BLKID) {
5087 ASSERT(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR);
5088 ASSERT(!(BP_IS_HOLE(db->db_blkptr)) &&
5089 db->db_blkptr == DN_SPILL_BLKPTR(dn->dn_phys));
5090 }
5091 #endif
5092
5093 if (db->db_level == 0) {
5094 ASSERT(db->db_blkid != DMU_BONUS_BLKID);
5095 ASSERT(dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN);
5096
5097 /* no dr_data if this is a NO_FILL or Direct I/O */
5098 if (dr->dt.dl.dr_data != NULL &&
5099 dr->dt.dl.dr_data != db->db_buf) {
5100 ASSERT3B(dr->dt.dl.dr_brtwrite, ==, B_FALSE);
5101 ASSERT3B(dr->dt.dl.dr_diowrite, ==, B_FALSE);
5102 arc_buf_destroy(dr->dt.dl.dr_data, db);
5103 }
5104 } else {
5105 ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
5106 ASSERT3U(db->db.db_size, ==, 1 << dn->dn_phys->dn_indblkshift);
5107 if (!BP_IS_HOLE(db->db_blkptr)) {
5108 int epbs __maybe_unused = dn->dn_phys->dn_indblkshift -
5109 SPA_BLKPTRSHIFT;
5110 ASSERT3U(db->db_blkid, <=,
5111 dn->dn_phys->dn_maxblkid >> (db->db_level * epbs));
5112 ASSERT3U(BP_GET_LSIZE(db->db_blkptr), ==,
5113 db->db.db_size);
5114 }
5115 mutex_destroy(&dr->dt.di.dr_mtx);
5116 list_destroy(&dr->dt.di.dr_children);
5117 }
5118
5119 cv_broadcast(&db->db_changed);
5120 ASSERT(db->db_dirtycnt > 0);
5121 db->db_dirtycnt -= 1;
5122 db->db_data_pending = NULL;
5123 dbuf_rele_and_unlock(db, (void *)(uintptr_t)tx->tx_txg, B_FALSE);
5124
5125 dsl_pool_undirty_space(dmu_objset_pool(os), dr->dr_accounted,
5126 zio->io_txg);
5127
5128 kmem_cache_free(dbuf_dirty_kmem_cache, dr);
5129 }
5130
5131 static void
dbuf_write_nofill_ready(zio_t * zio)5132 dbuf_write_nofill_ready(zio_t *zio)
5133 {
5134 dbuf_write_ready(zio, NULL, zio->io_private);
5135 }
5136
5137 static void
dbuf_write_nofill_done(zio_t * zio)5138 dbuf_write_nofill_done(zio_t *zio)
5139 {
5140 dbuf_write_done(zio, NULL, zio->io_private);
5141 }
5142
5143 static void
dbuf_write_override_ready(zio_t * zio)5144 dbuf_write_override_ready(zio_t *zio)
5145 {
5146 dbuf_dirty_record_t *dr = zio->io_private;
5147 dmu_buf_impl_t *db = dr->dr_dbuf;
5148
5149 dbuf_write_ready(zio, NULL, db);
5150 }
5151
5152 static void
dbuf_write_override_done(zio_t * zio)5153 dbuf_write_override_done(zio_t *zio)
5154 {
5155 dbuf_dirty_record_t *dr = zio->io_private;
5156 dmu_buf_impl_t *db = dr->dr_dbuf;
5157 blkptr_t *obp = &dr->dt.dl.dr_overridden_by;
5158
5159 mutex_enter(&db->db_mtx);
5160 if (!BP_EQUAL(zio->io_bp, obp)) {
5161 if (!BP_IS_HOLE(obp))
5162 dsl_free(spa_get_dsl(zio->io_spa), zio->io_txg, obp);
5163 arc_release(dr->dt.dl.dr_data, db);
5164 }
5165 mutex_exit(&db->db_mtx);
5166
5167 dbuf_write_done(zio, NULL, db);
5168
5169 if (zio->io_abd != NULL)
5170 abd_free(zio->io_abd);
5171 }
5172
5173 typedef struct dbuf_remap_impl_callback_arg {
5174 objset_t *drica_os;
5175 uint64_t drica_blk_birth;
5176 dmu_tx_t *drica_tx;
5177 } dbuf_remap_impl_callback_arg_t;
5178
5179 static void
dbuf_remap_impl_callback(uint64_t vdev,uint64_t offset,uint64_t size,void * arg)5180 dbuf_remap_impl_callback(uint64_t vdev, uint64_t offset, uint64_t size,
5181 void *arg)
5182 {
5183 dbuf_remap_impl_callback_arg_t *drica = arg;
5184 objset_t *os = drica->drica_os;
5185 spa_t *spa = dmu_objset_spa(os);
5186 dmu_tx_t *tx = drica->drica_tx;
5187
5188 ASSERT(dsl_pool_sync_context(spa_get_dsl(spa)));
5189
5190 if (os == spa_meta_objset(spa)) {
5191 spa_vdev_indirect_mark_obsolete(spa, vdev, offset, size, tx);
5192 } else {
5193 dsl_dataset_block_remapped(dmu_objset_ds(os), vdev, offset,
5194 size, drica->drica_blk_birth, tx);
5195 }
5196 }
5197
5198 static void
dbuf_remap_impl(dnode_t * dn,blkptr_t * bp,krwlock_t * rw,dmu_tx_t * tx)5199 dbuf_remap_impl(dnode_t *dn, blkptr_t *bp, krwlock_t *rw, dmu_tx_t *tx)
5200 {
5201 blkptr_t bp_copy = *bp;
5202 spa_t *spa = dmu_objset_spa(dn->dn_objset);
5203 dbuf_remap_impl_callback_arg_t drica;
5204
5205 ASSERT(dsl_pool_sync_context(spa_get_dsl(spa)));
5206
5207 drica.drica_os = dn->dn_objset;
5208 drica.drica_blk_birth = BP_GET_BIRTH(bp);
5209 drica.drica_tx = tx;
5210 if (spa_remap_blkptr(spa, &bp_copy, dbuf_remap_impl_callback,
5211 &drica)) {
5212 /*
5213 * If the blkptr being remapped is tracked by a livelist,
5214 * then we need to make sure the livelist reflects the update.
5215 * First, cancel out the old blkptr by appending a 'FREE'
5216 * entry. Next, add an 'ALLOC' to track the new version. This
5217 * way we avoid trying to free an inaccurate blkptr at delete.
5218 * Note that embedded blkptrs are not tracked in livelists.
5219 */
5220 if (dn->dn_objset != spa_meta_objset(spa)) {
5221 dsl_dataset_t *ds = dmu_objset_ds(dn->dn_objset);
5222 if (dsl_deadlist_is_open(&ds->ds_dir->dd_livelist) &&
5223 BP_GET_BIRTH(bp) > ds->ds_dir->dd_origin_txg) {
5224 ASSERT(!BP_IS_EMBEDDED(bp));
5225 ASSERT(dsl_dir_is_clone(ds->ds_dir));
5226 ASSERT(spa_feature_is_enabled(spa,
5227 SPA_FEATURE_LIVELIST));
5228 bplist_append(&ds->ds_dir->dd_pending_frees,
5229 bp);
5230 bplist_append(&ds->ds_dir->dd_pending_allocs,
5231 &bp_copy);
5232 }
5233 }
5234
5235 /*
5236 * The db_rwlock prevents dbuf_read_impl() from
5237 * dereferencing the BP while we are changing it. To
5238 * avoid lock contention, only grab it when we are actually
5239 * changing the BP.
5240 */
5241 if (rw != NULL)
5242 rw_enter(rw, RW_WRITER);
5243 *bp = bp_copy;
5244 if (rw != NULL)
5245 rw_exit(rw);
5246 }
5247 }
5248
5249 /*
5250 * Remap any existing BP's to concrete vdevs, if possible.
5251 */
5252 static void
dbuf_remap(dnode_t * dn,dmu_buf_impl_t * db,dmu_tx_t * tx)5253 dbuf_remap(dnode_t *dn, dmu_buf_impl_t *db, dmu_tx_t *tx)
5254 {
5255 spa_t *spa = dmu_objset_spa(db->db_objset);
5256 ASSERT(dsl_pool_sync_context(spa_get_dsl(spa)));
5257
5258 if (!spa_feature_is_active(spa, SPA_FEATURE_DEVICE_REMOVAL))
5259 return;
5260
5261 if (db->db_level > 0) {
5262 blkptr_t *bp = db->db.db_data;
5263 for (int i = 0; i < db->db.db_size >> SPA_BLKPTRSHIFT; i++) {
5264 dbuf_remap_impl(dn, &bp[i], &db->db_rwlock, tx);
5265 }
5266 } else if (db->db.db_object == DMU_META_DNODE_OBJECT) {
5267 dnode_phys_t *dnp = db->db.db_data;
5268 ASSERT3U(dn->dn_type, ==, DMU_OT_DNODE);
5269 for (int i = 0; i < db->db.db_size >> DNODE_SHIFT;
5270 i += dnp[i].dn_extra_slots + 1) {
5271 for (int j = 0; j < dnp[i].dn_nblkptr; j++) {
5272 krwlock_t *lock = (dn->dn_dbuf == NULL ? NULL :
5273 &dn->dn_dbuf->db_rwlock);
5274 dbuf_remap_impl(dn, &dnp[i].dn_blkptr[j], lock,
5275 tx);
5276 }
5277 }
5278 }
5279 }
5280
5281
5282 /*
5283 * Populate dr->dr_zio with a zio to commit a dirty buffer to disk.
5284 * Caller is responsible for issuing the zio_[no]wait(dr->dr_zio).
5285 */
5286 static void
dbuf_write(dbuf_dirty_record_t * dr,arc_buf_t * data,dmu_tx_t * tx)5287 dbuf_write(dbuf_dirty_record_t *dr, arc_buf_t *data, dmu_tx_t *tx)
5288 {
5289 dmu_buf_impl_t *db = dr->dr_dbuf;
5290 dnode_t *dn = dr->dr_dnode;
5291 objset_t *os;
5292 dmu_buf_impl_t *parent = db->db_parent;
5293 uint64_t txg = tx->tx_txg;
5294 zbookmark_phys_t zb;
5295 zio_prop_t zp;
5296 zio_t *pio; /* parent I/O */
5297 int wp_flag = 0;
5298
5299 ASSERT(dmu_tx_is_syncing(tx));
5300
5301 os = dn->dn_objset;
5302
5303 if (db->db_level > 0 || dn->dn_type == DMU_OT_DNODE) {
5304 /*
5305 * Private object buffers are released here rather than in
5306 * dbuf_dirty() since they are only modified in the syncing
5307 * context and we don't want the overhead of making multiple
5308 * copies of the data.
5309 */
5310 if (BP_IS_HOLE(db->db_blkptr))
5311 arc_buf_thaw(data);
5312 else
5313 dbuf_release_bp(db);
5314 dbuf_remap(dn, db, tx);
5315 }
5316
5317 if (parent != dn->dn_dbuf) {
5318 /* Our parent is an indirect block. */
5319 /* We have a dirty parent that has been scheduled for write. */
5320 ASSERT(parent && parent->db_data_pending);
5321 /* Our parent's buffer is one level closer to the dnode. */
5322 ASSERT(db->db_level == parent->db_level-1);
5323 /*
5324 * We're about to modify our parent's db_data by modifying
5325 * our block pointer, so the parent must be released.
5326 */
5327 ASSERT(arc_released(parent->db_buf));
5328 pio = parent->db_data_pending->dr_zio;
5329 } else {
5330 /* Our parent is the dnode itself. */
5331 ASSERT((db->db_level == dn->dn_phys->dn_nlevels-1 &&
5332 db->db_blkid != DMU_SPILL_BLKID) ||
5333 (db->db_blkid == DMU_SPILL_BLKID && db->db_level == 0));
5334 if (db->db_blkid != DMU_SPILL_BLKID)
5335 ASSERT3P(db->db_blkptr, ==,
5336 &dn->dn_phys->dn_blkptr[db->db_blkid]);
5337 pio = dn->dn_zio;
5338 }
5339
5340 ASSERT(db->db_level == 0 || data == db->db_buf);
5341 ASSERT3U(BP_GET_BIRTH(db->db_blkptr), <=, txg);
5342 ASSERT(pio);
5343
5344 SET_BOOKMARK(&zb, os->os_dsl_dataset ?
5345 os->os_dsl_dataset->ds_object : DMU_META_OBJSET,
5346 db->db.db_object, db->db_level, db->db_blkid);
5347
5348 if (db->db_blkid == DMU_SPILL_BLKID)
5349 wp_flag = WP_SPILL;
5350 wp_flag |= (data == NULL) ? WP_NOFILL : 0;
5351
5352 dmu_write_policy(os, dn, db->db_level, wp_flag, &zp);
5353
5354 /*
5355 * Set rewrite properties for zfs_rewrite() operations.
5356 */
5357 if (db->db_level == 0 && dr->dt.dl.dr_rewrite) {
5358 zp.zp_rewrite = B_TRUE;
5359
5360 /*
5361 * Mark physical rewrite feature for activation.
5362 * This will be activated automatically during dataset sync.
5363 */
5364 dsl_dataset_t *ds = os->os_dsl_dataset;
5365 if (!dsl_dataset_feature_is_active(ds,
5366 SPA_FEATURE_PHYSICAL_REWRITE)) {
5367 ds->ds_feature_activation[
5368 SPA_FEATURE_PHYSICAL_REWRITE] = (void *)B_TRUE;
5369 }
5370 }
5371
5372 /*
5373 * We copy the blkptr now (rather than when we instantiate the dirty
5374 * record), because its value can change between open context and
5375 * syncing context. We do not need to hold dn_struct_rwlock to read
5376 * db_blkptr because we are in syncing context.
5377 */
5378 dr->dr_bp_copy = *db->db_blkptr;
5379
5380 if (db->db_level == 0 &&
5381 dr->dt.dl.dr_override_state == DR_OVERRIDDEN) {
5382 /*
5383 * The BP for this block has been provided by open context
5384 * (by dmu_sync(), dmu_write_direct(),
5385 * or dmu_buf_write_embedded()).
5386 */
5387 abd_t *contents = (data != NULL) ?
5388 abd_get_from_buf(data->b_data, arc_buf_size(data)) : NULL;
5389
5390 dr->dr_zio = zio_write(pio, os->os_spa, txg, &dr->dr_bp_copy,
5391 contents, db->db.db_size, db->db.db_size, &zp,
5392 dbuf_write_override_ready, NULL,
5393 dbuf_write_override_done,
5394 dr, ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
5395 mutex_enter(&db->db_mtx);
5396 dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
5397 zio_write_override(dr->dr_zio, &dr->dt.dl.dr_overridden_by,
5398 dr->dt.dl.dr_copies, dr->dt.dl.dr_gang_copies,
5399 dr->dt.dl.dr_nopwrite, dr->dt.dl.dr_brtwrite);
5400 mutex_exit(&db->db_mtx);
5401 } else if (data == NULL) {
5402 ASSERT(zp.zp_checksum == ZIO_CHECKSUM_OFF ||
5403 zp.zp_checksum == ZIO_CHECKSUM_NOPARITY);
5404 dr->dr_zio = zio_write(pio, os->os_spa, txg,
5405 &dr->dr_bp_copy, NULL, db->db.db_size, db->db.db_size, &zp,
5406 dbuf_write_nofill_ready, NULL,
5407 dbuf_write_nofill_done, db,
5408 ZIO_PRIORITY_ASYNC_WRITE,
5409 ZIO_FLAG_MUSTSUCCEED | ZIO_FLAG_NODATA, &zb);
5410 } else {
5411 ASSERT(arc_released(data));
5412
5413 /*
5414 * For indirect blocks, we want to setup the children
5415 * ready callback so that we can properly handle an indirect
5416 * block that only contains holes.
5417 */
5418 arc_write_done_func_t *children_ready_cb = NULL;
5419 if (db->db_level != 0)
5420 children_ready_cb = dbuf_write_children_ready;
5421
5422 dr->dr_zio = arc_write(pio, os->os_spa, txg,
5423 &dr->dr_bp_copy, data, !DBUF_IS_CACHEABLE(db),
5424 dbuf_is_l2cacheable(db, NULL), &zp, dbuf_write_ready,
5425 children_ready_cb, dbuf_write_done, db,
5426 ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
5427 }
5428 }
5429
5430 EXPORT_SYMBOL(dbuf_find);
5431 EXPORT_SYMBOL(dbuf_is_metadata);
5432 EXPORT_SYMBOL(dbuf_destroy);
5433 EXPORT_SYMBOL(dbuf_whichblock);
5434 EXPORT_SYMBOL(dbuf_read);
5435 EXPORT_SYMBOL(dbuf_unoverride);
5436 EXPORT_SYMBOL(dbuf_free_range);
5437 EXPORT_SYMBOL(dbuf_new_size);
5438 EXPORT_SYMBOL(dbuf_release_bp);
5439 EXPORT_SYMBOL(dbuf_dirty);
5440 EXPORT_SYMBOL(dmu_buf_set_crypt_params);
5441 EXPORT_SYMBOL(dmu_buf_will_dirty);
5442 EXPORT_SYMBOL(dmu_buf_will_rewrite);
5443 EXPORT_SYMBOL(dmu_buf_is_dirty);
5444 EXPORT_SYMBOL(dmu_buf_will_clone_or_dio);
5445 EXPORT_SYMBOL(dmu_buf_will_not_fill);
5446 EXPORT_SYMBOL(dmu_buf_will_fill);
5447 EXPORT_SYMBOL(dmu_buf_fill_done);
5448 EXPORT_SYMBOL(dmu_buf_rele);
5449 EXPORT_SYMBOL(dbuf_assign_arcbuf);
5450 EXPORT_SYMBOL(dbuf_prefetch);
5451 EXPORT_SYMBOL(dbuf_hold_impl);
5452 EXPORT_SYMBOL(dbuf_hold);
5453 EXPORT_SYMBOL(dbuf_hold_level);
5454 EXPORT_SYMBOL(dbuf_create_bonus);
5455 EXPORT_SYMBOL(dbuf_spill_set_blksz);
5456 EXPORT_SYMBOL(dbuf_rm_spill);
5457 EXPORT_SYMBOL(dbuf_add_ref);
5458 EXPORT_SYMBOL(dbuf_rele);
5459 EXPORT_SYMBOL(dbuf_rele_and_unlock);
5460 EXPORT_SYMBOL(dbuf_refcount);
5461 EXPORT_SYMBOL(dbuf_sync_list);
5462 EXPORT_SYMBOL(dmu_buf_set_user);
5463 EXPORT_SYMBOL(dmu_buf_set_user_ie);
5464 EXPORT_SYMBOL(dmu_buf_get_user);
5465 EXPORT_SYMBOL(dmu_buf_get_blkptr);
5466
5467 ZFS_MODULE_PARAM(zfs_dbuf_cache, dbuf_cache_, max_bytes, U64, ZMOD_RW,
5468 "Maximum size in bytes of the dbuf cache.");
5469
5470 ZFS_MODULE_PARAM(zfs_dbuf_cache, dbuf_cache_, hiwater_pct, UINT, ZMOD_RW,
5471 "Percentage over dbuf_cache_max_bytes for direct dbuf eviction.");
5472
5473 ZFS_MODULE_PARAM(zfs_dbuf_cache, dbuf_cache_, lowater_pct, UINT, ZMOD_RW,
5474 "Percentage below dbuf_cache_max_bytes when dbuf eviction stops.");
5475
5476 ZFS_MODULE_PARAM(zfs_dbuf, dbuf_, metadata_cache_max_bytes, U64, ZMOD_RW,
5477 "Maximum size in bytes of dbuf metadata cache.");
5478
5479 ZFS_MODULE_PARAM(zfs_dbuf, dbuf_, cache_shift, UINT, ZMOD_RW,
5480 "Set size of dbuf cache to log2 fraction of arc size.");
5481
5482 ZFS_MODULE_PARAM(zfs_dbuf, dbuf_, metadata_cache_shift, UINT, ZMOD_RW,
5483 "Set size of dbuf metadata cache to log2 fraction of arc size.");
5484
5485 ZFS_MODULE_PARAM(zfs_dbuf, dbuf_, mutex_cache_shift, UINT, ZMOD_RD,
5486 "Set size of dbuf cache mutex array as log2 shift.");
5487