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