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