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