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