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