xref: /illumos-gate/usr/src/uts/common/fs/zfs/dbuf.c (revision cd485b49201b16c079663125308af274b6299e96)
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, 2014 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_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 uint64_t
552 dbuf_whichblock(dnode_t *dn, uint64_t offset)
553 {
554 	if (dn->dn_datablkshift) {
555 		return (offset >> dn->dn_datablkshift);
556 	} else {
557 		ASSERT3U(offset, <, dn->dn_datablksz);
558 		return (0);
559 	}
560 }
561 
562 static void
563 dbuf_read_done(zio_t *zio, arc_buf_t *buf, void *vdb)
564 {
565 	dmu_buf_impl_t *db = vdb;
566 
567 	mutex_enter(&db->db_mtx);
568 	ASSERT3U(db->db_state, ==, DB_READ);
569 	/*
570 	 * All reads are synchronous, so we must have a hold on the dbuf
571 	 */
572 	ASSERT(refcount_count(&db->db_holds) > 0);
573 	ASSERT(db->db_buf == NULL);
574 	ASSERT(db->db.db_data == NULL);
575 	if (db->db_level == 0 && db->db_freed_in_flight) {
576 		/* we were freed in flight; disregard any error */
577 		arc_release(buf, db);
578 		bzero(buf->b_data, db->db.db_size);
579 		arc_buf_freeze(buf);
580 		db->db_freed_in_flight = FALSE;
581 		dbuf_set_data(db, buf);
582 		db->db_state = DB_CACHED;
583 	} else if (zio == NULL || zio->io_error == 0) {
584 		dbuf_set_data(db, buf);
585 		db->db_state = DB_CACHED;
586 	} else {
587 		ASSERT(db->db_blkid != DMU_BONUS_BLKID);
588 		ASSERT3P(db->db_buf, ==, NULL);
589 		VERIFY(arc_buf_remove_ref(buf, db));
590 		db->db_state = DB_UNCACHED;
591 	}
592 	cv_broadcast(&db->db_changed);
593 	dbuf_rele_and_unlock(db, NULL);
594 }
595 
596 static void
597 dbuf_read_impl(dmu_buf_impl_t *db, zio_t *zio, uint32_t *flags)
598 {
599 	dnode_t *dn;
600 	zbookmark_phys_t zb;
601 	arc_flags_t aflags = ARC_FLAG_NOWAIT;
602 
603 	DB_DNODE_ENTER(db);
604 	dn = DB_DNODE(db);
605 	ASSERT(!refcount_is_zero(&db->db_holds));
606 	/* We need the struct_rwlock to prevent db_blkptr from changing. */
607 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
608 	ASSERT(MUTEX_HELD(&db->db_mtx));
609 	ASSERT(db->db_state == DB_UNCACHED);
610 	ASSERT(db->db_buf == NULL);
611 
612 	if (db->db_blkid == DMU_BONUS_BLKID) {
613 		int bonuslen = MIN(dn->dn_bonuslen, dn->dn_phys->dn_bonuslen);
614 
615 		ASSERT3U(bonuslen, <=, db->db.db_size);
616 		db->db.db_data = zio_buf_alloc(DN_MAX_BONUSLEN);
617 		arc_space_consume(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
618 		if (bonuslen < DN_MAX_BONUSLEN)
619 			bzero(db->db.db_data, DN_MAX_BONUSLEN);
620 		if (bonuslen)
621 			bcopy(DN_BONUS(dn->dn_phys), db->db.db_data, bonuslen);
622 		DB_DNODE_EXIT(db);
623 		db->db_state = DB_CACHED;
624 		mutex_exit(&db->db_mtx);
625 		return;
626 	}
627 
628 	/*
629 	 * Recheck BP_IS_HOLE() after dnode_block_freed() in case dnode_sync()
630 	 * processes the delete record and clears the bp while we are waiting
631 	 * for the dn_mtx (resulting in a "no" from block_freed).
632 	 */
633 	if (db->db_blkptr == NULL || BP_IS_HOLE(db->db_blkptr) ||
634 	    (db->db_level == 0 && (dnode_block_freed(dn, db->db_blkid) ||
635 	    BP_IS_HOLE(db->db_blkptr)))) {
636 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
637 
638 		DB_DNODE_EXIT(db);
639 		dbuf_set_data(db, arc_buf_alloc(db->db_objset->os_spa,
640 		    db->db.db_size, db, type));
641 		bzero(db->db.db_data, db->db.db_size);
642 		db->db_state = DB_CACHED;
643 		*flags |= DB_RF_CACHED;
644 		mutex_exit(&db->db_mtx);
645 		return;
646 	}
647 
648 	DB_DNODE_EXIT(db);
649 
650 	db->db_state = DB_READ;
651 	mutex_exit(&db->db_mtx);
652 
653 	if (DBUF_IS_L2CACHEABLE(db))
654 		aflags |= ARC_FLAG_L2CACHE;
655 	if (DBUF_IS_L2COMPRESSIBLE(db))
656 		aflags |= ARC_FLAG_L2COMPRESS;
657 
658 	SET_BOOKMARK(&zb, db->db_objset->os_dsl_dataset ?
659 	    db->db_objset->os_dsl_dataset->ds_object : DMU_META_OBJSET,
660 	    db->db.db_object, db->db_level, db->db_blkid);
661 
662 	dbuf_add_ref(db, NULL);
663 
664 	(void) arc_read(zio, db->db_objset->os_spa, db->db_blkptr,
665 	    dbuf_read_done, db, ZIO_PRIORITY_SYNC_READ,
666 	    (*flags & DB_RF_CANFAIL) ? ZIO_FLAG_CANFAIL : ZIO_FLAG_MUSTSUCCEED,
667 	    &aflags, &zb);
668 	if (aflags & ARC_FLAG_CACHED)
669 		*flags |= DB_RF_CACHED;
670 }
671 
672 int
673 dbuf_read(dmu_buf_impl_t *db, zio_t *zio, uint32_t flags)
674 {
675 	int err = 0;
676 	boolean_t havepzio = (zio != NULL);
677 	boolean_t prefetch;
678 	dnode_t *dn;
679 
680 	/*
681 	 * We don't have to hold the mutex to check db_state because it
682 	 * can't be freed while we have a hold on the buffer.
683 	 */
684 	ASSERT(!refcount_is_zero(&db->db_holds));
685 
686 	if (db->db_state == DB_NOFILL)
687 		return (SET_ERROR(EIO));
688 
689 	DB_DNODE_ENTER(db);
690 	dn = DB_DNODE(db);
691 	if ((flags & DB_RF_HAVESTRUCT) == 0)
692 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
693 
694 	prefetch = db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
695 	    (flags & DB_RF_NOPREFETCH) == 0 && dn != NULL &&
696 	    DBUF_IS_CACHEABLE(db);
697 
698 	mutex_enter(&db->db_mtx);
699 	if (db->db_state == DB_CACHED) {
700 		mutex_exit(&db->db_mtx);
701 		if (prefetch)
702 			dmu_zfetch(&dn->dn_zfetch, db->db.db_offset,
703 			    db->db.db_size, TRUE);
704 		if ((flags & DB_RF_HAVESTRUCT) == 0)
705 			rw_exit(&dn->dn_struct_rwlock);
706 		DB_DNODE_EXIT(db);
707 	} else if (db->db_state == DB_UNCACHED) {
708 		spa_t *spa = dn->dn_objset->os_spa;
709 
710 		if (zio == NULL)
711 			zio = zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL);
712 		dbuf_read_impl(db, zio, &flags);
713 
714 		/* dbuf_read_impl has dropped db_mtx for us */
715 
716 		if (prefetch)
717 			dmu_zfetch(&dn->dn_zfetch, db->db.db_offset,
718 			    db->db.db_size, flags & DB_RF_CACHED);
719 
720 		if ((flags & DB_RF_HAVESTRUCT) == 0)
721 			rw_exit(&dn->dn_struct_rwlock);
722 		DB_DNODE_EXIT(db);
723 
724 		if (!havepzio)
725 			err = zio_wait(zio);
726 	} else {
727 		/*
728 		 * Another reader came in while the dbuf was in flight
729 		 * between UNCACHED and CACHED.  Either a writer will finish
730 		 * writing the buffer (sending the dbuf to CACHED) or the
731 		 * first reader's request will reach the read_done callback
732 		 * and send the dbuf to CACHED.  Otherwise, a failure
733 		 * occurred and the dbuf went to UNCACHED.
734 		 */
735 		mutex_exit(&db->db_mtx);
736 		if (prefetch)
737 			dmu_zfetch(&dn->dn_zfetch, db->db.db_offset,
738 			    db->db.db_size, TRUE);
739 		if ((flags & DB_RF_HAVESTRUCT) == 0)
740 			rw_exit(&dn->dn_struct_rwlock);
741 		DB_DNODE_EXIT(db);
742 
743 		/* Skip the wait per the caller's request. */
744 		mutex_enter(&db->db_mtx);
745 		if ((flags & DB_RF_NEVERWAIT) == 0) {
746 			while (db->db_state == DB_READ ||
747 			    db->db_state == DB_FILL) {
748 				ASSERT(db->db_state == DB_READ ||
749 				    (flags & DB_RF_HAVESTRUCT) == 0);
750 				DTRACE_PROBE2(blocked__read, dmu_buf_impl_t *,
751 				    db, zio_t *, zio);
752 				cv_wait(&db->db_changed, &db->db_mtx);
753 			}
754 			if (db->db_state == DB_UNCACHED)
755 				err = SET_ERROR(EIO);
756 		}
757 		mutex_exit(&db->db_mtx);
758 	}
759 
760 	ASSERT(err || havepzio || db->db_state == DB_CACHED);
761 	return (err);
762 }
763 
764 static void
765 dbuf_noread(dmu_buf_impl_t *db)
766 {
767 	ASSERT(!refcount_is_zero(&db->db_holds));
768 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
769 	mutex_enter(&db->db_mtx);
770 	while (db->db_state == DB_READ || db->db_state == DB_FILL)
771 		cv_wait(&db->db_changed, &db->db_mtx);
772 	if (db->db_state == DB_UNCACHED) {
773 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
774 		spa_t *spa = db->db_objset->os_spa;
775 
776 		ASSERT(db->db_buf == NULL);
777 		ASSERT(db->db.db_data == NULL);
778 		dbuf_set_data(db, arc_buf_alloc(spa, db->db.db_size, db, type));
779 		db->db_state = DB_FILL;
780 	} else if (db->db_state == DB_NOFILL) {
781 		dbuf_clear_data(db);
782 	} else {
783 		ASSERT3U(db->db_state, ==, DB_CACHED);
784 	}
785 	mutex_exit(&db->db_mtx);
786 }
787 
788 /*
789  * This is our just-in-time copy function.  It makes a copy of
790  * buffers, that have been modified in a previous transaction
791  * group, before we modify them in the current active group.
792  *
793  * This function is used in two places: when we are dirtying a
794  * buffer for the first time in a txg, and when we are freeing
795  * a range in a dnode that includes this buffer.
796  *
797  * Note that when we are called from dbuf_free_range() we do
798  * not put a hold on the buffer, we just traverse the active
799  * dbuf list for the dnode.
800  */
801 static void
802 dbuf_fix_old_data(dmu_buf_impl_t *db, uint64_t txg)
803 {
804 	dbuf_dirty_record_t *dr = db->db_last_dirty;
805 
806 	ASSERT(MUTEX_HELD(&db->db_mtx));
807 	ASSERT(db->db.db_data != NULL);
808 	ASSERT(db->db_level == 0);
809 	ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT);
810 
811 	if (dr == NULL ||
812 	    (dr->dt.dl.dr_data !=
813 	    ((db->db_blkid  == DMU_BONUS_BLKID) ? db->db.db_data : db->db_buf)))
814 		return;
815 
816 	/*
817 	 * If the last dirty record for this dbuf has not yet synced
818 	 * and its referencing the dbuf data, either:
819 	 *	reset the reference to point to a new copy,
820 	 * or (if there a no active holders)
821 	 *	just null out the current db_data pointer.
822 	 */
823 	ASSERT(dr->dr_txg >= txg - 2);
824 	if (db->db_blkid == DMU_BONUS_BLKID) {
825 		/* Note that the data bufs here are zio_bufs */
826 		dr->dt.dl.dr_data = zio_buf_alloc(DN_MAX_BONUSLEN);
827 		arc_space_consume(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
828 		bcopy(db->db.db_data, dr->dt.dl.dr_data, DN_MAX_BONUSLEN);
829 	} else if (refcount_count(&db->db_holds) > db->db_dirtycnt) {
830 		int size = db->db.db_size;
831 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
832 		spa_t *spa = db->db_objset->os_spa;
833 
834 		dr->dt.dl.dr_data = arc_buf_alloc(spa, size, db, type);
835 		bcopy(db->db.db_data, dr->dt.dl.dr_data->b_data, size);
836 	} else {
837 		dbuf_clear_data(db);
838 	}
839 }
840 
841 void
842 dbuf_unoverride(dbuf_dirty_record_t *dr)
843 {
844 	dmu_buf_impl_t *db = dr->dr_dbuf;
845 	blkptr_t *bp = &dr->dt.dl.dr_overridden_by;
846 	uint64_t txg = dr->dr_txg;
847 
848 	ASSERT(MUTEX_HELD(&db->db_mtx));
849 	ASSERT(dr->dt.dl.dr_override_state != DR_IN_DMU_SYNC);
850 	ASSERT(db->db_level == 0);
851 
852 	if (db->db_blkid == DMU_BONUS_BLKID ||
853 	    dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN)
854 		return;
855 
856 	ASSERT(db->db_data_pending != dr);
857 
858 	/* free this block */
859 	if (!BP_IS_HOLE(bp) && !dr->dt.dl.dr_nopwrite)
860 		zio_free(db->db_objset->os_spa, txg, bp);
861 
862 	dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
863 	dr->dt.dl.dr_nopwrite = B_FALSE;
864 
865 	/*
866 	 * Release the already-written buffer, so we leave it in
867 	 * a consistent dirty state.  Note that all callers are
868 	 * modifying the buffer, so they will immediately do
869 	 * another (redundant) arc_release().  Therefore, leave
870 	 * the buf thawed to save the effort of freezing &
871 	 * immediately re-thawing it.
872 	 */
873 	arc_release(dr->dt.dl.dr_data, db);
874 }
875 
876 /*
877  * Evict (if its unreferenced) or clear (if its referenced) any level-0
878  * data blocks in the free range, so that any future readers will find
879  * empty blocks.
880  *
881  * This is a no-op if the dataset is in the middle of an incremental
882  * receive; see comment below for details.
883  */
884 void
885 dbuf_free_range(dnode_t *dn, uint64_t start_blkid, uint64_t end_blkid,
886     dmu_tx_t *tx)
887 {
888 	dmu_buf_impl_t db_search;
889 	dmu_buf_impl_t *db, *db_next;
890 	uint64_t txg = tx->tx_txg;
891 	avl_index_t where;
892 
893 	if (end_blkid > dn->dn_maxblkid && (end_blkid != DMU_SPILL_BLKID))
894 		end_blkid = dn->dn_maxblkid;
895 	dprintf_dnode(dn, "start=%llu end=%llu\n", start_blkid, end_blkid);
896 
897 	db_search.db_level = 0;
898 	db_search.db_blkid = start_blkid;
899 	db_search.db_state = DB_SEARCH;
900 
901 	mutex_enter(&dn->dn_dbufs_mtx);
902 	if (start_blkid >= dn->dn_unlisted_l0_blkid) {
903 		/* There can't be any dbufs in this range; no need to search. */
904 #ifdef DEBUG
905 		db = avl_find(&dn->dn_dbufs, &db_search, &where);
906 		ASSERT3P(db, ==, NULL);
907 		db = avl_nearest(&dn->dn_dbufs, where, AVL_AFTER);
908 		ASSERT(db == NULL || db->db_level > 0);
909 #endif
910 		mutex_exit(&dn->dn_dbufs_mtx);
911 		return;
912 	} else if (dmu_objset_is_receiving(dn->dn_objset)) {
913 		/*
914 		 * If we are receiving, we expect there to be no dbufs in
915 		 * the range to be freed, because receive modifies each
916 		 * block at most once, and in offset order.  If this is
917 		 * not the case, it can lead to performance problems,
918 		 * so note that we unexpectedly took the slow path.
919 		 */
920 		atomic_inc_64(&zfs_free_range_recv_miss);
921 	}
922 
923 	db = avl_find(&dn->dn_dbufs, &db_search, &where);
924 	ASSERT3P(db, ==, NULL);
925 	db = avl_nearest(&dn->dn_dbufs, where, AVL_AFTER);
926 
927 	for (; db != NULL; db = db_next) {
928 		db_next = AVL_NEXT(&dn->dn_dbufs, db);
929 		ASSERT(db->db_blkid != DMU_BONUS_BLKID);
930 
931 		if (db->db_level != 0 || db->db_blkid > end_blkid) {
932 			break;
933 		}
934 		ASSERT3U(db->db_blkid, >=, start_blkid);
935 
936 		/* found a level 0 buffer in the range */
937 		mutex_enter(&db->db_mtx);
938 		if (dbuf_undirty(db, tx)) {
939 			/* mutex has been dropped and dbuf destroyed */
940 			continue;
941 		}
942 
943 		if (db->db_state == DB_UNCACHED ||
944 		    db->db_state == DB_NOFILL ||
945 		    db->db_state == DB_EVICTING) {
946 			ASSERT(db->db.db_data == NULL);
947 			mutex_exit(&db->db_mtx);
948 			continue;
949 		}
950 		if (db->db_state == DB_READ || db->db_state == DB_FILL) {
951 			/* will be handled in dbuf_read_done or dbuf_rele */
952 			db->db_freed_in_flight = TRUE;
953 			mutex_exit(&db->db_mtx);
954 			continue;
955 		}
956 		if (refcount_count(&db->db_holds) == 0) {
957 			ASSERT(db->db_buf);
958 			dbuf_clear(db);
959 			continue;
960 		}
961 		/* The dbuf is referenced */
962 
963 		if (db->db_last_dirty != NULL) {
964 			dbuf_dirty_record_t *dr = db->db_last_dirty;
965 
966 			if (dr->dr_txg == txg) {
967 				/*
968 				 * This buffer is "in-use", re-adjust the file
969 				 * size to reflect that this buffer may
970 				 * contain new data when we sync.
971 				 */
972 				if (db->db_blkid != DMU_SPILL_BLKID &&
973 				    db->db_blkid > dn->dn_maxblkid)
974 					dn->dn_maxblkid = db->db_blkid;
975 				dbuf_unoverride(dr);
976 			} else {
977 				/*
978 				 * This dbuf is not dirty in the open context.
979 				 * Either uncache it (if its not referenced in
980 				 * the open context) or reset its contents to
981 				 * empty.
982 				 */
983 				dbuf_fix_old_data(db, txg);
984 			}
985 		}
986 		/* clear the contents if its cached */
987 		if (db->db_state == DB_CACHED) {
988 			ASSERT(db->db.db_data != NULL);
989 			arc_release(db->db_buf, db);
990 			bzero(db->db.db_data, db->db.db_size);
991 			arc_buf_freeze(db->db_buf);
992 		}
993 
994 		mutex_exit(&db->db_mtx);
995 	}
996 	mutex_exit(&dn->dn_dbufs_mtx);
997 }
998 
999 static int
1000 dbuf_block_freeable(dmu_buf_impl_t *db)
1001 {
1002 	dsl_dataset_t *ds = db->db_objset->os_dsl_dataset;
1003 	uint64_t birth_txg = 0;
1004 
1005 	/*
1006 	 * We don't need any locking to protect db_blkptr:
1007 	 * If it's syncing, then db_last_dirty will be set
1008 	 * so we'll ignore db_blkptr.
1009 	 *
1010 	 * This logic ensures that only block births for
1011 	 * filled blocks are considered.
1012 	 */
1013 	ASSERT(MUTEX_HELD(&db->db_mtx));
1014 	if (db->db_last_dirty && (db->db_blkptr == NULL ||
1015 	    !BP_IS_HOLE(db->db_blkptr))) {
1016 		birth_txg = db->db_last_dirty->dr_txg;
1017 	} else if (db->db_blkptr != NULL && !BP_IS_HOLE(db->db_blkptr)) {
1018 		birth_txg = db->db_blkptr->blk_birth;
1019 	}
1020 
1021 	/*
1022 	 * If this block don't exist or is in a snapshot, it can't be freed.
1023 	 * Don't pass the bp to dsl_dataset_block_freeable() since we
1024 	 * are holding the db_mtx lock and might deadlock if we are
1025 	 * prefetching a dedup-ed block.
1026 	 */
1027 	if (birth_txg != 0)
1028 		return (ds == NULL ||
1029 		    dsl_dataset_block_freeable(ds, NULL, birth_txg));
1030 	else
1031 		return (B_FALSE);
1032 }
1033 
1034 void
1035 dbuf_new_size(dmu_buf_impl_t *db, int size, dmu_tx_t *tx)
1036 {
1037 	arc_buf_t *buf, *obuf;
1038 	int osize = db->db.db_size;
1039 	arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1040 	dnode_t *dn;
1041 
1042 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1043 
1044 	DB_DNODE_ENTER(db);
1045 	dn = DB_DNODE(db);
1046 
1047 	/* XXX does *this* func really need the lock? */
1048 	ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
1049 
1050 	/*
1051 	 * This call to dmu_buf_will_dirty() with the dn_struct_rwlock held
1052 	 * is OK, because there can be no other references to the db
1053 	 * when we are changing its size, so no concurrent DB_FILL can
1054 	 * be happening.
1055 	 */
1056 	/*
1057 	 * XXX we should be doing a dbuf_read, checking the return
1058 	 * value and returning that up to our callers
1059 	 */
1060 	dmu_buf_will_dirty(&db->db, tx);
1061 
1062 	/* create the data buffer for the new block */
1063 	buf = arc_buf_alloc(dn->dn_objset->os_spa, size, db, type);
1064 
1065 	/* copy old block data to the new block */
1066 	obuf = db->db_buf;
1067 	bcopy(obuf->b_data, buf->b_data, MIN(osize, size));
1068 	/* zero the remainder */
1069 	if (size > osize)
1070 		bzero((uint8_t *)buf->b_data + osize, size - osize);
1071 
1072 	mutex_enter(&db->db_mtx);
1073 	dbuf_set_data(db, buf);
1074 	VERIFY(arc_buf_remove_ref(obuf, db));
1075 	db->db.db_size = size;
1076 
1077 	if (db->db_level == 0) {
1078 		ASSERT3U(db->db_last_dirty->dr_txg, ==, tx->tx_txg);
1079 		db->db_last_dirty->dt.dl.dr_data = buf;
1080 	}
1081 	mutex_exit(&db->db_mtx);
1082 
1083 	dnode_willuse_space(dn, size-osize, tx);
1084 	DB_DNODE_EXIT(db);
1085 }
1086 
1087 void
1088 dbuf_release_bp(dmu_buf_impl_t *db)
1089 {
1090 	objset_t *os = db->db_objset;
1091 
1092 	ASSERT(dsl_pool_sync_context(dmu_objset_pool(os)));
1093 	ASSERT(arc_released(os->os_phys_buf) ||
1094 	    list_link_active(&os->os_dsl_dataset->ds_synced_link));
1095 	ASSERT(db->db_parent == NULL || arc_released(db->db_parent->db_buf));
1096 
1097 	(void) arc_release(db->db_buf, db);
1098 }
1099 
1100 dbuf_dirty_record_t *
1101 dbuf_dirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
1102 {
1103 	dnode_t *dn;
1104 	objset_t *os;
1105 	dbuf_dirty_record_t **drp, *dr;
1106 	int drop_struct_lock = FALSE;
1107 	boolean_t do_free_accounting = B_FALSE;
1108 	int txgoff = tx->tx_txg & TXG_MASK;
1109 
1110 	ASSERT(tx->tx_txg != 0);
1111 	ASSERT(!refcount_is_zero(&db->db_holds));
1112 	DMU_TX_DIRTY_BUF(tx, db);
1113 
1114 	DB_DNODE_ENTER(db);
1115 	dn = DB_DNODE(db);
1116 	/*
1117 	 * Shouldn't dirty a regular buffer in syncing context.  Private
1118 	 * objects may be dirtied in syncing context, but only if they
1119 	 * were already pre-dirtied in open context.
1120 	 */
1121 	ASSERT(!dmu_tx_is_syncing(tx) ||
1122 	    BP_IS_HOLE(dn->dn_objset->os_rootbp) ||
1123 	    DMU_OBJECT_IS_SPECIAL(dn->dn_object) ||
1124 	    dn->dn_objset->os_dsl_dataset == NULL);
1125 	/*
1126 	 * We make this assert for private objects as well, but after we
1127 	 * check if we're already dirty.  They are allowed to re-dirty
1128 	 * in syncing context.
1129 	 */
1130 	ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
1131 	    dn->dn_dirtyctx == DN_UNDIRTIED || dn->dn_dirtyctx ==
1132 	    (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN));
1133 
1134 	mutex_enter(&db->db_mtx);
1135 	/*
1136 	 * XXX make this true for indirects too?  The problem is that
1137 	 * transactions created with dmu_tx_create_assigned() from
1138 	 * syncing context don't bother holding ahead.
1139 	 */
1140 	ASSERT(db->db_level != 0 ||
1141 	    db->db_state == DB_CACHED || db->db_state == DB_FILL ||
1142 	    db->db_state == DB_NOFILL);
1143 
1144 	mutex_enter(&dn->dn_mtx);
1145 	/*
1146 	 * Don't set dirtyctx to SYNC if we're just modifying this as we
1147 	 * initialize the objset.
1148 	 */
1149 	if (dn->dn_dirtyctx == DN_UNDIRTIED &&
1150 	    !BP_IS_HOLE(dn->dn_objset->os_rootbp)) {
1151 		dn->dn_dirtyctx =
1152 		    (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN);
1153 		ASSERT(dn->dn_dirtyctx_firstset == NULL);
1154 		dn->dn_dirtyctx_firstset = kmem_alloc(1, KM_SLEEP);
1155 	}
1156 	mutex_exit(&dn->dn_mtx);
1157 
1158 	if (db->db_blkid == DMU_SPILL_BLKID)
1159 		dn->dn_have_spill = B_TRUE;
1160 
1161 	/*
1162 	 * If this buffer is already dirty, we're done.
1163 	 */
1164 	drp = &db->db_last_dirty;
1165 	ASSERT(*drp == NULL || (*drp)->dr_txg <= tx->tx_txg ||
1166 	    db->db.db_object == DMU_META_DNODE_OBJECT);
1167 	while ((dr = *drp) != NULL && dr->dr_txg > tx->tx_txg)
1168 		drp = &dr->dr_next;
1169 	if (dr && dr->dr_txg == tx->tx_txg) {
1170 		DB_DNODE_EXIT(db);
1171 
1172 		if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID) {
1173 			/*
1174 			 * If this buffer has already been written out,
1175 			 * we now need to reset its state.
1176 			 */
1177 			dbuf_unoverride(dr);
1178 			if (db->db.db_object != DMU_META_DNODE_OBJECT &&
1179 			    db->db_state != DB_NOFILL)
1180 				arc_buf_thaw(db->db_buf);
1181 		}
1182 		mutex_exit(&db->db_mtx);
1183 		return (dr);
1184 	}
1185 
1186 	/*
1187 	 * Only valid if not already dirty.
1188 	 */
1189 	ASSERT(dn->dn_object == 0 ||
1190 	    dn->dn_dirtyctx == DN_UNDIRTIED || dn->dn_dirtyctx ==
1191 	    (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN));
1192 
1193 	ASSERT3U(dn->dn_nlevels, >, db->db_level);
1194 	ASSERT((dn->dn_phys->dn_nlevels == 0 && db->db_level == 0) ||
1195 	    dn->dn_phys->dn_nlevels > db->db_level ||
1196 	    dn->dn_next_nlevels[txgoff] > db->db_level ||
1197 	    dn->dn_next_nlevels[(tx->tx_txg-1) & TXG_MASK] > db->db_level ||
1198 	    dn->dn_next_nlevels[(tx->tx_txg-2) & TXG_MASK] > db->db_level);
1199 
1200 	/*
1201 	 * We should only be dirtying in syncing context if it's the
1202 	 * mos or we're initializing the os or it's a special object.
1203 	 * However, we are allowed to dirty in syncing context provided
1204 	 * we already dirtied it in open context.  Hence we must make
1205 	 * this assertion only if we're not already dirty.
1206 	 */
1207 	os = dn->dn_objset;
1208 	ASSERT(!dmu_tx_is_syncing(tx) || DMU_OBJECT_IS_SPECIAL(dn->dn_object) ||
1209 	    os->os_dsl_dataset == NULL || BP_IS_HOLE(os->os_rootbp));
1210 	ASSERT(db->db.db_size != 0);
1211 
1212 	dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
1213 
1214 	if (db->db_blkid != DMU_BONUS_BLKID) {
1215 		/*
1216 		 * Update the accounting.
1217 		 * Note: we delay "free accounting" until after we drop
1218 		 * the db_mtx.  This keeps us from grabbing other locks
1219 		 * (and possibly deadlocking) in bp_get_dsize() while
1220 		 * also holding the db_mtx.
1221 		 */
1222 		dnode_willuse_space(dn, db->db.db_size, tx);
1223 		do_free_accounting = dbuf_block_freeable(db);
1224 	}
1225 
1226 	/*
1227 	 * If this buffer is dirty in an old transaction group we need
1228 	 * to make a copy of it so that the changes we make in this
1229 	 * transaction group won't leak out when we sync the older txg.
1230 	 */
1231 	dr = kmem_zalloc(sizeof (dbuf_dirty_record_t), KM_SLEEP);
1232 	if (db->db_level == 0) {
1233 		void *data_old = db->db_buf;
1234 
1235 		if (db->db_state != DB_NOFILL) {
1236 			if (db->db_blkid == DMU_BONUS_BLKID) {
1237 				dbuf_fix_old_data(db, tx->tx_txg);
1238 				data_old = db->db.db_data;
1239 			} else if (db->db.db_object != DMU_META_DNODE_OBJECT) {
1240 				/*
1241 				 * Release the data buffer from the cache so
1242 				 * that we can modify it without impacting
1243 				 * possible other users of this cached data
1244 				 * block.  Note that indirect blocks and
1245 				 * private objects are not released until the
1246 				 * syncing state (since they are only modified
1247 				 * then).
1248 				 */
1249 				arc_release(db->db_buf, db);
1250 				dbuf_fix_old_data(db, tx->tx_txg);
1251 				data_old = db->db_buf;
1252 			}
1253 			ASSERT(data_old != NULL);
1254 		}
1255 		dr->dt.dl.dr_data = data_old;
1256 	} else {
1257 		mutex_init(&dr->dt.di.dr_mtx, NULL, MUTEX_DEFAULT, NULL);
1258 		list_create(&dr->dt.di.dr_children,
1259 		    sizeof (dbuf_dirty_record_t),
1260 		    offsetof(dbuf_dirty_record_t, dr_dirty_node));
1261 	}
1262 	if (db->db_blkid != DMU_BONUS_BLKID && os->os_dsl_dataset != NULL)
1263 		dr->dr_accounted = db->db.db_size;
1264 	dr->dr_dbuf = db;
1265 	dr->dr_txg = tx->tx_txg;
1266 	dr->dr_next = *drp;
1267 	*drp = dr;
1268 
1269 	/*
1270 	 * We could have been freed_in_flight between the dbuf_noread
1271 	 * and dbuf_dirty.  We win, as though the dbuf_noread() had
1272 	 * happened after the free.
1273 	 */
1274 	if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
1275 	    db->db_blkid != DMU_SPILL_BLKID) {
1276 		mutex_enter(&dn->dn_mtx);
1277 		if (dn->dn_free_ranges[txgoff] != NULL) {
1278 			range_tree_clear(dn->dn_free_ranges[txgoff],
1279 			    db->db_blkid, 1);
1280 		}
1281 		mutex_exit(&dn->dn_mtx);
1282 		db->db_freed_in_flight = FALSE;
1283 	}
1284 
1285 	/*
1286 	 * This buffer is now part of this txg
1287 	 */
1288 	dbuf_add_ref(db, (void *)(uintptr_t)tx->tx_txg);
1289 	db->db_dirtycnt += 1;
1290 	ASSERT3U(db->db_dirtycnt, <=, 3);
1291 
1292 	mutex_exit(&db->db_mtx);
1293 
1294 	if (db->db_blkid == DMU_BONUS_BLKID ||
1295 	    db->db_blkid == DMU_SPILL_BLKID) {
1296 		mutex_enter(&dn->dn_mtx);
1297 		ASSERT(!list_link_active(&dr->dr_dirty_node));
1298 		list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
1299 		mutex_exit(&dn->dn_mtx);
1300 		dnode_setdirty(dn, tx);
1301 		DB_DNODE_EXIT(db);
1302 		return (dr);
1303 	} else if (do_free_accounting) {
1304 		blkptr_t *bp = db->db_blkptr;
1305 		int64_t willfree = (bp && !BP_IS_HOLE(bp)) ?
1306 		    bp_get_dsize(os->os_spa, bp) : db->db.db_size;
1307 		/*
1308 		 * This is only a guess -- if the dbuf is dirty
1309 		 * in a previous txg, we don't know how much
1310 		 * space it will use on disk yet.  We should
1311 		 * really have the struct_rwlock to access
1312 		 * db_blkptr, but since this is just a guess,
1313 		 * it's OK if we get an odd answer.
1314 		 */
1315 		ddt_prefetch(os->os_spa, bp);
1316 		dnode_willuse_space(dn, -willfree, tx);
1317 	}
1318 
1319 	if (!RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
1320 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
1321 		drop_struct_lock = TRUE;
1322 	}
1323 
1324 	if (db->db_level == 0) {
1325 		dnode_new_blkid(dn, db->db_blkid, tx, drop_struct_lock);
1326 		ASSERT(dn->dn_maxblkid >= db->db_blkid);
1327 	}
1328 
1329 	if (db->db_level+1 < dn->dn_nlevels) {
1330 		dmu_buf_impl_t *parent = db->db_parent;
1331 		dbuf_dirty_record_t *di;
1332 		int parent_held = FALSE;
1333 
1334 		if (db->db_parent == NULL || db->db_parent == dn->dn_dbuf) {
1335 			int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
1336 
1337 			parent = dbuf_hold_level(dn, db->db_level+1,
1338 			    db->db_blkid >> epbs, FTAG);
1339 			ASSERT(parent != NULL);
1340 			parent_held = TRUE;
1341 		}
1342 		if (drop_struct_lock)
1343 			rw_exit(&dn->dn_struct_rwlock);
1344 		ASSERT3U(db->db_level+1, ==, parent->db_level);
1345 		di = dbuf_dirty(parent, tx);
1346 		if (parent_held)
1347 			dbuf_rele(parent, FTAG);
1348 
1349 		mutex_enter(&db->db_mtx);
1350 		/*
1351 		 * Since we've dropped the mutex, it's possible that
1352 		 * dbuf_undirty() might have changed this out from under us.
1353 		 */
1354 		if (db->db_last_dirty == dr ||
1355 		    dn->dn_object == DMU_META_DNODE_OBJECT) {
1356 			mutex_enter(&di->dt.di.dr_mtx);
1357 			ASSERT3U(di->dr_txg, ==, tx->tx_txg);
1358 			ASSERT(!list_link_active(&dr->dr_dirty_node));
1359 			list_insert_tail(&di->dt.di.dr_children, dr);
1360 			mutex_exit(&di->dt.di.dr_mtx);
1361 			dr->dr_parent = di;
1362 		}
1363 		mutex_exit(&db->db_mtx);
1364 	} else {
1365 		ASSERT(db->db_level+1 == dn->dn_nlevels);
1366 		ASSERT(db->db_blkid < dn->dn_nblkptr);
1367 		ASSERT(db->db_parent == NULL || db->db_parent == dn->dn_dbuf);
1368 		mutex_enter(&dn->dn_mtx);
1369 		ASSERT(!list_link_active(&dr->dr_dirty_node));
1370 		list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
1371 		mutex_exit(&dn->dn_mtx);
1372 		if (drop_struct_lock)
1373 			rw_exit(&dn->dn_struct_rwlock);
1374 	}
1375 
1376 	dnode_setdirty(dn, tx);
1377 	DB_DNODE_EXIT(db);
1378 	return (dr);
1379 }
1380 
1381 /*
1382  * Undirty a buffer in the transaction group referenced by the given
1383  * transaction.  Return whether this evicted the dbuf.
1384  */
1385 static boolean_t
1386 dbuf_undirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
1387 {
1388 	dnode_t *dn;
1389 	uint64_t txg = tx->tx_txg;
1390 	dbuf_dirty_record_t *dr, **drp;
1391 
1392 	ASSERT(txg != 0);
1393 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1394 	ASSERT0(db->db_level);
1395 	ASSERT(MUTEX_HELD(&db->db_mtx));
1396 
1397 	/*
1398 	 * If this buffer is not dirty, we're done.
1399 	 */
1400 	for (drp = &db->db_last_dirty; (dr = *drp) != NULL; drp = &dr->dr_next)
1401 		if (dr->dr_txg <= txg)
1402 			break;
1403 	if (dr == NULL || dr->dr_txg < txg)
1404 		return (B_FALSE);
1405 	ASSERT(dr->dr_txg == txg);
1406 	ASSERT(dr->dr_dbuf == db);
1407 
1408 	DB_DNODE_ENTER(db);
1409 	dn = DB_DNODE(db);
1410 
1411 	dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
1412 
1413 	ASSERT(db->db.db_size != 0);
1414 
1415 	/*
1416 	 * Any space we accounted for in dp_dirty_* will be cleaned up by
1417 	 * dsl_pool_sync().  This is relatively rare so the discrepancy
1418 	 * is not a big deal.
1419 	 */
1420 
1421 	*drp = dr->dr_next;
1422 
1423 	/*
1424 	 * Note that there are three places in dbuf_dirty()
1425 	 * where this dirty record may be put on a list.
1426 	 * Make sure to do a list_remove corresponding to
1427 	 * every one of those list_insert calls.
1428 	 */
1429 	if (dr->dr_parent) {
1430 		mutex_enter(&dr->dr_parent->dt.di.dr_mtx);
1431 		list_remove(&dr->dr_parent->dt.di.dr_children, dr);
1432 		mutex_exit(&dr->dr_parent->dt.di.dr_mtx);
1433 	} else if (db->db_blkid == DMU_SPILL_BLKID ||
1434 	    db->db_level+1 == dn->dn_nlevels) {
1435 		ASSERT(db->db_blkptr == NULL || db->db_parent == dn->dn_dbuf);
1436 		mutex_enter(&dn->dn_mtx);
1437 		list_remove(&dn->dn_dirty_records[txg & TXG_MASK], dr);
1438 		mutex_exit(&dn->dn_mtx);
1439 	}
1440 	DB_DNODE_EXIT(db);
1441 
1442 	if (db->db_state != DB_NOFILL) {
1443 		dbuf_unoverride(dr);
1444 
1445 		ASSERT(db->db_buf != NULL);
1446 		ASSERT(dr->dt.dl.dr_data != NULL);
1447 		if (dr->dt.dl.dr_data != db->db_buf)
1448 			VERIFY(arc_buf_remove_ref(dr->dt.dl.dr_data, db));
1449 	}
1450 
1451 	if (db->db_level != 0) {
1452 		mutex_destroy(&dr->dt.di.dr_mtx);
1453 		list_destroy(&dr->dt.di.dr_children);
1454 	}
1455 
1456 	kmem_free(dr, sizeof (dbuf_dirty_record_t));
1457 
1458 	ASSERT(db->db_dirtycnt > 0);
1459 	db->db_dirtycnt -= 1;
1460 
1461 	if (refcount_remove(&db->db_holds, (void *)(uintptr_t)txg) == 0) {
1462 		arc_buf_t *buf = db->db_buf;
1463 
1464 		ASSERT(db->db_state == DB_NOFILL || arc_released(buf));
1465 		dbuf_clear_data(db);
1466 		VERIFY(arc_buf_remove_ref(buf, db));
1467 		dbuf_evict(db);
1468 		return (B_TRUE);
1469 	}
1470 
1471 	return (B_FALSE);
1472 }
1473 
1474 void
1475 dmu_buf_will_dirty(dmu_buf_t *db_fake, dmu_tx_t *tx)
1476 {
1477 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1478 	int rf = DB_RF_MUST_SUCCEED | DB_RF_NOPREFETCH;
1479 
1480 	ASSERT(tx->tx_txg != 0);
1481 	ASSERT(!refcount_is_zero(&db->db_holds));
1482 
1483 	DB_DNODE_ENTER(db);
1484 	if (RW_WRITE_HELD(&DB_DNODE(db)->dn_struct_rwlock))
1485 		rf |= DB_RF_HAVESTRUCT;
1486 	DB_DNODE_EXIT(db);
1487 	(void) dbuf_read(db, NULL, rf);
1488 	(void) dbuf_dirty(db, tx);
1489 }
1490 
1491 void
1492 dmu_buf_will_not_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
1493 {
1494 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1495 
1496 	db->db_state = DB_NOFILL;
1497 
1498 	dmu_buf_will_fill(db_fake, tx);
1499 }
1500 
1501 void
1502 dmu_buf_will_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
1503 {
1504 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1505 
1506 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1507 	ASSERT(tx->tx_txg != 0);
1508 	ASSERT(db->db_level == 0);
1509 	ASSERT(!refcount_is_zero(&db->db_holds));
1510 
1511 	ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT ||
1512 	    dmu_tx_private_ok(tx));
1513 
1514 	dbuf_noread(db);
1515 	(void) dbuf_dirty(db, tx);
1516 }
1517 
1518 #pragma weak dmu_buf_fill_done = dbuf_fill_done
1519 /* ARGSUSED */
1520 void
1521 dbuf_fill_done(dmu_buf_impl_t *db, dmu_tx_t *tx)
1522 {
1523 	mutex_enter(&db->db_mtx);
1524 	DBUF_VERIFY(db);
1525 
1526 	if (db->db_state == DB_FILL) {
1527 		if (db->db_level == 0 && db->db_freed_in_flight) {
1528 			ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1529 			/* we were freed while filling */
1530 			/* XXX dbuf_undirty? */
1531 			bzero(db->db.db_data, db->db.db_size);
1532 			db->db_freed_in_flight = FALSE;
1533 		}
1534 		db->db_state = DB_CACHED;
1535 		cv_broadcast(&db->db_changed);
1536 	}
1537 	mutex_exit(&db->db_mtx);
1538 }
1539 
1540 void
1541 dmu_buf_write_embedded(dmu_buf_t *dbuf, void *data,
1542     bp_embedded_type_t etype, enum zio_compress comp,
1543     int uncompressed_size, int compressed_size, int byteorder,
1544     dmu_tx_t *tx)
1545 {
1546 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbuf;
1547 	struct dirty_leaf *dl;
1548 	dmu_object_type_t type;
1549 
1550 	DB_DNODE_ENTER(db);
1551 	type = DB_DNODE(db)->dn_type;
1552 	DB_DNODE_EXIT(db);
1553 
1554 	ASSERT0(db->db_level);
1555 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1556 
1557 	dmu_buf_will_not_fill(dbuf, tx);
1558 
1559 	ASSERT3U(db->db_last_dirty->dr_txg, ==, tx->tx_txg);
1560 	dl = &db->db_last_dirty->dt.dl;
1561 	encode_embedded_bp_compressed(&dl->dr_overridden_by,
1562 	    data, comp, uncompressed_size, compressed_size);
1563 	BPE_SET_ETYPE(&dl->dr_overridden_by, etype);
1564 	BP_SET_TYPE(&dl->dr_overridden_by, type);
1565 	BP_SET_LEVEL(&dl->dr_overridden_by, 0);
1566 	BP_SET_BYTEORDER(&dl->dr_overridden_by, byteorder);
1567 
1568 	dl->dr_override_state = DR_OVERRIDDEN;
1569 	dl->dr_overridden_by.blk_birth = db->db_last_dirty->dr_txg;
1570 }
1571 
1572 /*
1573  * Directly assign a provided arc buf to a given dbuf if it's not referenced
1574  * by anybody except our caller. Otherwise copy arcbuf's contents to dbuf.
1575  */
1576 void
1577 dbuf_assign_arcbuf(dmu_buf_impl_t *db, arc_buf_t *buf, dmu_tx_t *tx)
1578 {
1579 	ASSERT(!refcount_is_zero(&db->db_holds));
1580 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1581 	ASSERT(db->db_level == 0);
1582 	ASSERT(DBUF_GET_BUFC_TYPE(db) == ARC_BUFC_DATA);
1583 	ASSERT(buf != NULL);
1584 	ASSERT(arc_buf_size(buf) == db->db.db_size);
1585 	ASSERT(tx->tx_txg != 0);
1586 
1587 	arc_return_buf(buf, db);
1588 	ASSERT(arc_released(buf));
1589 
1590 	mutex_enter(&db->db_mtx);
1591 
1592 	while (db->db_state == DB_READ || db->db_state == DB_FILL)
1593 		cv_wait(&db->db_changed, &db->db_mtx);
1594 
1595 	ASSERT(db->db_state == DB_CACHED || db->db_state == DB_UNCACHED);
1596 
1597 	if (db->db_state == DB_CACHED &&
1598 	    refcount_count(&db->db_holds) - 1 > db->db_dirtycnt) {
1599 		mutex_exit(&db->db_mtx);
1600 		(void) dbuf_dirty(db, tx);
1601 		bcopy(buf->b_data, db->db.db_data, db->db.db_size);
1602 		VERIFY(arc_buf_remove_ref(buf, db));
1603 		xuio_stat_wbuf_copied();
1604 		return;
1605 	}
1606 
1607 	xuio_stat_wbuf_nocopy();
1608 	if (db->db_state == DB_CACHED) {
1609 		dbuf_dirty_record_t *dr = db->db_last_dirty;
1610 
1611 		ASSERT(db->db_buf != NULL);
1612 		if (dr != NULL && dr->dr_txg == tx->tx_txg) {
1613 			ASSERT(dr->dt.dl.dr_data == db->db_buf);
1614 			if (!arc_released(db->db_buf)) {
1615 				ASSERT(dr->dt.dl.dr_override_state ==
1616 				    DR_OVERRIDDEN);
1617 				arc_release(db->db_buf, db);
1618 			}
1619 			dr->dt.dl.dr_data = buf;
1620 			VERIFY(arc_buf_remove_ref(db->db_buf, db));
1621 		} else if (dr == NULL || dr->dt.dl.dr_data != db->db_buf) {
1622 			arc_release(db->db_buf, db);
1623 			VERIFY(arc_buf_remove_ref(db->db_buf, db));
1624 		}
1625 		db->db_buf = NULL;
1626 	}
1627 	ASSERT(db->db_buf == NULL);
1628 	dbuf_set_data(db, buf);
1629 	db->db_state = DB_FILL;
1630 	mutex_exit(&db->db_mtx);
1631 	(void) dbuf_dirty(db, tx);
1632 	dmu_buf_fill_done(&db->db, tx);
1633 }
1634 
1635 /*
1636  * "Clear" the contents of this dbuf.  This will mark the dbuf
1637  * EVICTING and clear *most* of its references.  Unfortunately,
1638  * when we are not holding the dn_dbufs_mtx, we can't clear the
1639  * entry in the dn_dbufs list.  We have to wait until dbuf_destroy()
1640  * in this case.  For callers from the DMU we will usually see:
1641  *	dbuf_clear()->arc_clear_callback()->dbuf_do_evict()->dbuf_destroy()
1642  * For the arc callback, we will usually see:
1643  *	dbuf_do_evict()->dbuf_clear();dbuf_destroy()
1644  * Sometimes, though, we will get a mix of these two:
1645  *	DMU: dbuf_clear()->arc_clear_callback()
1646  *	ARC: dbuf_do_evict()->dbuf_destroy()
1647  *
1648  * This routine will dissociate the dbuf from the arc, by calling
1649  * arc_clear_callback(), but will not evict the data from the ARC.
1650  */
1651 void
1652 dbuf_clear(dmu_buf_impl_t *db)
1653 {
1654 	dnode_t *dn;
1655 	dmu_buf_impl_t *parent = db->db_parent;
1656 	dmu_buf_impl_t *dndb;
1657 	boolean_t dbuf_gone = B_FALSE;
1658 
1659 	ASSERT(MUTEX_HELD(&db->db_mtx));
1660 	ASSERT(refcount_is_zero(&db->db_holds));
1661 
1662 	dbuf_evict_user(db);
1663 
1664 	if (db->db_state == DB_CACHED) {
1665 		ASSERT(db->db.db_data != NULL);
1666 		if (db->db_blkid == DMU_BONUS_BLKID) {
1667 			zio_buf_free(db->db.db_data, DN_MAX_BONUSLEN);
1668 			arc_space_return(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
1669 		}
1670 		db->db.db_data = NULL;
1671 		db->db_state = DB_UNCACHED;
1672 	}
1673 
1674 	ASSERT(db->db_state == DB_UNCACHED || db->db_state == DB_NOFILL);
1675 	ASSERT(db->db_data_pending == NULL);
1676 
1677 	db->db_state = DB_EVICTING;
1678 	db->db_blkptr = NULL;
1679 
1680 	DB_DNODE_ENTER(db);
1681 	dn = DB_DNODE(db);
1682 	dndb = dn->dn_dbuf;
1683 	if (db->db_blkid != DMU_BONUS_BLKID && MUTEX_HELD(&dn->dn_dbufs_mtx)) {
1684 		avl_remove(&dn->dn_dbufs, db);
1685 		atomic_dec_32(&dn->dn_dbufs_count);
1686 		membar_producer();
1687 		DB_DNODE_EXIT(db);
1688 		/*
1689 		 * Decrementing the dbuf count means that the hold corresponding
1690 		 * to the removed dbuf is no longer discounted in dnode_move(),
1691 		 * so the dnode cannot be moved until after we release the hold.
1692 		 * The membar_producer() ensures visibility of the decremented
1693 		 * value in dnode_move(), since DB_DNODE_EXIT doesn't actually
1694 		 * release any lock.
1695 		 */
1696 		dnode_rele(dn, db);
1697 		db->db_dnode_handle = NULL;
1698 	} else {
1699 		DB_DNODE_EXIT(db);
1700 	}
1701 
1702 	if (db->db_buf)
1703 		dbuf_gone = arc_clear_callback(db->db_buf);
1704 
1705 	if (!dbuf_gone)
1706 		mutex_exit(&db->db_mtx);
1707 
1708 	/*
1709 	 * If this dbuf is referenced from an indirect dbuf,
1710 	 * decrement the ref count on the indirect dbuf.
1711 	 */
1712 	if (parent && parent != dndb)
1713 		dbuf_rele(parent, db);
1714 }
1715 
1716 static int
1717 dbuf_findbp(dnode_t *dn, int level, uint64_t blkid, int fail_sparse,
1718     dmu_buf_impl_t **parentp, blkptr_t **bpp)
1719 {
1720 	int nlevels, epbs;
1721 
1722 	*parentp = NULL;
1723 	*bpp = NULL;
1724 
1725 	ASSERT(blkid != DMU_BONUS_BLKID);
1726 
1727 	if (blkid == DMU_SPILL_BLKID) {
1728 		mutex_enter(&dn->dn_mtx);
1729 		if (dn->dn_have_spill &&
1730 		    (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR))
1731 			*bpp = &dn->dn_phys->dn_spill;
1732 		else
1733 			*bpp = NULL;
1734 		dbuf_add_ref(dn->dn_dbuf, NULL);
1735 		*parentp = dn->dn_dbuf;
1736 		mutex_exit(&dn->dn_mtx);
1737 		return (0);
1738 	}
1739 
1740 	if (dn->dn_phys->dn_nlevels == 0)
1741 		nlevels = 1;
1742 	else
1743 		nlevels = dn->dn_phys->dn_nlevels;
1744 
1745 	epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
1746 
1747 	ASSERT3U(level * epbs, <, 64);
1748 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
1749 	if (level >= nlevels ||
1750 	    (blkid > (dn->dn_phys->dn_maxblkid >> (level * epbs)))) {
1751 		/* the buffer has no parent yet */
1752 		return (SET_ERROR(ENOENT));
1753 	} else if (level < nlevels-1) {
1754 		/* this block is referenced from an indirect block */
1755 		int err = dbuf_hold_impl(dn, level+1,
1756 		    blkid >> epbs, fail_sparse, NULL, parentp);
1757 		if (err)
1758 			return (err);
1759 		err = dbuf_read(*parentp, NULL,
1760 		    (DB_RF_HAVESTRUCT | DB_RF_NOPREFETCH | DB_RF_CANFAIL));
1761 		if (err) {
1762 			dbuf_rele(*parentp, NULL);
1763 			*parentp = NULL;
1764 			return (err);
1765 		}
1766 		*bpp = ((blkptr_t *)(*parentp)->db.db_data) +
1767 		    (blkid & ((1ULL << epbs) - 1));
1768 		return (0);
1769 	} else {
1770 		/* the block is referenced from the dnode */
1771 		ASSERT3U(level, ==, nlevels-1);
1772 		ASSERT(dn->dn_phys->dn_nblkptr == 0 ||
1773 		    blkid < dn->dn_phys->dn_nblkptr);
1774 		if (dn->dn_dbuf) {
1775 			dbuf_add_ref(dn->dn_dbuf, NULL);
1776 			*parentp = dn->dn_dbuf;
1777 		}
1778 		*bpp = &dn->dn_phys->dn_blkptr[blkid];
1779 		return (0);
1780 	}
1781 }
1782 
1783 static dmu_buf_impl_t *
1784 dbuf_create(dnode_t *dn, uint8_t level, uint64_t blkid,
1785     dmu_buf_impl_t *parent, blkptr_t *blkptr)
1786 {
1787 	objset_t *os = dn->dn_objset;
1788 	dmu_buf_impl_t *db, *odb;
1789 
1790 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
1791 	ASSERT(dn->dn_type != DMU_OT_NONE);
1792 
1793 	db = kmem_cache_alloc(dbuf_cache, KM_SLEEP);
1794 
1795 	db->db_objset = os;
1796 	db->db.db_object = dn->dn_object;
1797 	db->db_level = level;
1798 	db->db_blkid = blkid;
1799 	db->db_last_dirty = NULL;
1800 	db->db_dirtycnt = 0;
1801 	db->db_dnode_handle = dn->dn_handle;
1802 	db->db_parent = parent;
1803 	db->db_blkptr = blkptr;
1804 
1805 	db->db_user = NULL;
1806 	db->db_immediate_evict = 0;
1807 	db->db_freed_in_flight = 0;
1808 
1809 	if (blkid == DMU_BONUS_BLKID) {
1810 		ASSERT3P(parent, ==, dn->dn_dbuf);
1811 		db->db.db_size = DN_MAX_BONUSLEN -
1812 		    (dn->dn_nblkptr-1) * sizeof (blkptr_t);
1813 		ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
1814 		db->db.db_offset = DMU_BONUS_BLKID;
1815 		db->db_state = DB_UNCACHED;
1816 		/* the bonus dbuf is not placed in the hash table */
1817 		arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
1818 		return (db);
1819 	} else if (blkid == DMU_SPILL_BLKID) {
1820 		db->db.db_size = (blkptr != NULL) ?
1821 		    BP_GET_LSIZE(blkptr) : SPA_MINBLOCKSIZE;
1822 		db->db.db_offset = 0;
1823 	} else {
1824 		int blocksize =
1825 		    db->db_level ? 1 << dn->dn_indblkshift : dn->dn_datablksz;
1826 		db->db.db_size = blocksize;
1827 		db->db.db_offset = db->db_blkid * blocksize;
1828 	}
1829 
1830 	/*
1831 	 * Hold the dn_dbufs_mtx while we get the new dbuf
1832 	 * in the hash table *and* added to the dbufs list.
1833 	 * This prevents a possible deadlock with someone
1834 	 * trying to look up this dbuf before its added to the
1835 	 * dn_dbufs list.
1836 	 */
1837 	mutex_enter(&dn->dn_dbufs_mtx);
1838 	db->db_state = DB_EVICTING;
1839 	if ((odb = dbuf_hash_insert(db)) != NULL) {
1840 		/* someone else inserted it first */
1841 		kmem_cache_free(dbuf_cache, db);
1842 		mutex_exit(&dn->dn_dbufs_mtx);
1843 		return (odb);
1844 	}
1845 	avl_add(&dn->dn_dbufs, db);
1846 	if (db->db_level == 0 && db->db_blkid >=
1847 	    dn->dn_unlisted_l0_blkid)
1848 		dn->dn_unlisted_l0_blkid = db->db_blkid + 1;
1849 	db->db_state = DB_UNCACHED;
1850 	mutex_exit(&dn->dn_dbufs_mtx);
1851 	arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
1852 
1853 	if (parent && parent != dn->dn_dbuf)
1854 		dbuf_add_ref(parent, db);
1855 
1856 	ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
1857 	    refcount_count(&dn->dn_holds) > 0);
1858 	(void) refcount_add(&dn->dn_holds, db);
1859 	atomic_inc_32(&dn->dn_dbufs_count);
1860 
1861 	dprintf_dbuf(db, "db=%p\n", db);
1862 
1863 	return (db);
1864 }
1865 
1866 static int
1867 dbuf_do_evict(void *private)
1868 {
1869 	dmu_buf_impl_t *db = private;
1870 
1871 	if (!MUTEX_HELD(&db->db_mtx))
1872 		mutex_enter(&db->db_mtx);
1873 
1874 	ASSERT(refcount_is_zero(&db->db_holds));
1875 
1876 	if (db->db_state != DB_EVICTING) {
1877 		ASSERT(db->db_state == DB_CACHED);
1878 		DBUF_VERIFY(db);
1879 		db->db_buf = NULL;
1880 		dbuf_evict(db);
1881 	} else {
1882 		mutex_exit(&db->db_mtx);
1883 		dbuf_destroy(db);
1884 	}
1885 	return (0);
1886 }
1887 
1888 static void
1889 dbuf_destroy(dmu_buf_impl_t *db)
1890 {
1891 	ASSERT(refcount_is_zero(&db->db_holds));
1892 
1893 	if (db->db_blkid != DMU_BONUS_BLKID) {
1894 		/*
1895 		 * If this dbuf is still on the dn_dbufs list,
1896 		 * remove it from that list.
1897 		 */
1898 		if (db->db_dnode_handle != NULL) {
1899 			dnode_t *dn;
1900 
1901 			DB_DNODE_ENTER(db);
1902 			dn = DB_DNODE(db);
1903 			mutex_enter(&dn->dn_dbufs_mtx);
1904 			avl_remove(&dn->dn_dbufs, db);
1905 			atomic_dec_32(&dn->dn_dbufs_count);
1906 			mutex_exit(&dn->dn_dbufs_mtx);
1907 			DB_DNODE_EXIT(db);
1908 			/*
1909 			 * Decrementing the dbuf count means that the hold
1910 			 * corresponding to the removed dbuf is no longer
1911 			 * discounted in dnode_move(), so the dnode cannot be
1912 			 * moved until after we release the hold.
1913 			 */
1914 			dnode_rele(dn, db);
1915 			db->db_dnode_handle = NULL;
1916 		}
1917 		dbuf_hash_remove(db);
1918 	}
1919 	db->db_parent = NULL;
1920 	db->db_buf = NULL;
1921 
1922 	ASSERT(db->db.db_data == NULL);
1923 	ASSERT(db->db_hash_next == NULL);
1924 	ASSERT(db->db_blkptr == NULL);
1925 	ASSERT(db->db_data_pending == NULL);
1926 
1927 	kmem_cache_free(dbuf_cache, db);
1928 	arc_space_return(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
1929 }
1930 
1931 void
1932 dbuf_prefetch(dnode_t *dn, uint64_t blkid, zio_priority_t prio)
1933 {
1934 	dmu_buf_impl_t *db = NULL;
1935 	blkptr_t *bp = NULL;
1936 
1937 	ASSERT(blkid != DMU_BONUS_BLKID);
1938 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
1939 
1940 	if (dnode_block_freed(dn, blkid))
1941 		return;
1942 
1943 	/* dbuf_find() returns with db_mtx held */
1944 	if (db = dbuf_find(dn->dn_objset, dn->dn_object, 0, blkid)) {
1945 		/*
1946 		 * This dbuf is already in the cache.  We assume that
1947 		 * it is already CACHED, or else about to be either
1948 		 * read or filled.
1949 		 */
1950 		mutex_exit(&db->db_mtx);
1951 		return;
1952 	}
1953 
1954 	if (dbuf_findbp(dn, 0, blkid, TRUE, &db, &bp) == 0) {
1955 		if (bp && !BP_IS_HOLE(bp) && !BP_IS_EMBEDDED(bp)) {
1956 			dsl_dataset_t *ds = dn->dn_objset->os_dsl_dataset;
1957 			arc_flags_t aflags =
1958 			    ARC_FLAG_NOWAIT | ARC_FLAG_PREFETCH;
1959 			zbookmark_phys_t zb;
1960 
1961 			SET_BOOKMARK(&zb, ds ? ds->ds_object : DMU_META_OBJSET,
1962 			    dn->dn_object, 0, blkid);
1963 
1964 			(void) arc_read(NULL, dn->dn_objset->os_spa,
1965 			    bp, NULL, NULL, prio,
1966 			    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
1967 			    &aflags, &zb);
1968 		}
1969 		if (db)
1970 			dbuf_rele(db, NULL);
1971 	}
1972 }
1973 
1974 /*
1975  * Returns with db_holds incremented, and db_mtx not held.
1976  * Note: dn_struct_rwlock must be held.
1977  */
1978 int
1979 dbuf_hold_impl(dnode_t *dn, uint8_t level, uint64_t blkid, int fail_sparse,
1980     void *tag, dmu_buf_impl_t **dbp)
1981 {
1982 	dmu_buf_impl_t *db, *parent = NULL;
1983 
1984 	ASSERT(blkid != DMU_BONUS_BLKID);
1985 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
1986 	ASSERT3U(dn->dn_nlevels, >, level);
1987 
1988 	*dbp = NULL;
1989 top:
1990 	/* dbuf_find() returns with db_mtx held */
1991 	db = dbuf_find(dn->dn_objset, dn->dn_object, level, blkid);
1992 
1993 	if (db == NULL) {
1994 		blkptr_t *bp = NULL;
1995 		int err;
1996 
1997 		ASSERT3P(parent, ==, NULL);
1998 		err = dbuf_findbp(dn, level, blkid, fail_sparse, &parent, &bp);
1999 		if (fail_sparse) {
2000 			if (err == 0 && bp && BP_IS_HOLE(bp))
2001 				err = SET_ERROR(ENOENT);
2002 			if (err) {
2003 				if (parent)
2004 					dbuf_rele(parent, NULL);
2005 				return (err);
2006 			}
2007 		}
2008 		if (err && err != ENOENT)
2009 			return (err);
2010 		db = dbuf_create(dn, level, blkid, parent, bp);
2011 	}
2012 
2013 	if (db->db_buf && refcount_is_zero(&db->db_holds)) {
2014 		arc_buf_add_ref(db->db_buf, db);
2015 		if (db->db_buf->b_data == NULL) {
2016 			dbuf_clear(db);
2017 			if (parent) {
2018 				dbuf_rele(parent, NULL);
2019 				parent = NULL;
2020 			}
2021 			goto top;
2022 		}
2023 		ASSERT3P(db->db.db_data, ==, db->db_buf->b_data);
2024 	}
2025 
2026 	ASSERT(db->db_buf == NULL || arc_referenced(db->db_buf));
2027 
2028 	/*
2029 	 * If this buffer is currently syncing out, and we are are
2030 	 * still referencing it from db_data, we need to make a copy
2031 	 * of it in case we decide we want to dirty it again in this txg.
2032 	 */
2033 	if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
2034 	    dn->dn_object != DMU_META_DNODE_OBJECT &&
2035 	    db->db_state == DB_CACHED && db->db_data_pending) {
2036 		dbuf_dirty_record_t *dr = db->db_data_pending;
2037 
2038 		if (dr->dt.dl.dr_data == db->db_buf) {
2039 			arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
2040 
2041 			dbuf_set_data(db,
2042 			    arc_buf_alloc(dn->dn_objset->os_spa,
2043 			    db->db.db_size, db, type));
2044 			bcopy(dr->dt.dl.dr_data->b_data, db->db.db_data,
2045 			    db->db.db_size);
2046 		}
2047 	}
2048 
2049 	(void) refcount_add(&db->db_holds, tag);
2050 	DBUF_VERIFY(db);
2051 	mutex_exit(&db->db_mtx);
2052 
2053 	/* NOTE: we can't rele the parent until after we drop the db_mtx */
2054 	if (parent)
2055 		dbuf_rele(parent, NULL);
2056 
2057 	ASSERT3P(DB_DNODE(db), ==, dn);
2058 	ASSERT3U(db->db_blkid, ==, blkid);
2059 	ASSERT3U(db->db_level, ==, level);
2060 	*dbp = db;
2061 
2062 	return (0);
2063 }
2064 
2065 dmu_buf_impl_t *
2066 dbuf_hold(dnode_t *dn, uint64_t blkid, void *tag)
2067 {
2068 	dmu_buf_impl_t *db;
2069 	int err = dbuf_hold_impl(dn, 0, blkid, FALSE, tag, &db);
2070 	return (err ? NULL : db);
2071 }
2072 
2073 dmu_buf_impl_t *
2074 dbuf_hold_level(dnode_t *dn, int level, uint64_t blkid, void *tag)
2075 {
2076 	dmu_buf_impl_t *db;
2077 	int err = dbuf_hold_impl(dn, level, blkid, FALSE, tag, &db);
2078 	return (err ? NULL : db);
2079 }
2080 
2081 void
2082 dbuf_create_bonus(dnode_t *dn)
2083 {
2084 	ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
2085 
2086 	ASSERT(dn->dn_bonus == NULL);
2087 	dn->dn_bonus = dbuf_create(dn, 0, DMU_BONUS_BLKID, dn->dn_dbuf, NULL);
2088 }
2089 
2090 int
2091 dbuf_spill_set_blksz(dmu_buf_t *db_fake, uint64_t blksz, dmu_tx_t *tx)
2092 {
2093 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2094 	dnode_t *dn;
2095 
2096 	if (db->db_blkid != DMU_SPILL_BLKID)
2097 		return (SET_ERROR(ENOTSUP));
2098 	if (blksz == 0)
2099 		blksz = SPA_MINBLOCKSIZE;
2100 	ASSERT3U(blksz, <=, spa_maxblocksize(dmu_objset_spa(db->db_objset)));
2101 	blksz = P2ROUNDUP(blksz, SPA_MINBLOCKSIZE);
2102 
2103 	DB_DNODE_ENTER(db);
2104 	dn = DB_DNODE(db);
2105 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
2106 	dbuf_new_size(db, blksz, tx);
2107 	rw_exit(&dn->dn_struct_rwlock);
2108 	DB_DNODE_EXIT(db);
2109 
2110 	return (0);
2111 }
2112 
2113 void
2114 dbuf_rm_spill(dnode_t *dn, dmu_tx_t *tx)
2115 {
2116 	dbuf_free_range(dn, DMU_SPILL_BLKID, DMU_SPILL_BLKID, tx);
2117 }
2118 
2119 #pragma weak dmu_buf_add_ref = dbuf_add_ref
2120 void
2121 dbuf_add_ref(dmu_buf_impl_t *db, void *tag)
2122 {
2123 	int64_t holds = refcount_add(&db->db_holds, tag);
2124 	ASSERT(holds > 1);
2125 }
2126 
2127 #pragma weak dmu_buf_try_add_ref = dbuf_try_add_ref
2128 boolean_t
2129 dbuf_try_add_ref(dmu_buf_t *db_fake, objset_t *os, uint64_t obj, uint64_t blkid,
2130     void *tag)
2131 {
2132 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2133 	dmu_buf_impl_t *found_db;
2134 	boolean_t result = B_FALSE;
2135 
2136 	if (db->db_blkid == DMU_BONUS_BLKID)
2137 		found_db = dbuf_find_bonus(os, obj);
2138 	else
2139 		found_db = dbuf_find(os, obj, 0, blkid);
2140 
2141 	if (found_db != NULL) {
2142 		if (db == found_db && dbuf_refcount(db) > db->db_dirtycnt) {
2143 			(void) refcount_add(&db->db_holds, tag);
2144 			result = B_TRUE;
2145 		}
2146 		mutex_exit(&db->db_mtx);
2147 	}
2148 	return (result);
2149 }
2150 
2151 /*
2152  * If you call dbuf_rele() you had better not be referencing the dnode handle
2153  * unless you have some other direct or indirect hold on the dnode. (An indirect
2154  * hold is a hold on one of the dnode's dbufs, including the bonus buffer.)
2155  * Without that, the dbuf_rele() could lead to a dnode_rele() followed by the
2156  * dnode's parent dbuf evicting its dnode handles.
2157  */
2158 void
2159 dbuf_rele(dmu_buf_impl_t *db, void *tag)
2160 {
2161 	mutex_enter(&db->db_mtx);
2162 	dbuf_rele_and_unlock(db, tag);
2163 }
2164 
2165 void
2166 dmu_buf_rele(dmu_buf_t *db, void *tag)
2167 {
2168 	dbuf_rele((dmu_buf_impl_t *)db, tag);
2169 }
2170 
2171 /*
2172  * dbuf_rele() for an already-locked dbuf.  This is necessary to allow
2173  * db_dirtycnt and db_holds to be updated atomically.
2174  */
2175 void
2176 dbuf_rele_and_unlock(dmu_buf_impl_t *db, void *tag)
2177 {
2178 	int64_t holds;
2179 
2180 	ASSERT(MUTEX_HELD(&db->db_mtx));
2181 	DBUF_VERIFY(db);
2182 
2183 	/*
2184 	 * Remove the reference to the dbuf before removing its hold on the
2185 	 * dnode so we can guarantee in dnode_move() that a referenced bonus
2186 	 * buffer has a corresponding dnode hold.
2187 	 */
2188 	holds = refcount_remove(&db->db_holds, tag);
2189 	ASSERT(holds >= 0);
2190 
2191 	/*
2192 	 * We can't freeze indirects if there is a possibility that they
2193 	 * may be modified in the current syncing context.
2194 	 */
2195 	if (db->db_buf && holds == (db->db_level == 0 ? db->db_dirtycnt : 0))
2196 		arc_buf_freeze(db->db_buf);
2197 
2198 	if (holds == db->db_dirtycnt &&
2199 	    db->db_level == 0 && db->db_immediate_evict)
2200 		dbuf_evict_user(db);
2201 
2202 	if (holds == 0) {
2203 		if (db->db_blkid == DMU_BONUS_BLKID) {
2204 			dnode_t *dn;
2205 
2206 			/*
2207 			 * If the dnode moves here, we cannot cross this
2208 			 * barrier until the move completes.
2209 			 */
2210 			DB_DNODE_ENTER(db);
2211 
2212 			dn = DB_DNODE(db);
2213 			atomic_dec_32(&dn->dn_dbufs_count);
2214 
2215 			/*
2216 			 * Decrementing the dbuf count means that the bonus
2217 			 * buffer's dnode hold is no longer discounted in
2218 			 * dnode_move(). The dnode cannot move until after
2219 			 * the dnode_rele_and_unlock() below.
2220 			 */
2221 			DB_DNODE_EXIT(db);
2222 
2223 			/*
2224 			 * Do not reference db after its lock is dropped.
2225 			 * Another thread may evict it.
2226 			 */
2227 			mutex_exit(&db->db_mtx);
2228 
2229 			/*
2230 			 * If the dnode has been freed, evict the bonus
2231 			 * buffer immediately.	The data in the bonus
2232 			 * buffer is no longer relevant and this prevents
2233 			 * a stale bonus buffer from being associated
2234 			 * with this dnode_t should the dnode_t be reused
2235 			 * prior to being destroyed.
2236 			 */
2237 			mutex_enter(&dn->dn_mtx);
2238 			if (dn->dn_type == DMU_OT_NONE ||
2239 			    dn->dn_free_txg != 0) {
2240 				/*
2241 				 * Drop dn_mtx.  It is a leaf lock and
2242 				 * cannot be held when dnode_evict_bonus()
2243 				 * acquires other locks in order to
2244 				 * perform the eviction.
2245 				 *
2246 				 * Freed dnodes cannot be reused until the
2247 				 * last hold is released.  Since this bonus
2248 				 * buffer has a hold, the dnode will remain
2249 				 * in the free state, even without dn_mtx
2250 				 * held, until the dnode_rele_and_unlock()
2251 				 * below.
2252 				 */
2253 				mutex_exit(&dn->dn_mtx);
2254 				dnode_evict_bonus(dn);
2255 				mutex_enter(&dn->dn_mtx);
2256 			}
2257 			dnode_rele_and_unlock(dn, db);
2258 		} else if (db->db_buf == NULL) {
2259 			/*
2260 			 * This is a special case: we never associated this
2261 			 * dbuf with any data allocated from the ARC.
2262 			 */
2263 			ASSERT(db->db_state == DB_UNCACHED ||
2264 			    db->db_state == DB_NOFILL);
2265 			dbuf_evict(db);
2266 		} else if (arc_released(db->db_buf)) {
2267 			arc_buf_t *buf = db->db_buf;
2268 			/*
2269 			 * This dbuf has anonymous data associated with it.
2270 			 */
2271 			dbuf_clear_data(db);
2272 			VERIFY(arc_buf_remove_ref(buf, db));
2273 			dbuf_evict(db);
2274 		} else {
2275 			VERIFY(!arc_buf_remove_ref(db->db_buf, db));
2276 
2277 			/*
2278 			 * A dbuf will be eligible for eviction if either the
2279 			 * 'primarycache' property is set or a duplicate
2280 			 * copy of this buffer is already cached in the arc.
2281 			 *
2282 			 * In the case of the 'primarycache' a buffer
2283 			 * is considered for eviction if it matches the
2284 			 * criteria set in the property.
2285 			 *
2286 			 * To decide if our buffer is considered a
2287 			 * duplicate, we must call into the arc to determine
2288 			 * if multiple buffers are referencing the same
2289 			 * block on-disk. If so, then we simply evict
2290 			 * ourselves.
2291 			 */
2292 			if (!DBUF_IS_CACHEABLE(db)) {
2293 				if (db->db_blkptr != NULL &&
2294 				    !BP_IS_HOLE(db->db_blkptr) &&
2295 				    !BP_IS_EMBEDDED(db->db_blkptr)) {
2296 					spa_t *spa =
2297 					    dmu_objset_spa(db->db_objset);
2298 					blkptr_t bp = *db->db_blkptr;
2299 					dbuf_clear(db);
2300 					arc_freed(spa, &bp);
2301 				} else {
2302 					dbuf_clear(db);
2303 				}
2304 			} else if (db->db_objset->os_evicting ||
2305 			    arc_buf_eviction_needed(db->db_buf)) {
2306 				dbuf_clear(db);
2307 			} else {
2308 				mutex_exit(&db->db_mtx);
2309 			}
2310 		}
2311 	} else {
2312 		mutex_exit(&db->db_mtx);
2313 	}
2314 }
2315 
2316 #pragma weak dmu_buf_refcount = dbuf_refcount
2317 uint64_t
2318 dbuf_refcount(dmu_buf_impl_t *db)
2319 {
2320 	return (refcount_count(&db->db_holds));
2321 }
2322 
2323 void *
2324 dmu_buf_replace_user(dmu_buf_t *db_fake, dmu_buf_user_t *old_user,
2325     dmu_buf_user_t *new_user)
2326 {
2327 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2328 
2329 	mutex_enter(&db->db_mtx);
2330 	dbuf_verify_user(db, DBVU_NOT_EVICTING);
2331 	if (db->db_user == old_user)
2332 		db->db_user = new_user;
2333 	else
2334 		old_user = db->db_user;
2335 	dbuf_verify_user(db, DBVU_NOT_EVICTING);
2336 	mutex_exit(&db->db_mtx);
2337 
2338 	return (old_user);
2339 }
2340 
2341 void *
2342 dmu_buf_set_user(dmu_buf_t *db_fake, dmu_buf_user_t *user)
2343 {
2344 	return (dmu_buf_replace_user(db_fake, NULL, user));
2345 }
2346 
2347 void *
2348 dmu_buf_set_user_ie(dmu_buf_t *db_fake, dmu_buf_user_t *user)
2349 {
2350 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2351 
2352 	db->db_immediate_evict = TRUE;
2353 	return (dmu_buf_set_user(db_fake, user));
2354 }
2355 
2356 void *
2357 dmu_buf_remove_user(dmu_buf_t *db_fake, dmu_buf_user_t *user)
2358 {
2359 	return (dmu_buf_replace_user(db_fake, user, NULL));
2360 }
2361 
2362 void *
2363 dmu_buf_get_user(dmu_buf_t *db_fake)
2364 {
2365 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2366 
2367 	dbuf_verify_user(db, DBVU_NOT_EVICTING);
2368 	return (db->db_user);
2369 }
2370 
2371 void
2372 dmu_buf_user_evict_wait()
2373 {
2374 	taskq_wait(dbu_evict_taskq);
2375 }
2376 
2377 boolean_t
2378 dmu_buf_freeable(dmu_buf_t *dbuf)
2379 {
2380 	boolean_t res = B_FALSE;
2381 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbuf;
2382 
2383 	if (db->db_blkptr)
2384 		res = dsl_dataset_block_freeable(db->db_objset->os_dsl_dataset,
2385 		    db->db_blkptr, db->db_blkptr->blk_birth);
2386 
2387 	return (res);
2388 }
2389 
2390 blkptr_t *
2391 dmu_buf_get_blkptr(dmu_buf_t *db)
2392 {
2393 	dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
2394 	return (dbi->db_blkptr);
2395 }
2396 
2397 static void
2398 dbuf_check_blkptr(dnode_t *dn, dmu_buf_impl_t *db)
2399 {
2400 	/* ASSERT(dmu_tx_is_syncing(tx) */
2401 	ASSERT(MUTEX_HELD(&db->db_mtx));
2402 
2403 	if (db->db_blkptr != NULL)
2404 		return;
2405 
2406 	if (db->db_blkid == DMU_SPILL_BLKID) {
2407 		db->db_blkptr = &dn->dn_phys->dn_spill;
2408 		BP_ZERO(db->db_blkptr);
2409 		return;
2410 	}
2411 	if (db->db_level == dn->dn_phys->dn_nlevels-1) {
2412 		/*
2413 		 * This buffer was allocated at a time when there was
2414 		 * no available blkptrs from the dnode, or it was
2415 		 * inappropriate to hook it in (i.e., nlevels mis-match).
2416 		 */
2417 		ASSERT(db->db_blkid < dn->dn_phys->dn_nblkptr);
2418 		ASSERT(db->db_parent == NULL);
2419 		db->db_parent = dn->dn_dbuf;
2420 		db->db_blkptr = &dn->dn_phys->dn_blkptr[db->db_blkid];
2421 		DBUF_VERIFY(db);
2422 	} else {
2423 		dmu_buf_impl_t *parent = db->db_parent;
2424 		int epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
2425 
2426 		ASSERT(dn->dn_phys->dn_nlevels > 1);
2427 		if (parent == NULL) {
2428 			mutex_exit(&db->db_mtx);
2429 			rw_enter(&dn->dn_struct_rwlock, RW_READER);
2430 			(void) dbuf_hold_impl(dn, db->db_level+1,
2431 			    db->db_blkid >> epbs, FALSE, db, &parent);
2432 			rw_exit(&dn->dn_struct_rwlock);
2433 			mutex_enter(&db->db_mtx);
2434 			db->db_parent = parent;
2435 		}
2436 		db->db_blkptr = (blkptr_t *)parent->db.db_data +
2437 		    (db->db_blkid & ((1ULL << epbs) - 1));
2438 		DBUF_VERIFY(db);
2439 	}
2440 }
2441 
2442 static void
2443 dbuf_sync_indirect(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
2444 {
2445 	dmu_buf_impl_t *db = dr->dr_dbuf;
2446 	dnode_t *dn;
2447 	zio_t *zio;
2448 
2449 	ASSERT(dmu_tx_is_syncing(tx));
2450 
2451 	dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
2452 
2453 	mutex_enter(&db->db_mtx);
2454 
2455 	ASSERT(db->db_level > 0);
2456 	DBUF_VERIFY(db);
2457 
2458 	/* Read the block if it hasn't been read yet. */
2459 	if (db->db_buf == NULL) {
2460 		mutex_exit(&db->db_mtx);
2461 		(void) dbuf_read(db, NULL, DB_RF_MUST_SUCCEED);
2462 		mutex_enter(&db->db_mtx);
2463 	}
2464 	ASSERT3U(db->db_state, ==, DB_CACHED);
2465 	ASSERT(db->db_buf != NULL);
2466 
2467 	DB_DNODE_ENTER(db);
2468 	dn = DB_DNODE(db);
2469 	/* Indirect block size must match what the dnode thinks it is. */
2470 	ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
2471 	dbuf_check_blkptr(dn, db);
2472 	DB_DNODE_EXIT(db);
2473 
2474 	/* Provide the pending dirty record to child dbufs */
2475 	db->db_data_pending = dr;
2476 
2477 	mutex_exit(&db->db_mtx);
2478 	dbuf_write(dr, db->db_buf, tx);
2479 
2480 	zio = dr->dr_zio;
2481 	mutex_enter(&dr->dt.di.dr_mtx);
2482 	dbuf_sync_list(&dr->dt.di.dr_children, tx);
2483 	ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
2484 	mutex_exit(&dr->dt.di.dr_mtx);
2485 	zio_nowait(zio);
2486 }
2487 
2488 static void
2489 dbuf_sync_leaf(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
2490 {
2491 	arc_buf_t **datap = &dr->dt.dl.dr_data;
2492 	dmu_buf_impl_t *db = dr->dr_dbuf;
2493 	dnode_t *dn;
2494 	objset_t *os;
2495 	uint64_t txg = tx->tx_txg;
2496 
2497 	ASSERT(dmu_tx_is_syncing(tx));
2498 
2499 	dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
2500 
2501 	mutex_enter(&db->db_mtx);
2502 	/*
2503 	 * To be synced, we must be dirtied.  But we
2504 	 * might have been freed after the dirty.
2505 	 */
2506 	if (db->db_state == DB_UNCACHED) {
2507 		/* This buffer has been freed since it was dirtied */
2508 		ASSERT(db->db.db_data == NULL);
2509 	} else if (db->db_state == DB_FILL) {
2510 		/* This buffer was freed and is now being re-filled */
2511 		ASSERT(db->db.db_data != dr->dt.dl.dr_data);
2512 	} else {
2513 		ASSERT(db->db_state == DB_CACHED || db->db_state == DB_NOFILL);
2514 	}
2515 	DBUF_VERIFY(db);
2516 
2517 	DB_DNODE_ENTER(db);
2518 	dn = DB_DNODE(db);
2519 
2520 	if (db->db_blkid == DMU_SPILL_BLKID) {
2521 		mutex_enter(&dn->dn_mtx);
2522 		dn->dn_phys->dn_flags |= DNODE_FLAG_SPILL_BLKPTR;
2523 		mutex_exit(&dn->dn_mtx);
2524 	}
2525 
2526 	/*
2527 	 * If this is a bonus buffer, simply copy the bonus data into the
2528 	 * dnode.  It will be written out when the dnode is synced (and it
2529 	 * will be synced, since it must have been dirty for dbuf_sync to
2530 	 * be called).
2531 	 */
2532 	if (db->db_blkid == DMU_BONUS_BLKID) {
2533 		dbuf_dirty_record_t **drp;
2534 
2535 		ASSERT(*datap != NULL);
2536 		ASSERT0(db->db_level);
2537 		ASSERT3U(dn->dn_phys->dn_bonuslen, <=, DN_MAX_BONUSLEN);
2538 		bcopy(*datap, DN_BONUS(dn->dn_phys), dn->dn_phys->dn_bonuslen);
2539 		DB_DNODE_EXIT(db);
2540 
2541 		if (*datap != db->db.db_data) {
2542 			zio_buf_free(*datap, DN_MAX_BONUSLEN);
2543 			arc_space_return(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
2544 		}
2545 		db->db_data_pending = NULL;
2546 		drp = &db->db_last_dirty;
2547 		while (*drp != dr)
2548 			drp = &(*drp)->dr_next;
2549 		ASSERT(dr->dr_next == NULL);
2550 		ASSERT(dr->dr_dbuf == db);
2551 		*drp = dr->dr_next;
2552 		kmem_free(dr, sizeof (dbuf_dirty_record_t));
2553 		ASSERT(db->db_dirtycnt > 0);
2554 		db->db_dirtycnt -= 1;
2555 		dbuf_rele_and_unlock(db, (void *)(uintptr_t)txg);
2556 		return;
2557 	}
2558 
2559 	os = dn->dn_objset;
2560 
2561 	/*
2562 	 * This function may have dropped the db_mtx lock allowing a dmu_sync
2563 	 * operation to sneak in. As a result, we need to ensure that we
2564 	 * don't check the dr_override_state until we have returned from
2565 	 * dbuf_check_blkptr.
2566 	 */
2567 	dbuf_check_blkptr(dn, db);
2568 
2569 	/*
2570 	 * If this buffer is in the middle of an immediate write,
2571 	 * wait for the synchronous IO to complete.
2572 	 */
2573 	while (dr->dt.dl.dr_override_state == DR_IN_DMU_SYNC) {
2574 		ASSERT(dn->dn_object != DMU_META_DNODE_OBJECT);
2575 		cv_wait(&db->db_changed, &db->db_mtx);
2576 		ASSERT(dr->dt.dl.dr_override_state != DR_NOT_OVERRIDDEN);
2577 	}
2578 
2579 	if (db->db_state != DB_NOFILL &&
2580 	    dn->dn_object != DMU_META_DNODE_OBJECT &&
2581 	    refcount_count(&db->db_holds) > 1 &&
2582 	    dr->dt.dl.dr_override_state != DR_OVERRIDDEN &&
2583 	    *datap == db->db_buf) {
2584 		/*
2585 		 * If this buffer is currently "in use" (i.e., there
2586 		 * are active holds and db_data still references it),
2587 		 * then make a copy before we start the write so that
2588 		 * any modifications from the open txg will not leak
2589 		 * into this write.
2590 		 *
2591 		 * NOTE: this copy does not need to be made for
2592 		 * objects only modified in the syncing context (e.g.
2593 		 * DNONE_DNODE blocks).
2594 		 */
2595 		int blksz = arc_buf_size(*datap);
2596 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
2597 		*datap = arc_buf_alloc(os->os_spa, blksz, db, type);
2598 		bcopy(db->db.db_data, (*datap)->b_data, blksz);
2599 	}
2600 	db->db_data_pending = dr;
2601 
2602 	mutex_exit(&db->db_mtx);
2603 
2604 	dbuf_write(dr, *datap, tx);
2605 
2606 	ASSERT(!list_link_active(&dr->dr_dirty_node));
2607 	if (dn->dn_object == DMU_META_DNODE_OBJECT) {
2608 		list_insert_tail(&dn->dn_dirty_records[txg&TXG_MASK], dr);
2609 		DB_DNODE_EXIT(db);
2610 	} else {
2611 		/*
2612 		 * Although zio_nowait() does not "wait for an IO", it does
2613 		 * initiate the IO. If this is an empty write it seems plausible
2614 		 * that the IO could actually be completed before the nowait
2615 		 * returns. We need to DB_DNODE_EXIT() first in case
2616 		 * zio_nowait() invalidates the dbuf.
2617 		 */
2618 		DB_DNODE_EXIT(db);
2619 		zio_nowait(dr->dr_zio);
2620 	}
2621 }
2622 
2623 void
2624 dbuf_sync_list(list_t *list, dmu_tx_t *tx)
2625 {
2626 	dbuf_dirty_record_t *dr;
2627 
2628 	while (dr = list_head(list)) {
2629 		if (dr->dr_zio != NULL) {
2630 			/*
2631 			 * If we find an already initialized zio then we
2632 			 * are processing the meta-dnode, and we have finished.
2633 			 * The dbufs for all dnodes are put back on the list
2634 			 * during processing, so that we can zio_wait()
2635 			 * these IOs after initiating all child IOs.
2636 			 */
2637 			ASSERT3U(dr->dr_dbuf->db.db_object, ==,
2638 			    DMU_META_DNODE_OBJECT);
2639 			break;
2640 		}
2641 		list_remove(list, dr);
2642 		if (dr->dr_dbuf->db_level > 0)
2643 			dbuf_sync_indirect(dr, tx);
2644 		else
2645 			dbuf_sync_leaf(dr, tx);
2646 	}
2647 }
2648 
2649 /* ARGSUSED */
2650 static void
2651 dbuf_write_ready(zio_t *zio, arc_buf_t *buf, void *vdb)
2652 {
2653 	dmu_buf_impl_t *db = vdb;
2654 	dnode_t *dn;
2655 	blkptr_t *bp = zio->io_bp;
2656 	blkptr_t *bp_orig = &zio->io_bp_orig;
2657 	spa_t *spa = zio->io_spa;
2658 	int64_t delta;
2659 	uint64_t fill = 0;
2660 	int i;
2661 
2662 	ASSERT3P(db->db_blkptr, ==, bp);
2663 
2664 	DB_DNODE_ENTER(db);
2665 	dn = DB_DNODE(db);
2666 	delta = bp_get_dsize_sync(spa, bp) - bp_get_dsize_sync(spa, bp_orig);
2667 	dnode_diduse_space(dn, delta - zio->io_prev_space_delta);
2668 	zio->io_prev_space_delta = delta;
2669 
2670 	if (bp->blk_birth != 0) {
2671 		ASSERT((db->db_blkid != DMU_SPILL_BLKID &&
2672 		    BP_GET_TYPE(bp) == dn->dn_type) ||
2673 		    (db->db_blkid == DMU_SPILL_BLKID &&
2674 		    BP_GET_TYPE(bp) == dn->dn_bonustype) ||
2675 		    BP_IS_EMBEDDED(bp));
2676 		ASSERT(BP_GET_LEVEL(bp) == db->db_level);
2677 	}
2678 
2679 	mutex_enter(&db->db_mtx);
2680 
2681 #ifdef ZFS_DEBUG
2682 	if (db->db_blkid == DMU_SPILL_BLKID) {
2683 		ASSERT(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR);
2684 		ASSERT(!(BP_IS_HOLE(db->db_blkptr)) &&
2685 		    db->db_blkptr == &dn->dn_phys->dn_spill);
2686 	}
2687 #endif
2688 
2689 	if (db->db_level == 0) {
2690 		mutex_enter(&dn->dn_mtx);
2691 		if (db->db_blkid > dn->dn_phys->dn_maxblkid &&
2692 		    db->db_blkid != DMU_SPILL_BLKID)
2693 			dn->dn_phys->dn_maxblkid = db->db_blkid;
2694 		mutex_exit(&dn->dn_mtx);
2695 
2696 		if (dn->dn_type == DMU_OT_DNODE) {
2697 			dnode_phys_t *dnp = db->db.db_data;
2698 			for (i = db->db.db_size >> DNODE_SHIFT; i > 0;
2699 			    i--, dnp++) {
2700 				if (dnp->dn_type != DMU_OT_NONE)
2701 					fill++;
2702 			}
2703 		} else {
2704 			if (BP_IS_HOLE(bp)) {
2705 				fill = 0;
2706 			} else {
2707 				fill = 1;
2708 			}
2709 		}
2710 	} else {
2711 		blkptr_t *ibp = db->db.db_data;
2712 		ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
2713 		for (i = db->db.db_size >> SPA_BLKPTRSHIFT; i > 0; i--, ibp++) {
2714 			if (BP_IS_HOLE(ibp))
2715 				continue;
2716 			fill += BP_GET_FILL(ibp);
2717 		}
2718 	}
2719 	DB_DNODE_EXIT(db);
2720 
2721 	if (!BP_IS_EMBEDDED(bp))
2722 		bp->blk_fill = fill;
2723 
2724 	mutex_exit(&db->db_mtx);
2725 }
2726 
2727 /*
2728  * The SPA will call this callback several times for each zio - once
2729  * for every physical child i/o (zio->io_phys_children times).  This
2730  * allows the DMU to monitor the progress of each logical i/o.  For example,
2731  * there may be 2 copies of an indirect block, or many fragments of a RAID-Z
2732  * block.  There may be a long delay before all copies/fragments are completed,
2733  * so this callback allows us to retire dirty space gradually, as the physical
2734  * i/os complete.
2735  */
2736 /* ARGSUSED */
2737 static void
2738 dbuf_write_physdone(zio_t *zio, arc_buf_t *buf, void *arg)
2739 {
2740 	dmu_buf_impl_t *db = arg;
2741 	objset_t *os = db->db_objset;
2742 	dsl_pool_t *dp = dmu_objset_pool(os);
2743 	dbuf_dirty_record_t *dr;
2744 	int delta = 0;
2745 
2746 	dr = db->db_data_pending;
2747 	ASSERT3U(dr->dr_txg, ==, zio->io_txg);
2748 
2749 	/*
2750 	 * The callback will be called io_phys_children times.  Retire one
2751 	 * portion of our dirty space each time we are called.  Any rounding
2752 	 * error will be cleaned up by dsl_pool_sync()'s call to
2753 	 * dsl_pool_undirty_space().
2754 	 */
2755 	delta = dr->dr_accounted / zio->io_phys_children;
2756 	dsl_pool_undirty_space(dp, delta, zio->io_txg);
2757 }
2758 
2759 /* ARGSUSED */
2760 static void
2761 dbuf_write_done(zio_t *zio, arc_buf_t *buf, void *vdb)
2762 {
2763 	dmu_buf_impl_t *db = vdb;
2764 	blkptr_t *bp_orig = &zio->io_bp_orig;
2765 	blkptr_t *bp = db->db_blkptr;
2766 	objset_t *os = db->db_objset;
2767 	dmu_tx_t *tx = os->os_synctx;
2768 	dbuf_dirty_record_t **drp, *dr;
2769 
2770 	ASSERT0(zio->io_error);
2771 	ASSERT(db->db_blkptr == bp);
2772 
2773 	/*
2774 	 * For nopwrites and rewrites we ensure that the bp matches our
2775 	 * original and bypass all the accounting.
2776 	 */
2777 	if (zio->io_flags & (ZIO_FLAG_IO_REWRITE | ZIO_FLAG_NOPWRITE)) {
2778 		ASSERT(BP_EQUAL(bp, bp_orig));
2779 	} else {
2780 		dsl_dataset_t *ds = os->os_dsl_dataset;
2781 		(void) dsl_dataset_block_kill(ds, bp_orig, tx, B_TRUE);
2782 		dsl_dataset_block_born(ds, bp, tx);
2783 	}
2784 
2785 	mutex_enter(&db->db_mtx);
2786 
2787 	DBUF_VERIFY(db);
2788 
2789 	drp = &db->db_last_dirty;
2790 	while ((dr = *drp) != db->db_data_pending)
2791 		drp = &dr->dr_next;
2792 	ASSERT(!list_link_active(&dr->dr_dirty_node));
2793 	ASSERT(dr->dr_dbuf == db);
2794 	ASSERT(dr->dr_next == NULL);
2795 	*drp = dr->dr_next;
2796 
2797 #ifdef ZFS_DEBUG
2798 	if (db->db_blkid == DMU_SPILL_BLKID) {
2799 		dnode_t *dn;
2800 
2801 		DB_DNODE_ENTER(db);
2802 		dn = DB_DNODE(db);
2803 		ASSERT(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR);
2804 		ASSERT(!(BP_IS_HOLE(db->db_blkptr)) &&
2805 		    db->db_blkptr == &dn->dn_phys->dn_spill);
2806 		DB_DNODE_EXIT(db);
2807 	}
2808 #endif
2809 
2810 	if (db->db_level == 0) {
2811 		ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2812 		ASSERT(dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN);
2813 		if (db->db_state != DB_NOFILL) {
2814 			if (dr->dt.dl.dr_data != db->db_buf)
2815 				VERIFY(arc_buf_remove_ref(dr->dt.dl.dr_data,
2816 				    db));
2817 			else if (!arc_released(db->db_buf))
2818 				arc_set_callback(db->db_buf, dbuf_do_evict, db);
2819 		}
2820 	} else {
2821 		dnode_t *dn;
2822 
2823 		DB_DNODE_ENTER(db);
2824 		dn = DB_DNODE(db);
2825 		ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
2826 		ASSERT3U(db->db.db_size, ==, 1 << dn->dn_phys->dn_indblkshift);
2827 		if (!BP_IS_HOLE(db->db_blkptr)) {
2828 			int epbs =
2829 			    dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
2830 			ASSERT3U(db->db_blkid, <=,
2831 			    dn->dn_phys->dn_maxblkid >> (db->db_level * epbs));
2832 			ASSERT3U(BP_GET_LSIZE(db->db_blkptr), ==,
2833 			    db->db.db_size);
2834 			if (!arc_released(db->db_buf))
2835 				arc_set_callback(db->db_buf, dbuf_do_evict, db);
2836 		}
2837 		DB_DNODE_EXIT(db);
2838 		mutex_destroy(&dr->dt.di.dr_mtx);
2839 		list_destroy(&dr->dt.di.dr_children);
2840 	}
2841 	kmem_free(dr, sizeof (dbuf_dirty_record_t));
2842 
2843 	cv_broadcast(&db->db_changed);
2844 	ASSERT(db->db_dirtycnt > 0);
2845 	db->db_dirtycnt -= 1;
2846 	db->db_data_pending = NULL;
2847 	dbuf_rele_and_unlock(db, (void *)(uintptr_t)tx->tx_txg);
2848 }
2849 
2850 static void
2851 dbuf_write_nofill_ready(zio_t *zio)
2852 {
2853 	dbuf_write_ready(zio, NULL, zio->io_private);
2854 }
2855 
2856 static void
2857 dbuf_write_nofill_done(zio_t *zio)
2858 {
2859 	dbuf_write_done(zio, NULL, zio->io_private);
2860 }
2861 
2862 static void
2863 dbuf_write_override_ready(zio_t *zio)
2864 {
2865 	dbuf_dirty_record_t *dr = zio->io_private;
2866 	dmu_buf_impl_t *db = dr->dr_dbuf;
2867 
2868 	dbuf_write_ready(zio, NULL, db);
2869 }
2870 
2871 static void
2872 dbuf_write_override_done(zio_t *zio)
2873 {
2874 	dbuf_dirty_record_t *dr = zio->io_private;
2875 	dmu_buf_impl_t *db = dr->dr_dbuf;
2876 	blkptr_t *obp = &dr->dt.dl.dr_overridden_by;
2877 
2878 	mutex_enter(&db->db_mtx);
2879 	if (!BP_EQUAL(zio->io_bp, obp)) {
2880 		if (!BP_IS_HOLE(obp))
2881 			dsl_free(spa_get_dsl(zio->io_spa), zio->io_txg, obp);
2882 		arc_release(dr->dt.dl.dr_data, db);
2883 	}
2884 	mutex_exit(&db->db_mtx);
2885 
2886 	dbuf_write_done(zio, NULL, db);
2887 }
2888 
2889 /* Issue I/O to commit a dirty buffer to disk. */
2890 static void
2891 dbuf_write(dbuf_dirty_record_t *dr, arc_buf_t *data, dmu_tx_t *tx)
2892 {
2893 	dmu_buf_impl_t *db = dr->dr_dbuf;
2894 	dnode_t *dn;
2895 	objset_t *os;
2896 	dmu_buf_impl_t *parent = db->db_parent;
2897 	uint64_t txg = tx->tx_txg;
2898 	zbookmark_phys_t zb;
2899 	zio_prop_t zp;
2900 	zio_t *zio;
2901 	int wp_flag = 0;
2902 
2903 	DB_DNODE_ENTER(db);
2904 	dn = DB_DNODE(db);
2905 	os = dn->dn_objset;
2906 
2907 	if (db->db_state != DB_NOFILL) {
2908 		if (db->db_level > 0 || dn->dn_type == DMU_OT_DNODE) {
2909 			/*
2910 			 * Private object buffers are released here rather
2911 			 * than in dbuf_dirty() since they are only modified
2912 			 * in the syncing context and we don't want the
2913 			 * overhead of making multiple copies of the data.
2914 			 */
2915 			if (BP_IS_HOLE(db->db_blkptr)) {
2916 				arc_buf_thaw(data);
2917 			} else {
2918 				dbuf_release_bp(db);
2919 			}
2920 		}
2921 	}
2922 
2923 	if (parent != dn->dn_dbuf) {
2924 		/* Our parent is an indirect block. */
2925 		/* We have a dirty parent that has been scheduled for write. */
2926 		ASSERT(parent && parent->db_data_pending);
2927 		/* Our parent's buffer is one level closer to the dnode. */
2928 		ASSERT(db->db_level == parent->db_level-1);
2929 		/*
2930 		 * We're about to modify our parent's db_data by modifying
2931 		 * our block pointer, so the parent must be released.
2932 		 */
2933 		ASSERT(arc_released(parent->db_buf));
2934 		zio = parent->db_data_pending->dr_zio;
2935 	} else {
2936 		/* Our parent is the dnode itself. */
2937 		ASSERT((db->db_level == dn->dn_phys->dn_nlevels-1 &&
2938 		    db->db_blkid != DMU_SPILL_BLKID) ||
2939 		    (db->db_blkid == DMU_SPILL_BLKID && db->db_level == 0));
2940 		if (db->db_blkid != DMU_SPILL_BLKID)
2941 			ASSERT3P(db->db_blkptr, ==,
2942 			    &dn->dn_phys->dn_blkptr[db->db_blkid]);
2943 		zio = dn->dn_zio;
2944 	}
2945 
2946 	ASSERT(db->db_level == 0 || data == db->db_buf);
2947 	ASSERT3U(db->db_blkptr->blk_birth, <=, txg);
2948 	ASSERT(zio);
2949 
2950 	SET_BOOKMARK(&zb, os->os_dsl_dataset ?
2951 	    os->os_dsl_dataset->ds_object : DMU_META_OBJSET,
2952 	    db->db.db_object, db->db_level, db->db_blkid);
2953 
2954 	if (db->db_blkid == DMU_SPILL_BLKID)
2955 		wp_flag = WP_SPILL;
2956 	wp_flag |= (db->db_state == DB_NOFILL) ? WP_NOFILL : 0;
2957 
2958 	dmu_write_policy(os, dn, db->db_level, wp_flag, &zp);
2959 	DB_DNODE_EXIT(db);
2960 
2961 	if (db->db_level == 0 &&
2962 	    dr->dt.dl.dr_override_state == DR_OVERRIDDEN) {
2963 		/*
2964 		 * The BP for this block has been provided by open context
2965 		 * (by dmu_sync() or dmu_buf_write_embedded()).
2966 		 */
2967 		void *contents = (data != NULL) ? data->b_data : NULL;
2968 
2969 		dr->dr_zio = zio_write(zio, os->os_spa, txg,
2970 		    db->db_blkptr, contents, db->db.db_size, &zp,
2971 		    dbuf_write_override_ready, NULL, dbuf_write_override_done,
2972 		    dr, ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
2973 		mutex_enter(&db->db_mtx);
2974 		dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
2975 		zio_write_override(dr->dr_zio, &dr->dt.dl.dr_overridden_by,
2976 		    dr->dt.dl.dr_copies, dr->dt.dl.dr_nopwrite);
2977 		mutex_exit(&db->db_mtx);
2978 	} else if (db->db_state == DB_NOFILL) {
2979 		ASSERT(zp.zp_checksum == ZIO_CHECKSUM_OFF ||
2980 		    zp.zp_checksum == ZIO_CHECKSUM_NOPARITY);
2981 		dr->dr_zio = zio_write(zio, os->os_spa, txg,
2982 		    db->db_blkptr, NULL, db->db.db_size, &zp,
2983 		    dbuf_write_nofill_ready, NULL, dbuf_write_nofill_done, db,
2984 		    ZIO_PRIORITY_ASYNC_WRITE,
2985 		    ZIO_FLAG_MUSTSUCCEED | ZIO_FLAG_NODATA, &zb);
2986 	} else {
2987 		ASSERT(arc_released(data));
2988 		dr->dr_zio = arc_write(zio, os->os_spa, txg,
2989 		    db->db_blkptr, data, DBUF_IS_L2CACHEABLE(db),
2990 		    DBUF_IS_L2COMPRESSIBLE(db), &zp, dbuf_write_ready,
2991 		    dbuf_write_physdone, dbuf_write_done, db,
2992 		    ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
2993 	}
2994 }
2995