xref: /titanic_41/usr/src/uts/common/fs/zfs/dbuf.c (revision 44da9c13b9429d13843a807d44fdc018aa9a407c)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright 2011 Nexenta Systems, Inc.  All rights reserved.
24  * Copyright (c) 2012, 2015 by Delphix. All rights reserved.
25  * Copyright (c) 2013 by Saso Kiselkov. All rights reserved.
26  * Copyright (c) 2013, Joyent, Inc. All rights reserved.
27  * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
28  */
29 
30 #include <sys/zfs_context.h>
31 #include <sys/dmu.h>
32 #include <sys/dmu_send.h>
33 #include <sys/dmu_impl.h>
34 #include <sys/dbuf.h>
35 #include <sys/dmu_objset.h>
36 #include <sys/dsl_dataset.h>
37 #include <sys/dsl_dir.h>
38 #include <sys/dmu_tx.h>
39 #include <sys/spa.h>
40 #include <sys/zio.h>
41 #include <sys/dmu_zfetch.h>
42 #include <sys/sa.h>
43 #include <sys/sa_impl.h>
44 #include <sys/zfeature.h>
45 #include <sys/blkptr.h>
46 #include <sys/range_tree.h>
47 
48 /*
49  * Number of times that zfs_free_range() took the slow path while doing
50  * a zfs receive.  A nonzero value indicates a potential performance problem.
51  */
52 uint64_t zfs_free_range_recv_miss;
53 
54 static void dbuf_destroy(dmu_buf_impl_t *db);
55 static boolean_t dbuf_undirty(dmu_buf_impl_t *db, dmu_tx_t *tx);
56 static void dbuf_write(dbuf_dirty_record_t *dr, arc_buf_t *data, dmu_tx_t *tx);
57 
58 #ifndef __lint
59 extern inline void dmu_buf_init_user(dmu_buf_user_t *dbu,
60     dmu_buf_evict_func_t *evict_func, dmu_buf_t **clear_on_evict_dbufp);
61 #endif /* ! __lint */
62 
63 /*
64  * Global data structures and functions for the dbuf cache.
65  */
66 static kmem_cache_t *dbuf_cache;
67 static taskq_t *dbu_evict_taskq;
68 
69 /* ARGSUSED */
70 static int
71 dbuf_cons(void *vdb, void *unused, int kmflag)
72 {
73 	dmu_buf_impl_t *db = vdb;
74 	bzero(db, sizeof (dmu_buf_impl_t));
75 
76 	mutex_init(&db->db_mtx, NULL, MUTEX_DEFAULT, NULL);
77 	cv_init(&db->db_changed, NULL, CV_DEFAULT, NULL);
78 	refcount_create(&db->db_holds);
79 
80 	return (0);
81 }
82 
83 /* ARGSUSED */
84 static void
85 dbuf_dest(void *vdb, void *unused)
86 {
87 	dmu_buf_impl_t *db = vdb;
88 	mutex_destroy(&db->db_mtx);
89 	cv_destroy(&db->db_changed);
90 	refcount_destroy(&db->db_holds);
91 }
92 
93 /*
94  * dbuf hash table routines
95  */
96 static dbuf_hash_table_t dbuf_hash_table;
97 
98 static uint64_t dbuf_hash_count;
99 
100 static uint64_t
101 dbuf_hash(void *os, uint64_t obj, uint8_t lvl, uint64_t blkid)
102 {
103 	uintptr_t osv = (uintptr_t)os;
104 	uint64_t crc = -1ULL;
105 
106 	ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
107 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (lvl)) & 0xFF];
108 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (osv >> 6)) & 0xFF];
109 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (obj >> 0)) & 0xFF];
110 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (obj >> 8)) & 0xFF];
111 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (blkid >> 0)) & 0xFF];
112 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (blkid >> 8)) & 0xFF];
113 
114 	crc ^= (osv>>14) ^ (obj>>16) ^ (blkid>>16);
115 
116 	return (crc);
117 }
118 
119 #define	DBUF_HASH(os, obj, level, blkid) dbuf_hash(os, obj, level, blkid);
120 
121 #define	DBUF_EQUAL(dbuf, os, obj, level, blkid)		\
122 	((dbuf)->db.db_object == (obj) &&		\
123 	(dbuf)->db_objset == (os) &&			\
124 	(dbuf)->db_level == (level) &&			\
125 	(dbuf)->db_blkid == (blkid))
126 
127 dmu_buf_impl_t *
128 dbuf_find(objset_t *os, uint64_t obj, uint8_t level, uint64_t blkid)
129 {
130 	dbuf_hash_table_t *h = &dbuf_hash_table;
131 	uint64_t hv = DBUF_HASH(os, obj, level, blkid);
132 	uint64_t idx = hv & h->hash_table_mask;
133 	dmu_buf_impl_t *db;
134 
135 	mutex_enter(DBUF_HASH_MUTEX(h, idx));
136 	for (db = h->hash_table[idx]; db != NULL; db = db->db_hash_next) {
137 		if (DBUF_EQUAL(db, os, obj, level, blkid)) {
138 			mutex_enter(&db->db_mtx);
139 			if (db->db_state != DB_EVICTING) {
140 				mutex_exit(DBUF_HASH_MUTEX(h, idx));
141 				return (db);
142 			}
143 			mutex_exit(&db->db_mtx);
144 		}
145 	}
146 	mutex_exit(DBUF_HASH_MUTEX(h, idx));
147 	return (NULL);
148 }
149 
150 static dmu_buf_impl_t *
151 dbuf_find_bonus(objset_t *os, uint64_t object)
152 {
153 	dnode_t *dn;
154 	dmu_buf_impl_t *db = NULL;
155 
156 	if (dnode_hold(os, object, FTAG, &dn) == 0) {
157 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
158 		if (dn->dn_bonus != NULL) {
159 			db = dn->dn_bonus;
160 			mutex_enter(&db->db_mtx);
161 		}
162 		rw_exit(&dn->dn_struct_rwlock);
163 		dnode_rele(dn, FTAG);
164 	}
165 	return (db);
166 }
167 
168 /*
169  * Insert an entry into the hash table.  If there is already an element
170  * equal to elem in the hash table, then the already existing element
171  * will be returned and the new element will not be inserted.
172  * Otherwise returns NULL.
173  */
174 static dmu_buf_impl_t *
175 dbuf_hash_insert(dmu_buf_impl_t *db)
176 {
177 	dbuf_hash_table_t *h = &dbuf_hash_table;
178 	objset_t *os = db->db_objset;
179 	uint64_t obj = db->db.db_object;
180 	int level = db->db_level;
181 	uint64_t blkid = db->db_blkid;
182 	uint64_t hv = DBUF_HASH(os, obj, level, blkid);
183 	uint64_t idx = hv & h->hash_table_mask;
184 	dmu_buf_impl_t *dbf;
185 
186 	mutex_enter(DBUF_HASH_MUTEX(h, idx));
187 	for (dbf = h->hash_table[idx]; dbf != NULL; dbf = dbf->db_hash_next) {
188 		if (DBUF_EQUAL(dbf, os, obj, level, blkid)) {
189 			mutex_enter(&dbf->db_mtx);
190 			if (dbf->db_state != DB_EVICTING) {
191 				mutex_exit(DBUF_HASH_MUTEX(h, idx));
192 				return (dbf);
193 			}
194 			mutex_exit(&dbf->db_mtx);
195 		}
196 	}
197 
198 	mutex_enter(&db->db_mtx);
199 	db->db_hash_next = h->hash_table[idx];
200 	h->hash_table[idx] = db;
201 	mutex_exit(DBUF_HASH_MUTEX(h, idx));
202 	atomic_inc_64(&dbuf_hash_count);
203 
204 	return (NULL);
205 }
206 
207 /*
208  * Remove an entry from the hash table.  It must be in the EVICTING state.
209  */
210 static void
211 dbuf_hash_remove(dmu_buf_impl_t *db)
212 {
213 	dbuf_hash_table_t *h = &dbuf_hash_table;
214 	uint64_t hv = DBUF_HASH(db->db_objset, db->db.db_object,
215 	    db->db_level, db->db_blkid);
216 	uint64_t idx = hv & h->hash_table_mask;
217 	dmu_buf_impl_t *dbf, **dbp;
218 
219 	/*
220 	 * We musn't hold db_mtx to maintain lock ordering:
221 	 * DBUF_HASH_MUTEX > db_mtx.
222 	 */
223 	ASSERT(refcount_is_zero(&db->db_holds));
224 	ASSERT(db->db_state == DB_EVICTING);
225 	ASSERT(!MUTEX_HELD(&db->db_mtx));
226 
227 	mutex_enter(DBUF_HASH_MUTEX(h, idx));
228 	dbp = &h->hash_table[idx];
229 	while ((dbf = *dbp) != db) {
230 		dbp = &dbf->db_hash_next;
231 		ASSERT(dbf != NULL);
232 	}
233 	*dbp = db->db_hash_next;
234 	db->db_hash_next = NULL;
235 	mutex_exit(DBUF_HASH_MUTEX(h, idx));
236 	atomic_dec_64(&dbuf_hash_count);
237 }
238 
239 static arc_evict_func_t dbuf_do_evict;
240 
241 typedef enum {
242 	DBVU_EVICTING,
243 	DBVU_NOT_EVICTING
244 } dbvu_verify_type_t;
245 
246 static void
247 dbuf_verify_user(dmu_buf_impl_t *db, dbvu_verify_type_t verify_type)
248 {
249 #ifdef ZFS_DEBUG
250 	int64_t holds;
251 
252 	if (db->db_user == NULL)
253 		return;
254 
255 	/* Only data blocks support the attachment of user data. */
256 	ASSERT(db->db_level == 0);
257 
258 	/* Clients must resolve a dbuf before attaching user data. */
259 	ASSERT(db->db.db_data != NULL);
260 	ASSERT3U(db->db_state, ==, DB_CACHED);
261 
262 	holds = refcount_count(&db->db_holds);
263 	if (verify_type == DBVU_EVICTING) {
264 		/*
265 		 * Immediate eviction occurs when holds == dirtycnt.
266 		 * For normal eviction buffers, holds is zero on
267 		 * eviction, except when dbuf_fix_old_data() calls
268 		 * dbuf_clear_data().  However, the hold count can grow
269 		 * during eviction even though db_mtx is held (see
270 		 * dmu_bonus_hold() for an example), so we can only
271 		 * test the generic invariant that holds >= dirtycnt.
272 		 */
273 		ASSERT3U(holds, >=, db->db_dirtycnt);
274 	} else {
275 		if (db->db_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 
1394 	/*
1395 	 * Due to our use of dn_nlevels below, this can only be called
1396 	 * in open context, unless we are operating on the MOS.
1397 	 * From syncing context, dn_nlevels may be different from the
1398 	 * dn_nlevels used when dbuf was dirtied.
1399 	 */
1400 	ASSERT(db->db_objset ==
1401 	    dmu_objset_pool(db->db_objset)->dp_meta_objset ||
1402 	    txg != spa_syncing_txg(dmu_objset_spa(db->db_objset)));
1403 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1404 	ASSERT0(db->db_level);
1405 	ASSERT(MUTEX_HELD(&db->db_mtx));
1406 
1407 	/*
1408 	 * If this buffer is not dirty, we're done.
1409 	 */
1410 	for (drp = &db->db_last_dirty; (dr = *drp) != NULL; drp = &dr->dr_next)
1411 		if (dr->dr_txg <= txg)
1412 			break;
1413 	if (dr == NULL || dr->dr_txg < txg)
1414 		return (B_FALSE);
1415 	ASSERT(dr->dr_txg == txg);
1416 	ASSERT(dr->dr_dbuf == db);
1417 
1418 	DB_DNODE_ENTER(db);
1419 	dn = DB_DNODE(db);
1420 
1421 	dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
1422 
1423 	ASSERT(db->db.db_size != 0);
1424 
1425 	dsl_pool_undirty_space(dmu_objset_pool(dn->dn_objset),
1426 	    dr->dr_accounted, txg);
1427 
1428 	*drp = dr->dr_next;
1429 
1430 	/*
1431 	 * Note that there are three places in dbuf_dirty()
1432 	 * where this dirty record may be put on a list.
1433 	 * Make sure to do a list_remove corresponding to
1434 	 * every one of those list_insert calls.
1435 	 */
1436 	if (dr->dr_parent) {
1437 		mutex_enter(&dr->dr_parent->dt.di.dr_mtx);
1438 		list_remove(&dr->dr_parent->dt.di.dr_children, dr);
1439 		mutex_exit(&dr->dr_parent->dt.di.dr_mtx);
1440 	} else if (db->db_blkid == DMU_SPILL_BLKID ||
1441 	    db->db_level + 1 == dn->dn_nlevels) {
1442 		ASSERT(db->db_blkptr == NULL || db->db_parent == dn->dn_dbuf);
1443 		mutex_enter(&dn->dn_mtx);
1444 		list_remove(&dn->dn_dirty_records[txg & TXG_MASK], dr);
1445 		mutex_exit(&dn->dn_mtx);
1446 	}
1447 	DB_DNODE_EXIT(db);
1448 
1449 	if (db->db_state != DB_NOFILL) {
1450 		dbuf_unoverride(dr);
1451 
1452 		ASSERT(db->db_buf != NULL);
1453 		ASSERT(dr->dt.dl.dr_data != NULL);
1454 		if (dr->dt.dl.dr_data != db->db_buf)
1455 			VERIFY(arc_buf_remove_ref(dr->dt.dl.dr_data, db));
1456 	}
1457 
1458 	kmem_free(dr, sizeof (dbuf_dirty_record_t));
1459 
1460 	ASSERT(db->db_dirtycnt > 0);
1461 	db->db_dirtycnt -= 1;
1462 
1463 	if (refcount_remove(&db->db_holds, (void *)(uintptr_t)txg) == 0) {
1464 		arc_buf_t *buf = db->db_buf;
1465 
1466 		ASSERT(db->db_state == DB_NOFILL || arc_released(buf));
1467 		dbuf_clear_data(db);
1468 		VERIFY(arc_buf_remove_ref(buf, db));
1469 		dbuf_evict(db);
1470 		return (B_TRUE);
1471 	}
1472 
1473 	return (B_FALSE);
1474 }
1475 
1476 void
1477 dmu_buf_will_dirty(dmu_buf_t *db_fake, dmu_tx_t *tx)
1478 {
1479 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1480 	int rf = DB_RF_MUST_SUCCEED | DB_RF_NOPREFETCH;
1481 
1482 	ASSERT(tx->tx_txg != 0);
1483 	ASSERT(!refcount_is_zero(&db->db_holds));
1484 
1485 	DB_DNODE_ENTER(db);
1486 	if (RW_WRITE_HELD(&DB_DNODE(db)->dn_struct_rwlock))
1487 		rf |= DB_RF_HAVESTRUCT;
1488 	DB_DNODE_EXIT(db);
1489 	(void) dbuf_read(db, NULL, rf);
1490 	(void) dbuf_dirty(db, tx);
1491 }
1492 
1493 void
1494 dmu_buf_will_not_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
1495 {
1496 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1497 
1498 	db->db_state = DB_NOFILL;
1499 
1500 	dmu_buf_will_fill(db_fake, tx);
1501 }
1502 
1503 void
1504 dmu_buf_will_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
1505 {
1506 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1507 
1508 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1509 	ASSERT(tx->tx_txg != 0);
1510 	ASSERT(db->db_level == 0);
1511 	ASSERT(!refcount_is_zero(&db->db_holds));
1512 
1513 	ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT ||
1514 	    dmu_tx_private_ok(tx));
1515 
1516 	dbuf_noread(db);
1517 	(void) dbuf_dirty(db, tx);
1518 }
1519 
1520 #pragma weak dmu_buf_fill_done = dbuf_fill_done
1521 /* ARGSUSED */
1522 void
1523 dbuf_fill_done(dmu_buf_impl_t *db, dmu_tx_t *tx)
1524 {
1525 	mutex_enter(&db->db_mtx);
1526 	DBUF_VERIFY(db);
1527 
1528 	if (db->db_state == DB_FILL) {
1529 		if (db->db_level == 0 && db->db_freed_in_flight) {
1530 			ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1531 			/* we were freed while filling */
1532 			/* XXX dbuf_undirty? */
1533 			bzero(db->db.db_data, db->db.db_size);
1534 			db->db_freed_in_flight = FALSE;
1535 		}
1536 		db->db_state = DB_CACHED;
1537 		cv_broadcast(&db->db_changed);
1538 	}
1539 	mutex_exit(&db->db_mtx);
1540 }
1541 
1542 void
1543 dmu_buf_write_embedded(dmu_buf_t *dbuf, void *data,
1544     bp_embedded_type_t etype, enum zio_compress comp,
1545     int uncompressed_size, int compressed_size, int byteorder,
1546     dmu_tx_t *tx)
1547 {
1548 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbuf;
1549 	struct dirty_leaf *dl;
1550 	dmu_object_type_t type;
1551 
1552 	DB_DNODE_ENTER(db);
1553 	type = DB_DNODE(db)->dn_type;
1554 	DB_DNODE_EXIT(db);
1555 
1556 	ASSERT0(db->db_level);
1557 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1558 
1559 	dmu_buf_will_not_fill(dbuf, tx);
1560 
1561 	ASSERT3U(db->db_last_dirty->dr_txg, ==, tx->tx_txg);
1562 	dl = &db->db_last_dirty->dt.dl;
1563 	encode_embedded_bp_compressed(&dl->dr_overridden_by,
1564 	    data, comp, uncompressed_size, compressed_size);
1565 	BPE_SET_ETYPE(&dl->dr_overridden_by, etype);
1566 	BP_SET_TYPE(&dl->dr_overridden_by, type);
1567 	BP_SET_LEVEL(&dl->dr_overridden_by, 0);
1568 	BP_SET_BYTEORDER(&dl->dr_overridden_by, byteorder);
1569 
1570 	dl->dr_override_state = DR_OVERRIDDEN;
1571 	dl->dr_overridden_by.blk_birth = db->db_last_dirty->dr_txg;
1572 }
1573 
1574 /*
1575  * Directly assign a provided arc buf to a given dbuf if it's not referenced
1576  * by anybody except our caller. Otherwise copy arcbuf's contents to dbuf.
1577  */
1578 void
1579 dbuf_assign_arcbuf(dmu_buf_impl_t *db, arc_buf_t *buf, dmu_tx_t *tx)
1580 {
1581 	ASSERT(!refcount_is_zero(&db->db_holds));
1582 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1583 	ASSERT(db->db_level == 0);
1584 	ASSERT(DBUF_GET_BUFC_TYPE(db) == ARC_BUFC_DATA);
1585 	ASSERT(buf != NULL);
1586 	ASSERT(arc_buf_size(buf) == db->db.db_size);
1587 	ASSERT(tx->tx_txg != 0);
1588 
1589 	arc_return_buf(buf, db);
1590 	ASSERT(arc_released(buf));
1591 
1592 	mutex_enter(&db->db_mtx);
1593 
1594 	while (db->db_state == DB_READ || db->db_state == DB_FILL)
1595 		cv_wait(&db->db_changed, &db->db_mtx);
1596 
1597 	ASSERT(db->db_state == DB_CACHED || db->db_state == DB_UNCACHED);
1598 
1599 	if (db->db_state == DB_CACHED &&
1600 	    refcount_count(&db->db_holds) - 1 > db->db_dirtycnt) {
1601 		mutex_exit(&db->db_mtx);
1602 		(void) dbuf_dirty(db, tx);
1603 		bcopy(buf->b_data, db->db.db_data, db->db.db_size);
1604 		VERIFY(arc_buf_remove_ref(buf, db));
1605 		xuio_stat_wbuf_copied();
1606 		return;
1607 	}
1608 
1609 	xuio_stat_wbuf_nocopy();
1610 	if (db->db_state == DB_CACHED) {
1611 		dbuf_dirty_record_t *dr = db->db_last_dirty;
1612 
1613 		ASSERT(db->db_buf != NULL);
1614 		if (dr != NULL && dr->dr_txg == tx->tx_txg) {
1615 			ASSERT(dr->dt.dl.dr_data == db->db_buf);
1616 			if (!arc_released(db->db_buf)) {
1617 				ASSERT(dr->dt.dl.dr_override_state ==
1618 				    DR_OVERRIDDEN);
1619 				arc_release(db->db_buf, db);
1620 			}
1621 			dr->dt.dl.dr_data = buf;
1622 			VERIFY(arc_buf_remove_ref(db->db_buf, db));
1623 		} else if (dr == NULL || dr->dt.dl.dr_data != db->db_buf) {
1624 			arc_release(db->db_buf, db);
1625 			VERIFY(arc_buf_remove_ref(db->db_buf, db));
1626 		}
1627 		db->db_buf = NULL;
1628 	}
1629 	ASSERT(db->db_buf == NULL);
1630 	dbuf_set_data(db, buf);
1631 	db->db_state = DB_FILL;
1632 	mutex_exit(&db->db_mtx);
1633 	(void) dbuf_dirty(db, tx);
1634 	dmu_buf_fill_done(&db->db, tx);
1635 }
1636 
1637 /*
1638  * "Clear" the contents of this dbuf.  This will mark the dbuf
1639  * EVICTING and clear *most* of its references.  Unfortunately,
1640  * when we are not holding the dn_dbufs_mtx, we can't clear the
1641  * entry in the dn_dbufs list.  We have to wait until dbuf_destroy()
1642  * in this case.  For callers from the DMU we will usually see:
1643  *	dbuf_clear()->arc_clear_callback()->dbuf_do_evict()->dbuf_destroy()
1644  * For the arc callback, we will usually see:
1645  *	dbuf_do_evict()->dbuf_clear();dbuf_destroy()
1646  * Sometimes, though, we will get a mix of these two:
1647  *	DMU: dbuf_clear()->arc_clear_callback()
1648  *	ARC: dbuf_do_evict()->dbuf_destroy()
1649  *
1650  * This routine will dissociate the dbuf from the arc, by calling
1651  * arc_clear_callback(), but will not evict the data from the ARC.
1652  */
1653 void
1654 dbuf_clear(dmu_buf_impl_t *db)
1655 {
1656 	dnode_t *dn;
1657 	dmu_buf_impl_t *parent = db->db_parent;
1658 	dmu_buf_impl_t *dndb;
1659 	boolean_t dbuf_gone = B_FALSE;
1660 
1661 	ASSERT(MUTEX_HELD(&db->db_mtx));
1662 	ASSERT(refcount_is_zero(&db->db_holds));
1663 
1664 	dbuf_evict_user(db);
1665 
1666 	if (db->db_state == DB_CACHED) {
1667 		ASSERT(db->db.db_data != NULL);
1668 		if (db->db_blkid == DMU_BONUS_BLKID) {
1669 			zio_buf_free(db->db.db_data, DN_MAX_BONUSLEN);
1670 			arc_space_return(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
1671 		}
1672 		db->db.db_data = NULL;
1673 		db->db_state = DB_UNCACHED;
1674 	}
1675 
1676 	ASSERT(db->db_state == DB_UNCACHED || db->db_state == DB_NOFILL);
1677 	ASSERT(db->db_data_pending == NULL);
1678 
1679 	db->db_state = DB_EVICTING;
1680 	db->db_blkptr = NULL;
1681 
1682 	DB_DNODE_ENTER(db);
1683 	dn = DB_DNODE(db);
1684 	dndb = dn->dn_dbuf;
1685 	if (db->db_blkid != DMU_BONUS_BLKID && MUTEX_HELD(&dn->dn_dbufs_mtx)) {
1686 		avl_remove(&dn->dn_dbufs, db);
1687 		atomic_dec_32(&dn->dn_dbufs_count);
1688 		membar_producer();
1689 		DB_DNODE_EXIT(db);
1690 		/*
1691 		 * Decrementing the dbuf count means that the hold corresponding
1692 		 * to the removed dbuf is no longer discounted in dnode_move(),
1693 		 * so the dnode cannot be moved until after we release the hold.
1694 		 * The membar_producer() ensures visibility of the decremented
1695 		 * value in dnode_move(), since DB_DNODE_EXIT doesn't actually
1696 		 * release any lock.
1697 		 */
1698 		dnode_rele(dn, db);
1699 		db->db_dnode_handle = NULL;
1700 	} else {
1701 		DB_DNODE_EXIT(db);
1702 	}
1703 
1704 	if (db->db_buf)
1705 		dbuf_gone = arc_clear_callback(db->db_buf);
1706 
1707 	if (!dbuf_gone)
1708 		mutex_exit(&db->db_mtx);
1709 
1710 	/*
1711 	 * If this dbuf is referenced from an indirect dbuf,
1712 	 * decrement the ref count on the indirect dbuf.
1713 	 */
1714 	if (parent && parent != dndb)
1715 		dbuf_rele(parent, db);
1716 }
1717 
1718 static int
1719 dbuf_findbp(dnode_t *dn, int level, uint64_t blkid, int fail_sparse,
1720     dmu_buf_impl_t **parentp, blkptr_t **bpp)
1721 {
1722 	int nlevels, epbs;
1723 
1724 	*parentp = NULL;
1725 	*bpp = NULL;
1726 
1727 	ASSERT(blkid != DMU_BONUS_BLKID);
1728 
1729 	if (blkid == DMU_SPILL_BLKID) {
1730 		mutex_enter(&dn->dn_mtx);
1731 		if (dn->dn_have_spill &&
1732 		    (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR))
1733 			*bpp = &dn->dn_phys->dn_spill;
1734 		else
1735 			*bpp = NULL;
1736 		dbuf_add_ref(dn->dn_dbuf, NULL);
1737 		*parentp = dn->dn_dbuf;
1738 		mutex_exit(&dn->dn_mtx);
1739 		return (0);
1740 	}
1741 
1742 	if (dn->dn_phys->dn_nlevels == 0)
1743 		nlevels = 1;
1744 	else
1745 		nlevels = dn->dn_phys->dn_nlevels;
1746 
1747 	epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
1748 
1749 	ASSERT3U(level * epbs, <, 64);
1750 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
1751 	if (level >= nlevels ||
1752 	    (blkid > (dn->dn_phys->dn_maxblkid >> (level * epbs)))) {
1753 		/* the buffer has no parent yet */
1754 		return (SET_ERROR(ENOENT));
1755 	} else if (level < nlevels-1) {
1756 		/* this block is referenced from an indirect block */
1757 		int err = dbuf_hold_impl(dn, level+1,
1758 		    blkid >> epbs, fail_sparse, NULL, parentp);
1759 		if (err)
1760 			return (err);
1761 		err = dbuf_read(*parentp, NULL,
1762 		    (DB_RF_HAVESTRUCT | DB_RF_NOPREFETCH | DB_RF_CANFAIL));
1763 		if (err) {
1764 			dbuf_rele(*parentp, NULL);
1765 			*parentp = NULL;
1766 			return (err);
1767 		}
1768 		*bpp = ((blkptr_t *)(*parentp)->db.db_data) +
1769 		    (blkid & ((1ULL << epbs) - 1));
1770 		return (0);
1771 	} else {
1772 		/* the block is referenced from the dnode */
1773 		ASSERT3U(level, ==, nlevels-1);
1774 		ASSERT(dn->dn_phys->dn_nblkptr == 0 ||
1775 		    blkid < dn->dn_phys->dn_nblkptr);
1776 		if (dn->dn_dbuf) {
1777 			dbuf_add_ref(dn->dn_dbuf, NULL);
1778 			*parentp = dn->dn_dbuf;
1779 		}
1780 		*bpp = &dn->dn_phys->dn_blkptr[blkid];
1781 		return (0);
1782 	}
1783 }
1784 
1785 static dmu_buf_impl_t *
1786 dbuf_create(dnode_t *dn, uint8_t level, uint64_t blkid,
1787     dmu_buf_impl_t *parent, blkptr_t *blkptr)
1788 {
1789 	objset_t *os = dn->dn_objset;
1790 	dmu_buf_impl_t *db, *odb;
1791 
1792 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
1793 	ASSERT(dn->dn_type != DMU_OT_NONE);
1794 
1795 	db = kmem_cache_alloc(dbuf_cache, KM_SLEEP);
1796 
1797 	db->db_objset = os;
1798 	db->db.db_object = dn->dn_object;
1799 	db->db_level = level;
1800 	db->db_blkid = blkid;
1801 	db->db_last_dirty = NULL;
1802 	db->db_dirtycnt = 0;
1803 	db->db_dnode_handle = dn->dn_handle;
1804 	db->db_parent = parent;
1805 	db->db_blkptr = blkptr;
1806 
1807 	db->db_user = NULL;
1808 	db->db_immediate_evict = 0;
1809 	db->db_freed_in_flight = 0;
1810 
1811 	if (blkid == DMU_BONUS_BLKID) {
1812 		ASSERT3P(parent, ==, dn->dn_dbuf);
1813 		db->db.db_size = DN_MAX_BONUSLEN -
1814 		    (dn->dn_nblkptr-1) * sizeof (blkptr_t);
1815 		ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
1816 		db->db.db_offset = DMU_BONUS_BLKID;
1817 		db->db_state = DB_UNCACHED;
1818 		/* the bonus dbuf is not placed in the hash table */
1819 		arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
1820 		return (db);
1821 	} else if (blkid == DMU_SPILL_BLKID) {
1822 		db->db.db_size = (blkptr != NULL) ?
1823 		    BP_GET_LSIZE(blkptr) : SPA_MINBLOCKSIZE;
1824 		db->db.db_offset = 0;
1825 	} else {
1826 		int blocksize =
1827 		    db->db_level ? 1 << dn->dn_indblkshift : dn->dn_datablksz;
1828 		db->db.db_size = blocksize;
1829 		db->db.db_offset = db->db_blkid * blocksize;
1830 	}
1831 
1832 	/*
1833 	 * Hold the dn_dbufs_mtx while we get the new dbuf
1834 	 * in the hash table *and* added to the dbufs list.
1835 	 * This prevents a possible deadlock with someone
1836 	 * trying to look up this dbuf before its added to the
1837 	 * dn_dbufs list.
1838 	 */
1839 	mutex_enter(&dn->dn_dbufs_mtx);
1840 	db->db_state = DB_EVICTING;
1841 	if ((odb = dbuf_hash_insert(db)) != NULL) {
1842 		/* someone else inserted it first */
1843 		kmem_cache_free(dbuf_cache, db);
1844 		mutex_exit(&dn->dn_dbufs_mtx);
1845 		return (odb);
1846 	}
1847 	avl_add(&dn->dn_dbufs, db);
1848 	if (db->db_level == 0 && db->db_blkid >=
1849 	    dn->dn_unlisted_l0_blkid)
1850 		dn->dn_unlisted_l0_blkid = db->db_blkid + 1;
1851 	db->db_state = DB_UNCACHED;
1852 	mutex_exit(&dn->dn_dbufs_mtx);
1853 	arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
1854 
1855 	if (parent && parent != dn->dn_dbuf)
1856 		dbuf_add_ref(parent, db);
1857 
1858 	ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
1859 	    refcount_count(&dn->dn_holds) > 0);
1860 	(void) refcount_add(&dn->dn_holds, db);
1861 	atomic_inc_32(&dn->dn_dbufs_count);
1862 
1863 	dprintf_dbuf(db, "db=%p\n", db);
1864 
1865 	return (db);
1866 }
1867 
1868 static int
1869 dbuf_do_evict(void *private)
1870 {
1871 	dmu_buf_impl_t *db = private;
1872 
1873 	if (!MUTEX_HELD(&db->db_mtx))
1874 		mutex_enter(&db->db_mtx);
1875 
1876 	ASSERT(refcount_is_zero(&db->db_holds));
1877 
1878 	if (db->db_state != DB_EVICTING) {
1879 		ASSERT(db->db_state == DB_CACHED);
1880 		DBUF_VERIFY(db);
1881 		db->db_buf = NULL;
1882 		dbuf_evict(db);
1883 	} else {
1884 		mutex_exit(&db->db_mtx);
1885 		dbuf_destroy(db);
1886 	}
1887 	return (0);
1888 }
1889 
1890 static void
1891 dbuf_destroy(dmu_buf_impl_t *db)
1892 {
1893 	ASSERT(refcount_is_zero(&db->db_holds));
1894 
1895 	if (db->db_blkid != DMU_BONUS_BLKID) {
1896 		/*
1897 		 * If this dbuf is still on the dn_dbufs list,
1898 		 * remove it from that list.
1899 		 */
1900 		if (db->db_dnode_handle != NULL) {
1901 			dnode_t *dn;
1902 
1903 			DB_DNODE_ENTER(db);
1904 			dn = DB_DNODE(db);
1905 			mutex_enter(&dn->dn_dbufs_mtx);
1906 			avl_remove(&dn->dn_dbufs, db);
1907 			atomic_dec_32(&dn->dn_dbufs_count);
1908 			mutex_exit(&dn->dn_dbufs_mtx);
1909 			DB_DNODE_EXIT(db);
1910 			/*
1911 			 * Decrementing the dbuf count means that the hold
1912 			 * corresponding to the removed dbuf is no longer
1913 			 * discounted in dnode_move(), so the dnode cannot be
1914 			 * moved until after we release the hold.
1915 			 */
1916 			dnode_rele(dn, db);
1917 			db->db_dnode_handle = NULL;
1918 		}
1919 		dbuf_hash_remove(db);
1920 	}
1921 	db->db_parent = NULL;
1922 	db->db_buf = NULL;
1923 
1924 	ASSERT(db->db.db_data == NULL);
1925 	ASSERT(db->db_hash_next == NULL);
1926 	ASSERT(db->db_blkptr == NULL);
1927 	ASSERT(db->db_data_pending == NULL);
1928 
1929 	kmem_cache_free(dbuf_cache, db);
1930 	arc_space_return(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
1931 }
1932 
1933 void
1934 dbuf_prefetch(dnode_t *dn, uint64_t blkid, zio_priority_t prio)
1935 {
1936 	dmu_buf_impl_t *db = NULL;
1937 	blkptr_t *bp = NULL;
1938 
1939 	ASSERT(blkid != DMU_BONUS_BLKID);
1940 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
1941 
1942 	if (dnode_block_freed(dn, blkid))
1943 		return;
1944 
1945 	/* dbuf_find() returns with db_mtx held */
1946 	if (db = dbuf_find(dn->dn_objset, dn->dn_object, 0, blkid)) {
1947 		/*
1948 		 * This dbuf is already in the cache.  We assume that
1949 		 * it is already CACHED, or else about to be either
1950 		 * read or filled.
1951 		 */
1952 		mutex_exit(&db->db_mtx);
1953 		return;
1954 	}
1955 
1956 	if (dbuf_findbp(dn, 0, blkid, TRUE, &db, &bp) == 0) {
1957 		if (bp && !BP_IS_HOLE(bp) && !BP_IS_EMBEDDED(bp)) {
1958 			dsl_dataset_t *ds = dn->dn_objset->os_dsl_dataset;
1959 			arc_flags_t aflags =
1960 			    ARC_FLAG_NOWAIT | ARC_FLAG_PREFETCH;
1961 			zbookmark_phys_t zb;
1962 
1963 			SET_BOOKMARK(&zb, ds ? ds->ds_object : DMU_META_OBJSET,
1964 			    dn->dn_object, 0, blkid);
1965 
1966 			(void) arc_read(NULL, dn->dn_objset->os_spa,
1967 			    bp, NULL, NULL, prio,
1968 			    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
1969 			    &aflags, &zb);
1970 		}
1971 		if (db)
1972 			dbuf_rele(db, NULL);
1973 	}
1974 }
1975 
1976 /*
1977  * Returns with db_holds incremented, and db_mtx not held.
1978  * Note: dn_struct_rwlock must be held.
1979  */
1980 int
1981 dbuf_hold_impl(dnode_t *dn, uint8_t level, uint64_t blkid, int fail_sparse,
1982     void *tag, dmu_buf_impl_t **dbp)
1983 {
1984 	dmu_buf_impl_t *db, *parent = NULL;
1985 
1986 	ASSERT(blkid != DMU_BONUS_BLKID);
1987 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
1988 	ASSERT3U(dn->dn_nlevels, >, level);
1989 
1990 	*dbp = NULL;
1991 top:
1992 	/* dbuf_find() returns with db_mtx held */
1993 	db = dbuf_find(dn->dn_objset, dn->dn_object, level, blkid);
1994 
1995 	if (db == NULL) {
1996 		blkptr_t *bp = NULL;
1997 		int err;
1998 
1999 		ASSERT3P(parent, ==, NULL);
2000 		err = dbuf_findbp(dn, level, blkid, fail_sparse, &parent, &bp);
2001 		if (fail_sparse) {
2002 			if (err == 0 && bp && BP_IS_HOLE(bp))
2003 				err = SET_ERROR(ENOENT);
2004 			if (err) {
2005 				if (parent)
2006 					dbuf_rele(parent, NULL);
2007 				return (err);
2008 			}
2009 		}
2010 		if (err && err != ENOENT)
2011 			return (err);
2012 		db = dbuf_create(dn, level, blkid, parent, bp);
2013 	}
2014 
2015 	if (db->db_buf && refcount_is_zero(&db->db_holds)) {
2016 		arc_buf_add_ref(db->db_buf, db);
2017 		if (db->db_buf->b_data == NULL) {
2018 			dbuf_clear(db);
2019 			if (parent) {
2020 				dbuf_rele(parent, NULL);
2021 				parent = NULL;
2022 			}
2023 			goto top;
2024 		}
2025 		ASSERT3P(db->db.db_data, ==, db->db_buf->b_data);
2026 	}
2027 
2028 	ASSERT(db->db_buf == NULL || arc_referenced(db->db_buf));
2029 
2030 	/*
2031 	 * If this buffer is currently syncing out, and we are are
2032 	 * still referencing it from db_data, we need to make a copy
2033 	 * of it in case we decide we want to dirty it again in this txg.
2034 	 */
2035 	if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
2036 	    dn->dn_object != DMU_META_DNODE_OBJECT &&
2037 	    db->db_state == DB_CACHED && db->db_data_pending) {
2038 		dbuf_dirty_record_t *dr = db->db_data_pending;
2039 
2040 		if (dr->dt.dl.dr_data == db->db_buf) {
2041 			arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
2042 
2043 			dbuf_set_data(db,
2044 			    arc_buf_alloc(dn->dn_objset->os_spa,
2045 			    db->db.db_size, db, type));
2046 			bcopy(dr->dt.dl.dr_data->b_data, db->db.db_data,
2047 			    db->db.db_size);
2048 		}
2049 	}
2050 
2051 	(void) refcount_add(&db->db_holds, tag);
2052 	DBUF_VERIFY(db);
2053 	mutex_exit(&db->db_mtx);
2054 
2055 	/* NOTE: we can't rele the parent until after we drop the db_mtx */
2056 	if (parent)
2057 		dbuf_rele(parent, NULL);
2058 
2059 	ASSERT3P(DB_DNODE(db), ==, dn);
2060 	ASSERT3U(db->db_blkid, ==, blkid);
2061 	ASSERT3U(db->db_level, ==, level);
2062 	*dbp = db;
2063 
2064 	return (0);
2065 }
2066 
2067 dmu_buf_impl_t *
2068 dbuf_hold(dnode_t *dn, uint64_t blkid, void *tag)
2069 {
2070 	dmu_buf_impl_t *db;
2071 	int err = dbuf_hold_impl(dn, 0, blkid, FALSE, tag, &db);
2072 	return (err ? NULL : db);
2073 }
2074 
2075 dmu_buf_impl_t *
2076 dbuf_hold_level(dnode_t *dn, int level, uint64_t blkid, void *tag)
2077 {
2078 	dmu_buf_impl_t *db;
2079 	int err = dbuf_hold_impl(dn, level, blkid, FALSE, tag, &db);
2080 	return (err ? NULL : db);
2081 }
2082 
2083 void
2084 dbuf_create_bonus(dnode_t *dn)
2085 {
2086 	ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
2087 
2088 	ASSERT(dn->dn_bonus == NULL);
2089 	dn->dn_bonus = dbuf_create(dn, 0, DMU_BONUS_BLKID, dn->dn_dbuf, NULL);
2090 }
2091 
2092 int
2093 dbuf_spill_set_blksz(dmu_buf_t *db_fake, uint64_t blksz, dmu_tx_t *tx)
2094 {
2095 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2096 	dnode_t *dn;
2097 
2098 	if (db->db_blkid != DMU_SPILL_BLKID)
2099 		return (SET_ERROR(ENOTSUP));
2100 	if (blksz == 0)
2101 		blksz = SPA_MINBLOCKSIZE;
2102 	ASSERT3U(blksz, <=, spa_maxblocksize(dmu_objset_spa(db->db_objset)));
2103 	blksz = P2ROUNDUP(blksz, SPA_MINBLOCKSIZE);
2104 
2105 	DB_DNODE_ENTER(db);
2106 	dn = DB_DNODE(db);
2107 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
2108 	dbuf_new_size(db, blksz, tx);
2109 	rw_exit(&dn->dn_struct_rwlock);
2110 	DB_DNODE_EXIT(db);
2111 
2112 	return (0);
2113 }
2114 
2115 void
2116 dbuf_rm_spill(dnode_t *dn, dmu_tx_t *tx)
2117 {
2118 	dbuf_free_range(dn, DMU_SPILL_BLKID, DMU_SPILL_BLKID, tx);
2119 }
2120 
2121 #pragma weak dmu_buf_add_ref = dbuf_add_ref
2122 void
2123 dbuf_add_ref(dmu_buf_impl_t *db, void *tag)
2124 {
2125 	int64_t holds = refcount_add(&db->db_holds, tag);
2126 	ASSERT(holds > 1);
2127 }
2128 
2129 #pragma weak dmu_buf_try_add_ref = dbuf_try_add_ref
2130 boolean_t
2131 dbuf_try_add_ref(dmu_buf_t *db_fake, objset_t *os, uint64_t obj, uint64_t blkid,
2132     void *tag)
2133 {
2134 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2135 	dmu_buf_impl_t *found_db;
2136 	boolean_t result = B_FALSE;
2137 
2138 	if (db->db_blkid == DMU_BONUS_BLKID)
2139 		found_db = dbuf_find_bonus(os, obj);
2140 	else
2141 		found_db = dbuf_find(os, obj, 0, blkid);
2142 
2143 	if (found_db != NULL) {
2144 		if (db == found_db && dbuf_refcount(db) > db->db_dirtycnt) {
2145 			(void) refcount_add(&db->db_holds, tag);
2146 			result = B_TRUE;
2147 		}
2148 		mutex_exit(&db->db_mtx);
2149 	}
2150 	return (result);
2151 }
2152 
2153 /*
2154  * If you call dbuf_rele() you had better not be referencing the dnode handle
2155  * unless you have some other direct or indirect hold on the dnode. (An indirect
2156  * hold is a hold on one of the dnode's dbufs, including the bonus buffer.)
2157  * Without that, the dbuf_rele() could lead to a dnode_rele() followed by the
2158  * dnode's parent dbuf evicting its dnode handles.
2159  */
2160 void
2161 dbuf_rele(dmu_buf_impl_t *db, void *tag)
2162 {
2163 	mutex_enter(&db->db_mtx);
2164 	dbuf_rele_and_unlock(db, tag);
2165 }
2166 
2167 void
2168 dmu_buf_rele(dmu_buf_t *db, void *tag)
2169 {
2170 	dbuf_rele((dmu_buf_impl_t *)db, tag);
2171 }
2172 
2173 /*
2174  * dbuf_rele() for an already-locked dbuf.  This is necessary to allow
2175  * db_dirtycnt and db_holds to be updated atomically.
2176  */
2177 void
2178 dbuf_rele_and_unlock(dmu_buf_impl_t *db, void *tag)
2179 {
2180 	int64_t holds;
2181 
2182 	ASSERT(MUTEX_HELD(&db->db_mtx));
2183 	DBUF_VERIFY(db);
2184 
2185 	/*
2186 	 * Remove the reference to the dbuf before removing its hold on the
2187 	 * dnode so we can guarantee in dnode_move() that a referenced bonus
2188 	 * buffer has a corresponding dnode hold.
2189 	 */
2190 	holds = refcount_remove(&db->db_holds, tag);
2191 	ASSERT(holds >= 0);
2192 
2193 	/*
2194 	 * We can't freeze indirects if there is a possibility that they
2195 	 * may be modified in the current syncing context.
2196 	 */
2197 	if (db->db_buf && holds == (db->db_level == 0 ? db->db_dirtycnt : 0))
2198 		arc_buf_freeze(db->db_buf);
2199 
2200 	if (holds == db->db_dirtycnt &&
2201 	    db->db_level == 0 && db->db_immediate_evict)
2202 		dbuf_evict_user(db);
2203 
2204 	if (holds == 0) {
2205 		if (db->db_blkid == DMU_BONUS_BLKID) {
2206 			dnode_t *dn;
2207 
2208 			/*
2209 			 * If the dnode moves here, we cannot cross this
2210 			 * barrier until the move completes.
2211 			 */
2212 			DB_DNODE_ENTER(db);
2213 
2214 			dn = DB_DNODE(db);
2215 			atomic_dec_32(&dn->dn_dbufs_count);
2216 
2217 			/*
2218 			 * Decrementing the dbuf count means that the bonus
2219 			 * buffer's dnode hold is no longer discounted in
2220 			 * dnode_move(). The dnode cannot move until after
2221 			 * the dnode_rele_and_unlock() below.
2222 			 */
2223 			DB_DNODE_EXIT(db);
2224 
2225 			/*
2226 			 * Do not reference db after its lock is dropped.
2227 			 * Another thread may evict it.
2228 			 */
2229 			mutex_exit(&db->db_mtx);
2230 
2231 			/*
2232 			 * If the dnode has been freed, evict the bonus
2233 			 * buffer immediately.	The data in the bonus
2234 			 * buffer is no longer relevant and this prevents
2235 			 * a stale bonus buffer from being associated
2236 			 * with this dnode_t should the dnode_t be reused
2237 			 * prior to being destroyed.
2238 			 */
2239 			mutex_enter(&dn->dn_mtx);
2240 			if (dn->dn_type == DMU_OT_NONE ||
2241 			    dn->dn_free_txg != 0) {
2242 				/*
2243 				 * Drop dn_mtx.  It is a leaf lock and
2244 				 * cannot be held when dnode_evict_bonus()
2245 				 * acquires other locks in order to
2246 				 * perform the eviction.
2247 				 *
2248 				 * Freed dnodes cannot be reused until the
2249 				 * last hold is released.  Since this bonus
2250 				 * buffer has a hold, the dnode will remain
2251 				 * in the free state, even without dn_mtx
2252 				 * held, until the dnode_rele_and_unlock()
2253 				 * below.
2254 				 */
2255 				mutex_exit(&dn->dn_mtx);
2256 				dnode_evict_bonus(dn);
2257 				mutex_enter(&dn->dn_mtx);
2258 			}
2259 			dnode_rele_and_unlock(dn, db);
2260 		} else if (db->db_buf == NULL) {
2261 			/*
2262 			 * This is a special case: we never associated this
2263 			 * dbuf with any data allocated from the ARC.
2264 			 */
2265 			ASSERT(db->db_state == DB_UNCACHED ||
2266 			    db->db_state == DB_NOFILL);
2267 			dbuf_evict(db);
2268 		} else if (arc_released(db->db_buf)) {
2269 			arc_buf_t *buf = db->db_buf;
2270 			/*
2271 			 * This dbuf has anonymous data associated with it.
2272 			 */
2273 			dbuf_clear_data(db);
2274 			VERIFY(arc_buf_remove_ref(buf, db));
2275 			dbuf_evict(db);
2276 		} else {
2277 			VERIFY(!arc_buf_remove_ref(db->db_buf, db));
2278 
2279 			/*
2280 			 * A dbuf will be eligible for eviction if either the
2281 			 * 'primarycache' property is set or a duplicate
2282 			 * copy of this buffer is already cached in the arc.
2283 			 *
2284 			 * In the case of the 'primarycache' a buffer
2285 			 * is considered for eviction if it matches the
2286 			 * criteria set in the property.
2287 			 *
2288 			 * To decide if our buffer is considered a
2289 			 * duplicate, we must call into the arc to determine
2290 			 * if multiple buffers are referencing the same
2291 			 * block on-disk. If so, then we simply evict
2292 			 * ourselves.
2293 			 */
2294 			if (!DBUF_IS_CACHEABLE(db)) {
2295 				if (db->db_blkptr != NULL &&
2296 				    !BP_IS_HOLE(db->db_blkptr) &&
2297 				    !BP_IS_EMBEDDED(db->db_blkptr)) {
2298 					spa_t *spa =
2299 					    dmu_objset_spa(db->db_objset);
2300 					blkptr_t bp = *db->db_blkptr;
2301 					dbuf_clear(db);
2302 					arc_freed(spa, &bp);
2303 				} else {
2304 					dbuf_clear(db);
2305 				}
2306 			} else if (db->db_objset->os_evicting ||
2307 			    arc_buf_eviction_needed(db->db_buf)) {
2308 				dbuf_clear(db);
2309 			} else {
2310 				mutex_exit(&db->db_mtx);
2311 			}
2312 		}
2313 	} else {
2314 		mutex_exit(&db->db_mtx);
2315 	}
2316 }
2317 
2318 #pragma weak dmu_buf_refcount = dbuf_refcount
2319 uint64_t
2320 dbuf_refcount(dmu_buf_impl_t *db)
2321 {
2322 	return (refcount_count(&db->db_holds));
2323 }
2324 
2325 void *
2326 dmu_buf_replace_user(dmu_buf_t *db_fake, dmu_buf_user_t *old_user,
2327     dmu_buf_user_t *new_user)
2328 {
2329 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2330 
2331 	mutex_enter(&db->db_mtx);
2332 	dbuf_verify_user(db, DBVU_NOT_EVICTING);
2333 	if (db->db_user == old_user)
2334 		db->db_user = new_user;
2335 	else
2336 		old_user = db->db_user;
2337 	dbuf_verify_user(db, DBVU_NOT_EVICTING);
2338 	mutex_exit(&db->db_mtx);
2339 
2340 	return (old_user);
2341 }
2342 
2343 void *
2344 dmu_buf_set_user(dmu_buf_t *db_fake, dmu_buf_user_t *user)
2345 {
2346 	return (dmu_buf_replace_user(db_fake, NULL, user));
2347 }
2348 
2349 void *
2350 dmu_buf_set_user_ie(dmu_buf_t *db_fake, dmu_buf_user_t *user)
2351 {
2352 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2353 
2354 	db->db_immediate_evict = TRUE;
2355 	return (dmu_buf_set_user(db_fake, user));
2356 }
2357 
2358 void *
2359 dmu_buf_remove_user(dmu_buf_t *db_fake, dmu_buf_user_t *user)
2360 {
2361 	return (dmu_buf_replace_user(db_fake, user, NULL));
2362 }
2363 
2364 void *
2365 dmu_buf_get_user(dmu_buf_t *db_fake)
2366 {
2367 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2368 
2369 	dbuf_verify_user(db, DBVU_NOT_EVICTING);
2370 	return (db->db_user);
2371 }
2372 
2373 void
2374 dmu_buf_user_evict_wait()
2375 {
2376 	taskq_wait(dbu_evict_taskq);
2377 }
2378 
2379 boolean_t
2380 dmu_buf_freeable(dmu_buf_t *dbuf)
2381 {
2382 	boolean_t res = B_FALSE;
2383 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbuf;
2384 
2385 	if (db->db_blkptr)
2386 		res = dsl_dataset_block_freeable(db->db_objset->os_dsl_dataset,
2387 		    db->db_blkptr, db->db_blkptr->blk_birth);
2388 
2389 	return (res);
2390 }
2391 
2392 blkptr_t *
2393 dmu_buf_get_blkptr(dmu_buf_t *db)
2394 {
2395 	dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
2396 	return (dbi->db_blkptr);
2397 }
2398 
2399 static void
2400 dbuf_check_blkptr(dnode_t *dn, dmu_buf_impl_t *db)
2401 {
2402 	/* ASSERT(dmu_tx_is_syncing(tx) */
2403 	ASSERT(MUTEX_HELD(&db->db_mtx));
2404 
2405 	if (db->db_blkptr != NULL)
2406 		return;
2407 
2408 	if (db->db_blkid == DMU_SPILL_BLKID) {
2409 		db->db_blkptr = &dn->dn_phys->dn_spill;
2410 		BP_ZERO(db->db_blkptr);
2411 		return;
2412 	}
2413 	if (db->db_level == dn->dn_phys->dn_nlevels-1) {
2414 		/*
2415 		 * This buffer was allocated at a time when there was
2416 		 * no available blkptrs from the dnode, or it was
2417 		 * inappropriate to hook it in (i.e., nlevels mis-match).
2418 		 */
2419 		ASSERT(db->db_blkid < dn->dn_phys->dn_nblkptr);
2420 		ASSERT(db->db_parent == NULL);
2421 		db->db_parent = dn->dn_dbuf;
2422 		db->db_blkptr = &dn->dn_phys->dn_blkptr[db->db_blkid];
2423 		DBUF_VERIFY(db);
2424 	} else {
2425 		dmu_buf_impl_t *parent = db->db_parent;
2426 		int epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
2427 
2428 		ASSERT(dn->dn_phys->dn_nlevels > 1);
2429 		if (parent == NULL) {
2430 			mutex_exit(&db->db_mtx);
2431 			rw_enter(&dn->dn_struct_rwlock, RW_READER);
2432 			(void) dbuf_hold_impl(dn, db->db_level+1,
2433 			    db->db_blkid >> epbs, FALSE, db, &parent);
2434 			rw_exit(&dn->dn_struct_rwlock);
2435 			mutex_enter(&db->db_mtx);
2436 			db->db_parent = parent;
2437 		}
2438 		db->db_blkptr = (blkptr_t *)parent->db.db_data +
2439 		    (db->db_blkid & ((1ULL << epbs) - 1));
2440 		DBUF_VERIFY(db);
2441 	}
2442 }
2443 
2444 static void
2445 dbuf_sync_indirect(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
2446 {
2447 	dmu_buf_impl_t *db = dr->dr_dbuf;
2448 	dnode_t *dn;
2449 	zio_t *zio;
2450 
2451 	ASSERT(dmu_tx_is_syncing(tx));
2452 
2453 	dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
2454 
2455 	mutex_enter(&db->db_mtx);
2456 
2457 	ASSERT(db->db_level > 0);
2458 	DBUF_VERIFY(db);
2459 
2460 	/* Read the block if it hasn't been read yet. */
2461 	if (db->db_buf == NULL) {
2462 		mutex_exit(&db->db_mtx);
2463 		(void) dbuf_read(db, NULL, DB_RF_MUST_SUCCEED);
2464 		mutex_enter(&db->db_mtx);
2465 	}
2466 	ASSERT3U(db->db_state, ==, DB_CACHED);
2467 	ASSERT(db->db_buf != NULL);
2468 
2469 	DB_DNODE_ENTER(db);
2470 	dn = DB_DNODE(db);
2471 	/* Indirect block size must match what the dnode thinks it is. */
2472 	ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
2473 	dbuf_check_blkptr(dn, db);
2474 	DB_DNODE_EXIT(db);
2475 
2476 	/* Provide the pending dirty record to child dbufs */
2477 	db->db_data_pending = dr;
2478 
2479 	mutex_exit(&db->db_mtx);
2480 	dbuf_write(dr, db->db_buf, tx);
2481 
2482 	zio = dr->dr_zio;
2483 	mutex_enter(&dr->dt.di.dr_mtx);
2484 	dbuf_sync_list(&dr->dt.di.dr_children, db->db_level - 1, tx);
2485 	ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
2486 	mutex_exit(&dr->dt.di.dr_mtx);
2487 	zio_nowait(zio);
2488 }
2489 
2490 static void
2491 dbuf_sync_leaf(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
2492 {
2493 	arc_buf_t **datap = &dr->dt.dl.dr_data;
2494 	dmu_buf_impl_t *db = dr->dr_dbuf;
2495 	dnode_t *dn;
2496 	objset_t *os;
2497 	uint64_t txg = tx->tx_txg;
2498 
2499 	ASSERT(dmu_tx_is_syncing(tx));
2500 
2501 	dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
2502 
2503 	mutex_enter(&db->db_mtx);
2504 	/*
2505 	 * To be synced, we must be dirtied.  But we
2506 	 * might have been freed after the dirty.
2507 	 */
2508 	if (db->db_state == DB_UNCACHED) {
2509 		/* This buffer has been freed since it was dirtied */
2510 		ASSERT(db->db.db_data == NULL);
2511 	} else if (db->db_state == DB_FILL) {
2512 		/* This buffer was freed and is now being re-filled */
2513 		ASSERT(db->db.db_data != dr->dt.dl.dr_data);
2514 	} else {
2515 		ASSERT(db->db_state == DB_CACHED || db->db_state == DB_NOFILL);
2516 	}
2517 	DBUF_VERIFY(db);
2518 
2519 	DB_DNODE_ENTER(db);
2520 	dn = DB_DNODE(db);
2521 
2522 	if (db->db_blkid == DMU_SPILL_BLKID) {
2523 		mutex_enter(&dn->dn_mtx);
2524 		dn->dn_phys->dn_flags |= DNODE_FLAG_SPILL_BLKPTR;
2525 		mutex_exit(&dn->dn_mtx);
2526 	}
2527 
2528 	/*
2529 	 * If this is a bonus buffer, simply copy the bonus data into the
2530 	 * dnode.  It will be written out when the dnode is synced (and it
2531 	 * will be synced, since it must have been dirty for dbuf_sync to
2532 	 * be called).
2533 	 */
2534 	if (db->db_blkid == DMU_BONUS_BLKID) {
2535 		dbuf_dirty_record_t **drp;
2536 
2537 		ASSERT(*datap != NULL);
2538 		ASSERT0(db->db_level);
2539 		ASSERT3U(dn->dn_phys->dn_bonuslen, <=, DN_MAX_BONUSLEN);
2540 		bcopy(*datap, DN_BONUS(dn->dn_phys), dn->dn_phys->dn_bonuslen);
2541 		DB_DNODE_EXIT(db);
2542 
2543 		if (*datap != db->db.db_data) {
2544 			zio_buf_free(*datap, DN_MAX_BONUSLEN);
2545 			arc_space_return(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
2546 		}
2547 		db->db_data_pending = NULL;
2548 		drp = &db->db_last_dirty;
2549 		while (*drp != dr)
2550 			drp = &(*drp)->dr_next;
2551 		ASSERT(dr->dr_next == NULL);
2552 		ASSERT(dr->dr_dbuf == db);
2553 		*drp = dr->dr_next;
2554 		kmem_free(dr, sizeof (dbuf_dirty_record_t));
2555 		ASSERT(db->db_dirtycnt > 0);
2556 		db->db_dirtycnt -= 1;
2557 		dbuf_rele_and_unlock(db, (void *)(uintptr_t)txg);
2558 		return;
2559 	}
2560 
2561 	os = dn->dn_objset;
2562 
2563 	/*
2564 	 * This function may have dropped the db_mtx lock allowing a dmu_sync
2565 	 * operation to sneak in. As a result, we need to ensure that we
2566 	 * don't check the dr_override_state until we have returned from
2567 	 * dbuf_check_blkptr.
2568 	 */
2569 	dbuf_check_blkptr(dn, db);
2570 
2571 	/*
2572 	 * If this buffer is in the middle of an immediate write,
2573 	 * wait for the synchronous IO to complete.
2574 	 */
2575 	while (dr->dt.dl.dr_override_state == DR_IN_DMU_SYNC) {
2576 		ASSERT(dn->dn_object != DMU_META_DNODE_OBJECT);
2577 		cv_wait(&db->db_changed, &db->db_mtx);
2578 		ASSERT(dr->dt.dl.dr_override_state != DR_NOT_OVERRIDDEN);
2579 	}
2580 
2581 	if (db->db_state != DB_NOFILL &&
2582 	    dn->dn_object != DMU_META_DNODE_OBJECT &&
2583 	    refcount_count(&db->db_holds) > 1 &&
2584 	    dr->dt.dl.dr_override_state != DR_OVERRIDDEN &&
2585 	    *datap == db->db_buf) {
2586 		/*
2587 		 * If this buffer is currently "in use" (i.e., there
2588 		 * are active holds and db_data still references it),
2589 		 * then make a copy before we start the write so that
2590 		 * any modifications from the open txg will not leak
2591 		 * into this write.
2592 		 *
2593 		 * NOTE: this copy does not need to be made for
2594 		 * objects only modified in the syncing context (e.g.
2595 		 * DNONE_DNODE blocks).
2596 		 */
2597 		int blksz = arc_buf_size(*datap);
2598 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
2599 		*datap = arc_buf_alloc(os->os_spa, blksz, db, type);
2600 		bcopy(db->db.db_data, (*datap)->b_data, blksz);
2601 	}
2602 	db->db_data_pending = dr;
2603 
2604 	mutex_exit(&db->db_mtx);
2605 
2606 	dbuf_write(dr, *datap, tx);
2607 
2608 	ASSERT(!list_link_active(&dr->dr_dirty_node));
2609 	if (dn->dn_object == DMU_META_DNODE_OBJECT) {
2610 		list_insert_tail(&dn->dn_dirty_records[txg&TXG_MASK], dr);
2611 		DB_DNODE_EXIT(db);
2612 	} else {
2613 		/*
2614 		 * Although zio_nowait() does not "wait for an IO", it does
2615 		 * initiate the IO. If this is an empty write it seems plausible
2616 		 * that the IO could actually be completed before the nowait
2617 		 * returns. We need to DB_DNODE_EXIT() first in case
2618 		 * zio_nowait() invalidates the dbuf.
2619 		 */
2620 		DB_DNODE_EXIT(db);
2621 		zio_nowait(dr->dr_zio);
2622 	}
2623 }
2624 
2625 void
2626 dbuf_sync_list(list_t *list, int level, dmu_tx_t *tx)
2627 {
2628 	dbuf_dirty_record_t *dr;
2629 
2630 	while (dr = list_head(list)) {
2631 		if (dr->dr_zio != NULL) {
2632 			/*
2633 			 * If we find an already initialized zio then we
2634 			 * are processing the meta-dnode, and we have finished.
2635 			 * The dbufs for all dnodes are put back on the list
2636 			 * during processing, so that we can zio_wait()
2637 			 * these IOs after initiating all child IOs.
2638 			 */
2639 			ASSERT3U(dr->dr_dbuf->db.db_object, ==,
2640 			    DMU_META_DNODE_OBJECT);
2641 			break;
2642 		}
2643 		if (dr->dr_dbuf->db_blkid != DMU_BONUS_BLKID &&
2644 		    dr->dr_dbuf->db_blkid != DMU_SPILL_BLKID) {
2645 			VERIFY3U(dr->dr_dbuf->db_level, ==, level);
2646 		}
2647 		list_remove(list, dr);
2648 		if (dr->dr_dbuf->db_level > 0)
2649 			dbuf_sync_indirect(dr, tx);
2650 		else
2651 			dbuf_sync_leaf(dr, tx);
2652 	}
2653 }
2654 
2655 /* ARGSUSED */
2656 static void
2657 dbuf_write_ready(zio_t *zio, arc_buf_t *buf, void *vdb)
2658 {
2659 	dmu_buf_impl_t *db = vdb;
2660 	dnode_t *dn;
2661 	blkptr_t *bp = zio->io_bp;
2662 	blkptr_t *bp_orig = &zio->io_bp_orig;
2663 	spa_t *spa = zio->io_spa;
2664 	int64_t delta;
2665 	uint64_t fill = 0;
2666 	int i;
2667 
2668 	ASSERT3P(db->db_blkptr, ==, bp);
2669 
2670 	DB_DNODE_ENTER(db);
2671 	dn = DB_DNODE(db);
2672 	delta = bp_get_dsize_sync(spa, bp) - bp_get_dsize_sync(spa, bp_orig);
2673 	dnode_diduse_space(dn, delta - zio->io_prev_space_delta);
2674 	zio->io_prev_space_delta = delta;
2675 
2676 	if (bp->blk_birth != 0) {
2677 		ASSERT((db->db_blkid != DMU_SPILL_BLKID &&
2678 		    BP_GET_TYPE(bp) == dn->dn_type) ||
2679 		    (db->db_blkid == DMU_SPILL_BLKID &&
2680 		    BP_GET_TYPE(bp) == dn->dn_bonustype) ||
2681 		    BP_IS_EMBEDDED(bp));
2682 		ASSERT(BP_GET_LEVEL(bp) == db->db_level);
2683 	}
2684 
2685 	mutex_enter(&db->db_mtx);
2686 
2687 #ifdef ZFS_DEBUG
2688 	if (db->db_blkid == DMU_SPILL_BLKID) {
2689 		ASSERT(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR);
2690 		ASSERT(!(BP_IS_HOLE(db->db_blkptr)) &&
2691 		    db->db_blkptr == &dn->dn_phys->dn_spill);
2692 	}
2693 #endif
2694 
2695 	if (db->db_level == 0) {
2696 		mutex_enter(&dn->dn_mtx);
2697 		if (db->db_blkid > dn->dn_phys->dn_maxblkid &&
2698 		    db->db_blkid != DMU_SPILL_BLKID)
2699 			dn->dn_phys->dn_maxblkid = db->db_blkid;
2700 		mutex_exit(&dn->dn_mtx);
2701 
2702 		if (dn->dn_type == DMU_OT_DNODE) {
2703 			dnode_phys_t *dnp = db->db.db_data;
2704 			for (i = db->db.db_size >> DNODE_SHIFT; i > 0;
2705 			    i--, dnp++) {
2706 				if (dnp->dn_type != DMU_OT_NONE)
2707 					fill++;
2708 			}
2709 		} else {
2710 			if (BP_IS_HOLE(bp)) {
2711 				fill = 0;
2712 			} else {
2713 				fill = 1;
2714 			}
2715 		}
2716 	} else {
2717 		blkptr_t *ibp = db->db.db_data;
2718 		ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
2719 		for (i = db->db.db_size >> SPA_BLKPTRSHIFT; i > 0; i--, ibp++) {
2720 			if (BP_IS_HOLE(ibp))
2721 				continue;
2722 			fill += BP_GET_FILL(ibp);
2723 		}
2724 	}
2725 	DB_DNODE_EXIT(db);
2726 
2727 	if (!BP_IS_EMBEDDED(bp))
2728 		bp->blk_fill = fill;
2729 
2730 	mutex_exit(&db->db_mtx);
2731 }
2732 
2733 /*
2734  * The SPA will call this callback several times for each zio - once
2735  * for every physical child i/o (zio->io_phys_children times).  This
2736  * allows the DMU to monitor the progress of each logical i/o.  For example,
2737  * there may be 2 copies of an indirect block, or many fragments of a RAID-Z
2738  * block.  There may be a long delay before all copies/fragments are completed,
2739  * so this callback allows us to retire dirty space gradually, as the physical
2740  * i/os complete.
2741  */
2742 /* ARGSUSED */
2743 static void
2744 dbuf_write_physdone(zio_t *zio, arc_buf_t *buf, void *arg)
2745 {
2746 	dmu_buf_impl_t *db = arg;
2747 	objset_t *os = db->db_objset;
2748 	dsl_pool_t *dp = dmu_objset_pool(os);
2749 	dbuf_dirty_record_t *dr;
2750 	int delta = 0;
2751 
2752 	dr = db->db_data_pending;
2753 	ASSERT3U(dr->dr_txg, ==, zio->io_txg);
2754 
2755 	/*
2756 	 * The callback will be called io_phys_children times.  Retire one
2757 	 * portion of our dirty space each time we are called.  Any rounding
2758 	 * error will be cleaned up by dsl_pool_sync()'s call to
2759 	 * dsl_pool_undirty_space().
2760 	 */
2761 	delta = dr->dr_accounted / zio->io_phys_children;
2762 	dsl_pool_undirty_space(dp, delta, zio->io_txg);
2763 }
2764 
2765 /* ARGSUSED */
2766 static void
2767 dbuf_write_done(zio_t *zio, arc_buf_t *buf, void *vdb)
2768 {
2769 	dmu_buf_impl_t *db = vdb;
2770 	blkptr_t *bp_orig = &zio->io_bp_orig;
2771 	blkptr_t *bp = db->db_blkptr;
2772 	objset_t *os = db->db_objset;
2773 	dmu_tx_t *tx = os->os_synctx;
2774 	dbuf_dirty_record_t **drp, *dr;
2775 
2776 	ASSERT0(zio->io_error);
2777 	ASSERT(db->db_blkptr == bp);
2778 
2779 	/*
2780 	 * For nopwrites and rewrites we ensure that the bp matches our
2781 	 * original and bypass all the accounting.
2782 	 */
2783 	if (zio->io_flags & (ZIO_FLAG_IO_REWRITE | ZIO_FLAG_NOPWRITE)) {
2784 		ASSERT(BP_EQUAL(bp, bp_orig));
2785 	} else {
2786 		dsl_dataset_t *ds = os->os_dsl_dataset;
2787 		(void) dsl_dataset_block_kill(ds, bp_orig, tx, B_TRUE);
2788 		dsl_dataset_block_born(ds, bp, tx);
2789 	}
2790 
2791 	mutex_enter(&db->db_mtx);
2792 
2793 	DBUF_VERIFY(db);
2794 
2795 	drp = &db->db_last_dirty;
2796 	while ((dr = *drp) != db->db_data_pending)
2797 		drp = &dr->dr_next;
2798 	ASSERT(!list_link_active(&dr->dr_dirty_node));
2799 	ASSERT(dr->dr_dbuf == db);
2800 	ASSERT(dr->dr_next == NULL);
2801 	*drp = dr->dr_next;
2802 
2803 #ifdef ZFS_DEBUG
2804 	if (db->db_blkid == DMU_SPILL_BLKID) {
2805 		dnode_t *dn;
2806 
2807 		DB_DNODE_ENTER(db);
2808 		dn = DB_DNODE(db);
2809 		ASSERT(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR);
2810 		ASSERT(!(BP_IS_HOLE(db->db_blkptr)) &&
2811 		    db->db_blkptr == &dn->dn_phys->dn_spill);
2812 		DB_DNODE_EXIT(db);
2813 	}
2814 #endif
2815 
2816 	if (db->db_level == 0) {
2817 		ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2818 		ASSERT(dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN);
2819 		if (db->db_state != DB_NOFILL) {
2820 			if (dr->dt.dl.dr_data != db->db_buf)
2821 				VERIFY(arc_buf_remove_ref(dr->dt.dl.dr_data,
2822 				    db));
2823 			else if (!arc_released(db->db_buf))
2824 				arc_set_callback(db->db_buf, dbuf_do_evict, db);
2825 		}
2826 	} else {
2827 		dnode_t *dn;
2828 
2829 		DB_DNODE_ENTER(db);
2830 		dn = DB_DNODE(db);
2831 		ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
2832 		ASSERT3U(db->db.db_size, ==, 1 << dn->dn_phys->dn_indblkshift);
2833 		if (!BP_IS_HOLE(db->db_blkptr)) {
2834 			int epbs =
2835 			    dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
2836 			ASSERT3U(db->db_blkid, <=,
2837 			    dn->dn_phys->dn_maxblkid >> (db->db_level * epbs));
2838 			ASSERT3U(BP_GET_LSIZE(db->db_blkptr), ==,
2839 			    db->db.db_size);
2840 			if (!arc_released(db->db_buf))
2841 				arc_set_callback(db->db_buf, dbuf_do_evict, db);
2842 		}
2843 		DB_DNODE_EXIT(db);
2844 		mutex_destroy(&dr->dt.di.dr_mtx);
2845 		list_destroy(&dr->dt.di.dr_children);
2846 	}
2847 	kmem_free(dr, sizeof (dbuf_dirty_record_t));
2848 
2849 	cv_broadcast(&db->db_changed);
2850 	ASSERT(db->db_dirtycnt > 0);
2851 	db->db_dirtycnt -= 1;
2852 	db->db_data_pending = NULL;
2853 	dbuf_rele_and_unlock(db, (void *)(uintptr_t)tx->tx_txg);
2854 }
2855 
2856 static void
2857 dbuf_write_nofill_ready(zio_t *zio)
2858 {
2859 	dbuf_write_ready(zio, NULL, zio->io_private);
2860 }
2861 
2862 static void
2863 dbuf_write_nofill_done(zio_t *zio)
2864 {
2865 	dbuf_write_done(zio, NULL, zio->io_private);
2866 }
2867 
2868 static void
2869 dbuf_write_override_ready(zio_t *zio)
2870 {
2871 	dbuf_dirty_record_t *dr = zio->io_private;
2872 	dmu_buf_impl_t *db = dr->dr_dbuf;
2873 
2874 	dbuf_write_ready(zio, NULL, db);
2875 }
2876 
2877 static void
2878 dbuf_write_override_done(zio_t *zio)
2879 {
2880 	dbuf_dirty_record_t *dr = zio->io_private;
2881 	dmu_buf_impl_t *db = dr->dr_dbuf;
2882 	blkptr_t *obp = &dr->dt.dl.dr_overridden_by;
2883 
2884 	mutex_enter(&db->db_mtx);
2885 	if (!BP_EQUAL(zio->io_bp, obp)) {
2886 		if (!BP_IS_HOLE(obp))
2887 			dsl_free(spa_get_dsl(zio->io_spa), zio->io_txg, obp);
2888 		arc_release(dr->dt.dl.dr_data, db);
2889 	}
2890 	mutex_exit(&db->db_mtx);
2891 
2892 	dbuf_write_done(zio, NULL, db);
2893 }
2894 
2895 /* Issue I/O to commit a dirty buffer to disk. */
2896 static void
2897 dbuf_write(dbuf_dirty_record_t *dr, arc_buf_t *data, dmu_tx_t *tx)
2898 {
2899 	dmu_buf_impl_t *db = dr->dr_dbuf;
2900 	dnode_t *dn;
2901 	objset_t *os;
2902 	dmu_buf_impl_t *parent = db->db_parent;
2903 	uint64_t txg = tx->tx_txg;
2904 	zbookmark_phys_t zb;
2905 	zio_prop_t zp;
2906 	zio_t *zio;
2907 	int wp_flag = 0;
2908 
2909 	DB_DNODE_ENTER(db);
2910 	dn = DB_DNODE(db);
2911 	os = dn->dn_objset;
2912 
2913 	if (db->db_state != DB_NOFILL) {
2914 		if (db->db_level > 0 || dn->dn_type == DMU_OT_DNODE) {
2915 			/*
2916 			 * Private object buffers are released here rather
2917 			 * than in dbuf_dirty() since they are only modified
2918 			 * in the syncing context and we don't want the
2919 			 * overhead of making multiple copies of the data.
2920 			 */
2921 			if (BP_IS_HOLE(db->db_blkptr)) {
2922 				arc_buf_thaw(data);
2923 			} else {
2924 				dbuf_release_bp(db);
2925 			}
2926 		}
2927 	}
2928 
2929 	if (parent != dn->dn_dbuf) {
2930 		/* Our parent is an indirect block. */
2931 		/* We have a dirty parent that has been scheduled for write. */
2932 		ASSERT(parent && parent->db_data_pending);
2933 		/* Our parent's buffer is one level closer to the dnode. */
2934 		ASSERT(db->db_level == parent->db_level-1);
2935 		/*
2936 		 * We're about to modify our parent's db_data by modifying
2937 		 * our block pointer, so the parent must be released.
2938 		 */
2939 		ASSERT(arc_released(parent->db_buf));
2940 		zio = parent->db_data_pending->dr_zio;
2941 	} else {
2942 		/* Our parent is the dnode itself. */
2943 		ASSERT((db->db_level == dn->dn_phys->dn_nlevels-1 &&
2944 		    db->db_blkid != DMU_SPILL_BLKID) ||
2945 		    (db->db_blkid == DMU_SPILL_BLKID && db->db_level == 0));
2946 		if (db->db_blkid != DMU_SPILL_BLKID)
2947 			ASSERT3P(db->db_blkptr, ==,
2948 			    &dn->dn_phys->dn_blkptr[db->db_blkid]);
2949 		zio = dn->dn_zio;
2950 	}
2951 
2952 	ASSERT(db->db_level == 0 || data == db->db_buf);
2953 	ASSERT3U(db->db_blkptr->blk_birth, <=, txg);
2954 	ASSERT(zio);
2955 
2956 	SET_BOOKMARK(&zb, os->os_dsl_dataset ?
2957 	    os->os_dsl_dataset->ds_object : DMU_META_OBJSET,
2958 	    db->db.db_object, db->db_level, db->db_blkid);
2959 
2960 	if (db->db_blkid == DMU_SPILL_BLKID)
2961 		wp_flag = WP_SPILL;
2962 	wp_flag |= (db->db_state == DB_NOFILL) ? WP_NOFILL : 0;
2963 
2964 	dmu_write_policy(os, dn, db->db_level, wp_flag, &zp);
2965 	DB_DNODE_EXIT(db);
2966 
2967 	if (db->db_level == 0 &&
2968 	    dr->dt.dl.dr_override_state == DR_OVERRIDDEN) {
2969 		/*
2970 		 * The BP for this block has been provided by open context
2971 		 * (by dmu_sync() or dmu_buf_write_embedded()).
2972 		 */
2973 		void *contents = (data != NULL) ? data->b_data : NULL;
2974 
2975 		dr->dr_zio = zio_write(zio, os->os_spa, txg,
2976 		    db->db_blkptr, contents, db->db.db_size, &zp,
2977 		    dbuf_write_override_ready, NULL, dbuf_write_override_done,
2978 		    dr, ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
2979 		mutex_enter(&db->db_mtx);
2980 		dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
2981 		zio_write_override(dr->dr_zio, &dr->dt.dl.dr_overridden_by,
2982 		    dr->dt.dl.dr_copies, dr->dt.dl.dr_nopwrite);
2983 		mutex_exit(&db->db_mtx);
2984 	} else if (db->db_state == DB_NOFILL) {
2985 		ASSERT(zp.zp_checksum == ZIO_CHECKSUM_OFF ||
2986 		    zp.zp_checksum == ZIO_CHECKSUM_NOPARITY);
2987 		dr->dr_zio = zio_write(zio, os->os_spa, txg,
2988 		    db->db_blkptr, NULL, db->db.db_size, &zp,
2989 		    dbuf_write_nofill_ready, NULL, dbuf_write_nofill_done, db,
2990 		    ZIO_PRIORITY_ASYNC_WRITE,
2991 		    ZIO_FLAG_MUSTSUCCEED | ZIO_FLAG_NODATA, &zb);
2992 	} else {
2993 		ASSERT(arc_released(data));
2994 		dr->dr_zio = arc_write(zio, os->os_spa, txg,
2995 		    db->db_blkptr, data, DBUF_IS_L2CACHEABLE(db),
2996 		    DBUF_IS_L2COMPRESSIBLE(db), &zp, dbuf_write_ready,
2997 		    dbuf_write_physdone, dbuf_write_done, db,
2998 		    ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
2999 	}
3000 }
3001