xref: /titanic_41/usr/src/uts/common/fs/zfs/dbuf.c (revision d24234c24aeaca4ca56ee3ac2794507968f274c4)
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 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #include <sys/zfs_context.h>
27 #include <sys/dmu.h>
28 #include <sys/dmu_impl.h>
29 #include <sys/dbuf.h>
30 #include <sys/dmu_objset.h>
31 #include <sys/dsl_dataset.h>
32 #include <sys/dsl_dir.h>
33 #include <sys/dmu_tx.h>
34 #include <sys/spa.h>
35 #include <sys/zio.h>
36 #include <sys/dmu_zfetch.h>
37 
38 static void dbuf_destroy(dmu_buf_impl_t *db);
39 static int dbuf_undirty(dmu_buf_impl_t *db, dmu_tx_t *tx);
40 static void dbuf_write(dbuf_dirty_record_t *dr, arc_buf_t *data, dmu_tx_t *tx);
41 
42 /*
43  * Global data structures and functions for the dbuf cache.
44  */
45 static kmem_cache_t *dbuf_cache;
46 
47 /* ARGSUSED */
48 static int
49 dbuf_cons(void *vdb, void *unused, int kmflag)
50 {
51 	dmu_buf_impl_t *db = vdb;
52 	bzero(db, sizeof (dmu_buf_impl_t));
53 
54 	mutex_init(&db->db_mtx, NULL, MUTEX_DEFAULT, NULL);
55 	cv_init(&db->db_changed, NULL, CV_DEFAULT, NULL);
56 	refcount_create(&db->db_holds);
57 	return (0);
58 }
59 
60 /* ARGSUSED */
61 static void
62 dbuf_dest(void *vdb, void *unused)
63 {
64 	dmu_buf_impl_t *db = vdb;
65 	mutex_destroy(&db->db_mtx);
66 	cv_destroy(&db->db_changed);
67 	refcount_destroy(&db->db_holds);
68 }
69 
70 /*
71  * dbuf hash table routines
72  */
73 static dbuf_hash_table_t dbuf_hash_table;
74 
75 static uint64_t dbuf_hash_count;
76 
77 static uint64_t
78 dbuf_hash(void *os, uint64_t obj, uint8_t lvl, uint64_t blkid)
79 {
80 	uintptr_t osv = (uintptr_t)os;
81 	uint64_t crc = -1ULL;
82 
83 	ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
84 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (lvl)) & 0xFF];
85 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (osv >> 6)) & 0xFF];
86 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (obj >> 0)) & 0xFF];
87 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (obj >> 8)) & 0xFF];
88 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (blkid >> 0)) & 0xFF];
89 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (blkid >> 8)) & 0xFF];
90 
91 	crc ^= (osv>>14) ^ (obj>>16) ^ (blkid>>16);
92 
93 	return (crc);
94 }
95 
96 #define	DBUF_HASH(os, obj, level, blkid) dbuf_hash(os, obj, level, blkid);
97 
98 #define	DBUF_EQUAL(dbuf, os, obj, level, blkid)		\
99 	((dbuf)->db.db_object == (obj) &&		\
100 	(dbuf)->db_objset == (os) &&			\
101 	(dbuf)->db_level == (level) &&			\
102 	(dbuf)->db_blkid == (blkid))
103 
104 dmu_buf_impl_t *
105 dbuf_find(dnode_t *dn, uint8_t level, uint64_t blkid)
106 {
107 	dbuf_hash_table_t *h = &dbuf_hash_table;
108 	objset_t *os = dn->dn_objset;
109 	uint64_t obj = dn->dn_object;
110 	uint64_t hv = DBUF_HASH(os, obj, level, blkid);
111 	uint64_t idx = hv & h->hash_table_mask;
112 	dmu_buf_impl_t *db;
113 
114 	mutex_enter(DBUF_HASH_MUTEX(h, idx));
115 	for (db = h->hash_table[idx]; db != NULL; db = db->db_hash_next) {
116 		if (DBUF_EQUAL(db, os, obj, level, blkid)) {
117 			mutex_enter(&db->db_mtx);
118 			if (db->db_state != DB_EVICTING) {
119 				mutex_exit(DBUF_HASH_MUTEX(h, idx));
120 				return (db);
121 			}
122 			mutex_exit(&db->db_mtx);
123 		}
124 	}
125 	mutex_exit(DBUF_HASH_MUTEX(h, idx));
126 	return (NULL);
127 }
128 
129 /*
130  * Insert an entry into the hash table.  If there is already an element
131  * equal to elem in the hash table, then the already existing element
132  * will be returned and the new element will not be inserted.
133  * Otherwise returns NULL.
134  */
135 static dmu_buf_impl_t *
136 dbuf_hash_insert(dmu_buf_impl_t *db)
137 {
138 	dbuf_hash_table_t *h = &dbuf_hash_table;
139 	objset_t *os = db->db_objset;
140 	uint64_t obj = db->db.db_object;
141 	int level = db->db_level;
142 	uint64_t blkid = db->db_blkid;
143 	uint64_t hv = DBUF_HASH(os, obj, level, blkid);
144 	uint64_t idx = hv & h->hash_table_mask;
145 	dmu_buf_impl_t *dbf;
146 
147 	mutex_enter(DBUF_HASH_MUTEX(h, idx));
148 	for (dbf = h->hash_table[idx]; dbf != NULL; dbf = dbf->db_hash_next) {
149 		if (DBUF_EQUAL(dbf, os, obj, level, blkid)) {
150 			mutex_enter(&dbf->db_mtx);
151 			if (dbf->db_state != DB_EVICTING) {
152 				mutex_exit(DBUF_HASH_MUTEX(h, idx));
153 				return (dbf);
154 			}
155 			mutex_exit(&dbf->db_mtx);
156 		}
157 	}
158 
159 	mutex_enter(&db->db_mtx);
160 	db->db_hash_next = h->hash_table[idx];
161 	h->hash_table[idx] = db;
162 	mutex_exit(DBUF_HASH_MUTEX(h, idx));
163 	atomic_add_64(&dbuf_hash_count, 1);
164 
165 	return (NULL);
166 }
167 
168 /*
169  * Remove an entry from the hash table.  This operation will
170  * fail if there are any existing holds on the db.
171  */
172 static void
173 dbuf_hash_remove(dmu_buf_impl_t *db)
174 {
175 	dbuf_hash_table_t *h = &dbuf_hash_table;
176 	uint64_t hv = DBUF_HASH(db->db_objset, db->db.db_object,
177 	    db->db_level, db->db_blkid);
178 	uint64_t idx = hv & h->hash_table_mask;
179 	dmu_buf_impl_t *dbf, **dbp;
180 
181 	/*
182 	 * We musn't hold db_mtx to maintin lock ordering:
183 	 * DBUF_HASH_MUTEX > db_mtx.
184 	 */
185 	ASSERT(refcount_is_zero(&db->db_holds));
186 	ASSERT(db->db_state == DB_EVICTING);
187 	ASSERT(!MUTEX_HELD(&db->db_mtx));
188 
189 	mutex_enter(DBUF_HASH_MUTEX(h, idx));
190 	dbp = &h->hash_table[idx];
191 	while ((dbf = *dbp) != db) {
192 		dbp = &dbf->db_hash_next;
193 		ASSERT(dbf != NULL);
194 	}
195 	*dbp = db->db_hash_next;
196 	db->db_hash_next = NULL;
197 	mutex_exit(DBUF_HASH_MUTEX(h, idx));
198 	atomic_add_64(&dbuf_hash_count, -1);
199 }
200 
201 static arc_evict_func_t dbuf_do_evict;
202 
203 static void
204 dbuf_evict_user(dmu_buf_impl_t *db)
205 {
206 	ASSERT(MUTEX_HELD(&db->db_mtx));
207 
208 	if (db->db_level != 0 || db->db_evict_func == NULL)
209 		return;
210 
211 	if (db->db_user_data_ptr_ptr)
212 		*db->db_user_data_ptr_ptr = db->db.db_data;
213 	db->db_evict_func(&db->db, db->db_user_ptr);
214 	db->db_user_ptr = NULL;
215 	db->db_user_data_ptr_ptr = NULL;
216 	db->db_evict_func = NULL;
217 }
218 
219 void
220 dbuf_evict(dmu_buf_impl_t *db)
221 {
222 	ASSERT(MUTEX_HELD(&db->db_mtx));
223 	ASSERT(db->db_buf == NULL);
224 	ASSERT(db->db_data_pending == NULL);
225 
226 	dbuf_clear(db);
227 	dbuf_destroy(db);
228 }
229 
230 void
231 dbuf_init(void)
232 {
233 	uint64_t hsize = 1ULL << 16;
234 	dbuf_hash_table_t *h = &dbuf_hash_table;
235 	int i;
236 
237 	/*
238 	 * The hash table is big enough to fill all of physical memory
239 	 * with an average 4K block size.  The table will take up
240 	 * totalmem*sizeof(void*)/4K (i.e. 2MB/GB with 8-byte pointers).
241 	 */
242 	while (hsize * 4096 < physmem * PAGESIZE)
243 		hsize <<= 1;
244 
245 retry:
246 	h->hash_table_mask = hsize - 1;
247 	h->hash_table = kmem_zalloc(hsize * sizeof (void *), KM_NOSLEEP);
248 	if (h->hash_table == NULL) {
249 		/* XXX - we should really return an error instead of assert */
250 		ASSERT(hsize > (1ULL << 10));
251 		hsize >>= 1;
252 		goto retry;
253 	}
254 
255 	dbuf_cache = kmem_cache_create("dmu_buf_impl_t",
256 	    sizeof (dmu_buf_impl_t),
257 	    0, dbuf_cons, dbuf_dest, NULL, NULL, NULL, 0);
258 
259 	for (i = 0; i < DBUF_MUTEXES; i++)
260 		mutex_init(&h->hash_mutexes[i], NULL, MUTEX_DEFAULT, NULL);
261 }
262 
263 void
264 dbuf_fini(void)
265 {
266 	dbuf_hash_table_t *h = &dbuf_hash_table;
267 	int i;
268 
269 	for (i = 0; i < DBUF_MUTEXES; i++)
270 		mutex_destroy(&h->hash_mutexes[i]);
271 	kmem_free(h->hash_table, (h->hash_table_mask + 1) * sizeof (void *));
272 	kmem_cache_destroy(dbuf_cache);
273 }
274 
275 /*
276  * Other stuff.
277  */
278 
279 #ifdef ZFS_DEBUG
280 static void
281 dbuf_verify(dmu_buf_impl_t *db)
282 {
283 	dnode_t *dn = db->db_dnode;
284 	dbuf_dirty_record_t *dr;
285 
286 	ASSERT(MUTEX_HELD(&db->db_mtx));
287 
288 	if (!(zfs_flags & ZFS_DEBUG_DBUF_VERIFY))
289 		return;
290 
291 	ASSERT(db->db_objset != NULL);
292 	if (dn == NULL) {
293 		ASSERT(db->db_parent == NULL);
294 		ASSERT(db->db_blkptr == NULL);
295 	} else {
296 		ASSERT3U(db->db.db_object, ==, dn->dn_object);
297 		ASSERT3P(db->db_objset, ==, dn->dn_objset);
298 		ASSERT3U(db->db_level, <, dn->dn_nlevels);
299 		ASSERT(db->db_blkid == DB_BONUS_BLKID ||
300 		    list_head(&dn->dn_dbufs));
301 	}
302 	if (db->db_blkid == DB_BONUS_BLKID) {
303 		ASSERT(dn != NULL);
304 		ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
305 		ASSERT3U(db->db.db_offset, ==, DB_BONUS_BLKID);
306 	} else {
307 		ASSERT3U(db->db.db_offset, ==, db->db_blkid * db->db.db_size);
308 	}
309 
310 	for (dr = db->db_data_pending; dr != NULL; dr = dr->dr_next)
311 		ASSERT(dr->dr_dbuf == db);
312 
313 	for (dr = db->db_last_dirty; dr != NULL; dr = dr->dr_next)
314 		ASSERT(dr->dr_dbuf == db);
315 
316 	/*
317 	 * We can't assert that db_size matches dn_datablksz because it
318 	 * can be momentarily different when another thread is doing
319 	 * dnode_set_blksz().
320 	 */
321 	if (db->db_level == 0 && db->db.db_object == DMU_META_DNODE_OBJECT) {
322 		dr = db->db_data_pending;
323 		/*
324 		 * It should only be modified in syncing context, so
325 		 * make sure we only have one copy of the data.
326 		 */
327 		ASSERT(dr == NULL || dr->dt.dl.dr_data == db->db_buf);
328 	}
329 
330 	/* verify db->db_blkptr */
331 	if (db->db_blkptr) {
332 		if (db->db_parent == dn->dn_dbuf) {
333 			/* db is pointed to by the dnode */
334 			/* ASSERT3U(db->db_blkid, <, dn->dn_nblkptr); */
335 			if (DMU_OBJECT_IS_SPECIAL(db->db.db_object))
336 				ASSERT(db->db_parent == NULL);
337 			else
338 				ASSERT(db->db_parent != NULL);
339 			ASSERT3P(db->db_blkptr, ==,
340 			    &dn->dn_phys->dn_blkptr[db->db_blkid]);
341 		} else {
342 			/* db is pointed to by an indirect block */
343 			int epb = db->db_parent->db.db_size >> SPA_BLKPTRSHIFT;
344 			ASSERT3U(db->db_parent->db_level, ==, db->db_level+1);
345 			ASSERT3U(db->db_parent->db.db_object, ==,
346 			    db->db.db_object);
347 			/*
348 			 * dnode_grow_indblksz() can make this fail if we don't
349 			 * have the struct_rwlock.  XXX indblksz no longer
350 			 * grows.  safe to do this now?
351 			 */
352 			if (RW_WRITE_HELD(&db->db_dnode->dn_struct_rwlock)) {
353 				ASSERT3P(db->db_blkptr, ==,
354 				    ((blkptr_t *)db->db_parent->db.db_data +
355 				    db->db_blkid % epb));
356 			}
357 		}
358 	}
359 	if ((db->db_blkptr == NULL || BP_IS_HOLE(db->db_blkptr)) &&
360 	    db->db.db_data && db->db_blkid != DB_BONUS_BLKID &&
361 	    db->db_state != DB_FILL && !dn->dn_free_txg) {
362 		/*
363 		 * If the blkptr isn't set but they have nonzero data,
364 		 * it had better be dirty, otherwise we'll lose that
365 		 * data when we evict this buffer.
366 		 */
367 		if (db->db_dirtycnt == 0) {
368 			uint64_t *buf = db->db.db_data;
369 			int i;
370 
371 			for (i = 0; i < db->db.db_size >> 3; i++) {
372 				ASSERT(buf[i] == 0);
373 			}
374 		}
375 	}
376 }
377 #endif
378 
379 static void
380 dbuf_update_data(dmu_buf_impl_t *db)
381 {
382 	ASSERT(MUTEX_HELD(&db->db_mtx));
383 	if (db->db_level == 0 && db->db_user_data_ptr_ptr) {
384 		ASSERT(!refcount_is_zero(&db->db_holds));
385 		*db->db_user_data_ptr_ptr = db->db.db_data;
386 	}
387 }
388 
389 static void
390 dbuf_set_data(dmu_buf_impl_t *db, arc_buf_t *buf)
391 {
392 	ASSERT(MUTEX_HELD(&db->db_mtx));
393 	ASSERT(db->db_buf == NULL || !arc_has_callback(db->db_buf));
394 	db->db_buf = buf;
395 	if (buf != NULL) {
396 		ASSERT(buf->b_data != NULL);
397 		db->db.db_data = buf->b_data;
398 		if (!arc_released(buf))
399 			arc_set_callback(buf, dbuf_do_evict, db);
400 		dbuf_update_data(db);
401 	} else {
402 		dbuf_evict_user(db);
403 		db->db.db_data = NULL;
404 		if (db->db_state != DB_NOFILL)
405 			db->db_state = DB_UNCACHED;
406 	}
407 }
408 
409 uint64_t
410 dbuf_whichblock(dnode_t *dn, uint64_t offset)
411 {
412 	if (dn->dn_datablkshift) {
413 		return (offset >> dn->dn_datablkshift);
414 	} else {
415 		ASSERT3U(offset, <, dn->dn_datablksz);
416 		return (0);
417 	}
418 }
419 
420 static void
421 dbuf_read_done(zio_t *zio, arc_buf_t *buf, void *vdb)
422 {
423 	dmu_buf_impl_t *db = vdb;
424 
425 	mutex_enter(&db->db_mtx);
426 	ASSERT3U(db->db_state, ==, DB_READ);
427 	/*
428 	 * All reads are synchronous, so we must have a hold on the dbuf
429 	 */
430 	ASSERT(refcount_count(&db->db_holds) > 0);
431 	ASSERT(db->db_buf == NULL);
432 	ASSERT(db->db.db_data == NULL);
433 	if (db->db_level == 0 && db->db_freed_in_flight) {
434 		/* we were freed in flight; disregard any error */
435 		arc_release(buf, db);
436 		bzero(buf->b_data, db->db.db_size);
437 		arc_buf_freeze(buf);
438 		db->db_freed_in_flight = FALSE;
439 		dbuf_set_data(db, buf);
440 		db->db_state = DB_CACHED;
441 	} else if (zio == NULL || zio->io_error == 0) {
442 		dbuf_set_data(db, buf);
443 		db->db_state = DB_CACHED;
444 	} else {
445 		ASSERT(db->db_blkid != DB_BONUS_BLKID);
446 		ASSERT3P(db->db_buf, ==, NULL);
447 		VERIFY(arc_buf_remove_ref(buf, db) == 1);
448 		db->db_state = DB_UNCACHED;
449 	}
450 	cv_broadcast(&db->db_changed);
451 	mutex_exit(&db->db_mtx);
452 	dbuf_rele(db, NULL);
453 }
454 
455 static void
456 dbuf_read_impl(dmu_buf_impl_t *db, zio_t *zio, uint32_t *flags)
457 {
458 	dnode_t *dn = db->db_dnode;
459 	zbookmark_t zb;
460 	uint32_t aflags = ARC_NOWAIT;
461 	arc_buf_t *pbuf;
462 
463 	ASSERT(!refcount_is_zero(&db->db_holds));
464 	/* We need the struct_rwlock to prevent db_blkptr from changing. */
465 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
466 	ASSERT(MUTEX_HELD(&db->db_mtx));
467 	ASSERT(db->db_state == DB_UNCACHED);
468 	ASSERT(db->db_buf == NULL);
469 
470 	if (db->db_blkid == DB_BONUS_BLKID) {
471 		int bonuslen = MIN(dn->dn_bonuslen, dn->dn_phys->dn_bonuslen);
472 
473 		ASSERT3U(bonuslen, <=, db->db.db_size);
474 		db->db.db_data = zio_buf_alloc(DN_MAX_BONUSLEN);
475 		arc_space_consume(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
476 		if (bonuslen < DN_MAX_BONUSLEN)
477 			bzero(db->db.db_data, DN_MAX_BONUSLEN);
478 		if (bonuslen)
479 			bcopy(DN_BONUS(dn->dn_phys), db->db.db_data, bonuslen);
480 		dbuf_update_data(db);
481 		db->db_state = DB_CACHED;
482 		mutex_exit(&db->db_mtx);
483 		return;
484 	}
485 
486 	/*
487 	 * Recheck BP_IS_HOLE() after dnode_block_freed() in case dnode_sync()
488 	 * processes the delete record and clears the bp while we are waiting
489 	 * for the dn_mtx (resulting in a "no" from block_freed).
490 	 */
491 	if (db->db_blkptr == NULL || BP_IS_HOLE(db->db_blkptr) ||
492 	    (db->db_level == 0 && (dnode_block_freed(dn, db->db_blkid) ||
493 	    BP_IS_HOLE(db->db_blkptr)))) {
494 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
495 
496 		dbuf_set_data(db, arc_buf_alloc(dn->dn_objset->os_spa,
497 		    db->db.db_size, db, type));
498 		bzero(db->db.db_data, db->db.db_size);
499 		db->db_state = DB_CACHED;
500 		*flags |= DB_RF_CACHED;
501 		mutex_exit(&db->db_mtx);
502 		return;
503 	}
504 
505 	db->db_state = DB_READ;
506 	mutex_exit(&db->db_mtx);
507 
508 	if (DBUF_IS_L2CACHEABLE(db))
509 		aflags |= ARC_L2CACHE;
510 
511 	SET_BOOKMARK(&zb, db->db_objset->os_dsl_dataset ?
512 	    db->db_objset->os_dsl_dataset->ds_object : DMU_META_OBJSET,
513 	    db->db.db_object, db->db_level, db->db_blkid);
514 
515 	dbuf_add_ref(db, NULL);
516 	/* ZIO_FLAG_CANFAIL callers have to check the parent zio's error */
517 
518 	if (db->db_parent)
519 		pbuf = db->db_parent->db_buf;
520 	else
521 		pbuf = db->db_objset->os_phys_buf;
522 
523 	(void) arc_read(zio, dn->dn_objset->os_spa, db->db_blkptr, pbuf,
524 	    dbuf_read_done, db, ZIO_PRIORITY_SYNC_READ,
525 	    (*flags & DB_RF_CANFAIL) ? ZIO_FLAG_CANFAIL : ZIO_FLAG_MUSTSUCCEED,
526 	    &aflags, &zb);
527 	if (aflags & ARC_CACHED)
528 		*flags |= DB_RF_CACHED;
529 }
530 
531 int
532 dbuf_read(dmu_buf_impl_t *db, zio_t *zio, uint32_t flags)
533 {
534 	int err = 0;
535 	int havepzio = (zio != NULL);
536 	int prefetch;
537 
538 	/*
539 	 * We don't have to hold the mutex to check db_state because it
540 	 * can't be freed while we have a hold on the buffer.
541 	 */
542 	ASSERT(!refcount_is_zero(&db->db_holds));
543 
544 	if (db->db_state == DB_NOFILL)
545 		return (EIO);
546 
547 	if ((flags & DB_RF_HAVESTRUCT) == 0)
548 		rw_enter(&db->db_dnode->dn_struct_rwlock, RW_READER);
549 
550 	prefetch = db->db_level == 0 && db->db_blkid != DB_BONUS_BLKID &&
551 	    (flags & DB_RF_NOPREFETCH) == 0 && db->db_dnode != NULL &&
552 	    DBUF_IS_CACHEABLE(db);
553 
554 	mutex_enter(&db->db_mtx);
555 	if (db->db_state == DB_CACHED) {
556 		mutex_exit(&db->db_mtx);
557 		if (prefetch)
558 			dmu_zfetch(&db->db_dnode->dn_zfetch, db->db.db_offset,
559 			    db->db.db_size, TRUE);
560 		if ((flags & DB_RF_HAVESTRUCT) == 0)
561 			rw_exit(&db->db_dnode->dn_struct_rwlock);
562 	} else if (db->db_state == DB_UNCACHED) {
563 		if (zio == NULL) {
564 			zio = zio_root(db->db_dnode->dn_objset->os_spa,
565 			    NULL, NULL, ZIO_FLAG_CANFAIL);
566 		}
567 		dbuf_read_impl(db, zio, &flags);
568 
569 		/* dbuf_read_impl has dropped db_mtx for us */
570 
571 		if (prefetch)
572 			dmu_zfetch(&db->db_dnode->dn_zfetch, db->db.db_offset,
573 			    db->db.db_size, flags & DB_RF_CACHED);
574 
575 		if ((flags & DB_RF_HAVESTRUCT) == 0)
576 			rw_exit(&db->db_dnode->dn_struct_rwlock);
577 
578 		if (!havepzio)
579 			err = zio_wait(zio);
580 	} else {
581 		mutex_exit(&db->db_mtx);
582 		if (prefetch)
583 			dmu_zfetch(&db->db_dnode->dn_zfetch, db->db.db_offset,
584 			    db->db.db_size, TRUE);
585 		if ((flags & DB_RF_HAVESTRUCT) == 0)
586 			rw_exit(&db->db_dnode->dn_struct_rwlock);
587 
588 		mutex_enter(&db->db_mtx);
589 		if ((flags & DB_RF_NEVERWAIT) == 0) {
590 			while (db->db_state == DB_READ ||
591 			    db->db_state == DB_FILL) {
592 				ASSERT(db->db_state == DB_READ ||
593 				    (flags & DB_RF_HAVESTRUCT) == 0);
594 				cv_wait(&db->db_changed, &db->db_mtx);
595 			}
596 			if (db->db_state == DB_UNCACHED)
597 				err = EIO;
598 		}
599 		mutex_exit(&db->db_mtx);
600 	}
601 
602 	ASSERT(err || havepzio || db->db_state == DB_CACHED);
603 	return (err);
604 }
605 
606 static void
607 dbuf_noread(dmu_buf_impl_t *db)
608 {
609 	ASSERT(!refcount_is_zero(&db->db_holds));
610 	ASSERT(db->db_blkid != DB_BONUS_BLKID);
611 	mutex_enter(&db->db_mtx);
612 	while (db->db_state == DB_READ || db->db_state == DB_FILL)
613 		cv_wait(&db->db_changed, &db->db_mtx);
614 	if (db->db_state == DB_UNCACHED) {
615 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
616 
617 		ASSERT(db->db_buf == NULL);
618 		ASSERT(db->db.db_data == NULL);
619 		dbuf_set_data(db, arc_buf_alloc(db->db_dnode->dn_objset->os_spa,
620 		    db->db.db_size, db, type));
621 		db->db_state = DB_FILL;
622 	} else if (db->db_state == DB_NOFILL) {
623 		dbuf_set_data(db, NULL);
624 	} else {
625 		ASSERT3U(db->db_state, ==, DB_CACHED);
626 	}
627 	mutex_exit(&db->db_mtx);
628 }
629 
630 /*
631  * This is our just-in-time copy function.  It makes a copy of
632  * buffers, that have been modified in a previous transaction
633  * group, before we modify them in the current active group.
634  *
635  * This function is used in two places: when we are dirtying a
636  * buffer for the first time in a txg, and when we are freeing
637  * a range in a dnode that includes this buffer.
638  *
639  * Note that when we are called from dbuf_free_range() we do
640  * not put a hold on the buffer, we just traverse the active
641  * dbuf list for the dnode.
642  */
643 static void
644 dbuf_fix_old_data(dmu_buf_impl_t *db, uint64_t txg)
645 {
646 	dbuf_dirty_record_t *dr = db->db_last_dirty;
647 
648 	ASSERT(MUTEX_HELD(&db->db_mtx));
649 	ASSERT(db->db.db_data != NULL);
650 	ASSERT(db->db_level == 0);
651 	ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT);
652 
653 	if (dr == NULL ||
654 	    (dr->dt.dl.dr_data !=
655 	    ((db->db_blkid  == DB_BONUS_BLKID) ? db->db.db_data : db->db_buf)))
656 		return;
657 
658 	/*
659 	 * If the last dirty record for this dbuf has not yet synced
660 	 * and its referencing the dbuf data, either:
661 	 * 	reset the reference to point to a new copy,
662 	 * or (if there a no active holders)
663 	 *	just null out the current db_data pointer.
664 	 */
665 	ASSERT(dr->dr_txg >= txg - 2);
666 	if (db->db_blkid == DB_BONUS_BLKID) {
667 		/* Note that the data bufs here are zio_bufs */
668 		dr->dt.dl.dr_data = zio_buf_alloc(DN_MAX_BONUSLEN);
669 		arc_space_consume(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
670 		bcopy(db->db.db_data, dr->dt.dl.dr_data, DN_MAX_BONUSLEN);
671 	} else if (refcount_count(&db->db_holds) > db->db_dirtycnt) {
672 		int size = db->db.db_size;
673 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
674 		dr->dt.dl.dr_data = arc_buf_alloc(
675 		    db->db_dnode->dn_objset->os_spa, size, db, type);
676 		bcopy(db->db.db_data, dr->dt.dl.dr_data->b_data, size);
677 	} else {
678 		dbuf_set_data(db, NULL);
679 	}
680 }
681 
682 void
683 dbuf_unoverride(dbuf_dirty_record_t *dr)
684 {
685 	dmu_buf_impl_t *db = dr->dr_dbuf;
686 	blkptr_t *bp = &dr->dt.dl.dr_overridden_by;
687 	uint64_t txg = dr->dr_txg;
688 
689 	ASSERT(MUTEX_HELD(&db->db_mtx));
690 	ASSERT(dr->dt.dl.dr_override_state != DR_IN_DMU_SYNC);
691 	ASSERT(db->db_level == 0);
692 
693 	if (db->db_blkid == DB_BONUS_BLKID ||
694 	    dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN)
695 		return;
696 
697 	ASSERT(db->db_data_pending != dr);
698 
699 	/* free this block */
700 	if (!BP_IS_HOLE(bp))
701 		dsl_free(spa_get_dsl(db->db_dnode->dn_objset->os_spa), txg, bp);
702 
703 	dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
704 	/*
705 	 * Release the already-written buffer, so we leave it in
706 	 * a consistent dirty state.  Note that all callers are
707 	 * modifying the buffer, so they will immediately do
708 	 * another (redundant) arc_release().  Therefore, leave
709 	 * the buf thawed to save the effort of freezing &
710 	 * immediately re-thawing it.
711 	 */
712 	arc_release(dr->dt.dl.dr_data, db);
713 }
714 
715 /*
716  * Evict (if its unreferenced) or clear (if its referenced) any level-0
717  * data blocks in the free range, so that any future readers will find
718  * empty blocks.  Also, if we happen accross any level-1 dbufs in the
719  * range that have not already been marked dirty, mark them dirty so
720  * they stay in memory.
721  */
722 void
723 dbuf_free_range(dnode_t *dn, uint64_t start, uint64_t end, dmu_tx_t *tx)
724 {
725 	dmu_buf_impl_t *db, *db_next;
726 	uint64_t txg = tx->tx_txg;
727 	int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
728 	uint64_t first_l1 = start >> epbs;
729 	uint64_t last_l1 = end >> epbs;
730 
731 	if (end > dn->dn_maxblkid) {
732 		end = dn->dn_maxblkid;
733 		last_l1 = end >> epbs;
734 	}
735 	dprintf_dnode(dn, "start=%llu end=%llu\n", start, end);
736 	mutex_enter(&dn->dn_dbufs_mtx);
737 	for (db = list_head(&dn->dn_dbufs); db; db = db_next) {
738 		db_next = list_next(&dn->dn_dbufs, db);
739 		ASSERT(db->db_blkid != DB_BONUS_BLKID);
740 
741 		if (db->db_level == 1 &&
742 		    db->db_blkid >= first_l1 && db->db_blkid <= last_l1) {
743 			mutex_enter(&db->db_mtx);
744 			if (db->db_last_dirty &&
745 			    db->db_last_dirty->dr_txg < txg) {
746 				dbuf_add_ref(db, FTAG);
747 				mutex_exit(&db->db_mtx);
748 				dbuf_will_dirty(db, tx);
749 				dbuf_rele(db, FTAG);
750 			} else {
751 				mutex_exit(&db->db_mtx);
752 			}
753 		}
754 
755 		if (db->db_level != 0)
756 			continue;
757 		dprintf_dbuf(db, "found buf %s\n", "");
758 		if (db->db_blkid < start || db->db_blkid > end)
759 			continue;
760 
761 		/* found a level 0 buffer in the range */
762 		if (dbuf_undirty(db, tx))
763 			continue;
764 
765 		mutex_enter(&db->db_mtx);
766 		if (db->db_state == DB_UNCACHED ||
767 		    db->db_state == DB_NOFILL ||
768 		    db->db_state == DB_EVICTING) {
769 			ASSERT(db->db.db_data == NULL);
770 			mutex_exit(&db->db_mtx);
771 			continue;
772 		}
773 		if (db->db_state == DB_READ || db->db_state == DB_FILL) {
774 			/* will be handled in dbuf_read_done or dbuf_rele */
775 			db->db_freed_in_flight = TRUE;
776 			mutex_exit(&db->db_mtx);
777 			continue;
778 		}
779 		if (refcount_count(&db->db_holds) == 0) {
780 			ASSERT(db->db_buf);
781 			dbuf_clear(db);
782 			continue;
783 		}
784 		/* The dbuf is referenced */
785 
786 		if (db->db_last_dirty != NULL) {
787 			dbuf_dirty_record_t *dr = db->db_last_dirty;
788 
789 			if (dr->dr_txg == txg) {
790 				/*
791 				 * This buffer is "in-use", re-adjust the file
792 				 * size to reflect that this buffer may
793 				 * contain new data when we sync.
794 				 */
795 				if (db->db_blkid > dn->dn_maxblkid)
796 					dn->dn_maxblkid = db->db_blkid;
797 				dbuf_unoverride(dr);
798 			} else {
799 				/*
800 				 * This dbuf is not dirty in the open context.
801 				 * Either uncache it (if its not referenced in
802 				 * the open context) or reset its contents to
803 				 * empty.
804 				 */
805 				dbuf_fix_old_data(db, txg);
806 			}
807 		}
808 		/* clear the contents if its cached */
809 		if (db->db_state == DB_CACHED) {
810 			ASSERT(db->db.db_data != NULL);
811 			arc_release(db->db_buf, db);
812 			bzero(db->db.db_data, db->db.db_size);
813 			arc_buf_freeze(db->db_buf);
814 		}
815 
816 		mutex_exit(&db->db_mtx);
817 	}
818 	mutex_exit(&dn->dn_dbufs_mtx);
819 }
820 
821 static int
822 dbuf_block_freeable(dmu_buf_impl_t *db)
823 {
824 	dsl_dataset_t *ds = db->db_objset->os_dsl_dataset;
825 	uint64_t birth_txg = 0;
826 
827 	/*
828 	 * We don't need any locking to protect db_blkptr:
829 	 * If it's syncing, then db_last_dirty will be set
830 	 * so we'll ignore db_blkptr.
831 	 */
832 	ASSERT(MUTEX_HELD(&db->db_mtx));
833 	if (db->db_last_dirty)
834 		birth_txg = db->db_last_dirty->dr_txg;
835 	else if (db->db_blkptr)
836 		birth_txg = db->db_blkptr->blk_birth;
837 
838 	/* If we don't exist or are in a snapshot, we can't be freed */
839 	if (birth_txg)
840 		return (ds == NULL ||
841 		    dsl_dataset_block_freeable(ds, birth_txg));
842 	else
843 		return (FALSE);
844 }
845 
846 void
847 dbuf_new_size(dmu_buf_impl_t *db, int size, dmu_tx_t *tx)
848 {
849 	arc_buf_t *buf, *obuf;
850 	int osize = db->db.db_size;
851 	arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
852 
853 	ASSERT(db->db_blkid != DB_BONUS_BLKID);
854 
855 	/* XXX does *this* func really need the lock? */
856 	ASSERT(RW_WRITE_HELD(&db->db_dnode->dn_struct_rwlock));
857 
858 	/*
859 	 * This call to dbuf_will_dirty() with the dn_struct_rwlock held
860 	 * is OK, because there can be no other references to the db
861 	 * when we are changing its size, so no concurrent DB_FILL can
862 	 * be happening.
863 	 */
864 	/*
865 	 * XXX we should be doing a dbuf_read, checking the return
866 	 * value and returning that up to our callers
867 	 */
868 	dbuf_will_dirty(db, tx);
869 
870 	/* create the data buffer for the new block */
871 	buf = arc_buf_alloc(db->db_dnode->dn_objset->os_spa, size, db, type);
872 
873 	/* copy old block data to the new block */
874 	obuf = db->db_buf;
875 	bcopy(obuf->b_data, buf->b_data, MIN(osize, size));
876 	/* zero the remainder */
877 	if (size > osize)
878 		bzero((uint8_t *)buf->b_data + osize, size - osize);
879 
880 	mutex_enter(&db->db_mtx);
881 	dbuf_set_data(db, buf);
882 	VERIFY(arc_buf_remove_ref(obuf, db) == 1);
883 	db->db.db_size = size;
884 
885 	if (db->db_level == 0) {
886 		ASSERT3U(db->db_last_dirty->dr_txg, ==, tx->tx_txg);
887 		db->db_last_dirty->dt.dl.dr_data = buf;
888 	}
889 	mutex_exit(&db->db_mtx);
890 
891 	dnode_willuse_space(db->db_dnode, size-osize, tx);
892 }
893 
894 dbuf_dirty_record_t *
895 dbuf_dirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
896 {
897 	dnode_t *dn = db->db_dnode;
898 	objset_t *os = dn->dn_objset;
899 	dbuf_dirty_record_t **drp, *dr;
900 	int drop_struct_lock = FALSE;
901 	boolean_t do_free_accounting = B_FALSE;
902 	int txgoff = tx->tx_txg & TXG_MASK;
903 
904 	ASSERT(tx->tx_txg != 0);
905 	ASSERT(!refcount_is_zero(&db->db_holds));
906 	DMU_TX_DIRTY_BUF(tx, db);
907 
908 	/*
909 	 * Shouldn't dirty a regular buffer in syncing context.  Private
910 	 * objects may be dirtied in syncing context, but only if they
911 	 * were already pre-dirtied in open context.
912 	 */
913 	ASSERT(!dmu_tx_is_syncing(tx) ||
914 	    BP_IS_HOLE(dn->dn_objset->os_rootbp) ||
915 	    DMU_OBJECT_IS_SPECIAL(dn->dn_object) ||
916 	    dn->dn_objset->os_dsl_dataset == NULL);
917 	/*
918 	 * We make this assert for private objects as well, but after we
919 	 * check if we're already dirty.  They are allowed to re-dirty
920 	 * in syncing context.
921 	 */
922 	ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
923 	    dn->dn_dirtyctx == DN_UNDIRTIED || dn->dn_dirtyctx ==
924 	    (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN));
925 
926 	mutex_enter(&db->db_mtx);
927 	/*
928 	 * XXX make this true for indirects too?  The problem is that
929 	 * transactions created with dmu_tx_create_assigned() from
930 	 * syncing context don't bother holding ahead.
931 	 */
932 	ASSERT(db->db_level != 0 ||
933 	    db->db_state == DB_CACHED || db->db_state == DB_FILL ||
934 	    db->db_state == DB_NOFILL);
935 
936 	mutex_enter(&dn->dn_mtx);
937 	/*
938 	 * Don't set dirtyctx to SYNC if we're just modifying this as we
939 	 * initialize the objset.
940 	 */
941 	if (dn->dn_dirtyctx == DN_UNDIRTIED &&
942 	    !BP_IS_HOLE(dn->dn_objset->os_rootbp)) {
943 		dn->dn_dirtyctx =
944 		    (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN);
945 		ASSERT(dn->dn_dirtyctx_firstset == NULL);
946 		dn->dn_dirtyctx_firstset = kmem_alloc(1, KM_SLEEP);
947 	}
948 	mutex_exit(&dn->dn_mtx);
949 
950 	/*
951 	 * If this buffer is already dirty, we're done.
952 	 */
953 	drp = &db->db_last_dirty;
954 	ASSERT(*drp == NULL || (*drp)->dr_txg <= tx->tx_txg ||
955 	    db->db.db_object == DMU_META_DNODE_OBJECT);
956 	while ((dr = *drp) != NULL && dr->dr_txg > tx->tx_txg)
957 		drp = &dr->dr_next;
958 	if (dr && dr->dr_txg == tx->tx_txg) {
959 		if (db->db_level == 0 && db->db_blkid != DB_BONUS_BLKID) {
960 			/*
961 			 * If this buffer has already been written out,
962 			 * we now need to reset its state.
963 			 */
964 			dbuf_unoverride(dr);
965 			if (db->db.db_object != DMU_META_DNODE_OBJECT &&
966 			    db->db_state != DB_NOFILL)
967 				arc_buf_thaw(db->db_buf);
968 		}
969 		mutex_exit(&db->db_mtx);
970 		return (dr);
971 	}
972 
973 	/*
974 	 * Only valid if not already dirty.
975 	 */
976 	ASSERT(dn->dn_object == 0 ||
977 	    dn->dn_dirtyctx == DN_UNDIRTIED || dn->dn_dirtyctx ==
978 	    (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN));
979 
980 	ASSERT3U(dn->dn_nlevels, >, db->db_level);
981 	ASSERT((dn->dn_phys->dn_nlevels == 0 && db->db_level == 0) ||
982 	    dn->dn_phys->dn_nlevels > db->db_level ||
983 	    dn->dn_next_nlevels[txgoff] > db->db_level ||
984 	    dn->dn_next_nlevels[(tx->tx_txg-1) & TXG_MASK] > db->db_level ||
985 	    dn->dn_next_nlevels[(tx->tx_txg-2) & TXG_MASK] > db->db_level);
986 
987 	/*
988 	 * We should only be dirtying in syncing context if it's the
989 	 * mos or we're initializing the os or it's a special object.
990 	 * However, we are allowed to dirty in syncing context provided
991 	 * we already dirtied it in open context.  Hence we must make
992 	 * this assertion only if we're not already dirty.
993 	 */
994 	ASSERT(!dmu_tx_is_syncing(tx) || DMU_OBJECT_IS_SPECIAL(dn->dn_object) ||
995 	    os->os_dsl_dataset == NULL || BP_IS_HOLE(os->os_rootbp));
996 	ASSERT(db->db.db_size != 0);
997 
998 	dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
999 
1000 	if (db->db_blkid != DB_BONUS_BLKID) {
1001 		/*
1002 		 * Update the accounting.
1003 		 * Note: we delay "free accounting" until after we drop
1004 		 * the db_mtx.  This keeps us from grabbing other locks
1005 		 * (and possibly deadlocking) in bp_get_dsize() while
1006 		 * also holding the db_mtx.
1007 		 */
1008 		dnode_willuse_space(dn, db->db.db_size, tx);
1009 		do_free_accounting = dbuf_block_freeable(db);
1010 	}
1011 
1012 	/*
1013 	 * If this buffer is dirty in an old transaction group we need
1014 	 * to make a copy of it so that the changes we make in this
1015 	 * transaction group won't leak out when we sync the older txg.
1016 	 */
1017 	dr = kmem_zalloc(sizeof (dbuf_dirty_record_t), KM_SLEEP);
1018 	if (db->db_level == 0) {
1019 		void *data_old = db->db_buf;
1020 
1021 		if (db->db_state != DB_NOFILL) {
1022 			if (db->db_blkid == DB_BONUS_BLKID) {
1023 				dbuf_fix_old_data(db, tx->tx_txg);
1024 				data_old = db->db.db_data;
1025 			} else if (db->db.db_object != DMU_META_DNODE_OBJECT) {
1026 				/*
1027 				 * Release the data buffer from the cache so
1028 				 * that we can modify it without impacting
1029 				 * possible other users of this cached data
1030 				 * block.  Note that indirect blocks and
1031 				 * private objects are not released until the
1032 				 * syncing state (since they are only modified
1033 				 * then).
1034 				 */
1035 				arc_release(db->db_buf, db);
1036 				dbuf_fix_old_data(db, tx->tx_txg);
1037 				data_old = db->db_buf;
1038 			}
1039 			ASSERT(data_old != NULL);
1040 		}
1041 		dr->dt.dl.dr_data = data_old;
1042 	} else {
1043 		mutex_init(&dr->dt.di.dr_mtx, NULL, MUTEX_DEFAULT, NULL);
1044 		list_create(&dr->dt.di.dr_children,
1045 		    sizeof (dbuf_dirty_record_t),
1046 		    offsetof(dbuf_dirty_record_t, dr_dirty_node));
1047 	}
1048 	dr->dr_dbuf = db;
1049 	dr->dr_txg = tx->tx_txg;
1050 	dr->dr_next = *drp;
1051 	*drp = dr;
1052 
1053 	/*
1054 	 * We could have been freed_in_flight between the dbuf_noread
1055 	 * and dbuf_dirty.  We win, as though the dbuf_noread() had
1056 	 * happened after the free.
1057 	 */
1058 	if (db->db_level == 0 && db->db_blkid != DB_BONUS_BLKID) {
1059 		mutex_enter(&dn->dn_mtx);
1060 		dnode_clear_range(dn, db->db_blkid, 1, tx);
1061 		mutex_exit(&dn->dn_mtx);
1062 		db->db_freed_in_flight = FALSE;
1063 	}
1064 
1065 	/*
1066 	 * This buffer is now part of this txg
1067 	 */
1068 	dbuf_add_ref(db, (void *)(uintptr_t)tx->tx_txg);
1069 	db->db_dirtycnt += 1;
1070 	ASSERT3U(db->db_dirtycnt, <=, 3);
1071 
1072 	mutex_exit(&db->db_mtx);
1073 
1074 	if (db->db_blkid == DB_BONUS_BLKID) {
1075 		mutex_enter(&dn->dn_mtx);
1076 		ASSERT(!list_link_active(&dr->dr_dirty_node));
1077 		list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
1078 		mutex_exit(&dn->dn_mtx);
1079 		dnode_setdirty(dn, tx);
1080 		return (dr);
1081 	} else if (do_free_accounting) {
1082 		blkptr_t *bp = db->db_blkptr;
1083 		int64_t willfree = (bp && !BP_IS_HOLE(bp)) ?
1084 		    bp_get_dsize(os->os_spa, bp) : db->db.db_size;
1085 		/*
1086 		 * This is only a guess -- if the dbuf is dirty
1087 		 * in a previous txg, we don't know how much
1088 		 * space it will use on disk yet.  We should
1089 		 * really have the struct_rwlock to access
1090 		 * db_blkptr, but since this is just a guess,
1091 		 * it's OK if we get an odd answer.
1092 		 */
1093 		dnode_willuse_space(dn, -willfree, tx);
1094 	}
1095 
1096 	if (!RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
1097 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
1098 		drop_struct_lock = TRUE;
1099 	}
1100 
1101 	if (db->db_level == 0) {
1102 		dnode_new_blkid(dn, db->db_blkid, tx, drop_struct_lock);
1103 		ASSERT(dn->dn_maxblkid >= db->db_blkid);
1104 	}
1105 
1106 	if (db->db_level+1 < dn->dn_nlevels) {
1107 		dmu_buf_impl_t *parent = db->db_parent;
1108 		dbuf_dirty_record_t *di;
1109 		int parent_held = FALSE;
1110 
1111 		if (db->db_parent == NULL || db->db_parent == dn->dn_dbuf) {
1112 			int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
1113 
1114 			parent = dbuf_hold_level(dn, db->db_level+1,
1115 			    db->db_blkid >> epbs, FTAG);
1116 			parent_held = TRUE;
1117 		}
1118 		if (drop_struct_lock)
1119 			rw_exit(&dn->dn_struct_rwlock);
1120 		ASSERT3U(db->db_level+1, ==, parent->db_level);
1121 		di = dbuf_dirty(parent, tx);
1122 		if (parent_held)
1123 			dbuf_rele(parent, FTAG);
1124 
1125 		mutex_enter(&db->db_mtx);
1126 		/*  possible race with dbuf_undirty() */
1127 		if (db->db_last_dirty == dr ||
1128 		    dn->dn_object == DMU_META_DNODE_OBJECT) {
1129 			mutex_enter(&di->dt.di.dr_mtx);
1130 			ASSERT3U(di->dr_txg, ==, tx->tx_txg);
1131 			ASSERT(!list_link_active(&dr->dr_dirty_node));
1132 			list_insert_tail(&di->dt.di.dr_children, dr);
1133 			mutex_exit(&di->dt.di.dr_mtx);
1134 			dr->dr_parent = di;
1135 		}
1136 		mutex_exit(&db->db_mtx);
1137 	} else {
1138 		ASSERT(db->db_level+1 == dn->dn_nlevels);
1139 		ASSERT(db->db_blkid < dn->dn_nblkptr);
1140 		ASSERT(db->db_parent == NULL ||
1141 		    db->db_parent == db->db_dnode->dn_dbuf);
1142 		mutex_enter(&dn->dn_mtx);
1143 		ASSERT(!list_link_active(&dr->dr_dirty_node));
1144 		list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
1145 		mutex_exit(&dn->dn_mtx);
1146 		if (drop_struct_lock)
1147 			rw_exit(&dn->dn_struct_rwlock);
1148 	}
1149 
1150 	dnode_setdirty(dn, tx);
1151 	return (dr);
1152 }
1153 
1154 static int
1155 dbuf_undirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
1156 {
1157 	dnode_t *dn = db->db_dnode;
1158 	uint64_t txg = tx->tx_txg;
1159 	dbuf_dirty_record_t *dr, **drp;
1160 
1161 	ASSERT(txg != 0);
1162 	ASSERT(db->db_blkid != DB_BONUS_BLKID);
1163 
1164 	mutex_enter(&db->db_mtx);
1165 
1166 	/*
1167 	 * If this buffer is not dirty, we're done.
1168 	 */
1169 	for (drp = &db->db_last_dirty; (dr = *drp) != NULL; drp = &dr->dr_next)
1170 		if (dr->dr_txg <= txg)
1171 			break;
1172 	if (dr == NULL || dr->dr_txg < txg) {
1173 		mutex_exit(&db->db_mtx);
1174 		return (0);
1175 	}
1176 	ASSERT(dr->dr_txg == txg);
1177 	ASSERT(dr->dr_dbuf == db);
1178 
1179 	/*
1180 	 * If this buffer is currently held, we cannot undirty
1181 	 * it, since one of the current holders may be in the
1182 	 * middle of an update.  Note that users of dbuf_undirty()
1183 	 * should not place a hold on the dbuf before the call.
1184 	 */
1185 	if (refcount_count(&db->db_holds) > db->db_dirtycnt) {
1186 		mutex_exit(&db->db_mtx);
1187 		/* Make sure we don't toss this buffer at sync phase */
1188 		mutex_enter(&dn->dn_mtx);
1189 		dnode_clear_range(dn, db->db_blkid, 1, tx);
1190 		mutex_exit(&dn->dn_mtx);
1191 		return (0);
1192 	}
1193 
1194 	dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
1195 
1196 	ASSERT(db->db.db_size != 0);
1197 
1198 	/* XXX would be nice to fix up dn_towrite_space[] */
1199 
1200 	*drp = dr->dr_next;
1201 
1202 	if (dr->dr_parent) {
1203 		mutex_enter(&dr->dr_parent->dt.di.dr_mtx);
1204 		list_remove(&dr->dr_parent->dt.di.dr_children, dr);
1205 		mutex_exit(&dr->dr_parent->dt.di.dr_mtx);
1206 	} else if (db->db_level+1 == dn->dn_nlevels) {
1207 		ASSERT(db->db_blkptr == NULL || db->db_parent == dn->dn_dbuf);
1208 		mutex_enter(&dn->dn_mtx);
1209 		list_remove(&dn->dn_dirty_records[txg & TXG_MASK], dr);
1210 		mutex_exit(&dn->dn_mtx);
1211 	}
1212 
1213 	if (db->db_level == 0) {
1214 		if (db->db_state != DB_NOFILL) {
1215 			dbuf_unoverride(dr);
1216 
1217 			ASSERT(db->db_buf != NULL);
1218 			ASSERT(dr->dt.dl.dr_data != NULL);
1219 			if (dr->dt.dl.dr_data != db->db_buf)
1220 				VERIFY(arc_buf_remove_ref(dr->dt.dl.dr_data,
1221 				    db) == 1);
1222 		}
1223 	} else {
1224 		ASSERT(db->db_buf != NULL);
1225 		ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
1226 		mutex_destroy(&dr->dt.di.dr_mtx);
1227 		list_destroy(&dr->dt.di.dr_children);
1228 	}
1229 	kmem_free(dr, sizeof (dbuf_dirty_record_t));
1230 
1231 	ASSERT(db->db_dirtycnt > 0);
1232 	db->db_dirtycnt -= 1;
1233 
1234 	if (refcount_remove(&db->db_holds, (void *)(uintptr_t)txg) == 0) {
1235 		arc_buf_t *buf = db->db_buf;
1236 
1237 		ASSERT(db->db_state == DB_NOFILL || arc_released(buf));
1238 		dbuf_set_data(db, NULL);
1239 		VERIFY(arc_buf_remove_ref(buf, db) == 1);
1240 		dbuf_evict(db);
1241 		return (1);
1242 	}
1243 
1244 	mutex_exit(&db->db_mtx);
1245 	return (0);
1246 }
1247 
1248 #pragma weak dmu_buf_will_dirty = dbuf_will_dirty
1249 void
1250 dbuf_will_dirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
1251 {
1252 	int rf = DB_RF_MUST_SUCCEED | DB_RF_NOPREFETCH;
1253 
1254 	ASSERT(tx->tx_txg != 0);
1255 	ASSERT(!refcount_is_zero(&db->db_holds));
1256 
1257 	if (RW_WRITE_HELD(&db->db_dnode->dn_struct_rwlock))
1258 		rf |= DB_RF_HAVESTRUCT;
1259 	(void) dbuf_read(db, NULL, rf);
1260 	(void) dbuf_dirty(db, tx);
1261 }
1262 
1263 void
1264 dmu_buf_will_not_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
1265 {
1266 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1267 
1268 	db->db_state = DB_NOFILL;
1269 
1270 	dmu_buf_will_fill(db_fake, tx);
1271 }
1272 
1273 void
1274 dmu_buf_will_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
1275 {
1276 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1277 
1278 	ASSERT(db->db_blkid != DB_BONUS_BLKID);
1279 	ASSERT(tx->tx_txg != 0);
1280 	ASSERT(db->db_level == 0);
1281 	ASSERT(!refcount_is_zero(&db->db_holds));
1282 
1283 	ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT ||
1284 	    dmu_tx_private_ok(tx));
1285 
1286 	dbuf_noread(db);
1287 	(void) dbuf_dirty(db, tx);
1288 }
1289 
1290 #pragma weak dmu_buf_fill_done = dbuf_fill_done
1291 /* ARGSUSED */
1292 void
1293 dbuf_fill_done(dmu_buf_impl_t *db, dmu_tx_t *tx)
1294 {
1295 	mutex_enter(&db->db_mtx);
1296 	DBUF_VERIFY(db);
1297 
1298 	if (db->db_state == DB_FILL) {
1299 		if (db->db_level == 0 && db->db_freed_in_flight) {
1300 			ASSERT(db->db_blkid != DB_BONUS_BLKID);
1301 			/* we were freed while filling */
1302 			/* XXX dbuf_undirty? */
1303 			bzero(db->db.db_data, db->db.db_size);
1304 			db->db_freed_in_flight = FALSE;
1305 		}
1306 		db->db_state = DB_CACHED;
1307 		cv_broadcast(&db->db_changed);
1308 	}
1309 	mutex_exit(&db->db_mtx);
1310 }
1311 
1312 /*
1313  * Directly assign a provided arc buf to a given dbuf if it's not referenced
1314  * by anybody except our caller. Otherwise copy arcbuf's contents to dbuf.
1315  */
1316 void
1317 dbuf_assign_arcbuf(dmu_buf_impl_t *db, arc_buf_t *buf, dmu_tx_t *tx)
1318 {
1319 	ASSERT(!refcount_is_zero(&db->db_holds));
1320 	ASSERT(db->db_dnode->dn_object != DMU_META_DNODE_OBJECT);
1321 	ASSERT(db->db_blkid != DB_BONUS_BLKID);
1322 	ASSERT(db->db_level == 0);
1323 	ASSERT(DBUF_GET_BUFC_TYPE(db) == ARC_BUFC_DATA);
1324 	ASSERT(buf != NULL);
1325 	ASSERT(arc_buf_size(buf) == db->db.db_size);
1326 	ASSERT(tx->tx_txg != 0);
1327 
1328 	arc_return_buf(buf, db);
1329 	ASSERT(arc_released(buf));
1330 
1331 	mutex_enter(&db->db_mtx);
1332 
1333 	while (db->db_state == DB_READ || db->db_state == DB_FILL)
1334 		cv_wait(&db->db_changed, &db->db_mtx);
1335 
1336 	ASSERT(db->db_state == DB_CACHED || db->db_state == DB_UNCACHED);
1337 
1338 	if (db->db_state == DB_CACHED &&
1339 	    refcount_count(&db->db_holds) - 1 > db->db_dirtycnt) {
1340 		mutex_exit(&db->db_mtx);
1341 		(void) dbuf_dirty(db, tx);
1342 		bcopy(buf->b_data, db->db.db_data, db->db.db_size);
1343 		VERIFY(arc_buf_remove_ref(buf, db) == 1);
1344 		return;
1345 	}
1346 
1347 	if (db->db_state == DB_CACHED) {
1348 		dbuf_dirty_record_t *dr = db->db_last_dirty;
1349 
1350 		ASSERT(db->db_buf != NULL);
1351 		if (dr != NULL && dr->dr_txg == tx->tx_txg) {
1352 			ASSERT(dr->dt.dl.dr_data == db->db_buf);
1353 			if (!arc_released(db->db_buf)) {
1354 				ASSERT(dr->dt.dl.dr_override_state ==
1355 				    DR_OVERRIDDEN);
1356 				arc_release(db->db_buf, db);
1357 			}
1358 			dr->dt.dl.dr_data = buf;
1359 			VERIFY(arc_buf_remove_ref(db->db_buf, db) == 1);
1360 		} else if (dr == NULL || dr->dt.dl.dr_data != db->db_buf) {
1361 			arc_release(db->db_buf, db);
1362 			VERIFY(arc_buf_remove_ref(db->db_buf, db) == 1);
1363 		}
1364 		db->db_buf = NULL;
1365 	}
1366 	ASSERT(db->db_buf == NULL);
1367 	dbuf_set_data(db, buf);
1368 	db->db_state = DB_FILL;
1369 	mutex_exit(&db->db_mtx);
1370 	(void) dbuf_dirty(db, tx);
1371 	dbuf_fill_done(db, tx);
1372 }
1373 
1374 /*
1375  * "Clear" the contents of this dbuf.  This will mark the dbuf
1376  * EVICTING and clear *most* of its references.  Unfortunetely,
1377  * when we are not holding the dn_dbufs_mtx, we can't clear the
1378  * entry in the dn_dbufs list.  We have to wait until dbuf_destroy()
1379  * in this case.  For callers from the DMU we will usually see:
1380  *	dbuf_clear()->arc_buf_evict()->dbuf_do_evict()->dbuf_destroy()
1381  * For the arc callback, we will usually see:
1382  * 	dbuf_do_evict()->dbuf_clear();dbuf_destroy()
1383  * Sometimes, though, we will get a mix of these two:
1384  *	DMU: dbuf_clear()->arc_buf_evict()
1385  *	ARC: dbuf_do_evict()->dbuf_destroy()
1386  */
1387 void
1388 dbuf_clear(dmu_buf_impl_t *db)
1389 {
1390 	dnode_t *dn = db->db_dnode;
1391 	dmu_buf_impl_t *parent = db->db_parent;
1392 	dmu_buf_impl_t *dndb = dn->dn_dbuf;
1393 	int dbuf_gone = FALSE;
1394 
1395 	ASSERT(MUTEX_HELD(&db->db_mtx));
1396 	ASSERT(refcount_is_zero(&db->db_holds));
1397 
1398 	dbuf_evict_user(db);
1399 
1400 	if (db->db_state == DB_CACHED) {
1401 		ASSERT(db->db.db_data != NULL);
1402 		if (db->db_blkid == DB_BONUS_BLKID) {
1403 			zio_buf_free(db->db.db_data, DN_MAX_BONUSLEN);
1404 			arc_space_return(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
1405 		}
1406 		db->db.db_data = NULL;
1407 		db->db_state = DB_UNCACHED;
1408 	}
1409 
1410 	ASSERT(db->db_state == DB_UNCACHED || db->db_state == DB_NOFILL);
1411 	ASSERT(db->db_data_pending == NULL);
1412 
1413 	db->db_state = DB_EVICTING;
1414 	db->db_blkptr = NULL;
1415 
1416 	if (db->db_blkid != DB_BONUS_BLKID && MUTEX_HELD(&dn->dn_dbufs_mtx)) {
1417 		list_remove(&dn->dn_dbufs, db);
1418 		dnode_rele(dn, db);
1419 		db->db_dnode = NULL;
1420 	}
1421 
1422 	if (db->db_buf)
1423 		dbuf_gone = arc_buf_evict(db->db_buf);
1424 
1425 	if (!dbuf_gone)
1426 		mutex_exit(&db->db_mtx);
1427 
1428 	/*
1429 	 * If this dbuf is referened from an indirect dbuf,
1430 	 * decrement the ref count on the indirect dbuf.
1431 	 */
1432 	if (parent && parent != dndb)
1433 		dbuf_rele(parent, db);
1434 }
1435 
1436 static int
1437 dbuf_findbp(dnode_t *dn, int level, uint64_t blkid, int fail_sparse,
1438     dmu_buf_impl_t **parentp, blkptr_t **bpp)
1439 {
1440 	int nlevels, epbs;
1441 
1442 	*parentp = NULL;
1443 	*bpp = NULL;
1444 
1445 	ASSERT(blkid != DB_BONUS_BLKID);
1446 
1447 	if (dn->dn_phys->dn_nlevels == 0)
1448 		nlevels = 1;
1449 	else
1450 		nlevels = dn->dn_phys->dn_nlevels;
1451 
1452 	epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
1453 
1454 	ASSERT3U(level * epbs, <, 64);
1455 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
1456 	if (level >= nlevels ||
1457 	    (blkid > (dn->dn_phys->dn_maxblkid >> (level * epbs)))) {
1458 		/* the buffer has no parent yet */
1459 		return (ENOENT);
1460 	} else if (level < nlevels-1) {
1461 		/* this block is referenced from an indirect block */
1462 		int err = dbuf_hold_impl(dn, level+1,
1463 		    blkid >> epbs, fail_sparse, NULL, parentp);
1464 		if (err)
1465 			return (err);
1466 		err = dbuf_read(*parentp, NULL,
1467 		    (DB_RF_HAVESTRUCT | DB_RF_NOPREFETCH | DB_RF_CANFAIL));
1468 		if (err) {
1469 			dbuf_rele(*parentp, NULL);
1470 			*parentp = NULL;
1471 			return (err);
1472 		}
1473 		*bpp = ((blkptr_t *)(*parentp)->db.db_data) +
1474 		    (blkid & ((1ULL << epbs) - 1));
1475 		return (0);
1476 	} else {
1477 		/* the block is referenced from the dnode */
1478 		ASSERT3U(level, ==, nlevels-1);
1479 		ASSERT(dn->dn_phys->dn_nblkptr == 0 ||
1480 		    blkid < dn->dn_phys->dn_nblkptr);
1481 		if (dn->dn_dbuf) {
1482 			dbuf_add_ref(dn->dn_dbuf, NULL);
1483 			*parentp = dn->dn_dbuf;
1484 		}
1485 		*bpp = &dn->dn_phys->dn_blkptr[blkid];
1486 		return (0);
1487 	}
1488 }
1489 
1490 static dmu_buf_impl_t *
1491 dbuf_create(dnode_t *dn, uint8_t level, uint64_t blkid,
1492     dmu_buf_impl_t *parent, blkptr_t *blkptr)
1493 {
1494 	objset_t *os = dn->dn_objset;
1495 	dmu_buf_impl_t *db, *odb;
1496 
1497 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
1498 	ASSERT(dn->dn_type != DMU_OT_NONE);
1499 
1500 	db = kmem_cache_alloc(dbuf_cache, KM_SLEEP);
1501 
1502 	db->db_objset = os;
1503 	db->db.db_object = dn->dn_object;
1504 	db->db_level = level;
1505 	db->db_blkid = blkid;
1506 	db->db_last_dirty = NULL;
1507 	db->db_dirtycnt = 0;
1508 	db->db_dnode = dn;
1509 	db->db_parent = parent;
1510 	db->db_blkptr = blkptr;
1511 
1512 	db->db_user_ptr = NULL;
1513 	db->db_user_data_ptr_ptr = NULL;
1514 	db->db_evict_func = NULL;
1515 	db->db_immediate_evict = 0;
1516 	db->db_freed_in_flight = 0;
1517 
1518 	if (blkid == DB_BONUS_BLKID) {
1519 		ASSERT3P(parent, ==, dn->dn_dbuf);
1520 		db->db.db_size = DN_MAX_BONUSLEN -
1521 		    (dn->dn_nblkptr-1) * sizeof (blkptr_t);
1522 		ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
1523 		db->db.db_offset = DB_BONUS_BLKID;
1524 		db->db_state = DB_UNCACHED;
1525 		/* the bonus dbuf is not placed in the hash table */
1526 		arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
1527 		return (db);
1528 	} else {
1529 		int blocksize =
1530 		    db->db_level ? 1<<dn->dn_indblkshift :  dn->dn_datablksz;
1531 		db->db.db_size = blocksize;
1532 		db->db.db_offset = db->db_blkid * blocksize;
1533 	}
1534 
1535 	/*
1536 	 * Hold the dn_dbufs_mtx while we get the new dbuf
1537 	 * in the hash table *and* added to the dbufs list.
1538 	 * This prevents a possible deadlock with someone
1539 	 * trying to look up this dbuf before its added to the
1540 	 * dn_dbufs list.
1541 	 */
1542 	mutex_enter(&dn->dn_dbufs_mtx);
1543 	db->db_state = DB_EVICTING;
1544 	if ((odb = dbuf_hash_insert(db)) != NULL) {
1545 		/* someone else inserted it first */
1546 		kmem_cache_free(dbuf_cache, db);
1547 		mutex_exit(&dn->dn_dbufs_mtx);
1548 		return (odb);
1549 	}
1550 	list_insert_head(&dn->dn_dbufs, db);
1551 	db->db_state = DB_UNCACHED;
1552 	mutex_exit(&dn->dn_dbufs_mtx);
1553 	arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
1554 
1555 	if (parent && parent != dn->dn_dbuf)
1556 		dbuf_add_ref(parent, db);
1557 
1558 	ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
1559 	    refcount_count(&dn->dn_holds) > 0);
1560 	(void) refcount_add(&dn->dn_holds, db);
1561 
1562 	dprintf_dbuf(db, "db=%p\n", db);
1563 
1564 	return (db);
1565 }
1566 
1567 static int
1568 dbuf_do_evict(void *private)
1569 {
1570 	arc_buf_t *buf = private;
1571 	dmu_buf_impl_t *db = buf->b_private;
1572 
1573 	if (!MUTEX_HELD(&db->db_mtx))
1574 		mutex_enter(&db->db_mtx);
1575 
1576 	ASSERT(refcount_is_zero(&db->db_holds));
1577 
1578 	if (db->db_state != DB_EVICTING) {
1579 		ASSERT(db->db_state == DB_CACHED);
1580 		DBUF_VERIFY(db);
1581 		db->db_buf = NULL;
1582 		dbuf_evict(db);
1583 	} else {
1584 		mutex_exit(&db->db_mtx);
1585 		dbuf_destroy(db);
1586 	}
1587 	return (0);
1588 }
1589 
1590 static void
1591 dbuf_destroy(dmu_buf_impl_t *db)
1592 {
1593 	ASSERT(refcount_is_zero(&db->db_holds));
1594 
1595 	if (db->db_blkid != DB_BONUS_BLKID) {
1596 		/*
1597 		 * If this dbuf is still on the dn_dbufs list,
1598 		 * remove it from that list.
1599 		 */
1600 		if (db->db_dnode) {
1601 			dnode_t *dn = db->db_dnode;
1602 
1603 			mutex_enter(&dn->dn_dbufs_mtx);
1604 			list_remove(&dn->dn_dbufs, db);
1605 			mutex_exit(&dn->dn_dbufs_mtx);
1606 
1607 			dnode_rele(dn, db);
1608 			db->db_dnode = NULL;
1609 		}
1610 		dbuf_hash_remove(db);
1611 	}
1612 	db->db_parent = NULL;
1613 	db->db_buf = NULL;
1614 
1615 	ASSERT(!list_link_active(&db->db_link));
1616 	ASSERT(db->db.db_data == NULL);
1617 	ASSERT(db->db_hash_next == NULL);
1618 	ASSERT(db->db_blkptr == NULL);
1619 	ASSERT(db->db_data_pending == NULL);
1620 
1621 	kmem_cache_free(dbuf_cache, db);
1622 	arc_space_return(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
1623 }
1624 
1625 void
1626 dbuf_prefetch(dnode_t *dn, uint64_t blkid)
1627 {
1628 	dmu_buf_impl_t *db = NULL;
1629 	blkptr_t *bp = NULL;
1630 
1631 	ASSERT(blkid != DB_BONUS_BLKID);
1632 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
1633 
1634 	if (dnode_block_freed(dn, blkid))
1635 		return;
1636 
1637 	/* dbuf_find() returns with db_mtx held */
1638 	if (db = dbuf_find(dn, 0, blkid)) {
1639 		if (refcount_count(&db->db_holds) > 0) {
1640 			/*
1641 			 * This dbuf is active.  We assume that it is
1642 			 * already CACHED, or else about to be either
1643 			 * read or filled.
1644 			 */
1645 			mutex_exit(&db->db_mtx);
1646 			return;
1647 		}
1648 		mutex_exit(&db->db_mtx);
1649 		db = NULL;
1650 	}
1651 
1652 	if (dbuf_findbp(dn, 0, blkid, TRUE, &db, &bp) == 0) {
1653 		if (bp && !BP_IS_HOLE(bp)) {
1654 			arc_buf_t *pbuf;
1655 			dsl_dataset_t *ds = dn->dn_objset->os_dsl_dataset;
1656 			uint32_t aflags = ARC_NOWAIT | ARC_PREFETCH;
1657 			zbookmark_t zb;
1658 
1659 			SET_BOOKMARK(&zb, ds ? ds->ds_object : DMU_META_OBJSET,
1660 			    dn->dn_object, 0, blkid);
1661 
1662 			if (db)
1663 				pbuf = db->db_buf;
1664 			else
1665 				pbuf = dn->dn_objset->os_phys_buf;
1666 
1667 			(void) arc_read(NULL, dn->dn_objset->os_spa,
1668 			    bp, pbuf, NULL, NULL, ZIO_PRIORITY_ASYNC_READ,
1669 			    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
1670 			    &aflags, &zb);
1671 		}
1672 		if (db)
1673 			dbuf_rele(db, NULL);
1674 	}
1675 }
1676 
1677 /*
1678  * Returns with db_holds incremented, and db_mtx not held.
1679  * Note: dn_struct_rwlock must be held.
1680  */
1681 int
1682 dbuf_hold_impl(dnode_t *dn, uint8_t level, uint64_t blkid, int fail_sparse,
1683     void *tag, dmu_buf_impl_t **dbp)
1684 {
1685 	dmu_buf_impl_t *db, *parent = NULL;
1686 
1687 	ASSERT(blkid != DB_BONUS_BLKID);
1688 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
1689 	ASSERT3U(dn->dn_nlevels, >, level);
1690 
1691 	*dbp = NULL;
1692 top:
1693 	/* dbuf_find() returns with db_mtx held */
1694 	db = dbuf_find(dn, level, blkid);
1695 
1696 	if (db == NULL) {
1697 		blkptr_t *bp = NULL;
1698 		int err;
1699 
1700 		ASSERT3P(parent, ==, NULL);
1701 		err = dbuf_findbp(dn, level, blkid, fail_sparse, &parent, &bp);
1702 		if (fail_sparse) {
1703 			if (err == 0 && bp && BP_IS_HOLE(bp))
1704 				err = ENOENT;
1705 			if (err) {
1706 				if (parent)
1707 					dbuf_rele(parent, NULL);
1708 				return (err);
1709 			}
1710 		}
1711 		if (err && err != ENOENT)
1712 			return (err);
1713 		db = dbuf_create(dn, level, blkid, parent, bp);
1714 	}
1715 
1716 	if (db->db_buf && refcount_is_zero(&db->db_holds)) {
1717 		arc_buf_add_ref(db->db_buf, db);
1718 		if (db->db_buf->b_data == NULL) {
1719 			dbuf_clear(db);
1720 			if (parent) {
1721 				dbuf_rele(parent, NULL);
1722 				parent = NULL;
1723 			}
1724 			goto top;
1725 		}
1726 		ASSERT3P(db->db.db_data, ==, db->db_buf->b_data);
1727 	}
1728 
1729 	ASSERT(db->db_buf == NULL || arc_referenced(db->db_buf));
1730 
1731 	/*
1732 	 * If this buffer is currently syncing out, and we are are
1733 	 * still referencing it from db_data, we need to make a copy
1734 	 * of it in case we decide we want to dirty it again in this txg.
1735 	 */
1736 	if (db->db_level == 0 && db->db_blkid != DB_BONUS_BLKID &&
1737 	    dn->dn_object != DMU_META_DNODE_OBJECT &&
1738 	    db->db_state == DB_CACHED && db->db_data_pending) {
1739 		dbuf_dirty_record_t *dr = db->db_data_pending;
1740 
1741 		if (dr->dt.dl.dr_data == db->db_buf) {
1742 			arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1743 
1744 			dbuf_set_data(db,
1745 			    arc_buf_alloc(db->db_dnode->dn_objset->os_spa,
1746 			    db->db.db_size, db, type));
1747 			bcopy(dr->dt.dl.dr_data->b_data, db->db.db_data,
1748 			    db->db.db_size);
1749 		}
1750 	}
1751 
1752 	(void) refcount_add(&db->db_holds, tag);
1753 	dbuf_update_data(db);
1754 	DBUF_VERIFY(db);
1755 	mutex_exit(&db->db_mtx);
1756 
1757 	/* NOTE: we can't rele the parent until after we drop the db_mtx */
1758 	if (parent)
1759 		dbuf_rele(parent, NULL);
1760 
1761 	ASSERT3P(db->db_dnode, ==, dn);
1762 	ASSERT3U(db->db_blkid, ==, blkid);
1763 	ASSERT3U(db->db_level, ==, level);
1764 	*dbp = db;
1765 
1766 	return (0);
1767 }
1768 
1769 dmu_buf_impl_t *
1770 dbuf_hold(dnode_t *dn, uint64_t blkid, void *tag)
1771 {
1772 	dmu_buf_impl_t *db;
1773 	int err = dbuf_hold_impl(dn, 0, blkid, FALSE, tag, &db);
1774 	return (err ? NULL : db);
1775 }
1776 
1777 dmu_buf_impl_t *
1778 dbuf_hold_level(dnode_t *dn, int level, uint64_t blkid, void *tag)
1779 {
1780 	dmu_buf_impl_t *db;
1781 	int err = dbuf_hold_impl(dn, level, blkid, FALSE, tag, &db);
1782 	return (err ? NULL : db);
1783 }
1784 
1785 void
1786 dbuf_create_bonus(dnode_t *dn)
1787 {
1788 	ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
1789 
1790 	ASSERT(dn->dn_bonus == NULL);
1791 	dn->dn_bonus = dbuf_create(dn, 0, DB_BONUS_BLKID, dn->dn_dbuf, NULL);
1792 }
1793 
1794 #pragma weak dmu_buf_add_ref = dbuf_add_ref
1795 void
1796 dbuf_add_ref(dmu_buf_impl_t *db, void *tag)
1797 {
1798 	int64_t holds = refcount_add(&db->db_holds, tag);
1799 	ASSERT(holds > 1);
1800 }
1801 
1802 #pragma weak dmu_buf_rele = dbuf_rele
1803 void
1804 dbuf_rele(dmu_buf_impl_t *db, void *tag)
1805 {
1806 	mutex_enter(&db->db_mtx);
1807 	dbuf_rele_and_unlock(db, tag);
1808 }
1809 
1810 /*
1811  * dbuf_rele() for an already-locked dbuf.  This is necessary to allow
1812  * db_dirtycnt and db_holds to be updated atomically.
1813  */
1814 void
1815 dbuf_rele_and_unlock(dmu_buf_impl_t *db, void *tag)
1816 {
1817 	int64_t holds;
1818 
1819 	ASSERT(MUTEX_HELD(&db->db_mtx));
1820 	DBUF_VERIFY(db);
1821 
1822 	holds = refcount_remove(&db->db_holds, tag);
1823 	ASSERT(holds >= 0);
1824 
1825 	/*
1826 	 * We can't freeze indirects if there is a possibility that they
1827 	 * may be modified in the current syncing context.
1828 	 */
1829 	if (db->db_buf && holds == (db->db_level == 0 ? db->db_dirtycnt : 0))
1830 		arc_buf_freeze(db->db_buf);
1831 
1832 	if (holds == db->db_dirtycnt &&
1833 	    db->db_level == 0 && db->db_immediate_evict)
1834 		dbuf_evict_user(db);
1835 
1836 	if (holds == 0) {
1837 		if (db->db_blkid == DB_BONUS_BLKID) {
1838 			mutex_exit(&db->db_mtx);
1839 			dnode_rele(db->db_dnode, db);
1840 		} else if (db->db_buf == NULL) {
1841 			/*
1842 			 * This is a special case: we never associated this
1843 			 * dbuf with any data allocated from the ARC.
1844 			 */
1845 			ASSERT(db->db_state == DB_UNCACHED ||
1846 			    db->db_state == DB_NOFILL);
1847 			dbuf_evict(db);
1848 		} else if (arc_released(db->db_buf)) {
1849 			arc_buf_t *buf = db->db_buf;
1850 			/*
1851 			 * This dbuf has anonymous data associated with it.
1852 			 */
1853 			dbuf_set_data(db, NULL);
1854 			VERIFY(arc_buf_remove_ref(buf, db) == 1);
1855 			dbuf_evict(db);
1856 		} else {
1857 			VERIFY(arc_buf_remove_ref(db->db_buf, db) == 0);
1858 			if (!DBUF_IS_CACHEABLE(db))
1859 				dbuf_clear(db);
1860 			else
1861 				mutex_exit(&db->db_mtx);
1862 		}
1863 	} else {
1864 		mutex_exit(&db->db_mtx);
1865 	}
1866 }
1867 
1868 #pragma weak dmu_buf_refcount = dbuf_refcount
1869 uint64_t
1870 dbuf_refcount(dmu_buf_impl_t *db)
1871 {
1872 	return (refcount_count(&db->db_holds));
1873 }
1874 
1875 void *
1876 dmu_buf_set_user(dmu_buf_t *db_fake, void *user_ptr, void *user_data_ptr_ptr,
1877     dmu_buf_evict_func_t *evict_func)
1878 {
1879 	return (dmu_buf_update_user(db_fake, NULL, user_ptr,
1880 	    user_data_ptr_ptr, evict_func));
1881 }
1882 
1883 void *
1884 dmu_buf_set_user_ie(dmu_buf_t *db_fake, void *user_ptr, void *user_data_ptr_ptr,
1885     dmu_buf_evict_func_t *evict_func)
1886 {
1887 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1888 
1889 	db->db_immediate_evict = TRUE;
1890 	return (dmu_buf_update_user(db_fake, NULL, user_ptr,
1891 	    user_data_ptr_ptr, evict_func));
1892 }
1893 
1894 void *
1895 dmu_buf_update_user(dmu_buf_t *db_fake, void *old_user_ptr, void *user_ptr,
1896     void *user_data_ptr_ptr, dmu_buf_evict_func_t *evict_func)
1897 {
1898 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1899 	ASSERT(db->db_level == 0);
1900 
1901 	ASSERT((user_ptr == NULL) == (evict_func == NULL));
1902 
1903 	mutex_enter(&db->db_mtx);
1904 
1905 	if (db->db_user_ptr == old_user_ptr) {
1906 		db->db_user_ptr = user_ptr;
1907 		db->db_user_data_ptr_ptr = user_data_ptr_ptr;
1908 		db->db_evict_func = evict_func;
1909 
1910 		dbuf_update_data(db);
1911 	} else {
1912 		old_user_ptr = db->db_user_ptr;
1913 	}
1914 
1915 	mutex_exit(&db->db_mtx);
1916 	return (old_user_ptr);
1917 }
1918 
1919 void *
1920 dmu_buf_get_user(dmu_buf_t *db_fake)
1921 {
1922 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1923 	ASSERT(!refcount_is_zero(&db->db_holds));
1924 
1925 	return (db->db_user_ptr);
1926 }
1927 
1928 boolean_t
1929 dmu_buf_freeable(dmu_buf_t *dbuf)
1930 {
1931 	boolean_t res = B_FALSE;
1932 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbuf;
1933 
1934 	if (db->db_blkptr)
1935 		res = dsl_dataset_block_freeable(db->db_objset->os_dsl_dataset,
1936 		    db->db_blkptr->blk_birth);
1937 
1938 	return (res);
1939 }
1940 
1941 static void
1942 dbuf_check_blkptr(dnode_t *dn, dmu_buf_impl_t *db)
1943 {
1944 	/* ASSERT(dmu_tx_is_syncing(tx) */
1945 	ASSERT(MUTEX_HELD(&db->db_mtx));
1946 
1947 	if (db->db_blkptr != NULL)
1948 		return;
1949 
1950 	if (db->db_level == dn->dn_phys->dn_nlevels-1) {
1951 		/*
1952 		 * This buffer was allocated at a time when there was
1953 		 * no available blkptrs from the dnode, or it was
1954 		 * inappropriate to hook it in (i.e., nlevels mis-match).
1955 		 */
1956 		ASSERT(db->db_blkid < dn->dn_phys->dn_nblkptr);
1957 		ASSERT(db->db_parent == NULL);
1958 		db->db_parent = dn->dn_dbuf;
1959 		db->db_blkptr = &dn->dn_phys->dn_blkptr[db->db_blkid];
1960 		DBUF_VERIFY(db);
1961 	} else {
1962 		dmu_buf_impl_t *parent = db->db_parent;
1963 		int epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
1964 
1965 		ASSERT(dn->dn_phys->dn_nlevels > 1);
1966 		if (parent == NULL) {
1967 			mutex_exit(&db->db_mtx);
1968 			rw_enter(&dn->dn_struct_rwlock, RW_READER);
1969 			(void) dbuf_hold_impl(dn, db->db_level+1,
1970 			    db->db_blkid >> epbs, FALSE, db, &parent);
1971 			rw_exit(&dn->dn_struct_rwlock);
1972 			mutex_enter(&db->db_mtx);
1973 			db->db_parent = parent;
1974 		}
1975 		db->db_blkptr = (blkptr_t *)parent->db.db_data +
1976 		    (db->db_blkid & ((1ULL << epbs) - 1));
1977 		DBUF_VERIFY(db);
1978 	}
1979 }
1980 
1981 static void
1982 dbuf_sync_indirect(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
1983 {
1984 	dmu_buf_impl_t *db = dr->dr_dbuf;
1985 	dnode_t *dn = db->db_dnode;
1986 	zio_t *zio;
1987 
1988 	ASSERT(dmu_tx_is_syncing(tx));
1989 
1990 	dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
1991 
1992 	mutex_enter(&db->db_mtx);
1993 
1994 	ASSERT(db->db_level > 0);
1995 	DBUF_VERIFY(db);
1996 
1997 	if (db->db_buf == NULL) {
1998 		mutex_exit(&db->db_mtx);
1999 		(void) dbuf_read(db, NULL, DB_RF_MUST_SUCCEED);
2000 		mutex_enter(&db->db_mtx);
2001 	}
2002 	ASSERT3U(db->db_state, ==, DB_CACHED);
2003 	ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
2004 	ASSERT(db->db_buf != NULL);
2005 
2006 	dbuf_check_blkptr(dn, db);
2007 
2008 	db->db_data_pending = dr;
2009 
2010 	mutex_exit(&db->db_mtx);
2011 	dbuf_write(dr, db->db_buf, tx);
2012 
2013 	zio = dr->dr_zio;
2014 	mutex_enter(&dr->dt.di.dr_mtx);
2015 	dbuf_sync_list(&dr->dt.di.dr_children, tx);
2016 	ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
2017 	mutex_exit(&dr->dt.di.dr_mtx);
2018 	zio_nowait(zio);
2019 }
2020 
2021 static void
2022 dbuf_sync_leaf(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
2023 {
2024 	arc_buf_t **datap = &dr->dt.dl.dr_data;
2025 	dmu_buf_impl_t *db = dr->dr_dbuf;
2026 	dnode_t *dn = db->db_dnode;
2027 	objset_t *os = dn->dn_objset;
2028 	uint64_t txg = tx->tx_txg;
2029 
2030 	ASSERT(dmu_tx_is_syncing(tx));
2031 
2032 	dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
2033 
2034 	mutex_enter(&db->db_mtx);
2035 	/*
2036 	 * To be synced, we must be dirtied.  But we
2037 	 * might have been freed after the dirty.
2038 	 */
2039 	if (db->db_state == DB_UNCACHED) {
2040 		/* This buffer has been freed since it was dirtied */
2041 		ASSERT(db->db.db_data == NULL);
2042 	} else if (db->db_state == DB_FILL) {
2043 		/* This buffer was freed and is now being re-filled */
2044 		ASSERT(db->db.db_data != dr->dt.dl.dr_data);
2045 	} else {
2046 		ASSERT(db->db_state == DB_CACHED || db->db_state == DB_NOFILL);
2047 	}
2048 	DBUF_VERIFY(db);
2049 
2050 	/*
2051 	 * If this is a bonus buffer, simply copy the bonus data into the
2052 	 * dnode.  It will be written out when the dnode is synced (and it
2053 	 * will be synced, since it must have been dirty for dbuf_sync to
2054 	 * be called).
2055 	 */
2056 	if (db->db_blkid == DB_BONUS_BLKID) {
2057 		dbuf_dirty_record_t **drp;
2058 
2059 		ASSERT(*datap != NULL);
2060 		ASSERT3U(db->db_level, ==, 0);
2061 		ASSERT3U(dn->dn_phys->dn_bonuslen, <=, DN_MAX_BONUSLEN);
2062 		bcopy(*datap, DN_BONUS(dn->dn_phys), dn->dn_phys->dn_bonuslen);
2063 		if (*datap != db->db.db_data) {
2064 			zio_buf_free(*datap, DN_MAX_BONUSLEN);
2065 			arc_space_return(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
2066 		}
2067 		db->db_data_pending = NULL;
2068 		drp = &db->db_last_dirty;
2069 		while (*drp != dr)
2070 			drp = &(*drp)->dr_next;
2071 		ASSERT(dr->dr_next == NULL);
2072 		ASSERT(dr->dr_dbuf == db);
2073 		*drp = dr->dr_next;
2074 		kmem_free(dr, sizeof (dbuf_dirty_record_t));
2075 		ASSERT(db->db_dirtycnt > 0);
2076 		db->db_dirtycnt -= 1;
2077 		dbuf_rele_and_unlock(db, (void *)(uintptr_t)txg);
2078 		return;
2079 	}
2080 
2081 	/*
2082 	 * This function may have dropped the db_mtx lock allowing a dmu_sync
2083 	 * operation to sneak in. As a result, we need to ensure that we
2084 	 * don't check the dr_override_state until we have returned from
2085 	 * dbuf_check_blkptr.
2086 	 */
2087 	dbuf_check_blkptr(dn, db);
2088 
2089 	/*
2090 	 * If this buffer is in the middle of an immdiate write,
2091 	 * wait for the synchronous IO to complete.
2092 	 */
2093 	while (dr->dt.dl.dr_override_state == DR_IN_DMU_SYNC) {
2094 		ASSERT(dn->dn_object != DMU_META_DNODE_OBJECT);
2095 		cv_wait(&db->db_changed, &db->db_mtx);
2096 		ASSERT(dr->dt.dl.dr_override_state != DR_NOT_OVERRIDDEN);
2097 	}
2098 
2099 	if (db->db_state != DB_NOFILL &&
2100 	    dn->dn_object != DMU_META_DNODE_OBJECT &&
2101 	    refcount_count(&db->db_holds) > 1 &&
2102 	    dr->dt.dl.dr_override_state != DR_OVERRIDDEN &&
2103 	    *datap == db->db_buf) {
2104 		/*
2105 		 * If this buffer is currently "in use" (i.e., there
2106 		 * are active holds and db_data still references it),
2107 		 * then make a copy before we start the write so that
2108 		 * any modifications from the open txg will not leak
2109 		 * into this write.
2110 		 *
2111 		 * NOTE: this copy does not need to be made for
2112 		 * objects only modified in the syncing context (e.g.
2113 		 * DNONE_DNODE blocks).
2114 		 */
2115 		int blksz = arc_buf_size(*datap);
2116 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
2117 		*datap = arc_buf_alloc(os->os_spa, blksz, db, type);
2118 		bcopy(db->db.db_data, (*datap)->b_data, blksz);
2119 	}
2120 	db->db_data_pending = dr;
2121 
2122 	mutex_exit(&db->db_mtx);
2123 
2124 	dbuf_write(dr, *datap, tx);
2125 
2126 	ASSERT(!list_link_active(&dr->dr_dirty_node));
2127 	if (dn->dn_object == DMU_META_DNODE_OBJECT)
2128 		list_insert_tail(&dn->dn_dirty_records[txg&TXG_MASK], dr);
2129 	else
2130 		zio_nowait(dr->dr_zio);
2131 }
2132 
2133 void
2134 dbuf_sync_list(list_t *list, dmu_tx_t *tx)
2135 {
2136 	dbuf_dirty_record_t *dr;
2137 
2138 	while (dr = list_head(list)) {
2139 		if (dr->dr_zio != NULL) {
2140 			/*
2141 			 * If we find an already initialized zio then we
2142 			 * are processing the meta-dnode, and we have finished.
2143 			 * The dbufs for all dnodes are put back on the list
2144 			 * during processing, so that we can zio_wait()
2145 			 * these IOs after initiating all child IOs.
2146 			 */
2147 			ASSERT3U(dr->dr_dbuf->db.db_object, ==,
2148 			    DMU_META_DNODE_OBJECT);
2149 			break;
2150 		}
2151 		list_remove(list, dr);
2152 		if (dr->dr_dbuf->db_level > 0)
2153 			dbuf_sync_indirect(dr, tx);
2154 		else
2155 			dbuf_sync_leaf(dr, tx);
2156 	}
2157 }
2158 
2159 /* ARGSUSED */
2160 static void
2161 dbuf_write_ready(zio_t *zio, arc_buf_t *buf, void *vdb)
2162 {
2163 	dmu_buf_impl_t *db = vdb;
2164 	blkptr_t *bp = zio->io_bp;
2165 	blkptr_t *bp_orig = &zio->io_bp_orig;
2166 	dnode_t *dn = db->db_dnode;
2167 	spa_t *spa = zio->io_spa;
2168 	int64_t delta;
2169 	uint64_t fill = 0;
2170 	int i;
2171 
2172 	ASSERT(db->db_blkptr == bp);
2173 
2174 	delta = bp_get_dsize_sync(spa, bp) - bp_get_dsize_sync(spa, bp_orig);
2175 	dnode_diduse_space(dn, delta - zio->io_prev_space_delta);
2176 	zio->io_prev_space_delta = delta;
2177 
2178 	if (BP_IS_HOLE(bp)) {
2179 		ASSERT(bp->blk_fill == 0);
2180 		return;
2181 	}
2182 
2183 	ASSERT(BP_GET_TYPE(bp) == dn->dn_type);
2184 	ASSERT(BP_GET_LEVEL(bp) == db->db_level);
2185 
2186 	mutex_enter(&db->db_mtx);
2187 
2188 	if (db->db_level == 0) {
2189 		mutex_enter(&dn->dn_mtx);
2190 		if (db->db_blkid > dn->dn_phys->dn_maxblkid)
2191 			dn->dn_phys->dn_maxblkid = db->db_blkid;
2192 		mutex_exit(&dn->dn_mtx);
2193 
2194 		if (dn->dn_type == DMU_OT_DNODE) {
2195 			dnode_phys_t *dnp = db->db.db_data;
2196 			for (i = db->db.db_size >> DNODE_SHIFT; i > 0;
2197 			    i--, dnp++) {
2198 				if (dnp->dn_type != DMU_OT_NONE)
2199 					fill++;
2200 			}
2201 		} else {
2202 			fill = 1;
2203 		}
2204 	} else {
2205 		blkptr_t *ibp = db->db.db_data;
2206 		ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
2207 		for (i = db->db.db_size >> SPA_BLKPTRSHIFT; i > 0; i--, ibp++) {
2208 			if (BP_IS_HOLE(ibp))
2209 				continue;
2210 			ASSERT3U(BP_GET_LSIZE(ibp), ==,
2211 			    db->db_level == 1 ? dn->dn_datablksz :
2212 			    (1<<dn->dn_phys->dn_indblkshift));
2213 			fill += ibp->blk_fill;
2214 		}
2215 	}
2216 
2217 	bp->blk_fill = fill;
2218 
2219 	mutex_exit(&db->db_mtx);
2220 }
2221 
2222 /* ARGSUSED */
2223 static void
2224 dbuf_write_done(zio_t *zio, arc_buf_t *buf, void *vdb)
2225 {
2226 	dmu_buf_impl_t *db = vdb;
2227 	blkptr_t *bp = zio->io_bp;
2228 	blkptr_t *bp_orig = &zio->io_bp_orig;
2229 	dnode_t *dn = db->db_dnode;
2230 	objset_t *os = dn->dn_objset;
2231 	uint64_t txg = zio->io_txg;
2232 	dbuf_dirty_record_t **drp, *dr;
2233 
2234 	ASSERT3U(zio->io_error, ==, 0);
2235 	ASSERT(db->db_blkptr == bp);
2236 
2237 	if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
2238 		ASSERT(BP_EQUAL(bp, bp_orig));
2239 	} else {
2240 		dsl_dataset_t *ds = os->os_dsl_dataset;
2241 		dmu_tx_t *tx = os->os_synctx;
2242 
2243 		(void) dsl_dataset_block_kill(ds, bp_orig, tx, B_TRUE);
2244 		dsl_dataset_block_born(ds, bp, tx);
2245 	}
2246 
2247 	mutex_enter(&db->db_mtx);
2248 
2249 	DBUF_VERIFY(db);
2250 
2251 	drp = &db->db_last_dirty;
2252 	while ((dr = *drp) != db->db_data_pending)
2253 		drp = &dr->dr_next;
2254 	ASSERT(!list_link_active(&dr->dr_dirty_node));
2255 	ASSERT(dr->dr_txg == txg);
2256 	ASSERT(dr->dr_dbuf == db);
2257 	ASSERT(dr->dr_next == NULL);
2258 	*drp = dr->dr_next;
2259 
2260 	if (db->db_level == 0) {
2261 		ASSERT(db->db_blkid != DB_BONUS_BLKID);
2262 		ASSERT(dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN);
2263 		if (db->db_state != DB_NOFILL) {
2264 			if (dr->dt.dl.dr_data != db->db_buf)
2265 				VERIFY(arc_buf_remove_ref(dr->dt.dl.dr_data,
2266 				    db) == 1);
2267 			else if (!arc_released(db->db_buf))
2268 				arc_set_callback(db->db_buf, dbuf_do_evict, db);
2269 		}
2270 	} else {
2271 		ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
2272 		ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
2273 		if (!BP_IS_HOLE(db->db_blkptr)) {
2274 			int epbs =
2275 			    dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
2276 			ASSERT3U(BP_GET_LSIZE(db->db_blkptr), ==,
2277 			    db->db.db_size);
2278 			ASSERT3U(dn->dn_phys->dn_maxblkid
2279 			    >> (db->db_level * epbs), >=, db->db_blkid);
2280 			arc_set_callback(db->db_buf, dbuf_do_evict, db);
2281 		}
2282 		mutex_destroy(&dr->dt.di.dr_mtx);
2283 		list_destroy(&dr->dt.di.dr_children);
2284 	}
2285 	kmem_free(dr, sizeof (dbuf_dirty_record_t));
2286 
2287 	cv_broadcast(&db->db_changed);
2288 	ASSERT(db->db_dirtycnt > 0);
2289 	db->db_dirtycnt -= 1;
2290 	db->db_data_pending = NULL;
2291 	dbuf_rele_and_unlock(db, (void *)(uintptr_t)txg);
2292 }
2293 
2294 static void
2295 dbuf_write_nofill_ready(zio_t *zio)
2296 {
2297 	dbuf_write_ready(zio, NULL, zio->io_private);
2298 }
2299 
2300 static void
2301 dbuf_write_nofill_done(zio_t *zio)
2302 {
2303 	dbuf_write_done(zio, NULL, zio->io_private);
2304 }
2305 
2306 static void
2307 dbuf_write_override_ready(zio_t *zio)
2308 {
2309 	dbuf_dirty_record_t *dr = zio->io_private;
2310 	dmu_buf_impl_t *db = dr->dr_dbuf;
2311 
2312 	dbuf_write_ready(zio, NULL, db);
2313 }
2314 
2315 static void
2316 dbuf_write_override_done(zio_t *zio)
2317 {
2318 	dbuf_dirty_record_t *dr = zio->io_private;
2319 	dmu_buf_impl_t *db = dr->dr_dbuf;
2320 	blkptr_t *obp = &dr->dt.dl.dr_overridden_by;
2321 
2322 	mutex_enter(&db->db_mtx);
2323 	if (!BP_EQUAL(zio->io_bp, obp)) {
2324 		if (!BP_IS_HOLE(obp))
2325 			dsl_free(spa_get_dsl(zio->io_spa), zio->io_txg, obp);
2326 		arc_release(dr->dt.dl.dr_data, db);
2327 	}
2328 	mutex_exit(&db->db_mtx);
2329 
2330 	dbuf_write_done(zio, NULL, db);
2331 }
2332 
2333 static void
2334 dbuf_write(dbuf_dirty_record_t *dr, arc_buf_t *data, dmu_tx_t *tx)
2335 {
2336 	dmu_buf_impl_t *db = dr->dr_dbuf;
2337 	dnode_t *dn = db->db_dnode;
2338 	objset_t *os = dn->dn_objset;
2339 	dmu_buf_impl_t *parent = db->db_parent;
2340 	uint64_t txg = tx->tx_txg;
2341 	zbookmark_t zb;
2342 	zio_prop_t zp;
2343 	zio_t *zio;
2344 
2345 	if (db->db_state != DB_NOFILL) {
2346 		if (db->db_level > 0 || dn->dn_type == DMU_OT_DNODE) {
2347 			/*
2348 			 * Private object buffers are released here rather
2349 			 * than in dbuf_dirty() since they are only modified
2350 			 * in the syncing context and we don't want the
2351 			 * overhead of making multiple copies of the data.
2352 			 */
2353 			if (BP_IS_HOLE(db->db_blkptr)) {
2354 				arc_buf_thaw(data);
2355 			} else {
2356 				arc_release(data, db);
2357 			}
2358 		}
2359 	}
2360 
2361 	if (parent != dn->dn_dbuf) {
2362 		ASSERT(parent && parent->db_data_pending);
2363 		ASSERT(db->db_level == parent->db_level-1);
2364 		ASSERT(arc_released(parent->db_buf));
2365 		zio = parent->db_data_pending->dr_zio;
2366 	} else {
2367 		ASSERT(db->db_level == dn->dn_phys->dn_nlevels-1);
2368 		ASSERT3P(db->db_blkptr, ==,
2369 		    &dn->dn_phys->dn_blkptr[db->db_blkid]);
2370 		zio = dn->dn_zio;
2371 	}
2372 
2373 	ASSERT(db->db_level == 0 || data == db->db_buf);
2374 	ASSERT3U(db->db_blkptr->blk_birth, <=, txg);
2375 	ASSERT(zio);
2376 
2377 	SET_BOOKMARK(&zb, os->os_dsl_dataset ?
2378 	    os->os_dsl_dataset->ds_object : DMU_META_OBJSET,
2379 	    db->db.db_object, db->db_level, db->db_blkid);
2380 
2381 	dmu_write_policy(os, dn, db->db_level,
2382 	    db->db_state == DB_NOFILL ? WP_NOFILL : 0, &zp);
2383 
2384 	if (db->db_level == 0 && dr->dt.dl.dr_override_state == DR_OVERRIDDEN) {
2385 		ASSERT(db->db_state != DB_NOFILL);
2386 		dr->dr_zio = zio_write(zio, os->os_spa, txg,
2387 		    db->db_blkptr, data->b_data, arc_buf_size(data), &zp,
2388 		    dbuf_write_override_ready, dbuf_write_override_done, dr,
2389 		    ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
2390 		mutex_enter(&db->db_mtx);
2391 		dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
2392 		zio_write_override(dr->dr_zio, &dr->dt.dl.dr_overridden_by,
2393 		    dr->dt.dl.dr_copies);
2394 		mutex_exit(&db->db_mtx);
2395 	} else if (db->db_state == DB_NOFILL) {
2396 		ASSERT(zp.zp_checksum == ZIO_CHECKSUM_OFF);
2397 		dr->dr_zio = zio_write(zio, os->os_spa, txg,
2398 		    db->db_blkptr, NULL, db->db.db_size, &zp,
2399 		    dbuf_write_nofill_ready, dbuf_write_nofill_done, db,
2400 		    ZIO_PRIORITY_ASYNC_WRITE,
2401 		    ZIO_FLAG_MUSTSUCCEED | ZIO_FLAG_NODATA, &zb);
2402 	} else {
2403 		ASSERT(arc_released(data));
2404 		dr->dr_zio = arc_write(zio, os->os_spa, txg,
2405 		    db->db_blkptr, data, DBUF_IS_L2CACHEABLE(db), &zp,
2406 		    dbuf_write_ready, dbuf_write_done, db,
2407 		    ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
2408 	}
2409 }
2410