xref: /illumos-gate/usr/src/uts/common/fs/zfs/dbuf.c (revision eb633035c80613ec93d62f90482837adaaf21a0a)
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 					dbuf_rele(parent, NULL);
2874 				return (err);
2875 			}
2876 		}
2877 		if (err && err != ENOENT)
2878 			return (err);
2879 		db = dbuf_create(dn, level, blkid, parent, bp);
2880 	}
2881 
2882 	if (fail_uncached && db->db_state != DB_CACHED) {
2883 		mutex_exit(&db->db_mtx);
2884 		return (SET_ERROR(ENOENT));
2885 	}
2886 
2887 	if (db->db_buf != NULL) {
2888 		arc_buf_access(db->db_buf);
2889 		ASSERT3P(db->db.db_data, ==, db->db_buf->b_data);
2890 	}
2891 
2892 	ASSERT(db->db_buf == NULL || arc_referenced(db->db_buf));
2893 
2894 	/*
2895 	 * If this buffer is currently syncing out, and we are are
2896 	 * still referencing it from db_data, we need to make a copy
2897 	 * of it in case we decide we want to dirty it again in this txg.
2898 	 */
2899 	if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
2900 	    dn->dn_object != DMU_META_DNODE_OBJECT &&
2901 	    db->db_state == DB_CACHED && db->db_data_pending) {
2902 		dbuf_dirty_record_t *dr = db->db_data_pending;
2903 		if (dr->dt.dl.dr_data == db->db_buf)
2904 			dbuf_hold_copy(dn, db, dr);
2905 	}
2906 
2907 	if (multilist_link_active(&db->db_cache_link)) {
2908 		ASSERT(zfs_refcount_is_zero(&db->db_holds));
2909 		ASSERT(db->db_caching_status == DB_DBUF_CACHE ||
2910 		    db->db_caching_status == DB_DBUF_METADATA_CACHE);
2911 
2912 		multilist_remove(dbuf_caches[db->db_caching_status].cache, db);
2913 		(void) zfs_refcount_remove_many(
2914 		    &dbuf_caches[db->db_caching_status].size,
2915 		    db->db.db_size, db);
2916 
2917 		db->db_caching_status = DB_NO_CACHE;
2918 	}
2919 	(void) zfs_refcount_add(&db->db_holds, tag);
2920 	DBUF_VERIFY(db);
2921 	mutex_exit(&db->db_mtx);
2922 
2923 	/* NOTE: we can't rele the parent until after we drop the db_mtx */
2924 	if (parent)
2925 		dbuf_rele(parent, NULL);
2926 
2927 	ASSERT3P(DB_DNODE(db), ==, dn);
2928 	ASSERT3U(db->db_blkid, ==, blkid);
2929 	ASSERT3U(db->db_level, ==, level);
2930 	*dbp = db;
2931 
2932 	return (0);
2933 }
2934 
2935 dmu_buf_impl_t *
2936 dbuf_hold(dnode_t *dn, uint64_t blkid, void *tag)
2937 {
2938 	return (dbuf_hold_level(dn, 0, blkid, tag));
2939 }
2940 
2941 dmu_buf_impl_t *
2942 dbuf_hold_level(dnode_t *dn, int level, uint64_t blkid, void *tag)
2943 {
2944 	dmu_buf_impl_t *db;
2945 	int err = dbuf_hold_impl(dn, level, blkid, FALSE, FALSE, tag, &db);
2946 	return (err ? NULL : db);
2947 }
2948 
2949 void
2950 dbuf_create_bonus(dnode_t *dn)
2951 {
2952 	ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
2953 
2954 	ASSERT(dn->dn_bonus == NULL);
2955 	dn->dn_bonus = dbuf_create(dn, 0, DMU_BONUS_BLKID, dn->dn_dbuf, NULL);
2956 }
2957 
2958 int
2959 dbuf_spill_set_blksz(dmu_buf_t *db_fake, uint64_t blksz, dmu_tx_t *tx)
2960 {
2961 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2962 	dnode_t *dn;
2963 
2964 	if (db->db_blkid != DMU_SPILL_BLKID)
2965 		return (SET_ERROR(ENOTSUP));
2966 	if (blksz == 0)
2967 		blksz = SPA_MINBLOCKSIZE;
2968 	ASSERT3U(blksz, <=, spa_maxblocksize(dmu_objset_spa(db->db_objset)));
2969 	blksz = P2ROUNDUP(blksz, SPA_MINBLOCKSIZE);
2970 
2971 	DB_DNODE_ENTER(db);
2972 	dn = DB_DNODE(db);
2973 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
2974 	dbuf_new_size(db, blksz, tx);
2975 	rw_exit(&dn->dn_struct_rwlock);
2976 	DB_DNODE_EXIT(db);
2977 
2978 	return (0);
2979 }
2980 
2981 void
2982 dbuf_rm_spill(dnode_t *dn, dmu_tx_t *tx)
2983 {
2984 	dbuf_free_range(dn, DMU_SPILL_BLKID, DMU_SPILL_BLKID, tx);
2985 }
2986 
2987 #pragma weak dmu_buf_add_ref = dbuf_add_ref
2988 void
2989 dbuf_add_ref(dmu_buf_impl_t *db, void *tag)
2990 {
2991 	int64_t holds = zfs_refcount_add(&db->db_holds, tag);
2992 	ASSERT3S(holds, >, 1);
2993 }
2994 
2995 #pragma weak dmu_buf_try_add_ref = dbuf_try_add_ref
2996 boolean_t
2997 dbuf_try_add_ref(dmu_buf_t *db_fake, objset_t *os, uint64_t obj, uint64_t blkid,
2998     void *tag)
2999 {
3000 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
3001 	dmu_buf_impl_t *found_db;
3002 	boolean_t result = B_FALSE;
3003 
3004 	if (db->db_blkid == DMU_BONUS_BLKID)
3005 		found_db = dbuf_find_bonus(os, obj);
3006 	else
3007 		found_db = dbuf_find(os, obj, 0, blkid);
3008 
3009 	if (found_db != NULL) {
3010 		if (db == found_db && dbuf_refcount(db) > db->db_dirtycnt) {
3011 			(void) zfs_refcount_add(&db->db_holds, tag);
3012 			result = B_TRUE;
3013 		}
3014 		mutex_exit(&db->db_mtx);
3015 	}
3016 	return (result);
3017 }
3018 
3019 /*
3020  * If you call dbuf_rele() you had better not be referencing the dnode handle
3021  * unless you have some other direct or indirect hold on the dnode. (An indirect
3022  * hold is a hold on one of the dnode's dbufs, including the bonus buffer.)
3023  * Without that, the dbuf_rele() could lead to a dnode_rele() followed by the
3024  * dnode's parent dbuf evicting its dnode handles.
3025  */
3026 void
3027 dbuf_rele(dmu_buf_impl_t *db, void *tag)
3028 {
3029 	mutex_enter(&db->db_mtx);
3030 	dbuf_rele_and_unlock(db, tag, B_FALSE);
3031 }
3032 
3033 void
3034 dmu_buf_rele(dmu_buf_t *db, void *tag)
3035 {
3036 	dbuf_rele((dmu_buf_impl_t *)db, tag);
3037 }
3038 
3039 /*
3040  * dbuf_rele() for an already-locked dbuf.  This is necessary to allow
3041  * db_dirtycnt and db_holds to be updated atomically.  The 'evicting'
3042  * argument should be set if we are already in the dbuf-evicting code
3043  * path, in which case we don't want to recursively evict.  This allows us to
3044  * avoid deeply nested stacks that would have a call flow similar to this:
3045  *
3046  * dbuf_rele()-->dbuf_rele_and_unlock()-->dbuf_evict_notify()
3047  *	^						|
3048  *	|						|
3049  *	+-----dbuf_destroy()<--dbuf_evict_one()<--------+
3050  *
3051  */
3052 void
3053 dbuf_rele_and_unlock(dmu_buf_impl_t *db, void *tag, boolean_t evicting)
3054 {
3055 	int64_t holds;
3056 
3057 	ASSERT(MUTEX_HELD(&db->db_mtx));
3058 	DBUF_VERIFY(db);
3059 
3060 	/*
3061 	 * Remove the reference to the dbuf before removing its hold on the
3062 	 * dnode so we can guarantee in dnode_move() that a referenced bonus
3063 	 * buffer has a corresponding dnode hold.
3064 	 */
3065 	holds = zfs_refcount_remove(&db->db_holds, tag);
3066 	ASSERT(holds >= 0);
3067 
3068 	/*
3069 	 * We can't freeze indirects if there is a possibility that they
3070 	 * may be modified in the current syncing context.
3071 	 */
3072 	if (db->db_buf != NULL &&
3073 	    holds == (db->db_level == 0 ? db->db_dirtycnt : 0)) {
3074 		arc_buf_freeze(db->db_buf);
3075 	}
3076 
3077 	if (holds == db->db_dirtycnt &&
3078 	    db->db_level == 0 && db->db_user_immediate_evict)
3079 		dbuf_evict_user(db);
3080 
3081 	if (holds == 0) {
3082 		if (db->db_blkid == DMU_BONUS_BLKID) {
3083 			dnode_t *dn;
3084 			boolean_t evict_dbuf = db->db_pending_evict;
3085 
3086 			/*
3087 			 * If the dnode moves here, we cannot cross this
3088 			 * barrier until the move completes.
3089 			 */
3090 			DB_DNODE_ENTER(db);
3091 
3092 			dn = DB_DNODE(db);
3093 			atomic_dec_32(&dn->dn_dbufs_count);
3094 
3095 			/*
3096 			 * Decrementing the dbuf count means that the bonus
3097 			 * buffer's dnode hold is no longer discounted in
3098 			 * dnode_move(). The dnode cannot move until after
3099 			 * the dnode_rele() below.
3100 			 */
3101 			DB_DNODE_EXIT(db);
3102 
3103 			/*
3104 			 * Do not reference db after its lock is dropped.
3105 			 * Another thread may evict it.
3106 			 */
3107 			mutex_exit(&db->db_mtx);
3108 
3109 			if (evict_dbuf)
3110 				dnode_evict_bonus(dn);
3111 
3112 			dnode_rele(dn, db);
3113 		} else if (db->db_buf == NULL) {
3114 			/*
3115 			 * This is a special case: we never associated this
3116 			 * dbuf with any data allocated from the ARC.
3117 			 */
3118 			ASSERT(db->db_state == DB_UNCACHED ||
3119 			    db->db_state == DB_NOFILL);
3120 			dbuf_destroy(db);
3121 		} else if (arc_released(db->db_buf)) {
3122 			/*
3123 			 * This dbuf has anonymous data associated with it.
3124 			 */
3125 			dbuf_destroy(db);
3126 		} else {
3127 			boolean_t do_arc_evict = B_FALSE;
3128 			blkptr_t bp;
3129 			spa_t *spa = dmu_objset_spa(db->db_objset);
3130 
3131 			if (!DBUF_IS_CACHEABLE(db) &&
3132 			    db->db_blkptr != NULL &&
3133 			    !BP_IS_HOLE(db->db_blkptr) &&
3134 			    !BP_IS_EMBEDDED(db->db_blkptr)) {
3135 				do_arc_evict = B_TRUE;
3136 				bp = *db->db_blkptr;
3137 			}
3138 
3139 			if (!DBUF_IS_CACHEABLE(db) ||
3140 			    db->db_pending_evict) {
3141 				dbuf_destroy(db);
3142 			} else if (!multilist_link_active(&db->db_cache_link)) {
3143 				ASSERT3U(db->db_caching_status, ==,
3144 				    DB_NO_CACHE);
3145 
3146 				dbuf_cached_state_t dcs =
3147 				    dbuf_include_in_metadata_cache(db) ?
3148 				    DB_DBUF_METADATA_CACHE : DB_DBUF_CACHE;
3149 				db->db_caching_status = dcs;
3150 
3151 				multilist_insert(dbuf_caches[dcs].cache, db);
3152 				(void) zfs_refcount_add_many(
3153 				    &dbuf_caches[dcs].size, db->db.db_size, db);
3154 				mutex_exit(&db->db_mtx);
3155 
3156 				if (db->db_caching_status == DB_DBUF_CACHE &&
3157 				    !evicting) {
3158 					dbuf_evict_notify();
3159 				}
3160 			}
3161 
3162 			if (do_arc_evict)
3163 				arc_freed(spa, &bp);
3164 		}
3165 	} else {
3166 		mutex_exit(&db->db_mtx);
3167 	}
3168 
3169 }
3170 
3171 #pragma weak dmu_buf_refcount = dbuf_refcount
3172 uint64_t
3173 dbuf_refcount(dmu_buf_impl_t *db)
3174 {
3175 	return (zfs_refcount_count(&db->db_holds));
3176 }
3177 
3178 uint64_t
3179 dmu_buf_user_refcount(dmu_buf_t *db_fake)
3180 {
3181 	uint64_t holds;
3182 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
3183 
3184 	mutex_enter(&db->db_mtx);
3185 	ASSERT3U(zfs_refcount_count(&db->db_holds), >=, db->db_dirtycnt);
3186 	holds = zfs_refcount_count(&db->db_holds) - db->db_dirtycnt;
3187 	mutex_exit(&db->db_mtx);
3188 
3189 	return (holds);
3190 }
3191 
3192 void *
3193 dmu_buf_replace_user(dmu_buf_t *db_fake, dmu_buf_user_t *old_user,
3194     dmu_buf_user_t *new_user)
3195 {
3196 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
3197 
3198 	mutex_enter(&db->db_mtx);
3199 	dbuf_verify_user(db, DBVU_NOT_EVICTING);
3200 	if (db->db_user == old_user)
3201 		db->db_user = new_user;
3202 	else
3203 		old_user = db->db_user;
3204 	dbuf_verify_user(db, DBVU_NOT_EVICTING);
3205 	mutex_exit(&db->db_mtx);
3206 
3207 	return (old_user);
3208 }
3209 
3210 void *
3211 dmu_buf_set_user(dmu_buf_t *db_fake, dmu_buf_user_t *user)
3212 {
3213 	return (dmu_buf_replace_user(db_fake, NULL, user));
3214 }
3215 
3216 void *
3217 dmu_buf_set_user_ie(dmu_buf_t *db_fake, dmu_buf_user_t *user)
3218 {
3219 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
3220 
3221 	db->db_user_immediate_evict = TRUE;
3222 	return (dmu_buf_set_user(db_fake, user));
3223 }
3224 
3225 void *
3226 dmu_buf_remove_user(dmu_buf_t *db_fake, dmu_buf_user_t *user)
3227 {
3228 	return (dmu_buf_replace_user(db_fake, user, NULL));
3229 }
3230 
3231 void *
3232 dmu_buf_get_user(dmu_buf_t *db_fake)
3233 {
3234 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
3235 
3236 	dbuf_verify_user(db, DBVU_NOT_EVICTING);
3237 	return (db->db_user);
3238 }
3239 
3240 void
3241 dmu_buf_user_evict_wait()
3242 {
3243 	taskq_wait(dbu_evict_taskq);
3244 }
3245 
3246 blkptr_t *
3247 dmu_buf_get_blkptr(dmu_buf_t *db)
3248 {
3249 	dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
3250 	return (dbi->db_blkptr);
3251 }
3252 
3253 objset_t *
3254 dmu_buf_get_objset(dmu_buf_t *db)
3255 {
3256 	dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
3257 	return (dbi->db_objset);
3258 }
3259 
3260 dnode_t *
3261 dmu_buf_dnode_enter(dmu_buf_t *db)
3262 {
3263 	dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
3264 	DB_DNODE_ENTER(dbi);
3265 	return (DB_DNODE(dbi));
3266 }
3267 
3268 void
3269 dmu_buf_dnode_exit(dmu_buf_t *db)
3270 {
3271 	dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
3272 	DB_DNODE_EXIT(dbi);
3273 }
3274 
3275 static void
3276 dbuf_check_blkptr(dnode_t *dn, dmu_buf_impl_t *db)
3277 {
3278 	/* ASSERT(dmu_tx_is_syncing(tx) */
3279 	ASSERT(MUTEX_HELD(&db->db_mtx));
3280 
3281 	if (db->db_blkptr != NULL)
3282 		return;
3283 
3284 	if (db->db_blkid == DMU_SPILL_BLKID) {
3285 		db->db_blkptr = DN_SPILL_BLKPTR(dn->dn_phys);
3286 		BP_ZERO(db->db_blkptr);
3287 		return;
3288 	}
3289 	if (db->db_level == dn->dn_phys->dn_nlevels-1) {
3290 		/*
3291 		 * This buffer was allocated at a time when there was
3292 		 * no available blkptrs from the dnode, or it was
3293 		 * inappropriate to hook it in (i.e., nlevels mis-match).
3294 		 */
3295 		ASSERT(db->db_blkid < dn->dn_phys->dn_nblkptr);
3296 		ASSERT(db->db_parent == NULL);
3297 		db->db_parent = dn->dn_dbuf;
3298 		db->db_blkptr = &dn->dn_phys->dn_blkptr[db->db_blkid];
3299 		DBUF_VERIFY(db);
3300 	} else {
3301 		dmu_buf_impl_t *parent = db->db_parent;
3302 		int epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
3303 
3304 		ASSERT(dn->dn_phys->dn_nlevels > 1);
3305 		if (parent == NULL) {
3306 			mutex_exit(&db->db_mtx);
3307 			rw_enter(&dn->dn_struct_rwlock, RW_READER);
3308 			parent = dbuf_hold_level(dn, db->db_level + 1,
3309 			    db->db_blkid >> epbs, db);
3310 			rw_exit(&dn->dn_struct_rwlock);
3311 			mutex_enter(&db->db_mtx);
3312 			db->db_parent = parent;
3313 		}
3314 		db->db_blkptr = (blkptr_t *)parent->db.db_data +
3315 		    (db->db_blkid & ((1ULL << epbs) - 1));
3316 		DBUF_VERIFY(db);
3317 	}
3318 }
3319 
3320 /*
3321  * When syncing out blocks of dnodes, adjust the block to deal with
3322  * encryption.  Normally, we make sure the block is decrypted before writing
3323  * it.  If we have crypt params, then we are writing a raw (encrypted) block,
3324  * from a raw receive.  In this case, set the ARC buf's crypt params so
3325  * that the BP will be filled with the correct byteorder, salt, iv, and mac.
3326  *
3327  * XXX we should handle decrypting the dnode block in dbuf_dirty().
3328  */
3329 static void
3330 dbuf_prepare_encrypted_dnode_leaf(dbuf_dirty_record_t *dr)
3331 {
3332 	int err;
3333 	dmu_buf_impl_t *db = dr->dr_dbuf;
3334 
3335 	ASSERT(MUTEX_HELD(&db->db_mtx));
3336 	ASSERT3U(db->db.db_object, ==, DMU_META_DNODE_OBJECT);
3337 	ASSERT3U(db->db_level, ==, 0);
3338 
3339 	if (!db->db_objset->os_raw_receive && arc_is_encrypted(db->db_buf)) {
3340 		zbookmark_phys_t zb;
3341 
3342 		/*
3343 		 * Unfortunately, there is currently no mechanism for
3344 		 * syncing context to handle decryption errors. An error
3345 		 * here is only possible if an attacker maliciously
3346 		 * changed a dnode block and updated the associated
3347 		 * checksums going up the block tree.
3348 		 */
3349 		SET_BOOKMARK(&zb, dmu_objset_id(db->db_objset),
3350 		    db->db.db_object, db->db_level, db->db_blkid);
3351 		err = arc_untransform(db->db_buf, db->db_objset->os_spa,
3352 		    &zb, B_TRUE);
3353 		if (err)
3354 			panic("Invalid dnode block MAC");
3355 	} else if (dr->dt.dl.dr_has_raw_params) {
3356 		(void) arc_release(dr->dt.dl.dr_data, db);
3357 		arc_convert_to_raw(dr->dt.dl.dr_data,
3358 		    dmu_objset_id(db->db_objset),
3359 		    dr->dt.dl.dr_byteorder, DMU_OT_DNODE,
3360 		    dr->dt.dl.dr_salt, dr->dt.dl.dr_iv, dr->dt.dl.dr_mac);
3361 	}
3362 }
3363 
3364 static void
3365 dbuf_sync_indirect(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
3366 {
3367 	dmu_buf_impl_t *db = dr->dr_dbuf;
3368 	dnode_t *dn;
3369 	zio_t *zio;
3370 
3371 	ASSERT(dmu_tx_is_syncing(tx));
3372 
3373 	dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
3374 
3375 	mutex_enter(&db->db_mtx);
3376 
3377 	ASSERT(db->db_level > 0);
3378 	DBUF_VERIFY(db);
3379 
3380 	/* Read the block if it hasn't been read yet. */
3381 	if (db->db_buf == NULL) {
3382 		mutex_exit(&db->db_mtx);
3383 		(void) dbuf_read(db, NULL, DB_RF_MUST_SUCCEED);
3384 		mutex_enter(&db->db_mtx);
3385 	}
3386 	ASSERT3U(db->db_state, ==, DB_CACHED);
3387 	ASSERT(db->db_buf != NULL);
3388 
3389 	DB_DNODE_ENTER(db);
3390 	dn = DB_DNODE(db);
3391 	/* Indirect block size must match what the dnode thinks it is. */
3392 	ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
3393 	dbuf_check_blkptr(dn, db);
3394 	DB_DNODE_EXIT(db);
3395 
3396 	/* Provide the pending dirty record to child dbufs */
3397 	db->db_data_pending = dr;
3398 
3399 	mutex_exit(&db->db_mtx);
3400 
3401 	dbuf_write(dr, db->db_buf, tx);
3402 
3403 	zio = dr->dr_zio;
3404 	mutex_enter(&dr->dt.di.dr_mtx);
3405 	dbuf_sync_list(&dr->dt.di.dr_children, db->db_level - 1, tx);
3406 	ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
3407 	mutex_exit(&dr->dt.di.dr_mtx);
3408 	zio_nowait(zio);
3409 }
3410 
3411 static void
3412 dbuf_sync_leaf(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
3413 {
3414 	arc_buf_t **datap = &dr->dt.dl.dr_data;
3415 	dmu_buf_impl_t *db = dr->dr_dbuf;
3416 	dnode_t *dn;
3417 	objset_t *os;
3418 	uint64_t txg = tx->tx_txg;
3419 
3420 	ASSERT(dmu_tx_is_syncing(tx));
3421 
3422 	dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
3423 
3424 	mutex_enter(&db->db_mtx);
3425 	/*
3426 	 * To be synced, we must be dirtied.  But we
3427 	 * might have been freed after the dirty.
3428 	 */
3429 	if (db->db_state == DB_UNCACHED) {
3430 		/* This buffer has been freed since it was dirtied */
3431 		ASSERT(db->db.db_data == NULL);
3432 	} else if (db->db_state == DB_FILL) {
3433 		/* This buffer was freed and is now being re-filled */
3434 		ASSERT(db->db.db_data != dr->dt.dl.dr_data);
3435 	} else {
3436 		ASSERT(db->db_state == DB_CACHED || db->db_state == DB_NOFILL);
3437 	}
3438 	DBUF_VERIFY(db);
3439 
3440 	DB_DNODE_ENTER(db);
3441 	dn = DB_DNODE(db);
3442 
3443 	if (db->db_blkid == DMU_SPILL_BLKID) {
3444 		mutex_enter(&dn->dn_mtx);
3445 		dn->dn_phys->dn_flags |= DNODE_FLAG_SPILL_BLKPTR;
3446 		mutex_exit(&dn->dn_mtx);
3447 	}
3448 
3449 	/*
3450 	 * If this is a bonus buffer, simply copy the bonus data into the
3451 	 * dnode.  It will be written out when the dnode is synced (and it
3452 	 * will be synced, since it must have been dirty for dbuf_sync to
3453 	 * be called).
3454 	 */
3455 	if (db->db_blkid == DMU_BONUS_BLKID) {
3456 		dbuf_dirty_record_t **drp;
3457 
3458 		ASSERT(*datap != NULL);
3459 		ASSERT0(db->db_level);
3460 		ASSERT3U(DN_MAX_BONUS_LEN(dn->dn_phys), <=,
3461 		    DN_SLOTS_TO_BONUSLEN(dn->dn_phys->dn_extra_slots + 1));
3462 		bcopy(*datap, DN_BONUS(dn->dn_phys),
3463 		    DN_MAX_BONUS_LEN(dn->dn_phys));
3464 		DB_DNODE_EXIT(db);
3465 
3466 		if (*datap != db->db.db_data) {
3467 			int slots = DB_DNODE(db)->dn_num_slots;
3468 			int bonuslen = DN_SLOTS_TO_BONUSLEN(slots);
3469 			zio_buf_free(*datap, bonuslen);
3470 			arc_space_return(bonuslen, ARC_SPACE_BONUS);
3471 		}
3472 		db->db_data_pending = NULL;
3473 		drp = &db->db_last_dirty;
3474 		while (*drp != dr)
3475 			drp = &(*drp)->dr_next;
3476 		ASSERT(dr->dr_next == NULL);
3477 		ASSERT(dr->dr_dbuf == db);
3478 		*drp = dr->dr_next;
3479 		kmem_free(dr, sizeof (dbuf_dirty_record_t));
3480 		ASSERT(db->db_dirtycnt > 0);
3481 		db->db_dirtycnt -= 1;
3482 		dbuf_rele_and_unlock(db, (void *)(uintptr_t)txg, B_FALSE);
3483 		return;
3484 	}
3485 
3486 	os = dn->dn_objset;
3487 
3488 	/*
3489 	 * This function may have dropped the db_mtx lock allowing a dmu_sync
3490 	 * operation to sneak in. As a result, we need to ensure that we
3491 	 * don't check the dr_override_state until we have returned from
3492 	 * dbuf_check_blkptr.
3493 	 */
3494 	dbuf_check_blkptr(dn, db);
3495 
3496 	/*
3497 	 * If this buffer is in the middle of an immediate write,
3498 	 * wait for the synchronous IO to complete.
3499 	 */
3500 	while (dr->dt.dl.dr_override_state == DR_IN_DMU_SYNC) {
3501 		ASSERT(dn->dn_object != DMU_META_DNODE_OBJECT);
3502 		cv_wait(&db->db_changed, &db->db_mtx);
3503 		ASSERT(dr->dt.dl.dr_override_state != DR_NOT_OVERRIDDEN);
3504 	}
3505 
3506 	/*
3507 	 * If this is a dnode block, ensure it is appropriately encrypted
3508 	 * or decrypted, depending on what we are writing to it this txg.
3509 	 */
3510 	if (os->os_encrypted && dn->dn_object == DMU_META_DNODE_OBJECT)
3511 		dbuf_prepare_encrypted_dnode_leaf(dr);
3512 
3513 	if (db->db_state != DB_NOFILL &&
3514 	    dn->dn_object != DMU_META_DNODE_OBJECT &&
3515 	    zfs_refcount_count(&db->db_holds) > 1 &&
3516 	    dr->dt.dl.dr_override_state != DR_OVERRIDDEN &&
3517 	    *datap == db->db_buf) {
3518 		/*
3519 		 * If this buffer is currently "in use" (i.e., there
3520 		 * are active holds and db_data still references it),
3521 		 * then make a copy before we start the write so that
3522 		 * any modifications from the open txg will not leak
3523 		 * into this write.
3524 		 *
3525 		 * NOTE: this copy does not need to be made for
3526 		 * objects only modified in the syncing context (e.g.
3527 		 * DNONE_DNODE blocks).
3528 		 */
3529 		int psize = arc_buf_size(*datap);
3530 		int lsize = arc_buf_lsize(*datap);
3531 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
3532 		enum zio_compress compress_type = arc_get_compression(*datap);
3533 
3534 		if (arc_is_encrypted(*datap)) {
3535 			boolean_t byteorder;
3536 			uint8_t salt[ZIO_DATA_SALT_LEN];
3537 			uint8_t iv[ZIO_DATA_IV_LEN];
3538 			uint8_t mac[ZIO_DATA_MAC_LEN];
3539 
3540 			arc_get_raw_params(*datap, &byteorder, salt, iv, mac);
3541 			*datap = arc_alloc_raw_buf(os->os_spa, db,
3542 			    dmu_objset_id(os), byteorder, salt, iv, mac,
3543 			    dn->dn_type, psize, lsize, compress_type);
3544 		} else if (compress_type != ZIO_COMPRESS_OFF) {
3545 			ASSERT3U(type, ==, ARC_BUFC_DATA);
3546 			*datap = arc_alloc_compressed_buf(os->os_spa, db,
3547 			    psize, lsize, compress_type);
3548 		} else {
3549 			*datap = arc_alloc_buf(os->os_spa, db, type, psize);
3550 		}
3551 		bcopy(db->db.db_data, (*datap)->b_data, psize);
3552 	}
3553 	db->db_data_pending = dr;
3554 
3555 	mutex_exit(&db->db_mtx);
3556 
3557 	dbuf_write(dr, *datap, tx);
3558 
3559 	ASSERT(!list_link_active(&dr->dr_dirty_node));
3560 	if (dn->dn_object == DMU_META_DNODE_OBJECT) {
3561 		list_insert_tail(&dn->dn_dirty_records[txg&TXG_MASK], dr);
3562 		DB_DNODE_EXIT(db);
3563 	} else {
3564 		/*
3565 		 * Although zio_nowait() does not "wait for an IO", it does
3566 		 * initiate the IO. If this is an empty write it seems plausible
3567 		 * that the IO could actually be completed before the nowait
3568 		 * returns. We need to DB_DNODE_EXIT() first in case
3569 		 * zio_nowait() invalidates the dbuf.
3570 		 */
3571 		DB_DNODE_EXIT(db);
3572 		zio_nowait(dr->dr_zio);
3573 	}
3574 }
3575 
3576 void
3577 dbuf_sync_list(list_t *list, int level, dmu_tx_t *tx)
3578 {
3579 	dbuf_dirty_record_t *dr;
3580 
3581 	while (dr = list_head(list)) {
3582 		if (dr->dr_zio != NULL) {
3583 			/*
3584 			 * If we find an already initialized zio then we
3585 			 * are processing the meta-dnode, and we have finished.
3586 			 * The dbufs for all dnodes are put back on the list
3587 			 * during processing, so that we can zio_wait()
3588 			 * these IOs after initiating all child IOs.
3589 			 */
3590 			ASSERT3U(dr->dr_dbuf->db.db_object, ==,
3591 			    DMU_META_DNODE_OBJECT);
3592 			break;
3593 		}
3594 		if (dr->dr_dbuf->db_blkid != DMU_BONUS_BLKID &&
3595 		    dr->dr_dbuf->db_blkid != DMU_SPILL_BLKID) {
3596 			VERIFY3U(dr->dr_dbuf->db_level, ==, level);
3597 		}
3598 		list_remove(list, dr);
3599 		if (dr->dr_dbuf->db_level > 0)
3600 			dbuf_sync_indirect(dr, tx);
3601 		else
3602 			dbuf_sync_leaf(dr, tx);
3603 	}
3604 }
3605 
3606 /* ARGSUSED */
3607 static void
3608 dbuf_write_ready(zio_t *zio, arc_buf_t *buf, void *vdb)
3609 {
3610 	dmu_buf_impl_t *db = vdb;
3611 	dnode_t *dn;
3612 	blkptr_t *bp = zio->io_bp;
3613 	blkptr_t *bp_orig = &zio->io_bp_orig;
3614 	spa_t *spa = zio->io_spa;
3615 	int64_t delta;
3616 	uint64_t fill = 0;
3617 	int i;
3618 
3619 	ASSERT3P(db->db_blkptr, !=, NULL);
3620 	ASSERT3P(&db->db_data_pending->dr_bp_copy, ==, bp);
3621 
3622 	DB_DNODE_ENTER(db);
3623 	dn = DB_DNODE(db);
3624 	delta = bp_get_dsize_sync(spa, bp) - bp_get_dsize_sync(spa, bp_orig);
3625 	dnode_diduse_space(dn, delta - zio->io_prev_space_delta);
3626 	zio->io_prev_space_delta = delta;
3627 
3628 	if (bp->blk_birth != 0) {
3629 		ASSERT((db->db_blkid != DMU_SPILL_BLKID &&
3630 		    BP_GET_TYPE(bp) == dn->dn_type) ||
3631 		    (db->db_blkid == DMU_SPILL_BLKID &&
3632 		    BP_GET_TYPE(bp) == dn->dn_bonustype) ||
3633 		    BP_IS_EMBEDDED(bp));
3634 		ASSERT(BP_GET_LEVEL(bp) == db->db_level);
3635 	}
3636 
3637 	mutex_enter(&db->db_mtx);
3638 
3639 #ifdef ZFS_DEBUG
3640 	if (db->db_blkid == DMU_SPILL_BLKID) {
3641 		ASSERT(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR);
3642 		ASSERT(!(BP_IS_HOLE(bp)) &&
3643 		    db->db_blkptr == DN_SPILL_BLKPTR(dn->dn_phys));
3644 	}
3645 #endif
3646 
3647 	if (db->db_level == 0) {
3648 		mutex_enter(&dn->dn_mtx);
3649 		if (db->db_blkid > dn->dn_phys->dn_maxblkid &&
3650 		    db->db_blkid != DMU_SPILL_BLKID) {
3651 			ASSERT0(db->db_objset->os_raw_receive);
3652 			dn->dn_phys->dn_maxblkid = db->db_blkid;
3653 		}
3654 		mutex_exit(&dn->dn_mtx);
3655 
3656 		if (dn->dn_type == DMU_OT_DNODE) {
3657 			i = 0;
3658 			while (i < db->db.db_size) {
3659 				dnode_phys_t *dnp =
3660 				    (void *)(((char *)db->db.db_data) + i);
3661 
3662 				i += DNODE_MIN_SIZE;
3663 				if (dnp->dn_type != DMU_OT_NONE) {
3664 					fill++;
3665 					i += dnp->dn_extra_slots *
3666 					    DNODE_MIN_SIZE;
3667 				}
3668 			}
3669 		} else {
3670 			if (BP_IS_HOLE(bp)) {
3671 				fill = 0;
3672 			} else {
3673 				fill = 1;
3674 			}
3675 		}
3676 	} else {
3677 		blkptr_t *ibp = db->db.db_data;
3678 		ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
3679 		for (i = db->db.db_size >> SPA_BLKPTRSHIFT; i > 0; i--, ibp++) {
3680 			if (BP_IS_HOLE(ibp))
3681 				continue;
3682 			fill += BP_GET_FILL(ibp);
3683 		}
3684 	}
3685 	DB_DNODE_EXIT(db);
3686 
3687 	if (!BP_IS_EMBEDDED(bp))
3688 		BP_SET_FILL(bp, fill);
3689 
3690 	mutex_exit(&db->db_mtx);
3691 
3692 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
3693 	*db->db_blkptr = *bp;
3694 	rw_exit(&dn->dn_struct_rwlock);
3695 }
3696 
3697 /* ARGSUSED */
3698 /*
3699  * This function gets called just prior to running through the compression
3700  * stage of the zio pipeline. If we're an indirect block comprised of only
3701  * holes, then we want this indirect to be compressed away to a hole. In
3702  * order to do that we must zero out any information about the holes that
3703  * this indirect points to prior to before we try to compress it.
3704  */
3705 static void
3706 dbuf_write_children_ready(zio_t *zio, arc_buf_t *buf, void *vdb)
3707 {
3708 	dmu_buf_impl_t *db = vdb;
3709 	dnode_t *dn;
3710 	blkptr_t *bp;
3711 	unsigned int epbs, i;
3712 
3713 	ASSERT3U(db->db_level, >, 0);
3714 	DB_DNODE_ENTER(db);
3715 	dn = DB_DNODE(db);
3716 	epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
3717 	ASSERT3U(epbs, <, 31);
3718 
3719 	/* Determine if all our children are holes */
3720 	for (i = 0, bp = db->db.db_data; i < 1 << epbs; i++, bp++) {
3721 		if (!BP_IS_HOLE(bp))
3722 			break;
3723 	}
3724 
3725 	/*
3726 	 * If all the children are holes, then zero them all out so that
3727 	 * we may get compressed away.
3728 	 */
3729 	if (i == 1 << epbs) {
3730 		/*
3731 		 * We only found holes. Grab the rwlock to prevent
3732 		 * anybody from reading the blocks we're about to
3733 		 * zero out.
3734 		 */
3735 		rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
3736 		bzero(db->db.db_data, db->db.db_size);
3737 		rw_exit(&dn->dn_struct_rwlock);
3738 	}
3739 	DB_DNODE_EXIT(db);
3740 }
3741 
3742 /*
3743  * The SPA will call this callback several times for each zio - once
3744  * for every physical child i/o (zio->io_phys_children times).  This
3745  * allows the DMU to monitor the progress of each logical i/o.  For example,
3746  * there may be 2 copies of an indirect block, or many fragments of a RAID-Z
3747  * block.  There may be a long delay before all copies/fragments are completed,
3748  * so this callback allows us to retire dirty space gradually, as the physical
3749  * i/os complete.
3750  */
3751 /* ARGSUSED */
3752 static void
3753 dbuf_write_physdone(zio_t *zio, arc_buf_t *buf, void *arg)
3754 {
3755 	dmu_buf_impl_t *db = arg;
3756 	objset_t *os = db->db_objset;
3757 	dsl_pool_t *dp = dmu_objset_pool(os);
3758 	dbuf_dirty_record_t *dr;
3759 	int delta = 0;
3760 
3761 	dr = db->db_data_pending;
3762 	ASSERT3U(dr->dr_txg, ==, zio->io_txg);
3763 
3764 	/*
3765 	 * The callback will be called io_phys_children times.  Retire one
3766 	 * portion of our dirty space each time we are called.  Any rounding
3767 	 * error will be cleaned up by dsl_pool_sync()'s call to
3768 	 * dsl_pool_undirty_space().
3769 	 */
3770 	delta = dr->dr_accounted / zio->io_phys_children;
3771 	dsl_pool_undirty_space(dp, delta, zio->io_txg);
3772 }
3773 
3774 /* ARGSUSED */
3775 static void
3776 dbuf_write_done(zio_t *zio, arc_buf_t *buf, void *vdb)
3777 {
3778 	dmu_buf_impl_t *db = vdb;
3779 	blkptr_t *bp_orig = &zio->io_bp_orig;
3780 	blkptr_t *bp = db->db_blkptr;
3781 	objset_t *os = db->db_objset;
3782 	dmu_tx_t *tx = os->os_synctx;
3783 	dbuf_dirty_record_t **drp, *dr;
3784 
3785 	ASSERT0(zio->io_error);
3786 	ASSERT(db->db_blkptr == bp);
3787 
3788 	/*
3789 	 * For nopwrites and rewrites we ensure that the bp matches our
3790 	 * original and bypass all the accounting.
3791 	 */
3792 	if (zio->io_flags & (ZIO_FLAG_IO_REWRITE | ZIO_FLAG_NOPWRITE)) {
3793 		ASSERT(BP_EQUAL(bp, bp_orig));
3794 	} else {
3795 		dsl_dataset_t *ds = os->os_dsl_dataset;
3796 		(void) dsl_dataset_block_kill(ds, bp_orig, tx, B_TRUE);
3797 		dsl_dataset_block_born(ds, bp, tx);
3798 	}
3799 
3800 	mutex_enter(&db->db_mtx);
3801 
3802 	DBUF_VERIFY(db);
3803 
3804 	drp = &db->db_last_dirty;
3805 	while ((dr = *drp) != db->db_data_pending)
3806 		drp = &dr->dr_next;
3807 	ASSERT(!list_link_active(&dr->dr_dirty_node));
3808 	ASSERT(dr->dr_dbuf == db);
3809 	ASSERT(dr->dr_next == NULL);
3810 	*drp = dr->dr_next;
3811 
3812 #ifdef ZFS_DEBUG
3813 	if (db->db_blkid == DMU_SPILL_BLKID) {
3814 		dnode_t *dn;
3815 
3816 		DB_DNODE_ENTER(db);
3817 		dn = DB_DNODE(db);
3818 		ASSERT(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR);
3819 		ASSERT(!(BP_IS_HOLE(db->db_blkptr)) &&
3820 		    db->db_blkptr == DN_SPILL_BLKPTR(dn->dn_phys));
3821 		DB_DNODE_EXIT(db);
3822 	}
3823 #endif
3824 
3825 	if (db->db_level == 0) {
3826 		ASSERT(db->db_blkid != DMU_BONUS_BLKID);
3827 		ASSERT(dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN);
3828 		if (db->db_state != DB_NOFILL) {
3829 			if (dr->dt.dl.dr_data != db->db_buf)
3830 				arc_buf_destroy(dr->dt.dl.dr_data, db);
3831 		}
3832 	} else {
3833 		dnode_t *dn;
3834 
3835 		DB_DNODE_ENTER(db);
3836 		dn = DB_DNODE(db);
3837 		ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
3838 		ASSERT3U(db->db.db_size, ==, 1 << dn->dn_phys->dn_indblkshift);
3839 		if (!BP_IS_HOLE(db->db_blkptr)) {
3840 			int epbs =
3841 			    dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
3842 			ASSERT3U(db->db_blkid, <=,
3843 			    dn->dn_phys->dn_maxblkid >> (db->db_level * epbs));
3844 			ASSERT3U(BP_GET_LSIZE(db->db_blkptr), ==,
3845 			    db->db.db_size);
3846 		}
3847 		DB_DNODE_EXIT(db);
3848 		mutex_destroy(&dr->dt.di.dr_mtx);
3849 		list_destroy(&dr->dt.di.dr_children);
3850 	}
3851 	kmem_free(dr, sizeof (dbuf_dirty_record_t));
3852 
3853 	cv_broadcast(&db->db_changed);
3854 	ASSERT(db->db_dirtycnt > 0);
3855 	db->db_dirtycnt -= 1;
3856 	db->db_data_pending = NULL;
3857 	dbuf_rele_and_unlock(db, (void *)(uintptr_t)tx->tx_txg, B_FALSE);
3858 }
3859 
3860 static void
3861 dbuf_write_nofill_ready(zio_t *zio)
3862 {
3863 	dbuf_write_ready(zio, NULL, zio->io_private);
3864 }
3865 
3866 static void
3867 dbuf_write_nofill_done(zio_t *zio)
3868 {
3869 	dbuf_write_done(zio, NULL, zio->io_private);
3870 }
3871 
3872 static void
3873 dbuf_write_override_ready(zio_t *zio)
3874 {
3875 	dbuf_dirty_record_t *dr = zio->io_private;
3876 	dmu_buf_impl_t *db = dr->dr_dbuf;
3877 
3878 	dbuf_write_ready(zio, NULL, db);
3879 }
3880 
3881 static void
3882 dbuf_write_override_done(zio_t *zio)
3883 {
3884 	dbuf_dirty_record_t *dr = zio->io_private;
3885 	dmu_buf_impl_t *db = dr->dr_dbuf;
3886 	blkptr_t *obp = &dr->dt.dl.dr_overridden_by;
3887 
3888 	mutex_enter(&db->db_mtx);
3889 	if (!BP_EQUAL(zio->io_bp, obp)) {
3890 		if (!BP_IS_HOLE(obp))
3891 			dsl_free(spa_get_dsl(zio->io_spa), zio->io_txg, obp);
3892 		arc_release(dr->dt.dl.dr_data, db);
3893 	}
3894 	mutex_exit(&db->db_mtx);
3895 	dbuf_write_done(zio, NULL, db);
3896 
3897 	if (zio->io_abd != NULL)
3898 		abd_put(zio->io_abd);
3899 }
3900 
3901 typedef struct dbuf_remap_impl_callback_arg {
3902 	objset_t	*drica_os;
3903 	uint64_t	drica_blk_birth;
3904 	dmu_tx_t	*drica_tx;
3905 } dbuf_remap_impl_callback_arg_t;
3906 
3907 static void
3908 dbuf_remap_impl_callback(uint64_t vdev, uint64_t offset, uint64_t size,
3909     void *arg)
3910 {
3911 	dbuf_remap_impl_callback_arg_t *drica = arg;
3912 	objset_t *os = drica->drica_os;
3913 	spa_t *spa = dmu_objset_spa(os);
3914 	dmu_tx_t *tx = drica->drica_tx;
3915 
3916 	ASSERT(dsl_pool_sync_context(spa_get_dsl(spa)));
3917 
3918 	if (os == spa_meta_objset(spa)) {
3919 		spa_vdev_indirect_mark_obsolete(spa, vdev, offset, size, tx);
3920 	} else {
3921 		dsl_dataset_block_remapped(dmu_objset_ds(os), vdev, offset,
3922 		    size, drica->drica_blk_birth, tx);
3923 	}
3924 }
3925 
3926 static void
3927 dbuf_remap_impl(dnode_t *dn, blkptr_t *bp, dmu_tx_t *tx)
3928 {
3929 	blkptr_t bp_copy = *bp;
3930 	spa_t *spa = dmu_objset_spa(dn->dn_objset);
3931 	dbuf_remap_impl_callback_arg_t drica;
3932 
3933 	ASSERT(dsl_pool_sync_context(spa_get_dsl(spa)));
3934 
3935 	drica.drica_os = dn->dn_objset;
3936 	drica.drica_blk_birth = bp->blk_birth;
3937 	drica.drica_tx = tx;
3938 	if (spa_remap_blkptr(spa, &bp_copy, dbuf_remap_impl_callback,
3939 	    &drica)) {
3940 		/*
3941 		 * The struct_rwlock prevents dbuf_read_impl() from
3942 		 * dereferencing the BP while we are changing it.  To
3943 		 * avoid lock contention, only grab it when we are actually
3944 		 * changing the BP.
3945 		 */
3946 		rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
3947 		*bp = bp_copy;
3948 		rw_exit(&dn->dn_struct_rwlock);
3949 	}
3950 }
3951 
3952 /*
3953  * Returns true if a dbuf_remap would modify the dbuf. We do this by attempting
3954  * to remap a copy of every bp in the dbuf.
3955  */
3956 boolean_t
3957 dbuf_can_remap(const dmu_buf_impl_t *db)
3958 {
3959 	spa_t *spa = dmu_objset_spa(db->db_objset);
3960 	blkptr_t *bp = db->db.db_data;
3961 	boolean_t ret = B_FALSE;
3962 
3963 	ASSERT3U(db->db_level, >, 0);
3964 	ASSERT3S(db->db_state, ==, DB_CACHED);
3965 
3966 	ASSERT(spa_feature_is_active(spa, SPA_FEATURE_DEVICE_REMOVAL));
3967 
3968 	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3969 	for (int i = 0; i < db->db.db_size >> SPA_BLKPTRSHIFT; i++) {
3970 		blkptr_t bp_copy = bp[i];
3971 		if (spa_remap_blkptr(spa, &bp_copy, NULL, NULL)) {
3972 			ret = B_TRUE;
3973 			break;
3974 		}
3975 	}
3976 	spa_config_exit(spa, SCL_VDEV, FTAG);
3977 
3978 	return (ret);
3979 }
3980 
3981 boolean_t
3982 dnode_needs_remap(const dnode_t *dn)
3983 {
3984 	spa_t *spa = dmu_objset_spa(dn->dn_objset);
3985 	boolean_t ret = B_FALSE;
3986 
3987 	if (dn->dn_phys->dn_nlevels == 0) {
3988 		return (B_FALSE);
3989 	}
3990 
3991 	ASSERT(spa_feature_is_active(spa, SPA_FEATURE_DEVICE_REMOVAL));
3992 
3993 	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3994 	for (int j = 0; j < dn->dn_phys->dn_nblkptr; j++) {
3995 		blkptr_t bp_copy = dn->dn_phys->dn_blkptr[j];
3996 		if (spa_remap_blkptr(spa, &bp_copy, NULL, NULL)) {
3997 			ret = B_TRUE;
3998 			break;
3999 		}
4000 	}
4001 	spa_config_exit(spa, SCL_VDEV, FTAG);
4002 
4003 	return (ret);
4004 }
4005 
4006 /*
4007  * Remap any existing BP's to concrete vdevs, if possible.
4008  */
4009 static void
4010 dbuf_remap(dnode_t *dn, dmu_buf_impl_t *db, dmu_tx_t *tx)
4011 {
4012 	spa_t *spa = dmu_objset_spa(db->db_objset);
4013 	ASSERT(dsl_pool_sync_context(spa_get_dsl(spa)));
4014 
4015 	if (!spa_feature_is_active(spa, SPA_FEATURE_DEVICE_REMOVAL))
4016 		return;
4017 
4018 	if (db->db_level > 0) {
4019 		blkptr_t *bp = db->db.db_data;
4020 		for (int i = 0; i < db->db.db_size >> SPA_BLKPTRSHIFT; i++) {
4021 			dbuf_remap_impl(dn, &bp[i], tx);
4022 		}
4023 	} else if (db->db.db_object == DMU_META_DNODE_OBJECT) {
4024 		dnode_phys_t *dnp = db->db.db_data;
4025 		ASSERT3U(db->db_dnode_handle->dnh_dnode->dn_type, ==,
4026 		    DMU_OT_DNODE);
4027 		for (int i = 0; i < db->db.db_size >> DNODE_SHIFT; i++) {
4028 			for (int j = 0; j < dnp[i].dn_nblkptr; j++) {
4029 				dbuf_remap_impl(dn, &dnp[i].dn_blkptr[j], tx);
4030 			}
4031 		}
4032 	}
4033 }
4034 
4035 
4036 /* Issue I/O to commit a dirty buffer to disk. */
4037 static void
4038 dbuf_write(dbuf_dirty_record_t *dr, arc_buf_t *data, dmu_tx_t *tx)
4039 {
4040 	dmu_buf_impl_t *db = dr->dr_dbuf;
4041 	dnode_t *dn;
4042 	objset_t *os;
4043 	dmu_buf_impl_t *parent = db->db_parent;
4044 	uint64_t txg = tx->tx_txg;
4045 	zbookmark_phys_t zb;
4046 	zio_prop_t zp;
4047 	zio_t *zio;
4048 	int wp_flag = 0;
4049 
4050 	ASSERT(dmu_tx_is_syncing(tx));
4051 
4052 	DB_DNODE_ENTER(db);
4053 	dn = DB_DNODE(db);
4054 	os = dn->dn_objset;
4055 
4056 	if (db->db_state != DB_NOFILL) {
4057 		if (db->db_level > 0 || dn->dn_type == DMU_OT_DNODE) {
4058 			/*
4059 			 * Private object buffers are released here rather
4060 			 * than in dbuf_dirty() since they are only modified
4061 			 * in the syncing context and we don't want the
4062 			 * overhead of making multiple copies of the data.
4063 			 */
4064 			if (BP_IS_HOLE(db->db_blkptr)) {
4065 				arc_buf_thaw(data);
4066 			} else {
4067 				dbuf_release_bp(db);
4068 			}
4069 			dbuf_remap(dn, db, tx);
4070 		}
4071 	}
4072 
4073 	if (parent != dn->dn_dbuf) {
4074 		/* Our parent is an indirect block. */
4075 		/* We have a dirty parent that has been scheduled for write. */
4076 		ASSERT(parent && parent->db_data_pending);
4077 		/* Our parent's buffer is one level closer to the dnode. */
4078 		ASSERT(db->db_level == parent->db_level-1);
4079 		/*
4080 		 * We're about to modify our parent's db_data by modifying
4081 		 * our block pointer, so the parent must be released.
4082 		 */
4083 		ASSERT(arc_released(parent->db_buf));
4084 		zio = parent->db_data_pending->dr_zio;
4085 	} else {
4086 		/* Our parent is the dnode itself. */
4087 		ASSERT((db->db_level == dn->dn_phys->dn_nlevels-1 &&
4088 		    db->db_blkid != DMU_SPILL_BLKID) ||
4089 		    (db->db_blkid == DMU_SPILL_BLKID && db->db_level == 0));
4090 		if (db->db_blkid != DMU_SPILL_BLKID)
4091 			ASSERT3P(db->db_blkptr, ==,
4092 			    &dn->dn_phys->dn_blkptr[db->db_blkid]);
4093 		zio = dn->dn_zio;
4094 	}
4095 
4096 	ASSERT(db->db_level == 0 || data == db->db_buf);
4097 	ASSERT3U(db->db_blkptr->blk_birth, <=, txg);
4098 	ASSERT(zio);
4099 
4100 	SET_BOOKMARK(&zb, os->os_dsl_dataset ?
4101 	    os->os_dsl_dataset->ds_object : DMU_META_OBJSET,
4102 	    db->db.db_object, db->db_level, db->db_blkid);
4103 
4104 	if (db->db_blkid == DMU_SPILL_BLKID)
4105 		wp_flag = WP_SPILL;
4106 	wp_flag |= (db->db_state == DB_NOFILL) ? WP_NOFILL : 0;
4107 
4108 	dmu_write_policy(os, dn, db->db_level, wp_flag, &zp);
4109 
4110 	DB_DNODE_EXIT(db);
4111 
4112 	/*
4113 	 * We copy the blkptr now (rather than when we instantiate the dirty
4114 	 * record), because its value can change between open context and
4115 	 * syncing context. We do not need to hold dn_struct_rwlock to read
4116 	 * db_blkptr because we are in syncing context.
4117 	 */
4118 	dr->dr_bp_copy = *db->db_blkptr;
4119 
4120 	if (db->db_level == 0 &&
4121 	    dr->dt.dl.dr_override_state == DR_OVERRIDDEN) {
4122 		/*
4123 		 * The BP for this block has been provided by open context
4124 		 * (by dmu_sync() or dmu_buf_write_embedded()).
4125 		 */
4126 		abd_t *contents = (data != NULL) ?
4127 		    abd_get_from_buf(data->b_data, arc_buf_size(data)) : NULL;
4128 
4129 		dr->dr_zio = zio_write(zio, os->os_spa, txg, &dr->dr_bp_copy,
4130 		    contents, db->db.db_size, db->db.db_size, &zp,
4131 		    dbuf_write_override_ready, NULL, NULL,
4132 		    dbuf_write_override_done,
4133 		    dr, ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
4134 		mutex_enter(&db->db_mtx);
4135 		dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
4136 		zio_write_override(dr->dr_zio, &dr->dt.dl.dr_overridden_by,
4137 		    dr->dt.dl.dr_copies, dr->dt.dl.dr_nopwrite);
4138 		mutex_exit(&db->db_mtx);
4139 	} else if (db->db_state == DB_NOFILL) {
4140 		ASSERT(zp.zp_checksum == ZIO_CHECKSUM_OFF ||
4141 		    zp.zp_checksum == ZIO_CHECKSUM_NOPARITY);
4142 		dr->dr_zio = zio_write(zio, os->os_spa, txg,
4143 		    &dr->dr_bp_copy, NULL, db->db.db_size, db->db.db_size, &zp,
4144 		    dbuf_write_nofill_ready, NULL, NULL,
4145 		    dbuf_write_nofill_done, db,
4146 		    ZIO_PRIORITY_ASYNC_WRITE,
4147 		    ZIO_FLAG_MUSTSUCCEED | ZIO_FLAG_NODATA, &zb);
4148 	} else {
4149 		ASSERT(arc_released(data));
4150 
4151 		/*
4152 		 * For indirect blocks, we want to setup the children
4153 		 * ready callback so that we can properly handle an indirect
4154 		 * block that only contains holes.
4155 		 */
4156 		arc_write_done_func_t *children_ready_cb = NULL;
4157 		if (db->db_level != 0)
4158 			children_ready_cb = dbuf_write_children_ready;
4159 
4160 		dr->dr_zio = arc_write(zio, os->os_spa, txg,
4161 		    &dr->dr_bp_copy, data, DBUF_IS_L2CACHEABLE(db),
4162 		    &zp, dbuf_write_ready, children_ready_cb,
4163 		    dbuf_write_physdone, dbuf_write_done, db,
4164 		    ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
4165 	}
4166 }
4167