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