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