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