xref: /illumos-gate/usr/src/uts/common/fs/zfs/dbuf.c (revision eb633035)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright 2011 Nexenta Systems, Inc.  All rights reserved.
24  * Copyright (c) 2012, 2018 by Delphix. All rights reserved.
25  * Copyright (c) 2013 by Saso Kiselkov. All rights reserved.
26  * Copyright (c) 2013, Joyent, Inc. All rights reserved.
27  * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
28  * Copyright (c) 2014 Integros [integros.com]
29  */
30 
31 #include <sys/zfs_context.h>
32 #include <sys/dmu.h>
33 #include <sys/dmu_send.h>
34 #include <sys/dmu_impl.h>
35 #include <sys/dbuf.h>
36 #include <sys/dmu_objset.h>
37 #include <sys/dsl_dataset.h>
38 #include <sys/dsl_dir.h>
39 #include <sys/dmu_tx.h>
40 #include <sys/spa.h>
41 #include <sys/zio.h>
42 #include <sys/dmu_zfetch.h>
43 #include <sys/sa.h>
44 #include <sys/sa_impl.h>
45 #include <sys/zfeature.h>
46 #include <sys/blkptr.h>
47 #include <sys/range_tree.h>
48 #include <sys/callb.h>
49 #include <sys/abd.h>
50 #include <sys/vdev.h>
51 #include <sys/cityhash.h>
52 #include <sys/spa_impl.h>
53 
54 static boolean_t dbuf_undirty(dmu_buf_impl_t *db, dmu_tx_t *tx);
55 static void dbuf_write(dbuf_dirty_record_t *dr, arc_buf_t *data, dmu_tx_t *tx);
56 
57 #ifndef __lint
58 extern inline void dmu_buf_init_user(dmu_buf_user_t *dbu,
59     dmu_buf_evict_func_t *evict_func_sync,
60     dmu_buf_evict_func_t *evict_func_async,
61     dmu_buf_t **clear_on_evict_dbufp);
62 #endif /* ! __lint */
63 
64 /*
65  * Global data structures and functions for the dbuf cache.
66  */
67 static kmem_cache_t *dbuf_kmem_cache;
68 static taskq_t *dbu_evict_taskq;
69 
70 static kthread_t *dbuf_cache_evict_thread;
71 static kmutex_t dbuf_evict_lock;
72 static kcondvar_t dbuf_evict_cv;
73 static boolean_t dbuf_evict_thread_exit;
74 
75 /*
76  * There are two dbuf caches; each dbuf can only be in one of them at a time.
77  *
78  * 1. Cache of metadata dbufs, to help make read-heavy administrative commands
79  *    from /sbin/zfs run faster. The "metadata cache" specifically stores dbufs
80  *    that represent the metadata that describes filesystems/snapshots/
81  *    bookmarks/properties/etc. We only evict from this cache when we export a
82  *    pool, to short-circuit as much I/O as possible for all administrative
83  *    commands that need the metadata. There is no eviction policy for this
84  *    cache, because we try to only include types in it which would occupy a
85  *    very small amount of space per object but create a large impact on the
86  *    performance of these commands. Instead, after it reaches a maximum size
87  *    (which should only happen on very small memory systems with a very large
88  *    number of filesystem objects), we stop taking new dbufs into the
89  *    metadata cache, instead putting them in the normal dbuf cache.
90  *
91  * 2. LRU cache of dbufs. The "dbuf cache" maintains a list of dbufs that
92  *    are not currently held but have been recently released. These dbufs
93  *    are not eligible for arc eviction until they are aged out of the cache.
94  *    Dbufs that are aged out of the cache will be immediately destroyed and
95  *    become eligible for arc eviction.
96  *
97  * Dbufs are added to these caches once the last hold is released. If a dbuf is
98  * later accessed and still exists in the dbuf cache, then it will be removed
99  * from the cache and later re-added to the head of the cache.
100  *
101  * If a given dbuf meets the requirements for the metadata cache, it will go
102  * there, otherwise it will be considered for the generic LRU dbuf cache. The
103  * caches and the refcounts tracking their sizes are stored in an array indexed
104  * by those caches' matching enum values (from dbuf_cached_state_t).
105  */
106 typedef struct dbuf_cache {
107 	multilist_t *cache;
108 	zfs_refcount_t size;
109 } dbuf_cache_t;
110 dbuf_cache_t dbuf_caches[DB_CACHE_MAX];
111 
112 /* Size limits for the caches */
113 uint64_t dbuf_cache_max_bytes = 0;
114 uint64_t dbuf_metadata_cache_max_bytes = 0;
115 /* Set the default sizes of the caches to log2 fraction of arc size */
116 int dbuf_cache_shift = 5;
117 int dbuf_metadata_cache_shift = 6;
118 
119 /*
120  * For diagnostic purposes, this is incremented whenever we can't add
121  * something to the metadata cache because it's full, and instead put
122  * the data in the regular dbuf cache.
123  */
124 uint64_t dbuf_metadata_cache_overflow;
125 
126 /*
127  * The LRU dbuf cache uses a three-stage eviction policy:
128  *	- A low water marker designates when the dbuf eviction thread
129  *	should stop evicting from the dbuf cache.
130  *	- When we reach the maximum size (aka mid water mark), we
131  *	signal the eviction thread to run.
132  *	- The high water mark indicates when the eviction thread
133  *	is unable to keep up with the incoming load and eviction must
134  *	happen in the context of the calling thread.
135  *
136  * The dbuf cache:
137  *                                                 (max size)
138  *                                      low water   mid water   hi water
139  * +----------------------------------------+----------+----------+
140  * |                                        |          |          |
141  * |                                        |          |          |
142  * |                                        |          |          |
143  * |                                        |          |          |
144  * +----------------------------------------+----------+----------+
145  *                                        stop        signal     evict
146  *                                      evicting     eviction   directly
147  *                                                    thread
148  *
149  * The high and low water marks indicate the operating range for the eviction
150  * thread. The low water mark is, by default, 90% of the total size of the
151  * cache and the high water mark is at 110% (both of these percentages can be
152  * changed by setting dbuf_cache_lowater_pct and dbuf_cache_hiwater_pct,
153  * respectively). The eviction thread will try to ensure that the cache remains
154  * within this range by waking up every second and checking if the cache is
155  * above the low water mark. The thread can also be woken up by callers adding
156  * elements into the cache if the cache is larger than the mid water (i.e max
157  * cache size). Once the eviction thread is woken up and eviction is required,
158  * it will continue evicting buffers until it's able to reduce the cache size
159  * to the low water mark. If the cache size continues to grow and hits the high
160  * water mark, then callers adding elements to the cache will begin to evict
161  * directly from the cache until the cache is no longer above the high water
162  * mark.
163  */
164 
165 /*
166  * The percentage above and below the maximum cache size.
167  */
168 uint_t dbuf_cache_hiwater_pct = 10;
169 uint_t dbuf_cache_lowater_pct = 10;
170 
171 /* ARGSUSED */
172 static int
173 dbuf_cons(void *vdb, void *unused, int kmflag)
174 {
175 	dmu_buf_impl_t *db = vdb;
176 	bzero(db, sizeof (dmu_buf_impl_t));
177 
178 	mutex_init(&db->db_mtx, NULL, MUTEX_DEFAULT, NULL);
179 	cv_init(&db->db_changed, NULL, CV_DEFAULT, NULL);
180 	multilist_link_init(&db->db_cache_link);
181 	zfs_refcount_create(&db->db_holds);
182 
183 	return (0);
184 }
185 
186 /* ARGSUSED */
187 static void
188 dbuf_dest(void *vdb, void *unused)
189 {
190 	dmu_buf_impl_t *db = vdb;
191 	mutex_destroy(&db->db_mtx);
192 	cv_destroy(&db->db_changed);
193 	ASSERT(!multilist_link_active(&db->db_cache_link));
194 	zfs_refcount_destroy(&db->db_holds);
195 }
196 
197 /*
198  * dbuf hash table routines
199  */
200 static dbuf_hash_table_t dbuf_hash_table;
201 
202 static uint64_t dbuf_hash_count;
203 
204 /*
205  * We use Cityhash for this. It's fast, and has good hash properties without
206  * requiring any large static buffers.
207  */
208 static uint64_t
209 dbuf_hash(void *os, uint64_t obj, uint8_t lvl, uint64_t blkid)
210 {
211 	return (cityhash4((uintptr_t)os, obj, (uint64_t)lvl, blkid));
212 }
213 
214 #define	DBUF_EQUAL(dbuf, os, obj, level, blkid)		\
215 	((dbuf)->db.db_object == (obj) &&		\
216 	(dbuf)->db_objset == (os) &&			\
217 	(dbuf)->db_level == (level) &&			\
218 	(dbuf)->db_blkid == (blkid))
219 
220 dmu_buf_impl_t *
221 dbuf_find(objset_t *os, uint64_t obj, uint8_t level, uint64_t blkid)
222 {
223 	dbuf_hash_table_t *h = &dbuf_hash_table;
224 	uint64_t hv = dbuf_hash(os, obj, level, blkid);
225 	uint64_t idx = hv & h->hash_table_mask;
226 	dmu_buf_impl_t *db;
227 
228 	mutex_enter(DBUF_HASH_MUTEX(h, idx));
229 	for (db = h->hash_table[idx]; db != NULL; db = db->db_hash_next) {
230 		if (DBUF_EQUAL(db, os, obj, level, blkid)) {
231 			mutex_enter(&db->db_mtx);
232 			if (db->db_state != DB_EVICTING) {
233 				mutex_exit(DBUF_HASH_MUTEX(h, idx));
234 				return (db);
235 			}
236 			mutex_exit(&db->db_mtx);
237 		}
238 	}
239 	mutex_exit(DBUF_HASH_MUTEX(h, idx));
240 	return (NULL);
241 }
242 
243 static dmu_buf_impl_t *
244 dbuf_find_bonus(objset_t *os, uint64_t object)
245 {
246 	dnode_t *dn;
247 	dmu_buf_impl_t *db = NULL;
248 
249 	if (dnode_hold(os, object, FTAG, &dn) == 0) {
250 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
251 		if (dn->dn_bonus != NULL) {
252 			db = dn->dn_bonus;
253 			mutex_enter(&db->db_mtx);
254 		}
255 		rw_exit(&dn->dn_struct_rwlock);
256 		dnode_rele(dn, FTAG);
257 	}
258 	return (db);
259 }
260 
261 /*
262  * Insert an entry into the hash table.  If there is already an element
263  * equal to elem in the hash table, then the already existing element
264  * will be returned and the new element will not be inserted.
265  * Otherwise returns NULL.
266  */
267 static dmu_buf_impl_t *
268 dbuf_hash_insert(dmu_buf_impl_t *db)
269 {
270 	dbuf_hash_table_t *h = &dbuf_hash_table;
271 	objset_t *os = db->db_objset;
272 	uint64_t obj = db->db.db_object;
273 	int level = db->db_level;
274 	uint64_t blkid = db->db_blkid;
275 	uint64_t hv = dbuf_hash(os, obj, level, blkid);
276 	uint64_t idx = hv & h->hash_table_mask;
277 	dmu_buf_impl_t *dbf;
278 
279 	mutex_enter(DBUF_HASH_MUTEX(h, idx));
280 	for (dbf = h->hash_table[idx]; dbf != NULL; dbf = dbf->db_hash_next) {
281 		if (DBUF_EQUAL(dbf, os, obj, level, blkid)) {
282 			mutex_enter(&dbf->db_mtx);
283 			if (dbf->db_state != DB_EVICTING) {
284 				mutex_exit(DBUF_HASH_MUTEX(h, idx));
285 				return (dbf);
286 			}
287 			mutex_exit(&dbf->db_mtx);
288 		}
289 	}
290 
291 	mutex_enter(&db->db_mtx);
292 	db->db_hash_next = h->hash_table[idx];
293 	h->hash_table[idx] = db;
294 	mutex_exit(DBUF_HASH_MUTEX(h, idx));
295 	atomic_inc_64(&dbuf_hash_count);
296 
297 	return (NULL);
298 }
299 
300 /*
301  * Remove an entry from the hash table.  It must be in the EVICTING state.
302  */
303 static void
304 dbuf_hash_remove(dmu_buf_impl_t *db)
305 {
306 	dbuf_hash_table_t *h = &dbuf_hash_table;
307 	uint64_t hv = dbuf_hash(db->db_objset, db->db.db_object,
308 	    db->db_level, db->db_blkid);
309 	uint64_t idx = hv & h->hash_table_mask;
310 	dmu_buf_impl_t *dbf, **dbp;
311 
312 	/*
313 	 * We mustn't hold db_mtx to maintain lock ordering:
314 	 * DBUF_HASH_MUTEX > db_mtx.
315 	 */
316 	ASSERT(zfs_refcount_is_zero(&db->db_holds));
317 	ASSERT(db->db_state == DB_EVICTING);
318 	ASSERT(!MUTEX_HELD(&db->db_mtx));
319 
320 	mutex_enter(DBUF_HASH_MUTEX(h, idx));
321 	dbp = &h->hash_table[idx];
322 	while ((dbf = *dbp) != db) {
323 		dbp = &dbf->db_hash_next;
324 		ASSERT(dbf != NULL);
325 	}
326 	*dbp = db->db_hash_next;
327 	db->db_hash_next = NULL;
328 	mutex_exit(DBUF_HASH_MUTEX(h, idx));
329 	atomic_dec_64(&dbuf_hash_count);
330 }
331 
332 typedef enum {
333 	DBVU_EVICTING,
334 	DBVU_NOT_EVICTING
335 } dbvu_verify_type_t;
336 
337 static void
338 dbuf_verify_user(dmu_buf_impl_t *db, dbvu_verify_type_t verify_type)
339 {
340 #ifdef ZFS_DEBUG
341 	int64_t holds;
342 
343 	if (db->db_user == NULL)
344 		return;
345 
346 	/* Only data blocks support the attachment of user data. */
347 	ASSERT(db->db_level == 0);
348 
349 	/* Clients must resolve a dbuf before attaching user data. */
350 	ASSERT(db->db.db_data != NULL);
351 	ASSERT3U(db->db_state, ==, DB_CACHED);
352 
353 	holds = zfs_refcount_count(&db->db_holds);
354 	if (verify_type == DBVU_EVICTING) {
355 		/*
356 		 * Immediate eviction occurs when holds == dirtycnt.
357 		 * For normal eviction buffers, holds is zero on
358 		 * eviction, except when dbuf_fix_old_data() calls
359 		 * dbuf_clear_data().  However, the hold count can grow
360 		 * during eviction even though db_mtx is held (see
361 		 * dmu_bonus_hold() for an example), so we can only
362 		 * test the generic invariant that holds >= dirtycnt.
363 		 */
364 		ASSERT3U(holds, >=, db->db_dirtycnt);
365 	} else {
366 		if (db->db_user_immediate_evict == TRUE)
367 			ASSERT3U(holds, >=, db->db_dirtycnt);
368 		else
369 			ASSERT3U(holds, >, 0);
370 	}
371 #endif
372 }
373 
374 static void
375 dbuf_evict_user(dmu_buf_impl_t *db)
376 {
377 	dmu_buf_user_t *dbu = db->db_user;
378 
379 	ASSERT(MUTEX_HELD(&db->db_mtx));
380 
381 	if (dbu == NULL)
382 		return;
383 
384 	dbuf_verify_user(db, DBVU_EVICTING);
385 	db->db_user = NULL;
386 
387 #ifdef ZFS_DEBUG
388 	if (dbu->dbu_clear_on_evict_dbufp != NULL)
389 		*dbu->dbu_clear_on_evict_dbufp = NULL;
390 #endif
391 
392 	/*
393 	 * There are two eviction callbacks - one that we call synchronously
394 	 * and one that we invoke via a taskq.  The async one is useful for
395 	 * avoiding lock order reversals and limiting stack depth.
396 	 *
397 	 * Note that if we have a sync callback but no async callback,
398 	 * it's likely that the sync callback will free the structure
399 	 * containing the dbu.  In that case we need to take care to not
400 	 * dereference dbu after calling the sync evict func.
401 	 */
402 	boolean_t has_async = (dbu->dbu_evict_func_async != NULL);
403 
404 	if (dbu->dbu_evict_func_sync != NULL)
405 		dbu->dbu_evict_func_sync(dbu);
406 
407 	if (has_async) {
408 		taskq_dispatch_ent(dbu_evict_taskq, dbu->dbu_evict_func_async,
409 		    dbu, 0, &dbu->dbu_tqent);
410 	}
411 }
412 
413 boolean_t
414 dbuf_is_metadata(dmu_buf_impl_t *db)
415 {
416 	if (db->db_level > 0 || db->db_blkid == DMU_SPILL_BLKID) {
417 		return (B_TRUE);
418 	} else {
419 		boolean_t is_metadata;
420 
421 		DB_DNODE_ENTER(db);
422 		is_metadata = DMU_OT_IS_METADATA(DB_DNODE(db)->dn_type);
423 		DB_DNODE_EXIT(db);
424 
425 		return (is_metadata);
426 	}
427 }
428 
429 /*
430  * This returns whether this dbuf should be stored in the metadata cache, which
431  * is based on whether it's from one of the dnode types that store data related
432  * to traversing dataset hierarchies.
433  */
434 static boolean_t
435 dbuf_include_in_metadata_cache(dmu_buf_impl_t *db)
436 {
437 	DB_DNODE_ENTER(db);
438 	dmu_object_type_t type = DB_DNODE(db)->dn_type;
439 	DB_DNODE_EXIT(db);
440 
441 	/* Check if this dbuf is one of the types we care about */
442 	if (DMU_OT_IS_METADATA_CACHED(type)) {
443 		/* If we hit this, then we set something up wrong in dmu_ot */
444 		ASSERT(DMU_OT_IS_METADATA(type));
445 
446 		/*
447 		 * Sanity check for small-memory systems: don't allocate too
448 		 * much memory for this purpose.
449 		 */
450 		if (zfs_refcount_count(
451 		    &dbuf_caches[DB_DBUF_METADATA_CACHE].size) >
452 		    dbuf_metadata_cache_max_bytes) {
453 			dbuf_metadata_cache_overflow++;
454 			DTRACE_PROBE1(dbuf__metadata__cache__overflow,
455 			    dmu_buf_impl_t *, db);
456 			return (B_FALSE);
457 		}
458 
459 		return (B_TRUE);
460 	}
461 
462 	return (B_FALSE);
463 }
464 
465 /*
466  * This function *must* return indices evenly distributed between all
467  * sublists of the multilist. This is needed due to how the dbuf eviction
468  * code is laid out; dbuf_evict_thread() assumes dbufs are evenly
469  * distributed between all sublists and uses this assumption when
470  * deciding which sublist to evict from and how much to evict from it.
471  */
472 unsigned int
473 dbuf_cache_multilist_index_func(multilist_t *ml, void *obj)
474 {
475 	dmu_buf_impl_t *db = obj;
476 
477 	/*
478 	 * The assumption here, is the hash value for a given
479 	 * dmu_buf_impl_t will remain constant throughout it's lifetime
480 	 * (i.e. it's objset, object, level and blkid fields don't change).
481 	 * Thus, we don't need to store the dbuf's sublist index
482 	 * on insertion, as this index can be recalculated on removal.
483 	 *
484 	 * Also, the low order bits of the hash value are thought to be
485 	 * distributed evenly. Otherwise, in the case that the multilist
486 	 * has a power of two number of sublists, each sublists' usage
487 	 * would not be evenly distributed.
488 	 */
489 	return (dbuf_hash(db->db_objset, db->db.db_object,
490 	    db->db_level, db->db_blkid) %
491 	    multilist_get_num_sublists(ml));
492 }
493 
494 static inline boolean_t
495 dbuf_cache_above_hiwater(void)
496 {
497 	uint64_t dbuf_cache_hiwater_bytes =
498 	    (dbuf_cache_max_bytes * dbuf_cache_hiwater_pct) / 100;
499 
500 	return (zfs_refcount_count(&dbuf_caches[DB_DBUF_CACHE].size) >
501 	    dbuf_cache_max_bytes + dbuf_cache_hiwater_bytes);
502 }
503 
504 static inline boolean_t
505 dbuf_cache_above_lowater(void)
506 {
507 	uint64_t dbuf_cache_lowater_bytes =
508 	    (dbuf_cache_max_bytes * dbuf_cache_lowater_pct) / 100;
509 
510 	return (zfs_refcount_count(&dbuf_caches[DB_DBUF_CACHE].size) >
511 	    dbuf_cache_max_bytes - dbuf_cache_lowater_bytes);
512 }
513 
514 /*
515  * Evict the oldest eligible dbuf from the dbuf cache.
516  */
517 static void
518 dbuf_evict_one(void)
519 {
520 	int idx = multilist_get_random_index(dbuf_caches[DB_DBUF_CACHE].cache);
521 	multilist_sublist_t *mls = multilist_sublist_lock(
522 	    dbuf_caches[DB_DBUF_CACHE].cache, idx);
523 
524 	ASSERT(!MUTEX_HELD(&dbuf_evict_lock));
525 
526 	dmu_buf_impl_t *db = multilist_sublist_tail(mls);
527 	while (db != NULL && mutex_tryenter(&db->db_mtx) == 0) {
528 		db = multilist_sublist_prev(mls, db);
529 	}
530 
531 	DTRACE_PROBE2(dbuf__evict__one, dmu_buf_impl_t *, db,
532 	    multilist_sublist_t *, mls);
533 
534 	if (db != NULL) {
535 		multilist_sublist_remove(mls, db);
536 		multilist_sublist_unlock(mls);
537 		(void) zfs_refcount_remove_many(
538 		    &dbuf_caches[DB_DBUF_CACHE].size,
539 		    db->db.db_size, db);
540 		ASSERT3U(db->db_caching_status, ==, DB_DBUF_CACHE);
541 		db->db_caching_status = DB_NO_CACHE;
542 		dbuf_destroy(db);
543 	} else {
544 		multilist_sublist_unlock(mls);
545 	}
546 }
547 
548 /*
549  * The dbuf evict thread is responsible for aging out dbufs from the
550  * cache. Once the cache has reached it's maximum size, dbufs are removed
551  * and destroyed. The eviction thread will continue running until the size
552  * of the dbuf cache is at or below the maximum size. Once the dbuf is aged
553  * out of the cache it is destroyed and becomes eligible for arc eviction.
554  */
555 /* ARGSUSED */
556 static void
557 dbuf_evict_thread(void *unused)
558 {
559 	callb_cpr_t cpr;
560 
561 	CALLB_CPR_INIT(&cpr, &dbuf_evict_lock, callb_generic_cpr, FTAG);
562 
563 	mutex_enter(&dbuf_evict_lock);
564 	while (!dbuf_evict_thread_exit) {
565 		while (!dbuf_cache_above_lowater() && !dbuf_evict_thread_exit) {
566 			CALLB_CPR_SAFE_BEGIN(&cpr);
567 			(void) cv_timedwait_hires(&dbuf_evict_cv,
568 			    &dbuf_evict_lock, SEC2NSEC(1), MSEC2NSEC(1), 0);
569 			CALLB_CPR_SAFE_END(&cpr, &dbuf_evict_lock);
570 		}
571 		mutex_exit(&dbuf_evict_lock);
572 
573 		/*
574 		 * Keep evicting as long as we're above the low water mark
575 		 * for the cache. We do this without holding the locks to
576 		 * minimize lock contention.
577 		 */
578 		while (dbuf_cache_above_lowater() && !dbuf_evict_thread_exit) {
579 			dbuf_evict_one();
580 		}
581 
582 		mutex_enter(&dbuf_evict_lock);
583 	}
584 
585 	dbuf_evict_thread_exit = B_FALSE;
586 	cv_broadcast(&dbuf_evict_cv);
587 	CALLB_CPR_EXIT(&cpr);	/* drops dbuf_evict_lock */
588 	thread_exit();
589 }
590 
591 /*
592  * Wake up the dbuf eviction thread if the dbuf cache is at its max size.
593  * If the dbuf cache is at its high water mark, then evict a dbuf from the
594  * dbuf cache using the callers context.
595  */
596 static void
597 dbuf_evict_notify(void)
598 {
599 	/*
600 	 * We check if we should evict without holding the dbuf_evict_lock,
601 	 * because it's OK to occasionally make the wrong decision here,
602 	 * and grabbing the lock results in massive lock contention.
603 	 */
604 	if (zfs_refcount_count(&dbuf_caches[DB_DBUF_CACHE].size) >
605 	    dbuf_cache_max_bytes) {
606 		if (dbuf_cache_above_hiwater())
607 			dbuf_evict_one();
608 		cv_signal(&dbuf_evict_cv);
609 	}
610 }
611 
612 void
613 dbuf_init(void)
614 {
615 	uint64_t hsize = 1ULL << 16;
616 	dbuf_hash_table_t *h = &dbuf_hash_table;
617 	int i;
618 
619 	/*
620 	 * The hash table is big enough to fill all of physical memory
621 	 * with an average 4K block size.  The table will take up
622 	 * totalmem*sizeof(void*)/4K (i.e. 2MB/GB with 8-byte pointers).
623 	 */
624 	while (hsize * 4096 < physmem * PAGESIZE)
625 		hsize <<= 1;
626 
627 retry:
628 	h->hash_table_mask = hsize - 1;
629 	h->hash_table = kmem_zalloc(hsize * sizeof (void *), KM_NOSLEEP);
630 	if (h->hash_table == NULL) {
631 		/* XXX - we should really return an error instead of assert */
632 		ASSERT(hsize > (1ULL << 10));
633 		hsize >>= 1;
634 		goto retry;
635 	}
636 
637 	dbuf_kmem_cache = kmem_cache_create("dmu_buf_impl_t",
638 	    sizeof (dmu_buf_impl_t),
639 	    0, dbuf_cons, dbuf_dest, NULL, NULL, NULL, 0);
640 
641 	for (i = 0; i < DBUF_MUTEXES; i++)
642 		mutex_init(&h->hash_mutexes[i], NULL, MUTEX_DEFAULT, NULL);
643 
644 	/*
645 	 * Setup the parameters for the dbuf caches. We set the sizes of the
646 	 * dbuf cache and the metadata cache to 1/32nd and 1/16th (default)
647 	 * of the size of the ARC, respectively. If the values are set in
648 	 * /etc/system and they're not greater than the size of the ARC, then
649 	 * we honor that value.
650 	 */
651 	if (dbuf_cache_max_bytes == 0 ||
652 	    dbuf_cache_max_bytes >= arc_max_bytes())  {
653 		dbuf_cache_max_bytes = arc_max_bytes() >> dbuf_cache_shift;
654 	}
655 	if (dbuf_metadata_cache_max_bytes == 0 ||
656 	    dbuf_metadata_cache_max_bytes >= arc_max_bytes()) {
657 		dbuf_metadata_cache_max_bytes =
658 		    arc_max_bytes() >> dbuf_metadata_cache_shift;
659 	}
660 
661 	/*
662 	 * All entries are queued via taskq_dispatch_ent(), so min/maxalloc
663 	 * configuration is not required.
664 	 */
665 	dbu_evict_taskq = taskq_create("dbu_evict", 1, minclsyspri, 0, 0, 0);
666 
667 	for (dbuf_cached_state_t dcs = 0; dcs < DB_CACHE_MAX; dcs++) {
668 		dbuf_caches[dcs].cache =
669 		    multilist_create(sizeof (dmu_buf_impl_t),
670 		    offsetof(dmu_buf_impl_t, db_cache_link),
671 		    dbuf_cache_multilist_index_func);
672 		zfs_refcount_create(&dbuf_caches[dcs].size);
673 	}
674 
675 	dbuf_evict_thread_exit = B_FALSE;
676 	mutex_init(&dbuf_evict_lock, NULL, MUTEX_DEFAULT, NULL);
677 	cv_init(&dbuf_evict_cv, NULL, CV_DEFAULT, NULL);
678 	dbuf_cache_evict_thread = thread_create(NULL, 0, dbuf_evict_thread,
679 	    NULL, 0, &p0, TS_RUN, minclsyspri);
680 }
681 
682 void
683 dbuf_fini(void)
684 {
685 	dbuf_hash_table_t *h = &dbuf_hash_table;
686 	int i;
687 
688 	for (i = 0; i < DBUF_MUTEXES; i++)
689 		mutex_destroy(&h->hash_mutexes[i]);
690 	kmem_free(h->hash_table, (h->hash_table_mask + 1) * sizeof (void *));
691 	kmem_cache_destroy(dbuf_kmem_cache);
692 	taskq_destroy(dbu_evict_taskq);
693 
694 	mutex_enter(&dbuf_evict_lock);
695 	dbuf_evict_thread_exit = B_TRUE;
696 	while (dbuf_evict_thread_exit) {
697 		cv_signal(&dbuf_evict_cv);
698 		cv_wait(&dbuf_evict_cv, &dbuf_evict_lock);
699 	}
700 	mutex_exit(&dbuf_evict_lock);
701 
702 	mutex_destroy(&dbuf_evict_lock);
703 	cv_destroy(&dbuf_evict_cv);
704 
705 	for (dbuf_cached_state_t dcs = 0; dcs < DB_CACHE_MAX; dcs++) {
706 		zfs_refcount_destroy(&dbuf_caches[dcs].size);
707 		multilist_destroy(dbuf_caches[dcs].cache);
708 	}
709 }
710 
711 /*
712  * Other stuff.
713  */
714 
715 #ifdef ZFS_DEBUG
716 static void
717 dbuf_verify(dmu_buf_impl_t *db)
718 {
719 	dnode_t *dn;
720 	dbuf_dirty_record_t *dr;
721 
722 	ASSERT(MUTEX_HELD(&db->db_mtx));
723 
724 	if (!(zfs_flags & ZFS_DEBUG_DBUF_VERIFY))
725 		return;
726 
727 	ASSERT(db->db_objset != NULL);
728 	DB_DNODE_ENTER(db);
729 	dn = DB_DNODE(db);
730 	if (dn == NULL) {
731 		ASSERT(db->db_parent == NULL);
732 		ASSERT(db->db_blkptr == NULL);
733 	} else {
734 		ASSERT3U(db->db.db_object, ==, dn->dn_object);
735 		ASSERT3P(db->db_objset, ==, dn->dn_objset);
736 		ASSERT3U(db->db_level, <, dn->dn_nlevels);
737 		ASSERT(db->db_blkid == DMU_BONUS_BLKID ||
738 		    db->db_blkid == DMU_SPILL_BLKID ||
739 		    !avl_is_empty(&dn->dn_dbufs));
740 	}
741 	if (db->db_blkid == DMU_BONUS_BLKID) {
742 		ASSERT(dn != NULL);
743 		ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
744 		ASSERT3U(db->db.db_offset, ==, DMU_BONUS_BLKID);
745 	} else if (db->db_blkid == DMU_SPILL_BLKID) {
746 		ASSERT(dn != NULL);
747 		ASSERT0(db->db.db_offset);
748 	} else {
749 		ASSERT3U(db->db.db_offset, ==, db->db_blkid * db->db.db_size);
750 	}
751 
752 	for (dr = db->db_data_pending; dr != NULL; dr = dr->dr_next)
753 		ASSERT(dr->dr_dbuf == db);
754 
755 	for (dr = db->db_last_dirty; dr != NULL; dr = dr->dr_next)
756 		ASSERT(dr->dr_dbuf == db);
757 
758 	/*
759 	 * We can't assert that db_size matches dn_datablksz because it
760 	 * can be momentarily different when another thread is doing
761 	 * dnode_set_blksz().
762 	 */
763 	if (db->db_level == 0 && db->db.db_object == DMU_META_DNODE_OBJECT) {
764 		dr = db->db_data_pending;
765 		/*
766 		 * It should only be modified in syncing context, so
767 		 * make sure we only have one copy of the data.
768 		 */
769 		ASSERT(dr == NULL || dr->dt.dl.dr_data == db->db_buf);
770 	}
771 
772 	/* verify db->db_blkptr */
773 	if (db->db_blkptr) {
774 		if (db->db_parent == dn->dn_dbuf) {
775 			/* db is pointed to by the dnode */
776 			/* ASSERT3U(db->db_blkid, <, dn->dn_nblkptr); */
777 			if (DMU_OBJECT_IS_SPECIAL(db->db.db_object))
778 				ASSERT(db->db_parent == NULL);
779 			else
780 				ASSERT(db->db_parent != NULL);
781 			if (db->db_blkid != DMU_SPILL_BLKID)
782 				ASSERT3P(db->db_blkptr, ==,
783 				    &dn->dn_phys->dn_blkptr[db->db_blkid]);
784 		} else {
785 			/* db is pointed to by an indirect block */
786 			int epb = db->db_parent->db.db_size >> SPA_BLKPTRSHIFT;
787 			ASSERT3U(db->db_parent->db_level, ==, db->db_level+1);
788 			ASSERT3U(db->db_parent->db.db_object, ==,
789 			    db->db.db_object);
790 			/*
791 			 * dnode_grow_indblksz() can make this fail if we don't
792 			 * have the struct_rwlock.  XXX indblksz no longer
793 			 * grows.  safe to do this now?
794 			 */
795 			if (RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
796 				ASSERT3P(db->db_blkptr, ==,
797 				    ((blkptr_t *)db->db_parent->db.db_data +
798 				    db->db_blkid % epb));
799 			}
800 		}
801 	}
802 	if ((db->db_blkptr == NULL || BP_IS_HOLE(db->db_blkptr)) &&
803 	    (db->db_buf == NULL || db->db_buf->b_data) &&
804 	    db->db.db_data && db->db_blkid != DMU_BONUS_BLKID &&
805 	    db->db_state != DB_FILL && !dn->dn_free_txg) {
806 		/*
807 		 * If the blkptr isn't set but they have nonzero data,
808 		 * it had better be dirty, otherwise we'll lose that
809 		 * data when we evict this buffer.
810 		 *
811 		 * There is an exception to this rule for indirect blocks; in
812 		 * this case, if the indirect block is a hole, we fill in a few
813 		 * fields on each of the child blocks (importantly, birth time)
814 		 * to prevent hole birth times from being lost when you
815 		 * partially fill in a hole.
816 		 */
817 		if (db->db_dirtycnt == 0) {
818 			if (db->db_level == 0) {
819 				uint64_t *buf = db->db.db_data;
820 				int i;
821 
822 				for (i = 0; i < db->db.db_size >> 3; i++) {
823 					ASSERT(buf[i] == 0);
824 				}
825 			} else {
826 				blkptr_t *bps = db->db.db_data;
827 				ASSERT3U(1 << DB_DNODE(db)->dn_indblkshift, ==,
828 				    db->db.db_size);
829 				/*
830 				 * We want to verify that all the blkptrs in the
831 				 * indirect block are holes, but we may have
832 				 * automatically set up a few fields for them.
833 				 * We iterate through each blkptr and verify
834 				 * they only have those fields set.
835 				 */
836 				for (int i = 0;
837 				    i < db->db.db_size / sizeof (blkptr_t);
838 				    i++) {
839 					blkptr_t *bp = &bps[i];
840 					ASSERT(ZIO_CHECKSUM_IS_ZERO(
841 					    &bp->blk_cksum));
842 					ASSERT(
843 					    DVA_IS_EMPTY(&bp->blk_dva[0]) &&
844 					    DVA_IS_EMPTY(&bp->blk_dva[1]) &&
845 					    DVA_IS_EMPTY(&bp->blk_dva[2]));
846 					ASSERT0(bp->blk_fill);
847 					ASSERT0(bp->blk_pad[0]);
848 					ASSERT0(bp->blk_pad[1]);
849 					ASSERT(!BP_IS_EMBEDDED(bp));
850 					ASSERT(BP_IS_HOLE(bp));
851 					ASSERT0(bp->blk_phys_birth);
852 				}
853 			}
854 		}
855 	}
856 	DB_DNODE_EXIT(db);
857 }
858 #endif
859 
860 static void
861 dbuf_clear_data(dmu_buf_impl_t *db)
862 {
863 	ASSERT(MUTEX_HELD(&db->db_mtx));
864 	dbuf_evict_user(db);
865 	ASSERT3P(db->db_buf, ==, NULL);
866 	db->db.db_data = NULL;
867 	if (db->db_state != DB_NOFILL)
868 		db->db_state = DB_UNCACHED;
869 }
870 
871 static void
872 dbuf_set_data(dmu_buf_impl_t *db, arc_buf_t *buf)
873 {
874 	ASSERT(MUTEX_HELD(&db->db_mtx));
875 	ASSERT(buf != NULL);
876 
877 	db->db_buf = buf;
878 	ASSERT(buf->b_data != NULL);
879 	db->db.db_data = buf->b_data;
880 }
881 
882 /*
883  * Loan out an arc_buf for read.  Return the loaned arc_buf.
884  */
885 arc_buf_t *
886 dbuf_loan_arcbuf(dmu_buf_impl_t *db)
887 {
888 	arc_buf_t *abuf;
889 
890 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
891 	mutex_enter(&db->db_mtx);
892 	if (arc_released(db->db_buf) || zfs_refcount_count(&db->db_holds) > 1) {
893 		int blksz = db->db.db_size;
894 		spa_t *spa = db->db_objset->os_spa;
895 
896 		mutex_exit(&db->db_mtx);
897 		abuf = arc_loan_buf(spa, B_FALSE, blksz);
898 		bcopy(db->db.db_data, abuf->b_data, blksz);
899 	} else {
900 		abuf = db->db_buf;
901 		arc_loan_inuse_buf(abuf, db);
902 		db->db_buf = NULL;
903 		dbuf_clear_data(db);
904 		mutex_exit(&db->db_mtx);
905 	}
906 	return (abuf);
907 }
908 
909 /*
910  * Calculate which level n block references the data at the level 0 offset
911  * provided.
912  */
913 uint64_t
914 dbuf_whichblock(dnode_t *dn, int64_t level, uint64_t offset)
915 {
916 	if (dn->dn_datablkshift != 0 && dn->dn_indblkshift != 0) {
917 		/*
918 		 * The level n blkid is equal to the level 0 blkid divided by
919 		 * the number of level 0s in a level n block.
920 		 *
921 		 * The level 0 blkid is offset >> datablkshift =
922 		 * offset / 2^datablkshift.
923 		 *
924 		 * The number of level 0s in a level n is the number of block
925 		 * pointers in an indirect block, raised to the power of level.
926 		 * This is 2^(indblkshift - SPA_BLKPTRSHIFT)^level =
927 		 * 2^(level*(indblkshift - SPA_BLKPTRSHIFT)).
928 		 *
929 		 * Thus, the level n blkid is: offset /
930 		 * ((2^datablkshift)*(2^(level*(indblkshift - SPA_BLKPTRSHIFT)))
931 		 * = offset / 2^(datablkshift + level *
932 		 *   (indblkshift - SPA_BLKPTRSHIFT))
933 		 * = offset >> (datablkshift + level *
934 		 *   (indblkshift - SPA_BLKPTRSHIFT))
935 		 */
936 		return (offset >> (dn->dn_datablkshift + level *
937 		    (dn->dn_indblkshift - SPA_BLKPTRSHIFT)));
938 	} else {
939 		ASSERT3U(offset, <, dn->dn_datablksz);
940 		return (0);
941 	}
942 }
943 
944 /* ARGSUSED */
945 static void
946 dbuf_read_done(zio_t *zio, const zbookmark_phys_t *zb, const blkptr_t *bp,
947     arc_buf_t *buf, void *vdb)
948 {
949 	dmu_buf_impl_t *db = vdb;
950 
951 	mutex_enter(&db->db_mtx);
952 	ASSERT3U(db->db_state, ==, DB_READ);
953 	/*
954 	 * All reads are synchronous, so we must have a hold on the dbuf
955 	 */
956 	ASSERT(zfs_refcount_count(&db->db_holds) > 0);
957 	ASSERT(db->db_buf == NULL);
958 	ASSERT(db->db.db_data == NULL);
959 	if (buf == NULL) {
960 		/* i/o error */
961 		ASSERT(zio == NULL || zio->io_error != 0);
962 		ASSERT(db->db_blkid != DMU_BONUS_BLKID);
963 		ASSERT3P(db->db_buf, ==, NULL);
964 		db->db_state = DB_UNCACHED;
965 	} else if (db->db_level == 0 && db->db_freed_in_flight) {
966 		/* we were freed in flight; disregard any error */
967 		ASSERT(zio == NULL || zio->io_error == 0);
968 		if (buf == NULL) {
969 			buf = arc_alloc_buf(db->db_objset->os_spa,
970 			    db, DBUF_GET_BUFC_TYPE(db), db->db.db_size);
971 		}
972 		arc_release(buf, db);
973 		bzero(buf->b_data, db->db.db_size);
974 		arc_buf_freeze(buf);
975 		db->db_freed_in_flight = FALSE;
976 		dbuf_set_data(db, buf);
977 		db->db_state = DB_CACHED;
978 	} else if (buf != NULL) {
979 		/* success */
980 		ASSERT(zio == NULL || zio->io_error == 0);
981 		dbuf_set_data(db, buf);
982 		db->db_state = DB_CACHED;
983 	}
984 	cv_broadcast(&db->db_changed);
985 	dbuf_rele_and_unlock(db, NULL, B_FALSE);
986 }
987 
988 
989 /*
990  * This function ensures that, when doing a decrypting read of a block,
991  * we make sure we have decrypted the dnode associated with it. We must do
992  * this so that we ensure we are fully authenticating the checksum-of-MACs
993  * tree from the root of the objset down to this block. Indirect blocks are
994  * always verified against their secure checksum-of-MACs assuming that the
995  * dnode containing them is correct. Now that we are doing a decrypting read,
996  * we can be sure that the key is loaded and verify that assumption. This is
997  * especially important considering that we always read encrypted dnode
998  * blocks as raw data (without verifying their MACs) to start, and
999  * decrypt / authenticate them when we need to read an encrypted bonus buffer.
1000  */
1001 static int
1002 dbuf_read_verify_dnode_crypt(dmu_buf_impl_t *db, uint32_t flags)
1003 {
1004 	int err = 0;
1005 	objset_t *os = db->db_objset;
1006 	arc_buf_t *dnode_abuf;
1007 	dnode_t *dn;
1008 	zbookmark_phys_t zb;
1009 
1010 	ASSERT(MUTEX_HELD(&db->db_mtx));
1011 
1012 	if (!os->os_encrypted || os->os_raw_receive ||
1013 	    (flags & DB_RF_NO_DECRYPT) != 0)
1014 		return (0);
1015 
1016 	DB_DNODE_ENTER(db);
1017 	dn = DB_DNODE(db);
1018 	dnode_abuf = (dn->dn_dbuf != NULL) ? dn->dn_dbuf->db_buf : NULL;
1019 
1020 	if (dnode_abuf == NULL || !arc_is_encrypted(dnode_abuf)) {
1021 		DB_DNODE_EXIT(db);
1022 		return (0);
1023 	}
1024 
1025 	SET_BOOKMARK(&zb, dmu_objset_id(os),
1026 	    DMU_META_DNODE_OBJECT, 0, dn->dn_dbuf->db_blkid);
1027 	err = arc_untransform(dnode_abuf, os->os_spa, &zb, B_TRUE);
1028 
1029 	/*
1030 	 * An error code of EACCES tells us that the key is still not
1031 	 * available. This is ok if we are only reading authenticated
1032 	 * (and therefore non-encrypted) blocks.
1033 	 */
1034 	if (err == EACCES && ((db->db_blkid != DMU_BONUS_BLKID &&
1035 	    !DMU_OT_IS_ENCRYPTED(dn->dn_type)) ||
1036 	    (db->db_blkid == DMU_BONUS_BLKID &&
1037 	    !DMU_OT_IS_ENCRYPTED(dn->dn_bonustype))))
1038 		err = 0;
1039 
1040 
1041 	DB_DNODE_EXIT(db);
1042 
1043 	return (err);
1044 }
1045 
1046 static int
1047 dbuf_read_impl(dmu_buf_impl_t *db, zio_t *zio, uint32_t flags)
1048 {
1049 	dnode_t *dn;
1050 	zbookmark_phys_t zb;
1051 	arc_flags_t aflags = ARC_FLAG_NOWAIT;
1052 	int err, zio_flags = 0;
1053 
1054 	DB_DNODE_ENTER(db);
1055 	dn = DB_DNODE(db);
1056 	ASSERT(!zfs_refcount_is_zero(&db->db_holds));
1057 	/* We need the struct_rwlock to prevent db_blkptr from changing. */
1058 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
1059 	ASSERT(MUTEX_HELD(&db->db_mtx));
1060 	ASSERT(db->db_state == DB_UNCACHED);
1061 	ASSERT(db->db_buf == NULL);
1062 
1063 	if (db->db_blkid == DMU_BONUS_BLKID) {
1064 		/*
1065 		 * The bonus length stored in the dnode may be less than
1066 		 * the maximum available space in the bonus buffer.
1067 		 */
1068 		int bonuslen = MIN(dn->dn_bonuslen, dn->dn_phys->dn_bonuslen);
1069 		int max_bonuslen = DN_SLOTS_TO_BONUSLEN(dn->dn_num_slots);
1070 
1071 		/* if the underlying dnode block is encrypted, decrypt it */
1072 		err = dbuf_read_verify_dnode_crypt(db, flags);
1073 		if (err != 0) {
1074 			DB_DNODE_EXIT(db);
1075 			mutex_exit(&db->db_mtx);
1076 			return (err);
1077 		}
1078 
1079 		ASSERT3U(bonuslen, <=, db->db.db_size);
1080 		db->db.db_data = zio_buf_alloc(max_bonuslen);
1081 		arc_space_consume(max_bonuslen, ARC_SPACE_BONUS);
1082 		if (bonuslen < max_bonuslen)
1083 			bzero(db->db.db_data, max_bonuslen);
1084 		if (bonuslen)
1085 			bcopy(DN_BONUS(dn->dn_phys), db->db.db_data, bonuslen);
1086 		DB_DNODE_EXIT(db);
1087 		db->db_state = DB_CACHED;
1088 		mutex_exit(&db->db_mtx);
1089 		return (0);
1090 	}
1091 
1092 	/*
1093 	 * Recheck BP_IS_HOLE() after dnode_block_freed() in case dnode_sync()
1094 	 * processes the delete record and clears the bp while we are waiting
1095 	 * for the dn_mtx (resulting in a "no" from block_freed).
1096 	 */
1097 	if (db->db_blkptr == NULL || BP_IS_HOLE(db->db_blkptr) ||
1098 	    (db->db_level == 0 && (dnode_block_freed(dn, db->db_blkid) ||
1099 	    BP_IS_HOLE(db->db_blkptr)))) {
1100 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1101 
1102 		dbuf_set_data(db, arc_alloc_buf(db->db_objset->os_spa, db, type,
1103 		    db->db.db_size));
1104 		bzero(db->db.db_data, db->db.db_size);
1105 
1106 		if (db->db_blkptr != NULL && db->db_level > 0 &&
1107 		    BP_IS_HOLE(db->db_blkptr) &&
1108 		    db->db_blkptr->blk_birth != 0) {
1109 			blkptr_t *bps = db->db.db_data;
1110 			for (int i = 0; i < ((1 <<
1111 			    DB_DNODE(db)->dn_indblkshift) / sizeof (blkptr_t));
1112 			    i++) {
1113 				blkptr_t *bp = &bps[i];
1114 				ASSERT3U(BP_GET_LSIZE(db->db_blkptr), ==,
1115 				    1 << dn->dn_indblkshift);
1116 				BP_SET_LSIZE(bp,
1117 				    BP_GET_LEVEL(db->db_blkptr) == 1 ?
1118 				    dn->dn_datablksz :
1119 				    BP_GET_LSIZE(db->db_blkptr));
1120 				BP_SET_TYPE(bp, BP_GET_TYPE(db->db_blkptr));
1121 				BP_SET_LEVEL(bp,
1122 				    BP_GET_LEVEL(db->db_blkptr) - 1);
1123 				BP_SET_BIRTH(bp, db->db_blkptr->blk_birth, 0);
1124 			}
1125 		}
1126 		DB_DNODE_EXIT(db);
1127 		db->db_state = DB_CACHED;
1128 		mutex_exit(&db->db_mtx);
1129 		return (0);
1130 	}
1131 
1132 	SET_BOOKMARK(&zb, dmu_objset_id(db->db_objset),
1133 	    db->db.db_object, db->db_level, db->db_blkid);
1134 
1135 	/*
1136 	 * All bps of an encrypted os should have the encryption bit set.
1137 	 * If this is not true it indicates tampering and we report an error.
1138 	 */
1139 	if (db->db_objset->os_encrypted && !BP_USES_CRYPT(db->db_blkptr)) {
1140 		spa_log_error(db->db_objset->os_spa, &zb);
1141 		zfs_panic_recover("unencrypted block in encrypted "
1142 		    "object set %llu", dmu_objset_id(db->db_objset));
1143 		DB_DNODE_EXIT(db);
1144 		mutex_exit(&db->db_mtx);
1145 		return (SET_ERROR(EIO));
1146 	}
1147 
1148 	err = dbuf_read_verify_dnode_crypt(db, flags);
1149 	if (err != 0) {
1150 		DB_DNODE_EXIT(db);
1151 		mutex_exit(&db->db_mtx);
1152 		return (err);
1153 	}
1154 
1155 	DB_DNODE_EXIT(db);
1156 
1157 	db->db_state = DB_READ;
1158 	mutex_exit(&db->db_mtx);
1159 
1160 	if (DBUF_IS_L2CACHEABLE(db))
1161 		aflags |= ARC_FLAG_L2CACHE;
1162 
1163 	dbuf_add_ref(db, NULL);
1164 
1165 	zio_flags = (flags & DB_RF_CANFAIL) ?
1166 	    ZIO_FLAG_CANFAIL : ZIO_FLAG_MUSTSUCCEED;
1167 
1168 	if ((flags & DB_RF_NO_DECRYPT) && BP_IS_PROTECTED(db->db_blkptr))
1169 		zio_flags |= ZIO_FLAG_RAW;
1170 
1171 	err = arc_read(zio, db->db_objset->os_spa, db->db_blkptr,
1172 	    dbuf_read_done, db, ZIO_PRIORITY_SYNC_READ, zio_flags,
1173 	    &aflags, &zb);
1174 
1175 	return (err);
1176 }
1177 
1178 /*
1179  * This is our just-in-time copy function.  It makes a copy of buffers that
1180  * have been modified in a previous transaction group before we access them in
1181  * the current active group.
1182  *
1183  * This function is used in three places: when we are dirtying a buffer for the
1184  * first time in a txg, when we are freeing a range in a dnode that includes
1185  * this buffer, and when we are accessing a buffer which was received compressed
1186  * and later referenced in a WRITE_BYREF record.
1187  *
1188  * Note that when we are called from dbuf_free_range() we do not put a hold on
1189  * the buffer, we just traverse the active dbuf list for the dnode.
1190  */
1191 static void
1192 dbuf_fix_old_data(dmu_buf_impl_t *db, uint64_t txg)
1193 {
1194 	dbuf_dirty_record_t *dr = db->db_last_dirty;
1195 
1196 	ASSERT(MUTEX_HELD(&db->db_mtx));
1197 	ASSERT(db->db.db_data != NULL);
1198 	ASSERT(db->db_level == 0);
1199 	ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT);
1200 
1201 	if (dr == NULL ||
1202 	    (dr->dt.dl.dr_data !=
1203 	    ((db->db_blkid  == DMU_BONUS_BLKID) ? db->db.db_data : db->db_buf)))
1204 		return;
1205 
1206 	/*
1207 	 * If the last dirty record for this dbuf has not yet synced
1208 	 * and its referencing the dbuf data, either:
1209 	 *	reset the reference to point to a new copy,
1210 	 * or (if there a no active holders)
1211 	 *	just null out the current db_data pointer.
1212 	 */
1213 	ASSERT3U(dr->dr_txg, >=, txg - 2);
1214 	if (db->db_blkid == DMU_BONUS_BLKID) {
1215 		/* Note that the data bufs here are zio_bufs */
1216 		dnode_t *dn = DB_DNODE(db);
1217 		int bonuslen = DN_SLOTS_TO_BONUSLEN(dn->dn_num_slots);
1218 		dr->dt.dl.dr_data = zio_buf_alloc(bonuslen);
1219 		arc_space_consume(bonuslen, ARC_SPACE_BONUS);
1220 		bcopy(db->db.db_data, dr->dt.dl.dr_data, bonuslen);
1221 	} else if (zfs_refcount_count(&db->db_holds) > db->db_dirtycnt) {
1222 		dnode_t *dn = DB_DNODE(db);
1223 		int size = arc_buf_size(db->db_buf);
1224 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1225 		spa_t *spa = db->db_objset->os_spa;
1226 		enum zio_compress compress_type =
1227 		    arc_get_compression(db->db_buf);
1228 
1229 		if (arc_is_encrypted(db->db_buf)) {
1230 			boolean_t byteorder;
1231 			uint8_t salt[ZIO_DATA_SALT_LEN];
1232 			uint8_t iv[ZIO_DATA_IV_LEN];
1233 			uint8_t mac[ZIO_DATA_MAC_LEN];
1234 
1235 			arc_get_raw_params(db->db_buf, &byteorder, salt,
1236 			    iv, mac);
1237 			dr->dt.dl.dr_data = arc_alloc_raw_buf(spa, db,
1238 			    dmu_objset_id(dn->dn_objset), byteorder, salt, iv,
1239 			    mac, dn->dn_type, size, arc_buf_lsize(db->db_buf),
1240 			    compress_type);
1241 		} else if (compress_type != ZIO_COMPRESS_OFF) {
1242 			ASSERT3U(type, ==, ARC_BUFC_DATA);
1243 			dr->dt.dl.dr_data = arc_alloc_compressed_buf(spa, db,
1244 			    size, arc_buf_lsize(db->db_buf), compress_type);
1245 		} else {
1246 			dr->dt.dl.dr_data = arc_alloc_buf(spa, db, type, size);
1247 		}
1248 		bcopy(db->db.db_data, dr->dt.dl.dr_data->b_data, size);
1249 	} else {
1250 		db->db_buf = NULL;
1251 		dbuf_clear_data(db);
1252 	}
1253 }
1254 
1255 int
1256 dbuf_read(dmu_buf_impl_t *db, zio_t *zio, uint32_t flags)
1257 {
1258 	int err = 0;
1259 	boolean_t prefetch;
1260 	dnode_t *dn;
1261 
1262 	/*
1263 	 * We don't have to hold the mutex to check db_state because it
1264 	 * can't be freed while we have a hold on the buffer.
1265 	 */
1266 	ASSERT(!zfs_refcount_is_zero(&db->db_holds));
1267 
1268 	if (db->db_state == DB_NOFILL)
1269 		return (SET_ERROR(EIO));
1270 
1271 	DB_DNODE_ENTER(db);
1272 	dn = DB_DNODE(db);
1273 	if ((flags & DB_RF_HAVESTRUCT) == 0)
1274 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
1275 
1276 	prefetch = db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
1277 	    (flags & DB_RF_NOPREFETCH) == 0 && dn != NULL &&
1278 	    DBUF_IS_CACHEABLE(db);
1279 
1280 	mutex_enter(&db->db_mtx);
1281 	if (db->db_state == DB_CACHED) {
1282 		spa_t *spa = dn->dn_objset->os_spa;
1283 
1284 		/*
1285 		 * Ensure that this block's dnode has been decrypted if
1286 		 * the caller has requested decrypted data.
1287 		 */
1288 		err = dbuf_read_verify_dnode_crypt(db, flags);
1289 
1290 		/*
1291 		 * If the arc buf is compressed or encrypted and the caller
1292 		 * requested uncompressed data, we need to untransform it
1293 		 * before returning. We also call arc_untransform() on any
1294 		 * unauthenticated blocks, which will verify their MAC if
1295 		 * the key is now available.
1296 		 */
1297 		if (err == 0 && db->db_buf != NULL &&
1298 		    (flags & DB_RF_NO_DECRYPT) == 0 &&
1299 		    (arc_is_encrypted(db->db_buf) ||
1300 		    arc_is_unauthenticated(db->db_buf) ||
1301 		    arc_get_compression(db->db_buf) != ZIO_COMPRESS_OFF)) {
1302 			zbookmark_phys_t zb;
1303 
1304 			SET_BOOKMARK(&zb, dmu_objset_id(db->db_objset),
1305 			    db->db.db_object, db->db_level, db->db_blkid);
1306 			dbuf_fix_old_data(db, spa_syncing_txg(spa));
1307 			err = arc_untransform(db->db_buf, spa, &zb, B_FALSE);
1308 			dbuf_set_data(db, db->db_buf);
1309 		}
1310 		mutex_exit(&db->db_mtx);
1311 		if (err == 0 && prefetch)
1312 			dmu_zfetch(&dn->dn_zfetch, db->db_blkid, 1, B_TRUE);
1313 		if ((flags & DB_RF_HAVESTRUCT) == 0)
1314 			rw_exit(&dn->dn_struct_rwlock);
1315 		DB_DNODE_EXIT(db);
1316 	} else if (db->db_state == DB_UNCACHED) {
1317 		spa_t *spa = dn->dn_objset->os_spa;
1318 		boolean_t need_wait = B_FALSE;
1319 
1320 		if (zio == NULL &&
1321 		    db->db_blkptr != NULL && !BP_IS_HOLE(db->db_blkptr)) {
1322 			zio = zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL);
1323 			need_wait = B_TRUE;
1324 		}
1325 		err = dbuf_read_impl(db, zio, flags);
1326 
1327 		/* dbuf_read_impl has dropped db_mtx for us */
1328 
1329 		if (!err && prefetch)
1330 			dmu_zfetch(&dn->dn_zfetch, db->db_blkid, 1, B_TRUE);
1331 
1332 		if ((flags & DB_RF_HAVESTRUCT) == 0)
1333 			rw_exit(&dn->dn_struct_rwlock);
1334 		DB_DNODE_EXIT(db);
1335 
1336 		if (!err && need_wait)
1337 			err = zio_wait(zio);
1338 	} else {
1339 		/*
1340 		 * Another reader came in while the dbuf was in flight
1341 		 * between UNCACHED and CACHED.  Either a writer will finish
1342 		 * writing the buffer (sending the dbuf to CACHED) or the
1343 		 * first reader's request will reach the read_done callback
1344 		 * and send the dbuf to CACHED.  Otherwise, a failure
1345 		 * occurred and the dbuf went to UNCACHED.
1346 		 */
1347 		mutex_exit(&db->db_mtx);
1348 		if (prefetch)
1349 			dmu_zfetch(&dn->dn_zfetch, db->db_blkid, 1, B_TRUE);
1350 		if ((flags & DB_RF_HAVESTRUCT) == 0)
1351 			rw_exit(&dn->dn_struct_rwlock);
1352 		DB_DNODE_EXIT(db);
1353 
1354 		/* Skip the wait per the caller's request. */
1355 		mutex_enter(&db->db_mtx);
1356 		if ((flags & DB_RF_NEVERWAIT) == 0) {
1357 			while (db->db_state == DB_READ ||
1358 			    db->db_state == DB_FILL) {
1359 				ASSERT(db->db_state == DB_READ ||
1360 				    (flags & DB_RF_HAVESTRUCT) == 0);
1361 				DTRACE_PROBE2(blocked__read, dmu_buf_impl_t *,
1362 				    db, zio_t *, zio);
1363 				cv_wait(&db->db_changed, &db->db_mtx);
1364 			}
1365 			if (db->db_state == DB_UNCACHED)
1366 				err = SET_ERROR(EIO);
1367 		}
1368 		mutex_exit(&db->db_mtx);
1369 	}
1370 
1371 	return (err);
1372 }
1373 
1374 static void
1375 dbuf_noread(dmu_buf_impl_t *db)
1376 {
1377 	ASSERT(!zfs_refcount_is_zero(&db->db_holds));
1378 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1379 	mutex_enter(&db->db_mtx);
1380 	while (db->db_state == DB_READ || db->db_state == DB_FILL)
1381 		cv_wait(&db->db_changed, &db->db_mtx);
1382 	if (db->db_state == DB_UNCACHED) {
1383 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1384 		spa_t *spa = db->db_objset->os_spa;
1385 
1386 		ASSERT(db->db_buf == NULL);
1387 		ASSERT(db->db.db_data == NULL);
1388 		dbuf_set_data(db, arc_alloc_buf(spa, db, type, db->db.db_size));
1389 		db->db_state = DB_FILL;
1390 	} else if (db->db_state == DB_NOFILL) {
1391 		dbuf_clear_data(db);
1392 	} else {
1393 		ASSERT3U(db->db_state, ==, DB_CACHED);
1394 	}
1395 	mutex_exit(&db->db_mtx);
1396 }
1397 
1398 void
1399 dbuf_unoverride(dbuf_dirty_record_t *dr)
1400 {
1401 	dmu_buf_impl_t *db = dr->dr_dbuf;
1402 	blkptr_t *bp = &dr->dt.dl.dr_overridden_by;
1403 	uint64_t txg = dr->dr_txg;
1404 
1405 	ASSERT(MUTEX_HELD(&db->db_mtx));
1406 	/*
1407 	 * This assert is valid because dmu_sync() expects to be called by
1408 	 * a zilog's get_data while holding a range lock.  This call only
1409 	 * comes from dbuf_dirty() callers who must also hold a range lock.
1410 	 */
1411 	ASSERT(dr->dt.dl.dr_override_state != DR_IN_DMU_SYNC);
1412 	ASSERT(db->db_level == 0);
1413 
1414 	if (db->db_blkid == DMU_BONUS_BLKID ||
1415 	    dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN)
1416 		return;
1417 
1418 	ASSERT(db->db_data_pending != dr);
1419 
1420 	/* free this block */
1421 	if (!BP_IS_HOLE(bp) && !dr->dt.dl.dr_nopwrite)
1422 		zio_free(db->db_objset->os_spa, txg, bp);
1423 
1424 	dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
1425 	dr->dt.dl.dr_nopwrite = B_FALSE;
1426 	dr->dt.dl.dr_has_raw_params = B_FALSE;
1427 
1428 	/*
1429 	 * Release the already-written buffer, so we leave it in
1430 	 * a consistent dirty state.  Note that all callers are
1431 	 * modifying the buffer, so they will immediately do
1432 	 * another (redundant) arc_release().  Therefore, leave
1433 	 * the buf thawed to save the effort of freezing &
1434 	 * immediately re-thawing it.
1435 	 */
1436 	arc_release(dr->dt.dl.dr_data, db);
1437 }
1438 
1439 /*
1440  * Evict (if its unreferenced) or clear (if its referenced) any level-0
1441  * data blocks in the free range, so that any future readers will find
1442  * empty blocks.
1443  */
1444 void
1445 dbuf_free_range(dnode_t *dn, uint64_t start_blkid, uint64_t end_blkid,
1446     dmu_tx_t *tx)
1447 {
1448 	dmu_buf_impl_t db_search;
1449 	dmu_buf_impl_t *db, *db_next;
1450 	uint64_t txg = tx->tx_txg;
1451 	avl_index_t where;
1452 
1453 	if (end_blkid > dn->dn_maxblkid &&
1454 	    !(start_blkid == DMU_SPILL_BLKID || end_blkid == DMU_SPILL_BLKID))
1455 		end_blkid = dn->dn_maxblkid;
1456 	dprintf_dnode(dn, "start=%llu end=%llu\n", start_blkid, end_blkid);
1457 
1458 	db_search.db_level = 0;
1459 	db_search.db_blkid = start_blkid;
1460 	db_search.db_state = DB_SEARCH;
1461 
1462 	mutex_enter(&dn->dn_dbufs_mtx);
1463 	db = avl_find(&dn->dn_dbufs, &db_search, &where);
1464 	ASSERT3P(db, ==, NULL);
1465 
1466 	db = avl_nearest(&dn->dn_dbufs, where, AVL_AFTER);
1467 
1468 	for (; db != NULL; db = db_next) {
1469 		db_next = AVL_NEXT(&dn->dn_dbufs, db);
1470 		ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1471 
1472 		if (db->db_level != 0 || db->db_blkid > end_blkid) {
1473 			break;
1474 		}
1475 		ASSERT3U(db->db_blkid, >=, start_blkid);
1476 
1477 		/* found a level 0 buffer in the range */
1478 		mutex_enter(&db->db_mtx);
1479 		if (dbuf_undirty(db, tx)) {
1480 			/* mutex has been dropped and dbuf destroyed */
1481 			continue;
1482 		}
1483 
1484 		if (db->db_state == DB_UNCACHED ||
1485 		    db->db_state == DB_NOFILL ||
1486 		    db->db_state == DB_EVICTING) {
1487 			ASSERT(db->db.db_data == NULL);
1488 			mutex_exit(&db->db_mtx);
1489 			continue;
1490 		}
1491 		if (db->db_state == DB_READ || db->db_state == DB_FILL) {
1492 			/* will be handled in dbuf_read_done or dbuf_rele */
1493 			db->db_freed_in_flight = TRUE;
1494 			mutex_exit(&db->db_mtx);
1495 			continue;
1496 		}
1497 		if (zfs_refcount_count(&db->db_holds) == 0) {
1498 			ASSERT(db->db_buf);
1499 			dbuf_destroy(db);
1500 			continue;
1501 		}
1502 		/* The dbuf is referenced */
1503 
1504 		if (db->db_last_dirty != NULL) {
1505 			dbuf_dirty_record_t *dr = db->db_last_dirty;
1506 
1507 			if (dr->dr_txg == txg) {
1508 				/*
1509 				 * This buffer is "in-use", re-adjust the file
1510 				 * size to reflect that this buffer may
1511 				 * contain new data when we sync.
1512 				 */
1513 				if (db->db_blkid != DMU_SPILL_BLKID &&
1514 				    db->db_blkid > dn->dn_maxblkid)
1515 					dn->dn_maxblkid = db->db_blkid;
1516 				dbuf_unoverride(dr);
1517 			} else {
1518 				/*
1519 				 * This dbuf is not dirty in the open context.
1520 				 * Either uncache it (if its not referenced in
1521 				 * the open context) or reset its contents to
1522 				 * empty.
1523 				 */
1524 				dbuf_fix_old_data(db, txg);
1525 			}
1526 		}
1527 		/* clear the contents if its cached */
1528 		if (db->db_state == DB_CACHED) {
1529 			ASSERT(db->db.db_data != NULL);
1530 			arc_release(db->db_buf, db);
1531 			bzero(db->db.db_data, db->db.db_size);
1532 			arc_buf_freeze(db->db_buf);
1533 		}
1534 
1535 		mutex_exit(&db->db_mtx);
1536 	}
1537 	mutex_exit(&dn->dn_dbufs_mtx);
1538 }
1539 
1540 void
1541 dbuf_new_size(dmu_buf_impl_t *db, int size, dmu_tx_t *tx)
1542 {
1543 	arc_buf_t *buf, *obuf;
1544 	int osize = db->db.db_size;
1545 	arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1546 	dnode_t *dn;
1547 
1548 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1549 
1550 	DB_DNODE_ENTER(db);
1551 	dn = DB_DNODE(db);
1552 
1553 	/* XXX does *this* func really need the lock? */
1554 	ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
1555 
1556 	/*
1557 	 * This call to dmu_buf_will_dirty() with the dn_struct_rwlock held
1558 	 * is OK, because there can be no other references to the db
1559 	 * when we are changing its size, so no concurrent DB_FILL can
1560 	 * be happening.
1561 	 */
1562 	/*
1563 	 * XXX we should be doing a dbuf_read, checking the return
1564 	 * value and returning that up to our callers
1565 	 */
1566 	dmu_buf_will_dirty(&db->db, tx);
1567 
1568 	/* create the data buffer for the new block */
1569 	buf = arc_alloc_buf(dn->dn_objset->os_spa, db, type, size);
1570 
1571 	/* copy old block data to the new block */
1572 	obuf = db->db_buf;
1573 	bcopy(obuf->b_data, buf->b_data, MIN(osize, size));
1574 	/* zero the remainder */
1575 	if (size > osize)
1576 		bzero((uint8_t *)buf->b_data + osize, size - osize);
1577 
1578 	mutex_enter(&db->db_mtx);
1579 	dbuf_set_data(db, buf);
1580 	arc_buf_destroy(obuf, db);
1581 	db->db.db_size = size;
1582 
1583 	if (db->db_level == 0) {
1584 		ASSERT3U(db->db_last_dirty->dr_txg, ==, tx->tx_txg);
1585 		db->db_last_dirty->dt.dl.dr_data = buf;
1586 	}
1587 	mutex_exit(&db->db_mtx);
1588 
1589 	dmu_objset_willuse_space(dn->dn_objset, size - osize, tx);
1590 	DB_DNODE_EXIT(db);
1591 }
1592 
1593 void
1594 dbuf_release_bp(dmu_buf_impl_t *db)
1595 {
1596 	objset_t *os = db->db_objset;
1597 
1598 	ASSERT(dsl_pool_sync_context(dmu_objset_pool(os)));
1599 	ASSERT(arc_released(os->os_phys_buf) ||
1600 	    list_link_active(&os->os_dsl_dataset->ds_synced_link));
1601 	ASSERT(db->db_parent == NULL || arc_released(db->db_parent->db_buf));
1602 
1603 	(void) arc_release(db->db_buf, db);
1604 }
1605 
1606 /*
1607  * We already have a dirty record for this TXG, and we are being
1608  * dirtied again.
1609  */
1610 static void
1611 dbuf_redirty(dbuf_dirty_record_t *dr)
1612 {
1613 	dmu_buf_impl_t *db = dr->dr_dbuf;
1614 
1615 	ASSERT(MUTEX_HELD(&db->db_mtx));
1616 
1617 	if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID) {
1618 		/*
1619 		 * If this buffer has already been written out,
1620 		 * we now need to reset its state.
1621 		 */
1622 		dbuf_unoverride(dr);
1623 		if (db->db.db_object != DMU_META_DNODE_OBJECT &&
1624 		    db->db_state != DB_NOFILL) {
1625 			/* Already released on initial dirty, so just thaw. */
1626 			ASSERT(arc_released(db->db_buf));
1627 			arc_buf_thaw(db->db_buf);
1628 		}
1629 	}
1630 }
1631 
1632 dbuf_dirty_record_t *
1633 dbuf_dirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
1634 {
1635 	dnode_t *dn;
1636 	objset_t *os;
1637 	dbuf_dirty_record_t **drp, *dr;
1638 	int drop_struct_lock = FALSE;
1639 	int txgoff = tx->tx_txg & TXG_MASK;
1640 
1641 	ASSERT(tx->tx_txg != 0);
1642 	ASSERT(!zfs_refcount_is_zero(&db->db_holds));
1643 	DMU_TX_DIRTY_BUF(tx, db);
1644 
1645 	DB_DNODE_ENTER(db);
1646 	dn = DB_DNODE(db);
1647 	/*
1648 	 * Shouldn't dirty a regular buffer in syncing context.  Private
1649 	 * objects may be dirtied in syncing context, but only if they
1650 	 * were already pre-dirtied in open context.
1651 	 */
1652 #ifdef DEBUG
1653 	if (dn->dn_objset->os_dsl_dataset != NULL) {
1654 		rrw_enter(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock,
1655 		    RW_READER, FTAG);
1656 	}
1657 	ASSERT(!dmu_tx_is_syncing(tx) ||
1658 	    BP_IS_HOLE(dn->dn_objset->os_rootbp) ||
1659 	    DMU_OBJECT_IS_SPECIAL(dn->dn_object) ||
1660 	    dn->dn_objset->os_dsl_dataset == NULL);
1661 	if (dn->dn_objset->os_dsl_dataset != NULL)
1662 		rrw_exit(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock, FTAG);
1663 #endif
1664 	/*
1665 	 * We make this assert for private objects as well, but after we
1666 	 * check if we're already dirty.  They are allowed to re-dirty
1667 	 * in syncing context.
1668 	 */
1669 	ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
1670 	    dn->dn_dirtyctx == DN_UNDIRTIED || dn->dn_dirtyctx ==
1671 	    (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN));
1672 
1673 	mutex_enter(&db->db_mtx);
1674 	/*
1675 	 * XXX make this true for indirects too?  The problem is that
1676 	 * transactions created with dmu_tx_create_assigned() from
1677 	 * syncing context don't bother holding ahead.
1678 	 */
1679 	ASSERT(db->db_level != 0 ||
1680 	    db->db_state == DB_CACHED || db->db_state == DB_FILL ||
1681 	    db->db_state == DB_NOFILL);
1682 
1683 	mutex_enter(&dn->dn_mtx);
1684 	/*
1685 	 * Don't set dirtyctx to SYNC if we're just modifying this as we
1686 	 * initialize the objset.
1687 	 */
1688 	if (dn->dn_dirtyctx == DN_UNDIRTIED) {
1689 		if (dn->dn_objset->os_dsl_dataset != NULL) {
1690 			rrw_enter(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock,
1691 			    RW_READER, FTAG);
1692 		}
1693 		if (!BP_IS_HOLE(dn->dn_objset->os_rootbp)) {
1694 			dn->dn_dirtyctx = (dmu_tx_is_syncing(tx) ?
1695 			    DN_DIRTY_SYNC : DN_DIRTY_OPEN);
1696 			ASSERT(dn->dn_dirtyctx_firstset == NULL);
1697 			dn->dn_dirtyctx_firstset = kmem_alloc(1, KM_SLEEP);
1698 		}
1699 		if (dn->dn_objset->os_dsl_dataset != NULL) {
1700 			rrw_exit(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock,
1701 			    FTAG);
1702 		}
1703 	}
1704 
1705 	if (tx->tx_txg > dn->dn_dirty_txg)
1706 		dn->dn_dirty_txg = tx->tx_txg;
1707 	mutex_exit(&dn->dn_mtx);
1708 
1709 	if (db->db_blkid == DMU_SPILL_BLKID)
1710 		dn->dn_have_spill = B_TRUE;
1711 
1712 	/*
1713 	 * If this buffer is already dirty, we're done.
1714 	 */
1715 	drp = &db->db_last_dirty;
1716 	ASSERT(*drp == NULL || (*drp)->dr_txg <= tx->tx_txg ||
1717 	    db->db.db_object == DMU_META_DNODE_OBJECT);
1718 	while ((dr = *drp) != NULL && dr->dr_txg > tx->tx_txg)
1719 		drp = &dr->dr_next;
1720 	if (dr && dr->dr_txg == tx->tx_txg) {
1721 		DB_DNODE_EXIT(db);
1722 
1723 		dbuf_redirty(dr);
1724 		mutex_exit(&db->db_mtx);
1725 		return (dr);
1726 	}
1727 
1728 	/*
1729 	 * Only valid if not already dirty.
1730 	 */
1731 	ASSERT(dn->dn_object == 0 ||
1732 	    dn->dn_dirtyctx == DN_UNDIRTIED || dn->dn_dirtyctx ==
1733 	    (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN));
1734 
1735 	ASSERT3U(dn->dn_nlevels, >, db->db_level);
1736 
1737 	/*
1738 	 * We should only be dirtying in syncing context if it's the
1739 	 * mos or we're initializing the os or it's a special object.
1740 	 * However, we are allowed to dirty in syncing context provided
1741 	 * we already dirtied it in open context.  Hence we must make
1742 	 * this assertion only if we're not already dirty.
1743 	 */
1744 	os = dn->dn_objset;
1745 	VERIFY3U(tx->tx_txg, <=, spa_final_dirty_txg(os->os_spa));
1746 #ifdef DEBUG
1747 	if (dn->dn_objset->os_dsl_dataset != NULL)
1748 		rrw_enter(&os->os_dsl_dataset->ds_bp_rwlock, RW_READER, FTAG);
1749 	ASSERT(!dmu_tx_is_syncing(tx) || DMU_OBJECT_IS_SPECIAL(dn->dn_object) ||
1750 	    os->os_dsl_dataset == NULL || BP_IS_HOLE(os->os_rootbp));
1751 	if (dn->dn_objset->os_dsl_dataset != NULL)
1752 		rrw_exit(&os->os_dsl_dataset->ds_bp_rwlock, FTAG);
1753 #endif
1754 	ASSERT(db->db.db_size != 0);
1755 
1756 	dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
1757 
1758 	if (db->db_blkid != DMU_BONUS_BLKID) {
1759 		dmu_objset_willuse_space(os, db->db.db_size, tx);
1760 	}
1761 
1762 	/*
1763 	 * If this buffer is dirty in an old transaction group we need
1764 	 * to make a copy of it so that the changes we make in this
1765 	 * transaction group won't leak out when we sync the older txg.
1766 	 */
1767 	dr = kmem_zalloc(sizeof (dbuf_dirty_record_t), KM_SLEEP);
1768 	if (db->db_level == 0) {
1769 		void *data_old = db->db_buf;
1770 
1771 		if (db->db_state != DB_NOFILL) {
1772 			if (db->db_blkid == DMU_BONUS_BLKID) {
1773 				dbuf_fix_old_data(db, tx->tx_txg);
1774 				data_old = db->db.db_data;
1775 			} else if (db->db.db_object != DMU_META_DNODE_OBJECT) {
1776 				/*
1777 				 * Release the data buffer from the cache so
1778 				 * that we can modify it without impacting
1779 				 * possible other users of this cached data
1780 				 * block.  Note that indirect blocks and
1781 				 * private objects are not released until the
1782 				 * syncing state (since they are only modified
1783 				 * then).
1784 				 */
1785 				arc_release(db->db_buf, db);
1786 				dbuf_fix_old_data(db, tx->tx_txg);
1787 				data_old = db->db_buf;
1788 			}
1789 			ASSERT(data_old != NULL);
1790 		}
1791 		dr->dt.dl.dr_data = data_old;
1792 	} else {
1793 		mutex_init(&dr->dt.di.dr_mtx, NULL, MUTEX_DEFAULT, NULL);
1794 		list_create(&dr->dt.di.dr_children,
1795 		    sizeof (dbuf_dirty_record_t),
1796 		    offsetof(dbuf_dirty_record_t, dr_dirty_node));
1797 	}
1798 	if (db->db_blkid != DMU_BONUS_BLKID && os->os_dsl_dataset != NULL)
1799 		dr->dr_accounted = db->db.db_size;
1800 	dr->dr_dbuf = db;
1801 	dr->dr_txg = tx->tx_txg;
1802 	dr->dr_next = *drp;
1803 	*drp = dr;
1804 
1805 	/*
1806 	 * We could have been freed_in_flight between the dbuf_noread
1807 	 * and dbuf_dirty.  We win, as though the dbuf_noread() had
1808 	 * happened after the free.
1809 	 */
1810 	if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
1811 	    db->db_blkid != DMU_SPILL_BLKID) {
1812 		mutex_enter(&dn->dn_mtx);
1813 		if (dn->dn_free_ranges[txgoff] != NULL) {
1814 			range_tree_clear(dn->dn_free_ranges[txgoff],
1815 			    db->db_blkid, 1);
1816 		}
1817 		mutex_exit(&dn->dn_mtx);
1818 		db->db_freed_in_flight = FALSE;
1819 	}
1820 
1821 	/*
1822 	 * This buffer is now part of this txg
1823 	 */
1824 	dbuf_add_ref(db, (void *)(uintptr_t)tx->tx_txg);
1825 	db->db_dirtycnt += 1;
1826 	ASSERT3U(db->db_dirtycnt, <=, 3);
1827 
1828 	mutex_exit(&db->db_mtx);
1829 
1830 	if (db->db_blkid == DMU_BONUS_BLKID ||
1831 	    db->db_blkid == DMU_SPILL_BLKID) {
1832 		mutex_enter(&dn->dn_mtx);
1833 		ASSERT(!list_link_active(&dr->dr_dirty_node));
1834 		list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
1835 		mutex_exit(&dn->dn_mtx);
1836 		dnode_setdirty(dn, tx);
1837 		DB_DNODE_EXIT(db);
1838 		return (dr);
1839 	}
1840 
1841 	/*
1842 	 * The dn_struct_rwlock prevents db_blkptr from changing
1843 	 * due to a write from syncing context completing
1844 	 * while we are running, so we want to acquire it before
1845 	 * looking at db_blkptr.
1846 	 */
1847 	if (!RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
1848 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
1849 		drop_struct_lock = TRUE;
1850 	}
1851 
1852 	/*
1853 	 * We need to hold the dn_struct_rwlock to make this assertion,
1854 	 * because it protects dn_phys / dn_next_nlevels from changing.
1855 	 */
1856 	ASSERT((dn->dn_phys->dn_nlevels == 0 && db->db_level == 0) ||
1857 	    dn->dn_phys->dn_nlevels > db->db_level ||
1858 	    dn->dn_next_nlevels[txgoff] > db->db_level ||
1859 	    dn->dn_next_nlevels[(tx->tx_txg-1) & TXG_MASK] > db->db_level ||
1860 	    dn->dn_next_nlevels[(tx->tx_txg-2) & TXG_MASK] > db->db_level);
1861 
1862 	/*
1863 	 * If we are overwriting a dedup BP, then unless it is snapshotted,
1864 	 * when we get to syncing context we will need to decrement its
1865 	 * refcount in the DDT.  Prefetch the relevant DDT block so that
1866 	 * syncing context won't have to wait for the i/o.
1867 	 */
1868 	ddt_prefetch(os->os_spa, db->db_blkptr);
1869 
1870 	if (db->db_level == 0) {
1871 		ASSERT(!db->db_objset->os_raw_receive ||
1872 		    dn->dn_maxblkid >= db->db_blkid);
1873 		dnode_new_blkid(dn, db->db_blkid, tx,
1874 		    drop_struct_lock, B_FALSE);
1875 		ASSERT(dn->dn_maxblkid >= db->db_blkid);
1876 	}
1877 
1878 	if (db->db_level+1 < dn->dn_nlevels) {
1879 		dmu_buf_impl_t *parent = db->db_parent;
1880 		dbuf_dirty_record_t *di;
1881 		int parent_held = FALSE;
1882 
1883 		if (db->db_parent == NULL || db->db_parent == dn->dn_dbuf) {
1884 			int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
1885 
1886 			parent = dbuf_hold_level(dn, db->db_level+1,
1887 			    db->db_blkid >> epbs, FTAG);
1888 			ASSERT(parent != NULL);
1889 			parent_held = TRUE;
1890 		}
1891 		if (drop_struct_lock)
1892 			rw_exit(&dn->dn_struct_rwlock);
1893 		ASSERT3U(db->db_level+1, ==, parent->db_level);
1894 		di = dbuf_dirty(parent, tx);
1895 		if (parent_held)
1896 			dbuf_rele(parent, FTAG);
1897 
1898 		mutex_enter(&db->db_mtx);
1899 		/*
1900 		 * Since we've dropped the mutex, it's possible that
1901 		 * dbuf_undirty() might have changed this out from under us.
1902 		 */
1903 		if (db->db_last_dirty == dr ||
1904 		    dn->dn_object == DMU_META_DNODE_OBJECT) {
1905 			mutex_enter(&di->dt.di.dr_mtx);
1906 			ASSERT3U(di->dr_txg, ==, tx->tx_txg);
1907 			ASSERT(!list_link_active(&dr->dr_dirty_node));
1908 			list_insert_tail(&di->dt.di.dr_children, dr);
1909 			mutex_exit(&di->dt.di.dr_mtx);
1910 			dr->dr_parent = di;
1911 		}
1912 		mutex_exit(&db->db_mtx);
1913 	} else {
1914 		ASSERT(db->db_level+1 == dn->dn_nlevels);
1915 		ASSERT(db->db_blkid < dn->dn_nblkptr);
1916 		ASSERT(db->db_parent == NULL || db->db_parent == dn->dn_dbuf);
1917 		mutex_enter(&dn->dn_mtx);
1918 		ASSERT(!list_link_active(&dr->dr_dirty_node));
1919 		list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
1920 		mutex_exit(&dn->dn_mtx);
1921 		if (drop_struct_lock)
1922 			rw_exit(&dn->dn_struct_rwlock);
1923 	}
1924 
1925 	dnode_setdirty(dn, tx);
1926 	DB_DNODE_EXIT(db);
1927 	return (dr);
1928 }
1929 
1930 /*
1931  * Undirty a buffer in the transaction group referenced by the given
1932  * transaction.  Return whether this evicted the dbuf.
1933  */
1934 static boolean_t
1935 dbuf_undirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
1936 {
1937 	dnode_t *dn;
1938 	uint64_t txg = tx->tx_txg;
1939 	dbuf_dirty_record_t *dr, **drp;
1940 
1941 	ASSERT(txg != 0);
1942 
1943 	/*
1944 	 * Due to our use of dn_nlevels below, this can only be called
1945 	 * in open context, unless we are operating on the MOS.
1946 	 * From syncing context, dn_nlevels may be different from the
1947 	 * dn_nlevels used when dbuf was dirtied.
1948 	 */
1949 	ASSERT(db->db_objset ==
1950 	    dmu_objset_pool(db->db_objset)->dp_meta_objset ||
1951 	    txg != spa_syncing_txg(dmu_objset_spa(db->db_objset)));
1952 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1953 	ASSERT0(db->db_level);
1954 	ASSERT(MUTEX_HELD(&db->db_mtx));
1955 
1956 	/*
1957 	 * If this buffer is not dirty, we're done.
1958 	 */
1959 	for (drp = &db->db_last_dirty; (dr = *drp) != NULL; drp = &dr->dr_next)
1960 		if (dr->dr_txg <= txg)
1961 			break;
1962 	if (dr == NULL || dr->dr_txg < txg)
1963 		return (B_FALSE);
1964 	ASSERT(dr->dr_txg == txg);
1965 	ASSERT(dr->dr_dbuf == db);
1966 
1967 	DB_DNODE_ENTER(db);
1968 	dn = DB_DNODE(db);
1969 
1970 	dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
1971 
1972 	ASSERT(db->db.db_size != 0);
1973 
1974 	dsl_pool_undirty_space(dmu_objset_pool(dn->dn_objset),
1975 	    dr->dr_accounted, txg);
1976 
1977 	*drp = dr->dr_next;
1978 
1979 	/*
1980 	 * Note that there are three places in dbuf_dirty()
1981 	 * where this dirty record may be put on a list.
1982 	 * Make sure to do a list_remove corresponding to
1983 	 * every one of those list_insert calls.
1984 	 */
1985 	if (dr->dr_parent) {
1986 		mutex_enter(&dr->dr_parent->dt.di.dr_mtx);
1987 		list_remove(&dr->dr_parent->dt.di.dr_children, dr);
1988 		mutex_exit(&dr->dr_parent->dt.di.dr_mtx);
1989 	} else if (db->db_blkid == DMU_SPILL_BLKID ||
1990 	    db->db_level + 1 == dn->dn_nlevels) {
1991 		ASSERT(db->db_blkptr == NULL || db->db_parent == dn->dn_dbuf);
1992 		mutex_enter(&dn->dn_mtx);
1993 		list_remove(&dn->dn_dirty_records[txg & TXG_MASK], dr);
1994 		mutex_exit(&dn->dn_mtx);
1995 	}
1996 	DB_DNODE_EXIT(db);
1997 
1998 	if (db->db_state != DB_NOFILL) {
1999 		dbuf_unoverride(dr);
2000 
2001 		ASSERT(db->db_buf != NULL);
2002 		ASSERT(dr->dt.dl.dr_data != NULL);
2003 		if (dr->dt.dl.dr_data != db->db_buf)
2004 			arc_buf_destroy(dr->dt.dl.dr_data, db);
2005 	}
2006 
2007 	kmem_free(dr, sizeof (dbuf_dirty_record_t));
2008 
2009 	ASSERT(db->db_dirtycnt > 0);
2010 	db->db_dirtycnt -= 1;
2011 
2012 	if (zfs_refcount_remove(&db->db_holds, (void *)(uintptr_t)txg) == 0) {
2013 		ASSERT(db->db_state == DB_NOFILL || arc_released(db->db_buf));
2014 		dbuf_destroy(db);
2015 		return (B_TRUE);
2016 	}
2017 
2018 	return (B_FALSE);
2019 }
2020 
2021 static void
2022 dmu_buf_will_dirty_impl(dmu_buf_t *db_fake, int flags, dmu_tx_t *tx)
2023 {
2024 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2025 
2026 	ASSERT(tx->tx_txg != 0);
2027 	ASSERT(!zfs_refcount_is_zero(&db->db_holds));
2028 
2029 	/*
2030 	 * Quick check for dirtyness.  For already dirty blocks, this
2031 	 * reduces runtime of this function by >90%, and overall performance
2032 	 * by 50% for some workloads (e.g. file deletion with indirect blocks
2033 	 * cached).
2034 	 */
2035 	mutex_enter(&db->db_mtx);
2036 	dbuf_dirty_record_t *dr;
2037 	for (dr = db->db_last_dirty;
2038 	    dr != NULL && dr->dr_txg >= tx->tx_txg; dr = dr->dr_next) {
2039 		/*
2040 		 * It's possible that it is already dirty but not cached,
2041 		 * because there are some calls to dbuf_dirty() that don't
2042 		 * go through dmu_buf_will_dirty().
2043 		 */
2044 		if (dr->dr_txg == tx->tx_txg && db->db_state == DB_CACHED) {
2045 			/* This dbuf is already dirty and cached. */
2046 			dbuf_redirty(dr);
2047 			mutex_exit(&db->db_mtx);
2048 			return;
2049 		}
2050 	}
2051 	mutex_exit(&db->db_mtx);
2052 
2053 	DB_DNODE_ENTER(db);
2054 	if (RW_WRITE_HELD(&DB_DNODE(db)->dn_struct_rwlock))
2055 		flags |= DB_RF_HAVESTRUCT;
2056 	DB_DNODE_EXIT(db);
2057 	(void) dbuf_read(db, NULL, flags);
2058 	(void) dbuf_dirty(db, tx);
2059 }
2060 
2061 void
2062 dmu_buf_will_dirty(dmu_buf_t *db_fake, dmu_tx_t *tx)
2063 {
2064 	dmu_buf_will_dirty_impl(db_fake,
2065 	    DB_RF_MUST_SUCCEED | DB_RF_NOPREFETCH, tx);
2066 }
2067 
2068 void
2069 dmu_buf_will_not_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
2070 {
2071 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2072 
2073 	db->db_state = DB_NOFILL;
2074 
2075 	dmu_buf_will_fill(db_fake, tx);
2076 }
2077 
2078 void
2079 dmu_buf_will_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
2080 {
2081 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2082 
2083 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2084 	ASSERT(tx->tx_txg != 0);
2085 	ASSERT(db->db_level == 0);
2086 	ASSERT(!zfs_refcount_is_zero(&db->db_holds));
2087 
2088 	ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT ||
2089 	    dmu_tx_private_ok(tx));
2090 
2091 	dbuf_noread(db);
2092 	(void) dbuf_dirty(db, tx);
2093 }
2094 
2095 /*
2096  * This function is effectively the same as dmu_buf_will_dirty(), but
2097  * indicates the caller expects raw encrypted data in the db, and provides
2098  * the crypt params (byteorder, salt, iv, mac) which should be stored in the
2099  * blkptr_t when this dbuf is written.  This is only used for blocks of
2100  * dnodes during a raw receive.
2101  */
2102 void
2103 dmu_buf_set_crypt_params(dmu_buf_t *db_fake, boolean_t byteorder,
2104     const uint8_t *salt, const uint8_t *iv, const uint8_t *mac, dmu_tx_t *tx)
2105 {
2106 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2107 	dbuf_dirty_record_t *dr;
2108 
2109 	/*
2110 	 * dr_has_raw_params is only processed for blocks of dnodes
2111 	 * (see dbuf_sync_dnode_leaf_crypt()).
2112 	 */
2113 	ASSERT3U(db->db.db_object, ==, DMU_META_DNODE_OBJECT);
2114 	ASSERT3U(db->db_level, ==, 0);
2115 
2116 	dmu_buf_will_dirty_impl(db_fake,
2117 	    DB_RF_MUST_SUCCEED | DB_RF_NOPREFETCH | DB_RF_NO_DECRYPT, tx);
2118 
2119 	dr = db->db_last_dirty;
2120 	while (dr != NULL && dr->dr_txg > tx->tx_txg)
2121 		dr = dr->dr_next;
2122 
2123 	ASSERT3P(dr, !=, NULL);
2124 	ASSERT3U(dr->dr_txg, ==, tx->tx_txg);
2125 
2126 	dr->dt.dl.dr_has_raw_params = B_TRUE;
2127 	dr->dt.dl.dr_byteorder = byteorder;
2128 	bcopy(salt, dr->dt.dl.dr_salt, ZIO_DATA_SALT_LEN);
2129 	bcopy(iv, dr->dt.dl.dr_iv, ZIO_DATA_IV_LEN);
2130 	bcopy(mac, dr->dt.dl.dr_mac, ZIO_DATA_MAC_LEN);
2131 }
2132 
2133 #pragma weak dmu_buf_fill_done = dbuf_fill_done
2134 /* ARGSUSED */
2135 void
2136 dbuf_fill_done(dmu_buf_impl_t *db, dmu_tx_t *tx)
2137 {
2138 	mutex_enter(&db->db_mtx);
2139 	DBUF_VERIFY(db);
2140 
2141 	if (db->db_state == DB_FILL) {
2142 		if (db->db_level == 0 && db->db_freed_in_flight) {
2143 			ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2144 			/* we were freed while filling */
2145 			/* XXX dbuf_undirty? */
2146 			bzero(db->db.db_data, db->db.db_size);
2147 			db->db_freed_in_flight = FALSE;
2148 		}
2149 		db->db_state = DB_CACHED;
2150 		cv_broadcast(&db->db_changed);
2151 	}
2152 	mutex_exit(&db->db_mtx);
2153 }
2154 
2155 void
2156 dmu_buf_write_embedded(dmu_buf_t *dbuf, void *data,
2157     bp_embedded_type_t etype, enum zio_compress comp,
2158     int uncompressed_size, int compressed_size, int byteorder,
2159     dmu_tx_t *tx)
2160 {
2161 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbuf;
2162 	struct dirty_leaf *dl;
2163 	dmu_object_type_t type;
2164 
2165 	if (etype == BP_EMBEDDED_TYPE_DATA) {
2166 		ASSERT(spa_feature_is_active(dmu_objset_spa(db->db_objset),
2167 		    SPA_FEATURE_EMBEDDED_DATA));
2168 	}
2169 
2170 	DB_DNODE_ENTER(db);
2171 	type = DB_DNODE(db)->dn_type;
2172 	DB_DNODE_EXIT(db);
2173 
2174 	ASSERT0(db->db_level);
2175 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2176 
2177 	dmu_buf_will_not_fill(dbuf, tx);
2178 
2179 	ASSERT3U(db->db_last_dirty->dr_txg, ==, tx->tx_txg);
2180 	dl = &db->db_last_dirty->dt.dl;
2181 	encode_embedded_bp_compressed(&dl->dr_overridden_by,
2182 	    data, comp, uncompressed_size, compressed_size);
2183 	BPE_SET_ETYPE(&dl->dr_overridden_by, etype);
2184 	BP_SET_TYPE(&dl->dr_overridden_by, type);
2185 	BP_SET_LEVEL(&dl->dr_overridden_by, 0);
2186 	BP_SET_BYTEORDER(&dl->dr_overridden_by, byteorder);
2187 
2188 	dl->dr_override_state = DR_OVERRIDDEN;
2189 	dl->dr_overridden_by.blk_birth = db->db_last_dirty->dr_txg;
2190 }
2191 
2192 /*
2193  * Directly assign a provided arc buf to a given dbuf if it's not referenced
2194  * by anybody except our caller. Otherwise copy arcbuf's contents to dbuf.
2195  */
2196 void
2197 dbuf_assign_arcbuf(dmu_buf_impl_t *db, arc_buf_t *buf, dmu_tx_t *tx)
2198 {
2199 	ASSERT(!zfs_refcount_is_zero(&db->db_holds));
2200 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2201 	ASSERT(db->db_level == 0);
2202 	ASSERT3U(dbuf_is_metadata(db), ==, arc_is_metadata(buf));
2203 	ASSERT(buf != NULL);
2204 	ASSERT(arc_buf_lsize(buf) == db->db.db_size);
2205 	ASSERT(tx->tx_txg != 0);
2206 
2207 	arc_return_buf(buf, db);
2208 	ASSERT(arc_released(buf));
2209 
2210 	mutex_enter(&db->db_mtx);
2211 
2212 	while (db->db_state == DB_READ || db->db_state == DB_FILL)
2213 		cv_wait(&db->db_changed, &db->db_mtx);
2214 
2215 	ASSERT(db->db_state == DB_CACHED || db->db_state == DB_UNCACHED);
2216 
2217 	if (db->db_state == DB_CACHED &&
2218 	    zfs_refcount_count(&db->db_holds) - 1 > db->db_dirtycnt) {
2219 		/*
2220 		 * In practice, we will never have a case where we have an
2221 		 * encrypted arc buffer while additional holds exist on the
2222 		 * dbuf. We don't handle this here so we simply assert that
2223 		 * fact instead.
2224 		 */
2225 		ASSERT(!arc_is_encrypted(buf));
2226 		mutex_exit(&db->db_mtx);
2227 		(void) dbuf_dirty(db, tx);
2228 		bcopy(buf->b_data, db->db.db_data, db->db.db_size);
2229 		arc_buf_destroy(buf, db);
2230 		xuio_stat_wbuf_copied();
2231 		return;
2232 	}
2233 
2234 	xuio_stat_wbuf_nocopy();
2235 	if (db->db_state == DB_CACHED) {
2236 		dbuf_dirty_record_t *dr = db->db_last_dirty;
2237 
2238 		ASSERT(db->db_buf != NULL);
2239 		if (dr != NULL && dr->dr_txg == tx->tx_txg) {
2240 			ASSERT(dr->dt.dl.dr_data == db->db_buf);
2241 
2242 			if (!arc_released(db->db_buf)) {
2243 				ASSERT(dr->dt.dl.dr_override_state ==
2244 				    DR_OVERRIDDEN);
2245 				arc_release(db->db_buf, db);
2246 			}
2247 			dr->dt.dl.dr_data = buf;
2248 			arc_buf_destroy(db->db_buf, db);
2249 		} else if (dr == NULL || dr->dt.dl.dr_data != db->db_buf) {
2250 			arc_release(db->db_buf, db);
2251 			arc_buf_destroy(db->db_buf, db);
2252 		}
2253 		db->db_buf = NULL;
2254 	}
2255 	ASSERT(db->db_buf == NULL);
2256 	dbuf_set_data(db, buf);
2257 	db->db_state = DB_FILL;
2258 	mutex_exit(&db->db_mtx);
2259 	(void) dbuf_dirty(db, tx);
2260 	dmu_buf_fill_done(&db->db, tx);
2261 }
2262 
2263 void
2264 dbuf_destroy(dmu_buf_impl_t *db)
2265 {
2266 	dnode_t *dn;
2267 	dmu_buf_impl_t *parent = db->db_parent;
2268 	dmu_buf_impl_t *dndb;
2269 
2270 	ASSERT(MUTEX_HELD(&db->db_mtx));
2271 	ASSERT(zfs_refcount_is_zero(&db->db_holds));
2272 
2273 	if (db->db_buf != NULL) {
2274 		arc_buf_destroy(db->db_buf, db);
2275 		db->db_buf = NULL;
2276 	}
2277 
2278 	if (db->db_blkid == DMU_BONUS_BLKID) {
2279 		int slots = DB_DNODE(db)->dn_num_slots;
2280 		int bonuslen = DN_SLOTS_TO_BONUSLEN(slots);
2281 		if (db->db.db_data != NULL) {
2282 			zio_buf_free(db->db.db_data, bonuslen);
2283 			arc_space_return(bonuslen, ARC_SPACE_BONUS);
2284 			db->db_state = DB_UNCACHED;
2285 		}
2286 	}
2287 
2288 	dbuf_clear_data(db);
2289 
2290 	if (multilist_link_active(&db->db_cache_link)) {
2291 		ASSERT(db->db_caching_status == DB_DBUF_CACHE ||
2292 		    db->db_caching_status == DB_DBUF_METADATA_CACHE);
2293 
2294 		multilist_remove(dbuf_caches[db->db_caching_status].cache, db);
2295 		(void) zfs_refcount_remove_many(
2296 		    &dbuf_caches[db->db_caching_status].size,
2297 		    db->db.db_size, db);
2298 
2299 		db->db_caching_status = DB_NO_CACHE;
2300 	}
2301 
2302 	ASSERT(db->db_state == DB_UNCACHED || db->db_state == DB_NOFILL);
2303 	ASSERT(db->db_data_pending == NULL);
2304 
2305 	db->db_state = DB_EVICTING;
2306 	db->db_blkptr = NULL;
2307 
2308 	/*
2309 	 * Now that db_state is DB_EVICTING, nobody else can find this via
2310 	 * the hash table.  We can now drop db_mtx, which allows us to
2311 	 * acquire the dn_dbufs_mtx.
2312 	 */
2313 	mutex_exit(&db->db_mtx);
2314 
2315 	DB_DNODE_ENTER(db);
2316 	dn = DB_DNODE(db);
2317 	dndb = dn->dn_dbuf;
2318 	if (db->db_blkid != DMU_BONUS_BLKID) {
2319 		boolean_t needlock = !MUTEX_HELD(&dn->dn_dbufs_mtx);
2320 		if (needlock)
2321 			mutex_enter(&dn->dn_dbufs_mtx);
2322 		avl_remove(&dn->dn_dbufs, db);
2323 		atomic_dec_32(&dn->dn_dbufs_count);
2324 		membar_producer();
2325 		DB_DNODE_EXIT(db);
2326 		if (needlock)
2327 			mutex_exit(&dn->dn_dbufs_mtx);
2328 		/*
2329 		 * Decrementing the dbuf count means that the hold corresponding
2330 		 * to the removed dbuf is no longer discounted in dnode_move(),
2331 		 * so the dnode cannot be moved until after we release the hold.
2332 		 * The membar_producer() ensures visibility of the decremented
2333 		 * value in dnode_move(), since DB_DNODE_EXIT doesn't actually
2334 		 * release any lock.
2335 		 */
2336 		mutex_enter(&dn->dn_mtx);
2337 		dnode_rele_and_unlock(dn, db, B_TRUE);
2338 		db->db_dnode_handle = NULL;
2339 
2340 		dbuf_hash_remove(db);
2341 	} else {
2342 		DB_DNODE_EXIT(db);
2343 	}
2344 
2345 	ASSERT(zfs_refcount_is_zero(&db->db_holds));
2346 
2347 	db->db_parent = NULL;
2348 
2349 	ASSERT(db->db_buf == NULL);
2350 	ASSERT(db->db.db_data == NULL);
2351 	ASSERT(db->db_hash_next == NULL);
2352 	ASSERT(db->db_blkptr == NULL);
2353 	ASSERT(db->db_data_pending == NULL);
2354 	ASSERT3U(db->db_caching_status, ==, DB_NO_CACHE);
2355 	ASSERT(!multilist_link_active(&db->db_cache_link));
2356 
2357 	kmem_cache_free(dbuf_kmem_cache, db);
2358 	arc_space_return(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
2359 
2360 	/*
2361 	 * If this dbuf is referenced from an indirect dbuf,
2362 	 * decrement the ref count on the indirect dbuf.
2363 	 */
2364 	if (parent && parent != dndb) {
2365 		mutex_enter(&parent->db_mtx);
2366 		dbuf_rele_and_unlock(parent, db, B_TRUE);
2367 	}
2368 }
2369 
2370 /*
2371  * Note: While bpp will always be updated if the function returns success,
2372  * parentp will not be updated if the dnode does not have dn_dbuf filled in;
2373  * this happens when the dnode is the meta-dnode, or a userused or groupused
2374  * object.
2375  */
2376 static int
2377 dbuf_findbp(dnode_t *dn, int level, uint64_t blkid, int fail_sparse,
2378     dmu_buf_impl_t **parentp, blkptr_t **bpp)
2379 {
2380 	*parentp = NULL;
2381 	*bpp = NULL;
2382 
2383 	ASSERT(blkid != DMU_BONUS_BLKID);
2384 
2385 	if (blkid == DMU_SPILL_BLKID) {
2386 		mutex_enter(&dn->dn_mtx);
2387 		if (dn->dn_have_spill &&
2388 		    (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR))
2389 			*bpp = DN_SPILL_BLKPTR(dn->dn_phys);
2390 		else
2391 			*bpp = NULL;
2392 		dbuf_add_ref(dn->dn_dbuf, NULL);
2393 		*parentp = dn->dn_dbuf;
2394 		mutex_exit(&dn->dn_mtx);
2395 		return (0);
2396 	}
2397 
2398 	int nlevels =
2399 	    (dn->dn_phys->dn_nlevels == 0) ? 1 : dn->dn_phys->dn_nlevels;
2400 	int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
2401 
2402 	ASSERT3U(level * epbs, <, 64);
2403 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2404 	/*
2405 	 * This assertion shouldn't trip as long as the max indirect block size
2406 	 * is less than 1M.  The reason for this is that up to that point,
2407 	 * the number of levels required to address an entire object with blocks
2408 	 * of size SPA_MINBLOCKSIZE satisfies nlevels * epbs + 1 <= 64.  In
2409 	 * other words, if N * epbs + 1 > 64, then if (N-1) * epbs + 1 > 55
2410 	 * (i.e. we can address the entire object), objects will all use at most
2411 	 * N-1 levels and the assertion won't overflow.  However, once epbs is
2412 	 * 13, 4 * 13 + 1 = 53, but 5 * 13 + 1 = 66.  Then, 4 levels will not be
2413 	 * enough to address an entire object, so objects will have 5 levels,
2414 	 * but then this assertion will overflow.
2415 	 *
2416 	 * All this is to say that if we ever increase DN_MAX_INDBLKSHIFT, we
2417 	 * need to redo this logic to handle overflows.
2418 	 */
2419 	ASSERT(level >= nlevels ||
2420 	    ((nlevels - level - 1) * epbs) +
2421 	    highbit64(dn->dn_phys->dn_nblkptr) <= 64);
2422 	if (level >= nlevels ||
2423 	    blkid >= ((uint64_t)dn->dn_phys->dn_nblkptr <<
2424 	    ((nlevels - level - 1) * epbs)) ||
2425 	    (fail_sparse &&
2426 	    blkid > (dn->dn_phys->dn_maxblkid >> (level * epbs)))) {
2427 		/* the buffer has no parent yet */
2428 		return (SET_ERROR(ENOENT));
2429 	} else if (level < nlevels-1) {
2430 		/* this block is referenced from an indirect block */
2431 		int err = dbuf_hold_impl(dn, level+1,
2432 		    blkid >> epbs, fail_sparse, FALSE, NULL, parentp);
2433 		if (err)
2434 			return (err);
2435 		err = dbuf_read(*parentp, NULL,
2436 		    (DB_RF_HAVESTRUCT | DB_RF_NOPREFETCH | DB_RF_CANFAIL));
2437 		if (err) {
2438 			dbuf_rele(*parentp, NULL);
2439 			*parentp = NULL;
2440 			return (err);
2441 		}
2442 		*bpp = ((blkptr_t *)(*parentp)->db.db_data) +
2443 		    (blkid & ((1ULL << epbs) - 1));
2444 		if (blkid > (dn->dn_phys->dn_maxblkid >> (level * epbs)))
2445 			ASSERT(BP_IS_HOLE(*bpp));
2446 		return (0);
2447 	} else {
2448 		/* the block is referenced from the dnode */
2449 		ASSERT3U(level, ==, nlevels-1);
2450 		ASSERT(dn->dn_phys->dn_nblkptr == 0 ||
2451 		    blkid < dn->dn_phys->dn_nblkptr);
2452 		if (dn->dn_dbuf) {
2453 			dbuf_add_ref(dn->dn_dbuf, NULL);
2454 			*parentp = dn->dn_dbuf;
2455 		}
2456 		*bpp = &dn->dn_phys->dn_blkptr[blkid];
2457 		return (0);
2458 	}
2459 }
2460 
2461 static dmu_buf_impl_t *
2462 dbuf_create(dnode_t *dn, uint8_t level, uint64_t blkid,
2463     dmu_buf_impl_t *parent, blkptr_t *blkptr)
2464 {
2465 	objset_t *os = dn->dn_objset;
2466 	dmu_buf_impl_t *db, *odb;
2467 
2468 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2469 	ASSERT(dn->dn_type != DMU_OT_NONE);
2470 
2471 	db = kmem_cache_alloc(dbuf_kmem_cache, KM_SLEEP);
2472 
2473 	db->db_objset = os;
2474 	db->db.db_object = dn->dn_object;
2475 	db->db_level = level;
2476 	db->db_blkid = blkid;
2477 	db->db_last_dirty = NULL;
2478 	db->db_dirtycnt = 0;
2479 	db->db_dnode_handle = dn->dn_handle;
2480 	db->db_parent = parent;
2481 	db->db_blkptr = blkptr;
2482 
2483 	db->db_user = NULL;
2484 	db->db_user_immediate_evict = FALSE;
2485 	db->db_freed_in_flight = FALSE;
2486 	db->db_pending_evict = FALSE;
2487 
2488 	if (blkid == DMU_BONUS_BLKID) {
2489 		ASSERT3P(parent, ==, dn->dn_dbuf);
2490 		db->db.db_size = DN_SLOTS_TO_BONUSLEN(dn->dn_num_slots) -
2491 		    (dn->dn_nblkptr-1) * sizeof (blkptr_t);
2492 		ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
2493 		db->db.db_offset = DMU_BONUS_BLKID;
2494 		db->db_state = DB_UNCACHED;
2495 		db->db_caching_status = DB_NO_CACHE;
2496 		/* the bonus dbuf is not placed in the hash table */
2497 		arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
2498 		return (db);
2499 	} else if (blkid == DMU_SPILL_BLKID) {
2500 		db->db.db_size = (blkptr != NULL) ?
2501 		    BP_GET_LSIZE(blkptr) : SPA_MINBLOCKSIZE;
2502 		db->db.db_offset = 0;
2503 	} else {
2504 		int blocksize =
2505 		    db->db_level ? 1 << dn->dn_indblkshift : dn->dn_datablksz;
2506 		db->db.db_size = blocksize;
2507 		db->db.db_offset = db->db_blkid * blocksize;
2508 	}
2509 
2510 	/*
2511 	 * Hold the dn_dbufs_mtx while we get the new dbuf
2512 	 * in the hash table *and* added to the dbufs list.
2513 	 * This prevents a possible deadlock with someone
2514 	 * trying to look up this dbuf before its added to the
2515 	 * dn_dbufs list.
2516 	 */
2517 	mutex_enter(&dn->dn_dbufs_mtx);
2518 	db->db_state = DB_EVICTING;
2519 	if ((odb = dbuf_hash_insert(db)) != NULL) {
2520 		/* someone else inserted it first */
2521 		kmem_cache_free(dbuf_kmem_cache, db);
2522 		mutex_exit(&dn->dn_dbufs_mtx);
2523 		return (odb);
2524 	}
2525 	avl_add(&dn->dn_dbufs, db);
2526 
2527 	db->db_state = DB_UNCACHED;
2528 	db->db_caching_status = DB_NO_CACHE;
2529 	mutex_exit(&dn->dn_dbufs_mtx);
2530 	arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
2531 
2532 	if (parent && parent != dn->dn_dbuf)
2533 		dbuf_add_ref(parent, db);
2534 
2535 	ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
2536 	    zfs_refcount_count(&dn->dn_holds) > 0);
2537 	(void) zfs_refcount_add(&dn->dn_holds, db);
2538 	atomic_inc_32(&dn->dn_dbufs_count);
2539 
2540 	dprintf_dbuf(db, "db=%p\n", db);
2541 
2542 	return (db);
2543 }
2544 
2545 typedef struct dbuf_prefetch_arg {
2546 	spa_t *dpa_spa;	/* The spa to issue the prefetch in. */
2547 	zbookmark_phys_t dpa_zb; /* The target block to prefetch. */
2548 	int dpa_epbs; /* Entries (blkptr_t's) Per Block Shift. */
2549 	int dpa_curlevel; /* The current level that we're reading */
2550 	dnode_t *dpa_dnode; /* The dnode associated with the prefetch */
2551 	zio_priority_t dpa_prio; /* The priority I/Os should be issued at. */
2552 	zio_t *dpa_zio; /* The parent zio_t for all prefetches. */
2553 	arc_flags_t dpa_aflags; /* Flags to pass to the final prefetch. */
2554 } dbuf_prefetch_arg_t;
2555 
2556 /*
2557  * Actually issue the prefetch read for the block given.
2558  */
2559 static void
2560 dbuf_issue_final_prefetch(dbuf_prefetch_arg_t *dpa, blkptr_t *bp)
2561 {
2562 	if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
2563 		return;
2564 
2565 	int zio_flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE;
2566 	arc_flags_t aflags =
2567 	    dpa->dpa_aflags | ARC_FLAG_NOWAIT | ARC_FLAG_PREFETCH;
2568 
2569 	/* dnodes are always read as raw and then converted later */
2570 	if (BP_GET_TYPE(bp) == DMU_OT_DNODE && BP_IS_PROTECTED(bp) &&
2571 	    dpa->dpa_curlevel == 0)
2572 		zio_flags |= ZIO_FLAG_RAW;
2573 
2574 	ASSERT3U(dpa->dpa_curlevel, ==, BP_GET_LEVEL(bp));
2575 	ASSERT3U(dpa->dpa_curlevel, ==, dpa->dpa_zb.zb_level);
2576 	ASSERT(dpa->dpa_zio != NULL);
2577 	(void) arc_read(dpa->dpa_zio, dpa->dpa_spa, bp, NULL, NULL,
2578 	    dpa->dpa_prio, zio_flags, &aflags, &dpa->dpa_zb);
2579 }
2580 
2581 /*
2582  * Called when an indirect block above our prefetch target is read in.  This
2583  * will either read in the next indirect block down the tree or issue the actual
2584  * prefetch if the next block down is our target.
2585  */
2586 /* ARGSUSED */
2587 static void
2588 dbuf_prefetch_indirect_done(zio_t *zio, const zbookmark_phys_t *zb,
2589     const blkptr_t *iobp, arc_buf_t *abuf, void *private)
2590 {
2591 	dbuf_prefetch_arg_t *dpa = private;
2592 
2593 	ASSERT3S(dpa->dpa_zb.zb_level, <, dpa->dpa_curlevel);
2594 	ASSERT3S(dpa->dpa_curlevel, >, 0);
2595 
2596 	if (abuf == NULL) {
2597 		ASSERT(zio == NULL || zio->io_error != 0);
2598 		kmem_free(dpa, sizeof (*dpa));
2599 		return;
2600 	}
2601 	ASSERT(zio == NULL || zio->io_error == 0);
2602 
2603 	/*
2604 	 * The dpa_dnode is only valid if we are called with a NULL
2605 	 * zio. This indicates that the arc_read() returned without
2606 	 * first calling zio_read() to issue a physical read. Once
2607 	 * a physical read is made the dpa_dnode must be invalidated
2608 	 * as the locks guarding it may have been dropped. If the
2609 	 * dpa_dnode is still valid, then we want to add it to the dbuf
2610 	 * cache. To do so, we must hold the dbuf associated with the block
2611 	 * we just prefetched, read its contents so that we associate it
2612 	 * with an arc_buf_t, and then release it.
2613 	 */
2614 	if (zio != NULL) {
2615 		ASSERT3S(BP_GET_LEVEL(zio->io_bp), ==, dpa->dpa_curlevel);
2616 		if (zio->io_flags & ZIO_FLAG_RAW_COMPRESS) {
2617 			ASSERT3U(BP_GET_PSIZE(zio->io_bp), ==, zio->io_size);
2618 		} else {
2619 			ASSERT3U(BP_GET_LSIZE(zio->io_bp), ==, zio->io_size);
2620 		}
2621 		ASSERT3P(zio->io_spa, ==, dpa->dpa_spa);
2622 
2623 		dpa->dpa_dnode = NULL;
2624 	} else if (dpa->dpa_dnode != NULL) {
2625 		uint64_t curblkid = dpa->dpa_zb.zb_blkid >>
2626 		    (dpa->dpa_epbs * (dpa->dpa_curlevel -
2627 		    dpa->dpa_zb.zb_level));
2628 		dmu_buf_impl_t *db = dbuf_hold_level(dpa->dpa_dnode,
2629 		    dpa->dpa_curlevel, curblkid, FTAG);
2630 		(void) dbuf_read(db, NULL,
2631 		    DB_RF_MUST_SUCCEED | DB_RF_NOPREFETCH | DB_RF_HAVESTRUCT);
2632 		dbuf_rele(db, FTAG);
2633 	}
2634 
2635 	dpa->dpa_curlevel--;
2636 	uint64_t nextblkid = dpa->dpa_zb.zb_blkid >>
2637 	    (dpa->dpa_epbs * (dpa->dpa_curlevel - dpa->dpa_zb.zb_level));
2638 	blkptr_t *bp = ((blkptr_t *)abuf->b_data) +
2639 	    P2PHASE(nextblkid, 1ULL << dpa->dpa_epbs);
2640 
2641 	if (BP_IS_HOLE(bp)) {
2642 		kmem_free(dpa, sizeof (*dpa));
2643 	} else if (dpa->dpa_curlevel == dpa->dpa_zb.zb_level) {
2644 		ASSERT3U(nextblkid, ==, dpa->dpa_zb.zb_blkid);
2645 		dbuf_issue_final_prefetch(dpa, bp);
2646 		kmem_free(dpa, sizeof (*dpa));
2647 	} else {
2648 		arc_flags_t iter_aflags = ARC_FLAG_NOWAIT;
2649 		zbookmark_phys_t zb;
2650 
2651 		/* flag if L2ARC eligible, l2arc_noprefetch then decides */
2652 		if (dpa->dpa_aflags & ARC_FLAG_L2CACHE)
2653 			iter_aflags |= ARC_FLAG_L2CACHE;
2654 
2655 		ASSERT3U(dpa->dpa_curlevel, ==, BP_GET_LEVEL(bp));
2656 
2657 		SET_BOOKMARK(&zb, dpa->dpa_zb.zb_objset,
2658 		    dpa->dpa_zb.zb_object, dpa->dpa_curlevel, nextblkid);
2659 
2660 		(void) arc_read(dpa->dpa_zio, dpa->dpa_spa,
2661 		    bp, dbuf_prefetch_indirect_done, dpa, dpa->dpa_prio,
2662 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
2663 		    &iter_aflags, &zb);
2664 	}
2665 
2666 	arc_buf_destroy(abuf, private);
2667 }
2668 
2669 /*
2670  * Issue prefetch reads for the given block on the given level.  If the indirect
2671  * blocks above that block are not in memory, we will read them in
2672  * asynchronously.  As a result, this call never blocks waiting for a read to
2673  * complete. Note that the prefetch might fail if the dataset is encrypted and
2674  * the encryption key is unmapped before the IO completes.
2675  */
2676 void
2677 dbuf_prefetch(dnode_t *dn, int64_t level, uint64_t blkid, zio_priority_t prio,
2678     arc_flags_t aflags)
2679 {
2680 	blkptr_t bp;
2681 	int epbs, nlevels, curlevel;
2682 	uint64_t curblkid;
2683 
2684 	ASSERT(blkid != DMU_BONUS_BLKID);
2685 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2686 
2687 	if (blkid > dn->dn_maxblkid)
2688 		return;
2689 
2690 	if (dnode_block_freed(dn, blkid))
2691 		return;
2692 
2693 	/*
2694 	 * This dnode hasn't been written to disk yet, so there's nothing to
2695 	 * prefetch.
2696 	 */
2697 	nlevels = dn->dn_phys->dn_nlevels;
2698 	if (level >= nlevels || dn->dn_phys->dn_nblkptr == 0)
2699 		return;
2700 
2701 	epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
2702 	if (dn->dn_phys->dn_maxblkid < blkid << (epbs * level))
2703 		return;
2704 
2705 	dmu_buf_impl_t *db = dbuf_find(dn->dn_objset, dn->dn_object,
2706 	    level, blkid);
2707 	if (db != NULL) {
2708 		mutex_exit(&db->db_mtx);
2709 		/*
2710 		 * This dbuf already exists.  It is either CACHED, or
2711 		 * (we assume) about to be read or filled.
2712 		 */
2713 		return;
2714 	}
2715 
2716 	/*
2717 	 * Find the closest ancestor (indirect block) of the target block
2718 	 * that is present in the cache.  In this indirect block, we will
2719 	 * find the bp that is at curlevel, curblkid.
2720 	 */
2721 	curlevel = level;
2722 	curblkid = blkid;
2723 	while (curlevel < nlevels - 1) {
2724 		int parent_level = curlevel + 1;
2725 		uint64_t parent_blkid = curblkid >> epbs;
2726 		dmu_buf_impl_t *db;
2727 
2728 		if (dbuf_hold_impl(dn, parent_level, parent_blkid,
2729 		    FALSE, TRUE, FTAG, &db) == 0) {
2730 			blkptr_t *bpp = db->db_buf->b_data;
2731 			bp = bpp[P2PHASE(curblkid, 1 << epbs)];
2732 			dbuf_rele(db, FTAG);
2733 			break;
2734 		}
2735 
2736 		curlevel = parent_level;
2737 		curblkid = parent_blkid;
2738 	}
2739 
2740 	if (curlevel == nlevels - 1) {
2741 		/* No cached indirect blocks found. */
2742 		ASSERT3U(curblkid, <, dn->dn_phys->dn_nblkptr);
2743 		bp = dn->dn_phys->dn_blkptr[curblkid];
2744 	}
2745 	if (BP_IS_HOLE(&bp))
2746 		return;
2747 
2748 	ASSERT3U(curlevel, ==, BP_GET_LEVEL(&bp));
2749 
2750 	zio_t *pio = zio_root(dmu_objset_spa(dn->dn_objset), NULL, NULL,
2751 	    ZIO_FLAG_CANFAIL);
2752 
2753 	dbuf_prefetch_arg_t *dpa = kmem_zalloc(sizeof (*dpa), KM_SLEEP);
2754 	dsl_dataset_t *ds = dn->dn_objset->os_dsl_dataset;
2755 	SET_BOOKMARK(&dpa->dpa_zb, ds != NULL ? ds->ds_object : DMU_META_OBJSET,
2756 	    dn->dn_object, level, blkid);
2757 	dpa->dpa_curlevel = curlevel;
2758 	dpa->dpa_prio = prio;
2759 	dpa->dpa_aflags = aflags;
2760 	dpa->dpa_spa = dn->dn_objset->os_spa;
2761 	dpa->dpa_dnode = dn;
2762 	dpa->dpa_epbs = epbs;
2763 	dpa->dpa_zio = pio;
2764 
2765 	/* flag if L2ARC eligible, l2arc_noprefetch then decides */
2766 	if (DNODE_LEVEL_IS_L2CACHEABLE(dn, level))
2767 		dpa->dpa_aflags |= ARC_FLAG_L2CACHE;
2768 
2769 	/*
2770 	 * If we have the indirect just above us, no need to do the asynchronous
2771 	 * prefetch chain; we'll just run the last step ourselves.  If we're at
2772 	 * a higher level, though, we want to issue the prefetches for all the
2773 	 * indirect blocks asynchronously, so we can go on with whatever we were
2774 	 * doing.
2775 	 */
2776 	if (curlevel == level) {
2777 		ASSERT3U(curblkid, ==, blkid);
2778 		dbuf_issue_final_prefetch(dpa, &bp);
2779 		kmem_free(dpa, sizeof (*dpa));
2780 	} else {
2781 		arc_flags_t iter_aflags = ARC_FLAG_NOWAIT;
2782 		zbookmark_phys_t zb;
2783 
2784 		/* flag if L2ARC eligible, l2arc_noprefetch then decides */
2785 		if (DNODE_LEVEL_IS_L2CACHEABLE(dn, level))
2786 			iter_aflags |= ARC_FLAG_L2CACHE;
2787 
2788 		SET_BOOKMARK(&zb, ds != NULL ? ds->ds_object : DMU_META_OBJSET,
2789 		    dn->dn_object, curlevel, curblkid);
2790 		(void) arc_read(dpa->dpa_zio, dpa->dpa_spa,
2791 		    &bp, dbuf_prefetch_indirect_done, dpa, prio,
2792 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
2793 		    &iter_aflags, &zb);
2794 	}
2795 	/*
2796 	 * We use pio here instead of dpa_zio since it's possible that
2797 	 * dpa may have already been freed.
2798 	 */
2799 	zio_nowait(pio);
2800 }
2801 
2802 /*
2803  * Helper function for __dbuf_hold_impl() to copy a buffer. Handles
2804  * the case of encrypted, compressed and uncompressed buffers by
2805  * allocating the new buffer, respectively, with arc_alloc_raw_buf(),
2806  * arc_alloc_compressed_buf() or arc_alloc_buf().*
2807  *
2808  * NOTE: Declared noinline to avoid stack bloat in __dbuf_hold_impl().
2809  */
2810 static void
2811 dbuf_hold_copy(dnode_t *dn,	dmu_buf_impl_t *db, dbuf_dirty_record_t *dr)
2812 {
2813 	arc_buf_t *data = dr->dt.dl.dr_data;
2814 	enum zio_compress compress_type = arc_get_compression(data);
2815 
2816 	if (arc_is_encrypted(data)) {
2817 		boolean_t byteorder;
2818 		uint8_t salt[ZIO_DATA_SALT_LEN];
2819 		uint8_t iv[ZIO_DATA_IV_LEN];
2820 		uint8_t mac[ZIO_DATA_MAC_LEN];
2821 
2822 		arc_get_raw_params(data, &byteorder, salt, iv, mac);
2823 		dbuf_set_data(db, arc_alloc_raw_buf(dn->dn_objset->os_spa, db,
2824 		    dmu_objset_id(dn->dn_objset), byteorder, salt, iv, mac,
2825 		    dn->dn_type, arc_buf_size(data), arc_buf_lsize(data),
2826 		    compress_type));
2827 	} else if (compress_type != ZIO_COMPRESS_OFF) {
2828 		dbuf_set_data(db, arc_alloc_compressed_buf(
2829 		    dn->dn_objset->os_spa, db, arc_buf_size(data),
2830 		    arc_buf_lsize(data), compress_type));
2831 	} else {
2832 		dbuf_set_data(db, arc_alloc_buf(dn->dn_objset->os_spa, db,
2833 		    DBUF_GET_BUFC_TYPE(db), db->db.db_size));
2834 	}
2835 
2836 	bcopy(data->b_data, db->db.db_data, arc_buf_size(data));
2837 }
2838 
2839 /*
2840  * Returns with db_holds incremented, and db_mtx not held.
2841  * Note: dn_struct_rwlock must be held.
2842  */
2843 int
2844 dbuf_hold_impl(dnode_t *dn, uint8_t level, uint64_t blkid,
2845     boolean_t fail_sparse, boolean_t fail_uncached,
2846     void *tag, dmu_buf_impl_t **dbp)
2847 {
2848 	dmu_buf_impl_t *db, *parent = NULL;
2849 
2850 	ASSERT(blkid != DMU_BONUS_BLKID);
2851 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2852 	ASSERT3U(dn->dn_nlevels, >, level);
2853 
2854 	*dbp = NULL;
2855 top:
2856 	/* dbuf_find() returns with db_mtx held */
2857 	db = dbuf_find(dn->dn_objset, dn->dn_object, level, blkid);
2858 
2859 	if (db == NULL) {
2860 		blkptr_t *bp = NULL;
2861 		int err;
2862 
2863 		if (fail_uncached)
2864 			return (SET_ERROR(ENOENT));
2865 
2866 		ASSERT3P(parent, ==, NULL);
2867 		err = dbuf_findbp(dn, level, blkid, fail_sparse, &parent, &bp);
2868 		if (fail_sparse) {
2869 			if (err == 0 && bp && BP_IS_HOLE(bp))
2870 				err = SET_ERROR(ENOENT);
2871 			if (err) {
2872 				if (parent)
2873