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