xref: /illumos-gate/usr/src/uts/common/fs/zfs/dbuf.c (revision e0f1c0afa46cc84d4b1e40124032a9a87310386e)
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 elments 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 musn'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) {
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 static void
945 dbuf_read_done(zio_t *zio, arc_buf_t *buf, void *vdb)
946 {
947 	dmu_buf_impl_t *db = vdb;
948 
949 	mutex_enter(&db->db_mtx);
950 	ASSERT3U(db->db_state, ==, DB_READ);
951 	/*
952 	 * All reads are synchronous, so we must have a hold on the dbuf
953 	 */
954 	ASSERT(zfs_refcount_count(&db->db_holds) > 0);
955 	ASSERT(db->db_buf == NULL);
956 	ASSERT(db->db.db_data == NULL);
957 	if (buf == NULL) {
958 		/* i/o error */
959 		ASSERT(zio == NULL || zio->io_error != 0);
960 		ASSERT(db->db_blkid != DMU_BONUS_BLKID);
961 		ASSERT3P(db->db_buf, ==, NULL);
962 		db->db_state = DB_UNCACHED;
963 	} else if (db->db_level == 0 && db->db_freed_in_flight) {
964 		/* freed in flight */
965 		ASSERT(zio == NULL || zio->io_error == 0);
966 		arc_release(buf, db);
967 		bzero(buf->b_data, db->db.db_size);
968 		arc_buf_freeze(buf);
969 		db->db_freed_in_flight = FALSE;
970 		dbuf_set_data(db, buf);
971 		db->db_state = DB_CACHED;
972 	} else {
973 		/* success */
974 		ASSERT(zio == NULL || zio->io_error == 0);
975 		dbuf_set_data(db, buf);
976 		db->db_state = DB_CACHED;
977 	}
978 	cv_broadcast(&db->db_changed);
979 	dbuf_rele_and_unlock(db, NULL, B_FALSE);
980 }
981 
982 static void
983 dbuf_read_impl(dmu_buf_impl_t *db, zio_t *zio, uint32_t flags)
984 {
985 	dnode_t *dn;
986 	zbookmark_phys_t zb;
987 	arc_flags_t aflags = ARC_FLAG_NOWAIT;
988 
989 	DB_DNODE_ENTER(db);
990 	dn = DB_DNODE(db);
991 	ASSERT(!zfs_refcount_is_zero(&db->db_holds));
992 	/* We need the struct_rwlock to prevent db_blkptr from changing. */
993 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
994 	ASSERT(MUTEX_HELD(&db->db_mtx));
995 	ASSERT(db->db_state == DB_UNCACHED);
996 	ASSERT(db->db_buf == NULL);
997 
998 	if (db->db_blkid == DMU_BONUS_BLKID) {
999 		/*
1000 		 * The bonus length stored in the dnode may be less than
1001 		 * the maximum available space in the bonus buffer.
1002 		 */
1003 		int bonuslen = MIN(dn->dn_bonuslen, dn->dn_phys->dn_bonuslen);
1004 		int max_bonuslen = DN_SLOTS_TO_BONUSLEN(dn->dn_num_slots);
1005 
1006 		ASSERT3U(bonuslen, <=, db->db.db_size);
1007 		db->db.db_data = zio_buf_alloc(max_bonuslen);
1008 		arc_space_consume(max_bonuslen, ARC_SPACE_BONUS);
1009 		if (bonuslen < max_bonuslen)
1010 			bzero(db->db.db_data, max_bonuslen);
1011 		if (bonuslen)
1012 			bcopy(DN_BONUS(dn->dn_phys), db->db.db_data, bonuslen);
1013 		DB_DNODE_EXIT(db);
1014 		db->db_state = DB_CACHED;
1015 		mutex_exit(&db->db_mtx);
1016 		return;
1017 	}
1018 
1019 	/*
1020 	 * Recheck BP_IS_HOLE() after dnode_block_freed() in case dnode_sync()
1021 	 * processes the delete record and clears the bp while we are waiting
1022 	 * for the dn_mtx (resulting in a "no" from block_freed).
1023 	 */
1024 	if (db->db_blkptr == NULL || BP_IS_HOLE(db->db_blkptr) ||
1025 	    (db->db_level == 0 && (dnode_block_freed(dn, db->db_blkid) ||
1026 	    BP_IS_HOLE(db->db_blkptr)))) {
1027 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1028 
1029 		dbuf_set_data(db, arc_alloc_buf(db->db_objset->os_spa, db, type,
1030 		    db->db.db_size));
1031 		bzero(db->db.db_data, db->db.db_size);
1032 
1033 		if (db->db_blkptr != NULL && db->db_level > 0 &&
1034 		    BP_IS_HOLE(db->db_blkptr) &&
1035 		    db->db_blkptr->blk_birth != 0) {
1036 			blkptr_t *bps = db->db.db_data;
1037 			for (int i = 0; i < ((1 <<
1038 			    DB_DNODE(db)->dn_indblkshift) / sizeof (blkptr_t));
1039 			    i++) {
1040 				blkptr_t *bp = &bps[i];
1041 				ASSERT3U(BP_GET_LSIZE(db->db_blkptr), ==,
1042 				    1 << dn->dn_indblkshift);
1043 				BP_SET_LSIZE(bp,
1044 				    BP_GET_LEVEL(db->db_blkptr) == 1 ?
1045 				    dn->dn_datablksz :
1046 				    BP_GET_LSIZE(db->db_blkptr));
1047 				BP_SET_TYPE(bp, BP_GET_TYPE(db->db_blkptr));
1048 				BP_SET_LEVEL(bp,
1049 				    BP_GET_LEVEL(db->db_blkptr) - 1);
1050 				BP_SET_BIRTH(bp, db->db_blkptr->blk_birth, 0);
1051 			}
1052 		}
1053 		DB_DNODE_EXIT(db);
1054 		db->db_state = DB_CACHED;
1055 		mutex_exit(&db->db_mtx);
1056 		return;
1057 	}
1058 
1059 	DB_DNODE_EXIT(db);
1060 
1061 	db->db_state = DB_READ;
1062 	mutex_exit(&db->db_mtx);
1063 
1064 	if (DBUF_IS_L2CACHEABLE(db))
1065 		aflags |= ARC_FLAG_L2CACHE;
1066 
1067 	SET_BOOKMARK(&zb, db->db_objset->os_dsl_dataset ?
1068 	    db->db_objset->os_dsl_dataset->ds_object : DMU_META_OBJSET,
1069 	    db->db.db_object, db->db_level, db->db_blkid);
1070 
1071 	dbuf_add_ref(db, NULL);
1072 
1073 	(void) arc_read(zio, db->db_objset->os_spa, db->db_blkptr,
1074 	    dbuf_read_done, db, ZIO_PRIORITY_SYNC_READ,
1075 	    (flags & DB_RF_CANFAIL) ? ZIO_FLAG_CANFAIL : ZIO_FLAG_MUSTSUCCEED,
1076 	    &aflags, &zb);
1077 }
1078 
1079 /*
1080  * This is our just-in-time copy function.  It makes a copy of buffers that
1081  * have been modified in a previous transaction group before we access them in
1082  * the current active group.
1083  *
1084  * This function is used in three places: when we are dirtying a buffer for the
1085  * first time in a txg, when we are freeing a range in a dnode that includes
1086  * this buffer, and when we are accessing a buffer which was received compressed
1087  * and later referenced in a WRITE_BYREF record.
1088  *
1089  * Note that when we are called from dbuf_free_range() we do not put a hold on
1090  * the buffer, we just traverse the active dbuf list for the dnode.
1091  */
1092 static void
1093 dbuf_fix_old_data(dmu_buf_impl_t *db, uint64_t txg)
1094 {
1095 	dbuf_dirty_record_t *dr = db->db_last_dirty;
1096 
1097 	ASSERT(MUTEX_HELD(&db->db_mtx));
1098 	ASSERT(db->db.db_data != NULL);
1099 	ASSERT(db->db_level == 0);
1100 	ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT);
1101 
1102 	if (dr == NULL ||
1103 	    (dr->dt.dl.dr_data !=
1104 	    ((db->db_blkid  == DMU_BONUS_BLKID) ? db->db.db_data : db->db_buf)))
1105 		return;
1106 
1107 	/*
1108 	 * If the last dirty record for this dbuf has not yet synced
1109 	 * and its referencing the dbuf data, either:
1110 	 *	reset the reference to point to a new copy,
1111 	 * or (if there a no active holders)
1112 	 *	just null out the current db_data pointer.
1113 	 */
1114 	ASSERT(dr->dr_txg >= txg - 2);
1115 	if (db->db_blkid == DMU_BONUS_BLKID) {
1116 		/* Note that the data bufs here are zio_bufs */
1117 		dnode_t *dn = DB_DNODE(db);
1118 		int bonuslen = DN_SLOTS_TO_BONUSLEN(dn->dn_num_slots);
1119 		dr->dt.dl.dr_data = zio_buf_alloc(bonuslen);
1120 		arc_space_consume(bonuslen, ARC_SPACE_BONUS);
1121 		bcopy(db->db.db_data, dr->dt.dl.dr_data, bonuslen);
1122 	} else if (zfs_refcount_count(&db->db_holds) > db->db_dirtycnt) {
1123 		int size = arc_buf_size(db->db_buf);
1124 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1125 		spa_t *spa = db->db_objset->os_spa;
1126 		enum zio_compress compress_type =
1127 		    arc_get_compression(db->db_buf);
1128 
1129 		if (compress_type == ZIO_COMPRESS_OFF) {
1130 			dr->dt.dl.dr_data = arc_alloc_buf(spa, db, type, size);
1131 		} else {
1132 			ASSERT3U(type, ==, ARC_BUFC_DATA);
1133 			dr->dt.dl.dr_data = arc_alloc_compressed_buf(spa, db,
1134 			    size, arc_buf_lsize(db->db_buf), compress_type);
1135 		}
1136 		bcopy(db->db.db_data, dr->dt.dl.dr_data->b_data, size);
1137 	} else {
1138 		db->db_buf = NULL;
1139 		dbuf_clear_data(db);
1140 	}
1141 }
1142 
1143 int
1144 dbuf_read(dmu_buf_impl_t *db, zio_t *zio, uint32_t flags)
1145 {
1146 	int err = 0;
1147 	boolean_t prefetch;
1148 	dnode_t *dn;
1149 
1150 	/*
1151 	 * We don't have to hold the mutex to check db_state because it
1152 	 * can't be freed while we have a hold on the buffer.
1153 	 */
1154 	ASSERT(!zfs_refcount_is_zero(&db->db_holds));
1155 
1156 	if (db->db_state == DB_NOFILL)
1157 		return (SET_ERROR(EIO));
1158 
1159 	DB_DNODE_ENTER(db);
1160 	dn = DB_DNODE(db);
1161 	if ((flags & DB_RF_HAVESTRUCT) == 0)
1162 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
1163 
1164 	prefetch = db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
1165 	    (flags & DB_RF_NOPREFETCH) == 0 && dn != NULL &&
1166 	    DBUF_IS_CACHEABLE(db);
1167 
1168 	mutex_enter(&db->db_mtx);
1169 	if (db->db_state == DB_CACHED) {
1170 		/*
1171 		 * If the arc buf is compressed, we need to decompress it to
1172 		 * read the data. This could happen during the "zfs receive" of
1173 		 * a stream which is compressed and deduplicated.
1174 		 */
1175 		if (db->db_buf != NULL &&
1176 		    arc_get_compression(db->db_buf) != ZIO_COMPRESS_OFF) {
1177 			dbuf_fix_old_data(db,
1178 			    spa_syncing_txg(dmu_objset_spa(db->db_objset)));
1179 			err = arc_decompress(db->db_buf);
1180 			dbuf_set_data(db, db->db_buf);
1181 		}
1182 		mutex_exit(&db->db_mtx);
1183 		if (prefetch)
1184 			dmu_zfetch(&dn->dn_zfetch, db->db_blkid, 1, B_TRUE);
1185 		if ((flags & DB_RF_HAVESTRUCT) == 0)
1186 			rw_exit(&dn->dn_struct_rwlock);
1187 		DB_DNODE_EXIT(db);
1188 	} else if (db->db_state == DB_UNCACHED) {
1189 		spa_t *spa = dn->dn_objset->os_spa;
1190 		boolean_t need_wait = B_FALSE;
1191 
1192 		if (zio == NULL &&
1193 		    db->db_blkptr != NULL && !BP_IS_HOLE(db->db_blkptr)) {
1194 			zio = zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL);
1195 			need_wait = B_TRUE;
1196 		}
1197 		dbuf_read_impl(db, zio, flags);
1198 
1199 		/* dbuf_read_impl has dropped db_mtx for us */
1200 
1201 		if (prefetch)
1202 			dmu_zfetch(&dn->dn_zfetch, db->db_blkid, 1, B_TRUE);
1203 
1204 		if ((flags & DB_RF_HAVESTRUCT) == 0)
1205 			rw_exit(&dn->dn_struct_rwlock);
1206 		DB_DNODE_EXIT(db);
1207 
1208 		if (need_wait)
1209 			err = zio_wait(zio);
1210 	} else {
1211 		/*
1212 		 * Another reader came in while the dbuf was in flight
1213 		 * between UNCACHED and CACHED.  Either a writer will finish
1214 		 * writing the buffer (sending the dbuf to CACHED) or the
1215 		 * first reader's request will reach the read_done callback
1216 		 * and send the dbuf to CACHED.  Otherwise, a failure
1217 		 * occurred and the dbuf went to UNCACHED.
1218 		 */
1219 		mutex_exit(&db->db_mtx);
1220 		if (prefetch)
1221 			dmu_zfetch(&dn->dn_zfetch, db->db_blkid, 1, B_TRUE);
1222 		if ((flags & DB_RF_HAVESTRUCT) == 0)
1223 			rw_exit(&dn->dn_struct_rwlock);
1224 		DB_DNODE_EXIT(db);
1225 
1226 		/* Skip the wait per the caller's request. */
1227 		mutex_enter(&db->db_mtx);
1228 		if ((flags & DB_RF_NEVERWAIT) == 0) {
1229 			while (db->db_state == DB_READ ||
1230 			    db->db_state == DB_FILL) {
1231 				ASSERT(db->db_state == DB_READ ||
1232 				    (flags & DB_RF_HAVESTRUCT) == 0);
1233 				DTRACE_PROBE2(blocked__read, dmu_buf_impl_t *,
1234 				    db, zio_t *, zio);
1235 				cv_wait(&db->db_changed, &db->db_mtx);
1236 			}
1237 			if (db->db_state == DB_UNCACHED)
1238 				err = SET_ERROR(EIO);
1239 		}
1240 		mutex_exit(&db->db_mtx);
1241 	}
1242 
1243 	return (err);
1244 }
1245 
1246 static void
1247 dbuf_noread(dmu_buf_impl_t *db)
1248 {
1249 	ASSERT(!zfs_refcount_is_zero(&db->db_holds));
1250 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1251 	mutex_enter(&db->db_mtx);
1252 	while (db->db_state == DB_READ || db->db_state == DB_FILL)
1253 		cv_wait(&db->db_changed, &db->db_mtx);
1254 	if (db->db_state == DB_UNCACHED) {
1255 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1256 		spa_t *spa = db->db_objset->os_spa;
1257 
1258 		ASSERT(db->db_buf == NULL);
1259 		ASSERT(db->db.db_data == NULL);
1260 		dbuf_set_data(db, arc_alloc_buf(spa, db, type, db->db.db_size));
1261 		db->db_state = DB_FILL;
1262 	} else if (db->db_state == DB_NOFILL) {
1263 		dbuf_clear_data(db);
1264 	} else {
1265 		ASSERT3U(db->db_state, ==, DB_CACHED);
1266 	}
1267 	mutex_exit(&db->db_mtx);
1268 }
1269 
1270 void
1271 dbuf_unoverride(dbuf_dirty_record_t *dr)
1272 {
1273 	dmu_buf_impl_t *db = dr->dr_dbuf;
1274 	blkptr_t *bp = &dr->dt.dl.dr_overridden_by;
1275 	uint64_t txg = dr->dr_txg;
1276 
1277 	ASSERT(MUTEX_HELD(&db->db_mtx));
1278 	/*
1279 	 * This assert is valid because dmu_sync() expects to be called by
1280 	 * a zilog's get_data while holding a range lock.  This call only
1281 	 * comes from dbuf_dirty() callers who must also hold a range lock.
1282 	 */
1283 	ASSERT(dr->dt.dl.dr_override_state != DR_IN_DMU_SYNC);
1284 	ASSERT(db->db_level == 0);
1285 
1286 	if (db->db_blkid == DMU_BONUS_BLKID ||
1287 	    dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN)
1288 		return;
1289 
1290 	ASSERT(db->db_data_pending != dr);
1291 
1292 	/* free this block */
1293 	if (!BP_IS_HOLE(bp) && !dr->dt.dl.dr_nopwrite)
1294 		zio_free(db->db_objset->os_spa, txg, bp);
1295 
1296 	dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
1297 	dr->dt.dl.dr_nopwrite = B_FALSE;
1298 
1299 	/*
1300 	 * Release the already-written buffer, so we leave it in
1301 	 * a consistent dirty state.  Note that all callers are
1302 	 * modifying the buffer, so they will immediately do
1303 	 * another (redundant) arc_release().  Therefore, leave
1304 	 * the buf thawed to save the effort of freezing &
1305 	 * immediately re-thawing it.
1306 	 */
1307 	arc_release(dr->dt.dl.dr_data, db);
1308 }
1309 
1310 /*
1311  * Evict (if its unreferenced) or clear (if its referenced) any level-0
1312  * data blocks in the free range, so that any future readers will find
1313  * empty blocks.
1314  */
1315 void
1316 dbuf_free_range(dnode_t *dn, uint64_t start_blkid, uint64_t end_blkid,
1317     dmu_tx_t *tx)
1318 {
1319 	dmu_buf_impl_t db_search;
1320 	dmu_buf_impl_t *db, *db_next;
1321 	uint64_t txg = tx->tx_txg;
1322 	avl_index_t where;
1323 
1324 	if (end_blkid > dn->dn_maxblkid &&
1325 	    !(start_blkid == DMU_SPILL_BLKID || end_blkid == DMU_SPILL_BLKID))
1326 		end_blkid = dn->dn_maxblkid;
1327 	dprintf_dnode(dn, "start=%llu end=%llu\n", start_blkid, end_blkid);
1328 
1329 	db_search.db_level = 0;
1330 	db_search.db_blkid = start_blkid;
1331 	db_search.db_state = DB_SEARCH;
1332 
1333 	mutex_enter(&dn->dn_dbufs_mtx);
1334 	db = avl_find(&dn->dn_dbufs, &db_search, &where);
1335 	ASSERT3P(db, ==, NULL);
1336 
1337 	db = avl_nearest(&dn->dn_dbufs, where, AVL_AFTER);
1338 
1339 	for (; db != NULL; db = db_next) {
1340 		db_next = AVL_NEXT(&dn->dn_dbufs, db);
1341 		ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1342 
1343 		if (db->db_level != 0 || db->db_blkid > end_blkid) {
1344 			break;
1345 		}
1346 		ASSERT3U(db->db_blkid, >=, start_blkid);
1347 
1348 		/* found a level 0 buffer in the range */
1349 		mutex_enter(&db->db_mtx);
1350 		if (dbuf_undirty(db, tx)) {
1351 			/* mutex has been dropped and dbuf destroyed */
1352 			continue;
1353 		}
1354 
1355 		if (db->db_state == DB_UNCACHED ||
1356 		    db->db_state == DB_NOFILL ||
1357 		    db->db_state == DB_EVICTING) {
1358 			ASSERT(db->db.db_data == NULL);
1359 			mutex_exit(&db->db_mtx);
1360 			continue;
1361 		}
1362 		if (db->db_state == DB_READ || db->db_state == DB_FILL) {
1363 			/* will be handled in dbuf_read_done or dbuf_rele */
1364 			db->db_freed_in_flight = TRUE;
1365 			mutex_exit(&db->db_mtx);
1366 			continue;
1367 		}
1368 		if (zfs_refcount_count(&db->db_holds) == 0) {
1369 			ASSERT(db->db_buf);
1370 			dbuf_destroy(db);
1371 			continue;
1372 		}
1373 		/* The dbuf is referenced */
1374 
1375 		if (db->db_last_dirty != NULL) {
1376 			dbuf_dirty_record_t *dr = db->db_last_dirty;
1377 
1378 			if (dr->dr_txg == txg) {
1379 				/*
1380 				 * This buffer is "in-use", re-adjust the file
1381 				 * size to reflect that this buffer may
1382 				 * contain new data when we sync.
1383 				 */
1384 				if (db->db_blkid != DMU_SPILL_BLKID &&
1385 				    db->db_blkid > dn->dn_maxblkid)
1386 					dn->dn_maxblkid = db->db_blkid;
1387 				dbuf_unoverride(dr);
1388 			} else {
1389 				/*
1390 				 * This dbuf is not dirty in the open context.
1391 				 * Either uncache it (if its not referenced in
1392 				 * the open context) or reset its contents to
1393 				 * empty.
1394 				 */
1395 				dbuf_fix_old_data(db, txg);
1396 			}
1397 		}
1398 		/* clear the contents if its cached */
1399 		if (db->db_state == DB_CACHED) {
1400 			ASSERT(db->db.db_data != NULL);
1401 			arc_release(db->db_buf, db);
1402 			bzero(db->db.db_data, db->db.db_size);
1403 			arc_buf_freeze(db->db_buf);
1404 		}
1405 
1406 		mutex_exit(&db->db_mtx);
1407 	}
1408 	mutex_exit(&dn->dn_dbufs_mtx);
1409 }
1410 
1411 void
1412 dbuf_new_size(dmu_buf_impl_t *db, int size, dmu_tx_t *tx)
1413 {
1414 	arc_buf_t *buf, *obuf;
1415 	int osize = db->db.db_size;
1416 	arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1417 	dnode_t *dn;
1418 
1419 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1420 
1421 	DB_DNODE_ENTER(db);
1422 	dn = DB_DNODE(db);
1423 
1424 	/* XXX does *this* func really need the lock? */
1425 	ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
1426 
1427 	/*
1428 	 * This call to dmu_buf_will_dirty() with the dn_struct_rwlock held
1429 	 * is OK, because there can be no other references to the db
1430 	 * when we are changing its size, so no concurrent DB_FILL can
1431 	 * be happening.
1432 	 */
1433 	/*
1434 	 * XXX we should be doing a dbuf_read, checking the return
1435 	 * value and returning that up to our callers
1436 	 */
1437 	dmu_buf_will_dirty(&db->db, tx);
1438 
1439 	/* create the data buffer for the new block */
1440 	buf = arc_alloc_buf(dn->dn_objset->os_spa, db, type, size);
1441 
1442 	/* copy old block data to the new block */
1443 	obuf = db->db_buf;
1444 	bcopy(obuf->b_data, buf->b_data, MIN(osize, size));
1445 	/* zero the remainder */
1446 	if (size > osize)
1447 		bzero((uint8_t *)buf->b_data + osize, size - osize);
1448 
1449 	mutex_enter(&db->db_mtx);
1450 	dbuf_set_data(db, buf);
1451 	arc_buf_destroy(obuf, db);
1452 	db->db.db_size = size;
1453 
1454 	if (db->db_level == 0) {
1455 		ASSERT3U(db->db_last_dirty->dr_txg, ==, tx->tx_txg);
1456 		db->db_last_dirty->dt.dl.dr_data = buf;
1457 	}
1458 	mutex_exit(&db->db_mtx);
1459 
1460 	dmu_objset_willuse_space(dn->dn_objset, size - osize, tx);
1461 	DB_DNODE_EXIT(db);
1462 }
1463 
1464 void
1465 dbuf_release_bp(dmu_buf_impl_t *db)
1466 {
1467 	objset_t *os = db->db_objset;
1468 
1469 	ASSERT(dsl_pool_sync_context(dmu_objset_pool(os)));
1470 	ASSERT(arc_released(os->os_phys_buf) ||
1471 	    list_link_active(&os->os_dsl_dataset->ds_synced_link));
1472 	ASSERT(db->db_parent == NULL || arc_released(db->db_parent->db_buf));
1473 
1474 	(void) arc_release(db->db_buf, db);
1475 }
1476 
1477 /*
1478  * We already have a dirty record for this TXG, and we are being
1479  * dirtied again.
1480  */
1481 static void
1482 dbuf_redirty(dbuf_dirty_record_t *dr)
1483 {
1484 	dmu_buf_impl_t *db = dr->dr_dbuf;
1485 
1486 	ASSERT(MUTEX_HELD(&db->db_mtx));
1487 
1488 	if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID) {
1489 		/*
1490 		 * If this buffer has already been written out,
1491 		 * we now need to reset its state.
1492 		 */
1493 		dbuf_unoverride(dr);
1494 		if (db->db.db_object != DMU_META_DNODE_OBJECT &&
1495 		    db->db_state != DB_NOFILL) {
1496 			/* Already released on initial dirty, so just thaw. */
1497 			ASSERT(arc_released(db->db_buf));
1498 			arc_buf_thaw(db->db_buf);
1499 		}
1500 	}
1501 }
1502 
1503 dbuf_dirty_record_t *
1504 dbuf_dirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
1505 {
1506 	dnode_t *dn;
1507 	objset_t *os;
1508 	dbuf_dirty_record_t **drp, *dr;
1509 	int drop_struct_lock = FALSE;
1510 	int txgoff = tx->tx_txg & TXG_MASK;
1511 
1512 	ASSERT(tx->tx_txg != 0);
1513 	ASSERT(!zfs_refcount_is_zero(&db->db_holds));
1514 	DMU_TX_DIRTY_BUF(tx, db);
1515 
1516 	DB_DNODE_ENTER(db);
1517 	dn = DB_DNODE(db);
1518 	/*
1519 	 * Shouldn't dirty a regular buffer in syncing context.  Private
1520 	 * objects may be dirtied in syncing context, but only if they
1521 	 * were already pre-dirtied in open context.
1522 	 */
1523 #ifdef DEBUG
1524 	if (dn->dn_objset->os_dsl_dataset != NULL) {
1525 		rrw_enter(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock,
1526 		    RW_READER, FTAG);
1527 	}
1528 	ASSERT(!dmu_tx_is_syncing(tx) ||
1529 	    BP_IS_HOLE(dn->dn_objset->os_rootbp) ||
1530 	    DMU_OBJECT_IS_SPECIAL(dn->dn_object) ||
1531 	    dn->dn_objset->os_dsl_dataset == NULL);
1532 	if (dn->dn_objset->os_dsl_dataset != NULL)
1533 		rrw_exit(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock, FTAG);
1534 #endif
1535 	/*
1536 	 * We make this assert for private objects as well, but after we
1537 	 * check if we're already dirty.  They are allowed to re-dirty
1538 	 * in syncing context.
1539 	 */
1540 	ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
1541 	    dn->dn_dirtyctx == DN_UNDIRTIED || dn->dn_dirtyctx ==
1542 	    (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN));
1543 
1544 	mutex_enter(&db->db_mtx);
1545 	/*
1546 	 * XXX make this true for indirects too?  The problem is that
1547 	 * transactions created with dmu_tx_create_assigned() from
1548 	 * syncing context don't bother holding ahead.
1549 	 */
1550 	ASSERT(db->db_level != 0 ||
1551 	    db->db_state == DB_CACHED || db->db_state == DB_FILL ||
1552 	    db->db_state == DB_NOFILL);
1553 
1554 	mutex_enter(&dn->dn_mtx);
1555 	/*
1556 	 * Don't set dirtyctx to SYNC if we're just modifying this as we
1557 	 * initialize the objset.
1558 	 */
1559 	if (dn->dn_dirtyctx == DN_UNDIRTIED) {
1560 		if (dn->dn_objset->os_dsl_dataset != NULL) {
1561 			rrw_enter(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock,
1562 			    RW_READER, FTAG);
1563 		}
1564 		if (!BP_IS_HOLE(dn->dn_objset->os_rootbp)) {
1565 			dn->dn_dirtyctx = (dmu_tx_is_syncing(tx) ?
1566 			    DN_DIRTY_SYNC : DN_DIRTY_OPEN);
1567 			ASSERT(dn->dn_dirtyctx_firstset == NULL);
1568 			dn->dn_dirtyctx_firstset = kmem_alloc(1, KM_SLEEP);
1569 		}
1570 		if (dn->dn_objset->os_dsl_dataset != NULL) {
1571 			rrw_exit(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock,
1572 			    FTAG);
1573 		}
1574 	}
1575 
1576 	if (tx->tx_txg > dn->dn_dirty_txg)
1577 		dn->dn_dirty_txg = tx->tx_txg;
1578 	mutex_exit(&dn->dn_mtx);
1579 
1580 	if (db->db_blkid == DMU_SPILL_BLKID)
1581 		dn->dn_have_spill = B_TRUE;
1582 
1583 	/*
1584 	 * If this buffer is already dirty, we're done.
1585 	 */
1586 	drp = &db->db_last_dirty;
1587 	ASSERT(*drp == NULL || (*drp)->dr_txg <= tx->tx_txg ||
1588 	    db->db.db_object == DMU_META_DNODE_OBJECT);
1589 	while ((dr = *drp) != NULL && dr->dr_txg > tx->tx_txg)
1590 		drp = &dr->dr_next;
1591 	if (dr && dr->dr_txg == tx->tx_txg) {
1592 		DB_DNODE_EXIT(db);
1593 
1594 		dbuf_redirty(dr);
1595 		mutex_exit(&db->db_mtx);
1596 		return (dr);
1597 	}
1598 
1599 	/*
1600 	 * Only valid if not already dirty.
1601 	 */
1602 	ASSERT(dn->dn_object == 0 ||
1603 	    dn->dn_dirtyctx == DN_UNDIRTIED || dn->dn_dirtyctx ==
1604 	    (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN));
1605 
1606 	ASSERT3U(dn->dn_nlevels, >, db->db_level);
1607 
1608 	/*
1609 	 * We should only be dirtying in syncing context if it's the
1610 	 * mos or we're initializing the os or it's a special object.
1611 	 * However, we are allowed to dirty in syncing context provided
1612 	 * we already dirtied it in open context.  Hence we must make
1613 	 * this assertion only if we're not already dirty.
1614 	 */
1615 	os = dn->dn_objset;
1616 	VERIFY3U(tx->tx_txg, <=, spa_final_dirty_txg(os->os_spa));
1617 #ifdef DEBUG
1618 	if (dn->dn_objset->os_dsl_dataset != NULL)
1619 		rrw_enter(&os->os_dsl_dataset->ds_bp_rwlock, RW_READER, FTAG);
1620 	ASSERT(!dmu_tx_is_syncing(tx) || DMU_OBJECT_IS_SPECIAL(dn->dn_object) ||
1621 	    os->os_dsl_dataset == NULL || BP_IS_HOLE(os->os_rootbp));
1622 	if (dn->dn_objset->os_dsl_dataset != NULL)
1623 		rrw_exit(&os->os_dsl_dataset->ds_bp_rwlock, FTAG);
1624 #endif
1625 	ASSERT(db->db.db_size != 0);
1626 
1627 	dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
1628 
1629 	if (db->db_blkid != DMU_BONUS_BLKID) {
1630 		dmu_objset_willuse_space(os, db->db.db_size, tx);
1631 	}
1632 
1633 	/*
1634 	 * If this buffer is dirty in an old transaction group we need
1635 	 * to make a copy of it so that the changes we make in this
1636 	 * transaction group won't leak out when we sync the older txg.
1637 	 */
1638 	dr = kmem_zalloc(sizeof (dbuf_dirty_record_t), KM_SLEEP);
1639 	if (db->db_level == 0) {
1640 		void *data_old = db->db_buf;
1641 
1642 		if (db->db_state != DB_NOFILL) {
1643 			if (db->db_blkid == DMU_BONUS_BLKID) {
1644 				dbuf_fix_old_data(db, tx->tx_txg);
1645 				data_old = db->db.db_data;
1646 			} else if (db->db.db_object != DMU_META_DNODE_OBJECT) {
1647 				/*
1648 				 * Release the data buffer from the cache so
1649 				 * that we can modify it without impacting
1650 				 * possible other users of this cached data
1651 				 * block.  Note that indirect blocks and
1652 				 * private objects are not released until the
1653 				 * syncing state (since they are only modified
1654 				 * then).
1655 				 */
1656 				arc_release(db->db_buf, db);
1657 				dbuf_fix_old_data(db, tx->tx_txg);
1658 				data_old = db->db_buf;
1659 			}
1660 			ASSERT(data_old != NULL);
1661 		}
1662 		dr->dt.dl.dr_data = data_old;
1663 	} else {
1664 		mutex_init(&dr->dt.di.dr_mtx, NULL, MUTEX_DEFAULT, NULL);
1665 		list_create(&dr->dt.di.dr_children,
1666 		    sizeof (dbuf_dirty_record_t),
1667 		    offsetof(dbuf_dirty_record_t, dr_dirty_node));
1668 	}
1669 	if (db->db_blkid != DMU_BONUS_BLKID && os->os_dsl_dataset != NULL)
1670 		dr->dr_accounted = db->db.db_size;
1671 	dr->dr_dbuf = db;
1672 	dr->dr_txg = tx->tx_txg;
1673 	dr->dr_next = *drp;
1674 	*drp = dr;
1675 
1676 	/*
1677 	 * We could have been freed_in_flight between the dbuf_noread
1678 	 * and dbuf_dirty.  We win, as though the dbuf_noread() had
1679 	 * happened after the free.
1680 	 */
1681 	if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
1682 	    db->db_blkid != DMU_SPILL_BLKID) {
1683 		mutex_enter(&dn->dn_mtx);
1684 		if (dn->dn_free_ranges[txgoff] != NULL) {
1685 			range_tree_clear(dn->dn_free_ranges[txgoff],
1686 			    db->db_blkid, 1);
1687 		}
1688 		mutex_exit(&dn->dn_mtx);
1689 		db->db_freed_in_flight = FALSE;
1690 	}
1691 
1692 	/*
1693 	 * This buffer is now part of this txg
1694 	 */
1695 	dbuf_add_ref(db, (void *)(uintptr_t)tx->tx_txg);
1696 	db->db_dirtycnt += 1;
1697 	ASSERT3U(db->db_dirtycnt, <=, 3);
1698 
1699 	mutex_exit(&db->db_mtx);
1700 
1701 	if (db->db_blkid == DMU_BONUS_BLKID ||
1702 	    db->db_blkid == DMU_SPILL_BLKID) {
1703 		mutex_enter(&dn->dn_mtx);
1704 		ASSERT(!list_link_active(&dr->dr_dirty_node));
1705 		list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
1706 		mutex_exit(&dn->dn_mtx);
1707 		dnode_setdirty(dn, tx);
1708 		DB_DNODE_EXIT(db);
1709 		return (dr);
1710 	}
1711 
1712 	/*
1713 	 * The dn_struct_rwlock prevents db_blkptr from changing
1714 	 * due to a write from syncing context completing
1715 	 * while we are running, so we want to acquire it before
1716 	 * looking at db_blkptr.
1717 	 */
1718 	if (!RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
1719 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
1720 		drop_struct_lock = TRUE;
1721 	}
1722 
1723 	/*
1724 	 * We need to hold the dn_struct_rwlock to make this assertion,
1725 	 * because it protects dn_phys / dn_next_nlevels from changing.
1726 	 */
1727 	ASSERT((dn->dn_phys->dn_nlevels == 0 && db->db_level == 0) ||
1728 	    dn->dn_phys->dn_nlevels > db->db_level ||
1729 	    dn->dn_next_nlevels[txgoff] > db->db_level ||
1730 	    dn->dn_next_nlevels[(tx->tx_txg-1) & TXG_MASK] > db->db_level ||
1731 	    dn->dn_next_nlevels[(tx->tx_txg-2) & TXG_MASK] > db->db_level);
1732 
1733 	/*
1734 	 * If we are overwriting a dedup BP, then unless it is snapshotted,
1735 	 * when we get to syncing context we will need to decrement its
1736 	 * refcount in the DDT.  Prefetch the relevant DDT block so that
1737 	 * syncing context won't have to wait for the i/o.
1738 	 */
1739 	ddt_prefetch(os->os_spa, db->db_blkptr);
1740 
1741 	if (db->db_level == 0) {
1742 		dnode_new_blkid(dn, db->db_blkid, tx, drop_struct_lock);
1743 		ASSERT(dn->dn_maxblkid >= db->db_blkid);
1744 	}
1745 
1746 	if (db->db_level+1 < dn->dn_nlevels) {
1747 		dmu_buf_impl_t *parent = db->db_parent;
1748 		dbuf_dirty_record_t *di;
1749 		int parent_held = FALSE;
1750 
1751 		if (db->db_parent == NULL || db->db_parent == dn->dn_dbuf) {
1752 			int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
1753 
1754 			parent = dbuf_hold_level(dn, db->db_level+1,
1755 			    db->db_blkid >> epbs, FTAG);
1756 			ASSERT(parent != NULL);
1757 			parent_held = TRUE;
1758 		}
1759 		if (drop_struct_lock)
1760 			rw_exit(&dn->dn_struct_rwlock);
1761 		ASSERT3U(db->db_level+1, ==, parent->db_level);
1762 		di = dbuf_dirty(parent, tx);
1763 		if (parent_held)
1764 			dbuf_rele(parent, FTAG);
1765 
1766 		mutex_enter(&db->db_mtx);
1767 		/*
1768 		 * Since we've dropped the mutex, it's possible that
1769 		 * dbuf_undirty() might have changed this out from under us.
1770 		 */
1771 		if (db->db_last_dirty == dr ||
1772 		    dn->dn_object == DMU_META_DNODE_OBJECT) {
1773 			mutex_enter(&di->dt.di.dr_mtx);
1774 			ASSERT3U(di->dr_txg, ==, tx->tx_txg);
1775 			ASSERT(!list_link_active(&dr->dr_dirty_node));
1776 			list_insert_tail(&di->dt.di.dr_children, dr);
1777 			mutex_exit(&di->dt.di.dr_mtx);
1778 			dr->dr_parent = di;
1779 		}
1780 		mutex_exit(&db->db_mtx);
1781 	} else {
1782 		ASSERT(db->db_level+1 == dn->dn_nlevels);
1783 		ASSERT(db->db_blkid < dn->dn_nblkptr);
1784 		ASSERT(db->db_parent == NULL || db->db_parent == dn->dn_dbuf);
1785 		mutex_enter(&dn->dn_mtx);
1786 		ASSERT(!list_link_active(&dr->dr_dirty_node));
1787 		list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
1788 		mutex_exit(&dn->dn_mtx);
1789 		if (drop_struct_lock)
1790 			rw_exit(&dn->dn_struct_rwlock);
1791 	}
1792 
1793 	dnode_setdirty(dn, tx);
1794 	DB_DNODE_EXIT(db);
1795 	return (dr);
1796 }
1797 
1798 /*
1799  * Undirty a buffer in the transaction group referenced by the given
1800  * transaction.  Return whether this evicted the dbuf.
1801  */
1802 static boolean_t
1803 dbuf_undirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
1804 {
1805 	dnode_t *dn;
1806 	uint64_t txg = tx->tx_txg;
1807 	dbuf_dirty_record_t *dr, **drp;
1808 
1809 	ASSERT(txg != 0);
1810 
1811 	/*
1812 	 * Due to our use of dn_nlevels below, this can only be called
1813 	 * in open context, unless we are operating on the MOS.
1814 	 * From syncing context, dn_nlevels may be different from the
1815 	 * dn_nlevels used when dbuf was dirtied.
1816 	 */
1817 	ASSERT(db->db_objset ==
1818 	    dmu_objset_pool(db->db_objset)->dp_meta_objset ||
1819 	    txg != spa_syncing_txg(dmu_objset_spa(db->db_objset)));
1820 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1821 	ASSERT0(db->db_level);
1822 	ASSERT(MUTEX_HELD(&db->db_mtx));
1823 
1824 	/*
1825 	 * If this buffer is not dirty, we're done.
1826 	 */
1827 	for (drp = &db->db_last_dirty; (dr = *drp) != NULL; drp = &dr->dr_next)
1828 		if (dr->dr_txg <= txg)
1829 			break;
1830 	if (dr == NULL || dr->dr_txg < txg)
1831 		return (B_FALSE);
1832 	ASSERT(dr->dr_txg == txg);
1833 	ASSERT(dr->dr_dbuf == db);
1834 
1835 	DB_DNODE_ENTER(db);
1836 	dn = DB_DNODE(db);
1837 
1838 	dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
1839 
1840 	ASSERT(db->db.db_size != 0);
1841 
1842 	dsl_pool_undirty_space(dmu_objset_pool(dn->dn_objset),
1843 	    dr->dr_accounted, txg);
1844 
1845 	*drp = dr->dr_next;
1846 
1847 	/*
1848 	 * Note that there are three places in dbuf_dirty()
1849 	 * where this dirty record may be put on a list.
1850 	 * Make sure to do a list_remove corresponding to
1851 	 * every one of those list_insert calls.
1852 	 */
1853 	if (dr->dr_parent) {
1854 		mutex_enter(&dr->dr_parent->dt.di.dr_mtx);
1855 		list_remove(&dr->dr_parent->dt.di.dr_children, dr);
1856 		mutex_exit(&dr->dr_parent->dt.di.dr_mtx);
1857 	} else if (db->db_blkid == DMU_SPILL_BLKID ||
1858 	    db->db_level + 1 == dn->dn_nlevels) {
1859 		ASSERT(db->db_blkptr == NULL || db->db_parent == dn->dn_dbuf);
1860 		mutex_enter(&dn->dn_mtx);
1861 		list_remove(&dn->dn_dirty_records[txg & TXG_MASK], dr);
1862 		mutex_exit(&dn->dn_mtx);
1863 	}
1864 	DB_DNODE_EXIT(db);
1865 
1866 	if (db->db_state != DB_NOFILL) {
1867 		dbuf_unoverride(dr);
1868 
1869 		ASSERT(db->db_buf != NULL);
1870 		ASSERT(dr->dt.dl.dr_data != NULL);
1871 		if (dr->dt.dl.dr_data != db->db_buf)
1872 			arc_buf_destroy(dr->dt.dl.dr_data, db);
1873 	}
1874 
1875 	kmem_free(dr, sizeof (dbuf_dirty_record_t));
1876 
1877 	ASSERT(db->db_dirtycnt > 0);
1878 	db->db_dirtycnt -= 1;
1879 
1880 	if (zfs_refcount_remove(&db->db_holds, (void *)(uintptr_t)txg) == 0) {
1881 		ASSERT(db->db_state == DB_NOFILL || arc_released(db->db_buf));
1882 		dbuf_destroy(db);
1883 		return (B_TRUE);
1884 	}
1885 
1886 	return (B_FALSE);
1887 }
1888 
1889 void
1890 dmu_buf_will_dirty(dmu_buf_t *db_fake, dmu_tx_t *tx)
1891 {
1892 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1893 	int rf = DB_RF_MUST_SUCCEED | DB_RF_NOPREFETCH;
1894 
1895 	ASSERT(tx->tx_txg != 0);
1896 	ASSERT(!zfs_refcount_is_zero(&db->db_holds));
1897 
1898 	/*
1899 	 * Quick check for dirtyness.  For already dirty blocks, this
1900 	 * reduces runtime of this function by >90%, and overall performance
1901 	 * by 50% for some workloads (e.g. file deletion with indirect blocks
1902 	 * cached).
1903 	 */
1904 	mutex_enter(&db->db_mtx);
1905 	dbuf_dirty_record_t *dr;
1906 	for (dr = db->db_last_dirty;
1907 	    dr != NULL && dr->dr_txg >= tx->tx_txg; dr = dr->dr_next) {
1908 		/*
1909 		 * It's possible that it is already dirty but not cached,
1910 		 * because there are some calls to dbuf_dirty() that don't
1911 		 * go through dmu_buf_will_dirty().
1912 		 */
1913 		if (dr->dr_txg == tx->tx_txg && db->db_state == DB_CACHED) {
1914 			/* This dbuf is already dirty and cached. */
1915 			dbuf_redirty(dr);
1916 			mutex_exit(&db->db_mtx);
1917 			return;
1918 		}
1919 	}
1920 	mutex_exit(&db->db_mtx);
1921 
1922 	DB_DNODE_ENTER(db);
1923 	if (RW_WRITE_HELD(&DB_DNODE(db)->dn_struct_rwlock))
1924 		rf |= DB_RF_HAVESTRUCT;
1925 	DB_DNODE_EXIT(db);
1926 	(void) dbuf_read(db, NULL, rf);
1927 	(void) dbuf_dirty(db, tx);
1928 }
1929 
1930 void
1931 dmu_buf_will_not_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
1932 {
1933 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1934 
1935 	db->db_state = DB_NOFILL;
1936 
1937 	dmu_buf_will_fill(db_fake, tx);
1938 }
1939 
1940 void
1941 dmu_buf_will_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
1942 {
1943 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1944 
1945 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1946 	ASSERT(tx->tx_txg != 0);
1947 	ASSERT(db->db_level == 0);
1948 	ASSERT(!zfs_refcount_is_zero(&db->db_holds));
1949 
1950 	ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT ||
1951 	    dmu_tx_private_ok(tx));
1952 
1953 	dbuf_noread(db);
1954 	(void) dbuf_dirty(db, tx);
1955 }
1956 
1957 #pragma weak dmu_buf_fill_done = dbuf_fill_done
1958 /* ARGSUSED */
1959 void
1960 dbuf_fill_done(dmu_buf_impl_t *db, dmu_tx_t *tx)
1961 {
1962 	mutex_enter(&db->db_mtx);
1963 	DBUF_VERIFY(db);
1964 
1965 	if (db->db_state == DB_FILL) {
1966 		if (db->db_level == 0 && db->db_freed_in_flight) {
1967 			ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1968 			/* we were freed while filling */
1969 			/* XXX dbuf_undirty? */
1970 			bzero(db->db.db_data, db->db.db_size);
1971 			db->db_freed_in_flight = FALSE;
1972 		}
1973 		db->db_state = DB_CACHED;
1974 		cv_broadcast(&db->db_changed);
1975 	}
1976 	mutex_exit(&db->db_mtx);
1977 }
1978 
1979 void
1980 dmu_buf_write_embedded(dmu_buf_t *dbuf, void *data,
1981     bp_embedded_type_t etype, enum zio_compress comp,
1982     int uncompressed_size, int compressed_size, int byteorder,
1983     dmu_tx_t *tx)
1984 {
1985 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbuf;
1986 	struct dirty_leaf *dl;
1987 	dmu_object_type_t type;
1988 
1989 	if (etype == BP_EMBEDDED_TYPE_DATA) {
1990 		ASSERT(spa_feature_is_active(dmu_objset_spa(db->db_objset),
1991 		    SPA_FEATURE_EMBEDDED_DATA));
1992 	}
1993 
1994 	DB_DNODE_ENTER(db);
1995 	type = DB_DNODE(db)->dn_type;
1996 	DB_DNODE_EXIT(db);
1997 
1998 	ASSERT0(db->db_level);
1999 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2000 
2001 	dmu_buf_will_not_fill(dbuf, tx);
2002 
2003 	ASSERT3U(db->db_last_dirty->dr_txg, ==, tx->tx_txg);
2004 	dl = &db->db_last_dirty->dt.dl;
2005 	encode_embedded_bp_compressed(&dl->dr_overridden_by,
2006 	    data, comp, uncompressed_size, compressed_size);
2007 	BPE_SET_ETYPE(&dl->dr_overridden_by, etype);
2008 	BP_SET_TYPE(&dl->dr_overridden_by, type);
2009 	BP_SET_LEVEL(&dl->dr_overridden_by, 0);
2010 	BP_SET_BYTEORDER(&dl->dr_overridden_by, byteorder);
2011 
2012 	dl->dr_override_state = DR_OVERRIDDEN;
2013 	dl->dr_overridden_by.blk_birth = db->db_last_dirty->dr_txg;
2014 }
2015 
2016 /*
2017  * Directly assign a provided arc buf to a given dbuf if it's not referenced
2018  * by anybody except our caller. Otherwise copy arcbuf's contents to dbuf.
2019  */
2020 void
2021 dbuf_assign_arcbuf(dmu_buf_impl_t *db, arc_buf_t *buf, dmu_tx_t *tx)
2022 {
2023 	ASSERT(!zfs_refcount_is_zero(&db->db_holds));
2024 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2025 	ASSERT(db->db_level == 0);
2026 	ASSERT3U(dbuf_is_metadata(db), ==, arc_is_metadata(buf));
2027 	ASSERT(buf != NULL);
2028 	ASSERT(arc_buf_lsize(buf) == db->db.db_size);
2029 	ASSERT(tx->tx_txg != 0);
2030 
2031 	arc_return_buf(buf, db);
2032 	ASSERT(arc_released(buf));
2033 
2034 	mutex_enter(&db->db_mtx);
2035 
2036 	while (db->db_state == DB_READ || db->db_state == DB_FILL)
2037 		cv_wait(&db->db_changed, &db->db_mtx);
2038 
2039 	ASSERT(db->db_state == DB_CACHED || db->db_state == DB_UNCACHED);
2040 
2041 	if (db->db_state == DB_CACHED &&
2042 	    zfs_refcount_count(&db->db_holds) - 1 > db->db_dirtycnt) {
2043 		mutex_exit(&db->db_mtx);
2044 		(void) dbuf_dirty(db, tx);
2045 		bcopy(buf->b_data, db->db.db_data, db->db.db_size);
2046 		arc_buf_destroy(buf, db);
2047 		xuio_stat_wbuf_copied();
2048 		return;
2049 	}
2050 
2051 	xuio_stat_wbuf_nocopy();
2052 	if (db->db_state == DB_CACHED) {
2053 		dbuf_dirty_record_t *dr = db->db_last_dirty;
2054 
2055 		ASSERT(db->db_buf != NULL);
2056 		if (dr != NULL && dr->dr_txg == tx->tx_txg) {
2057 			ASSERT(dr->dt.dl.dr_data == db->db_buf);
2058 			if (!arc_released(db->db_buf)) {
2059 				ASSERT(dr->dt.dl.dr_override_state ==
2060 				    DR_OVERRIDDEN);
2061 				arc_release(db->db_buf, db);
2062 			}
2063 			dr->dt.dl.dr_data = buf;
2064 			arc_buf_destroy(db->db_buf, db);
2065 		} else if (dr == NULL || dr->dt.dl.dr_data != db->db_buf) {
2066 			arc_release(db->db_buf, db);
2067 			arc_buf_destroy(db->db_buf, db);
2068 		}
2069 		db->db_buf = NULL;
2070 	}
2071 	ASSERT(db->db_buf == NULL);
2072 	dbuf_set_data(db, buf);
2073 	db->db_state = DB_FILL;
2074 	mutex_exit(&db->db_mtx);
2075 	(void) dbuf_dirty(db, tx);
2076 	dmu_buf_fill_done(&db->db, tx);
2077 }
2078 
2079 void
2080 dbuf_destroy(dmu_buf_impl_t *db)
2081 {
2082 	dnode_t *dn;
2083 	dmu_buf_impl_t *parent = db->db_parent;
2084 	dmu_buf_impl_t *dndb;
2085 
2086 	ASSERT(MUTEX_HELD(&db->db_mtx));
2087 	ASSERT(zfs_refcount_is_zero(&db->db_holds));
2088 
2089 	if (db->db_buf != NULL) {
2090 		arc_buf_destroy(db->db_buf, db);
2091 		db->db_buf = NULL;
2092 	}
2093 
2094 	if (db->db_blkid == DMU_BONUS_BLKID) {
2095 		int slots = DB_DNODE(db)->dn_num_slots;
2096 		int bonuslen = DN_SLOTS_TO_BONUSLEN(slots);
2097 		if (db->db.db_data != NULL) {
2098 			zio_buf_free(db->db.db_data, bonuslen);
2099 			arc_space_return(bonuslen, ARC_SPACE_BONUS);
2100 			db->db_state = DB_UNCACHED;
2101 		}
2102 	}
2103 
2104 	dbuf_clear_data(db);
2105 
2106 	if (multilist_link_active(&db->db_cache_link)) {
2107 		ASSERT(db->db_caching_status == DB_DBUF_CACHE ||
2108 		    db->db_caching_status == DB_DBUF_METADATA_CACHE);
2109 
2110 		multilist_remove(dbuf_caches[db->db_caching_status].cache, db);
2111 		(void) zfs_refcount_remove_many(
2112 		    &dbuf_caches[db->db_caching_status].size,
2113 		    db->db.db_size, db);
2114 
2115 		db->db_caching_status = DB_NO_CACHE;
2116 	}
2117 
2118 	ASSERT(db->db_state == DB_UNCACHED || db->db_state == DB_NOFILL);
2119 	ASSERT(db->db_data_pending == NULL);
2120 
2121 	db->db_state = DB_EVICTING;
2122 	db->db_blkptr = NULL;
2123 
2124 	/*
2125 	 * Now that db_state is DB_EVICTING, nobody else can find this via
2126 	 * the hash table.  We can now drop db_mtx, which allows us to
2127 	 * acquire the dn_dbufs_mtx.
2128 	 */
2129 	mutex_exit(&db->db_mtx);
2130 
2131 	DB_DNODE_ENTER(db);
2132 	dn = DB_DNODE(db);
2133 	dndb = dn->dn_dbuf;
2134 	if (db->db_blkid != DMU_BONUS_BLKID) {
2135 		boolean_t needlock = !MUTEX_HELD(&dn->dn_dbufs_mtx);
2136 		if (needlock)
2137 			mutex_enter(&dn->dn_dbufs_mtx);
2138 		avl_remove(&dn->dn_dbufs, db);
2139 		atomic_dec_32(&dn->dn_dbufs_count);
2140 		membar_producer();
2141 		DB_DNODE_EXIT(db);
2142 		if (needlock)
2143 			mutex_exit(&dn->dn_dbufs_mtx);
2144 		/*
2145 		 * Decrementing the dbuf count means that the hold corresponding
2146 		 * to the removed dbuf is no longer discounted in dnode_move(),
2147 		 * so the dnode cannot be moved until after we release the hold.
2148 		 * The membar_producer() ensures visibility of the decremented
2149 		 * value in dnode_move(), since DB_DNODE_EXIT doesn't actually
2150 		 * release any lock.
2151 		 */
2152 		mutex_enter(&dn->dn_mtx);
2153 		dnode_rele_and_unlock(dn, db, B_TRUE);
2154 		db->db_dnode_handle = NULL;
2155 
2156 		dbuf_hash_remove(db);
2157 	} else {
2158 		DB_DNODE_EXIT(db);
2159 	}
2160 
2161 	ASSERT(zfs_refcount_is_zero(&db->db_holds));
2162 
2163 	db->db_parent = NULL;
2164 
2165 	ASSERT(db->db_buf == NULL);
2166 	ASSERT(db->db.db_data == NULL);
2167 	ASSERT(db->db_hash_next == NULL);
2168 	ASSERT(db->db_blkptr == NULL);
2169 	ASSERT(db->db_data_pending == NULL);
2170 	ASSERT3U(db->db_caching_status, ==, DB_NO_CACHE);
2171 	ASSERT(!multilist_link_active(&db->db_cache_link));
2172 
2173 	kmem_cache_free(dbuf_kmem_cache, db);
2174 	arc_space_return(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
2175 
2176 	/*
2177 	 * If this dbuf is referenced from an indirect dbuf,
2178 	 * decrement the ref count on the indirect dbuf.
2179 	 */
2180 	if (parent && parent != dndb) {
2181 		mutex_enter(&parent->db_mtx);
2182 		dbuf_rele_and_unlock(parent, db, B_TRUE);
2183 	}
2184 }
2185 
2186 /*
2187  * Note: While bpp will always be updated if the function returns success,
2188  * parentp will not be updated if the dnode does not have dn_dbuf filled in;
2189  * this happens when the dnode is the meta-dnode, or a userused or groupused
2190  * object.
2191  */
2192 static int
2193 dbuf_findbp(dnode_t *dn, int level, uint64_t blkid, int fail_sparse,
2194     dmu_buf_impl_t **parentp, blkptr_t **bpp)
2195 {
2196 	*parentp = NULL;
2197 	*bpp = NULL;
2198 
2199 	ASSERT(blkid != DMU_BONUS_BLKID);
2200 
2201 	if (blkid == DMU_SPILL_BLKID) {
2202 		mutex_enter(&dn->dn_mtx);
2203 		if (dn->dn_have_spill &&
2204 		    (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR))
2205 			*bpp = DN_SPILL_BLKPTR(dn->dn_phys);
2206 		else
2207 			*bpp = NULL;
2208 		dbuf_add_ref(dn->dn_dbuf, NULL);
2209 		*parentp = dn->dn_dbuf;
2210 		mutex_exit(&dn->dn_mtx);
2211 		return (0);
2212 	}
2213 
2214 	int nlevels =
2215 	    (dn->dn_phys->dn_nlevels == 0) ? 1 : dn->dn_phys->dn_nlevels;
2216 	int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
2217 
2218 	ASSERT3U(level * epbs, <, 64);
2219 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2220 	/*
2221 	 * This assertion shouldn't trip as long as the max indirect block size
2222 	 * is less than 1M.  The reason for this is that up to that point,
2223 	 * the number of levels required to address an entire object with blocks
2224 	 * of size SPA_MINBLOCKSIZE satisfies nlevels * epbs + 1 <= 64.  In
2225 	 * other words, if N * epbs + 1 > 64, then if (N-1) * epbs + 1 > 55
2226 	 * (i.e. we can address the entire object), objects will all use at most
2227 	 * N-1 levels and the assertion won't overflow.  However, once epbs is
2228 	 * 13, 4 * 13 + 1 = 53, but 5 * 13 + 1 = 66.  Then, 4 levels will not be
2229 	 * enough to address an entire object, so objects will have 5 levels,
2230 	 * but then this assertion will overflow.
2231 	 *
2232 	 * All this is to say that if we ever increase DN_MAX_INDBLKSHIFT, we
2233 	 * need to redo this logic to handle overflows.
2234 	 */
2235 	ASSERT(level >= nlevels ||
2236 	    ((nlevels - level - 1) * epbs) +
2237 	    highbit64(dn->dn_phys->dn_nblkptr) <= 64);
2238 	if (level >= nlevels ||
2239 	    blkid >= ((uint64_t)dn->dn_phys->dn_nblkptr <<
2240 	    ((nlevels - level - 1) * epbs)) ||
2241 	    (fail_sparse &&
2242 	    blkid > (dn->dn_phys->dn_maxblkid >> (level * epbs)))) {
2243 		/* the buffer has no parent yet */
2244 		return (SET_ERROR(ENOENT));
2245 	} else if (level < nlevels-1) {
2246 		/* this block is referenced from an indirect block */
2247 		int err = dbuf_hold_impl(dn, level+1,
2248 		    blkid >> epbs, fail_sparse, FALSE, NULL, parentp);
2249 		if (err)
2250 			return (err);
2251 		err = dbuf_read(*parentp, NULL,
2252 		    (DB_RF_HAVESTRUCT | DB_RF_NOPREFETCH | DB_RF_CANFAIL));
2253 		if (err) {
2254 			dbuf_rele(*parentp, NULL);
2255 			*parentp = NULL;
2256 			return (err);
2257 		}
2258 		*bpp = ((blkptr_t *)(*parentp)->db.db_data) +
2259 		    (blkid & ((1ULL << epbs) - 1));
2260 		if (blkid > (dn->dn_phys->dn_maxblkid >> (level * epbs)))
2261 			ASSERT(BP_IS_HOLE(*bpp));
2262 		return (0);
2263 	} else {
2264 		/* the block is referenced from the dnode */
2265 		ASSERT3U(level, ==, nlevels-1);
2266 		ASSERT(dn->dn_phys->dn_nblkptr == 0 ||
2267 		    blkid < dn->dn_phys->dn_nblkptr);
2268 		if (dn->dn_dbuf) {
2269 			dbuf_add_ref(dn->dn_dbuf, NULL);
2270 			*parentp = dn->dn_dbuf;
2271 		}
2272 		*bpp = &dn->dn_phys->dn_blkptr[blkid];
2273 		return (0);
2274 	}
2275 }
2276 
2277 static dmu_buf_impl_t *
2278 dbuf_create(dnode_t *dn, uint8_t level, uint64_t blkid,
2279     dmu_buf_impl_t *parent, blkptr_t *blkptr)
2280 {
2281 	objset_t *os = dn->dn_objset;
2282 	dmu_buf_impl_t *db, *odb;
2283 
2284 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2285 	ASSERT(dn->dn_type != DMU_OT_NONE);
2286 
2287 	db = kmem_cache_alloc(dbuf_kmem_cache, KM_SLEEP);
2288 
2289 	db->db_objset = os;
2290 	db->db.db_object = dn->dn_object;
2291 	db->db_level = level;
2292 	db->db_blkid = blkid;
2293 	db->db_last_dirty = NULL;
2294 	db->db_dirtycnt = 0;
2295 	db->db_dnode_handle = dn->dn_handle;
2296 	db->db_parent = parent;
2297 	db->db_blkptr = blkptr;
2298 
2299 	db->db_user = NULL;
2300 	db->db_user_immediate_evict = FALSE;
2301 	db->db_freed_in_flight = FALSE;
2302 	db->db_pending_evict = FALSE;
2303 
2304 	if (blkid == DMU_BONUS_BLKID) {
2305 		ASSERT3P(parent, ==, dn->dn_dbuf);
2306 		db->db.db_size = DN_SLOTS_TO_BONUSLEN(dn->dn_num_slots) -
2307 		    (dn->dn_nblkptr-1) * sizeof (blkptr_t);
2308 		ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
2309 		db->db.db_offset = DMU_BONUS_BLKID;
2310 		db->db_state = DB_UNCACHED;
2311 		db->db_caching_status = DB_NO_CACHE;
2312 		/* the bonus dbuf is not placed in the hash table */
2313 		arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
2314 		return (db);
2315 	} else if (blkid == DMU_SPILL_BLKID) {
2316 		db->db.db_size = (blkptr != NULL) ?
2317 		    BP_GET_LSIZE(blkptr) : SPA_MINBLOCKSIZE;
2318 		db->db.db_offset = 0;
2319 	} else {
2320 		int blocksize =
2321 		    db->db_level ? 1 << dn->dn_indblkshift : dn->dn_datablksz;
2322 		db->db.db_size = blocksize;
2323 		db->db.db_offset = db->db_blkid * blocksize;
2324 	}
2325 
2326 	/*
2327 	 * Hold the dn_dbufs_mtx while we get the new dbuf
2328 	 * in the hash table *and* added to the dbufs list.
2329 	 * This prevents a possible deadlock with someone
2330 	 * trying to look up this dbuf before its added to the
2331 	 * dn_dbufs list.
2332 	 */
2333 	mutex_enter(&dn->dn_dbufs_mtx);
2334 	db->db_state = DB_EVICTING;
2335 	if ((odb = dbuf_hash_insert(db)) != NULL) {
2336 		/* someone else inserted it first */
2337 		kmem_cache_free(dbuf_kmem_cache, db);
2338 		mutex_exit(&dn->dn_dbufs_mtx);
2339 		return (odb);
2340 	}
2341 	avl_add(&dn->dn_dbufs, db);
2342 
2343 	db->db_state = DB_UNCACHED;
2344 	db->db_caching_status = DB_NO_CACHE;
2345 	mutex_exit(&dn->dn_dbufs_mtx);
2346 	arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
2347 
2348 	if (parent && parent != dn->dn_dbuf)
2349 		dbuf_add_ref(parent, db);
2350 
2351 	ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
2352 	    zfs_refcount_count(&dn->dn_holds) > 0);
2353 	(void) zfs_refcount_add(&dn->dn_holds, db);
2354 	atomic_inc_32(&dn->dn_dbufs_count);
2355 
2356 	dprintf_dbuf(db, "db=%p\n", db);
2357 
2358 	return (db);
2359 }
2360 
2361 typedef struct dbuf_prefetch_arg {
2362 	spa_t *dpa_spa;	/* The spa to issue the prefetch in. */
2363 	zbookmark_phys_t dpa_zb; /* The target block to prefetch. */
2364 	int dpa_epbs; /* Entries (blkptr_t's) Per Block Shift. */
2365 	int dpa_curlevel; /* The current level that we're reading */
2366 	dnode_t *dpa_dnode; /* The dnode associated with the prefetch */
2367 	zio_priority_t dpa_prio; /* The priority I/Os should be issued at. */
2368 	zio_t *dpa_zio; /* The parent zio_t for all prefetches. */
2369 	arc_flags_t dpa_aflags; /* Flags to pass to the final prefetch. */
2370 } dbuf_prefetch_arg_t;
2371 
2372 /*
2373  * Actually issue the prefetch read for the block given.
2374  */
2375 static void
2376 dbuf_issue_final_prefetch(dbuf_prefetch_arg_t *dpa, blkptr_t *bp)
2377 {
2378 	if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
2379 		return;
2380 
2381 	arc_flags_t aflags =
2382 	    dpa->dpa_aflags | ARC_FLAG_NOWAIT | ARC_FLAG_PREFETCH;
2383 
2384 	ASSERT3U(dpa->dpa_curlevel, ==, BP_GET_LEVEL(bp));
2385 	ASSERT3U(dpa->dpa_curlevel, ==, dpa->dpa_zb.zb_level);
2386 	ASSERT(dpa->dpa_zio != NULL);
2387 	(void) arc_read(dpa->dpa_zio, dpa->dpa_spa, bp, NULL, NULL,
2388 	    dpa->dpa_prio, ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
2389 	    &aflags, &dpa->dpa_zb);
2390 }
2391 
2392 /*
2393  * Called when an indirect block above our prefetch target is read in.  This
2394  * will either read in the next indirect block down the tree or issue the actual
2395  * prefetch if the next block down is our target.
2396  */
2397 static void
2398 dbuf_prefetch_indirect_done(zio_t *zio, arc_buf_t *abuf, void *private)
2399 {
2400 	dbuf_prefetch_arg_t *dpa = private;
2401 
2402 	ASSERT3S(dpa->dpa_zb.zb_level, <, dpa->dpa_curlevel);
2403 	ASSERT3S(dpa->dpa_curlevel, >, 0);
2404 
2405 	if (abuf == NULL) {
2406 		ASSERT(zio == NULL || zio->io_error != 0);
2407 		kmem_free(dpa, sizeof (*dpa));
2408 		return;
2409 	}
2410 	ASSERT(zio == NULL || zio->io_error == 0);
2411 
2412 	/*
2413 	 * The dpa_dnode is only valid if we are called with a NULL
2414 	 * zio. This indicates that the arc_read() returned without
2415 	 * first calling zio_read() to issue a physical read. Once
2416 	 * a physical read is made the dpa_dnode must be invalidated
2417 	 * as the locks guarding it may have been dropped. If the
2418 	 * dpa_dnode is still valid, then we want to add it to the dbuf
2419 	 * cache. To do so, we must hold the dbuf associated with the block
2420 	 * we just prefetched, read its contents so that we associate it
2421 	 * with an arc_buf_t, and then release it.
2422 	 */
2423 	if (zio != NULL) {
2424 		ASSERT3S(BP_GET_LEVEL(zio->io_bp), ==, dpa->dpa_curlevel);
2425 		if (zio->io_flags & ZIO_FLAG_RAW) {
2426 			ASSERT3U(BP_GET_PSIZE(zio->io_bp), ==, zio->io_size);
2427 		} else {
2428 			ASSERT3U(BP_GET_LSIZE(zio->io_bp), ==, zio->io_size);
2429 		}
2430 		ASSERT3P(zio->io_spa, ==, dpa->dpa_spa);
2431 
2432 		dpa->dpa_dnode = NULL;
2433 	} else if (dpa->dpa_dnode != NULL) {
2434 		uint64_t curblkid = dpa->dpa_zb.zb_blkid >>
2435 		    (dpa->dpa_epbs * (dpa->dpa_curlevel -
2436 		    dpa->dpa_zb.zb_level));
2437 		dmu_buf_impl_t *db = dbuf_hold_level(dpa->dpa_dnode,
2438 		    dpa->dpa_curlevel, curblkid, FTAG);
2439 		(void) dbuf_read(db, NULL,
2440 		    DB_RF_MUST_SUCCEED | DB_RF_NOPREFETCH | DB_RF_HAVESTRUCT);
2441 		dbuf_rele(db, FTAG);
2442 	}
2443 
2444 	dpa->dpa_curlevel--;
2445 
2446 	uint64_t nextblkid = dpa->dpa_zb.zb_blkid >>
2447 	    (dpa->dpa_epbs * (dpa->dpa_curlevel - dpa->dpa_zb.zb_level));
2448 	blkptr_t *bp = ((blkptr_t *)abuf->b_data) +
2449 	    P2PHASE(nextblkid, 1ULL << dpa->dpa_epbs);
2450 	if (BP_IS_HOLE(bp)) {
2451 		kmem_free(dpa, sizeof (*dpa));
2452 	} else if (dpa->dpa_curlevel == dpa->dpa_zb.zb_level) {
2453 		ASSERT3U(nextblkid, ==, dpa->dpa_zb.zb_blkid);
2454 		dbuf_issue_final_prefetch(dpa, bp);
2455 		kmem_free(dpa, sizeof (*dpa));
2456 	} else {
2457 		arc_flags_t iter_aflags = ARC_FLAG_NOWAIT;
2458 		zbookmark_phys_t zb;
2459 
2460 		/* flag if L2ARC eligible, l2arc_noprefetch then decides */
2461 		if (dpa->dpa_aflags & ARC_FLAG_L2CACHE)
2462 			iter_aflags |= ARC_FLAG_L2CACHE;
2463 
2464 		ASSERT3U(dpa->dpa_curlevel, ==, BP_GET_LEVEL(bp));
2465 
2466 		SET_BOOKMARK(&zb, dpa->dpa_zb.zb_objset,
2467 		    dpa->dpa_zb.zb_object, dpa->dpa_curlevel, nextblkid);
2468 
2469 		(void) arc_read(dpa->dpa_zio, dpa->dpa_spa,
2470 		    bp, dbuf_prefetch_indirect_done, dpa, dpa->dpa_prio,
2471 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
2472 		    &iter_aflags, &zb);
2473 	}
2474 
2475 	arc_buf_destroy(abuf, private);
2476 }
2477 
2478 /*
2479  * Issue prefetch reads for the given block on the given level.  If the indirect
2480  * blocks above that block are not in memory, we will read them in
2481  * asynchronously.  As a result, this call never blocks waiting for a read to
2482  * complete.
2483  */
2484 void
2485 dbuf_prefetch(dnode_t *dn, int64_t level, uint64_t blkid, zio_priority_t prio,
2486     arc_flags_t aflags)
2487 {
2488 	blkptr_t bp;
2489 	int epbs, nlevels, curlevel;
2490 	uint64_t curblkid;
2491 
2492 	ASSERT(blkid != DMU_BONUS_BLKID);
2493 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2494 
2495 	if (blkid > dn->dn_maxblkid)
2496 		return;
2497 
2498 	if (dnode_block_freed(dn, blkid))
2499 		return;
2500 
2501 	/*
2502 	 * This dnode hasn't been written to disk yet, so there's nothing to
2503 	 * prefetch.
2504 	 */
2505 	nlevels = dn->dn_phys->dn_nlevels;
2506 	if (level >= nlevels || dn->dn_phys->dn_nblkptr == 0)
2507 		return;
2508 
2509 	epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
2510 	if (dn->dn_phys->dn_maxblkid < blkid << (epbs * level))
2511 		return;
2512 
2513 	dmu_buf_impl_t *db = dbuf_find(dn->dn_objset, dn->dn_object,
2514 	    level, blkid);
2515 	if (db != NULL) {
2516 		mutex_exit(&db->db_mtx);
2517 		/*
2518 		 * This dbuf already exists.  It is either CACHED, or
2519 		 * (we assume) about to be read or filled.
2520 		 */
2521 		return;
2522 	}
2523 
2524 	/*
2525 	 * Find the closest ancestor (indirect block) of the target block
2526 	 * that is present in the cache.  In this indirect block, we will
2527 	 * find the bp that is at curlevel, curblkid.
2528 	 */
2529 	curlevel = level;
2530 	curblkid = blkid;
2531 	while (curlevel < nlevels - 1) {
2532 		int parent_level = curlevel + 1;
2533 		uint64_t parent_blkid = curblkid >> epbs;
2534 		dmu_buf_impl_t *db;
2535 
2536 		if (dbuf_hold_impl(dn, parent_level, parent_blkid,
2537 		    FALSE, TRUE, FTAG, &db) == 0) {
2538 			blkptr_t *bpp = db->db_buf->b_data;
2539 			bp = bpp[P2PHASE(curblkid, 1 << epbs)];
2540 			dbuf_rele(db, FTAG);
2541 			break;
2542 		}
2543 
2544 		curlevel = parent_level;
2545 		curblkid = parent_blkid;
2546 	}
2547 
2548 	if (curlevel == nlevels - 1) {
2549 		/* No cached indirect blocks found. */
2550 		ASSERT3U(curblkid, <, dn->dn_phys->dn_nblkptr);
2551 		bp = dn->dn_phys->dn_blkptr[curblkid];
2552 	}
2553 	if (BP_IS_HOLE(&bp))
2554 		return;
2555 
2556 	ASSERT3U(curlevel, ==, BP_GET_LEVEL(&bp));
2557 
2558 	zio_t *pio = zio_root(dmu_objset_spa(dn->dn_objset), NULL, NULL,
2559 	    ZIO_FLAG_CANFAIL);
2560 
2561 	dbuf_prefetch_arg_t *dpa = kmem_zalloc(sizeof (*dpa), KM_SLEEP);
2562 	dsl_dataset_t *ds = dn->dn_objset->os_dsl_dataset;
2563 	SET_BOOKMARK(&dpa->dpa_zb, ds != NULL ? ds->ds_object : DMU_META_OBJSET,
2564 	    dn->dn_object, level, blkid);
2565 	dpa->dpa_curlevel = curlevel;
2566 	dpa->dpa_prio = prio;
2567 	dpa->dpa_aflags = aflags;
2568 	dpa->dpa_spa = dn->dn_objset->os_spa;
2569 	dpa->dpa_dnode = dn;
2570 	dpa->dpa_epbs = epbs;
2571 	dpa->dpa_zio = pio;
2572 
2573 	/* flag if L2ARC eligible, l2arc_noprefetch then decides */
2574 	if (DNODE_LEVEL_IS_L2CACHEABLE(dn, level))
2575 		dpa->dpa_aflags |= ARC_FLAG_L2CACHE;
2576 
2577 	/*
2578 	 * If we have the indirect just above us, no need to do the asynchronous
2579 	 * prefetch chain; we'll just run the last step ourselves.  If we're at
2580 	 * a higher level, though, we want to issue the prefetches for all the
2581 	 * indirect blocks asynchronously, so we can go on with whatever we were
2582 	 * doing.
2583 	 */
2584 	if (curlevel == level) {
2585 		ASSERT3U(curblkid, ==, blkid);
2586 		dbuf_issue_final_prefetch(dpa, &bp);
2587 		kmem_free(dpa, sizeof (*dpa));
2588 	} else {
2589 		arc_flags_t iter_aflags = ARC_FLAG_NOWAIT;
2590 		zbookmark_phys_t zb;
2591 
2592 		/* flag if L2ARC eligible, l2arc_noprefetch then decides */
2593 		if (DNODE_LEVEL_IS_L2CACHEABLE(dn, level))
2594 			iter_aflags |= ARC_FLAG_L2CACHE;
2595 
2596 		SET_BOOKMARK(&zb, ds != NULL ? ds->ds_object : DMU_META_OBJSET,
2597 		    dn->dn_object, curlevel, curblkid);
2598 		(void) arc_read(dpa->dpa_zio, dpa->dpa_spa,
2599 		    &bp, dbuf_prefetch_indirect_done, dpa, prio,
2600 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
2601 		    &iter_aflags, &zb);
2602 	}
2603 	/*
2604 	 * We use pio here instead of dpa_zio since it's possible that
2605 	 * dpa may have already been freed.
2606 	 */
2607 	zio_nowait(pio);
2608 }
2609 
2610 /*
2611  * Returns with db_holds incremented, and db_mtx not held.
2612  * Note: dn_struct_rwlock must be held.
2613  */
2614 int
2615 dbuf_hold_impl(dnode_t *dn, uint8_t level, uint64_t blkid,
2616     boolean_t fail_sparse, boolean_t fail_uncached,
2617     void *tag, dmu_buf_impl_t **dbp)
2618 {
2619 	dmu_buf_impl_t *db, *parent = NULL;
2620 
2621 	ASSERT(blkid != DMU_BONUS_BLKID);
2622 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2623 	ASSERT3U(dn->dn_nlevels, >, level);
2624 
2625 	*dbp = NULL;
2626 top:
2627 	/* dbuf_find() returns with db_mtx held */
2628 	db = dbuf_find(dn->dn_objset, dn->dn_object, level, blkid);
2629 
2630 	if (db == NULL) {
2631 		blkptr_t *bp = NULL;
2632 		int err;
2633 
2634 		if (fail_uncached)
2635 			return (SET_ERROR(ENOENT));
2636 
2637 		ASSERT3P(parent, ==, NULL);
2638 		err = dbuf_findbp(dn, level, blkid, fail_sparse, &parent, &bp);
2639 		if (fail_sparse) {
2640 			if (err == 0 && bp && BP_IS_HOLE(bp))
2641 				err = SET_ERROR(ENOENT);
2642 			if (err) {
2643 				if (parent)
2644 					dbuf_rele(parent, NULL);
2645 				return (err);
2646 			}
2647 		}
2648 		if (err && err != ENOENT)
2649 			return (err);
2650 		db = dbuf_create(dn, level, blkid, parent, bp);
2651 	}
2652 
2653 	if (fail_uncached && db->db_state != DB_CACHED) {
2654 		mutex_exit(&db->db_mtx);
2655 		return (SET_ERROR(ENOENT));
2656 	}
2657 
2658 	if (db->db_buf != NULL) {
2659 		arc_buf_access(db->db_buf);
2660 		ASSERT3P(db->db.db_data, ==, db->db_buf->b_data);
2661 	}
2662 
2663 	ASSERT(db->db_buf == NULL || arc_referenced(db->db_buf));
2664 
2665 	/*
2666 	 * If this buffer is currently syncing out, and we are are
2667 	 * still referencing it from db_data, we need to make a copy
2668 	 * of it in case we decide we want to dirty it again in this txg.
2669 	 */
2670 	if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
2671 	    dn->dn_object != DMU_META_DNODE_OBJECT &&
2672 	    db->db_state == DB_CACHED && db->db_data_pending) {
2673 		dbuf_dirty_record_t *dr = db->db_data_pending;
2674 
2675 		if (dr->dt.dl.dr_data == db->db_buf) {
2676 			arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
2677 
2678 			dbuf_set_data(db,
2679 			    arc_alloc_buf(dn->dn_objset->os_spa, db, type,
2680 			    db->db.db_size));
2681 			bcopy(dr->dt.dl.dr_data->b_data, db->db.db_data,
2682 			    db->db.db_size);
2683 		}
2684 	}
2685 
2686 	if (multilist_link_active(&db->db_cache_link)) {
2687 		ASSERT(zfs_refcount_is_zero(&db->db_holds));
2688 		ASSERT(db->db_caching_status == DB_DBUF_CACHE ||
2689 		    db->db_caching_status == DB_DBUF_METADATA_CACHE);
2690 
2691 		multilist_remove(dbuf_caches[db->db_caching_status].cache, db);
2692 		(void) zfs_refcount_remove_many(
2693 		    &dbuf_caches[db->db_caching_status].size,
2694 		    db->db.db_size, db);
2695 
2696 		db->db_caching_status = DB_NO_CACHE;
2697 	}
2698 	(void) zfs_refcount_add(&db->db_holds, tag);
2699 	DBUF_VERIFY(db);
2700 	mutex_exit(&db->db_mtx);
2701 
2702 	/* NOTE: we can't rele the parent until after we drop the db_mtx */
2703 	if (parent)
2704 		dbuf_rele(parent, NULL);
2705 
2706 	ASSERT3P(DB_DNODE(db), ==, dn);
2707 	ASSERT3U(db->db_blkid, ==, blkid);
2708 	ASSERT3U(db->db_level, ==, level);
2709 	*dbp = db;
2710 
2711 	return (0);
2712 }
2713 
2714 dmu_buf_impl_t *
2715 dbuf_hold(dnode_t *dn, uint64_t blkid, void *tag)
2716 {
2717 	return (dbuf_hold_level(dn, 0, blkid, tag));
2718 }
2719 
2720 dmu_buf_impl_t *
2721 dbuf_hold_level(dnode_t *dn, int level, uint64_t blkid, void *tag)
2722 {
2723 	dmu_buf_impl_t *db;
2724 	int err = dbuf_hold_impl(dn, level, blkid, FALSE, FALSE, tag, &db);
2725 	return (err ? NULL : db);
2726 }
2727 
2728 void
2729 dbuf_create_bonus(dnode_t *dn)
2730 {
2731 	ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
2732 
2733 	ASSERT(dn->dn_bonus == NULL);
2734 	dn->dn_bonus = dbuf_create(dn, 0, DMU_BONUS_BLKID, dn->dn_dbuf, NULL);
2735 }
2736 
2737 int
2738 dbuf_spill_set_blksz(dmu_buf_t *db_fake, uint64_t blksz, dmu_tx_t *tx)
2739 {
2740 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2741 	dnode_t *dn;
2742 
2743 	if (db->db_blkid != DMU_SPILL_BLKID)
2744 		return (SET_ERROR(ENOTSUP));
2745 	if (blksz == 0)
2746 		blksz = SPA_MINBLOCKSIZE;
2747 	ASSERT3U(blksz, <=, spa_maxblocksize(dmu_objset_spa(db->db_objset)));
2748 	blksz = P2ROUNDUP(blksz, SPA_MINBLOCKSIZE);
2749 
2750 	DB_DNODE_ENTER(db);
2751 	dn = DB_DNODE(db);
2752 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
2753 	dbuf_new_size(db, blksz, tx);
2754 	rw_exit(&dn->dn_struct_rwlock);
2755 	DB_DNODE_EXIT(db);
2756 
2757 	return (0);
2758 }
2759 
2760 void
2761 dbuf_rm_spill(dnode_t *dn, dmu_tx_t *tx)
2762 {
2763 	dbuf_free_range(dn, DMU_SPILL_BLKID, DMU_SPILL_BLKID, tx);
2764 }
2765 
2766 #pragma weak dmu_buf_add_ref = dbuf_add_ref
2767 void
2768 dbuf_add_ref(dmu_buf_impl_t *db, void *tag)
2769 {
2770 	int64_t holds = zfs_refcount_add(&db->db_holds, tag);
2771 	ASSERT3S(holds, >, 1);
2772 }
2773 
2774 #pragma weak dmu_buf_try_add_ref = dbuf_try_add_ref
2775 boolean_t
2776 dbuf_try_add_ref(dmu_buf_t *db_fake, objset_t *os, uint64_t obj, uint64_t blkid,
2777     void *tag)
2778 {
2779 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2780 	dmu_buf_impl_t *found_db;
2781 	boolean_t result = B_FALSE;
2782 
2783 	if (db->db_blkid == DMU_BONUS_BLKID)
2784 		found_db = dbuf_find_bonus(os, obj);
2785 	else
2786 		found_db = dbuf_find(os, obj, 0, blkid);
2787 
2788 	if (found_db != NULL) {
2789 		if (db == found_db && dbuf_refcount(db) > db->db_dirtycnt) {
2790 			(void) zfs_refcount_add(&db->db_holds, tag);
2791 			result = B_TRUE;
2792 		}
2793 		mutex_exit(&db->db_mtx);
2794 	}
2795 	return (result);
2796 }
2797 
2798 /*
2799  * If you call dbuf_rele() you had better not be referencing the dnode handle
2800  * unless you have some other direct or indirect hold on the dnode. (An indirect
2801  * hold is a hold on one of the dnode's dbufs, including the bonus buffer.)
2802  * Without that, the dbuf_rele() could lead to a dnode_rele() followed by the
2803  * dnode's parent dbuf evicting its dnode handles.
2804  */
2805 void
2806 dbuf_rele(dmu_buf_impl_t *db, void *tag)
2807 {
2808 	mutex_enter(&db->db_mtx);
2809 	dbuf_rele_and_unlock(db, tag, B_FALSE);
2810 }
2811 
2812 void
2813 dmu_buf_rele(dmu_buf_t *db, void *tag)
2814 {
2815 	dbuf_rele((dmu_buf_impl_t *)db, tag);
2816 }
2817 
2818 /*
2819  * dbuf_rele() for an already-locked dbuf.  This is necessary to allow
2820  * db_dirtycnt and db_holds to be updated atomically.  The 'evicting'
2821  * argument should be set if we are already in the dbuf-evicting code
2822  * path, in which case we don't want to recursively evict.  This allows us to
2823  * avoid deeply nested stacks that would have a call flow similar to this:
2824  *
2825  * dbuf_rele()-->dbuf_rele_and_unlock()-->dbuf_evict_notify()
2826  *	^						|
2827  *	|						|
2828  *	+-----dbuf_destroy()<--dbuf_evict_one()<--------+
2829  *
2830  */
2831 void
2832 dbuf_rele_and_unlock(dmu_buf_impl_t *db, void *tag, boolean_t evicting)
2833 {
2834 	int64_t holds;
2835 
2836 	ASSERT(MUTEX_HELD(&db->db_mtx));
2837 	DBUF_VERIFY(db);
2838 
2839 	/*
2840 	 * Remove the reference to the dbuf before removing its hold on the
2841 	 * dnode so we can guarantee in dnode_move() that a referenced bonus
2842 	 * buffer has a corresponding dnode hold.
2843 	 */
2844 	holds = zfs_refcount_remove(&db->db_holds, tag);
2845 	ASSERT(holds >= 0);
2846 
2847 	/*
2848 	 * We can't freeze indirects if there is a possibility that they
2849 	 * may be modified in the current syncing context.
2850 	 */
2851 	if (db->db_buf != NULL &&
2852 	    holds == (db->db_level == 0 ? db->db_dirtycnt : 0)) {
2853 		arc_buf_freeze(db->db_buf);
2854 	}
2855 
2856 	if (holds == db->db_dirtycnt &&
2857 	    db->db_level == 0 && db->db_user_immediate_evict)
2858 		dbuf_evict_user(db);
2859 
2860 	if (holds == 0) {
2861 		if (db->db_blkid == DMU_BONUS_BLKID) {
2862 			dnode_t *dn;
2863 			boolean_t evict_dbuf = db->db_pending_evict;
2864 
2865 			/*
2866 			 * If the dnode moves here, we cannot cross this
2867 			 * barrier until the move completes.
2868 			 */
2869 			DB_DNODE_ENTER(db);
2870 
2871 			dn = DB_DNODE(db);
2872 			atomic_dec_32(&dn->dn_dbufs_count);
2873 
2874 			/*
2875 			 * Decrementing the dbuf count means that the bonus
2876 			 * buffer's dnode hold is no longer discounted in
2877 			 * dnode_move(). The dnode cannot move until after
2878 			 * the dnode_rele() below.
2879 			 */
2880 			DB_DNODE_EXIT(db);
2881 
2882 			/*
2883 			 * Do not reference db after its lock is dropped.
2884 			 * Another thread may evict it.
2885 			 */
2886 			mutex_exit(&db->db_mtx);
2887 
2888 			if (evict_dbuf)
2889 				dnode_evict_bonus(dn);
2890 
2891 			dnode_rele(dn, db);
2892 		} else if (db->db_buf == NULL) {
2893 			/*
2894 			 * This is a special case: we never associated this
2895 			 * dbuf with any data allocated from the ARC.
2896 			 */
2897 			ASSERT(db->db_state == DB_UNCACHED ||
2898 			    db->db_state == DB_NOFILL);
2899 			dbuf_destroy(db);
2900 		} else if (arc_released(db->db_buf)) {
2901 			/*
2902 			 * This dbuf has anonymous data associated with it.
2903 			 */
2904 			dbuf_destroy(db);
2905 		} else {
2906 			boolean_t do_arc_evict = B_FALSE;
2907 			blkptr_t bp;
2908 			spa_t *spa = dmu_objset_spa(db->db_objset);
2909 
2910 			if (!DBUF_IS_CACHEABLE(db) &&
2911 			    db->db_blkptr != NULL &&
2912 			    !BP_IS_HOLE(db->db_blkptr) &&
2913 			    !BP_IS_EMBEDDED(db->db_blkptr)) {
2914 				do_arc_evict = B_TRUE;
2915 				bp = *db->db_blkptr;
2916 			}
2917 
2918 			if (!DBUF_IS_CACHEABLE(db) ||
2919 			    db->db_pending_evict) {
2920 				dbuf_destroy(db);
2921 			} else if (!multilist_link_active(&db->db_cache_link)) {
2922 				ASSERT3U(db->db_caching_status, ==,
2923 				    DB_NO_CACHE);
2924 
2925 				dbuf_cached_state_t dcs =
2926 				    dbuf_include_in_metadata_cache(db) ?
2927 				    DB_DBUF_METADATA_CACHE : DB_DBUF_CACHE;
2928 				db->db_caching_status = dcs;
2929 
2930 				multilist_insert(dbuf_caches[dcs].cache, db);
2931 				(void) zfs_refcount_add_many(
2932 				    &dbuf_caches[dcs].size, db->db.db_size, db);
2933 				mutex_exit(&db->db_mtx);
2934 
2935 				if (db->db_caching_status == DB_DBUF_CACHE &&
2936 				    !evicting) {
2937 					dbuf_evict_notify();
2938 				}
2939 			}
2940 
2941 			if (do_arc_evict)
2942 				arc_freed(spa, &bp);
2943 		}
2944 	} else {
2945 		mutex_exit(&db->db_mtx);
2946 	}
2947 
2948 }
2949 
2950 #pragma weak dmu_buf_refcount = dbuf_refcount
2951 uint64_t
2952 dbuf_refcount(dmu_buf_impl_t *db)
2953 {
2954 	return (zfs_refcount_count(&db->db_holds));
2955 }
2956 
2957 void *
2958 dmu_buf_replace_user(dmu_buf_t *db_fake, dmu_buf_user_t *old_user,
2959     dmu_buf_user_t *new_user)
2960 {
2961 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2962 
2963 	mutex_enter(&db->db_mtx);
2964 	dbuf_verify_user(db, DBVU_NOT_EVICTING);
2965 	if (db->db_user == old_user)
2966 		db->db_user = new_user;
2967 	else
2968 		old_user = db->db_user;
2969 	dbuf_verify_user(db, DBVU_NOT_EVICTING);
2970 	mutex_exit(&db->db_mtx);
2971 
2972 	return (old_user);
2973 }
2974 
2975 void *
2976 dmu_buf_set_user(dmu_buf_t *db_fake, dmu_buf_user_t *user)
2977 {
2978 	return (dmu_buf_replace_user(db_fake, NULL, user));
2979 }
2980 
2981 void *
2982 dmu_buf_set_user_ie(dmu_buf_t *db_fake, dmu_buf_user_t *user)
2983 {
2984 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2985 
2986 	db->db_user_immediate_evict = TRUE;
2987 	return (dmu_buf_set_user(db_fake, user));
2988 }
2989 
2990 void *
2991 dmu_buf_remove_user(dmu_buf_t *db_fake, dmu_buf_user_t *user)
2992 {
2993 	return (dmu_buf_replace_user(db_fake, user, NULL));
2994 }
2995 
2996 void *
2997 dmu_buf_get_user(dmu_buf_t *db_fake)
2998 {
2999 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
3000 
3001 	dbuf_verify_user(db, DBVU_NOT_EVICTING);
3002 	return (db->db_user);
3003 }
3004 
3005 void
3006 dmu_buf_user_evict_wait()
3007 {
3008 	taskq_wait(dbu_evict_taskq);
3009 }
3010 
3011 blkptr_t *
3012 dmu_buf_get_blkptr(dmu_buf_t *db)
3013 {
3014 	dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
3015 	return (dbi->db_blkptr);
3016 }
3017 
3018 objset_t *
3019 dmu_buf_get_objset(dmu_buf_t *db)
3020 {
3021 	dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
3022 	return (dbi->db_objset);
3023 }
3024 
3025 dnode_t *
3026 dmu_buf_dnode_enter(dmu_buf_t *db)
3027 {
3028 	dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
3029 	DB_DNODE_ENTER(dbi);
3030 	return (DB_DNODE(dbi));
3031 }
3032 
3033 void
3034 dmu_buf_dnode_exit(dmu_buf_t *db)
3035 {
3036 	dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
3037 	DB_DNODE_EXIT(dbi);
3038 }
3039 
3040 static void
3041 dbuf_check_blkptr(dnode_t *dn, dmu_buf_impl_t *db)
3042 {
3043 	/* ASSERT(dmu_tx_is_syncing(tx) */
3044 	ASSERT(MUTEX_HELD(&db->db_mtx));
3045 
3046 	if (db->db_blkptr != NULL)
3047 		return;
3048 
3049 	if (db->db_blkid == DMU_SPILL_BLKID) {
3050 		db->db_blkptr = DN_SPILL_BLKPTR(dn->dn_phys);
3051 		BP_ZERO(db->db_blkptr);
3052 		return;
3053 	}
3054 	if (db->db_level == dn->dn_phys->dn_nlevels-1) {
3055 		/*
3056 		 * This buffer was allocated at a time when there was
3057 		 * no available blkptrs from the dnode, or it was
3058 		 * inappropriate to hook it in (i.e., nlevels mis-match).
3059 		 */
3060 		ASSERT(db->db_blkid < dn->dn_phys->dn_nblkptr);
3061 		ASSERT(db->db_parent == NULL);
3062 		db->db_parent = dn->dn_dbuf;
3063 		db->db_blkptr = &dn->dn_phys->dn_blkptr[db->db_blkid];
3064 		DBUF_VERIFY(db);
3065 	} else {
3066 		dmu_buf_impl_t *parent = db->db_parent;
3067 		int epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
3068 
3069 		ASSERT(dn->dn_phys->dn_nlevels > 1);
3070 		if (parent == NULL) {
3071 			mutex_exit(&db->db_mtx);
3072 			rw_enter(&dn->dn_struct_rwlock, RW_READER);
3073 			parent = dbuf_hold_level(dn, db->db_level + 1,
3074 			    db->db_blkid >> epbs, db);
3075 			rw_exit(&dn->dn_struct_rwlock);
3076 			mutex_enter(&db->db_mtx);
3077 			db->db_parent = parent;
3078 		}
3079 		db->db_blkptr = (blkptr_t *)parent->db.db_data +
3080 		    (db->db_blkid & ((1ULL << epbs) - 1));
3081 		DBUF_VERIFY(db);
3082 	}
3083 }
3084 
3085 static void
3086 dbuf_sync_indirect(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
3087 {
3088 	dmu_buf_impl_t *db = dr->dr_dbuf;
3089 	dnode_t *dn;
3090 	zio_t *zio;
3091 
3092 	ASSERT(dmu_tx_is_syncing(tx));
3093 
3094 	dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
3095 
3096 	mutex_enter(&db->db_mtx);
3097 
3098 	ASSERT(db->db_level > 0);
3099 	DBUF_VERIFY(db);
3100 
3101 	/* Read the block if it hasn't been read yet. */
3102 	if (db->db_buf == NULL) {
3103 		mutex_exit(&db->db_mtx);
3104 		(void) dbuf_read(db, NULL, DB_RF_MUST_SUCCEED);
3105 		mutex_enter(&db->db_mtx);
3106 	}
3107 	ASSERT3U(db->db_state, ==, DB_CACHED);
3108 	ASSERT(db->db_buf != NULL);
3109 
3110 	DB_DNODE_ENTER(db);
3111 	dn = DB_DNODE(db);
3112 	/* Indirect block size must match what the dnode thinks it is. */
3113 	ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
3114 	dbuf_check_blkptr(dn, db);
3115 	DB_DNODE_EXIT(db);
3116 
3117 	/* Provide the pending dirty record to child dbufs */
3118 	db->db_data_pending = dr;
3119 
3120 	mutex_exit(&db->db_mtx);
3121 
3122 	dbuf_write(dr, db->db_buf, tx);
3123 
3124 	zio = dr->dr_zio;
3125 	mutex_enter(&dr->dt.di.dr_mtx);
3126 	dbuf_sync_list(&dr->dt.di.dr_children, db->db_level - 1, tx);
3127 	ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
3128 	mutex_exit(&dr->dt.di.dr_mtx);
3129 	zio_nowait(zio);
3130 }
3131 
3132 static void
3133 dbuf_sync_leaf(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
3134 {
3135 	arc_buf_t **datap = &dr->dt.dl.dr_data;
3136 	dmu_buf_impl_t *db = dr->dr_dbuf;
3137 	dnode_t *dn;
3138 	objset_t *os;
3139 	uint64_t txg = tx->tx_txg;
3140 
3141 	ASSERT(dmu_tx_is_syncing(tx));
3142 
3143 	dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
3144 
3145 	mutex_enter(&db->db_mtx);
3146 	/*
3147 	 * To be synced, we must be dirtied.  But we
3148 	 * might have been freed after the dirty.
3149 	 */
3150 	if (db->db_state == DB_UNCACHED) {
3151 		/* This buffer has been freed since it was dirtied */
3152 		ASSERT(db->db.db_data == NULL);
3153 	} else if (db->db_state == DB_FILL) {
3154 		/* This buffer was freed and is now being re-filled */
3155 		ASSERT(db->db.db_data != dr->dt.dl.dr_data);
3156 	} else {
3157 		ASSERT(db->db_state == DB_CACHED || db->db_state == DB_NOFILL);
3158 	}
3159 	DBUF_VERIFY(db);
3160 
3161 	DB_DNODE_ENTER(db);
3162 	dn = DB_DNODE(db);
3163 
3164 	if (db->db_blkid == DMU_SPILL_BLKID) {
3165 		mutex_enter(&dn->dn_mtx);
3166 		dn->dn_phys->dn_flags |= DNODE_FLAG_SPILL_BLKPTR;
3167 		mutex_exit(&dn->dn_mtx);
3168 	}
3169 
3170 	/*
3171 	 * If this is a bonus buffer, simply copy the bonus data into the
3172 	 * dnode.  It will be written out when the dnode is synced (and it
3173 	 * will be synced, since it must have been dirty for dbuf_sync to
3174 	 * be called).
3175 	 */
3176 	if (db->db_blkid == DMU_BONUS_BLKID) {
3177 		dbuf_dirty_record_t **drp;
3178 
3179 		ASSERT(*datap != NULL);
3180 		ASSERT0(db->db_level);
3181 		ASSERT3U(DN_MAX_BONUS_LEN(dn->dn_phys), <=,
3182 		    DN_SLOTS_TO_BONUSLEN(dn->dn_phys->dn_extra_slots + 1));
3183 		bcopy(*datap, DN_BONUS(dn->dn_phys),
3184 		    DN_MAX_BONUS_LEN(dn->dn_phys));
3185 		DB_DNODE_EXIT(db);
3186 
3187 		if (*datap != db->db.db_data) {
3188 			int slots = DB_DNODE(db)->dn_num_slots;
3189 			int bonuslen = DN_SLOTS_TO_BONUSLEN(slots);
3190 			zio_buf_free(*datap, bonuslen);
3191 			arc_space_return(bonuslen, ARC_SPACE_BONUS);
3192 		}
3193 		db->db_data_pending = NULL;
3194 		drp = &db->db_last_dirty;
3195 		while (*drp != dr)
3196 			drp = &(*drp)->dr_next;
3197 		ASSERT(dr->dr_next == NULL);
3198 		ASSERT(dr->dr_dbuf == db);
3199 		*drp = dr->dr_next;
3200 		kmem_free(dr, sizeof (dbuf_dirty_record_t));
3201 		ASSERT(db->db_dirtycnt > 0);
3202 		db->db_dirtycnt -= 1;
3203 		dbuf_rele_and_unlock(db, (void *)(uintptr_t)txg, B_FALSE);
3204 		return;
3205 	}
3206 
3207 	os = dn->dn_objset;
3208 
3209 	/*
3210 	 * This function may have dropped the db_mtx lock allowing a dmu_sync
3211 	 * operation to sneak in. As a result, we need to ensure that we
3212 	 * don't check the dr_override_state until we have returned from
3213 	 * dbuf_check_blkptr.
3214 	 */
3215 	dbuf_check_blkptr(dn, db);
3216 
3217 	/*
3218 	 * If this buffer is in the middle of an immediate write,
3219 	 * wait for the synchronous IO to complete.
3220 	 */
3221 	while (dr->dt.dl.dr_override_state == DR_IN_DMU_SYNC) {
3222 		ASSERT(dn->dn_object != DMU_META_DNODE_OBJECT);
3223 		cv_wait(&db->db_changed, &db->db_mtx);
3224 		ASSERT(dr->dt.dl.dr_override_state != DR_NOT_OVERRIDDEN);
3225 	}
3226 
3227 	if (db->db_state != DB_NOFILL &&
3228 	    dn->dn_object != DMU_META_DNODE_OBJECT &&
3229 	    zfs_refcount_count(&db->db_holds) > 1 &&
3230 	    dr->dt.dl.dr_override_state != DR_OVERRIDDEN &&
3231 	    *datap == db->db_buf) {
3232 		/*
3233 		 * If this buffer is currently "in use" (i.e., there
3234 		 * are active holds and db_data still references it),
3235 		 * then make a copy before we start the write so that
3236 		 * any modifications from the open txg will not leak
3237 		 * into this write.
3238 		 *
3239 		 * NOTE: this copy does not need to be made for
3240 		 * objects only modified in the syncing context (e.g.
3241 		 * DNONE_DNODE blocks).
3242 		 */
3243 		int psize = arc_buf_size(*datap);
3244 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
3245 		enum zio_compress compress_type = arc_get_compression(*datap);
3246 
3247 		if (compress_type == ZIO_COMPRESS_OFF) {
3248 			*datap = arc_alloc_buf(os->os_spa, db, type, psize);
3249 		} else {
3250 			ASSERT3U(type, ==, ARC_BUFC_DATA);
3251 			int lsize = arc_buf_lsize(*datap);
3252 			*datap = arc_alloc_compressed_buf(os->os_spa, db,
3253 			    psize, lsize, compress_type);
3254 		}
3255 		bcopy(db->db.db_data, (*datap)->b_data, psize);
3256 	}
3257 	db->db_data_pending = dr;
3258 
3259 	mutex_exit(&db->db_mtx);
3260 
3261 	dbuf_write(dr, *datap, tx);
3262 
3263 	ASSERT(!list_link_active(&dr->dr_dirty_node));
3264 	if (dn->dn_object == DMU_META_DNODE_OBJECT) {
3265 		list_insert_tail(&dn->dn_dirty_records[txg&TXG_MASK], dr);
3266 		DB_DNODE_EXIT(db);
3267 	} else {
3268 		/*
3269 		 * Although zio_nowait() does not "wait for an IO", it does
3270 		 * initiate the IO. If this is an empty write it seems plausible
3271 		 * that the IO could actually be completed before the nowait
3272 		 * returns. We need to DB_DNODE_EXIT() first in case
3273 		 * zio_nowait() invalidates the dbuf.
3274 		 */
3275 		DB_DNODE_EXIT(db);
3276 		zio_nowait(dr->dr_zio);
3277 	}
3278 }
3279 
3280 void
3281 dbuf_sync_list(list_t *list, int level, dmu_tx_t *tx)
3282 {
3283 	dbuf_dirty_record_t *dr;
3284 
3285 	while (dr = list_head(list)) {
3286 		if (dr->dr_zio != NULL) {
3287 			/*
3288 			 * If we find an already initialized zio then we
3289 			 * are processing the meta-dnode, and we have finished.
3290 			 * The dbufs for all dnodes are put back on the list
3291 			 * during processing, so that we can zio_wait()
3292 			 * these IOs after initiating all child IOs.
3293 			 */
3294 			ASSERT3U(dr->dr_dbuf->db.db_object, ==,
3295 			    DMU_META_DNODE_OBJECT);
3296 			break;
3297 		}
3298 		if (dr->dr_dbuf->db_blkid != DMU_BONUS_BLKID &&
3299 		    dr->dr_dbuf->db_blkid != DMU_SPILL_BLKID) {
3300 			VERIFY3U(dr->dr_dbuf->db_level, ==, level);
3301 		}
3302 		list_remove(list, dr);
3303 		if (dr->dr_dbuf->db_level > 0)
3304 			dbuf_sync_indirect(dr, tx);
3305 		else
3306 			dbuf_sync_leaf(dr, tx);
3307 	}
3308 }
3309 
3310 /* ARGSUSED */
3311 static void
3312 dbuf_write_ready(zio_t *zio, arc_buf_t *buf, void *vdb)
3313 {
3314 	dmu_buf_impl_t *db = vdb;
3315 	dnode_t *dn;
3316 	blkptr_t *bp = zio->io_bp;
3317 	blkptr_t *bp_orig = &zio->io_bp_orig;
3318 	spa_t *spa = zio->io_spa;
3319 	int64_t delta;
3320 	uint64_t fill = 0;
3321 	int i;
3322 
3323 	ASSERT3P(db->db_blkptr, !=, NULL);
3324 	ASSERT3P(&db->db_data_pending->dr_bp_copy, ==, bp);
3325 
3326 	DB_DNODE_ENTER(db);
3327 	dn = DB_DNODE(db);
3328 	delta = bp_get_dsize_sync(spa, bp) - bp_get_dsize_sync(spa, bp_orig);
3329 	dnode_diduse_space(dn, delta - zio->io_prev_space_delta);
3330 	zio->io_prev_space_delta = delta;
3331 
3332 	if (bp->blk_birth != 0) {
3333 		ASSERT((db->db_blkid != DMU_SPILL_BLKID &&
3334 		    BP_GET_TYPE(bp) == dn->dn_type) ||
3335 		    (db->db_blkid == DMU_SPILL_BLKID &&
3336 		    BP_GET_TYPE(bp) == dn->dn_bonustype) ||
3337 		    BP_IS_EMBEDDED(bp));
3338 		ASSERT(BP_GET_LEVEL(bp) == db->db_level);
3339 	}
3340 
3341 	mutex_enter(&db->db_mtx);
3342 
3343 #ifdef ZFS_DEBUG
3344 	if (db->db_blkid == DMU_SPILL_BLKID) {
3345 		ASSERT(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR);
3346 		ASSERT(!(BP_IS_HOLE(bp)) &&
3347 		    db->db_blkptr == DN_SPILL_BLKPTR(dn->dn_phys));
3348 	}
3349 #endif
3350 
3351 	if (db->db_level == 0) {
3352 		mutex_enter(&dn->dn_mtx);
3353 		if (db->db_blkid > dn->dn_phys->dn_maxblkid &&
3354 		    db->db_blkid != DMU_SPILL_BLKID)
3355 			dn->dn_phys->dn_maxblkid = db->db_blkid;
3356 		mutex_exit(&dn->dn_mtx);
3357 
3358 		if (dn->dn_type == DMU_OT_DNODE) {
3359 			i = 0;
3360 			while (i < db->db.db_size) {
3361 				dnode_phys_t *dnp =
3362 				    (void *)(((char *)db->db.db_data) + i);
3363 
3364 				i += DNODE_MIN_SIZE;
3365 				if (dnp->dn_type != DMU_OT_NONE) {
3366 					fill++;
3367 					i += dnp->dn_extra_slots *
3368 					    DNODE_MIN_SIZE;
3369 				}
3370 			}
3371 		} else {
3372 			if (BP_IS_HOLE(bp)) {
3373 				fill = 0;
3374 			} else {
3375 				fill = 1;
3376 			}
3377 		}
3378 	} else {
3379 		blkptr_t *ibp = db->db.db_data;
3380 		ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
3381 		for (i = db->db.db_size >> SPA_BLKPTRSHIFT; i > 0; i--, ibp++) {
3382 			if (BP_IS_HOLE(ibp))
3383 				continue;
3384 			fill += BP_GET_FILL(ibp);
3385 		}
3386 	}
3387 	DB_DNODE_EXIT(db);
3388 
3389 	if (!BP_IS_EMBEDDED(bp))
3390 		bp->blk_fill = fill;
3391 
3392 	mutex_exit(&db->db_mtx);
3393 
3394 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
3395 	*db->db_blkptr = *bp;
3396 	rw_exit(&dn->dn_struct_rwlock);
3397 }
3398 
3399 /* ARGSUSED */
3400 /*
3401  * This function gets called just prior to running through the compression
3402  * stage of the zio pipeline. If we're an indirect block comprised of only
3403  * holes, then we want this indirect to be compressed away to a hole. In
3404  * order to do that we must zero out any information about the holes that
3405  * this indirect points to prior to before we try to compress it.
3406  */
3407 static void
3408 dbuf_write_children_ready(zio_t *zio, arc_buf_t *buf, void *vdb)
3409 {
3410 	dmu_buf_impl_t *db = vdb;
3411 	dnode_t *dn;
3412 	blkptr_t *bp;
3413 	unsigned int epbs, i;
3414 
3415 	ASSERT3U(db->db_level, >, 0);
3416 	DB_DNODE_ENTER(db);
3417 	dn = DB_DNODE(db);
3418 	epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
3419 	ASSERT3U(epbs, <, 31);
3420 
3421 	/* Determine if all our children are holes */
3422 	for (i = 0, bp = db->db.db_data; i < 1 << epbs; i++, bp++) {
3423 		if (!BP_IS_HOLE(bp))
3424 			break;
3425 	}
3426 
3427 	/*
3428 	 * If all the children are holes, then zero them all out so that
3429 	 * we may get compressed away.
3430 	 */
3431 	if (i == 1 << epbs) {
3432 		/*
3433 		 * We only found holes. Grab the rwlock to prevent
3434 		 * anybody from reading the blocks we're about to
3435 		 * zero out.
3436 		 */
3437 		rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
3438 		bzero(db->db.db_data, db->db.db_size);
3439 		rw_exit(&dn->dn_struct_rwlock);
3440 	}
3441 	DB_DNODE_EXIT(db);
3442 }
3443 
3444 /*
3445  * The SPA will call this callback several times for each zio - once
3446  * for every physical child i/o (zio->io_phys_children times).  This
3447  * allows the DMU to monitor the progress of each logical i/o.  For example,
3448  * there may be 2 copies of an indirect block, or many fragments of a RAID-Z
3449  * block.  There may be a long delay before all copies/fragments are completed,
3450  * so this callback allows us to retire dirty space gradually, as the physical
3451  * i/os complete.
3452  */
3453 /* ARGSUSED */
3454 static void
3455 dbuf_write_physdone(zio_t *zio, arc_buf_t *buf, void *arg)
3456 {
3457 	dmu_buf_impl_t *db = arg;
3458 	objset_t *os = db->db_objset;
3459 	dsl_pool_t *dp = dmu_objset_pool(os);
3460 	dbuf_dirty_record_t *dr;
3461 	int delta = 0;
3462 
3463 	dr = db->db_data_pending;
3464 	ASSERT3U(dr->dr_txg, ==, zio->io_txg);
3465 
3466 	/*
3467 	 * The callback will be called io_phys_children times.  Retire one
3468 	 * portion of our dirty space each time we are called.  Any rounding
3469 	 * error will be cleaned up by dsl_pool_sync()'s call to
3470 	 * dsl_pool_undirty_space().
3471 	 */
3472 	delta = dr->dr_accounted / zio->io_phys_children;
3473 	dsl_pool_undirty_space(dp, delta, zio->io_txg);
3474 }
3475 
3476 /* ARGSUSED */
3477 static void
3478 dbuf_write_done(zio_t *zio, arc_buf_t *buf, void *vdb)
3479 {
3480 	dmu_buf_impl_t *db = vdb;
3481 	blkptr_t *bp_orig = &zio->io_bp_orig;
3482 	blkptr_t *bp = db->db_blkptr;
3483 	objset_t *os = db->db_objset;
3484 	dmu_tx_t *tx = os->os_synctx;
3485 	dbuf_dirty_record_t **drp, *dr;
3486 
3487 	ASSERT0(zio->io_error);
3488 	ASSERT(db->db_blkptr == bp);
3489 
3490 	/*
3491 	 * For nopwrites and rewrites we ensure that the bp matches our
3492 	 * original and bypass all the accounting.
3493 	 */
3494 	if (zio->io_flags & (ZIO_FLAG_IO_REWRITE | ZIO_FLAG_NOPWRITE)) {
3495 		ASSERT(BP_EQUAL(bp, bp_orig));
3496 	} else {
3497 		dsl_dataset_t *ds = os->os_dsl_dataset;
3498 		(void) dsl_dataset_block_kill(ds, bp_orig, tx, B_TRUE);
3499 		dsl_dataset_block_born(ds, bp, tx);
3500 	}
3501 
3502 	mutex_enter(&db->db_mtx);
3503 
3504 	DBUF_VERIFY(db);
3505 
3506 	drp = &db->db_last_dirty;
3507 	while ((dr = *drp) != db->db_data_pending)
3508 		drp = &dr->dr_next;
3509 	ASSERT(!list_link_active(&dr->dr_dirty_node));
3510 	ASSERT(dr->dr_dbuf == db);
3511 	ASSERT(dr->dr_next == NULL);
3512 	*drp = dr->dr_next;
3513 
3514 #ifdef ZFS_DEBUG
3515 	if (db->db_blkid == DMU_SPILL_BLKID) {
3516 		dnode_t *dn;
3517 
3518 		DB_DNODE_ENTER(db);
3519 		dn = DB_DNODE(db);
3520 		ASSERT(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR);
3521 		ASSERT(!(BP_IS_HOLE(db->db_blkptr)) &&
3522 		    db->db_blkptr == DN_SPILL_BLKPTR(dn->dn_phys));
3523 		DB_DNODE_EXIT(db);
3524 	}
3525 #endif
3526 
3527 	if (db->db_level == 0) {
3528 		ASSERT(db->db_blkid != DMU_BONUS_BLKID);
3529 		ASSERT(dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN);
3530 		if (db->db_state != DB_NOFILL) {
3531 			if (dr->dt.dl.dr_data != db->db_buf)
3532 				arc_buf_destroy(dr->dt.dl.dr_data, db);
3533 		}
3534 	} else {
3535 		dnode_t *dn;
3536 
3537 		DB_DNODE_ENTER(db);
3538 		dn = DB_DNODE(db);
3539 		ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
3540 		ASSERT3U(db->db.db_size, ==, 1 << dn->dn_phys->dn_indblkshift);
3541 		if (!BP_IS_HOLE(db->db_blkptr)) {
3542 			int epbs =
3543 			    dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
3544 			ASSERT3U(db->db_blkid, <=,
3545 			    dn->dn_phys->dn_maxblkid >> (db->db_level * epbs));
3546 			ASSERT3U(BP_GET_LSIZE(db->db_blkptr), ==,
3547 			    db->db.db_size);
3548 		}
3549 		DB_DNODE_EXIT(db);
3550 		mutex_destroy(&dr->dt.di.dr_mtx);
3551 		list_destroy(&dr->dt.di.dr_children);
3552 	}
3553 	kmem_free(dr, sizeof (dbuf_dirty_record_t));
3554 
3555 	cv_broadcast(&db->db_changed);
3556 	ASSERT(db->db_dirtycnt > 0);
3557 	db->db_dirtycnt -= 1;
3558 	db->db_data_pending = NULL;
3559 	dbuf_rele_and_unlock(db, (void *)(uintptr_t)tx->tx_txg, B_FALSE);
3560 }
3561 
3562 static void
3563 dbuf_write_nofill_ready(zio_t *zio)
3564 {
3565 	dbuf_write_ready(zio, NULL, zio->io_private);
3566 }
3567 
3568 static void
3569 dbuf_write_nofill_done(zio_t *zio)
3570 {
3571 	dbuf_write_done(zio, NULL, zio->io_private);
3572 }
3573 
3574 static void
3575 dbuf_write_override_ready(zio_t *zio)
3576 {
3577 	dbuf_dirty_record_t *dr = zio->io_private;
3578 	dmu_buf_impl_t *db = dr->dr_dbuf;
3579 
3580 	dbuf_write_ready(zio, NULL, db);
3581 }
3582 
3583 static void
3584 dbuf_write_override_done(zio_t *zio)
3585 {
3586 	dbuf_dirty_record_t *dr = zio->io_private;
3587 	dmu_buf_impl_t *db = dr->dr_dbuf;
3588 	blkptr_t *obp = &dr->dt.dl.dr_overridden_by;
3589 
3590 	mutex_enter(&db->db_mtx);
3591 	if (!BP_EQUAL(zio->io_bp, obp)) {
3592 		if (!BP_IS_HOLE(obp))
3593 			dsl_free(spa_get_dsl(zio->io_spa), zio->io_txg, obp);
3594 		arc_release(dr->dt.dl.dr_data, db);
3595 	}
3596 	mutex_exit(&db->db_mtx);
3597 	dbuf_write_done(zio, NULL, db);
3598 
3599 	if (zio->io_abd != NULL)
3600 		abd_put(zio->io_abd);
3601 }
3602 
3603 typedef struct dbuf_remap_impl_callback_arg {
3604 	objset_t	*drica_os;
3605 	uint64_t	drica_blk_birth;
3606 	dmu_tx_t	*drica_tx;
3607 } dbuf_remap_impl_callback_arg_t;
3608 
3609 static void
3610 dbuf_remap_impl_callback(uint64_t vdev, uint64_t offset, uint64_t size,
3611     void *arg)
3612 {
3613 	dbuf_remap_impl_callback_arg_t *drica = arg;
3614 	objset_t *os = drica->drica_os;
3615 	spa_t *spa = dmu_objset_spa(os);
3616 	dmu_tx_t *tx = drica->drica_tx;
3617 
3618 	ASSERT(dsl_pool_sync_context(spa_get_dsl(spa)));
3619 
3620 	if (os == spa_meta_objset(spa)) {
3621 		spa_vdev_indirect_mark_obsolete(spa, vdev, offset, size, tx);
3622 	} else {
3623 		dsl_dataset_block_remapped(dmu_objset_ds(os), vdev, offset,
3624 		    size, drica->drica_blk_birth, tx);
3625 	}
3626 }
3627 
3628 static void
3629 dbuf_remap_impl(dnode_t *dn, blkptr_t *bp, dmu_tx_t *tx)
3630 {
3631 	blkptr_t bp_copy = *bp;
3632 	spa_t *spa = dmu_objset_spa(dn->dn_objset);
3633 	dbuf_remap_impl_callback_arg_t drica;
3634 
3635 	ASSERT(dsl_pool_sync_context(spa_get_dsl(spa)));
3636 
3637 	drica.drica_os = dn->dn_objset;
3638 	drica.drica_blk_birth = bp->blk_birth;
3639 	drica.drica_tx = tx;
3640 	if (spa_remap_blkptr(spa, &bp_copy, dbuf_remap_impl_callback,
3641 	    &drica)) {
3642 		/*
3643 		 * The struct_rwlock prevents dbuf_read_impl() from
3644 		 * dereferencing the BP while we are changing it.  To
3645 		 * avoid lock contention, only grab it when we are actually
3646 		 * changing the BP.
3647 		 */
3648 		rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
3649 		*bp = bp_copy;
3650 		rw_exit(&dn->dn_struct_rwlock);
3651 	}
3652 }
3653 
3654 /*
3655  * Returns true if a dbuf_remap would modify the dbuf. We do this by attempting
3656  * to remap a copy of every bp in the dbuf.
3657  */
3658 boolean_t
3659 dbuf_can_remap(const dmu_buf_impl_t *db)
3660 {
3661 	spa_t *spa = dmu_objset_spa(db->db_objset);
3662 	blkptr_t *bp = db->db.db_data;
3663 	boolean_t ret = B_FALSE;
3664 
3665 	ASSERT3U(db->db_level, >, 0);
3666 	ASSERT3S(db->db_state, ==, DB_CACHED);
3667 
3668 	ASSERT(spa_feature_is_active(spa, SPA_FEATURE_DEVICE_REMOVAL));
3669 
3670 	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3671 	for (int i = 0; i < db->db.db_size >> SPA_BLKPTRSHIFT; i++) {
3672 		blkptr_t bp_copy = bp[i];
3673 		if (spa_remap_blkptr(spa, &bp_copy, NULL, NULL)) {
3674 			ret = B_TRUE;
3675 			break;
3676 		}
3677 	}
3678 	spa_config_exit(spa, SCL_VDEV, FTAG);
3679 
3680 	return (ret);
3681 }
3682 
3683 boolean_t
3684 dnode_needs_remap(const dnode_t *dn)
3685 {
3686 	spa_t *spa = dmu_objset_spa(dn->dn_objset);
3687 	boolean_t ret = B_FALSE;
3688 
3689 	if (dn->dn_phys->dn_nlevels == 0) {
3690 		return (B_FALSE);
3691 	}
3692 
3693 	ASSERT(spa_feature_is_active(spa, SPA_FEATURE_DEVICE_REMOVAL));
3694 
3695 	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3696 	for (int j = 0; j < dn->dn_phys->dn_nblkptr; j++) {
3697 		blkptr_t bp_copy = dn->dn_phys->dn_blkptr[j];
3698 		if (spa_remap_blkptr(spa, &bp_copy, NULL, NULL)) {
3699 			ret = B_TRUE;
3700 			break;
3701 		}
3702 	}
3703 	spa_config_exit(spa, SCL_VDEV, FTAG);
3704 
3705 	return (ret);
3706 }
3707 
3708 /*
3709  * Remap any existing BP's to concrete vdevs, if possible.
3710  */
3711 static void
3712 dbuf_remap(dnode_t *dn, dmu_buf_impl_t *db, dmu_tx_t *tx)
3713 {
3714 	spa_t *spa = dmu_objset_spa(db->db_objset);
3715 	ASSERT(dsl_pool_sync_context(spa_get_dsl(spa)));
3716 
3717 	if (!spa_feature_is_active(spa, SPA_FEATURE_DEVICE_REMOVAL))
3718 		return;
3719 
3720 	if (db->db_level > 0) {
3721 		blkptr_t *bp = db->db.db_data;
3722 		for (int i = 0; i < db->db.db_size >> SPA_BLKPTRSHIFT; i++) {
3723 			dbuf_remap_impl(dn, &bp[i], tx);
3724 		}
3725 	} else if (db->db.db_object == DMU_META_DNODE_OBJECT) {
3726 		dnode_phys_t *dnp = db->db.db_data;
3727 		ASSERT3U(db->db_dnode_handle->dnh_dnode->dn_type, ==,
3728 		    DMU_OT_DNODE);
3729 		for (int i = 0; i < db->db.db_size >> DNODE_SHIFT; i++) {
3730 			for (int j = 0; j < dnp[i].dn_nblkptr; j++) {
3731 				dbuf_remap_impl(dn, &dnp[i].dn_blkptr[j], tx);
3732 			}
3733 		}
3734 	}
3735 }
3736 
3737 
3738 /* Issue I/O to commit a dirty buffer to disk. */
3739 static void
3740 dbuf_write(dbuf_dirty_record_t *dr, arc_buf_t *data, dmu_tx_t *tx)
3741 {
3742 	dmu_buf_impl_t *db = dr->dr_dbuf;
3743 	dnode_t *dn;
3744 	objset_t *os;
3745 	dmu_buf_impl_t *parent = db->db_parent;
3746 	uint64_t txg = tx->tx_txg;
3747 	zbookmark_phys_t zb;
3748 	zio_prop_t zp;
3749 	zio_t *zio;
3750 	int wp_flag = 0;
3751 
3752 	ASSERT(dmu_tx_is_syncing(tx));
3753 
3754 	DB_DNODE_ENTER(db);
3755 	dn = DB_DNODE(db);
3756 	os = dn->dn_objset;
3757 
3758 	if (db->db_state != DB_NOFILL) {
3759 		if (db->db_level > 0 || dn->dn_type == DMU_OT_DNODE) {
3760 			/*
3761 			 * Private object buffers are released here rather
3762 			 * than in dbuf_dirty() since they are only modified
3763 			 * in the syncing context and we don't want the
3764 			 * overhead of making multiple copies of the data.
3765 			 */
3766 			if (BP_IS_HOLE(db->db_blkptr)) {
3767 				arc_buf_thaw(data);
3768 			} else {
3769 				dbuf_release_bp(db);
3770 			}
3771 			dbuf_remap(dn, db, tx);
3772 		}
3773 	}
3774 
3775 	if (parent != dn->dn_dbuf) {
3776 		/* Our parent is an indirect block. */
3777 		/* We have a dirty parent that has been scheduled for write. */
3778 		ASSERT(parent && parent->db_data_pending);
3779 		/* Our parent's buffer is one level closer to the dnode. */
3780 		ASSERT(db->db_level == parent->db_level-1);
3781 		/*
3782 		 * We're about to modify our parent's db_data by modifying
3783 		 * our block pointer, so the parent must be released.
3784 		 */
3785 		ASSERT(arc_released(parent->db_buf));
3786 		zio = parent->db_data_pending->dr_zio;
3787 	} else {
3788 		/* Our parent is the dnode itself. */
3789 		ASSERT((db->db_level == dn->dn_phys->dn_nlevels-1 &&
3790 		    db->db_blkid != DMU_SPILL_BLKID) ||
3791 		    (db->db_blkid == DMU_SPILL_BLKID && db->db_level == 0));
3792 		if (db->db_blkid != DMU_SPILL_BLKID)
3793 			ASSERT3P(db->db_blkptr, ==,
3794 			    &dn->dn_phys->dn_blkptr[db->db_blkid]);
3795 		zio = dn->dn_zio;
3796 	}
3797 
3798 	ASSERT(db->db_level == 0 || data == db->db_buf);
3799 	ASSERT3U(db->db_blkptr->blk_birth, <=, txg);
3800 	ASSERT(zio);
3801 
3802 	SET_BOOKMARK(&zb, os->os_dsl_dataset ?
3803 	    os->os_dsl_dataset->ds_object : DMU_META_OBJSET,
3804 	    db->db.db_object, db->db_level, db->db_blkid);
3805 
3806 	if (db->db_blkid == DMU_SPILL_BLKID)
3807 		wp_flag = WP_SPILL;
3808 	wp_flag |= (db->db_state == DB_NOFILL) ? WP_NOFILL : 0;
3809 
3810 	dmu_write_policy(os, dn, db->db_level, wp_flag, &zp);
3811 	DB_DNODE_EXIT(db);
3812 
3813 	/*
3814 	 * We copy the blkptr now (rather than when we instantiate the dirty
3815 	 * record), because its value can change between open context and
3816 	 * syncing context. We do not need to hold dn_struct_rwlock to read
3817 	 * db_blkptr because we are in syncing context.
3818 	 */
3819 	dr->dr_bp_copy = *db->db_blkptr;
3820 
3821 	if (db->db_level == 0 &&
3822 	    dr->dt.dl.dr_override_state == DR_OVERRIDDEN) {
3823 		/*
3824 		 * The BP for this block has been provided by open context
3825 		 * (by dmu_sync() or dmu_buf_write_embedded()).
3826 		 */
3827 		abd_t *contents = (data != NULL) ?
3828 		    abd_get_from_buf(data->b_data, arc_buf_size(data)) : NULL;
3829 
3830 		dr->dr_zio = zio_write(zio, os->os_spa, txg, &dr->dr_bp_copy,
3831 		    contents, db->db.db_size, db->db.db_size, &zp,
3832 		    dbuf_write_override_ready, NULL, NULL,
3833 		    dbuf_write_override_done,
3834 		    dr, ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
3835 		mutex_enter(&db->db_mtx);
3836 		dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
3837 		zio_write_override(dr->dr_zio, &dr->dt.dl.dr_overridden_by,
3838 		    dr->dt.dl.dr_copies, dr->dt.dl.dr_nopwrite);
3839 		mutex_exit(&db->db_mtx);
3840 	} else if (db->db_state == DB_NOFILL) {
3841 		ASSERT(zp.zp_checksum == ZIO_CHECKSUM_OFF ||
3842 		    zp.zp_checksum == ZIO_CHECKSUM_NOPARITY);
3843 		dr->dr_zio = zio_write(zio, os->os_spa, txg,
3844 		    &dr->dr_bp_copy, NULL, db->db.db_size, db->db.db_size, &zp,
3845 		    dbuf_write_nofill_ready, NULL, NULL,
3846 		    dbuf_write_nofill_done, db,
3847 		    ZIO_PRIORITY_ASYNC_WRITE,
3848 		    ZIO_FLAG_MUSTSUCCEED | ZIO_FLAG_NODATA, &zb);
3849 	} else {
3850 		ASSERT(arc_released(data));
3851 
3852 		/*
3853 		 * For indirect blocks, we want to setup the children
3854 		 * ready callback so that we can properly handle an indirect
3855 		 * block that only contains holes.
3856 		 */
3857 		arc_done_func_t *children_ready_cb = NULL;
3858 		if (db->db_level != 0)
3859 			children_ready_cb = dbuf_write_children_ready;
3860 
3861 		dr->dr_zio = arc_write(zio, os->os_spa, txg,
3862 		    &dr->dr_bp_copy, data, DBUF_IS_L2CACHEABLE(db),
3863 		    &zp, dbuf_write_ready, children_ready_cb,
3864 		    dbuf_write_physdone, dbuf_write_done, db,
3865 		    ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
3866 	}
3867 }
3868