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