xref: /titanic_41/usr/src/uts/common/fs/zfs/dbuf.c (revision 55d97424a9cd61c5c4deb24127804a1dac5bf1df)
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, 2015 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  */
29 
30 #include <sys/zfs_context.h>
31 #include <sys/dmu.h>
32 #include <sys/dmu_send.h>
33 #include <sys/dmu_impl.h>
34 #include <sys/dbuf.h>
35 #include <sys/dmu_objset.h>
36 #include <sys/dsl_dataset.h>
37 #include <sys/dsl_dir.h>
38 #include <sys/dmu_tx.h>
39 #include <sys/spa.h>
40 #include <sys/zio.h>
41 #include <sys/dmu_zfetch.h>
42 #include <sys/sa.h>
43 #include <sys/sa_impl.h>
44 #include <sys/zfeature.h>
45 #include <sys/blkptr.h>
46 #include <sys/range_tree.h>
47 
48 /*
49  * Number of times that zfs_free_range() took the slow path while doing
50  * a zfs receive.  A nonzero value indicates a potential performance problem.
51  */
52 uint64_t zfs_free_range_recv_miss;
53 
54 static void dbuf_destroy(dmu_buf_impl_t *db);
55 static boolean_t dbuf_undirty(dmu_buf_impl_t *db, dmu_tx_t *tx);
56 static void dbuf_write(dbuf_dirty_record_t *dr, arc_buf_t *data, dmu_tx_t *tx);
57 
58 #ifndef __lint
59 extern inline void dmu_buf_init_user(dmu_buf_user_t *dbu,
60     dmu_buf_evict_func_t *evict_func, dmu_buf_t **clear_on_evict_dbufp);
61 #endif /* ! __lint */
62 
63 /*
64  * Global data structures and functions for the dbuf cache.
65  */
66 static kmem_cache_t *dbuf_cache;
67 static taskq_t *dbu_evict_taskq;
68 
69 /* ARGSUSED */
70 static int
71 dbuf_cons(void *vdb, void *unused, int kmflag)
72 {
73 	dmu_buf_impl_t *db = vdb;
74 	bzero(db, sizeof (dmu_buf_impl_t));
75 
76 	mutex_init(&db->db_mtx, NULL, MUTEX_DEFAULT, NULL);
77 	cv_init(&db->db_changed, NULL, CV_DEFAULT, NULL);
78 	refcount_create(&db->db_holds);
79 
80 	return (0);
81 }
82 
83 /* ARGSUSED */
84 static void
85 dbuf_dest(void *vdb, void *unused)
86 {
87 	dmu_buf_impl_t *db = vdb;
88 	mutex_destroy(&db->db_mtx);
89 	cv_destroy(&db->db_changed);
90 	refcount_destroy(&db->db_holds);
91 }
92 
93 /*
94  * dbuf hash table routines
95  */
96 static dbuf_hash_table_t dbuf_hash_table;
97 
98 static uint64_t dbuf_hash_count;
99 
100 static uint64_t
101 dbuf_hash(void *os, uint64_t obj, uint8_t lvl, uint64_t blkid)
102 {
103 	uintptr_t osv = (uintptr_t)os;
104 	uint64_t crc = -1ULL;
105 
106 	ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
107 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (lvl)) & 0xFF];
108 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (osv >> 6)) & 0xFF];
109 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (obj >> 0)) & 0xFF];
110 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (obj >> 8)) & 0xFF];
111 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (blkid >> 0)) & 0xFF];
112 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (blkid >> 8)) & 0xFF];
113 
114 	crc ^= (osv>>14) ^ (obj>>16) ^ (blkid>>16);
115 
116 	return (crc);
117 }
118 
119 #define	DBUF_HASH(os, obj, level, blkid) dbuf_hash(os, obj, level, blkid);
120 
121 #define	DBUF_EQUAL(dbuf, os, obj, level, blkid)		\
122 	((dbuf)->db.db_object == (obj) &&		\
123 	(dbuf)->db_objset == (os) &&			\
124 	(dbuf)->db_level == (level) &&			\
125 	(dbuf)->db_blkid == (blkid))
126 
127 dmu_buf_impl_t *
128 dbuf_find(objset_t *os, uint64_t obj, uint8_t level, uint64_t blkid)
129 {
130 	dbuf_hash_table_t *h = &dbuf_hash_table;
131 	uint64_t hv = DBUF_HASH(os, obj, level, blkid);
132 	uint64_t idx = hv & h->hash_table_mask;
133 	dmu_buf_impl_t *db;
134 
135 	mutex_enter(DBUF_HASH_MUTEX(h, idx));
136 	for (db = h->hash_table[idx]; db != NULL; db = db->db_hash_next) {
137 		if (DBUF_EQUAL(db, os, obj, level, blkid)) {
138 			mutex_enter(&db->db_mtx);
139 			if (db->db_state != DB_EVICTING) {
140 				mutex_exit(DBUF_HASH_MUTEX(h, idx));
141 				return (db);
142 			}
143 			mutex_exit(&db->db_mtx);
144 		}
145 	}
146 	mutex_exit(DBUF_HASH_MUTEX(h, idx));
147 	return (NULL);
148 }
149 
150 static dmu_buf_impl_t *
151 dbuf_find_bonus(objset_t *os, uint64_t object)
152 {
153 	dnode_t *dn;
154 	dmu_buf_impl_t *db = NULL;
155 
156 	if (dnode_hold(os, object, FTAG, &dn) == 0) {
157 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
158 		if (dn->dn_bonus != NULL) {
159 			db = dn->dn_bonus;
160 			mutex_enter(&db->db_mtx);
161 		}
162 		rw_exit(&dn->dn_struct_rwlock);
163 		dnode_rele(dn, FTAG);
164 	}
165 	return (db);
166 }
167 
168 /*
169  * Insert an entry into the hash table.  If there is already an element
170  * equal to elem in the hash table, then the already existing element
171  * will be returned and the new element will not be inserted.
172  * Otherwise returns NULL.
173  */
174 static dmu_buf_impl_t *
175 dbuf_hash_insert(dmu_buf_impl_t *db)
176 {
177 	dbuf_hash_table_t *h = &dbuf_hash_table;
178 	objset_t *os = db->db_objset;
179 	uint64_t obj = db->db.db_object;
180 	int level = db->db_level;
181 	uint64_t blkid = db->db_blkid;
182 	uint64_t hv = DBUF_HASH(os, obj, level, blkid);
183 	uint64_t idx = hv & h->hash_table_mask;
184 	dmu_buf_impl_t *dbf;
185 
186 	mutex_enter(DBUF_HASH_MUTEX(h, idx));
187 	for (dbf = h->hash_table[idx]; dbf != NULL; dbf = dbf->db_hash_next) {
188 		if (DBUF_EQUAL(dbf, os, obj, level, blkid)) {
189 			mutex_enter(&dbf->db_mtx);
190 			if (dbf->db_state != DB_EVICTING) {
191 				mutex_exit(DBUF_HASH_MUTEX(h, idx));
192 				return (dbf);
193 			}
194 			mutex_exit(&dbf->db_mtx);
195 		}
196 	}
197 
198 	mutex_enter(&db->db_mtx);
199 	db->db_hash_next = h->hash_table[idx];
200 	h->hash_table[idx] = db;
201 	mutex_exit(DBUF_HASH_MUTEX(h, idx));
202 	atomic_inc_64(&dbuf_hash_count);
203 
204 	return (NULL);
205 }
206 
207 /*
208  * Remove an entry from the hash table.  It must be in the EVICTING state.
209  */
210 static void
211 dbuf_hash_remove(dmu_buf_impl_t *db)
212 {
213 	dbuf_hash_table_t *h = &dbuf_hash_table;
214 	uint64_t hv = DBUF_HASH(db->db_objset, db->db.db_object,
215 	    db->db_level, db->db_blkid);
216 	uint64_t idx = hv & h->hash_table_mask;
217 	dmu_buf_impl_t *dbf, **dbp;
218 
219 	/*
220 	 * We musn't hold db_mtx to maintain lock ordering:
221 	 * DBUF_HASH_MUTEX > db_mtx.
222 	 */
223 	ASSERT(refcount_is_zero(&db->db_holds));
224 	ASSERT(db->db_state == DB_EVICTING);
225 	ASSERT(!MUTEX_HELD(&db->db_mtx));
226 
227 	mutex_enter(DBUF_HASH_MUTEX(h, idx));
228 	dbp = &h->hash_table[idx];
229 	while ((dbf = *dbp) != db) {
230 		dbp = &dbf->db_hash_next;
231 		ASSERT(dbf != NULL);
232 	}
233 	*dbp = db->db_hash_next;
234 	db->db_hash_next = NULL;
235 	mutex_exit(DBUF_HASH_MUTEX(h, idx));
236 	atomic_dec_64(&dbuf_hash_count);
237 }
238 
239 static arc_evict_func_t dbuf_do_evict;
240 
241 typedef enum {
242 	DBVU_EVICTING,
243 	DBVU_NOT_EVICTING
244 } dbvu_verify_type_t;
245 
246 static void
247 dbuf_verify_user(dmu_buf_impl_t *db, dbvu_verify_type_t verify_type)
248 {
249 #ifdef ZFS_DEBUG
250 	int64_t holds;
251 
252 	if (db->db_user == NULL)
253 		return;
254 
255 	/* Only data blocks support the attachment of user data. */
256 	ASSERT(db->db_level == 0);
257 
258 	/* Clients must resolve a dbuf before attaching user data. */
259 	ASSERT(db->db.db_data != NULL);
260 	ASSERT3U(db->db_state, ==, DB_CACHED);
261 
262 	holds = refcount_count(&db->db_holds);
263 	if (verify_type == DBVU_EVICTING) {
264 		/*
265 		 * Immediate eviction occurs when holds == dirtycnt.
266 		 * For normal eviction buffers, holds is zero on
267 		 * eviction, except when dbuf_fix_old_data() calls
268 		 * dbuf_clear_data().  However, the hold count can grow
269 		 * during eviction even though db_mtx is held (see
270 		 * dmu_bonus_hold() for an example), so we can only
271 		 * test the generic invariant that holds >= dirtycnt.
272 		 */
273 		ASSERT3U(holds, >=, db->db_dirtycnt);
274 	} else {
275 		if (db->db_user_immediate_evict == TRUE)
276 			ASSERT3U(holds, >=, db->db_dirtycnt);
277 		else
278 			ASSERT3U(holds, >, 0);
279 	}
280 #endif
281 }
282 
283 static void
284 dbuf_evict_user(dmu_buf_impl_t *db)
285 {
286 	dmu_buf_user_t *dbu = db->db_user;
287 
288 	ASSERT(MUTEX_HELD(&db->db_mtx));
289 
290 	if (dbu == NULL)
291 		return;
292 
293 	dbuf_verify_user(db, DBVU_EVICTING);
294 	db->db_user = NULL;
295 
296 #ifdef ZFS_DEBUG
297 	if (dbu->dbu_clear_on_evict_dbufp != NULL)
298 		*dbu->dbu_clear_on_evict_dbufp = NULL;
299 #endif
300 
301 	/*
302 	 * Invoke the callback from a taskq to avoid lock order reversals
303 	 * and limit stack depth.
304 	 */
305 	taskq_dispatch_ent(dbu_evict_taskq, dbu->dbu_evict_func, dbu, 0,
306 	    &dbu->dbu_tqent);
307 }
308 
309 boolean_t
310 dbuf_is_metadata(dmu_buf_impl_t *db)
311 {
312 	if (db->db_level > 0) {
313 		return (B_TRUE);
314 	} else {
315 		boolean_t is_metadata;
316 
317 		DB_DNODE_ENTER(db);
318 		is_metadata = DMU_OT_IS_METADATA(DB_DNODE(db)->dn_type);
319 		DB_DNODE_EXIT(db);
320 
321 		return (is_metadata);
322 	}
323 }
324 
325 void
326 dbuf_evict(dmu_buf_impl_t *db)
327 {
328 	ASSERT(MUTEX_HELD(&db->db_mtx));
329 	ASSERT(db->db_buf == NULL);
330 	ASSERT(db->db_data_pending == NULL);
331 
332 	dbuf_clear(db);
333 	dbuf_destroy(db);
334 }
335 
336 void
337 dbuf_init(void)
338 {
339 	uint64_t hsize = 1ULL << 16;
340 	dbuf_hash_table_t *h = &dbuf_hash_table;
341 	int i;
342 
343 	/*
344 	 * The hash table is big enough to fill all of physical memory
345 	 * with an average 4K block size.  The table will take up
346 	 * totalmem*sizeof(void*)/4K (i.e. 2MB/GB with 8-byte pointers).
347 	 */
348 	while (hsize * 4096 < physmem * PAGESIZE)
349 		hsize <<= 1;
350 
351 retry:
352 	h->hash_table_mask = hsize - 1;
353 	h->hash_table = kmem_zalloc(hsize * sizeof (void *), KM_NOSLEEP);
354 	if (h->hash_table == NULL) {
355 		/* XXX - we should really return an error instead of assert */
356 		ASSERT(hsize > (1ULL << 10));
357 		hsize >>= 1;
358 		goto retry;
359 	}
360 
361 	dbuf_cache = kmem_cache_create("dmu_buf_impl_t",
362 	    sizeof (dmu_buf_impl_t),
363 	    0, dbuf_cons, dbuf_dest, NULL, NULL, NULL, 0);
364 
365 	for (i = 0; i < DBUF_MUTEXES; i++)
366 		mutex_init(&h->hash_mutexes[i], NULL, MUTEX_DEFAULT, NULL);
367 
368 	/*
369 	 * All entries are queued via taskq_dispatch_ent(), so min/maxalloc
370 	 * configuration is not required.
371 	 */
372 	dbu_evict_taskq = taskq_create("dbu_evict", 1, minclsyspri, 0, 0, 0);
373 }
374 
375 void
376 dbuf_fini(void)
377 {
378 	dbuf_hash_table_t *h = &dbuf_hash_table;
379 	int i;
380 
381 	for (i = 0; i < DBUF_MUTEXES; i++)
382 		mutex_destroy(&h->hash_mutexes[i]);
383 	kmem_free(h->hash_table, (h->hash_table_mask + 1) * sizeof (void *));
384 	kmem_cache_destroy(dbuf_cache);
385 	taskq_destroy(dbu_evict_taskq);
386 }
387 
388 /*
389  * Other stuff.
390  */
391 
392 #ifdef ZFS_DEBUG
393 static void
394 dbuf_verify(dmu_buf_impl_t *db)
395 {
396 	dnode_t *dn;
397 	dbuf_dirty_record_t *dr;
398 
399 	ASSERT(MUTEX_HELD(&db->db_mtx));
400 
401 	if (!(zfs_flags & ZFS_DEBUG_DBUF_VERIFY))
402 		return;
403 
404 	ASSERT(db->db_objset != NULL);
405 	DB_DNODE_ENTER(db);
406 	dn = DB_DNODE(db);
407 	if (dn == NULL) {
408 		ASSERT(db->db_parent == NULL);
409 		ASSERT(db->db_blkptr == NULL);
410 	} else {
411 		ASSERT3U(db->db.db_object, ==, dn->dn_object);
412 		ASSERT3P(db->db_objset, ==, dn->dn_objset);
413 		ASSERT3U(db->db_level, <, dn->dn_nlevels);
414 		ASSERT(db->db_blkid == DMU_BONUS_BLKID ||
415 		    db->db_blkid == DMU_SPILL_BLKID ||
416 		    !avl_is_empty(&dn->dn_dbufs));
417 	}
418 	if (db->db_blkid == DMU_BONUS_BLKID) {
419 		ASSERT(dn != NULL);
420 		ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
421 		ASSERT3U(db->db.db_offset, ==, DMU_BONUS_BLKID);
422 	} else if (db->db_blkid == DMU_SPILL_BLKID) {
423 		ASSERT(dn != NULL);
424 		ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
425 		ASSERT0(db->db.db_offset);
426 	} else {
427 		ASSERT3U(db->db.db_offset, ==, db->db_blkid * db->db.db_size);
428 	}
429 
430 	for (dr = db->db_data_pending; dr != NULL; dr = dr->dr_next)
431 		ASSERT(dr->dr_dbuf == db);
432 
433 	for (dr = db->db_last_dirty; dr != NULL; dr = dr->dr_next)
434 		ASSERT(dr->dr_dbuf == db);
435 
436 	/*
437 	 * We can't assert that db_size matches dn_datablksz because it
438 	 * can be momentarily different when another thread is doing
439 	 * dnode_set_blksz().
440 	 */
441 	if (db->db_level == 0 && db->db.db_object == DMU_META_DNODE_OBJECT) {
442 		dr = db->db_data_pending;
443 		/*
444 		 * It should only be modified in syncing context, so
445 		 * make sure we only have one copy of the data.
446 		 */
447 		ASSERT(dr == NULL || dr->dt.dl.dr_data == db->db_buf);
448 	}
449 
450 	/* verify db->db_blkptr */
451 	if (db->db_blkptr) {
452 		if (db->db_parent == dn->dn_dbuf) {
453 			/* db is pointed to by the dnode */
454 			/* ASSERT3U(db->db_blkid, <, dn->dn_nblkptr); */
455 			if (DMU_OBJECT_IS_SPECIAL(db->db.db_object))
456 				ASSERT(db->db_parent == NULL);
457 			else
458 				ASSERT(db->db_parent != NULL);
459 			if (db->db_blkid != DMU_SPILL_BLKID)
460 				ASSERT3P(db->db_blkptr, ==,
461 				    &dn->dn_phys->dn_blkptr[db->db_blkid]);
462 		} else {
463 			/* db is pointed to by an indirect block */
464 			int epb = db->db_parent->db.db_size >> SPA_BLKPTRSHIFT;
465 			ASSERT3U(db->db_parent->db_level, ==, db->db_level+1);
466 			ASSERT3U(db->db_parent->db.db_object, ==,
467 			    db->db.db_object);
468 			/*
469 			 * dnode_grow_indblksz() can make this fail if we don't
470 			 * have the struct_rwlock.  XXX indblksz no longer
471 			 * grows.  safe to do this now?
472 			 */
473 			if (RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
474 				ASSERT3P(db->db_blkptr, ==,
475 				    ((blkptr_t *)db->db_parent->db.db_data +
476 				    db->db_blkid % epb));
477 			}
478 		}
479 	}
480 	if ((db->db_blkptr == NULL || BP_IS_HOLE(db->db_blkptr)) &&
481 	    (db->db_buf == NULL || db->db_buf->b_data) &&
482 	    db->db.db_data && db->db_blkid != DMU_BONUS_BLKID &&
483 	    db->db_state != DB_FILL && !dn->dn_free_txg) {
484 		/*
485 		 * If the blkptr isn't set but they have nonzero data,
486 		 * it had better be dirty, otherwise we'll lose that
487 		 * data when we evict this buffer.
488 		 */
489 		if (db->db_dirtycnt == 0) {
490 			uint64_t *buf = db->db.db_data;
491 			int i;
492 
493 			for (i = 0; i < db->db.db_size >> 3; i++) {
494 				ASSERT(buf[i] == 0);
495 			}
496 		}
497 	}
498 	DB_DNODE_EXIT(db);
499 }
500 #endif
501 
502 static void
503 dbuf_clear_data(dmu_buf_impl_t *db)
504 {
505 	ASSERT(MUTEX_HELD(&db->db_mtx));
506 	dbuf_evict_user(db);
507 	db->db_buf = NULL;
508 	db->db.db_data = NULL;
509 	if (db->db_state != DB_NOFILL)
510 		db->db_state = DB_UNCACHED;
511 }
512 
513 static void
514 dbuf_set_data(dmu_buf_impl_t *db, arc_buf_t *buf)
515 {
516 	ASSERT(MUTEX_HELD(&db->db_mtx));
517 	ASSERT(buf != NULL);
518 
519 	db->db_buf = buf;
520 	ASSERT(buf->b_data != NULL);
521 	db->db.db_data = buf->b_data;
522 	if (!arc_released(buf))
523 		arc_set_callback(buf, dbuf_do_evict, db);
524 }
525 
526 /*
527  * Loan out an arc_buf for read.  Return the loaned arc_buf.
528  */
529 arc_buf_t *
530 dbuf_loan_arcbuf(dmu_buf_impl_t *db)
531 {
532 	arc_buf_t *abuf;
533 
534 	mutex_enter(&db->db_mtx);
535 	if (arc_released(db->db_buf) || refcount_count(&db->db_holds) > 1) {
536 		int blksz = db->db.db_size;
537 		spa_t *spa = db->db_objset->os_spa;
538 
539 		mutex_exit(&db->db_mtx);
540 		abuf = arc_loan_buf(spa, blksz);
541 		bcopy(db->db.db_data, abuf->b_data, blksz);
542 	} else {
543 		abuf = db->db_buf;
544 		arc_loan_inuse_buf(abuf, db);
545 		dbuf_clear_data(db);
546 		mutex_exit(&db->db_mtx);
547 	}
548 	return (abuf);
549 }
550 
551 /*
552  * Calculate which level n block references the data at the level 0 offset
553  * provided.
554  */
555 uint64_t
556 dbuf_whichblock(dnode_t *dn, int64_t level, uint64_t offset)
557 {
558 	if (dn->dn_datablkshift != 0 && dn->dn_indblkshift != 0) {
559 		/*
560 		 * The level n blkid is equal to the level 0 blkid divided by
561 		 * the number of level 0s in a level n block.
562 		 *
563 		 * The level 0 blkid is offset >> datablkshift =
564 		 * offset / 2^datablkshift.
565 		 *
566 		 * The number of level 0s in a level n is the number of block
567 		 * pointers in an indirect block, raised to the power of level.
568 		 * This is 2^(indblkshift - SPA_BLKPTRSHIFT)^level =
569 		 * 2^(level*(indblkshift - SPA_BLKPTRSHIFT)).
570 		 *
571 		 * Thus, the level n blkid is: offset /
572 		 * ((2^datablkshift)*(2^(level*(indblkshift - SPA_BLKPTRSHIFT)))
573 		 * = offset / 2^(datablkshift + level *
574 		 *   (indblkshift - SPA_BLKPTRSHIFT))
575 		 * = offset >> (datablkshift + level *
576 		 *   (indblkshift - SPA_BLKPTRSHIFT))
577 		 */
578 		return (offset >> (dn->dn_datablkshift + level *
579 		    (dn->dn_indblkshift - SPA_BLKPTRSHIFT)));
580 	} else {
581 		ASSERT3U(offset, <, dn->dn_datablksz);
582 		return (0);
583 	}
584 }
585 
586 static void
587 dbuf_read_done(zio_t *zio, arc_buf_t *buf, void *vdb)
588 {
589 	dmu_buf_impl_t *db = vdb;
590 
591 	mutex_enter(&db->db_mtx);
592 	ASSERT3U(db->db_state, ==, DB_READ);
593 	/*
594 	 * All reads are synchronous, so we must have a hold on the dbuf
595 	 */
596 	ASSERT(refcount_count(&db->db_holds) > 0);
597 	ASSERT(db->db_buf == NULL);
598 	ASSERT(db->db.db_data == NULL);
599 	if (db->db_level == 0 && db->db_freed_in_flight) {
600 		/* we were freed in flight; disregard any error */
601 		arc_release(buf, db);
602 		bzero(buf->b_data, db->db.db_size);
603 		arc_buf_freeze(buf);
604 		db->db_freed_in_flight = FALSE;
605 		dbuf_set_data(db, buf);
606 		db->db_state = DB_CACHED;
607 	} else if (zio == NULL || zio->io_error == 0) {
608 		dbuf_set_data(db, buf);
609 		db->db_state = DB_CACHED;
610 	} else {
611 		ASSERT(db->db_blkid != DMU_BONUS_BLKID);
612 		ASSERT3P(db->db_buf, ==, NULL);
613 		VERIFY(arc_buf_remove_ref(buf, db));
614 		db->db_state = DB_UNCACHED;
615 	}
616 	cv_broadcast(&db->db_changed);
617 	dbuf_rele_and_unlock(db, NULL);
618 }
619 
620 static void
621 dbuf_read_impl(dmu_buf_impl_t *db, zio_t *zio, uint32_t *flags)
622 {
623 	dnode_t *dn;
624 	zbookmark_phys_t zb;
625 	arc_flags_t aflags = ARC_FLAG_NOWAIT;
626 
627 	DB_DNODE_ENTER(db);
628 	dn = DB_DNODE(db);
629 	ASSERT(!refcount_is_zero(&db->db_holds));
630 	/* We need the struct_rwlock to prevent db_blkptr from changing. */
631 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
632 	ASSERT(MUTEX_HELD(&db->db_mtx));
633 	ASSERT(db->db_state == DB_UNCACHED);
634 	ASSERT(db->db_buf == NULL);
635 
636 	if (db->db_blkid == DMU_BONUS_BLKID) {
637 		int bonuslen = MIN(dn->dn_bonuslen, dn->dn_phys->dn_bonuslen);
638 
639 		ASSERT3U(bonuslen, <=, db->db.db_size);
640 		db->db.db_data = zio_buf_alloc(DN_MAX_BONUSLEN);
641 		arc_space_consume(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
642 		if (bonuslen < DN_MAX_BONUSLEN)
643 			bzero(db->db.db_data, DN_MAX_BONUSLEN);
644 		if (bonuslen)
645 			bcopy(DN_BONUS(dn->dn_phys), db->db.db_data, bonuslen);
646 		DB_DNODE_EXIT(db);
647 		db->db_state = DB_CACHED;
648 		mutex_exit(&db->db_mtx);
649 		return;
650 	}
651 
652 	/*
653 	 * Recheck BP_IS_HOLE() after dnode_block_freed() in case dnode_sync()
654 	 * processes the delete record and clears the bp while we are waiting
655 	 * for the dn_mtx (resulting in a "no" from block_freed).
656 	 */
657 	if (db->db_blkptr == NULL || BP_IS_HOLE(db->db_blkptr) ||
658 	    (db->db_level == 0 && (dnode_block_freed(dn, db->db_blkid) ||
659 	    BP_IS_HOLE(db->db_blkptr)))) {
660 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
661 
662 		DB_DNODE_EXIT(db);
663 		dbuf_set_data(db, arc_buf_alloc(db->db_objset->os_spa,
664 		    db->db.db_size, db, type));
665 		bzero(db->db.db_data, db->db.db_size);
666 		db->db_state = DB_CACHED;
667 		*flags |= DB_RF_CACHED;
668 		mutex_exit(&db->db_mtx);
669 		return;
670 	}
671 
672 	DB_DNODE_EXIT(db);
673 
674 	db->db_state = DB_READ;
675 	mutex_exit(&db->db_mtx);
676 
677 	if (DBUF_IS_L2CACHEABLE(db))
678 		aflags |= ARC_FLAG_L2CACHE;
679 	if (DBUF_IS_L2COMPRESSIBLE(db))
680 		aflags |= ARC_FLAG_L2COMPRESS;
681 
682 	SET_BOOKMARK(&zb, db->db_objset->os_dsl_dataset ?
683 	    db->db_objset->os_dsl_dataset->ds_object : DMU_META_OBJSET,
684 	    db->db.db_object, db->db_level, db->db_blkid);
685 
686 	dbuf_add_ref(db, NULL);
687 
688 	(void) arc_read(zio, db->db_objset->os_spa, db->db_blkptr,
689 	    dbuf_read_done, db, ZIO_PRIORITY_SYNC_READ,
690 	    (*flags & DB_RF_CANFAIL) ? ZIO_FLAG_CANFAIL : ZIO_FLAG_MUSTSUCCEED,
691 	    &aflags, &zb);
692 	if (aflags & ARC_FLAG_CACHED)
693 		*flags |= DB_RF_CACHED;
694 }
695 
696 int
697 dbuf_read(dmu_buf_impl_t *db, zio_t *zio, uint32_t flags)
698 {
699 	int err = 0;
700 	boolean_t havepzio = (zio != NULL);
701 	boolean_t prefetch;
702 	dnode_t *dn;
703 
704 	/*
705 	 * We don't have to hold the mutex to check db_state because it
706 	 * can't be freed while we have a hold on the buffer.
707 	 */
708 	ASSERT(!refcount_is_zero(&db->db_holds));
709 
710 	if (db->db_state == DB_NOFILL)
711 		return (SET_ERROR(EIO));
712 
713 	DB_DNODE_ENTER(db);
714 	dn = DB_DNODE(db);
715 	if ((flags & DB_RF_HAVESTRUCT) == 0)
716 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
717 
718 	prefetch = db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
719 	    (flags & DB_RF_NOPREFETCH) == 0 && dn != NULL &&
720 	    DBUF_IS_CACHEABLE(db);
721 
722 	mutex_enter(&db->db_mtx);
723 	if (db->db_state == DB_CACHED) {
724 		mutex_exit(&db->db_mtx);
725 		if (prefetch)
726 			dmu_zfetch(&dn->dn_zfetch, db->db.db_offset,
727 			    db->db.db_size, TRUE);
728 		if ((flags & DB_RF_HAVESTRUCT) == 0)
729 			rw_exit(&dn->dn_struct_rwlock);
730 		DB_DNODE_EXIT(db);
731 	} else if (db->db_state == DB_UNCACHED) {
732 		spa_t *spa = dn->dn_objset->os_spa;
733 
734 		if (zio == NULL)
735 			zio = zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL);
736 		dbuf_read_impl(db, zio, &flags);
737 
738 		/* dbuf_read_impl has dropped db_mtx for us */
739 
740 		if (prefetch)
741 			dmu_zfetch(&dn->dn_zfetch, db->db.db_offset,
742 			    db->db.db_size, flags & DB_RF_CACHED);
743 
744 		if ((flags & DB_RF_HAVESTRUCT) == 0)
745 			rw_exit(&dn->dn_struct_rwlock);
746 		DB_DNODE_EXIT(db);
747 
748 		if (!havepzio)
749 			err = zio_wait(zio);
750 	} else {
751 		/*
752 		 * Another reader came in while the dbuf was in flight
753 		 * between UNCACHED and CACHED.  Either a writer will finish
754 		 * writing the buffer (sending the dbuf to CACHED) or the
755 		 * first reader's request will reach the read_done callback
756 		 * and send the dbuf to CACHED.  Otherwise, a failure
757 		 * occurred and the dbuf went to UNCACHED.
758 		 */
759 		mutex_exit(&db->db_mtx);
760 		if (prefetch)
761 			dmu_zfetch(&dn->dn_zfetch, db->db.db_offset,
762 			    db->db.db_size, TRUE);
763 		if ((flags & DB_RF_HAVESTRUCT) == 0)
764 			rw_exit(&dn->dn_struct_rwlock);
765 		DB_DNODE_EXIT(db);
766 
767 		/* Skip the wait per the caller's request. */
768 		mutex_enter(&db->db_mtx);
769 		if ((flags & DB_RF_NEVERWAIT) == 0) {
770 			while (db->db_state == DB_READ ||
771 			    db->db_state == DB_FILL) {
772 				ASSERT(db->db_state == DB_READ ||
773 				    (flags & DB_RF_HAVESTRUCT) == 0);
774 				DTRACE_PROBE2(blocked__read, dmu_buf_impl_t *,
775 				    db, zio_t *, zio);
776 				cv_wait(&db->db_changed, &db->db_mtx);
777 			}
778 			if (db->db_state == DB_UNCACHED)
779 				err = SET_ERROR(EIO);
780 		}
781 		mutex_exit(&db->db_mtx);
782 	}
783 
784 	ASSERT(err || havepzio || db->db_state == DB_CACHED);
785 	return (err);
786 }
787 
788 static void
789 dbuf_noread(dmu_buf_impl_t *db)
790 {
791 	ASSERT(!refcount_is_zero(&db->db_holds));
792 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
793 	mutex_enter(&db->db_mtx);
794 	while (db->db_state == DB_READ || db->db_state == DB_FILL)
795 		cv_wait(&db->db_changed, &db->db_mtx);
796 	if (db->db_state == DB_UNCACHED) {
797 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
798 		spa_t *spa = db->db_objset->os_spa;
799 
800 		ASSERT(db->db_buf == NULL);
801 		ASSERT(db->db.db_data == NULL);
802 		dbuf_set_data(db, arc_buf_alloc(spa, db->db.db_size, db, type));
803 		db->db_state = DB_FILL;
804 	} else if (db->db_state == DB_NOFILL) {
805 		dbuf_clear_data(db);
806 	} else {
807 		ASSERT3U(db->db_state, ==, DB_CACHED);
808 	}
809 	mutex_exit(&db->db_mtx);
810 }
811 
812 /*
813  * This is our just-in-time copy function.  It makes a copy of
814  * buffers, that have been modified in a previous transaction
815  * group, before we modify them in the current active group.
816  *
817  * This function is used in two places: when we are dirtying a
818  * buffer for the first time in a txg, and when we are freeing
819  * a range in a dnode that includes this buffer.
820  *
821  * Note that when we are called from dbuf_free_range() we do
822  * not put a hold on the buffer, we just traverse the active
823  * dbuf list for the dnode.
824  */
825 static void
826 dbuf_fix_old_data(dmu_buf_impl_t *db, uint64_t txg)
827 {
828 	dbuf_dirty_record_t *dr = db->db_last_dirty;
829 
830 	ASSERT(MUTEX_HELD(&db->db_mtx));
831 	ASSERT(db->db.db_data != NULL);
832 	ASSERT(db->db_level == 0);
833 	ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT);
834 
835 	if (dr == NULL ||
836 	    (dr->dt.dl.dr_data !=
837 	    ((db->db_blkid  == DMU_BONUS_BLKID) ? db->db.db_data : db->db_buf)))
838 		return;
839 
840 	/*
841 	 * If the last dirty record for this dbuf has not yet synced
842 	 * and its referencing the dbuf data, either:
843 	 *	reset the reference to point to a new copy,
844 	 * or (if there a no active holders)
845 	 *	just null out the current db_data pointer.
846 	 */
847 	ASSERT(dr->dr_txg >= txg - 2);
848 	if (db->db_blkid == DMU_BONUS_BLKID) {
849 		/* Note that the data bufs here are zio_bufs */
850 		dr->dt.dl.dr_data = zio_buf_alloc(DN_MAX_BONUSLEN);
851 		arc_space_consume(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
852 		bcopy(db->db.db_data, dr->dt.dl.dr_data, DN_MAX_BONUSLEN);
853 	} else if (refcount_count(&db->db_holds) > db->db_dirtycnt) {
854 		int size = db->db.db_size;
855 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
856 		spa_t *spa = db->db_objset->os_spa;
857 
858 		dr->dt.dl.dr_data = arc_buf_alloc(spa, size, db, type);
859 		bcopy(db->db.db_data, dr->dt.dl.dr_data->b_data, size);
860 	} else {
861 		dbuf_clear_data(db);
862 	}
863 }
864 
865 void
866 dbuf_unoverride(dbuf_dirty_record_t *dr)
867 {
868 	dmu_buf_impl_t *db = dr->dr_dbuf;
869 	blkptr_t *bp = &dr->dt.dl.dr_overridden_by;
870 	uint64_t txg = dr->dr_txg;
871 
872 	ASSERT(MUTEX_HELD(&db->db_mtx));
873 	ASSERT(dr->dt.dl.dr_override_state != DR_IN_DMU_SYNC);
874 	ASSERT(db->db_level == 0);
875 
876 	if (db->db_blkid == DMU_BONUS_BLKID ||
877 	    dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN)
878 		return;
879 
880 	ASSERT(db->db_data_pending != dr);
881 
882 	/* free this block */
883 	if (!BP_IS_HOLE(bp) && !dr->dt.dl.dr_nopwrite)
884 		zio_free(db->db_objset->os_spa, txg, bp);
885 
886 	dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
887 	dr->dt.dl.dr_nopwrite = B_FALSE;
888 
889 	/*
890 	 * Release the already-written buffer, so we leave it in
891 	 * a consistent dirty state.  Note that all callers are
892 	 * modifying the buffer, so they will immediately do
893 	 * another (redundant) arc_release().  Therefore, leave
894 	 * the buf thawed to save the effort of freezing &
895 	 * immediately re-thawing it.
896 	 */
897 	arc_release(dr->dt.dl.dr_data, db);
898 }
899 
900 /*
901  * Evict (if its unreferenced) or clear (if its referenced) any level-0
902  * data blocks in the free range, so that any future readers will find
903  * empty blocks.
904  *
905  * This is a no-op if the dataset is in the middle of an incremental
906  * receive; see comment below for details.
907  */
908 void
909 dbuf_free_range(dnode_t *dn, uint64_t start_blkid, uint64_t end_blkid,
910     dmu_tx_t *tx)
911 {
912 	dmu_buf_impl_t db_search;
913 	dmu_buf_impl_t *db, *db_next;
914 	uint64_t txg = tx->tx_txg;
915 	avl_index_t where;
916 
917 	if (end_blkid > dn->dn_maxblkid && (end_blkid != DMU_SPILL_BLKID))
918 		end_blkid = dn->dn_maxblkid;
919 	dprintf_dnode(dn, "start=%llu end=%llu\n", start_blkid, end_blkid);
920 
921 	db_search.db_level = 0;
922 	db_search.db_blkid = start_blkid;
923 	db_search.db_state = DB_SEARCH;
924 
925 	mutex_enter(&dn->dn_dbufs_mtx);
926 	if (start_blkid >= dn->dn_unlisted_l0_blkid) {
927 		/* There can't be any dbufs in this range; no need to search. */
928 #ifdef DEBUG
929 		db = avl_find(&dn->dn_dbufs, &db_search, &where);
930 		ASSERT3P(db, ==, NULL);
931 		db = avl_nearest(&dn->dn_dbufs, where, AVL_AFTER);
932 		ASSERT(db == NULL || db->db_level > 0);
933 #endif
934 		mutex_exit(&dn->dn_dbufs_mtx);
935 		return;
936 	} else if (dmu_objset_is_receiving(dn->dn_objset)) {
937 		/*
938 		 * If we are receiving, we expect there to be no dbufs in
939 		 * the range to be freed, because receive modifies each
940 		 * block at most once, and in offset order.  If this is
941 		 * not the case, it can lead to performance problems,
942 		 * so note that we unexpectedly took the slow path.
943 		 */
944 		atomic_inc_64(&zfs_free_range_recv_miss);
945 	}
946 
947 	db = avl_find(&dn->dn_dbufs, &db_search, &where);
948 	ASSERT3P(db, ==, NULL);
949 	db = avl_nearest(&dn->dn_dbufs, where, AVL_AFTER);
950 
951 	for (; db != NULL; db = db_next) {
952 		db_next = AVL_NEXT(&dn->dn_dbufs, db);
953 		ASSERT(db->db_blkid != DMU_BONUS_BLKID);
954 
955 		if (db->db_level != 0 || db->db_blkid > end_blkid) {
956 			break;
957 		}
958 		ASSERT3U(db->db_blkid, >=, start_blkid);
959 
960 		/* found a level 0 buffer in the range */
961 		mutex_enter(&db->db_mtx);
962 		if (dbuf_undirty(db, tx)) {
963 			/* mutex has been dropped and dbuf destroyed */
964 			continue;
965 		}
966 
967 		if (db->db_state == DB_UNCACHED ||
968 		    db->db_state == DB_NOFILL ||
969 		    db->db_state == DB_EVICTING) {
970 			ASSERT(db->db.db_data == NULL);
971 			mutex_exit(&db->db_mtx);
972 			continue;
973 		}
974 		if (db->db_state == DB_READ || db->db_state == DB_FILL) {
975 			/* will be handled in dbuf_read_done or dbuf_rele */
976 			db->db_freed_in_flight = TRUE;
977 			mutex_exit(&db->db_mtx);
978 			continue;
979 		}
980 		if (refcount_count(&db->db_holds) == 0) {
981 			ASSERT(db->db_buf);
982 			dbuf_clear(db);
983 			continue;
984 		}
985 		/* The dbuf is referenced */
986 
987 		if (db->db_last_dirty != NULL) {
988 			dbuf_dirty_record_t *dr = db->db_last_dirty;
989 
990 			if (dr->dr_txg == txg) {
991 				/*
992 				 * This buffer is "in-use", re-adjust the file
993 				 * size to reflect that this buffer may
994 				 * contain new data when we sync.
995 				 */
996 				if (db->db_blkid != DMU_SPILL_BLKID &&
997 				    db->db_blkid > dn->dn_maxblkid)
998 					dn->dn_maxblkid = db->db_blkid;
999 				dbuf_unoverride(dr);
1000 			} else {
1001 				/*
1002 				 * This dbuf is not dirty in the open context.
1003 				 * Either uncache it (if its not referenced in
1004 				 * the open context) or reset its contents to
1005 				 * empty.
1006 				 */
1007 				dbuf_fix_old_data(db, txg);
1008 			}
1009 		}
1010 		/* clear the contents if its cached */
1011 		if (db->db_state == DB_CACHED) {
1012 			ASSERT(db->db.db_data != NULL);
1013 			arc_release(db->db_buf, db);
1014 			bzero(db->db.db_data, db->db.db_size);
1015 			arc_buf_freeze(db->db_buf);
1016 		}
1017 
1018 		mutex_exit(&db->db_mtx);
1019 	}
1020 	mutex_exit(&dn->dn_dbufs_mtx);
1021 }
1022 
1023 static int
1024 dbuf_block_freeable(dmu_buf_impl_t *db)
1025 {
1026 	dsl_dataset_t *ds = db->db_objset->os_dsl_dataset;
1027 	uint64_t birth_txg = 0;
1028 
1029 	/*
1030 	 * We don't need any locking to protect db_blkptr:
1031 	 * If it's syncing, then db_last_dirty will be set
1032 	 * so we'll ignore db_blkptr.
1033 	 *
1034 	 * This logic ensures that only block births for
1035 	 * filled blocks are considered.
1036 	 */
1037 	ASSERT(MUTEX_HELD(&db->db_mtx));
1038 	if (db->db_last_dirty && (db->db_blkptr == NULL ||
1039 	    !BP_IS_HOLE(db->db_blkptr))) {
1040 		birth_txg = db->db_last_dirty->dr_txg;
1041 	} else if (db->db_blkptr != NULL && !BP_IS_HOLE(db->db_blkptr)) {
1042 		birth_txg = db->db_blkptr->blk_birth;
1043 	}
1044 
1045 	/*
1046 	 * If this block don't exist or is in a snapshot, it can't be freed.
1047 	 * Don't pass the bp to dsl_dataset_block_freeable() since we
1048 	 * are holding the db_mtx lock and might deadlock if we are
1049 	 * prefetching a dedup-ed block.
1050 	 */
1051 	if (birth_txg != 0)
1052 		return (ds == NULL ||
1053 		    dsl_dataset_block_freeable(ds, NULL, birth_txg));
1054 	else
1055 		return (B_FALSE);
1056 }
1057 
1058 void
1059 dbuf_new_size(dmu_buf_impl_t *db, int size, dmu_tx_t *tx)
1060 {
1061 	arc_buf_t *buf, *obuf;
1062 	int osize = db->db.db_size;
1063 	arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1064 	dnode_t *dn;
1065 
1066 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1067 
1068 	DB_DNODE_ENTER(db);
1069 	dn = DB_DNODE(db);
1070 
1071 	/* XXX does *this* func really need the lock? */
1072 	ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
1073 
1074 	/*
1075 	 * This call to dmu_buf_will_dirty() with the dn_struct_rwlock held
1076 	 * is OK, because there can be no other references to the db
1077 	 * when we are changing its size, so no concurrent DB_FILL can
1078 	 * be happening.
1079 	 */
1080 	/*
1081 	 * XXX we should be doing a dbuf_read, checking the return
1082 	 * value and returning that up to our callers
1083 	 */
1084 	dmu_buf_will_dirty(&db->db, tx);
1085 
1086 	/* create the data buffer for the new block */
1087 	buf = arc_buf_alloc(dn->dn_objset->os_spa, size, db, type);
1088 
1089 	/* copy old block data to the new block */
1090 	obuf = db->db_buf;
1091 	bcopy(obuf->b_data, buf->b_data, MIN(osize, size));
1092 	/* zero the remainder */
1093 	if (size > osize)
1094 		bzero((uint8_t *)buf->b_data + osize, size - osize);
1095 
1096 	mutex_enter(&db->db_mtx);
1097 	dbuf_set_data(db, buf);
1098 	VERIFY(arc_buf_remove_ref(obuf, db));
1099 	db->db.db_size = size;
1100 
1101 	if (db->db_level == 0) {
1102 		ASSERT3U(db->db_last_dirty->dr_txg, ==, tx->tx_txg);
1103 		db->db_last_dirty->dt.dl.dr_data = buf;
1104 	}
1105 	mutex_exit(&db->db_mtx);
1106 
1107 	dnode_willuse_space(dn, size-osize, tx);
1108 	DB_DNODE_EXIT(db);
1109 }
1110 
1111 void
1112 dbuf_release_bp(dmu_buf_impl_t *db)
1113 {
1114 	objset_t *os = db->db_objset;
1115 
1116 	ASSERT(dsl_pool_sync_context(dmu_objset_pool(os)));
1117 	ASSERT(arc_released(os->os_phys_buf) ||
1118 	    list_link_active(&os->os_dsl_dataset->ds_synced_link));
1119 	ASSERT(db->db_parent == NULL || arc_released(db->db_parent->db_buf));
1120 
1121 	(void) arc_release(db->db_buf, db);
1122 }
1123 
1124 dbuf_dirty_record_t *
1125 dbuf_dirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
1126 {
1127 	dnode_t *dn;
1128 	objset_t *os;
1129 	dbuf_dirty_record_t **drp, *dr;
1130 	int drop_struct_lock = FALSE;
1131 	boolean_t do_free_accounting = B_FALSE;
1132 	int txgoff = tx->tx_txg & TXG_MASK;
1133 
1134 	ASSERT(tx->tx_txg != 0);
1135 	ASSERT(!refcount_is_zero(&db->db_holds));
1136 	DMU_TX_DIRTY_BUF(tx, db);
1137 
1138 	DB_DNODE_ENTER(db);
1139 	dn = DB_DNODE(db);
1140 	/*
1141 	 * Shouldn't dirty a regular buffer in syncing context.  Private
1142 	 * objects may be dirtied in syncing context, but only if they
1143 	 * were already pre-dirtied in open context.
1144 	 */
1145 	ASSERT(!dmu_tx_is_syncing(tx) ||
1146 	    BP_IS_HOLE(dn->dn_objset->os_rootbp) ||
1147 	    DMU_OBJECT_IS_SPECIAL(dn->dn_object) ||
1148 	    dn->dn_objset->os_dsl_dataset == NULL);
1149 	/*
1150 	 * We make this assert for private objects as well, but after we
1151 	 * check if we're already dirty.  They are allowed to re-dirty
1152 	 * in syncing context.
1153 	 */
1154 	ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
1155 	    dn->dn_dirtyctx == DN_UNDIRTIED || dn->dn_dirtyctx ==
1156 	    (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN));
1157 
1158 	mutex_enter(&db->db_mtx);
1159 	/*
1160 	 * XXX make this true for indirects too?  The problem is that
1161 	 * transactions created with dmu_tx_create_assigned() from
1162 	 * syncing context don't bother holding ahead.
1163 	 */
1164 	ASSERT(db->db_level != 0 ||
1165 	    db->db_state == DB_CACHED || db->db_state == DB_FILL ||
1166 	    db->db_state == DB_NOFILL);
1167 
1168 	mutex_enter(&dn->dn_mtx);
1169 	/*
1170 	 * Don't set dirtyctx to SYNC if we're just modifying this as we
1171 	 * initialize the objset.
1172 	 */
1173 	if (dn->dn_dirtyctx == DN_UNDIRTIED &&
1174 	    !BP_IS_HOLE(dn->dn_objset->os_rootbp)) {
1175 		dn->dn_dirtyctx =
1176 		    (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN);
1177 		ASSERT(dn->dn_dirtyctx_firstset == NULL);
1178 		dn->dn_dirtyctx_firstset = kmem_alloc(1, KM_SLEEP);
1179 	}
1180 	mutex_exit(&dn->dn_mtx);
1181 
1182 	if (db->db_blkid == DMU_SPILL_BLKID)
1183 		dn->dn_have_spill = B_TRUE;
1184 
1185 	/*
1186 	 * If this buffer is already dirty, we're done.
1187 	 */
1188 	drp = &db->db_last_dirty;
1189 	ASSERT(*drp == NULL || (*drp)->dr_txg <= tx->tx_txg ||
1190 	    db->db.db_object == DMU_META_DNODE_OBJECT);
1191 	while ((dr = *drp) != NULL && dr->dr_txg > tx->tx_txg)
1192 		drp = &dr->dr_next;
1193 	if (dr && dr->dr_txg == tx->tx_txg) {
1194 		DB_DNODE_EXIT(db);
1195 
1196 		if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID) {
1197 			/*
1198 			 * If this buffer has already been written out,
1199 			 * we now need to reset its state.
1200 			 */
1201 			dbuf_unoverride(dr);
1202 			if (db->db.db_object != DMU_META_DNODE_OBJECT &&
1203 			    db->db_state != DB_NOFILL)
1204 				arc_buf_thaw(db->db_buf);
1205 		}
1206 		mutex_exit(&db->db_mtx);
1207 		return (dr);
1208 	}
1209 
1210 	/*
1211 	 * Only valid if not already dirty.
1212 	 */
1213 	ASSERT(dn->dn_object == 0 ||
1214 	    dn->dn_dirtyctx == DN_UNDIRTIED || dn->dn_dirtyctx ==
1215 	    (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN));
1216 
1217 	ASSERT3U(dn->dn_nlevels, >, db->db_level);
1218 	ASSERT((dn->dn_phys->dn_nlevels == 0 && db->db_level == 0) ||
1219 	    dn->dn_phys->dn_nlevels > db->db_level ||
1220 	    dn->dn_next_nlevels[txgoff] > db->db_level ||
1221 	    dn->dn_next_nlevels[(tx->tx_txg-1) & TXG_MASK] > db->db_level ||
1222 	    dn->dn_next_nlevels[(tx->tx_txg-2) & TXG_MASK] > db->db_level);
1223 
1224 	/*
1225 	 * We should only be dirtying in syncing context if it's the
1226 	 * mos or we're initializing the os or it's a special object.
1227 	 * However, we are allowed to dirty in syncing context provided
1228 	 * we already dirtied it in open context.  Hence we must make
1229 	 * this assertion only if we're not already dirty.
1230 	 */
1231 	os = dn->dn_objset;
1232 	ASSERT(!dmu_tx_is_syncing(tx) || DMU_OBJECT_IS_SPECIAL(dn->dn_object) ||
1233 	    os->os_dsl_dataset == NULL || BP_IS_HOLE(os->os_rootbp));
1234 	ASSERT(db->db.db_size != 0);
1235 
1236 	dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
1237 
1238 	if (db->db_blkid != DMU_BONUS_BLKID) {
1239 		/*
1240 		 * Update the accounting.
1241 		 * Note: we delay "free accounting" until after we drop
1242 		 * the db_mtx.  This keeps us from grabbing other locks
1243 		 * (and possibly deadlocking) in bp_get_dsize() while
1244 		 * also holding the db_mtx.
1245 		 */
1246 		dnode_willuse_space(dn, db->db.db_size, tx);
1247 		do_free_accounting = dbuf_block_freeable(db);
1248 	}
1249 
1250 	/*
1251 	 * If this buffer is dirty in an old transaction group we need
1252 	 * to make a copy of it so that the changes we make in this
1253 	 * transaction group won't leak out when we sync the older txg.
1254 	 */
1255 	dr = kmem_zalloc(sizeof (dbuf_dirty_record_t), KM_SLEEP);
1256 	if (db->db_level == 0) {
1257 		void *data_old = db->db_buf;
1258 
1259 		if (db->db_state != DB_NOFILL) {
1260 			if (db->db_blkid == DMU_BONUS_BLKID) {
1261 				dbuf_fix_old_data(db, tx->tx_txg);
1262 				data_old = db->db.db_data;
1263 			} else if (db->db.db_object != DMU_META_DNODE_OBJECT) {
1264 				/*
1265 				 * Release the data buffer from the cache so
1266 				 * that we can modify it without impacting
1267 				 * possible other users of this cached data
1268 				 * block.  Note that indirect blocks and
1269 				 * private objects are not released until the
1270 				 * syncing state (since they are only modified
1271 				 * then).
1272 				 */
1273 				arc_release(db->db_buf, db);
1274 				dbuf_fix_old_data(db, tx->tx_txg);
1275 				data_old = db->db_buf;
1276 			}
1277 			ASSERT(data_old != NULL);
1278 		}
1279 		dr->dt.dl.dr_data = data_old;
1280 	} else {
1281 		mutex_init(&dr->dt.di.dr_mtx, NULL, MUTEX_DEFAULT, NULL);
1282 		list_create(&dr->dt.di.dr_children,
1283 		    sizeof (dbuf_dirty_record_t),
1284 		    offsetof(dbuf_dirty_record_t, dr_dirty_node));
1285 	}
1286 	if (db->db_blkid != DMU_BONUS_BLKID && os->os_dsl_dataset != NULL)
1287 		dr->dr_accounted = db->db.db_size;
1288 	dr->dr_dbuf = db;
1289 	dr->dr_txg = tx->tx_txg;
1290 	dr->dr_next = *drp;
1291 	*drp = dr;
1292 
1293 	/*
1294 	 * We could have been freed_in_flight between the dbuf_noread
1295 	 * and dbuf_dirty.  We win, as though the dbuf_noread() had
1296 	 * happened after the free.
1297 	 */
1298 	if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
1299 	    db->db_blkid != DMU_SPILL_BLKID) {
1300 		mutex_enter(&dn->dn_mtx);
1301 		if (dn->dn_free_ranges[txgoff] != NULL) {
1302 			range_tree_clear(dn->dn_free_ranges[txgoff],
1303 			    db->db_blkid, 1);
1304 		}
1305 		mutex_exit(&dn->dn_mtx);
1306 		db->db_freed_in_flight = FALSE;
1307 	}
1308 
1309 	/*
1310 	 * This buffer is now part of this txg
1311 	 */
1312 	dbuf_add_ref(db, (void *)(uintptr_t)tx->tx_txg);
1313 	db->db_dirtycnt += 1;
1314 	ASSERT3U(db->db_dirtycnt, <=, 3);
1315 
1316 	mutex_exit(&db->db_mtx);
1317 
1318 	if (db->db_blkid == DMU_BONUS_BLKID ||
1319 	    db->db_blkid == DMU_SPILL_BLKID) {
1320 		mutex_enter(&dn->dn_mtx);
1321 		ASSERT(!list_link_active(&dr->dr_dirty_node));
1322 		list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
1323 		mutex_exit(&dn->dn_mtx);
1324 		dnode_setdirty(dn, tx);
1325 		DB_DNODE_EXIT(db);
1326 		return (dr);
1327 	} else if (do_free_accounting) {
1328 		blkptr_t *bp = db->db_blkptr;
1329 		int64_t willfree = (bp && !BP_IS_HOLE(bp)) ?
1330 		    bp_get_dsize(os->os_spa, bp) : db->db.db_size;
1331 		/*
1332 		 * This is only a guess -- if the dbuf is dirty
1333 		 * in a previous txg, we don't know how much
1334 		 * space it will use on disk yet.  We should
1335 		 * really have the struct_rwlock to access
1336 		 * db_blkptr, but since this is just a guess,
1337 		 * it's OK if we get an odd answer.
1338 		 */
1339 		ddt_prefetch(os->os_spa, bp);
1340 		dnode_willuse_space(dn, -willfree, tx);
1341 	}
1342 
1343 	if (!RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
1344 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
1345 		drop_struct_lock = TRUE;
1346 	}
1347 
1348 	if (db->db_level == 0) {
1349 		dnode_new_blkid(dn, db->db_blkid, tx, drop_struct_lock);
1350 		ASSERT(dn->dn_maxblkid >= db->db_blkid);
1351 	}
1352 
1353 	if (db->db_level+1 < dn->dn_nlevels) {
1354 		dmu_buf_impl_t *parent = db->db_parent;
1355 		dbuf_dirty_record_t *di;
1356 		int parent_held = FALSE;
1357 
1358 		if (db->db_parent == NULL || db->db_parent == dn->dn_dbuf) {
1359 			int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
1360 
1361 			parent = dbuf_hold_level(dn, db->db_level+1,
1362 			    db->db_blkid >> epbs, FTAG);
1363 			ASSERT(parent != NULL);
1364 			parent_held = TRUE;
1365 		}
1366 		if (drop_struct_lock)
1367 			rw_exit(&dn->dn_struct_rwlock);
1368 		ASSERT3U(db->db_level+1, ==, parent->db_level);
1369 		di = dbuf_dirty(parent, tx);
1370 		if (parent_held)
1371 			dbuf_rele(parent, FTAG);
1372 
1373 		mutex_enter(&db->db_mtx);
1374 		/*
1375 		 * Since we've dropped the mutex, it's possible that
1376 		 * dbuf_undirty() might have changed this out from under us.
1377 		 */
1378 		if (db->db_last_dirty == dr ||
1379 		    dn->dn_object == DMU_META_DNODE_OBJECT) {
1380 			mutex_enter(&di->dt.di.dr_mtx);
1381 			ASSERT3U(di->dr_txg, ==, tx->tx_txg);
1382 			ASSERT(!list_link_active(&dr->dr_dirty_node));
1383 			list_insert_tail(&di->dt.di.dr_children, dr);
1384 			mutex_exit(&di->dt.di.dr_mtx);
1385 			dr->dr_parent = di;
1386 		}
1387 		mutex_exit(&db->db_mtx);
1388 	} else {
1389 		ASSERT(db->db_level+1 == dn->dn_nlevels);
1390 		ASSERT(db->db_blkid < dn->dn_nblkptr);
1391 		ASSERT(db->db_parent == NULL || db->db_parent == dn->dn_dbuf);
1392 		mutex_enter(&dn->dn_mtx);
1393 		ASSERT(!list_link_active(&dr->dr_dirty_node));
1394 		list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
1395 		mutex_exit(&dn->dn_mtx);
1396 		if (drop_struct_lock)
1397 			rw_exit(&dn->dn_struct_rwlock);
1398 	}
1399 
1400 	dnode_setdirty(dn, tx);
1401 	DB_DNODE_EXIT(db);
1402 	return (dr);
1403 }
1404 
1405 /*
1406  * Undirty a buffer in the transaction group referenced by the given
1407  * transaction.  Return whether this evicted the dbuf.
1408  */
1409 static boolean_t
1410 dbuf_undirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
1411 {
1412 	dnode_t *dn;
1413 	uint64_t txg = tx->tx_txg;
1414 	dbuf_dirty_record_t *dr, **drp;
1415 
1416 	ASSERT(txg != 0);
1417 
1418 	/*
1419 	 * Due to our use of dn_nlevels below, this can only be called
1420 	 * in open context, unless we are operating on the MOS.
1421 	 * From syncing context, dn_nlevels may be different from the
1422 	 * dn_nlevels used when dbuf was dirtied.
1423 	 */
1424 	ASSERT(db->db_objset ==
1425 	    dmu_objset_pool(db->db_objset)->dp_meta_objset ||
1426 	    txg != spa_syncing_txg(dmu_objset_spa(db->db_objset)));
1427 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1428 	ASSERT0(db->db_level);
1429 	ASSERT(MUTEX_HELD(&db->db_mtx));
1430 
1431 	/*
1432 	 * If this buffer is not dirty, we're done.
1433 	 */
1434 	for (drp = &db->db_last_dirty; (dr = *drp) != NULL; drp = &dr->dr_next)
1435 		if (dr->dr_txg <= txg)
1436 			break;
1437 	if (dr == NULL || dr->dr_txg < txg)
1438 		return (B_FALSE);
1439 	ASSERT(dr->dr_txg == txg);
1440 	ASSERT(dr->dr_dbuf == db);
1441 
1442 	DB_DNODE_ENTER(db);
1443 	dn = DB_DNODE(db);
1444 
1445 	dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
1446 
1447 	ASSERT(db->db.db_size != 0);
1448 
1449 	dsl_pool_undirty_space(dmu_objset_pool(dn->dn_objset),
1450 	    dr->dr_accounted, txg);
1451 
1452 	*drp = dr->dr_next;
1453 
1454 	/*
1455 	 * Note that there are three places in dbuf_dirty()
1456 	 * where this dirty record may be put on a list.
1457 	 * Make sure to do a list_remove corresponding to
1458 	 * every one of those list_insert calls.
1459 	 */
1460 	if (dr->dr_parent) {
1461 		mutex_enter(&dr->dr_parent->dt.di.dr_mtx);
1462 		list_remove(&dr->dr_parent->dt.di.dr_children, dr);
1463 		mutex_exit(&dr->dr_parent->dt.di.dr_mtx);
1464 	} else if (db->db_blkid == DMU_SPILL_BLKID ||
1465 	    db->db_level + 1 == dn->dn_nlevels) {
1466 		ASSERT(db->db_blkptr == NULL || db->db_parent == dn->dn_dbuf);
1467 		mutex_enter(&dn->dn_mtx);
1468 		list_remove(&dn->dn_dirty_records[txg & TXG_MASK], dr);
1469 		mutex_exit(&dn->dn_mtx);
1470 	}
1471 	DB_DNODE_EXIT(db);
1472 
1473 	if (db->db_state != DB_NOFILL) {
1474 		dbuf_unoverride(dr);
1475 
1476 		ASSERT(db->db_buf != NULL);
1477 		ASSERT(dr->dt.dl.dr_data != NULL);
1478 		if (dr->dt.dl.dr_data != db->db_buf)
1479 			VERIFY(arc_buf_remove_ref(dr->dt.dl.dr_data, db));
1480 	}
1481 
1482 	kmem_free(dr, sizeof (dbuf_dirty_record_t));
1483 
1484 	ASSERT(db->db_dirtycnt > 0);
1485 	db->db_dirtycnt -= 1;
1486 
1487 	if (refcount_remove(&db->db_holds, (void *)(uintptr_t)txg) == 0) {
1488 		arc_buf_t *buf = db->db_buf;
1489 
1490 		ASSERT(db->db_state == DB_NOFILL || arc_released(buf));
1491 		dbuf_clear_data(db);
1492 		VERIFY(arc_buf_remove_ref(buf, db));
1493 		dbuf_evict(db);
1494 		return (B_TRUE);
1495 	}
1496 
1497 	return (B_FALSE);
1498 }
1499 
1500 void
1501 dmu_buf_will_dirty(dmu_buf_t *db_fake, dmu_tx_t *tx)
1502 {
1503 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1504 	int rf = DB_RF_MUST_SUCCEED | DB_RF_NOPREFETCH;
1505 
1506 	ASSERT(tx->tx_txg != 0);
1507 	ASSERT(!refcount_is_zero(&db->db_holds));
1508 
1509 	DB_DNODE_ENTER(db);
1510 	if (RW_WRITE_HELD(&DB_DNODE(db)->dn_struct_rwlock))
1511 		rf |= DB_RF_HAVESTRUCT;
1512 	DB_DNODE_EXIT(db);
1513 	(void) dbuf_read(db, NULL, rf);
1514 	(void) dbuf_dirty(db, tx);
1515 }
1516 
1517 void
1518 dmu_buf_will_not_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
1519 {
1520 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1521 
1522 	db->db_state = DB_NOFILL;
1523 
1524 	dmu_buf_will_fill(db_fake, tx);
1525 }
1526 
1527 void
1528 dmu_buf_will_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
1529 {
1530 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1531 
1532 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1533 	ASSERT(tx->tx_txg != 0);
1534 	ASSERT(db->db_level == 0);
1535 	ASSERT(!refcount_is_zero(&db->db_holds));
1536 
1537 	ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT ||
1538 	    dmu_tx_private_ok(tx));
1539 
1540 	dbuf_noread(db);
1541 	(void) dbuf_dirty(db, tx);
1542 }
1543 
1544 #pragma weak dmu_buf_fill_done = dbuf_fill_done
1545 /* ARGSUSED */
1546 void
1547 dbuf_fill_done(dmu_buf_impl_t *db, dmu_tx_t *tx)
1548 {
1549 	mutex_enter(&db->db_mtx);
1550 	DBUF_VERIFY(db);
1551 
1552 	if (db->db_state == DB_FILL) {
1553 		if (db->db_level == 0 && db->db_freed_in_flight) {
1554 			ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1555 			/* we were freed while filling */
1556 			/* XXX dbuf_undirty? */
1557 			bzero(db->db.db_data, db->db.db_size);
1558 			db->db_freed_in_flight = FALSE;
1559 		}
1560 		db->db_state = DB_CACHED;
1561 		cv_broadcast(&db->db_changed);
1562 	}
1563 	mutex_exit(&db->db_mtx);
1564 }
1565 
1566 void
1567 dmu_buf_write_embedded(dmu_buf_t *dbuf, void *data,
1568     bp_embedded_type_t etype, enum zio_compress comp,
1569     int uncompressed_size, int compressed_size, int byteorder,
1570     dmu_tx_t *tx)
1571 {
1572 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbuf;
1573 	struct dirty_leaf *dl;
1574 	dmu_object_type_t type;
1575 
1576 	if (etype == BP_EMBEDDED_TYPE_DATA) {
1577 		ASSERT(spa_feature_is_active(dmu_objset_spa(db->db_objset),
1578 		    SPA_FEATURE_EMBEDDED_DATA));
1579 	}
1580 
1581 	DB_DNODE_ENTER(db);
1582 	type = DB_DNODE(db)->dn_type;
1583 	DB_DNODE_EXIT(db);
1584 
1585 	ASSERT0(db->db_level);
1586 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1587 
1588 	dmu_buf_will_not_fill(dbuf, tx);
1589 
1590 	ASSERT3U(db->db_last_dirty->dr_txg, ==, tx->tx_txg);
1591 	dl = &db->db_last_dirty->dt.dl;
1592 	encode_embedded_bp_compressed(&dl->dr_overridden_by,
1593 	    data, comp, uncompressed_size, compressed_size);
1594 	BPE_SET_ETYPE(&dl->dr_overridden_by, etype);
1595 	BP_SET_TYPE(&dl->dr_overridden_by, type);
1596 	BP_SET_LEVEL(&dl->dr_overridden_by, 0);
1597 	BP_SET_BYTEORDER(&dl->dr_overridden_by, byteorder);
1598 
1599 	dl->dr_override_state = DR_OVERRIDDEN;
1600 	dl->dr_overridden_by.blk_birth = db->db_last_dirty->dr_txg;
1601 }
1602 
1603 /*
1604  * Directly assign a provided arc buf to a given dbuf if it's not referenced
1605  * by anybody except our caller. Otherwise copy arcbuf's contents to dbuf.
1606  */
1607 void
1608 dbuf_assign_arcbuf(dmu_buf_impl_t *db, arc_buf_t *buf, dmu_tx_t *tx)
1609 {
1610 	ASSERT(!refcount_is_zero(&db->db_holds));
1611 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1612 	ASSERT(db->db_level == 0);
1613 	ASSERT(DBUF_GET_BUFC_TYPE(db) == ARC_BUFC_DATA);
1614 	ASSERT(buf != NULL);
1615 	ASSERT(arc_buf_size(buf) == db->db.db_size);
1616 	ASSERT(tx->tx_txg != 0);
1617 
1618 	arc_return_buf(buf, db);
1619 	ASSERT(arc_released(buf));
1620 
1621 	mutex_enter(&db->db_mtx);
1622 
1623 	while (db->db_state == DB_READ || db->db_state == DB_FILL)
1624 		cv_wait(&db->db_changed, &db->db_mtx);
1625 
1626 	ASSERT(db->db_state == DB_CACHED || db->db_state == DB_UNCACHED);
1627 
1628 	if (db->db_state == DB_CACHED &&
1629 	    refcount_count(&db->db_holds) - 1 > db->db_dirtycnt) {
1630 		mutex_exit(&db->db_mtx);
1631 		(void) dbuf_dirty(db, tx);
1632 		bcopy(buf->b_data, db->db.db_data, db->db.db_size);
1633 		VERIFY(arc_buf_remove_ref(buf, db));
1634 		xuio_stat_wbuf_copied();
1635 		return;
1636 	}
1637 
1638 	xuio_stat_wbuf_nocopy();
1639 	if (db->db_state == DB_CACHED) {
1640 		dbuf_dirty_record_t *dr = db->db_last_dirty;
1641 
1642 		ASSERT(db->db_buf != NULL);
1643 		if (dr != NULL && dr->dr_txg == tx->tx_txg) {
1644 			ASSERT(dr->dt.dl.dr_data == db->db_buf);
1645 			if (!arc_released(db->db_buf)) {
1646 				ASSERT(dr->dt.dl.dr_override_state ==
1647 				    DR_OVERRIDDEN);
1648 				arc_release(db->db_buf, db);
1649 			}
1650 			dr->dt.dl.dr_data = buf;
1651 			VERIFY(arc_buf_remove_ref(db->db_buf, db));
1652 		} else if (dr == NULL || dr->dt.dl.dr_data != db->db_buf) {
1653 			arc_release(db->db_buf, db);
1654 			VERIFY(arc_buf_remove_ref(db->db_buf, db));
1655 		}
1656 		db->db_buf = NULL;
1657 	}
1658 	ASSERT(db->db_buf == NULL);
1659 	dbuf_set_data(db, buf);
1660 	db->db_state = DB_FILL;
1661 	mutex_exit(&db->db_mtx);
1662 	(void) dbuf_dirty(db, tx);
1663 	dmu_buf_fill_done(&db->db, tx);
1664 }
1665 
1666 /*
1667  * "Clear" the contents of this dbuf.  This will mark the dbuf
1668  * EVICTING and clear *most* of its references.  Unfortunately,
1669  * when we are not holding the dn_dbufs_mtx, we can't clear the
1670  * entry in the dn_dbufs list.  We have to wait until dbuf_destroy()
1671  * in this case.  For callers from the DMU we will usually see:
1672  *	dbuf_clear()->arc_clear_callback()->dbuf_do_evict()->dbuf_destroy()
1673  * For the arc callback, we will usually see:
1674  *	dbuf_do_evict()->dbuf_clear();dbuf_destroy()
1675  * Sometimes, though, we will get a mix of these two:
1676  *	DMU: dbuf_clear()->arc_clear_callback()
1677  *	ARC: dbuf_do_evict()->dbuf_destroy()
1678  *
1679  * This routine will dissociate the dbuf from the arc, by calling
1680  * arc_clear_callback(), but will not evict the data from the ARC.
1681  */
1682 void
1683 dbuf_clear(dmu_buf_impl_t *db)
1684 {
1685 	dnode_t *dn;
1686 	dmu_buf_impl_t *parent = db->db_parent;
1687 	dmu_buf_impl_t *dndb;
1688 	boolean_t dbuf_gone = B_FALSE;
1689 
1690 	ASSERT(MUTEX_HELD(&db->db_mtx));
1691 	ASSERT(refcount_is_zero(&db->db_holds));
1692 
1693 	dbuf_evict_user(db);
1694 
1695 	if (db->db_state == DB_CACHED) {
1696 		ASSERT(db->db.db_data != NULL);
1697 		if (db->db_blkid == DMU_BONUS_BLKID) {
1698 			zio_buf_free(db->db.db_data, DN_MAX_BONUSLEN);
1699 			arc_space_return(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
1700 		}
1701 		db->db.db_data = NULL;
1702 		db->db_state = DB_UNCACHED;
1703 	}
1704 
1705 	ASSERT(db->db_state == DB_UNCACHED || db->db_state == DB_NOFILL);
1706 	ASSERT(db->db_data_pending == NULL);
1707 
1708 	db->db_state = DB_EVICTING;
1709 	db->db_blkptr = NULL;
1710 
1711 	DB_DNODE_ENTER(db);
1712 	dn = DB_DNODE(db);
1713 	dndb = dn->dn_dbuf;
1714 	if (db->db_blkid != DMU_BONUS_BLKID && MUTEX_HELD(&dn->dn_dbufs_mtx)) {
1715 		avl_remove(&dn->dn_dbufs, db);
1716 		atomic_dec_32(&dn->dn_dbufs_count);
1717 		membar_producer();
1718 		DB_DNODE_EXIT(db);
1719 		/*
1720 		 * Decrementing the dbuf count means that the hold corresponding
1721 		 * to the removed dbuf is no longer discounted in dnode_move(),
1722 		 * so the dnode cannot be moved until after we release the hold.
1723 		 * The membar_producer() ensures visibility of the decremented
1724 		 * value in dnode_move(), since DB_DNODE_EXIT doesn't actually
1725 		 * release any lock.
1726 		 */
1727 		dnode_rele(dn, db);
1728 		db->db_dnode_handle = NULL;
1729 	} else {
1730 		DB_DNODE_EXIT(db);
1731 	}
1732 
1733 	if (db->db_buf)
1734 		dbuf_gone = arc_clear_callback(db->db_buf);
1735 
1736 	if (!dbuf_gone)
1737 		mutex_exit(&db->db_mtx);
1738 
1739 	/*
1740 	 * If this dbuf is referenced from an indirect dbuf,
1741 	 * decrement the ref count on the indirect dbuf.
1742 	 */
1743 	if (parent && parent != dndb)
1744 		dbuf_rele(parent, db);
1745 }
1746 
1747 /*
1748  * Note: While bpp will always be updated if the function returns success,
1749  * parentp will not be updated if the dnode does not have dn_dbuf filled in;
1750  * this happens when the dnode is the meta-dnode, or a userused or groupused
1751  * object.
1752  */
1753 static int
1754 dbuf_findbp(dnode_t *dn, int level, uint64_t blkid, int fail_sparse,
1755     dmu_buf_impl_t **parentp, blkptr_t **bpp)
1756 {
1757 	int nlevels, epbs;
1758 
1759 	*parentp = NULL;
1760 	*bpp = NULL;
1761 
1762 	ASSERT(blkid != DMU_BONUS_BLKID);
1763 
1764 	if (blkid == DMU_SPILL_BLKID) {
1765 		mutex_enter(&dn->dn_mtx);
1766 		if (dn->dn_have_spill &&
1767 		    (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR))
1768 			*bpp = &dn->dn_phys->dn_spill;
1769 		else
1770 			*bpp = NULL;
1771 		dbuf_add_ref(dn->dn_dbuf, NULL);
1772 		*parentp = dn->dn_dbuf;
1773 		mutex_exit(&dn->dn_mtx);
1774 		return (0);
1775 	}
1776 
1777 	if (dn->dn_phys->dn_nlevels == 0)
1778 		nlevels = 1;
1779 	else
1780 		nlevels = dn->dn_phys->dn_nlevels;
1781 
1782 	epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
1783 
1784 	ASSERT3U(level * epbs, <, 64);
1785 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
1786 	if (level >= nlevels ||
1787 	    (blkid > (dn->dn_phys->dn_maxblkid >> (level * epbs)))) {
1788 		/* the buffer has no parent yet */
1789 		return (SET_ERROR(ENOENT));
1790 	} else if (level < nlevels-1) {
1791 		/* this block is referenced from an indirect block */
1792 		int err = dbuf_hold_impl(dn, level+1,
1793 		    blkid >> epbs, fail_sparse, FALSE, NULL, parentp);
1794 		if (err)
1795 			return (err);
1796 		err = dbuf_read(*parentp, NULL,
1797 		    (DB_RF_HAVESTRUCT | DB_RF_NOPREFETCH | DB_RF_CANFAIL));
1798 		if (err) {
1799 			dbuf_rele(*parentp, NULL);
1800 			*parentp = NULL;
1801 			return (err);
1802 		}
1803 		*bpp = ((blkptr_t *)(*parentp)->db.db_data) +
1804 		    (blkid & ((1ULL << epbs) - 1));
1805 		return (0);
1806 	} else {
1807 		/* the block is referenced from the dnode */
1808 		ASSERT3U(level, ==, nlevels-1);
1809 		ASSERT(dn->dn_phys->dn_nblkptr == 0 ||
1810 		    blkid < dn->dn_phys->dn_nblkptr);
1811 		if (dn->dn_dbuf) {
1812 			dbuf_add_ref(dn->dn_dbuf, NULL);
1813 			*parentp = dn->dn_dbuf;
1814 		}
1815 		*bpp = &dn->dn_phys->dn_blkptr[blkid];
1816 		return (0);
1817 	}
1818 }
1819 
1820 static dmu_buf_impl_t *
1821 dbuf_create(dnode_t *dn, uint8_t level, uint64_t blkid,
1822     dmu_buf_impl_t *parent, blkptr_t *blkptr)
1823 {
1824 	objset_t *os = dn->dn_objset;
1825 	dmu_buf_impl_t *db, *odb;
1826 
1827 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
1828 	ASSERT(dn->dn_type != DMU_OT_NONE);
1829 
1830 	db = kmem_cache_alloc(dbuf_cache, KM_SLEEP);
1831 
1832 	db->db_objset = os;
1833 	db->db.db_object = dn->dn_object;
1834 	db->db_level = level;
1835 	db->db_blkid = blkid;
1836 	db->db_last_dirty = NULL;
1837 	db->db_dirtycnt = 0;
1838 	db->db_dnode_handle = dn->dn_handle;
1839 	db->db_parent = parent;
1840 	db->db_blkptr = blkptr;
1841 
1842 	db->db_user = NULL;
1843 	db->db_user_immediate_evict = FALSE;
1844 	db->db_freed_in_flight = FALSE;
1845 	db->db_pending_evict = FALSE;
1846 
1847 	if (blkid == DMU_BONUS_BLKID) {
1848 		ASSERT3P(parent, ==, dn->dn_dbuf);
1849 		db->db.db_size = DN_MAX_BONUSLEN -
1850 		    (dn->dn_nblkptr-1) * sizeof (blkptr_t);
1851 		ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
1852 		db->db.db_offset = DMU_BONUS_BLKID;
1853 		db->db_state = DB_UNCACHED;
1854 		/* the bonus dbuf is not placed in the hash table */
1855 		arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
1856 		return (db);
1857 	} else if (blkid == DMU_SPILL_BLKID) {
1858 		db->db.db_size = (blkptr != NULL) ?
1859 		    BP_GET_LSIZE(blkptr) : SPA_MINBLOCKSIZE;
1860 		db->db.db_offset = 0;
1861 	} else {
1862 		int blocksize =
1863 		    db->db_level ? 1 << dn->dn_indblkshift : dn->dn_datablksz;
1864 		db->db.db_size = blocksize;
1865 		db->db.db_offset = db->db_blkid * blocksize;
1866 	}
1867 
1868 	/*
1869 	 * Hold the dn_dbufs_mtx while we get the new dbuf
1870 	 * in the hash table *and* added to the dbufs list.
1871 	 * This prevents a possible deadlock with someone
1872 	 * trying to look up this dbuf before its added to the
1873 	 * dn_dbufs list.
1874 	 */
1875 	mutex_enter(&dn->dn_dbufs_mtx);
1876 	db->db_state = DB_EVICTING;
1877 	if ((odb = dbuf_hash_insert(db)) != NULL) {
1878 		/* someone else inserted it first */
1879 		kmem_cache_free(dbuf_cache, db);
1880 		mutex_exit(&dn->dn_dbufs_mtx);
1881 		return (odb);
1882 	}
1883 	avl_add(&dn->dn_dbufs, db);
1884 	if (db->db_level == 0 && db->db_blkid >=
1885 	    dn->dn_unlisted_l0_blkid)
1886 		dn->dn_unlisted_l0_blkid = db->db_blkid + 1;
1887 	db->db_state = DB_UNCACHED;
1888 	mutex_exit(&dn->dn_dbufs_mtx);
1889 	arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
1890 
1891 	if (parent && parent != dn->dn_dbuf)
1892 		dbuf_add_ref(parent, db);
1893 
1894 	ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
1895 	    refcount_count(&dn->dn_holds) > 0);
1896 	(void) refcount_add(&dn->dn_holds, db);
1897 	atomic_inc_32(&dn->dn_dbufs_count);
1898 
1899 	dprintf_dbuf(db, "db=%p\n", db);
1900 
1901 	return (db);
1902 }
1903 
1904 static int
1905 dbuf_do_evict(void *private)
1906 {
1907 	dmu_buf_impl_t *db = private;
1908 
1909 	if (!MUTEX_HELD(&db->db_mtx))
1910 		mutex_enter(&db->db_mtx);
1911 
1912 	ASSERT(refcount_is_zero(&db->db_holds));
1913 
1914 	if (db->db_state != DB_EVICTING) {
1915 		ASSERT(db->db_state == DB_CACHED);
1916 		DBUF_VERIFY(db);
1917 		db->db_buf = NULL;
1918 		dbuf_evict(db);
1919 	} else {
1920 		mutex_exit(&db->db_mtx);
1921 		dbuf_destroy(db);
1922 	}
1923 	return (0);
1924 }
1925 
1926 static void
1927 dbuf_destroy(dmu_buf_impl_t *db)
1928 {
1929 	ASSERT(refcount_is_zero(&db->db_holds));
1930 
1931 	if (db->db_blkid != DMU_BONUS_BLKID) {
1932 		/*
1933 		 * If this dbuf is still on the dn_dbufs list,
1934 		 * remove it from that list.
1935 		 */
1936 		if (db->db_dnode_handle != NULL) {
1937 			dnode_t *dn;
1938 
1939 			DB_DNODE_ENTER(db);
1940 			dn = DB_DNODE(db);
1941 			mutex_enter(&dn->dn_dbufs_mtx);
1942 			avl_remove(&dn->dn_dbufs, db);
1943 			atomic_dec_32(&dn->dn_dbufs_count);
1944 			mutex_exit(&dn->dn_dbufs_mtx);
1945 			DB_DNODE_EXIT(db);
1946 			/*
1947 			 * Decrementing the dbuf count means that the hold
1948 			 * corresponding to the removed dbuf is no longer
1949 			 * discounted in dnode_move(), so the dnode cannot be
1950 			 * moved until after we release the hold.
1951 			 */
1952 			dnode_rele(dn, db);
1953 			db->db_dnode_handle = NULL;
1954 		}
1955 		dbuf_hash_remove(db);
1956 	}
1957 	db->db_parent = NULL;
1958 	db->db_buf = NULL;
1959 
1960 	ASSERT(db->db.db_data == NULL);
1961 	ASSERT(db->db_hash_next == NULL);
1962 	ASSERT(db->db_blkptr == NULL);
1963 	ASSERT(db->db_data_pending == NULL);
1964 
1965 	kmem_cache_free(dbuf_cache, db);
1966 	arc_space_return(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
1967 }
1968 
1969 typedef struct dbuf_prefetch_arg {
1970 	spa_t *dpa_spa;	/* The spa to issue the prefetch in. */
1971 	zbookmark_phys_t dpa_zb; /* The target block to prefetch. */
1972 	int dpa_epbs; /* Entries (blkptr_t's) Per Block Shift. */
1973 	int dpa_curlevel; /* The current level that we're reading */
1974 	zio_priority_t dpa_prio; /* The priority I/Os should be issued at. */
1975 	zio_t *dpa_zio; /* The parent zio_t for all prefetches. */
1976 	arc_flags_t dpa_aflags; /* Flags to pass to the final prefetch. */
1977 } dbuf_prefetch_arg_t;
1978 
1979 /*
1980  * Actually issue the prefetch read for the block given.
1981  */
1982 static void
1983 dbuf_issue_final_prefetch(dbuf_prefetch_arg_t *dpa, blkptr_t *bp)
1984 {
1985 	if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
1986 		return;
1987 
1988 	arc_flags_t aflags =
1989 	    dpa->dpa_aflags | ARC_FLAG_NOWAIT | ARC_FLAG_PREFETCH;
1990 
1991 	ASSERT3U(dpa->dpa_curlevel, ==, BP_GET_LEVEL(bp));
1992 	ASSERT3U(dpa->dpa_curlevel, ==, dpa->dpa_zb.zb_level);
1993 	ASSERT(dpa->dpa_zio != NULL);
1994 	(void) arc_read(dpa->dpa_zio, dpa->dpa_spa, bp, NULL, NULL,
1995 	    dpa->dpa_prio, ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
1996 	    &aflags, &dpa->dpa_zb);
1997 }
1998 
1999 /*
2000  * Called when an indirect block above our prefetch target is read in.  This
2001  * will either read in the next indirect block down the tree or issue the actual
2002  * prefetch if the next block down is our target.
2003  */
2004 static void
2005 dbuf_prefetch_indirect_done(zio_t *zio, arc_buf_t *abuf, void *private)
2006 {
2007 	dbuf_prefetch_arg_t *dpa = private;
2008 
2009 	ASSERT3S(dpa->dpa_zb.zb_level, <, dpa->dpa_curlevel);
2010 	ASSERT3S(dpa->dpa_curlevel, >, 0);
2011 	if (zio != NULL) {
2012 		ASSERT3S(BP_GET_LEVEL(zio->io_bp), ==, dpa->dpa_curlevel);
2013 		ASSERT3U(BP_GET_LSIZE(zio->io_bp), ==, zio->io_size);
2014 		ASSERT3P(zio->io_spa, ==, dpa->dpa_spa);
2015 	}
2016 
2017 	dpa->dpa_curlevel--;
2018 
2019 	uint64_t nextblkid = dpa->dpa_zb.zb_blkid >>
2020 	    (dpa->dpa_epbs * (dpa->dpa_curlevel - dpa->dpa_zb.zb_level));
2021 	blkptr_t *bp = ((blkptr_t *)abuf->b_data) +
2022 	    P2PHASE(nextblkid, 1ULL << dpa->dpa_epbs);
2023 	if (BP_IS_HOLE(bp) || (zio != NULL && zio->io_error != 0)) {
2024 		kmem_free(dpa, sizeof (*dpa));
2025 	} else if (dpa->dpa_curlevel == dpa->dpa_zb.zb_level) {
2026 		ASSERT3U(nextblkid, ==, dpa->dpa_zb.zb_blkid);
2027 		dbuf_issue_final_prefetch(dpa, bp);
2028 		kmem_free(dpa, sizeof (*dpa));
2029 	} else {
2030 		arc_flags_t iter_aflags = ARC_FLAG_NOWAIT;
2031 		zbookmark_phys_t zb;
2032 
2033 		ASSERT3U(dpa->dpa_curlevel, ==, BP_GET_LEVEL(bp));
2034 
2035 		SET_BOOKMARK(&zb, dpa->dpa_zb.zb_objset,
2036 		    dpa->dpa_zb.zb_object, dpa->dpa_curlevel, nextblkid);
2037 
2038 		(void) arc_read(dpa->dpa_zio, dpa->dpa_spa,
2039 		    bp, dbuf_prefetch_indirect_done, dpa, dpa->dpa_prio,
2040 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
2041 		    &iter_aflags, &zb);
2042 	}
2043 	(void) arc_buf_remove_ref(abuf, private);
2044 }
2045 
2046 /*
2047  * Issue prefetch reads for the given block on the given level.  If the indirect
2048  * blocks above that block are not in memory, we will read them in
2049  * asynchronously.  As a result, this call never blocks waiting for a read to
2050  * complete.
2051  */
2052 void
2053 dbuf_prefetch(dnode_t *dn, int64_t level, uint64_t blkid, zio_priority_t prio,
2054     arc_flags_t aflags)
2055 {
2056 	blkptr_t bp;
2057 	int epbs, nlevels, curlevel;
2058 	uint64_t curblkid;
2059 
2060 	ASSERT(blkid != DMU_BONUS_BLKID);
2061 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2062 
2063 	if (dnode_block_freed(dn, blkid))
2064 		return;
2065 
2066 	/*
2067 	 * This dnode hasn't been written to disk yet, so there's nothing to
2068 	 * prefetch.
2069 	 */
2070 	nlevels = dn->dn_phys->dn_nlevels;
2071 	if (level >= nlevels || dn->dn_phys->dn_nblkptr == 0)
2072 		return;
2073 
2074 	epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
2075 	if (dn->dn_phys->dn_maxblkid < blkid << (epbs * level))
2076 		return;
2077 
2078 	dmu_buf_impl_t *db = dbuf_find(dn->dn_objset, dn->dn_object,
2079 	    level, blkid);
2080 	if (db != NULL) {
2081 		mutex_exit(&db->db_mtx);
2082 		/*
2083 		 * This dbuf already exists.  It is either CACHED, or
2084 		 * (we assume) about to be read or filled.
2085 		 */
2086 		return;
2087 	}
2088 
2089 	/*
2090 	 * Find the closest ancestor (indirect block) of the target block
2091 	 * that is present in the cache.  In this indirect block, we will
2092 	 * find the bp that is at curlevel, curblkid.
2093 	 */
2094 	curlevel = level;
2095 	curblkid = blkid;
2096 	while (curlevel < nlevels - 1) {
2097 		int parent_level = curlevel + 1;
2098 		uint64_t parent_blkid = curblkid >> epbs;
2099 		dmu_buf_impl_t *db;
2100 
2101 		if (dbuf_hold_impl(dn, parent_level, parent_blkid,
2102 		    FALSE, TRUE, FTAG, &db) == 0) {
2103 			blkptr_t *bpp = db->db_buf->b_data;
2104 			bp = bpp[P2PHASE(curblkid, 1 << epbs)];
2105 			dbuf_rele(db, FTAG);
2106 			break;
2107 		}
2108 
2109 		curlevel = parent_level;
2110 		curblkid = parent_blkid;
2111 	}
2112 
2113 	if (curlevel == nlevels - 1) {
2114 		/* No cached indirect blocks found. */
2115 		ASSERT3U(curblkid, <, dn->dn_phys->dn_nblkptr);
2116 		bp = dn->dn_phys->dn_blkptr[curblkid];
2117 	}
2118 	if (BP_IS_HOLE(&bp))
2119 		return;
2120 
2121 	ASSERT3U(curlevel, ==, BP_GET_LEVEL(&bp));
2122 
2123 	zio_t *pio = zio_root(dmu_objset_spa(dn->dn_objset), NULL, NULL,
2124 	    ZIO_FLAG_CANFAIL);
2125 
2126 	dbuf_prefetch_arg_t *dpa = kmem_zalloc(sizeof (*dpa), KM_SLEEP);
2127 	dsl_dataset_t *ds = dn->dn_objset->os_dsl_dataset;
2128 	SET_BOOKMARK(&dpa->dpa_zb, ds != NULL ? ds->ds_object : DMU_META_OBJSET,
2129 	    dn->dn_object, level, blkid);
2130 	dpa->dpa_curlevel = curlevel;
2131 	dpa->dpa_prio = prio;
2132 	dpa->dpa_aflags = aflags;
2133 	dpa->dpa_spa = dn->dn_objset->os_spa;
2134 	dpa->dpa_epbs = epbs;
2135 	dpa->dpa_zio = pio;
2136 
2137 	/*
2138 	 * If we have the indirect just above us, no need to do the asynchronous
2139 	 * prefetch chain; we'll just run the last step ourselves.  If we're at
2140 	 * a higher level, though, we want to issue the prefetches for all the
2141 	 * indirect blocks asynchronously, so we can go on with whatever we were
2142 	 * doing.
2143 	 */
2144 	if (curlevel == level) {
2145 		ASSERT3U(curblkid, ==, blkid);
2146 		dbuf_issue_final_prefetch(dpa, &bp);
2147 		kmem_free(dpa, sizeof (*dpa));
2148 	} else {
2149 		arc_flags_t iter_aflags = ARC_FLAG_NOWAIT;
2150 		zbookmark_phys_t zb;
2151 
2152 		SET_BOOKMARK(&zb, ds != NULL ? ds->ds_object : DMU_META_OBJSET,
2153 		    dn->dn_object, curlevel, curblkid);
2154 		(void) arc_read(dpa->dpa_zio, dpa->dpa_spa,
2155 		    &bp, dbuf_prefetch_indirect_done, dpa, prio,
2156 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
2157 		    &iter_aflags, &zb);
2158 	}
2159 	/*
2160 	 * We use pio here instead of dpa_zio since it's possible that
2161 	 * dpa may have already been freed.
2162 	 */
2163 	zio_nowait(pio);
2164 }
2165 
2166 /*
2167  * Returns with db_holds incremented, and db_mtx not held.
2168  * Note: dn_struct_rwlock must be held.
2169  */
2170 int
2171 dbuf_hold_impl(dnode_t *dn, uint8_t level, uint64_t blkid,
2172     boolean_t fail_sparse, boolean_t fail_uncached,
2173     void *tag, dmu_buf_impl_t **dbp)
2174 {
2175 	dmu_buf_impl_t *db, *parent = NULL;
2176 
2177 	ASSERT(blkid != DMU_BONUS_BLKID);
2178 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2179 	ASSERT3U(dn->dn_nlevels, >, level);
2180 
2181 	*dbp = NULL;
2182 top:
2183 	/* dbuf_find() returns with db_mtx held */
2184 	db = dbuf_find(dn->dn_objset, dn->dn_object, level, blkid);
2185 
2186 	if (db == NULL) {
2187 		blkptr_t *bp = NULL;
2188 		int err;
2189 
2190 		if (fail_uncached)
2191 			return (SET_ERROR(ENOENT));
2192 
2193 		ASSERT3P(parent, ==, NULL);
2194 		err = dbuf_findbp(dn, level, blkid, fail_sparse, &parent, &bp);
2195 		if (fail_sparse) {
2196 			if (err == 0 && bp && BP_IS_HOLE(bp))
2197 				err = SET_ERROR(ENOENT);
2198 			if (err) {
2199 				if (parent)
2200 					dbuf_rele(parent, NULL);
2201 				return (err);
2202 			}
2203 		}
2204 		if (err && err != ENOENT)
2205 			return (err);
2206 		db = dbuf_create(dn, level, blkid, parent, bp);
2207 	}
2208 
2209 	if (fail_uncached && db->db_state != DB_CACHED) {
2210 		mutex_exit(&db->db_mtx);
2211 		return (SET_ERROR(ENOENT));
2212 	}
2213 
2214 	if (db->db_buf && refcount_is_zero(&db->db_holds)) {
2215 		arc_buf_add_ref(db->db_buf, db);
2216 		if (db->db_buf->b_data == NULL) {
2217 			dbuf_clear(db);
2218 			if (parent) {
2219 				dbuf_rele(parent, NULL);
2220 				parent = NULL;
2221 			}
2222 			goto top;
2223 		}
2224 		ASSERT3P(db->db.db_data, ==, db->db_buf->b_data);
2225 	}
2226 
2227 	ASSERT(db->db_buf == NULL || arc_referenced(db->db_buf));
2228 
2229 	/*
2230 	 * If this buffer is currently syncing out, and we are are
2231 	 * still referencing it from db_data, we need to make a copy
2232 	 * of it in case we decide we want to dirty it again in this txg.
2233 	 */
2234 	if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
2235 	    dn->dn_object != DMU_META_DNODE_OBJECT &&
2236 	    db->db_state == DB_CACHED && db->db_data_pending) {
2237 		dbuf_dirty_record_t *dr = db->db_data_pending;
2238 
2239 		if (dr->dt.dl.dr_data == db->db_buf) {
2240 			arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
2241 
2242 			dbuf_set_data(db,
2243 			    arc_buf_alloc(dn->dn_objset->os_spa,
2244 			    db->db.db_size, db, type));
2245 			bcopy(dr->dt.dl.dr_data->b_data, db->db.db_data,
2246 			    db->db.db_size);
2247 		}
2248 	}
2249 
2250 	(void) refcount_add(&db->db_holds, tag);
2251 	DBUF_VERIFY(db);
2252 	mutex_exit(&db->db_mtx);
2253 
2254 	/* NOTE: we can't rele the parent until after we drop the db_mtx */
2255 	if (parent)
2256 		dbuf_rele(parent, NULL);
2257 
2258 	ASSERT3P(DB_DNODE(db), ==, dn);
2259 	ASSERT3U(db->db_blkid, ==, blkid);
2260 	ASSERT3U(db->db_level, ==, level);
2261 	*dbp = db;
2262 
2263 	return (0);
2264 }
2265 
2266 dmu_buf_impl_t *
2267 dbuf_hold(dnode_t *dn, uint64_t blkid, void *tag)
2268 {
2269 	return (dbuf_hold_level(dn, 0, blkid, tag));
2270 }
2271 
2272 dmu_buf_impl_t *
2273 dbuf_hold_level(dnode_t *dn, int level, uint64_t blkid, void *tag)
2274 {
2275 	dmu_buf_impl_t *db;
2276 	int err = dbuf_hold_impl(dn, level, blkid, FALSE, FALSE, tag, &db);
2277 	return (err ? NULL : db);
2278 }
2279 
2280 void
2281 dbuf_create_bonus(dnode_t *dn)
2282 {
2283 	ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
2284 
2285 	ASSERT(dn->dn_bonus == NULL);
2286 	dn->dn_bonus = dbuf_create(dn, 0, DMU_BONUS_BLKID, dn->dn_dbuf, NULL);
2287 }
2288 
2289 int
2290 dbuf_spill_set_blksz(dmu_buf_t *db_fake, uint64_t blksz, dmu_tx_t *tx)
2291 {
2292 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2293 	dnode_t *dn;
2294 
2295 	if (db->db_blkid != DMU_SPILL_BLKID)
2296 		return (SET_ERROR(ENOTSUP));
2297 	if (blksz == 0)
2298 		blksz = SPA_MINBLOCKSIZE;
2299 	ASSERT3U(blksz, <=, spa_maxblocksize(dmu_objset_spa(db->db_objset)));
2300 	blksz = P2ROUNDUP(blksz, SPA_MINBLOCKSIZE);
2301 
2302 	DB_DNODE_ENTER(db);
2303 	dn = DB_DNODE(db);
2304 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
2305 	dbuf_new_size(db, blksz, tx);
2306 	rw_exit(&dn->dn_struct_rwlock);
2307 	DB_DNODE_EXIT(db);
2308 
2309 	return (0);
2310 }
2311 
2312 void
2313 dbuf_rm_spill(dnode_t *dn, dmu_tx_t *tx)
2314 {
2315 	dbuf_free_range(dn, DMU_SPILL_BLKID, DMU_SPILL_BLKID, tx);
2316 }
2317 
2318 #pragma weak dmu_buf_add_ref = dbuf_add_ref
2319 void
2320 dbuf_add_ref(dmu_buf_impl_t *db, void *tag)
2321 {
2322 	int64_t holds = refcount_add(&db->db_holds, tag);
2323 	ASSERT(holds > 1);
2324 }
2325 
2326 #pragma weak dmu_buf_try_add_ref = dbuf_try_add_ref
2327 boolean_t
2328 dbuf_try_add_ref(dmu_buf_t *db_fake, objset_t *os, uint64_t obj, uint64_t blkid,
2329     void *tag)
2330 {
2331 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2332 	dmu_buf_impl_t *found_db;
2333 	boolean_t result = B_FALSE;
2334 
2335 	if (db->db_blkid == DMU_BONUS_BLKID)
2336 		found_db = dbuf_find_bonus(os, obj);
2337 	else
2338 		found_db = dbuf_find(os, obj, 0, blkid);
2339 
2340 	if (found_db != NULL) {
2341 		if (db == found_db && dbuf_refcount(db) > db->db_dirtycnt) {
2342 			(void) refcount_add(&db->db_holds, tag);
2343 			result = B_TRUE;
2344 		}
2345 		mutex_exit(&db->db_mtx);
2346 	}
2347 	return (result);
2348 }
2349 
2350 /*
2351  * If you call dbuf_rele() you had better not be referencing the dnode handle
2352  * unless you have some other direct or indirect hold on the dnode. (An indirect
2353  * hold is a hold on one of the dnode's dbufs, including the bonus buffer.)
2354  * Without that, the dbuf_rele() could lead to a dnode_rele() followed by the
2355  * dnode's parent dbuf evicting its dnode handles.
2356  */
2357 void
2358 dbuf_rele(dmu_buf_impl_t *db, void *tag)
2359 {
2360 	mutex_enter(&db->db_mtx);
2361 	dbuf_rele_and_unlock(db, tag);
2362 }
2363 
2364 void
2365 dmu_buf_rele(dmu_buf_t *db, void *tag)
2366 {
2367 	dbuf_rele((dmu_buf_impl_t *)db, tag);
2368 }
2369 
2370 /*
2371  * dbuf_rele() for an already-locked dbuf.  This is necessary to allow
2372  * db_dirtycnt and db_holds to be updated atomically.
2373  */
2374 void
2375 dbuf_rele_and_unlock(dmu_buf_impl_t *db, void *tag)
2376 {
2377 	int64_t holds;
2378 
2379 	ASSERT(MUTEX_HELD(&db->db_mtx));
2380 	DBUF_VERIFY(db);
2381 
2382 	/*
2383 	 * Remove the reference to the dbuf before removing its hold on the
2384 	 * dnode so we can guarantee in dnode_move() that a referenced bonus
2385 	 * buffer has a corresponding dnode hold.
2386 	 */
2387 	holds = refcount_remove(&db->db_holds, tag);
2388 	ASSERT(holds >= 0);
2389 
2390 	/*
2391 	 * We can't freeze indirects if there is a possibility that they
2392 	 * may be modified in the current syncing context.
2393 	 */
2394 	if (db->db_buf && holds == (db->db_level == 0 ? db->db_dirtycnt : 0))
2395 		arc_buf_freeze(db->db_buf);
2396 
2397 	if (holds == db->db_dirtycnt &&
2398 	    db->db_level == 0 && db->db_user_immediate_evict)
2399 		dbuf_evict_user(db);
2400 
2401 	if (holds == 0) {
2402 		if (db->db_blkid == DMU_BONUS_BLKID) {
2403 			dnode_t *dn;
2404 			boolean_t evict_dbuf = db->db_pending_evict;
2405 
2406 			/*
2407 			 * If the dnode moves here, we cannot cross this
2408 			 * barrier until the move completes.
2409 			 */
2410 			DB_DNODE_ENTER(db);
2411 
2412 			dn = DB_DNODE(db);
2413 			atomic_dec_32(&dn->dn_dbufs_count);
2414 
2415 			/*
2416 			 * Decrementing the dbuf count means that the bonus
2417 			 * buffer's dnode hold is no longer discounted in
2418 			 * dnode_move(). The dnode cannot move until after
2419 			 * the dnode_rele() below.
2420 			 */
2421 			DB_DNODE_EXIT(db);
2422 
2423 			/*
2424 			 * Do not reference db after its lock is dropped.
2425 			 * Another thread may evict it.
2426 			 */
2427 			mutex_exit(&db->db_mtx);
2428 
2429 			if (evict_dbuf)
2430 				dnode_evict_bonus(dn);
2431 
2432 			dnode_rele(dn, db);
2433 		} else if (db->db_buf == NULL) {
2434 			/*
2435 			 * This is a special case: we never associated this
2436 			 * dbuf with any data allocated from the ARC.
2437 			 */
2438 			ASSERT(db->db_state == DB_UNCACHED ||
2439 			    db->db_state == DB_NOFILL);
2440 			dbuf_evict(db);
2441 		} else if (arc_released(db->db_buf)) {
2442 			arc_buf_t *buf = db->db_buf;
2443 			/*
2444 			 * This dbuf has anonymous data associated with it.
2445 			 */
2446 			dbuf_clear_data(db);
2447 			VERIFY(arc_buf_remove_ref(buf, db));
2448 			dbuf_evict(db);
2449 		} else {
2450 			VERIFY(!arc_buf_remove_ref(db->db_buf, db));
2451 
2452 			/*
2453 			 * A dbuf will be eligible for eviction if either the
2454 			 * 'primarycache' property is set or a duplicate
2455 			 * copy of this buffer is already cached in the arc.
2456 			 *
2457 			 * In the case of the 'primarycache' a buffer
2458 			 * is considered for eviction if it matches the
2459 			 * criteria set in the property.
2460 			 *
2461 			 * To decide if our buffer is considered a
2462 			 * duplicate, we must call into the arc to determine
2463 			 * if multiple buffers are referencing the same
2464 			 * block on-disk. If so, then we simply evict
2465 			 * ourselves.
2466 			 */
2467 			if (!DBUF_IS_CACHEABLE(db)) {
2468 				if (db->db_blkptr != NULL &&
2469 				    !BP_IS_HOLE(db->db_blkptr) &&
2470 				    !BP_IS_EMBEDDED(db->db_blkptr)) {
2471 					spa_t *spa =
2472 					    dmu_objset_spa(db->db_objset);
2473 					blkptr_t bp = *db->db_blkptr;
2474 					dbuf_clear(db);
2475 					arc_freed(spa, &bp);
2476 				} else {
2477 					dbuf_clear(db);
2478 				}
2479 			} else if (db->db_pending_evict ||
2480 			    arc_buf_eviction_needed(db->db_buf)) {
2481 				dbuf_clear(db);
2482 			} else {
2483 				mutex_exit(&db->db_mtx);
2484 			}
2485 		}
2486 	} else {
2487 		mutex_exit(&db->db_mtx);
2488 	}
2489 }
2490 
2491 #pragma weak dmu_buf_refcount = dbuf_refcount
2492 uint64_t
2493 dbuf_refcount(dmu_buf_impl_t *db)
2494 {
2495 	return (refcount_count(&db->db_holds));
2496 }
2497 
2498 void *
2499 dmu_buf_replace_user(dmu_buf_t *db_fake, dmu_buf_user_t *old_user,
2500     dmu_buf_user_t *new_user)
2501 {
2502 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2503 
2504 	mutex_enter(&db->db_mtx);
2505 	dbuf_verify_user(db, DBVU_NOT_EVICTING);
2506 	if (db->db_user == old_user)
2507 		db->db_user = new_user;
2508 	else
2509 		old_user = db->db_user;
2510 	dbuf_verify_user(db, DBVU_NOT_EVICTING);
2511 	mutex_exit(&db->db_mtx);
2512 
2513 	return (old_user);
2514 }
2515 
2516 void *
2517 dmu_buf_set_user(dmu_buf_t *db_fake, dmu_buf_user_t *user)
2518 {
2519 	return (dmu_buf_replace_user(db_fake, NULL, user));
2520 }
2521 
2522 void *
2523 dmu_buf_set_user_ie(dmu_buf_t *db_fake, dmu_buf_user_t *user)
2524 {
2525 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2526 
2527 	db->db_user_immediate_evict = TRUE;
2528 	return (dmu_buf_set_user(db_fake, user));
2529 }
2530 
2531 void *
2532 dmu_buf_remove_user(dmu_buf_t *db_fake, dmu_buf_user_t *user)
2533 {
2534 	return (dmu_buf_replace_user(db_fake, user, NULL));
2535 }
2536 
2537 void *
2538 dmu_buf_get_user(dmu_buf_t *db_fake)
2539 {
2540 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2541 
2542 	dbuf_verify_user(db, DBVU_NOT_EVICTING);
2543 	return (db->db_user);
2544 }
2545 
2546 void
2547 dmu_buf_user_evict_wait()
2548 {
2549 	taskq_wait(dbu_evict_taskq);
2550 }
2551 
2552 boolean_t
2553 dmu_buf_freeable(dmu_buf_t *dbuf)
2554 {
2555 	boolean_t res = B_FALSE;
2556 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbuf;
2557 
2558 	if (db->db_blkptr)
2559 		res = dsl_dataset_block_freeable(db->db_objset->os_dsl_dataset,
2560 		    db->db_blkptr, db->db_blkptr->blk_birth);
2561 
2562 	return (res);
2563 }
2564 
2565 blkptr_t *
2566 dmu_buf_get_blkptr(dmu_buf_t *db)
2567 {
2568 	dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
2569 	return (dbi->db_blkptr);
2570 }
2571 
2572 static void
2573 dbuf_check_blkptr(dnode_t *dn, dmu_buf_impl_t *db)
2574 {
2575 	/* ASSERT(dmu_tx_is_syncing(tx) */
2576 	ASSERT(MUTEX_HELD(&db->db_mtx));
2577 
2578 	if (db->db_blkptr != NULL)
2579 		return;
2580 
2581 	if (db->db_blkid == DMU_SPILL_BLKID) {
2582 		db->db_blkptr = &dn->dn_phys->dn_spill;
2583 		BP_ZERO(db->db_blkptr);
2584 		return;
2585 	}
2586 	if (db->db_level == dn->dn_phys->dn_nlevels-1) {
2587 		/*
2588 		 * This buffer was allocated at a time when there was
2589 		 * no available blkptrs from the dnode, or it was
2590 		 * inappropriate to hook it in (i.e., nlevels mis-match).
2591 		 */
2592 		ASSERT(db->db_blkid < dn->dn_phys->dn_nblkptr);
2593 		ASSERT(db->db_parent == NULL);
2594 		db->db_parent = dn->dn_dbuf;
2595 		db->db_blkptr = &dn->dn_phys->dn_blkptr[db->db_blkid];
2596 		DBUF_VERIFY(db);
2597 	} else {
2598 		dmu_buf_impl_t *parent = db->db_parent;
2599 		int epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
2600 
2601 		ASSERT(dn->dn_phys->dn_nlevels > 1);
2602 		if (parent == NULL) {
2603 			mutex_exit(&db->db_mtx);
2604 			rw_enter(&dn->dn_struct_rwlock, RW_READER);
2605 			parent = dbuf_hold_level(dn, db->db_level + 1,
2606 			    db->db_blkid >> epbs, db);
2607 			rw_exit(&dn->dn_struct_rwlock);
2608 			mutex_enter(&db->db_mtx);
2609 			db->db_parent = parent;
2610 		}
2611 		db->db_blkptr = (blkptr_t *)parent->db.db_data +
2612 		    (db->db_blkid & ((1ULL << epbs) - 1));
2613 		DBUF_VERIFY(db);
2614 	}
2615 }
2616 
2617 static void
2618 dbuf_sync_indirect(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
2619 {
2620 	dmu_buf_impl_t *db = dr->dr_dbuf;
2621 	dnode_t *dn;
2622 	zio_t *zio;
2623 
2624 	ASSERT(dmu_tx_is_syncing(tx));
2625 
2626 	dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
2627 
2628 	mutex_enter(&db->db_mtx);
2629 
2630 	ASSERT(db->db_level > 0);
2631 	DBUF_VERIFY(db);
2632 
2633 	/* Read the block if it hasn't been read yet. */
2634 	if (db->db_buf == NULL) {
2635 		mutex_exit(&db->db_mtx);
2636 		(void) dbuf_read(db, NULL, DB_RF_MUST_SUCCEED);
2637 		mutex_enter(&db->db_mtx);
2638 	}
2639 	ASSERT3U(db->db_state, ==, DB_CACHED);
2640 	ASSERT(db->db_buf != NULL);
2641 
2642 	DB_DNODE_ENTER(db);
2643 	dn = DB_DNODE(db);
2644 	/* Indirect block size must match what the dnode thinks it is. */
2645 	ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
2646 	dbuf_check_blkptr(dn, db);
2647 	DB_DNODE_EXIT(db);
2648 
2649 	/* Provide the pending dirty record to child dbufs */
2650 	db->db_data_pending = dr;
2651 
2652 	mutex_exit(&db->db_mtx);
2653 	dbuf_write(dr, db->db_buf, tx);
2654 
2655 	zio = dr->dr_zio;
2656 	mutex_enter(&dr->dt.di.dr_mtx);
2657 	dbuf_sync_list(&dr->dt.di.dr_children, db->db_level - 1, tx);
2658 	ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
2659 	mutex_exit(&dr->dt.di.dr_mtx);
2660 	zio_nowait(zio);
2661 }
2662 
2663 static void
2664 dbuf_sync_leaf(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
2665 {
2666 	arc_buf_t **datap = &dr->dt.dl.dr_data;
2667 	dmu_buf_impl_t *db = dr->dr_dbuf;
2668 	dnode_t *dn;
2669 	objset_t *os;
2670 	uint64_t txg = tx->tx_txg;
2671 
2672 	ASSERT(dmu_tx_is_syncing(tx));
2673 
2674 	dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
2675 
2676 	mutex_enter(&db->db_mtx);
2677 	/*
2678 	 * To be synced, we must be dirtied.  But we
2679 	 * might have been freed after the dirty.
2680 	 */
2681 	if (db->db_state == DB_UNCACHED) {
2682 		/* This buffer has been freed since it was dirtied */
2683 		ASSERT(db->db.db_data == NULL);
2684 	} else if (db->db_state == DB_FILL) {
2685 		/* This buffer was freed and is now being re-filled */
2686 		ASSERT(db->db.db_data != dr->dt.dl.dr_data);
2687 	} else {
2688 		ASSERT(db->db_state == DB_CACHED || db->db_state == DB_NOFILL);
2689 	}
2690 	DBUF_VERIFY(db);
2691 
2692 	DB_DNODE_ENTER(db);
2693 	dn = DB_DNODE(db);
2694 
2695 	if (db->db_blkid == DMU_SPILL_BLKID) {
2696 		mutex_enter(&dn->dn_mtx);
2697 		dn->dn_phys->dn_flags |= DNODE_FLAG_SPILL_BLKPTR;
2698 		mutex_exit(&dn->dn_mtx);
2699 	}
2700 
2701 	/*
2702 	 * If this is a bonus buffer, simply copy the bonus data into the
2703 	 * dnode.  It will be written out when the dnode is synced (and it
2704 	 * will be synced, since it must have been dirty for dbuf_sync to
2705 	 * be called).
2706 	 */
2707 	if (db->db_blkid == DMU_BONUS_BLKID) {
2708 		dbuf_dirty_record_t **drp;
2709 
2710 		ASSERT(*datap != NULL);
2711 		ASSERT0(db->db_level);
2712 		ASSERT3U(dn->dn_phys->dn_bonuslen, <=, DN_MAX_BONUSLEN);
2713 		bcopy(*datap, DN_BONUS(dn->dn_phys), dn->dn_phys->dn_bonuslen);
2714 		DB_DNODE_EXIT(db);
2715 
2716 		if (*datap != db->db.db_data) {
2717 			zio_buf_free(*datap, DN_MAX_BONUSLEN);
2718 			arc_space_return(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
2719 		}
2720 		db->db_data_pending = NULL;
2721 		drp = &db->db_last_dirty;
2722 		while (*drp != dr)
2723 			drp = &(*drp)->dr_next;
2724 		ASSERT(dr->dr_next == NULL);
2725 		ASSERT(dr->dr_dbuf == db);
2726 		*drp = dr->dr_next;
2727 		kmem_free(dr, sizeof (dbuf_dirty_record_t));
2728 		ASSERT(db->db_dirtycnt > 0);
2729 		db->db_dirtycnt -= 1;
2730 		dbuf_rele_and_unlock(db, (void *)(uintptr_t)txg);
2731 		return;
2732 	}
2733 
2734 	os = dn->dn_objset;
2735 
2736 	/*
2737 	 * This function may have dropped the db_mtx lock allowing a dmu_sync
2738 	 * operation to sneak in. As a result, we need to ensure that we
2739 	 * don't check the dr_override_state until we have returned from
2740 	 * dbuf_check_blkptr.
2741 	 */
2742 	dbuf_check_blkptr(dn, db);
2743 
2744 	/*
2745 	 * If this buffer is in the middle of an immediate write,
2746 	 * wait for the synchronous IO to complete.
2747 	 */
2748 	while (dr->dt.dl.dr_override_state == DR_IN_DMU_SYNC) {
2749 		ASSERT(dn->dn_object != DMU_META_DNODE_OBJECT);
2750 		cv_wait(&db->db_changed, &db->db_mtx);
2751 		ASSERT(dr->dt.dl.dr_override_state != DR_NOT_OVERRIDDEN);
2752 	}
2753 
2754 	if (db->db_state != DB_NOFILL &&
2755 	    dn->dn_object != DMU_META_DNODE_OBJECT &&
2756 	    refcount_count(&db->db_holds) > 1 &&
2757 	    dr->dt.dl.dr_override_state != DR_OVERRIDDEN &&
2758 	    *datap == db->db_buf) {
2759 		/*
2760 		 * If this buffer is currently "in use" (i.e., there
2761 		 * are active holds and db_data still references it),
2762 		 * then make a copy before we start the write so that
2763 		 * any modifications from the open txg will not leak
2764 		 * into this write.
2765 		 *
2766 		 * NOTE: this copy does not need to be made for
2767 		 * objects only modified in the syncing context (e.g.
2768 		 * DNONE_DNODE blocks).
2769 		 */
2770 		int blksz = arc_buf_size(*datap);
2771 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
2772 		*datap = arc_buf_alloc(os->os_spa, blksz, db, type);
2773 		bcopy(db->db.db_data, (*datap)->b_data, blksz);
2774 	}
2775 	db->db_data_pending = dr;
2776 
2777 	mutex_exit(&db->db_mtx);
2778 
2779 	dbuf_write(dr, *datap, tx);
2780 
2781 	ASSERT(!list_link_active(&dr->dr_dirty_node));
2782 	if (dn->dn_object == DMU_META_DNODE_OBJECT) {
2783 		list_insert_tail(&dn->dn_dirty_records[txg&TXG_MASK], dr);
2784 		DB_DNODE_EXIT(db);
2785 	} else {
2786 		/*
2787 		 * Although zio_nowait() does not "wait for an IO", it does
2788 		 * initiate the IO. If this is an empty write it seems plausible
2789 		 * that the IO could actually be completed before the nowait
2790 		 * returns. We need to DB_DNODE_EXIT() first in case
2791 		 * zio_nowait() invalidates the dbuf.
2792 		 */
2793 		DB_DNODE_EXIT(db);
2794 		zio_nowait(dr->dr_zio);
2795 	}
2796 }
2797 
2798 void
2799 dbuf_sync_list(list_t *list, int level, dmu_tx_t *tx)
2800 {
2801 	dbuf_dirty_record_t *dr;
2802 
2803 	while (dr = list_head(list)) {
2804 		if (dr->dr_zio != NULL) {
2805 			/*
2806 			 * If we find an already initialized zio then we
2807 			 * are processing the meta-dnode, and we have finished.
2808 			 * The dbufs for all dnodes are put back on the list
2809 			 * during processing, so that we can zio_wait()
2810 			 * these IOs after initiating all child IOs.
2811 			 */
2812 			ASSERT3U(dr->dr_dbuf->db.db_object, ==,
2813 			    DMU_META_DNODE_OBJECT);
2814 			break;
2815 		}
2816 		if (dr->dr_dbuf->db_blkid != DMU_BONUS_BLKID &&
2817 		    dr->dr_dbuf->db_blkid != DMU_SPILL_BLKID) {
2818 			VERIFY3U(dr->dr_dbuf->db_level, ==, level);
2819 		}
2820 		list_remove(list, dr);
2821 		if (dr->dr_dbuf->db_level > 0)
2822 			dbuf_sync_indirect(dr, tx);
2823 		else
2824 			dbuf_sync_leaf(dr, tx);
2825 	}
2826 }
2827 
2828 /* ARGSUSED */
2829 static void
2830 dbuf_write_ready(zio_t *zio, arc_buf_t *buf, void *vdb)
2831 {
2832 	dmu_buf_impl_t *db = vdb;
2833 	dnode_t *dn;
2834 	blkptr_t *bp = zio->io_bp;
2835 	blkptr_t *bp_orig = &zio->io_bp_orig;
2836 	spa_t *spa = zio->io_spa;
2837 	int64_t delta;
2838 	uint64_t fill = 0;
2839 	int i;
2840 
2841 	ASSERT3P(db->db_blkptr, ==, bp);
2842 
2843 	DB_DNODE_ENTER(db);
2844 	dn = DB_DNODE(db);
2845 	delta = bp_get_dsize_sync(spa, bp) - bp_get_dsize_sync(spa, bp_orig);
2846 	dnode_diduse_space(dn, delta - zio->io_prev_space_delta);
2847 	zio->io_prev_space_delta = delta;
2848 
2849 	if (bp->blk_birth != 0) {
2850 		ASSERT((db->db_blkid != DMU_SPILL_BLKID &&
2851 		    BP_GET_TYPE(bp) == dn->dn_type) ||
2852 		    (db->db_blkid == DMU_SPILL_BLKID &&
2853 		    BP_GET_TYPE(bp) == dn->dn_bonustype) ||
2854 		    BP_IS_EMBEDDED(bp));
2855 		ASSERT(BP_GET_LEVEL(bp) == db->db_level);
2856 	}
2857 
2858 	mutex_enter(&db->db_mtx);
2859 
2860 #ifdef ZFS_DEBUG
2861 	if (db->db_blkid == DMU_SPILL_BLKID) {
2862 		ASSERT(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR);
2863 		ASSERT(!(BP_IS_HOLE(db->db_blkptr)) &&
2864 		    db->db_blkptr == &dn->dn_phys->dn_spill);
2865 	}
2866 #endif
2867 
2868 	if (db->db_level == 0) {
2869 		mutex_enter(&dn->dn_mtx);
2870 		if (db->db_blkid > dn->dn_phys->dn_maxblkid &&
2871 		    db->db_blkid != DMU_SPILL_BLKID)
2872 			dn->dn_phys->dn_maxblkid = db->db_blkid;
2873 		mutex_exit(&dn->dn_mtx);
2874 
2875 		if (dn->dn_type == DMU_OT_DNODE) {
2876 			dnode_phys_t *dnp = db->db.db_data;
2877 			for (i = db->db.db_size >> DNODE_SHIFT; i > 0;
2878 			    i--, dnp++) {
2879 				if (dnp->dn_type != DMU_OT_NONE)
2880 					fill++;
2881 			}
2882 		} else {
2883 			if (BP_IS_HOLE(bp)) {
2884 				fill = 0;
2885 			} else {
2886 				fill = 1;
2887 			}
2888 		}
2889 	} else {
2890 		blkptr_t *ibp = db->db.db_data;
2891 		ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
2892 		for (i = db->db.db_size >> SPA_BLKPTRSHIFT; i > 0; i--, ibp++) {
2893 			if (BP_IS_HOLE(ibp))
2894 				continue;
2895 			fill += BP_GET_FILL(ibp);
2896 		}
2897 	}
2898 	DB_DNODE_EXIT(db);
2899 
2900 	if (!BP_IS_EMBEDDED(bp))
2901 		bp->blk_fill = fill;
2902 
2903 	mutex_exit(&db->db_mtx);
2904 }
2905 
2906 /*
2907  * The SPA will call this callback several times for each zio - once
2908  * for every physical child i/o (zio->io_phys_children times).  This
2909  * allows the DMU to monitor the progress of each logical i/o.  For example,
2910  * there may be 2 copies of an indirect block, or many fragments of a RAID-Z
2911  * block.  There may be a long delay before all copies/fragments are completed,
2912  * so this callback allows us to retire dirty space gradually, as the physical
2913  * i/os complete.
2914  */
2915 /* ARGSUSED */
2916 static void
2917 dbuf_write_physdone(zio_t *zio, arc_buf_t *buf, void *arg)
2918 {
2919 	dmu_buf_impl_t *db = arg;
2920 	objset_t *os = db->db_objset;
2921 	dsl_pool_t *dp = dmu_objset_pool(os);
2922 	dbuf_dirty_record_t *dr;
2923 	int delta = 0;
2924 
2925 	dr = db->db_data_pending;
2926 	ASSERT3U(dr->dr_txg, ==, zio->io_txg);
2927 
2928 	/*
2929 	 * The callback will be called io_phys_children times.  Retire one
2930 	 * portion of our dirty space each time we are called.  Any rounding
2931 	 * error will be cleaned up by dsl_pool_sync()'s call to
2932 	 * dsl_pool_undirty_space().
2933 	 */
2934 	delta = dr->dr_accounted / zio->io_phys_children;
2935 	dsl_pool_undirty_space(dp, delta, zio->io_txg);
2936 }
2937 
2938 /* ARGSUSED */
2939 static void
2940 dbuf_write_done(zio_t *zio, arc_buf_t *buf, void *vdb)
2941 {
2942 	dmu_buf_impl_t *db = vdb;
2943 	blkptr_t *bp_orig = &zio->io_bp_orig;
2944 	blkptr_t *bp = db->db_blkptr;
2945 	objset_t *os = db->db_objset;
2946 	dmu_tx_t *tx = os->os_synctx;
2947 	dbuf_dirty_record_t **drp, *dr;
2948 
2949 	ASSERT0(zio->io_error);
2950 	ASSERT(db->db_blkptr == bp);
2951 
2952 	/*
2953 	 * For nopwrites and rewrites we ensure that the bp matches our
2954 	 * original and bypass all the accounting.
2955 	 */
2956 	if (zio->io_flags & (ZIO_FLAG_IO_REWRITE | ZIO_FLAG_NOPWRITE)) {
2957 		ASSERT(BP_EQUAL(bp, bp_orig));
2958 	} else {
2959 		dsl_dataset_t *ds = os->os_dsl_dataset;
2960 		(void) dsl_dataset_block_kill(ds, bp_orig, tx, B_TRUE);
2961 		dsl_dataset_block_born(ds, bp, tx);
2962 	}
2963 
2964 	mutex_enter(&db->db_mtx);
2965 
2966 	DBUF_VERIFY(db);
2967 
2968 	drp = &db->db_last_dirty;
2969 	while ((dr = *drp) != db->db_data_pending)
2970 		drp = &dr->dr_next;
2971 	ASSERT(!list_link_active(&dr->dr_dirty_node));
2972 	ASSERT(dr->dr_dbuf == db);
2973 	ASSERT(dr->dr_next == NULL);
2974 	*drp = dr->dr_next;
2975 
2976 #ifdef ZFS_DEBUG
2977 	if (db->db_blkid == DMU_SPILL_BLKID) {
2978 		dnode_t *dn;
2979 
2980 		DB_DNODE_ENTER(db);
2981 		dn = DB_DNODE(db);
2982 		ASSERT(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR);
2983 		ASSERT(!(BP_IS_HOLE(db->db_blkptr)) &&
2984 		    db->db_blkptr == &dn->dn_phys->dn_spill);
2985 		DB_DNODE_EXIT(db);
2986 	}
2987 #endif
2988 
2989 	if (db->db_level == 0) {
2990 		ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2991 		ASSERT(dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN);
2992 		if (db->db_state != DB_NOFILL) {
2993 			if (dr->dt.dl.dr_data != db->db_buf)
2994 				VERIFY(arc_buf_remove_ref(dr->dt.dl.dr_data,
2995 				    db));
2996 			else if (!arc_released(db->db_buf))
2997 				arc_set_callback(db->db_buf, dbuf_do_evict, db);
2998 		}
2999 	} else {
3000 		dnode_t *dn;
3001 
3002 		DB_DNODE_ENTER(db);
3003 		dn = DB_DNODE(db);
3004 		ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
3005 		ASSERT3U(db->db.db_size, ==, 1 << dn->dn_phys->dn_indblkshift);
3006 		if (!BP_IS_HOLE(db->db_blkptr)) {
3007 			int epbs =
3008 			    dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
3009 			ASSERT3U(db->db_blkid, <=,
3010 			    dn->dn_phys->dn_maxblkid >> (db->db_level * epbs));
3011 			ASSERT3U(BP_GET_LSIZE(db->db_blkptr), ==,
3012 			    db->db.db_size);
3013 			if (!arc_released(db->db_buf))
3014 				arc_set_callback(db->db_buf, dbuf_do_evict, db);
3015 		}
3016 		DB_DNODE_EXIT(db);
3017 		mutex_destroy(&dr->dt.di.dr_mtx);
3018 		list_destroy(&dr->dt.di.dr_children);
3019 	}
3020 	kmem_free(dr, sizeof (dbuf_dirty_record_t));
3021 
3022 	cv_broadcast(&db->db_changed);
3023 	ASSERT(db->db_dirtycnt > 0);
3024 	db->db_dirtycnt -= 1;
3025 	db->db_data_pending = NULL;
3026 	dbuf_rele_and_unlock(db, (void *)(uintptr_t)tx->tx_txg);
3027 }
3028 
3029 static void
3030 dbuf_write_nofill_ready(zio_t *zio)
3031 {
3032 	dbuf_write_ready(zio, NULL, zio->io_private);
3033 }
3034 
3035 static void
3036 dbuf_write_nofill_done(zio_t *zio)
3037 {
3038 	dbuf_write_done(zio, NULL, zio->io_private);
3039 }
3040 
3041 static void
3042 dbuf_write_override_ready(zio_t *zio)
3043 {
3044 	dbuf_dirty_record_t *dr = zio->io_private;
3045 	dmu_buf_impl_t *db = dr->dr_dbuf;
3046 
3047 	dbuf_write_ready(zio, NULL, db);
3048 }
3049 
3050 static void
3051 dbuf_write_override_done(zio_t *zio)
3052 {
3053 	dbuf_dirty_record_t *dr = zio->io_private;
3054 	dmu_buf_impl_t *db = dr->dr_dbuf;
3055 	blkptr_t *obp = &dr->dt.dl.dr_overridden_by;
3056 
3057 	mutex_enter(&db->db_mtx);
3058 	if (!BP_EQUAL(zio->io_bp, obp)) {
3059 		if (!BP_IS_HOLE(obp))
3060 			dsl_free(spa_get_dsl(zio->io_spa), zio->io_txg, obp);
3061 		arc_release(dr->dt.dl.dr_data, db);
3062 	}
3063 	mutex_exit(&db->db_mtx);
3064 
3065 	dbuf_write_done(zio, NULL, db);
3066 }
3067 
3068 /* Issue I/O to commit a dirty buffer to disk. */
3069 static void
3070 dbuf_write(dbuf_dirty_record_t *dr, arc_buf_t *data, dmu_tx_t *tx)
3071 {
3072 	dmu_buf_impl_t *db = dr->dr_dbuf;
3073 	dnode_t *dn;
3074 	objset_t *os;
3075 	dmu_buf_impl_t *parent = db->db_parent;
3076 	uint64_t txg = tx->tx_txg;
3077 	zbookmark_phys_t zb;
3078 	zio_prop_t zp;
3079 	zio_t *zio;
3080 	int wp_flag = 0;
3081 
3082 	DB_DNODE_ENTER(db);
3083 	dn = DB_DNODE(db);
3084 	os = dn->dn_objset;
3085 
3086 	if (db->db_state != DB_NOFILL) {
3087 		if (db->db_level > 0 || dn->dn_type == DMU_OT_DNODE) {
3088 			/*
3089 			 * Private object buffers are released here rather
3090 			 * than in dbuf_dirty() since they are only modified
3091 			 * in the syncing context and we don't want the
3092 			 * overhead of making multiple copies of the data.
3093 			 */
3094 			if (BP_IS_HOLE(db->db_blkptr)) {
3095 				arc_buf_thaw(data);
3096 			} else {
3097 				dbuf_release_bp(db);
3098 			}
3099 		}
3100 	}
3101 
3102 	if (parent != dn->dn_dbuf) {
3103 		/* Our parent is an indirect block. */
3104 		/* We have a dirty parent that has been scheduled for write. */
3105 		ASSERT(parent && parent->db_data_pending);
3106 		/* Our parent's buffer is one level closer to the dnode. */
3107 		ASSERT(db->db_level == parent->db_level-1);
3108 		/*
3109 		 * We're about to modify our parent's db_data by modifying
3110 		 * our block pointer, so the parent must be released.
3111 		 */
3112 		ASSERT(arc_released(parent->db_buf));
3113 		zio = parent->db_data_pending->dr_zio;
3114 	} else {
3115 		/* Our parent is the dnode itself. */
3116 		ASSERT((db->db_level == dn->dn_phys->dn_nlevels-1 &&
3117 		    db->db_blkid != DMU_SPILL_BLKID) ||
3118 		    (db->db_blkid == DMU_SPILL_BLKID && db->db_level == 0));
3119 		if (db->db_blkid != DMU_SPILL_BLKID)
3120 			ASSERT3P(db->db_blkptr, ==,
3121 			    &dn->dn_phys->dn_blkptr[db->db_blkid]);
3122 		zio = dn->dn_zio;
3123 	}
3124 
3125 	ASSERT(db->db_level == 0 || data == db->db_buf);
3126 	ASSERT3U(db->db_blkptr->blk_birth, <=, txg);
3127 	ASSERT(zio);
3128 
3129 	SET_BOOKMARK(&zb, os->os_dsl_dataset ?
3130 	    os->os_dsl_dataset->ds_object : DMU_META_OBJSET,
3131 	    db->db.db_object, db->db_level, db->db_blkid);
3132 
3133 	if (db->db_blkid == DMU_SPILL_BLKID)
3134 		wp_flag = WP_SPILL;
3135 	wp_flag |= (db->db_state == DB_NOFILL) ? WP_NOFILL : 0;
3136 
3137 	dmu_write_policy(os, dn, db->db_level, wp_flag, &zp);
3138 	DB_DNODE_EXIT(db);
3139 
3140 	if (db->db_level == 0 &&
3141 	    dr->dt.dl.dr_override_state == DR_OVERRIDDEN) {
3142 		/*
3143 		 * The BP for this block has been provided by open context
3144 		 * (by dmu_sync() or dmu_buf_write_embedded()).
3145 		 */
3146 		void *contents = (data != NULL) ? data->b_data : NULL;
3147 
3148 		dr->dr_zio = zio_write(zio, os->os_spa, txg,
3149 		    db->db_blkptr, contents, db->db.db_size, &zp,
3150 		    dbuf_write_override_ready, NULL, dbuf_write_override_done,
3151 		    dr, ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
3152 		mutex_enter(&db->db_mtx);
3153 		dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
3154 		zio_write_override(dr->dr_zio, &dr->dt.dl.dr_overridden_by,
3155 		    dr->dt.dl.dr_copies, dr->dt.dl.dr_nopwrite);
3156 		mutex_exit(&db->db_mtx);
3157 	} else if (db->db_state == DB_NOFILL) {
3158 		ASSERT(zp.zp_checksum == ZIO_CHECKSUM_OFF ||
3159 		    zp.zp_checksum == ZIO_CHECKSUM_NOPARITY);
3160 		dr->dr_zio = zio_write(zio, os->os_spa, txg,
3161 		    db->db_blkptr, NULL, db->db.db_size, &zp,
3162 		    dbuf_write_nofill_ready, NULL, dbuf_write_nofill_done, db,
3163 		    ZIO_PRIORITY_ASYNC_WRITE,
3164 		    ZIO_FLAG_MUSTSUCCEED | ZIO_FLAG_NODATA, &zb);
3165 	} else {
3166 		ASSERT(arc_released(data));
3167 		dr->dr_zio = arc_write(zio, os->os_spa, txg,
3168 		    db->db_blkptr, data, DBUF_IS_L2CACHEABLE(db),
3169 		    DBUF_IS_L2COMPRESSIBLE(db), &zp, dbuf_write_ready,
3170 		    dbuf_write_physdone, dbuf_write_done, db,
3171 		    ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
3172 	}
3173 }
3174