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