dbuf.c revision 290754
179110Sjoerg/*
279110Sjoerg * CDDL HEADER START
379110Sjoerg *
479110Sjoerg * The contents of this file are subject to the terms of the
579110Sjoerg * Common Development and Distribution License (the "License").
679110Sjoerg * You may not use this file except in compliance with the License.
779110Sjoerg *
879110Sjoerg * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
979110Sjoerg * or http://www.opensolaris.org/os/licensing.
1079110Sjoerg * See the License for the specific language governing permissions
1179110Sjoerg * and limitations under the License.
1279110Sjoerg *
1379110Sjoerg * When distributing Covered Code, include this CDDL HEADER in each
1479110Sjoerg * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
1579110Sjoerg * If applicable, add the following below this CDDL HEADER, with the
1679110Sjoerg * fields enclosed by brackets "[]" replaced with your own identifying
1779110Sjoerg * information: Portions Copyright [yyyy] [name of copyright owner]
1879110Sjoerg *
1979110Sjoerg * CDDL HEADER END
2079110Sjoerg */
2179110Sjoerg/*
2279110Sjoerg * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
2379110Sjoerg * Copyright 2011 Nexenta Systems, Inc.  All rights reserved.
2479110Sjoerg * Copyright (c) 2012, 2015 by Delphix. All rights reserved.
2579110Sjoerg * Copyright (c) 2013 by Saso Kiselkov. All rights reserved.
2679110Sjoerg * Copyright (c) 2013, Joyent, Inc. All rights reserved.
2779110Sjoerg * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
2879110Sjoerg */
2987992Sjoerg
3087992Sjoerg#include <sys/zfs_context.h>
3179110Sjoerg#include <sys/dmu.h>
3279110Sjoerg#include <sys/dmu_send.h>
3387992Sjoerg#include <sys/dmu_impl.h>
3479110Sjoerg#include <sys/dbuf.h>
3587992Sjoerg#include <sys/dmu_objset.h>
3679110Sjoerg#include <sys/dsl_dataset.h>
3787992Sjoerg#include <sys/dsl_dir.h>
3879110Sjoerg#include <sys/dmu_tx.h>
3979110Sjoerg#include <sys/spa.h>
4079110Sjoerg#include <sys/zio.h>
4187992Sjoerg#include <sys/dmu_zfetch.h>
4287992Sjoerg#include <sys/sa.h>
4387992Sjoerg#include <sys/sa_impl.h>
4487992Sjoerg#include <sys/zfeature.h>
4587992Sjoerg#include <sys/blkptr.h>
4679110Sjoerg#include <sys/range_tree.h>
4779110Sjoerg
4879110Sjoerg/*
4979110Sjoerg * Number of times that zfs_free_range() took the slow path while doing
5079110Sjoerg * a zfs receive.  A nonzero value indicates a potential performance problem.
5179110Sjoerg */
5279110Sjoerguint64_t zfs_free_range_recv_miss;
5379110Sjoerg
5479110Sjoergstatic void dbuf_destroy(dmu_buf_impl_t *db);
5579110Sjoergstatic boolean_t dbuf_undirty(dmu_buf_impl_t *db, dmu_tx_t *tx);
5679110Sjoergstatic void dbuf_write(dbuf_dirty_record_t *dr, arc_buf_t *data, dmu_tx_t *tx);
5779110Sjoerg
5879110Sjoerg/*
5979110Sjoerg * Global data structures and functions for the dbuf cache.
6079110Sjoerg */
6179110Sjoergstatic kmem_cache_t *dbuf_cache;
62134081Sphkstatic taskq_t *dbu_evict_taskq;
63134081Sphk
64134081Sphk/* ARGSUSED */
6579110Sjoergstatic int
6679110Sjoergdbuf_cons(void *vdb, void *unused, int kmflag)
6779110Sjoerg{
6879110Sjoerg	dmu_buf_impl_t *db = vdb;
6979110Sjoerg	bzero(db, sizeof (dmu_buf_impl_t));
7079110Sjoerg
7179110Sjoerg	mutex_init(&db->db_mtx, NULL, MUTEX_DEFAULT, NULL);
7279110Sjoerg	cv_init(&db->db_changed, NULL, CV_DEFAULT, NULL);
7379110Sjoerg	refcount_create(&db->db_holds);
7479110Sjoerg
7579110Sjoerg	return (0);
7679110Sjoerg}
7779110Sjoerg
7879110Sjoerg/* ARGSUSED */
7979110Sjoergstatic void
8079110Sjoergdbuf_dest(void *vdb, void *unused)
8179110Sjoerg{
8279110Sjoerg	dmu_buf_impl_t *db = vdb;
8379110Sjoerg	mutex_destroy(&db->db_mtx);
8479110Sjoerg	cv_destroy(&db->db_changed);
8579110Sjoerg	refcount_destroy(&db->db_holds);
8679110Sjoerg}
8779110Sjoerg
8879110Sjoerg/*
8979110Sjoerg * dbuf hash table routines
90134081Sphk */
91134081Sphkstatic dbuf_hash_table_t dbuf_hash_table;
92126230Sphk
93127522Snyanstatic uint64_t dbuf_hash_count;
94134081Sphk
95274024Snyanstatic uint64_t
96127522Snyandbuf_hash(void *os, uint64_t obj, uint8_t lvl, uint64_t blkid)
97134081Sphk{
98127522Snyan	uintptr_t osv = (uintptr_t)os;
99134081Sphk	uint64_t crc = -1ULL;
100134081Sphk
101134081Sphk	ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
102134081Sphk	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (lvl)) & 0xFF];
103134081Sphk	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (osv >> 6)) & 0xFF];
104134081Sphk	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (obj >> 0)) & 0xFF];
105134081Sphk	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (obj >> 8)) & 0xFF];
106274024Snyan	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (blkid >> 0)) & 0xFF];
107139905Sdelphij	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (blkid >> 8)) & 0xFF];
108127522Snyan
109127522Snyan	crc ^= (osv>>14) ^ (obj>>16) ^ (blkid>>16);
110127522Snyan
111137459Snyan	return (crc);
112134081Sphk}
113134081Sphk
114134081Sphk#define	DBUF_HASH(os, obj, level, blkid) dbuf_hash(os, obj, level, blkid);
115137459Snyan
116137459Snyan#define	DBUF_EQUAL(dbuf, os, obj, level, blkid)		\
117137459Snyan	((dbuf)->db.db_object == (obj) &&		\
118139905Sdelphij	(dbuf)->db_objset == (os) &&			\
119137459Snyan	(dbuf)->db_level == (level) &&			\
120137459Snyan	(dbuf)->db_blkid == (blkid))
121137459Snyan
122137459Snyandmu_buf_impl_t *
123137459Snyandbuf_find(objset_t *os, uint64_t obj, uint8_t level, uint64_t blkid)
124137459Snyan{
125137459Snyan	dbuf_hash_table_t *h = &dbuf_hash_table;
126137459Snyan	uint64_t hv = DBUF_HASH(os, obj, level, blkid);
127139905Sdelphij	uint64_t idx = hv & h->hash_table_mask;
128137459Snyan	dmu_buf_impl_t *db;
129127522Snyan
130127522Snyan	mutex_enter(DBUF_HASH_MUTEX(h, idx));
131134081Sphk	for (db = h->hash_table[idx]; db != NULL; db = db->db_hash_next) {
132137459Snyan		if (DBUF_EQUAL(db, os, obj, level, blkid)) {
133134081Sphk			mutex_enter(&db->db_mtx);
134137459Snyan			if (db->db_state != DB_EVICTING) {
135137459Snyan				mutex_exit(DBUF_HASH_MUTEX(h, idx));
136137459Snyan				return (db);
137134081Sphk			}
138139905Sdelphij			mutex_exit(&db->db_mtx);
139137459Snyan		}
140137459Snyan	}
141137459Snyan	mutex_exit(DBUF_HASH_MUTEX(h, idx));
142134081Sphk	return (NULL);
143134081Sphk}
144134081Sphk
145134081Sphkstatic dmu_buf_impl_t *
146134081Sphkdbuf_find_bonus(objset_t *os, uint64_t object)
147134081Sphk{
148134081Sphk	dnode_t *dn;
149139905Sdelphij	dmu_buf_impl_t *db = NULL;
150137459Snyan
15187992Sjoerg	if (dnode_hold(os, object, FTAG, &dn) == 0) {
15287992Sjoerg		rw_enter(&dn->dn_struct_rwlock, RW_READER);
15387992Sjoerg		if (dn->dn_bonus != NULL) {
15487992Sjoerg			db = dn->dn_bonus;
155274024Snyan			mutex_enter(&db->db_mtx);
156134081Sphk		}
157274024Snyan		rw_exit(&dn->dn_struct_rwlock);
158139905Sdelphij		dnode_rele(dn, FTAG);
15987992Sjoerg	}
16087992Sjoerg	return (db);
16187992Sjoerg}
16287992Sjoerg
163274024Snyan/*
164134081Sphk * Insert an entry into the hash table.  If there is already an element
165274024Snyan * equal to elem in the hash table, then the already existing element
166139905Sdelphij * will be returned and the new element will not be inserted.
16787992Sjoerg * Otherwise returns NULL.
16887992Sjoerg */
169127522Snyanstatic dmu_buf_impl_t *
17087992Sjoergdbuf_hash_insert(dmu_buf_impl_t *db)
17187992Sjoerg{
17287992Sjoerg	dbuf_hash_table_t *h = &dbuf_hash_table;
17387992Sjoerg	objset_t *os = db->db_objset;
17487992Sjoerg	uint64_t obj = db->db.db_object;
17587992Sjoerg	int level = db->db_level;
17687992Sjoerg	uint64_t blkid = db->db_blkid;
17787992Sjoerg	uint64_t hv = DBUF_HASH(os, obj, level, blkid);
17887992Sjoerg	uint64_t idx = hv & h->hash_table_mask;
17987992Sjoerg	dmu_buf_impl_t *dbf;
18087992Sjoerg
18187992Sjoerg	mutex_enter(DBUF_HASH_MUTEX(h, idx));
18287992Sjoerg	for (dbf = h->hash_table[idx]; dbf != NULL; dbf = dbf->db_hash_next) {
18387992Sjoerg		if (DBUF_EQUAL(dbf, os, obj, level, blkid)) {
18487992Sjoerg			mutex_enter(&dbf->db_mtx);
18587992Sjoerg			if (dbf->db_state != DB_EVICTING) {
18687992Sjoerg				mutex_exit(DBUF_HASH_MUTEX(h, idx));
18787992Sjoerg				return (dbf);
18887992Sjoerg			}
18987992Sjoerg			mutex_exit(&dbf->db_mtx);
19087992Sjoerg		}
19187992Sjoerg	}
19287992Sjoerg
19387992Sjoerg	mutex_enter(&db->db_mtx);
19487992Sjoerg	db->db_hash_next = h->hash_table[idx];
19587992Sjoerg	h->hash_table[idx] = db;
19687992Sjoerg	mutex_exit(DBUF_HASH_MUTEX(h, idx));
19787992Sjoerg	atomic_inc_64(&dbuf_hash_count);
19887992Sjoerg
19987992Sjoerg	return (NULL);
20087992Sjoerg}
20187992Sjoerg
20287992Sjoerg/*
20387992Sjoerg * Remove an entry from the hash table.  It must be in the EVICTING state.
20487992Sjoerg */
20587992Sjoergstatic void
20687992Sjoergdbuf_hash_remove(dmu_buf_impl_t *db)
20787992Sjoerg{
20887992Sjoerg	dbuf_hash_table_t *h = &dbuf_hash_table;
20987992Sjoerg	uint64_t hv = DBUF_HASH(db->db_objset, db->db.db_object,
21087992Sjoerg	    db->db_level, db->db_blkid);
21187992Sjoerg	uint64_t idx = hv & h->hash_table_mask;
21287992Sjoerg	dmu_buf_impl_t *dbf, **dbp;
21387992Sjoerg
21487992Sjoerg	/*
21587992Sjoerg	 * We musn't hold db_mtx to maintain lock ordering:
21687992Sjoerg	 * DBUF_HASH_MUTEX > db_mtx.
21787992Sjoerg	 */
21887992Sjoerg	ASSERT(refcount_is_zero(&db->db_holds));
21987992Sjoerg	ASSERT(db->db_state == DB_EVICTING);
22087992Sjoerg	ASSERT(!MUTEX_HELD(&db->db_mtx));
22187992Sjoerg
22287992Sjoerg	mutex_enter(DBUF_HASH_MUTEX(h, idx));
22387992Sjoerg	dbp = &h->hash_table[idx];
22487992Sjoerg	while ((dbf = *dbp) != db) {
22587992Sjoerg		dbp = &dbf->db_hash_next;
22687992Sjoerg		ASSERT(dbf != NULL);
22787992Sjoerg	}
22887992Sjoerg	*dbp = db->db_hash_next;
22987992Sjoerg	db->db_hash_next = NULL;
23087992Sjoerg	mutex_exit(DBUF_HASH_MUTEX(h, idx));
23187992Sjoerg	atomic_dec_64(&dbuf_hash_count);
23287992Sjoerg}
23387992Sjoerg
23487992Sjoergstatic arc_evict_func_t dbuf_do_evict;
23587992Sjoerg
23687992Sjoergtypedef enum {
23787992Sjoerg	DBVU_EVICTING,
23887992Sjoerg	DBVU_NOT_EVICTING
23987992Sjoerg} dbvu_verify_type_t;
24087992Sjoerg
24187992Sjoergstatic void
24287992Sjoergdbuf_verify_user(dmu_buf_impl_t *db, dbvu_verify_type_t verify_type)
24387992Sjoerg{
24487992Sjoerg#ifdef ZFS_DEBUG
24587992Sjoerg	int64_t holds;
24687992Sjoerg
24787992Sjoerg	if (db->db_user == NULL)
24887992Sjoerg		return;
24987992Sjoerg
25087992Sjoerg	/* Only data blocks support the attachment of user data. */
25187992Sjoerg	ASSERT(db->db_level == 0);
25287992Sjoerg
25387992Sjoerg	/* Clients must resolve a dbuf before attaching user data. */
25487992Sjoerg	ASSERT(db->db.db_data != NULL);
25587992Sjoerg	ASSERT3U(db->db_state, ==, DB_CACHED);
25687992Sjoerg
25787992Sjoerg	holds = refcount_count(&db->db_holds);
25887992Sjoerg	if (verify_type == DBVU_EVICTING) {
25987992Sjoerg		/*
26087992Sjoerg		 * Immediate eviction occurs when holds == dirtycnt.
26187992Sjoerg		 * For normal eviction buffers, holds is zero on
26287992Sjoerg		 * eviction, except when dbuf_fix_old_data() calls
26387992Sjoerg		 * dbuf_clear_data().  However, the hold count can grow
26487992Sjoerg		 * during eviction even though db_mtx is held (see
26587992Sjoerg		 * dmu_bonus_hold() for an example), so we can only
26687992Sjoerg		 * test the generic invariant that holds >= dirtycnt.
26787992Sjoerg		 */
26887992Sjoerg		ASSERT3U(holds, >=, db->db_dirtycnt);
26987992Sjoerg	} else {
27087992Sjoerg		if (db->db_user_immediate_evict == TRUE)
27187992Sjoerg			ASSERT3U(holds, >=, db->db_dirtycnt);
27287992Sjoerg		else
27387992Sjoerg			ASSERT3U(holds, >, 0);
27487992Sjoerg	}
27587992Sjoerg#endif
27687992Sjoerg}
27787992Sjoerg
27887992Sjoergstatic void
27987992Sjoergdbuf_evict_user(dmu_buf_impl_t *db)
280127522Snyan{
28187992Sjoerg	dmu_buf_user_t *dbu = db->db_user;
28287992Sjoerg
28387992Sjoerg	ASSERT(MUTEX_HELD(&db->db_mtx));
28487992Sjoerg
28587992Sjoerg	if (dbu == NULL)
28687992Sjoerg		return;
287134081Sphk
288134081Sphk	dbuf_verify_user(db, DBVU_EVICTING);
28987992Sjoerg	db->db_user = NULL;
29087992Sjoerg
29187992Sjoerg#ifdef ZFS_DEBUG
292127522Snyan	if (dbu->dbu_clear_on_evict_dbufp != NULL)
29387992Sjoerg		*dbu->dbu_clear_on_evict_dbufp = NULL;
29487992Sjoerg#endif
29587992Sjoerg
29687992Sjoerg	/*
29787992Sjoerg	 * Invoke the callback from a taskq to avoid lock order reversals
29887992Sjoerg	 * and limit stack depth.
29987992Sjoerg	 */
30087992Sjoerg	taskq_dispatch_ent(dbu_evict_taskq, dbu->dbu_evict_func, dbu, 0,
30187992Sjoerg	    &dbu->dbu_tqent);
30287992Sjoerg}
30387992Sjoerg
30487992Sjoergboolean_t
305127522Snyandbuf_is_metadata(dmu_buf_impl_t *db)
30687992Sjoerg{
30787992Sjoerg	if (db->db_level > 0) {
30887992Sjoerg		return (B_TRUE);
30987992Sjoerg	} else {
31087992Sjoerg		boolean_t is_metadata;
31187992Sjoerg
31287992Sjoerg		DB_DNODE_ENTER(db);
31387992Sjoerg		is_metadata = DMU_OT_IS_METADATA(DB_DNODE(db)->dn_type);
31487992Sjoerg		DB_DNODE_EXIT(db);
31587992Sjoerg
31687992Sjoerg		return (is_metadata);
31787992Sjoerg	}
31887992Sjoerg}
31987992Sjoerg
32087992Sjoergvoid
32187992Sjoergdbuf_evict(dmu_buf_impl_t *db)
32287992Sjoerg{
32387992Sjoerg	ASSERT(MUTEX_HELD(&db->db_mtx));
32487992Sjoerg	ASSERT(db->db_buf == NULL);
32587992Sjoerg	ASSERT(db->db_data_pending == NULL);
32687992Sjoerg
32787992Sjoerg	dbuf_clear(db);
32887992Sjoerg	dbuf_destroy(db);
32987992Sjoerg}
33087992Sjoerg
33187992Sjoergvoid
33287992Sjoergdbuf_init(void)
33387992Sjoerg{
33487992Sjoerg	uint64_t hsize = 1ULL << 16;
33587992Sjoerg	dbuf_hash_table_t *h = &dbuf_hash_table;
33687992Sjoerg	int i;
33787992Sjoerg
33887992Sjoerg	/*
33987992Sjoerg	 * The hash table is big enough to fill all of physical memory
34087992Sjoerg	 * with an average 4K block size.  The table will take up
34187992Sjoerg	 * totalmem*sizeof(void*)/4K (i.e. 2MB/GB with 8-byte pointers).
34287992Sjoerg	 */
343134081Sphk	while (hsize * 4096 < (uint64_t)physmem * PAGESIZE)
344134081Sphk		hsize <<= 1;
345134081Sphk
346134081Sphkretry:
34787992Sjoerg	h->hash_table_mask = hsize - 1;
34887992Sjoerg	h->hash_table = kmem_zalloc(hsize * sizeof (void *), KM_NOSLEEP);
34987992Sjoerg	if (h->hash_table == NULL) {
35087992Sjoerg		/* XXX - we should really return an error instead of assert */
35187992Sjoerg		ASSERT(hsize > (1ULL << 10));
35287992Sjoerg		hsize >>= 1;
35387992Sjoerg		goto retry;
35487992Sjoerg	}
35587992Sjoerg
35687992Sjoerg	dbuf_cache = kmem_cache_create("dmu_buf_impl_t",
35787992Sjoerg	    sizeof (dmu_buf_impl_t),
35887992Sjoerg	    0, dbuf_cons, dbuf_dest, NULL, NULL, NULL, 0);
35987992Sjoerg
36087992Sjoerg	for (i = 0; i < DBUF_MUTEXES; i++)
36187992Sjoerg		mutex_init(&h->hash_mutexes[i], NULL, MUTEX_DEFAULT, NULL);
362126230Sphk
36387992Sjoerg	/*
36487992Sjoerg	 * All entries are queued via taskq_dispatch_ent(), so min/maxalloc
36587992Sjoerg	 * configuration is not required.
36687992Sjoerg	 */
36787992Sjoerg	dbu_evict_taskq = taskq_create("dbu_evict", 1, minclsyspri, 0, 0, 0);
36887992Sjoerg}
36987992Sjoerg
37087992Sjoergvoid
37187992Sjoergdbuf_fini(void)
37287992Sjoerg{
37387992Sjoerg	dbuf_hash_table_t *h = &dbuf_hash_table;
37487992Sjoerg	int i;
37587992Sjoerg
37687992Sjoerg	for (i = 0; i < DBUF_MUTEXES; i++)
37787992Sjoerg		mutex_destroy(&h->hash_mutexes[i]);
37887992Sjoerg	kmem_free(h->hash_table, (h->hash_table_mask + 1) * sizeof (void *));
37987992Sjoerg	kmem_cache_destroy(dbuf_cache);
38087992Sjoerg	taskq_destroy(dbu_evict_taskq);
38187992Sjoerg}
38287992Sjoerg
38387992Sjoerg/*
38487992Sjoerg * Other stuff.
38587992Sjoerg */
38687992Sjoerg
38787992Sjoerg#ifdef ZFS_DEBUG
38887992Sjoergstatic void
38987992Sjoergdbuf_verify(dmu_buf_impl_t *db)
39087992Sjoerg{
39187992Sjoerg	dnode_t *dn;
39287992Sjoerg	dbuf_dirty_record_t *dr;
393134081Sphk
394134081Sphk	ASSERT(MUTEX_HELD(&db->db_mtx));
39587992Sjoerg
39687992Sjoerg	if (!(zfs_flags & ZFS_DEBUG_DBUF_VERIFY))
39787992Sjoerg		return;
39887992Sjoerg
39987992Sjoerg	ASSERT(db->db_objset != NULL);
40087992Sjoerg	DB_DNODE_ENTER(db);
40187992Sjoerg	dn = DB_DNODE(db);
40287992Sjoerg	if (dn == NULL) {
40387992Sjoerg		ASSERT(db->db_parent == NULL);
40487992Sjoerg		ASSERT(db->db_blkptr == NULL);
40587992Sjoerg	} else {
40687992Sjoerg		ASSERT3U(db->db.db_object, ==, dn->dn_object);
40787992Sjoerg		ASSERT3P(db->db_objset, ==, dn->dn_objset);
40887992Sjoerg		ASSERT3U(db->db_level, <, dn->dn_nlevels);
40987992Sjoerg		ASSERT(db->db_blkid == DMU_BONUS_BLKID ||
41087992Sjoerg		    db->db_blkid == DMU_SPILL_BLKID ||
41187992Sjoerg		    !avl_is_empty(&dn->dn_dbufs));
41287992Sjoerg	}
41387992Sjoerg	if (db->db_blkid == DMU_BONUS_BLKID) {
41487992Sjoerg		ASSERT(dn != NULL);
41587992Sjoerg		ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
41687992Sjoerg		ASSERT3U(db->db.db_offset, ==, DMU_BONUS_BLKID);
41787992Sjoerg	} else if (db->db_blkid == DMU_SPILL_BLKID) {
41887992Sjoerg		ASSERT(dn != NULL);
41987992Sjoerg		ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
42087992Sjoerg		ASSERT0(db->db.db_offset);
42187992Sjoerg	} else {
42287992Sjoerg		ASSERT3U(db->db.db_offset, ==, db->db_blkid * db->db.db_size);
42387992Sjoerg	}
42487992Sjoerg
42587992Sjoerg	for (dr = db->db_data_pending; dr != NULL; dr = dr->dr_next)
42687992Sjoerg		ASSERT(dr->dr_dbuf == db);
42787992Sjoerg
42887992Sjoerg	for (dr = db->db_last_dirty; dr != NULL; dr = dr->dr_next)
42987992Sjoerg		ASSERT(dr->dr_dbuf == db);
43087992Sjoerg
43187992Sjoerg	/*
43287992Sjoerg	 * We can't assert that db_size matches dn_datablksz because it
43387992Sjoerg	 * can be momentarily different when another thread is doing
43487992Sjoerg	 * dnode_set_blksz().
43587992Sjoerg	 */
43687992Sjoerg	if (db->db_level == 0 && db->db.db_object == DMU_META_DNODE_OBJECT) {
43787992Sjoerg		dr = db->db_data_pending;
43887992Sjoerg		/*
43987992Sjoerg		 * It should only be modified in syncing context, so
440126230Sphk		 * make sure we only have one copy of the data.
441126230Sphk		 */
442126230Sphk		ASSERT(dr == NULL || dr->dt.dl.dr_data == db->db_buf);
443134081Sphk	}
444134081Sphk
445127522Snyan	/* verify db->db_blkptr */
446127522Snyan	if (db->db_blkptr) {
447134081Sphk		if (db->db_parent == dn->dn_dbuf) {
44887992Sjoerg			/* db is pointed to by the dnode */
44987992Sjoerg			/* ASSERT3U(db->db_blkid, <, dn->dn_nblkptr); */
45087992Sjoerg			if (DMU_OBJECT_IS_SPECIAL(db->db.db_object))
45187992Sjoerg				ASSERT(db->db_parent == NULL);
45287992Sjoerg			else
45387992Sjoerg				ASSERT(db->db_parent != NULL);
45487992Sjoerg			if (db->db_blkid != DMU_SPILL_BLKID)
45587992Sjoerg				ASSERT3P(db->db_blkptr, ==,
45687992Sjoerg				    &dn->dn_phys->dn_blkptr[db->db_blkid]);
45787992Sjoerg		} else {
45887992Sjoerg			/* db is pointed to by an indirect block */
45987992Sjoerg			int epb = db->db_parent->db.db_size >> SPA_BLKPTRSHIFT;
46087992Sjoerg			ASSERT3U(db->db_parent->db_level, ==, db->db_level+1);
46187992Sjoerg			ASSERT3U(db->db_parent->db.db_object, ==,
46287992Sjoerg			    db->db.db_object);
46387992Sjoerg			/*
46487992Sjoerg			 * dnode_grow_indblksz() can make this fail if we don't
46587992Sjoerg			 * have the struct_rwlock.  XXX indblksz no longer
46687992Sjoerg			 * grows.  safe to do this now?
46787992Sjoerg			 */
46887992Sjoerg			if (RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
46987992Sjoerg				ASSERT3P(db->db_blkptr, ==,
47087992Sjoerg				    ((blkptr_t *)db->db_parent->db.db_data +
47187992Sjoerg				    db->db_blkid % epb));
47287992Sjoerg			}
47387992Sjoerg		}
47487992Sjoerg	}
47587992Sjoerg	if ((db->db_blkptr == NULL || BP_IS_HOLE(db->db_blkptr)) &&
47687992Sjoerg	    (db->db_buf == NULL || db->db_buf->b_data) &&
47787992Sjoerg	    db->db.db_data && db->db_blkid != DMU_BONUS_BLKID &&
47887992Sjoerg	    db->db_state != DB_FILL && !dn->dn_free_txg) {
47987992Sjoerg		/*
48087992Sjoerg		 * If the blkptr isn't set but they have nonzero data,
48187992Sjoerg		 * it had better be dirty, otherwise we'll lose that
48287992Sjoerg		 * data when we evict this buffer.
48387992Sjoerg		 */
48487992Sjoerg		if (db->db_dirtycnt == 0) {
48587992Sjoerg			uint64_t *buf = db->db.db_data;
48687992Sjoerg			int i;
48787992Sjoerg
48887992Sjoerg			for (i = 0; i < db->db.db_size >> 3; i++) {
48987992Sjoerg				ASSERT(buf[i] == 0);
49087992Sjoerg			}
49187992Sjoerg		}
49287992Sjoerg	}
49387992Sjoerg	DB_DNODE_EXIT(db);
49487992Sjoerg}
49587992Sjoerg#endif
49687992Sjoerg
49787992Sjoergstatic void
49887992Sjoergdbuf_clear_data(dmu_buf_impl_t *db)
49987992Sjoerg{
50087992Sjoerg	ASSERT(MUTEX_HELD(&db->db_mtx));
50187992Sjoerg	dbuf_evict_user(db);
50287992Sjoerg	db->db_buf = NULL;
50387992Sjoerg	db->db.db_data = NULL;
50487992Sjoerg	if (db->db_state != DB_NOFILL)
50587992Sjoerg		db->db_state = DB_UNCACHED;
50687992Sjoerg}
50787992Sjoerg
50887992Sjoergstatic void
50987992Sjoergdbuf_set_data(dmu_buf_impl_t *db, arc_buf_t *buf)
510{
511	ASSERT(MUTEX_HELD(&db->db_mtx));
512	ASSERT(buf != NULL);
513
514	db->db_buf = buf;
515	ASSERT(buf->b_data != NULL);
516	db->db.db_data = buf->b_data;
517	if (!arc_released(buf))
518		arc_set_callback(buf, dbuf_do_evict, db);
519}
520
521/*
522 * Loan out an arc_buf for read.  Return the loaned arc_buf.
523 */
524arc_buf_t *
525dbuf_loan_arcbuf(dmu_buf_impl_t *db)
526{
527	arc_buf_t *abuf;
528
529	mutex_enter(&db->db_mtx);
530	if (arc_released(db->db_buf) || refcount_count(&db->db_holds) > 1) {
531		int blksz = db->db.db_size;
532		spa_t *spa = db->db_objset->os_spa;
533
534		mutex_exit(&db->db_mtx);
535		abuf = arc_loan_buf(spa, blksz);
536		bcopy(db->db.db_data, abuf->b_data, blksz);
537	} else {
538		abuf = db->db_buf;
539		arc_loan_inuse_buf(abuf, db);
540		dbuf_clear_data(db);
541		mutex_exit(&db->db_mtx);
542	}
543	return (abuf);
544}
545
546/*
547 * Calculate which level n block references the data at the level 0 offset
548 * provided.
549 */
550uint64_t
551dbuf_whichblock(dnode_t *dn, int64_t level, uint64_t offset)
552{
553	if (dn->dn_datablkshift != 0 && dn->dn_indblkshift != 0) {
554		/*
555		 * The level n blkid is equal to the level 0 blkid divided by
556		 * the number of level 0s in a level n block.
557		 *
558		 * The level 0 blkid is offset >> datablkshift =
559		 * offset / 2^datablkshift.
560		 *
561		 * The number of level 0s in a level n is the number of block
562		 * pointers in an indirect block, raised to the power of level.
563		 * This is 2^(indblkshift - SPA_BLKPTRSHIFT)^level =
564		 * 2^(level*(indblkshift - SPA_BLKPTRSHIFT)).
565		 *
566		 * Thus, the level n blkid is: offset /
567		 * ((2^datablkshift)*(2^(level*(indblkshift - SPA_BLKPTRSHIFT)))
568		 * = offset / 2^(datablkshift + level *
569		 *   (indblkshift - SPA_BLKPTRSHIFT))
570		 * = offset >> (datablkshift + level *
571		 *   (indblkshift - SPA_BLKPTRSHIFT))
572		 */
573		return (offset >> (dn->dn_datablkshift + level *
574		    (dn->dn_indblkshift - SPA_BLKPTRSHIFT)));
575	} else {
576		ASSERT3U(offset, <, dn->dn_datablksz);
577		return (0);
578	}
579}
580
581static void
582dbuf_read_done(zio_t *zio, arc_buf_t *buf, void *vdb)
583{
584	dmu_buf_impl_t *db = vdb;
585
586	mutex_enter(&db->db_mtx);
587	ASSERT3U(db->db_state, ==, DB_READ);
588	/*
589	 * All reads are synchronous, so we must have a hold on the dbuf
590	 */
591	ASSERT(refcount_count(&db->db_holds) > 0);
592	ASSERT(db->db_buf == NULL);
593	ASSERT(db->db.db_data == NULL);
594	if (db->db_level == 0 && db->db_freed_in_flight) {
595		/* we were freed in flight; disregard any error */
596		arc_release(buf, db);
597		bzero(buf->b_data, db->db.db_size);
598		arc_buf_freeze(buf);
599		db->db_freed_in_flight = FALSE;
600		dbuf_set_data(db, buf);
601		db->db_state = DB_CACHED;
602	} else if (zio == NULL || zio->io_error == 0) {
603		dbuf_set_data(db, buf);
604		db->db_state = DB_CACHED;
605	} else {
606		ASSERT(db->db_blkid != DMU_BONUS_BLKID);
607		ASSERT3P(db->db_buf, ==, NULL);
608		VERIFY(arc_buf_remove_ref(buf, db));
609		db->db_state = DB_UNCACHED;
610	}
611	cv_broadcast(&db->db_changed);
612	dbuf_rele_and_unlock(db, NULL);
613}
614
615static void
616dbuf_read_impl(dmu_buf_impl_t *db, zio_t *zio, uint32_t flags)
617{
618	dnode_t *dn;
619	zbookmark_phys_t zb;
620	arc_flags_t aflags = ARC_FLAG_NOWAIT;
621
622	DB_DNODE_ENTER(db);
623	dn = DB_DNODE(db);
624	ASSERT(!refcount_is_zero(&db->db_holds));
625	/* We need the struct_rwlock to prevent db_blkptr from changing. */
626	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
627	ASSERT(MUTEX_HELD(&db->db_mtx));
628	ASSERT(db->db_state == DB_UNCACHED);
629	ASSERT(db->db_buf == NULL);
630
631	if (db->db_blkid == DMU_BONUS_BLKID) {
632		int bonuslen = MIN(dn->dn_bonuslen, dn->dn_phys->dn_bonuslen);
633
634		ASSERT3U(bonuslen, <=, db->db.db_size);
635		db->db.db_data = zio_buf_alloc(DN_MAX_BONUSLEN);
636		arc_space_consume(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
637		if (bonuslen < DN_MAX_BONUSLEN)
638			bzero(db->db.db_data, DN_MAX_BONUSLEN);
639		if (bonuslen)
640			bcopy(DN_BONUS(dn->dn_phys), db->db.db_data, bonuslen);
641		DB_DNODE_EXIT(db);
642		db->db_state = DB_CACHED;
643		mutex_exit(&db->db_mtx);
644		return;
645	}
646
647	/*
648	 * Recheck BP_IS_HOLE() after dnode_block_freed() in case dnode_sync()
649	 * processes the delete record and clears the bp while we are waiting
650	 * for the dn_mtx (resulting in a "no" from block_freed).
651	 */
652	if (db->db_blkptr == NULL || BP_IS_HOLE(db->db_blkptr) ||
653	    (db->db_level == 0 && (dnode_block_freed(dn, db->db_blkid) ||
654	    BP_IS_HOLE(db->db_blkptr)))) {
655		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
656
657		DB_DNODE_EXIT(db);
658		dbuf_set_data(db, arc_buf_alloc(db->db_objset->os_spa,
659		    db->db.db_size, db, type));
660		bzero(db->db.db_data, db->db.db_size);
661		db->db_state = DB_CACHED;
662		mutex_exit(&db->db_mtx);
663		return;
664	}
665
666	DB_DNODE_EXIT(db);
667
668	db->db_state = DB_READ;
669	mutex_exit(&db->db_mtx);
670
671	if (DBUF_IS_L2CACHEABLE(db))
672		aflags |= ARC_FLAG_L2CACHE;
673	if (DBUF_IS_L2COMPRESSIBLE(db))
674		aflags |= ARC_FLAG_L2COMPRESS;
675
676	SET_BOOKMARK(&zb, db->db_objset->os_dsl_dataset ?
677	    db->db_objset->os_dsl_dataset->ds_object : DMU_META_OBJSET,
678	    db->db.db_object, db->db_level, db->db_blkid);
679
680	dbuf_add_ref(db, NULL);
681
682	(void) arc_read(zio, db->db_objset->os_spa, db->db_blkptr,
683	    dbuf_read_done, db, ZIO_PRIORITY_SYNC_READ,
684	    (flags & DB_RF_CANFAIL) ? ZIO_FLAG_CANFAIL : ZIO_FLAG_MUSTSUCCEED,
685	    &aflags, &zb);
686}
687
688int
689dbuf_read(dmu_buf_impl_t *db, zio_t *zio, uint32_t flags)
690{
691	int err = 0;
692	boolean_t havepzio = (zio != NULL);
693	boolean_t prefetch;
694	dnode_t *dn;
695
696	/*
697	 * We don't have to hold the mutex to check db_state because it
698	 * can't be freed while we have a hold on the buffer.
699	 */
700	ASSERT(!refcount_is_zero(&db->db_holds));
701
702	if (db->db_state == DB_NOFILL)
703		return (SET_ERROR(EIO));
704
705	DB_DNODE_ENTER(db);
706	dn = DB_DNODE(db);
707	if ((flags & DB_RF_HAVESTRUCT) == 0)
708		rw_enter(&dn->dn_struct_rwlock, RW_READER);
709
710	prefetch = db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
711	    (flags & DB_RF_NOPREFETCH) == 0 && dn != NULL &&
712	    DBUF_IS_CACHEABLE(db);
713
714	mutex_enter(&db->db_mtx);
715	if (db->db_state == DB_CACHED) {
716		mutex_exit(&db->db_mtx);
717		if (prefetch)
718			dmu_zfetch(&dn->dn_zfetch, db->db_blkid, 1);
719		if ((flags & DB_RF_HAVESTRUCT) == 0)
720			rw_exit(&dn->dn_struct_rwlock);
721		DB_DNODE_EXIT(db);
722	} else if (db->db_state == DB_UNCACHED) {
723		spa_t *spa = dn->dn_objset->os_spa;
724
725		if (zio == NULL)
726			zio = zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL);
727		dbuf_read_impl(db, zio, flags);
728
729		/* dbuf_read_impl has dropped db_mtx for us */
730
731		if (prefetch)
732			dmu_zfetch(&dn->dn_zfetch, db->db_blkid, 1);
733
734		if ((flags & DB_RF_HAVESTRUCT) == 0)
735			rw_exit(&dn->dn_struct_rwlock);
736		DB_DNODE_EXIT(db);
737
738		if (!havepzio)
739			err = zio_wait(zio);
740	} else {
741		/*
742		 * Another reader came in while the dbuf was in flight
743		 * between UNCACHED and CACHED.  Either a writer will finish
744		 * writing the buffer (sending the dbuf to CACHED) or the
745		 * first reader's request will reach the read_done callback
746		 * and send the dbuf to CACHED.  Otherwise, a failure
747		 * occurred and the dbuf went to UNCACHED.
748		 */
749		mutex_exit(&db->db_mtx);
750		if (prefetch)
751			dmu_zfetch(&dn->dn_zfetch, db->db_blkid, 1);
752		if ((flags & DB_RF_HAVESTRUCT) == 0)
753			rw_exit(&dn->dn_struct_rwlock);
754		DB_DNODE_EXIT(db);
755
756		/* Skip the wait per the caller's request. */
757		mutex_enter(&db->db_mtx);
758		if ((flags & DB_RF_NEVERWAIT) == 0) {
759			while (db->db_state == DB_READ ||
760			    db->db_state == DB_FILL) {
761				ASSERT(db->db_state == DB_READ ||
762				    (flags & DB_RF_HAVESTRUCT) == 0);
763				DTRACE_PROBE2(blocked__read, dmu_buf_impl_t *,
764				    db, zio_t *, zio);
765				cv_wait(&db->db_changed, &db->db_mtx);
766			}
767			if (db->db_state == DB_UNCACHED)
768				err = SET_ERROR(EIO);
769		}
770		mutex_exit(&db->db_mtx);
771	}
772
773	ASSERT(err || havepzio || db->db_state == DB_CACHED);
774	return (err);
775}
776
777static void
778dbuf_noread(dmu_buf_impl_t *db)
779{
780	ASSERT(!refcount_is_zero(&db->db_holds));
781	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
782	mutex_enter(&db->db_mtx);
783	while (db->db_state == DB_READ || db->db_state == DB_FILL)
784		cv_wait(&db->db_changed, &db->db_mtx);
785	if (db->db_state == DB_UNCACHED) {
786		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
787		spa_t *spa = db->db_objset->os_spa;
788
789		ASSERT(db->db_buf == NULL);
790		ASSERT(db->db.db_data == NULL);
791		dbuf_set_data(db, arc_buf_alloc(spa, db->db.db_size, db, type));
792		db->db_state = DB_FILL;
793	} else if (db->db_state == DB_NOFILL) {
794		dbuf_clear_data(db);
795	} else {
796		ASSERT3U(db->db_state, ==, DB_CACHED);
797	}
798	mutex_exit(&db->db_mtx);
799}
800
801/*
802 * This is our just-in-time copy function.  It makes a copy of
803 * buffers, that have been modified in a previous transaction
804 * group, before we modify them in the current active group.
805 *
806 * This function is used in two places: when we are dirtying a
807 * buffer for the first time in a txg, and when we are freeing
808 * a range in a dnode that includes this buffer.
809 *
810 * Note that when we are called from dbuf_free_range() we do
811 * not put a hold on the buffer, we just traverse the active
812 * dbuf list for the dnode.
813 */
814static void
815dbuf_fix_old_data(dmu_buf_impl_t *db, uint64_t txg)
816{
817	dbuf_dirty_record_t *dr = db->db_last_dirty;
818
819	ASSERT(MUTEX_HELD(&db->db_mtx));
820	ASSERT(db->db.db_data != NULL);
821	ASSERT(db->db_level == 0);
822	ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT);
823
824	if (dr == NULL ||
825	    (dr->dt.dl.dr_data !=
826	    ((db->db_blkid  == DMU_BONUS_BLKID) ? db->db.db_data : db->db_buf)))
827		return;
828
829	/*
830	 * If the last dirty record for this dbuf has not yet synced
831	 * and its referencing the dbuf data, either:
832	 *	reset the reference to point to a new copy,
833	 * or (if there a no active holders)
834	 *	just null out the current db_data pointer.
835	 */
836	ASSERT(dr->dr_txg >= txg - 2);
837	if (db->db_blkid == DMU_BONUS_BLKID) {
838		/* Note that the data bufs here are zio_bufs */
839		dr->dt.dl.dr_data = zio_buf_alloc(DN_MAX_BONUSLEN);
840		arc_space_consume(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
841		bcopy(db->db.db_data, dr->dt.dl.dr_data, DN_MAX_BONUSLEN);
842	} else if (refcount_count(&db->db_holds) > db->db_dirtycnt) {
843		int size = db->db.db_size;
844		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
845		spa_t *spa = db->db_objset->os_spa;
846
847		dr->dt.dl.dr_data = arc_buf_alloc(spa, size, db, type);
848		bcopy(db->db.db_data, dr->dt.dl.dr_data->b_data, size);
849	} else {
850		dbuf_clear_data(db);
851	}
852}
853
854void
855dbuf_unoverride(dbuf_dirty_record_t *dr)
856{
857	dmu_buf_impl_t *db = dr->dr_dbuf;
858	blkptr_t *bp = &dr->dt.dl.dr_overridden_by;
859	uint64_t txg = dr->dr_txg;
860
861	ASSERT(MUTEX_HELD(&db->db_mtx));
862	ASSERT(dr->dt.dl.dr_override_state != DR_IN_DMU_SYNC);
863	ASSERT(db->db_level == 0);
864
865	if (db->db_blkid == DMU_BONUS_BLKID ||
866	    dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN)
867		return;
868
869	ASSERT(db->db_data_pending != dr);
870
871	/* free this block */
872	if (!BP_IS_HOLE(bp) && !dr->dt.dl.dr_nopwrite)
873		zio_free(db->db_objset->os_spa, txg, bp);
874
875	dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
876	dr->dt.dl.dr_nopwrite = B_FALSE;
877
878	/*
879	 * Release the already-written buffer, so we leave it in
880	 * a consistent dirty state.  Note that all callers are
881	 * modifying the buffer, so they will immediately do
882	 * another (redundant) arc_release().  Therefore, leave
883	 * the buf thawed to save the effort of freezing &
884	 * immediately re-thawing it.
885	 */
886	arc_release(dr->dt.dl.dr_data, db);
887}
888
889/*
890 * Evict (if its unreferenced) or clear (if its referenced) any level-0
891 * data blocks in the free range, so that any future readers will find
892 * empty blocks.
893 *
894 * This is a no-op if the dataset is in the middle of an incremental
895 * receive; see comment below for details.
896 */
897void
898dbuf_free_range(dnode_t *dn, uint64_t start_blkid, uint64_t end_blkid,
899    dmu_tx_t *tx)
900{
901	dmu_buf_impl_t db_search;
902	dmu_buf_impl_t *db, *db_next;
903	uint64_t txg = tx->tx_txg;
904	avl_index_t where;
905
906	if (end_blkid > dn->dn_maxblkid && (end_blkid != DMU_SPILL_BLKID))
907		end_blkid = dn->dn_maxblkid;
908	dprintf_dnode(dn, "start=%llu end=%llu\n", start_blkid, end_blkid);
909
910	db_search.db_level = 0;
911	db_search.db_blkid = start_blkid;
912	db_search.db_state = DB_SEARCH;
913
914	mutex_enter(&dn->dn_dbufs_mtx);
915	if (start_blkid >= dn->dn_unlisted_l0_blkid) {
916		/* There can't be any dbufs in this range; no need to search. */
917#ifdef DEBUG
918		db = avl_find(&dn->dn_dbufs, &db_search, &where);
919		ASSERT3P(db, ==, NULL);
920		db = avl_nearest(&dn->dn_dbufs, where, AVL_AFTER);
921		ASSERT(db == NULL || db->db_level > 0);
922#endif
923		mutex_exit(&dn->dn_dbufs_mtx);
924		return;
925	} else if (dmu_objset_is_receiving(dn->dn_objset)) {
926		/*
927		 * If we are receiving, we expect there to be no dbufs in
928		 * the range to be freed, because receive modifies each
929		 * block at most once, and in offset order.  If this is
930		 * not the case, it can lead to performance problems,
931		 * so note that we unexpectedly took the slow path.
932		 */
933		atomic_inc_64(&zfs_free_range_recv_miss);
934	}
935
936	db = avl_find(&dn->dn_dbufs, &db_search, &where);
937	ASSERT3P(db, ==, NULL);
938	db = avl_nearest(&dn->dn_dbufs, where, AVL_AFTER);
939
940	for (; db != NULL; db = db_next) {
941		db_next = AVL_NEXT(&dn->dn_dbufs, db);
942		ASSERT(db->db_blkid != DMU_BONUS_BLKID);
943
944		if (db->db_level != 0 || db->db_blkid > end_blkid) {
945			break;
946		}
947		ASSERT3U(db->db_blkid, >=, start_blkid);
948
949		/* found a level 0 buffer in the range */
950		mutex_enter(&db->db_mtx);
951		if (dbuf_undirty(db, tx)) {
952			/* mutex has been dropped and dbuf destroyed */
953			continue;
954		}
955
956		if (db->db_state == DB_UNCACHED ||
957		    db->db_state == DB_NOFILL ||
958		    db->db_state == DB_EVICTING) {
959			ASSERT(db->db.db_data == NULL);
960			mutex_exit(&db->db_mtx);
961			continue;
962		}
963		if (db->db_state == DB_READ || db->db_state == DB_FILL) {
964			/* will be handled in dbuf_read_done or dbuf_rele */
965			db->db_freed_in_flight = TRUE;
966			mutex_exit(&db->db_mtx);
967			continue;
968		}
969		if (refcount_count(&db->db_holds) == 0) {
970			ASSERT(db->db_buf);
971			dbuf_clear(db);
972			continue;
973		}
974		/* The dbuf is referenced */
975
976		if (db->db_last_dirty != NULL) {
977			dbuf_dirty_record_t *dr = db->db_last_dirty;
978
979			if (dr->dr_txg == txg) {
980				/*
981				 * This buffer is "in-use", re-adjust the file
982				 * size to reflect that this buffer may
983				 * contain new data when we sync.
984				 */
985				if (db->db_blkid != DMU_SPILL_BLKID &&
986				    db->db_blkid > dn->dn_maxblkid)
987					dn->dn_maxblkid = db->db_blkid;
988				dbuf_unoverride(dr);
989			} else {
990				/*
991				 * This dbuf is not dirty in the open context.
992				 * Either uncache it (if its not referenced in
993				 * the open context) or reset its contents to
994				 * empty.
995				 */
996				dbuf_fix_old_data(db, txg);
997			}
998		}
999		/* clear the contents if its cached */
1000		if (db->db_state == DB_CACHED) {
1001			ASSERT(db->db.db_data != NULL);
1002			arc_release(db->db_buf, db);
1003			bzero(db->db.db_data, db->db.db_size);
1004			arc_buf_freeze(db->db_buf);
1005		}
1006
1007		mutex_exit(&db->db_mtx);
1008	}
1009	mutex_exit(&dn->dn_dbufs_mtx);
1010}
1011
1012static int
1013dbuf_block_freeable(dmu_buf_impl_t *db)
1014{
1015	dsl_dataset_t *ds = db->db_objset->os_dsl_dataset;
1016	uint64_t birth_txg = 0;
1017
1018	/*
1019	 * We don't need any locking to protect db_blkptr:
1020	 * If it's syncing, then db_last_dirty will be set
1021	 * so we'll ignore db_blkptr.
1022	 *
1023	 * This logic ensures that only block births for
1024	 * filled blocks are considered.
1025	 */
1026	ASSERT(MUTEX_HELD(&db->db_mtx));
1027	if (db->db_last_dirty && (db->db_blkptr == NULL ||
1028	    !BP_IS_HOLE(db->db_blkptr))) {
1029		birth_txg = db->db_last_dirty->dr_txg;
1030	} else if (db->db_blkptr != NULL && !BP_IS_HOLE(db->db_blkptr)) {
1031		birth_txg = db->db_blkptr->blk_birth;
1032	}
1033
1034	/*
1035	 * If this block don't exist or is in a snapshot, it can't be freed.
1036	 * Don't pass the bp to dsl_dataset_block_freeable() since we
1037	 * are holding the db_mtx lock and might deadlock if we are
1038	 * prefetching a dedup-ed block.
1039	 */
1040	if (birth_txg != 0)
1041		return (ds == NULL ||
1042		    dsl_dataset_block_freeable(ds, NULL, birth_txg));
1043	else
1044		return (B_FALSE);
1045}
1046
1047void
1048dbuf_new_size(dmu_buf_impl_t *db, int size, dmu_tx_t *tx)
1049{
1050	arc_buf_t *buf, *obuf;
1051	int osize = db->db.db_size;
1052	arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1053	dnode_t *dn;
1054
1055	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1056
1057	DB_DNODE_ENTER(db);
1058	dn = DB_DNODE(db);
1059
1060	/* XXX does *this* func really need the lock? */
1061	ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
1062
1063	/*
1064	 * This call to dmu_buf_will_dirty() with the dn_struct_rwlock held
1065	 * is OK, because there can be no other references to the db
1066	 * when we are changing its size, so no concurrent DB_FILL can
1067	 * be happening.
1068	 */
1069	/*
1070	 * XXX we should be doing a dbuf_read, checking the return
1071	 * value and returning that up to our callers
1072	 */
1073	dmu_buf_will_dirty(&db->db, tx);
1074
1075	/* create the data buffer for the new block */
1076	buf = arc_buf_alloc(dn->dn_objset->os_spa, size, db, type);
1077
1078	/* copy old block data to the new block */
1079	obuf = db->db_buf;
1080	bcopy(obuf->b_data, buf->b_data, MIN(osize, size));
1081	/* zero the remainder */
1082	if (size > osize)
1083		bzero((uint8_t *)buf->b_data + osize, size - osize);
1084
1085	mutex_enter(&db->db_mtx);
1086	dbuf_set_data(db, buf);
1087	VERIFY(arc_buf_remove_ref(obuf, db));
1088	db->db.db_size = size;
1089
1090	if (db->db_level == 0) {
1091		ASSERT3U(db->db_last_dirty->dr_txg, ==, tx->tx_txg);
1092		db->db_last_dirty->dt.dl.dr_data = buf;
1093	}
1094	mutex_exit(&db->db_mtx);
1095
1096	dnode_willuse_space(dn, size-osize, tx);
1097	DB_DNODE_EXIT(db);
1098}
1099
1100void
1101dbuf_release_bp(dmu_buf_impl_t *db)
1102{
1103	objset_t *os = db->db_objset;
1104
1105	ASSERT(dsl_pool_sync_context(dmu_objset_pool(os)));
1106	ASSERT(arc_released(os->os_phys_buf) ||
1107	    list_link_active(&os->os_dsl_dataset->ds_synced_link));
1108	ASSERT(db->db_parent == NULL || arc_released(db->db_parent->db_buf));
1109
1110	(void) arc_release(db->db_buf, db);
1111}
1112
1113/*
1114 * We already have a dirty record for this TXG, and we are being
1115 * dirtied again.
1116 */
1117static void
1118dbuf_redirty(dbuf_dirty_record_t *dr)
1119{
1120	dmu_buf_impl_t *db = dr->dr_dbuf;
1121
1122	ASSERT(MUTEX_HELD(&db->db_mtx));
1123
1124	if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID) {
1125		/*
1126		 * If this buffer has already been written out,
1127		 * we now need to reset its state.
1128		 */
1129		dbuf_unoverride(dr);
1130		if (db->db.db_object != DMU_META_DNODE_OBJECT &&
1131		    db->db_state != DB_NOFILL) {
1132			/* Already released on initial dirty, so just thaw. */
1133			ASSERT(arc_released(db->db_buf));
1134			arc_buf_thaw(db->db_buf);
1135		}
1136	}
1137}
1138
1139dbuf_dirty_record_t *
1140dbuf_dirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
1141{
1142	dnode_t *dn;
1143	objset_t *os;
1144	dbuf_dirty_record_t **drp, *dr;
1145	int drop_struct_lock = FALSE;
1146	boolean_t do_free_accounting = B_FALSE;
1147	int txgoff = tx->tx_txg & TXG_MASK;
1148
1149	ASSERT(tx->tx_txg != 0);
1150	ASSERT(!refcount_is_zero(&db->db_holds));
1151	DMU_TX_DIRTY_BUF(tx, db);
1152
1153	DB_DNODE_ENTER(db);
1154	dn = DB_DNODE(db);
1155	/*
1156	 * Shouldn't dirty a regular buffer in syncing context.  Private
1157	 * objects may be dirtied in syncing context, but only if they
1158	 * were already pre-dirtied in open context.
1159	 */
1160	ASSERT(!dmu_tx_is_syncing(tx) ||
1161	    BP_IS_HOLE(dn->dn_objset->os_rootbp) ||
1162	    DMU_OBJECT_IS_SPECIAL(dn->dn_object) ||
1163	    dn->dn_objset->os_dsl_dataset == NULL);
1164	/*
1165	 * We make this assert for private objects as well, but after we
1166	 * check if we're already dirty.  They are allowed to re-dirty
1167	 * in syncing context.
1168	 */
1169	ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
1170	    dn->dn_dirtyctx == DN_UNDIRTIED || dn->dn_dirtyctx ==
1171	    (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN));
1172
1173	mutex_enter(&db->db_mtx);
1174	/*
1175	 * XXX make this true for indirects too?  The problem is that
1176	 * transactions created with dmu_tx_create_assigned() from
1177	 * syncing context don't bother holding ahead.
1178	 */
1179	ASSERT(db->db_level != 0 ||
1180	    db->db_state == DB_CACHED || db->db_state == DB_FILL ||
1181	    db->db_state == DB_NOFILL);
1182
1183	mutex_enter(&dn->dn_mtx);
1184	/*
1185	 * Don't set dirtyctx to SYNC if we're just modifying this as we
1186	 * initialize the objset.
1187	 */
1188	if (dn->dn_dirtyctx == DN_UNDIRTIED &&
1189	    !BP_IS_HOLE(dn->dn_objset->os_rootbp)) {
1190		dn->dn_dirtyctx =
1191		    (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN);
1192		ASSERT(dn->dn_dirtyctx_firstset == NULL);
1193		dn->dn_dirtyctx_firstset = kmem_alloc(1, KM_SLEEP);
1194	}
1195	mutex_exit(&dn->dn_mtx);
1196
1197	if (db->db_blkid == DMU_SPILL_BLKID)
1198		dn->dn_have_spill = B_TRUE;
1199
1200	/*
1201	 * If this buffer is already dirty, we're done.
1202	 */
1203	drp = &db->db_last_dirty;
1204	ASSERT(*drp == NULL || (*drp)->dr_txg <= tx->tx_txg ||
1205	    db->db.db_object == DMU_META_DNODE_OBJECT);
1206	while ((dr = *drp) != NULL && dr->dr_txg > tx->tx_txg)
1207		drp = &dr->dr_next;
1208	if (dr && dr->dr_txg == tx->tx_txg) {
1209		DB_DNODE_EXIT(db);
1210
1211		dbuf_redirty(dr);
1212		mutex_exit(&db->db_mtx);
1213		return (dr);
1214	}
1215
1216	/*
1217	 * Only valid if not already dirty.
1218	 */
1219	ASSERT(dn->dn_object == 0 ||
1220	    dn->dn_dirtyctx == DN_UNDIRTIED || dn->dn_dirtyctx ==
1221	    (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN));
1222
1223	ASSERT3U(dn->dn_nlevels, >, db->db_level);
1224	ASSERT((dn->dn_phys->dn_nlevels == 0 && db->db_level == 0) ||
1225	    dn->dn_phys->dn_nlevels > db->db_level ||
1226	    dn->dn_next_nlevels[txgoff] > db->db_level ||
1227	    dn->dn_next_nlevels[(tx->tx_txg-1) & TXG_MASK] > db->db_level ||
1228	    dn->dn_next_nlevels[(tx->tx_txg-2) & TXG_MASK] > db->db_level);
1229
1230	/*
1231	 * We should only be dirtying in syncing context if it's the
1232	 * mos or we're initializing the os or it's a special object.
1233	 * However, we are allowed to dirty in syncing context provided
1234	 * we already dirtied it in open context.  Hence we must make
1235	 * this assertion only if we're not already dirty.
1236	 */
1237	os = dn->dn_objset;
1238	ASSERT(!dmu_tx_is_syncing(tx) || DMU_OBJECT_IS_SPECIAL(dn->dn_object) ||
1239	    os->os_dsl_dataset == NULL || BP_IS_HOLE(os->os_rootbp));
1240	ASSERT(db->db.db_size != 0);
1241
1242	dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
1243
1244	if (db->db_blkid != DMU_BONUS_BLKID) {
1245		/*
1246		 * Update the accounting.
1247		 * Note: we delay "free accounting" until after we drop
1248		 * the db_mtx.  This keeps us from grabbing other locks
1249		 * (and possibly deadlocking) in bp_get_dsize() while
1250		 * also holding the db_mtx.
1251		 */
1252		dnode_willuse_space(dn, db->db.db_size, tx);
1253		do_free_accounting = dbuf_block_freeable(db);
1254	}
1255
1256	/*
1257	 * If this buffer is dirty in an old transaction group we need
1258	 * to make a copy of it so that the changes we make in this
1259	 * transaction group won't leak out when we sync the older txg.
1260	 */
1261	dr = kmem_zalloc(sizeof (dbuf_dirty_record_t), KM_SLEEP);
1262	if (db->db_level == 0) {
1263		void *data_old = db->db_buf;
1264
1265		if (db->db_state != DB_NOFILL) {
1266			if (db->db_blkid == DMU_BONUS_BLKID) {
1267				dbuf_fix_old_data(db, tx->tx_txg);
1268				data_old = db->db.db_data;
1269			} else if (db->db.db_object != DMU_META_DNODE_OBJECT) {
1270				/*
1271				 * Release the data buffer from the cache so
1272				 * that we can modify it without impacting
1273				 * possible other users of this cached data
1274				 * block.  Note that indirect blocks and
1275				 * private objects are not released until the
1276				 * syncing state (since they are only modified
1277				 * then).
1278				 */
1279				arc_release(db->db_buf, db);
1280				dbuf_fix_old_data(db, tx->tx_txg);
1281				data_old = db->db_buf;
1282			}
1283			ASSERT(data_old != NULL);
1284		}
1285		dr->dt.dl.dr_data = data_old;
1286	} else {
1287		mutex_init(&dr->dt.di.dr_mtx, NULL, MUTEX_DEFAULT, NULL);
1288		list_create(&dr->dt.di.dr_children,
1289		    sizeof (dbuf_dirty_record_t),
1290		    offsetof(dbuf_dirty_record_t, dr_dirty_node));
1291	}
1292	if (db->db_blkid != DMU_BONUS_BLKID && os->os_dsl_dataset != NULL)
1293		dr->dr_accounted = db->db.db_size;
1294	dr->dr_dbuf = db;
1295	dr->dr_txg = tx->tx_txg;
1296	dr->dr_next = *drp;
1297	*drp = dr;
1298
1299	/*
1300	 * We could have been freed_in_flight between the dbuf_noread
1301	 * and dbuf_dirty.  We win, as though the dbuf_noread() had
1302	 * happened after the free.
1303	 */
1304	if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
1305	    db->db_blkid != DMU_SPILL_BLKID) {
1306		mutex_enter(&dn->dn_mtx);
1307		if (dn->dn_free_ranges[txgoff] != NULL) {
1308			range_tree_clear(dn->dn_free_ranges[txgoff],
1309			    db->db_blkid, 1);
1310		}
1311		mutex_exit(&dn->dn_mtx);
1312		db->db_freed_in_flight = FALSE;
1313	}
1314
1315	/*
1316	 * This buffer is now part of this txg
1317	 */
1318	dbuf_add_ref(db, (void *)(uintptr_t)tx->tx_txg);
1319	db->db_dirtycnt += 1;
1320	ASSERT3U(db->db_dirtycnt, <=, 3);
1321
1322	mutex_exit(&db->db_mtx);
1323
1324	if (db->db_blkid == DMU_BONUS_BLKID ||
1325	    db->db_blkid == DMU_SPILL_BLKID) {
1326		mutex_enter(&dn->dn_mtx);
1327		ASSERT(!list_link_active(&dr->dr_dirty_node));
1328		list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
1329		mutex_exit(&dn->dn_mtx);
1330		dnode_setdirty(dn, tx);
1331		DB_DNODE_EXIT(db);
1332		return (dr);
1333	} else if (do_free_accounting) {
1334		blkptr_t *bp = db->db_blkptr;
1335		int64_t willfree = (bp && !BP_IS_HOLE(bp)) ?
1336		    bp_get_dsize(os->os_spa, bp) : db->db.db_size;
1337		/*
1338		 * This is only a guess -- if the dbuf is dirty
1339		 * in a previous txg, we don't know how much
1340		 * space it will use on disk yet.  We should
1341		 * really have the struct_rwlock to access
1342		 * db_blkptr, but since this is just a guess,
1343		 * it's OK if we get an odd answer.
1344		 */
1345		ddt_prefetch(os->os_spa, bp);
1346		dnode_willuse_space(dn, -willfree, tx);
1347	}
1348
1349	if (!RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
1350		rw_enter(&dn->dn_struct_rwlock, RW_READER);
1351		drop_struct_lock = TRUE;
1352	}
1353
1354	if (db->db_level == 0) {
1355		dnode_new_blkid(dn, db->db_blkid, tx, drop_struct_lock);
1356		ASSERT(dn->dn_maxblkid >= db->db_blkid);
1357	}
1358
1359	if (db->db_level+1 < dn->dn_nlevels) {
1360		dmu_buf_impl_t *parent = db->db_parent;
1361		dbuf_dirty_record_t *di;
1362		int parent_held = FALSE;
1363
1364		if (db->db_parent == NULL || db->db_parent == dn->dn_dbuf) {
1365			int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
1366
1367			parent = dbuf_hold_level(dn, db->db_level+1,
1368			    db->db_blkid >> epbs, FTAG);
1369			ASSERT(parent != NULL);
1370			parent_held = TRUE;
1371		}
1372		if (drop_struct_lock)
1373			rw_exit(&dn->dn_struct_rwlock);
1374		ASSERT3U(db->db_level+1, ==, parent->db_level);
1375		di = dbuf_dirty(parent, tx);
1376		if (parent_held)
1377			dbuf_rele(parent, FTAG);
1378
1379		mutex_enter(&db->db_mtx);
1380		/*
1381		 * Since we've dropped the mutex, it's possible that
1382		 * dbuf_undirty() might have changed this out from under us.
1383		 */
1384		if (db->db_last_dirty == dr ||
1385		    dn->dn_object == DMU_META_DNODE_OBJECT) {
1386			mutex_enter(&di->dt.di.dr_mtx);
1387			ASSERT3U(di->dr_txg, ==, tx->tx_txg);
1388			ASSERT(!list_link_active(&dr->dr_dirty_node));
1389			list_insert_tail(&di->dt.di.dr_children, dr);
1390			mutex_exit(&di->dt.di.dr_mtx);
1391			dr->dr_parent = di;
1392		}
1393		mutex_exit(&db->db_mtx);
1394	} else {
1395		ASSERT(db->db_level+1 == dn->dn_nlevels);
1396		ASSERT(db->db_blkid < dn->dn_nblkptr);
1397		ASSERT(db->db_parent == NULL || db->db_parent == dn->dn_dbuf);
1398		mutex_enter(&dn->dn_mtx);
1399		ASSERT(!list_link_active(&dr->dr_dirty_node));
1400		list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
1401		mutex_exit(&dn->dn_mtx);
1402		if (drop_struct_lock)
1403			rw_exit(&dn->dn_struct_rwlock);
1404	}
1405
1406	dnode_setdirty(dn, tx);
1407	DB_DNODE_EXIT(db);
1408	return (dr);
1409}
1410
1411/*
1412 * Undirty a buffer in the transaction group referenced by the given
1413 * transaction.  Return whether this evicted the dbuf.
1414 */
1415static boolean_t
1416dbuf_undirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
1417{
1418	dnode_t *dn;
1419	uint64_t txg = tx->tx_txg;
1420	dbuf_dirty_record_t *dr, **drp;
1421
1422	ASSERT(txg != 0);
1423
1424	/*
1425	 * Due to our use of dn_nlevels below, this can only be called
1426	 * in open context, unless we are operating on the MOS.
1427	 * From syncing context, dn_nlevels may be different from the
1428	 * dn_nlevels used when dbuf was dirtied.
1429	 */
1430	ASSERT(db->db_objset ==
1431	    dmu_objset_pool(db->db_objset)->dp_meta_objset ||
1432	    txg != spa_syncing_txg(dmu_objset_spa(db->db_objset)));
1433	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1434	ASSERT0(db->db_level);
1435	ASSERT(MUTEX_HELD(&db->db_mtx));
1436
1437	/*
1438	 * If this buffer is not dirty, we're done.
1439	 */
1440	for (drp = &db->db_last_dirty; (dr = *drp) != NULL; drp = &dr->dr_next)
1441		if (dr->dr_txg <= txg)
1442			break;
1443	if (dr == NULL || dr->dr_txg < txg)
1444		return (B_FALSE);
1445	ASSERT(dr->dr_txg == txg);
1446	ASSERT(dr->dr_dbuf == db);
1447
1448	DB_DNODE_ENTER(db);
1449	dn = DB_DNODE(db);
1450
1451	dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
1452
1453	ASSERT(db->db.db_size != 0);
1454
1455	dsl_pool_undirty_space(dmu_objset_pool(dn->dn_objset),
1456	    dr->dr_accounted, txg);
1457
1458	*drp = dr->dr_next;
1459
1460	/*
1461	 * Note that there are three places in dbuf_dirty()
1462	 * where this dirty record may be put on a list.
1463	 * Make sure to do a list_remove corresponding to
1464	 * every one of those list_insert calls.
1465	 */
1466	if (dr->dr_parent) {
1467		mutex_enter(&dr->dr_parent->dt.di.dr_mtx);
1468		list_remove(&dr->dr_parent->dt.di.dr_children, dr);
1469		mutex_exit(&dr->dr_parent->dt.di.dr_mtx);
1470	} else if (db->db_blkid == DMU_SPILL_BLKID ||
1471	    db->db_level + 1 == dn->dn_nlevels) {
1472		ASSERT(db->db_blkptr == NULL || db->db_parent == dn->dn_dbuf);
1473		mutex_enter(&dn->dn_mtx);
1474		list_remove(&dn->dn_dirty_records[txg & TXG_MASK], dr);
1475		mutex_exit(&dn->dn_mtx);
1476	}
1477	DB_DNODE_EXIT(db);
1478
1479	if (db->db_state != DB_NOFILL) {
1480		dbuf_unoverride(dr);
1481
1482		ASSERT(db->db_buf != NULL);
1483		ASSERT(dr->dt.dl.dr_data != NULL);
1484		if (dr->dt.dl.dr_data != db->db_buf)
1485			VERIFY(arc_buf_remove_ref(dr->dt.dl.dr_data, db));
1486	}
1487
1488	kmem_free(dr, sizeof (dbuf_dirty_record_t));
1489
1490	ASSERT(db->db_dirtycnt > 0);
1491	db->db_dirtycnt -= 1;
1492
1493	if (refcount_remove(&db->db_holds, (void *)(uintptr_t)txg) == 0) {
1494		arc_buf_t *buf = db->db_buf;
1495
1496		ASSERT(db->db_state == DB_NOFILL || arc_released(buf));
1497		dbuf_clear_data(db);
1498		VERIFY(arc_buf_remove_ref(buf, db));
1499		dbuf_evict(db);
1500		return (B_TRUE);
1501	}
1502
1503	return (B_FALSE);
1504}
1505
1506void
1507dmu_buf_will_dirty(dmu_buf_t *db_fake, dmu_tx_t *tx)
1508{
1509	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1510	int rf = DB_RF_MUST_SUCCEED | DB_RF_NOPREFETCH;
1511
1512	ASSERT(tx->tx_txg != 0);
1513	ASSERT(!refcount_is_zero(&db->db_holds));
1514
1515	/*
1516	 * Quick check for dirtyness.  For already dirty blocks, this
1517	 * reduces runtime of this function by >90%, and overall performance
1518	 * by 50% for some workloads (e.g. file deletion with indirect blocks
1519	 * cached).
1520	 */
1521	mutex_enter(&db->db_mtx);
1522	dbuf_dirty_record_t *dr;
1523	for (dr = db->db_last_dirty;
1524	    dr != NULL && dr->dr_txg >= tx->tx_txg; dr = dr->dr_next) {
1525		/*
1526		 * It's possible that it is already dirty but not cached,
1527		 * because there are some calls to dbuf_dirty() that don't
1528		 * go through dmu_buf_will_dirty().
1529		 */
1530		if (dr->dr_txg == tx->tx_txg && db->db_state == DB_CACHED) {
1531			/* This dbuf is already dirty and cached. */
1532			dbuf_redirty(dr);
1533			mutex_exit(&db->db_mtx);
1534			return;
1535		}
1536	}
1537	mutex_exit(&db->db_mtx);
1538
1539	DB_DNODE_ENTER(db);
1540	if (RW_WRITE_HELD(&DB_DNODE(db)->dn_struct_rwlock))
1541		rf |= DB_RF_HAVESTRUCT;
1542	DB_DNODE_EXIT(db);
1543	(void) dbuf_read(db, NULL, rf);
1544	(void) dbuf_dirty(db, tx);
1545}
1546
1547void
1548dmu_buf_will_not_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
1549{
1550	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1551
1552	db->db_state = DB_NOFILL;
1553
1554	dmu_buf_will_fill(db_fake, tx);
1555}
1556
1557void
1558dmu_buf_will_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
1559{
1560	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1561
1562	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1563	ASSERT(tx->tx_txg != 0);
1564	ASSERT(db->db_level == 0);
1565	ASSERT(!refcount_is_zero(&db->db_holds));
1566
1567	ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT ||
1568	    dmu_tx_private_ok(tx));
1569
1570	dbuf_noread(db);
1571	(void) dbuf_dirty(db, tx);
1572}
1573
1574#pragma weak dmu_buf_fill_done = dbuf_fill_done
1575/* ARGSUSED */
1576void
1577dbuf_fill_done(dmu_buf_impl_t *db, dmu_tx_t *tx)
1578{
1579	mutex_enter(&db->db_mtx);
1580	DBUF_VERIFY(db);
1581
1582	if (db->db_state == DB_FILL) {
1583		if (db->db_level == 0 && db->db_freed_in_flight) {
1584			ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1585			/* we were freed while filling */
1586			/* XXX dbuf_undirty? */
1587			bzero(db->db.db_data, db->db.db_size);
1588			db->db_freed_in_flight = FALSE;
1589		}
1590		db->db_state = DB_CACHED;
1591		cv_broadcast(&db->db_changed);
1592	}
1593	mutex_exit(&db->db_mtx);
1594}
1595
1596void
1597dmu_buf_write_embedded(dmu_buf_t *dbuf, void *data,
1598    bp_embedded_type_t etype, enum zio_compress comp,
1599    int uncompressed_size, int compressed_size, int byteorder,
1600    dmu_tx_t *tx)
1601{
1602	dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbuf;
1603	struct dirty_leaf *dl;
1604	dmu_object_type_t type;
1605
1606	if (etype == BP_EMBEDDED_TYPE_DATA) {
1607		ASSERT(spa_feature_is_active(dmu_objset_spa(db->db_objset),
1608		    SPA_FEATURE_EMBEDDED_DATA));
1609	}
1610
1611	DB_DNODE_ENTER(db);
1612	type = DB_DNODE(db)->dn_type;
1613	DB_DNODE_EXIT(db);
1614
1615	ASSERT0(db->db_level);
1616	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1617
1618	dmu_buf_will_not_fill(dbuf, tx);
1619
1620	ASSERT3U(db->db_last_dirty->dr_txg, ==, tx->tx_txg);
1621	dl = &db->db_last_dirty->dt.dl;
1622	encode_embedded_bp_compressed(&dl->dr_overridden_by,
1623	    data, comp, uncompressed_size, compressed_size);
1624	BPE_SET_ETYPE(&dl->dr_overridden_by, etype);
1625	BP_SET_TYPE(&dl->dr_overridden_by, type);
1626	BP_SET_LEVEL(&dl->dr_overridden_by, 0);
1627	BP_SET_BYTEORDER(&dl->dr_overridden_by, byteorder);
1628
1629	dl->dr_override_state = DR_OVERRIDDEN;
1630	dl->dr_overridden_by.blk_birth = db->db_last_dirty->dr_txg;
1631}
1632
1633/*
1634 * Directly assign a provided arc buf to a given dbuf if it's not referenced
1635 * by anybody except our caller. Otherwise copy arcbuf's contents to dbuf.
1636 */
1637void
1638dbuf_assign_arcbuf(dmu_buf_impl_t *db, arc_buf_t *buf, dmu_tx_t *tx)
1639{
1640	ASSERT(!refcount_is_zero(&db->db_holds));
1641	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1642	ASSERT(db->db_level == 0);
1643	ASSERT(DBUF_GET_BUFC_TYPE(db) == ARC_BUFC_DATA);
1644	ASSERT(buf != NULL);
1645	ASSERT(arc_buf_size(buf) == db->db.db_size);
1646	ASSERT(tx->tx_txg != 0);
1647
1648	arc_return_buf(buf, db);
1649	ASSERT(arc_released(buf));
1650
1651	mutex_enter(&db->db_mtx);
1652
1653	while (db->db_state == DB_READ || db->db_state == DB_FILL)
1654		cv_wait(&db->db_changed, &db->db_mtx);
1655
1656	ASSERT(db->db_state == DB_CACHED || db->db_state == DB_UNCACHED);
1657
1658	if (db->db_state == DB_CACHED &&
1659	    refcount_count(&db->db_holds) - 1 > db->db_dirtycnt) {
1660		mutex_exit(&db->db_mtx);
1661		(void) dbuf_dirty(db, tx);
1662		bcopy(buf->b_data, db->db.db_data, db->db.db_size);
1663		VERIFY(arc_buf_remove_ref(buf, db));
1664		xuio_stat_wbuf_copied();
1665		return;
1666	}
1667
1668	xuio_stat_wbuf_nocopy();
1669	if (db->db_state == DB_CACHED) {
1670		dbuf_dirty_record_t *dr = db->db_last_dirty;
1671
1672		ASSERT(db->db_buf != NULL);
1673		if (dr != NULL && dr->dr_txg == tx->tx_txg) {
1674			ASSERT(dr->dt.dl.dr_data == db->db_buf);
1675			if (!arc_released(db->db_buf)) {
1676				ASSERT(dr->dt.dl.dr_override_state ==
1677				    DR_OVERRIDDEN);
1678				arc_release(db->db_buf, db);
1679			}
1680			dr->dt.dl.dr_data = buf;
1681			VERIFY(arc_buf_remove_ref(db->db_buf, db));
1682		} else if (dr == NULL || dr->dt.dl.dr_data != db->db_buf) {
1683			arc_release(db->db_buf, db);
1684			VERIFY(arc_buf_remove_ref(db->db_buf, db));
1685		}
1686		db->db_buf = NULL;
1687	}
1688	ASSERT(db->db_buf == NULL);
1689	dbuf_set_data(db, buf);
1690	db->db_state = DB_FILL;
1691	mutex_exit(&db->db_mtx);
1692	(void) dbuf_dirty(db, tx);
1693	dmu_buf_fill_done(&db->db, tx);
1694}
1695
1696/*
1697 * "Clear" the contents of this dbuf.  This will mark the dbuf
1698 * EVICTING and clear *most* of its references.  Unfortunately,
1699 * when we are not holding the dn_dbufs_mtx, we can't clear the
1700 * entry in the dn_dbufs list.  We have to wait until dbuf_destroy()
1701 * in this case.  For callers from the DMU we will usually see:
1702 *	dbuf_clear()->arc_clear_callback()->dbuf_do_evict()->dbuf_destroy()
1703 * For the arc callback, we will usually see:
1704 *	dbuf_do_evict()->dbuf_clear();dbuf_destroy()
1705 * Sometimes, though, we will get a mix of these two:
1706 *	DMU: dbuf_clear()->arc_clear_callback()
1707 *	ARC: dbuf_do_evict()->dbuf_destroy()
1708 *
1709 * This routine will dissociate the dbuf from the arc, by calling
1710 * arc_clear_callback(), but will not evict the data from the ARC.
1711 */
1712void
1713dbuf_clear(dmu_buf_impl_t *db)
1714{
1715	dnode_t *dn;
1716	dmu_buf_impl_t *parent = db->db_parent;
1717	dmu_buf_impl_t *dndb;
1718	boolean_t dbuf_gone = B_FALSE;
1719
1720	ASSERT(MUTEX_HELD(&db->db_mtx));
1721	ASSERT(refcount_is_zero(&db->db_holds));
1722
1723	dbuf_evict_user(db);
1724
1725	if (db->db_state == DB_CACHED) {
1726		ASSERT(db->db.db_data != NULL);
1727		if (db->db_blkid == DMU_BONUS_BLKID) {
1728			zio_buf_free(db->db.db_data, DN_MAX_BONUSLEN);
1729			arc_space_return(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
1730		}
1731		db->db.db_data = NULL;
1732		db->db_state = DB_UNCACHED;
1733	}
1734
1735	ASSERT(db->db_state == DB_UNCACHED || db->db_state == DB_NOFILL);
1736	ASSERT(db->db_data_pending == NULL);
1737
1738	db->db_state = DB_EVICTING;
1739	db->db_blkptr = NULL;
1740
1741	DB_DNODE_ENTER(db);
1742	dn = DB_DNODE(db);
1743	dndb = dn->dn_dbuf;
1744	if (db->db_blkid != DMU_BONUS_BLKID && MUTEX_HELD(&dn->dn_dbufs_mtx)) {
1745		avl_remove(&dn->dn_dbufs, db);
1746		atomic_dec_32(&dn->dn_dbufs_count);
1747		membar_producer();
1748		DB_DNODE_EXIT(db);
1749		/*
1750		 * Decrementing the dbuf count means that the hold corresponding
1751		 * to the removed dbuf is no longer discounted in dnode_move(),
1752		 * so the dnode cannot be moved until after we release the hold.
1753		 * The membar_producer() ensures visibility of the decremented
1754		 * value in dnode_move(), since DB_DNODE_EXIT doesn't actually
1755		 * release any lock.
1756		 */
1757		dnode_rele(dn, db);
1758		db->db_dnode_handle = NULL;
1759	} else {
1760		DB_DNODE_EXIT(db);
1761	}
1762
1763	if (db->db_buf)
1764		dbuf_gone = arc_clear_callback(db->db_buf);
1765
1766	if (!dbuf_gone)
1767		mutex_exit(&db->db_mtx);
1768
1769	/*
1770	 * If this dbuf is referenced from an indirect dbuf,
1771	 * decrement the ref count on the indirect dbuf.
1772	 */
1773	if (parent && parent != dndb)
1774		dbuf_rele(parent, db);
1775}
1776
1777/*
1778 * Note: While bpp will always be updated if the function returns success,
1779 * parentp will not be updated if the dnode does not have dn_dbuf filled in;
1780 * this happens when the dnode is the meta-dnode, or a userused or groupused
1781 * object.
1782 */
1783static int
1784dbuf_findbp(dnode_t *dn, int level, uint64_t blkid, int fail_sparse,
1785    dmu_buf_impl_t **parentp, blkptr_t **bpp)
1786{
1787	int nlevels, epbs;
1788
1789	*parentp = NULL;
1790	*bpp = NULL;
1791
1792	ASSERT(blkid != DMU_BONUS_BLKID);
1793
1794	if (blkid == DMU_SPILL_BLKID) {
1795		mutex_enter(&dn->dn_mtx);
1796		if (dn->dn_have_spill &&
1797		    (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR))
1798			*bpp = &dn->dn_phys->dn_spill;
1799		else
1800			*bpp = NULL;
1801		dbuf_add_ref(dn->dn_dbuf, NULL);
1802		*parentp = dn->dn_dbuf;
1803		mutex_exit(&dn->dn_mtx);
1804		return (0);
1805	}
1806
1807	if (dn->dn_phys->dn_nlevels == 0)
1808		nlevels = 1;
1809	else
1810		nlevels = dn->dn_phys->dn_nlevels;
1811
1812	epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
1813
1814	ASSERT3U(level * epbs, <, 64);
1815	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
1816	if (level >= nlevels ||
1817	    (blkid > (dn->dn_phys->dn_maxblkid >> (level * epbs)))) {
1818		/* the buffer has no parent yet */
1819		return (SET_ERROR(ENOENT));
1820	} else if (level < nlevels-1) {
1821		/* this block is referenced from an indirect block */
1822		int err = dbuf_hold_impl(dn, level+1,
1823		    blkid >> epbs, fail_sparse, FALSE, NULL, parentp);
1824		if (err)
1825			return (err);
1826		err = dbuf_read(*parentp, NULL,
1827		    (DB_RF_HAVESTRUCT | DB_RF_NOPREFETCH | DB_RF_CANFAIL));
1828		if (err) {
1829			dbuf_rele(*parentp, NULL);
1830			*parentp = NULL;
1831			return (err);
1832		}
1833		*bpp = ((blkptr_t *)(*parentp)->db.db_data) +
1834		    (blkid & ((1ULL << epbs) - 1));
1835		return (0);
1836	} else {
1837		/* the block is referenced from the dnode */
1838		ASSERT3U(level, ==, nlevels-1);
1839		ASSERT(dn->dn_phys->dn_nblkptr == 0 ||
1840		    blkid < dn->dn_phys->dn_nblkptr);
1841		if (dn->dn_dbuf) {
1842			dbuf_add_ref(dn->dn_dbuf, NULL);
1843			*parentp = dn->dn_dbuf;
1844		}
1845		*bpp = &dn->dn_phys->dn_blkptr[blkid];
1846		return (0);
1847	}
1848}
1849
1850static dmu_buf_impl_t *
1851dbuf_create(dnode_t *dn, uint8_t level, uint64_t blkid,
1852    dmu_buf_impl_t *parent, blkptr_t *blkptr)
1853{
1854	objset_t *os = dn->dn_objset;
1855	dmu_buf_impl_t *db, *odb;
1856
1857	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
1858	ASSERT(dn->dn_type != DMU_OT_NONE);
1859
1860	db = kmem_cache_alloc(dbuf_cache, KM_SLEEP);
1861
1862	db->db_objset = os;
1863	db->db.db_object = dn->dn_object;
1864	db->db_level = level;
1865	db->db_blkid = blkid;
1866	db->db_last_dirty = NULL;
1867	db->db_dirtycnt = 0;
1868	db->db_dnode_handle = dn->dn_handle;
1869	db->db_parent = parent;
1870	db->db_blkptr = blkptr;
1871
1872	db->db_user = NULL;
1873	db->db_user_immediate_evict = FALSE;
1874	db->db_freed_in_flight = FALSE;
1875	db->db_pending_evict = FALSE;
1876
1877	if (blkid == DMU_BONUS_BLKID) {
1878		ASSERT3P(parent, ==, dn->dn_dbuf);
1879		db->db.db_size = DN_MAX_BONUSLEN -
1880		    (dn->dn_nblkptr-1) * sizeof (blkptr_t);
1881		ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
1882		db->db.db_offset = DMU_BONUS_BLKID;
1883		db->db_state = DB_UNCACHED;
1884		/* the bonus dbuf is not placed in the hash table */
1885		arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
1886		return (db);
1887	} else if (blkid == DMU_SPILL_BLKID) {
1888		db->db.db_size = (blkptr != NULL) ?
1889		    BP_GET_LSIZE(blkptr) : SPA_MINBLOCKSIZE;
1890		db->db.db_offset = 0;
1891	} else {
1892		int blocksize =
1893		    db->db_level ? 1 << dn->dn_indblkshift : dn->dn_datablksz;
1894		db->db.db_size = blocksize;
1895		db->db.db_offset = db->db_blkid * blocksize;
1896	}
1897
1898	/*
1899	 * Hold the dn_dbufs_mtx while we get the new dbuf
1900	 * in the hash table *and* added to the dbufs list.
1901	 * This prevents a possible deadlock with someone
1902	 * trying to look up this dbuf before its added to the
1903	 * dn_dbufs list.
1904	 */
1905	mutex_enter(&dn->dn_dbufs_mtx);
1906	db->db_state = DB_EVICTING;
1907	if ((odb = dbuf_hash_insert(db)) != NULL) {
1908		/* someone else inserted it first */
1909		kmem_cache_free(dbuf_cache, db);
1910		mutex_exit(&dn->dn_dbufs_mtx);
1911		return (odb);
1912	}
1913	avl_add(&dn->dn_dbufs, db);
1914	if (db->db_level == 0 && db->db_blkid >=
1915	    dn->dn_unlisted_l0_blkid)
1916		dn->dn_unlisted_l0_blkid = db->db_blkid + 1;
1917	db->db_state = DB_UNCACHED;
1918	mutex_exit(&dn->dn_dbufs_mtx);
1919	arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
1920
1921	if (parent && parent != dn->dn_dbuf)
1922		dbuf_add_ref(parent, db);
1923
1924	ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
1925	    refcount_count(&dn->dn_holds) > 0);
1926	(void) refcount_add(&dn->dn_holds, db);
1927	atomic_inc_32(&dn->dn_dbufs_count);
1928
1929	dprintf_dbuf(db, "db=%p\n", db);
1930
1931	return (db);
1932}
1933
1934static int
1935dbuf_do_evict(void *private)
1936{
1937	dmu_buf_impl_t *db = private;
1938
1939	if (!MUTEX_HELD(&db->db_mtx))
1940		mutex_enter(&db->db_mtx);
1941
1942	ASSERT(refcount_is_zero(&db->db_holds));
1943
1944	if (db->db_state != DB_EVICTING) {
1945		ASSERT(db->db_state == DB_CACHED);
1946		DBUF_VERIFY(db);
1947		db->db_buf = NULL;
1948		dbuf_evict(db);
1949	} else {
1950		mutex_exit(&db->db_mtx);
1951		dbuf_destroy(db);
1952	}
1953	return (0);
1954}
1955
1956static void
1957dbuf_destroy(dmu_buf_impl_t *db)
1958{
1959	ASSERT(refcount_is_zero(&db->db_holds));
1960
1961	if (db->db_blkid != DMU_BONUS_BLKID) {
1962		/*
1963		 * If this dbuf is still on the dn_dbufs list,
1964		 * remove it from that list.
1965		 */
1966		if (db->db_dnode_handle != NULL) {
1967			dnode_t *dn;
1968
1969			DB_DNODE_ENTER(db);
1970			dn = DB_DNODE(db);
1971			mutex_enter(&dn->dn_dbufs_mtx);
1972			avl_remove(&dn->dn_dbufs, db);
1973			atomic_dec_32(&dn->dn_dbufs_count);
1974			mutex_exit(&dn->dn_dbufs_mtx);
1975			DB_DNODE_EXIT(db);
1976			/*
1977			 * Decrementing the dbuf count means that the hold
1978			 * corresponding to the removed dbuf is no longer
1979			 * discounted in dnode_move(), so the dnode cannot be
1980			 * moved until after we release the hold.
1981			 */
1982			dnode_rele(dn, db);
1983			db->db_dnode_handle = NULL;
1984		}
1985		dbuf_hash_remove(db);
1986	}
1987	db->db_parent = NULL;
1988	db->db_buf = NULL;
1989
1990	ASSERT(db->db.db_data == NULL);
1991	ASSERT(db->db_hash_next == NULL);
1992	ASSERT(db->db_blkptr == NULL);
1993	ASSERT(db->db_data_pending == NULL);
1994
1995	kmem_cache_free(dbuf_cache, db);
1996	arc_space_return(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
1997}
1998
1999typedef struct dbuf_prefetch_arg {
2000	spa_t *dpa_spa;	/* The spa to issue the prefetch in. */
2001	zbookmark_phys_t dpa_zb; /* The target block to prefetch. */
2002	int dpa_epbs; /* Entries (blkptr_t's) Per Block Shift. */
2003	int dpa_curlevel; /* The current level that we're reading */
2004	zio_priority_t dpa_prio; /* The priority I/Os should be issued at. */
2005	zio_t *dpa_zio; /* The parent zio_t for all prefetches. */
2006	arc_flags_t dpa_aflags; /* Flags to pass to the final prefetch. */
2007} dbuf_prefetch_arg_t;
2008
2009/*
2010 * Actually issue the prefetch read for the block given.
2011 */
2012static void
2013dbuf_issue_final_prefetch(dbuf_prefetch_arg_t *dpa, blkptr_t *bp)
2014{
2015	if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
2016		return;
2017
2018	arc_flags_t aflags =
2019	    dpa->dpa_aflags | ARC_FLAG_NOWAIT | ARC_FLAG_PREFETCH;
2020
2021	ASSERT3U(dpa->dpa_curlevel, ==, BP_GET_LEVEL(bp));
2022	ASSERT3U(dpa->dpa_curlevel, ==, dpa->dpa_zb.zb_level);
2023	ASSERT(dpa->dpa_zio != NULL);
2024	(void) arc_read(dpa->dpa_zio, dpa->dpa_spa, bp, NULL, NULL,
2025	    dpa->dpa_prio, ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
2026	    &aflags, &dpa->dpa_zb);
2027}
2028
2029/*
2030 * Called when an indirect block above our prefetch target is read in.  This
2031 * will either read in the next indirect block down the tree or issue the actual
2032 * prefetch if the next block down is our target.
2033 */
2034static void
2035dbuf_prefetch_indirect_done(zio_t *zio, arc_buf_t *abuf, void *private)
2036{
2037	dbuf_prefetch_arg_t *dpa = private;
2038
2039	ASSERT3S(dpa->dpa_zb.zb_level, <, dpa->dpa_curlevel);
2040	ASSERT3S(dpa->dpa_curlevel, >, 0);
2041	if (zio != NULL) {
2042		ASSERT3S(BP_GET_LEVEL(zio->io_bp), ==, dpa->dpa_curlevel);
2043		ASSERT3U(BP_GET_LSIZE(zio->io_bp), ==, zio->io_size);
2044		ASSERT3P(zio->io_spa, ==, dpa->dpa_spa);
2045	}
2046
2047	dpa->dpa_curlevel--;
2048
2049	uint64_t nextblkid = dpa->dpa_zb.zb_blkid >>
2050	    (dpa->dpa_epbs * (dpa->dpa_curlevel - dpa->dpa_zb.zb_level));
2051	blkptr_t *bp = ((blkptr_t *)abuf->b_data) +
2052	    P2PHASE(nextblkid, 1ULL << dpa->dpa_epbs);
2053	if (BP_IS_HOLE(bp) || (zio != NULL && zio->io_error != 0)) {
2054		kmem_free(dpa, sizeof (*dpa));
2055	} else if (dpa->dpa_curlevel == dpa->dpa_zb.zb_level) {
2056		ASSERT3U(nextblkid, ==, dpa->dpa_zb.zb_blkid);
2057		dbuf_issue_final_prefetch(dpa, bp);
2058		kmem_free(dpa, sizeof (*dpa));
2059	} else {
2060		arc_flags_t iter_aflags = ARC_FLAG_NOWAIT;
2061		zbookmark_phys_t zb;
2062
2063		ASSERT3U(dpa->dpa_curlevel, ==, BP_GET_LEVEL(bp));
2064
2065		SET_BOOKMARK(&zb, dpa->dpa_zb.zb_objset,
2066		    dpa->dpa_zb.zb_object, dpa->dpa_curlevel, nextblkid);
2067
2068		(void) arc_read(dpa->dpa_zio, dpa->dpa_spa,
2069		    bp, dbuf_prefetch_indirect_done, dpa, dpa->dpa_prio,
2070		    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
2071		    &iter_aflags, &zb);
2072	}
2073	(void) arc_buf_remove_ref(abuf, private);
2074}
2075
2076/*
2077 * Issue prefetch reads for the given block on the given level.  If the indirect
2078 * blocks above that block are not in memory, we will read them in
2079 * asynchronously.  As a result, this call never blocks waiting for a read to
2080 * complete.
2081 */
2082void
2083dbuf_prefetch(dnode_t *dn, int64_t level, uint64_t blkid, zio_priority_t prio,
2084    arc_flags_t aflags)
2085{
2086	blkptr_t bp;
2087	int epbs, nlevels, curlevel;
2088	uint64_t curblkid;
2089
2090	ASSERT(blkid != DMU_BONUS_BLKID);
2091	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2092
2093	if (blkid > dn->dn_maxblkid)
2094		return;
2095
2096	if (dnode_block_freed(dn, blkid))
2097		return;
2098
2099	/*
2100	 * This dnode hasn't been written to disk yet, so there's nothing to
2101	 * prefetch.
2102	 */
2103	nlevels = dn->dn_phys->dn_nlevels;
2104	if (level >= nlevels || dn->dn_phys->dn_nblkptr == 0)
2105		return;
2106
2107	epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
2108	if (dn->dn_phys->dn_maxblkid < blkid << (epbs * level))
2109		return;
2110
2111	dmu_buf_impl_t *db = dbuf_find(dn->dn_objset, dn->dn_object,
2112	    level, blkid);
2113	if (db != NULL) {
2114		mutex_exit(&db->db_mtx);
2115		/*
2116		 * This dbuf already exists.  It is either CACHED, or
2117		 * (we assume) about to be read or filled.
2118		 */
2119		return;
2120	}
2121
2122	/*
2123	 * Find the closest ancestor (indirect block) of the target block
2124	 * that is present in the cache.  In this indirect block, we will
2125	 * find the bp that is at curlevel, curblkid.
2126	 */
2127	curlevel = level;
2128	curblkid = blkid;
2129	while (curlevel < nlevels - 1) {
2130		int parent_level = curlevel + 1;
2131		uint64_t parent_blkid = curblkid >> epbs;
2132		dmu_buf_impl_t *db;
2133
2134		if (dbuf_hold_impl(dn, parent_level, parent_blkid,
2135		    FALSE, TRUE, FTAG, &db) == 0) {
2136			blkptr_t *bpp = db->db_buf->b_data;
2137			bp = bpp[P2PHASE(curblkid, 1 << epbs)];
2138			dbuf_rele(db, FTAG);
2139			break;
2140		}
2141
2142		curlevel = parent_level;
2143		curblkid = parent_blkid;
2144	}
2145
2146	if (curlevel == nlevels - 1) {
2147		/* No cached indirect blocks found. */
2148		ASSERT3U(curblkid, <, dn->dn_phys->dn_nblkptr);
2149		bp = dn->dn_phys->dn_blkptr[curblkid];
2150	}
2151	if (BP_IS_HOLE(&bp))
2152		return;
2153
2154	ASSERT3U(curlevel, ==, BP_GET_LEVEL(&bp));
2155
2156	zio_t *pio = zio_root(dmu_objset_spa(dn->dn_objset), NULL, NULL,
2157	    ZIO_FLAG_CANFAIL);
2158
2159	dbuf_prefetch_arg_t *dpa = kmem_zalloc(sizeof (*dpa), KM_SLEEP);
2160	dsl_dataset_t *ds = dn->dn_objset->os_dsl_dataset;
2161	SET_BOOKMARK(&dpa->dpa_zb, ds != NULL ? ds->ds_object : DMU_META_OBJSET,
2162	    dn->dn_object, level, blkid);
2163	dpa->dpa_curlevel = curlevel;
2164	dpa->dpa_prio = prio;
2165	dpa->dpa_aflags = aflags;
2166	dpa->dpa_spa = dn->dn_objset->os_spa;
2167	dpa->dpa_epbs = epbs;
2168	dpa->dpa_zio = pio;
2169
2170	/*
2171	 * If we have the indirect just above us, no need to do the asynchronous
2172	 * prefetch chain; we'll just run the last step ourselves.  If we're at
2173	 * a higher level, though, we want to issue the prefetches for all the
2174	 * indirect blocks asynchronously, so we can go on with whatever we were
2175	 * doing.
2176	 */
2177	if (curlevel == level) {
2178		ASSERT3U(curblkid, ==, blkid);
2179		dbuf_issue_final_prefetch(dpa, &bp);
2180		kmem_free(dpa, sizeof (*dpa));
2181	} else {
2182		arc_flags_t iter_aflags = ARC_FLAG_NOWAIT;
2183		zbookmark_phys_t zb;
2184
2185		SET_BOOKMARK(&zb, ds != NULL ? ds->ds_object : DMU_META_OBJSET,
2186		    dn->dn_object, curlevel, curblkid);
2187		(void) arc_read(dpa->dpa_zio, dpa->dpa_spa,
2188		    &bp, dbuf_prefetch_indirect_done, dpa, prio,
2189		    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
2190		    &iter_aflags, &zb);
2191	}
2192	/*
2193	 * We use pio here instead of dpa_zio since it's possible that
2194	 * dpa may have already been freed.
2195	 */
2196	zio_nowait(pio);
2197}
2198
2199/*
2200 * Returns with db_holds incremented, and db_mtx not held.
2201 * Note: dn_struct_rwlock must be held.
2202 */
2203int
2204dbuf_hold_impl(dnode_t *dn, uint8_t level, uint64_t blkid,
2205    boolean_t fail_sparse, boolean_t fail_uncached,
2206    void *tag, dmu_buf_impl_t **dbp)
2207{
2208	dmu_buf_impl_t *db, *parent = NULL;
2209
2210	ASSERT(blkid != DMU_BONUS_BLKID);
2211	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2212	ASSERT3U(dn->dn_nlevels, >, level);
2213
2214	*dbp = NULL;
2215top:
2216	/* dbuf_find() returns with db_mtx held */
2217	db = dbuf_find(dn->dn_objset, dn->dn_object, level, blkid);
2218
2219	if (db == NULL) {
2220		blkptr_t *bp = NULL;
2221		int err;
2222
2223		if (fail_uncached)
2224			return (SET_ERROR(ENOENT));
2225
2226		ASSERT3P(parent, ==, NULL);
2227		err = dbuf_findbp(dn, level, blkid, fail_sparse, &parent, &bp);
2228		if (fail_sparse) {
2229			if (err == 0 && bp && BP_IS_HOLE(bp))
2230				err = SET_ERROR(ENOENT);
2231			if (err) {
2232				if (parent)
2233					dbuf_rele(parent, NULL);
2234				return (err);
2235			}
2236		}
2237		if (err && err != ENOENT)
2238			return (err);
2239		db = dbuf_create(dn, level, blkid, parent, bp);
2240	}
2241
2242	if (fail_uncached && db->db_state != DB_CACHED) {
2243		mutex_exit(&db->db_mtx);
2244		return (SET_ERROR(ENOENT));
2245	}
2246
2247	if (db->db_buf && refcount_is_zero(&db->db_holds)) {
2248		arc_buf_add_ref(db->db_buf, db);
2249		if (db->db_buf->b_data == NULL) {
2250			dbuf_clear(db);
2251			if (parent) {
2252				dbuf_rele(parent, NULL);
2253				parent = NULL;
2254			}
2255			goto top;
2256		}
2257		ASSERT3P(db->db.db_data, ==, db->db_buf->b_data);
2258	}
2259
2260	ASSERT(db->db_buf == NULL || arc_referenced(db->db_buf));
2261
2262	/*
2263	 * If this buffer is currently syncing out, and we are are
2264	 * still referencing it from db_data, we need to make a copy
2265	 * of it in case we decide we want to dirty it again in this txg.
2266	 */
2267	if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
2268	    dn->dn_object != DMU_META_DNODE_OBJECT &&
2269	    db->db_state == DB_CACHED && db->db_data_pending) {
2270		dbuf_dirty_record_t *dr = db->db_data_pending;
2271
2272		if (dr->dt.dl.dr_data == db->db_buf) {
2273			arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
2274
2275			dbuf_set_data(db,
2276			    arc_buf_alloc(dn->dn_objset->os_spa,
2277			    db->db.db_size, db, type));
2278			bcopy(dr->dt.dl.dr_data->b_data, db->db.db_data,
2279			    db->db.db_size);
2280		}
2281	}
2282
2283	(void) refcount_add(&db->db_holds, tag);
2284	DBUF_VERIFY(db);
2285	mutex_exit(&db->db_mtx);
2286
2287	/* NOTE: we can't rele the parent until after we drop the db_mtx */
2288	if (parent)
2289		dbuf_rele(parent, NULL);
2290
2291	ASSERT3P(DB_DNODE(db), ==, dn);
2292	ASSERT3U(db->db_blkid, ==, blkid);
2293	ASSERT3U(db->db_level, ==, level);
2294	*dbp = db;
2295
2296	return (0);
2297}
2298
2299dmu_buf_impl_t *
2300dbuf_hold(dnode_t *dn, uint64_t blkid, void *tag)
2301{
2302	return (dbuf_hold_level(dn, 0, blkid, tag));
2303}
2304
2305dmu_buf_impl_t *
2306dbuf_hold_level(dnode_t *dn, int level, uint64_t blkid, void *tag)
2307{
2308	dmu_buf_impl_t *db;
2309	int err = dbuf_hold_impl(dn, level, blkid, FALSE, FALSE, tag, &db);
2310	return (err ? NULL : db);
2311}
2312
2313void
2314dbuf_create_bonus(dnode_t *dn)
2315{
2316	ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
2317
2318	ASSERT(dn->dn_bonus == NULL);
2319	dn->dn_bonus = dbuf_create(dn, 0, DMU_BONUS_BLKID, dn->dn_dbuf, NULL);
2320}
2321
2322int
2323dbuf_spill_set_blksz(dmu_buf_t *db_fake, uint64_t blksz, dmu_tx_t *tx)
2324{
2325	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2326	dnode_t *dn;
2327
2328	if (db->db_blkid != DMU_SPILL_BLKID)
2329		return (SET_ERROR(ENOTSUP));
2330	if (blksz == 0)
2331		blksz = SPA_MINBLOCKSIZE;
2332	ASSERT3U(blksz, <=, spa_maxblocksize(dmu_objset_spa(db->db_objset)));
2333	blksz = P2ROUNDUP(blksz, SPA_MINBLOCKSIZE);
2334
2335	DB_DNODE_ENTER(db);
2336	dn = DB_DNODE(db);
2337	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
2338	dbuf_new_size(db, blksz, tx);
2339	rw_exit(&dn->dn_struct_rwlock);
2340	DB_DNODE_EXIT(db);
2341
2342	return (0);
2343}
2344
2345void
2346dbuf_rm_spill(dnode_t *dn, dmu_tx_t *tx)
2347{
2348	dbuf_free_range(dn, DMU_SPILL_BLKID, DMU_SPILL_BLKID, tx);
2349}
2350
2351#pragma weak dmu_buf_add_ref = dbuf_add_ref
2352void
2353dbuf_add_ref(dmu_buf_impl_t *db, void *tag)
2354{
2355	int64_t holds = refcount_add(&db->db_holds, tag);
2356	ASSERT(holds > 1);
2357}
2358
2359#pragma weak dmu_buf_try_add_ref = dbuf_try_add_ref
2360boolean_t
2361dbuf_try_add_ref(dmu_buf_t *db_fake, objset_t *os, uint64_t obj, uint64_t blkid,
2362    void *tag)
2363{
2364	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2365	dmu_buf_impl_t *found_db;
2366	boolean_t result = B_FALSE;
2367
2368	if (db->db_blkid == DMU_BONUS_BLKID)
2369		found_db = dbuf_find_bonus(os, obj);
2370	else
2371		found_db = dbuf_find(os, obj, 0, blkid);
2372
2373	if (found_db != NULL) {
2374		if (db == found_db && dbuf_refcount(db) > db->db_dirtycnt) {
2375			(void) refcount_add(&db->db_holds, tag);
2376			result = B_TRUE;
2377		}
2378		mutex_exit(&db->db_mtx);
2379	}
2380	return (result);
2381}
2382
2383/*
2384 * If you call dbuf_rele() you had better not be referencing the dnode handle
2385 * unless you have some other direct or indirect hold on the dnode. (An indirect
2386 * hold is a hold on one of the dnode's dbufs, including the bonus buffer.)
2387 * Without that, the dbuf_rele() could lead to a dnode_rele() followed by the
2388 * dnode's parent dbuf evicting its dnode handles.
2389 */
2390void
2391dbuf_rele(dmu_buf_impl_t *db, void *tag)
2392{
2393	mutex_enter(&db->db_mtx);
2394	dbuf_rele_and_unlock(db, tag);
2395}
2396
2397void
2398dmu_buf_rele(dmu_buf_t *db, void *tag)
2399{
2400	dbuf_rele((dmu_buf_impl_t *)db, tag);
2401}
2402
2403/*
2404 * dbuf_rele() for an already-locked dbuf.  This is necessary to allow
2405 * db_dirtycnt and db_holds to be updated atomically.
2406 */
2407void
2408dbuf_rele_and_unlock(dmu_buf_impl_t *db, void *tag)
2409{
2410	int64_t holds;
2411
2412	ASSERT(MUTEX_HELD(&db->db_mtx));
2413	DBUF_VERIFY(db);
2414
2415	/*
2416	 * Remove the reference to the dbuf before removing its hold on the
2417	 * dnode so we can guarantee in dnode_move() that a referenced bonus
2418	 * buffer has a corresponding dnode hold.
2419	 */
2420	holds = refcount_remove(&db->db_holds, tag);
2421	ASSERT(holds >= 0);
2422
2423	/*
2424	 * We can't freeze indirects if there is a possibility that they
2425	 * may be modified in the current syncing context.
2426	 */
2427	if (db->db_buf && holds == (db->db_level == 0 ? db->db_dirtycnt : 0))
2428		arc_buf_freeze(db->db_buf);
2429
2430	if (holds == db->db_dirtycnt &&
2431	    db->db_level == 0 && db->db_user_immediate_evict)
2432		dbuf_evict_user(db);
2433
2434	if (holds == 0) {
2435		if (db->db_blkid == DMU_BONUS_BLKID) {
2436			dnode_t *dn;
2437			boolean_t evict_dbuf = db->db_pending_evict;
2438
2439			/*
2440			 * If the dnode moves here, we cannot cross this
2441			 * barrier until the move completes.
2442			 */
2443			DB_DNODE_ENTER(db);
2444
2445			dn = DB_DNODE(db);
2446			atomic_dec_32(&dn->dn_dbufs_count);
2447
2448			/*
2449			 * Decrementing the dbuf count means that the bonus
2450			 * buffer's dnode hold is no longer discounted in
2451			 * dnode_move(). The dnode cannot move until after
2452			 * the dnode_rele() below.
2453			 */
2454			DB_DNODE_EXIT(db);
2455
2456			/*
2457			 * Do not reference db after its lock is dropped.
2458			 * Another thread may evict it.
2459			 */
2460			mutex_exit(&db->db_mtx);
2461
2462			if (evict_dbuf)
2463				dnode_evict_bonus(dn);
2464
2465			dnode_rele(dn, db);
2466		} else if (db->db_buf == NULL) {
2467			/*
2468			 * This is a special case: we never associated this
2469			 * dbuf with any data allocated from the ARC.
2470			 */
2471			ASSERT(db->db_state == DB_UNCACHED ||
2472			    db->db_state == DB_NOFILL);
2473			dbuf_evict(db);
2474		} else if (arc_released(db->db_buf)) {
2475			arc_buf_t *buf = db->db_buf;
2476			/*
2477			 * This dbuf has anonymous data associated with it.
2478			 */
2479			dbuf_clear_data(db);
2480			VERIFY(arc_buf_remove_ref(buf, db));
2481			dbuf_evict(db);
2482		} else {
2483			VERIFY(!arc_buf_remove_ref(db->db_buf, db));
2484
2485			/*
2486			 * A dbuf will be eligible for eviction if either the
2487			 * 'primarycache' property is set or a duplicate
2488			 * copy of this buffer is already cached in the arc.
2489			 *
2490			 * In the case of the 'primarycache' a buffer
2491			 * is considered for eviction if it matches the
2492			 * criteria set in the property.
2493			 *
2494			 * To decide if our buffer is considered a
2495			 * duplicate, we must call into the arc to determine
2496			 * if multiple buffers are referencing the same
2497			 * block on-disk. If so, then we simply evict
2498			 * ourselves.
2499			 */
2500			if (!DBUF_IS_CACHEABLE(db)) {
2501				if (db->db_blkptr != NULL &&
2502				    !BP_IS_HOLE(db->db_blkptr) &&
2503				    !BP_IS_EMBEDDED(db->db_blkptr)) {
2504					spa_t *spa =
2505					    dmu_objset_spa(db->db_objset);
2506					blkptr_t bp = *db->db_blkptr;
2507					dbuf_clear(db);
2508					arc_freed(spa, &bp);
2509				} else {
2510					dbuf_clear(db);
2511				}
2512			} else if (db->db_pending_evict ||
2513			    arc_buf_eviction_needed(db->db_buf)) {
2514				dbuf_clear(db);
2515			} else {
2516				mutex_exit(&db->db_mtx);
2517			}
2518		}
2519	} else {
2520		mutex_exit(&db->db_mtx);
2521	}
2522}
2523
2524#pragma weak dmu_buf_refcount = dbuf_refcount
2525uint64_t
2526dbuf_refcount(dmu_buf_impl_t *db)
2527{
2528	return (refcount_count(&db->db_holds));
2529}
2530
2531void *
2532dmu_buf_replace_user(dmu_buf_t *db_fake, dmu_buf_user_t *old_user,
2533    dmu_buf_user_t *new_user)
2534{
2535	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2536
2537	mutex_enter(&db->db_mtx);
2538	dbuf_verify_user(db, DBVU_NOT_EVICTING);
2539	if (db->db_user == old_user)
2540		db->db_user = new_user;
2541	else
2542		old_user = db->db_user;
2543	dbuf_verify_user(db, DBVU_NOT_EVICTING);
2544	mutex_exit(&db->db_mtx);
2545
2546	return (old_user);
2547}
2548
2549void *
2550dmu_buf_set_user(dmu_buf_t *db_fake, dmu_buf_user_t *user)
2551{
2552	return (dmu_buf_replace_user(db_fake, NULL, user));
2553}
2554
2555void *
2556dmu_buf_set_user_ie(dmu_buf_t *db_fake, dmu_buf_user_t *user)
2557{
2558	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2559
2560	db->db_user_immediate_evict = TRUE;
2561	return (dmu_buf_set_user(db_fake, user));
2562}
2563
2564void *
2565dmu_buf_remove_user(dmu_buf_t *db_fake, dmu_buf_user_t *user)
2566{
2567	return (dmu_buf_replace_user(db_fake, user, NULL));
2568}
2569
2570void *
2571dmu_buf_get_user(dmu_buf_t *db_fake)
2572{
2573	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2574
2575	dbuf_verify_user(db, DBVU_NOT_EVICTING);
2576	return (db->db_user);
2577}
2578
2579void
2580dmu_buf_user_evict_wait()
2581{
2582	taskq_wait(dbu_evict_taskq);
2583}
2584
2585boolean_t
2586dmu_buf_freeable(dmu_buf_t *dbuf)
2587{
2588	boolean_t res = B_FALSE;
2589	dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbuf;
2590
2591	if (db->db_blkptr)
2592		res = dsl_dataset_block_freeable(db->db_objset->os_dsl_dataset,
2593		    db->db_blkptr, db->db_blkptr->blk_birth);
2594
2595	return (res);
2596}
2597
2598blkptr_t *
2599dmu_buf_get_blkptr(dmu_buf_t *db)
2600{
2601	dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
2602	return (dbi->db_blkptr);
2603}
2604
2605static void
2606dbuf_check_blkptr(dnode_t *dn, dmu_buf_impl_t *db)
2607{
2608	/* ASSERT(dmu_tx_is_syncing(tx) */
2609	ASSERT(MUTEX_HELD(&db->db_mtx));
2610
2611	if (db->db_blkptr != NULL)
2612		return;
2613
2614	if (db->db_blkid == DMU_SPILL_BLKID) {
2615		db->db_blkptr = &dn->dn_phys->dn_spill;
2616		BP_ZERO(db->db_blkptr);
2617		return;
2618	}
2619	if (db->db_level == dn->dn_phys->dn_nlevels-1) {
2620		/*
2621		 * This buffer was allocated at a time when there was
2622		 * no available blkptrs from the dnode, or it was
2623		 * inappropriate to hook it in (i.e., nlevels mis-match).
2624		 */
2625		ASSERT(db->db_blkid < dn->dn_phys->dn_nblkptr);
2626		ASSERT(db->db_parent == NULL);
2627		db->db_parent = dn->dn_dbuf;
2628		db->db_blkptr = &dn->dn_phys->dn_blkptr[db->db_blkid];
2629		DBUF_VERIFY(db);
2630	} else {
2631		dmu_buf_impl_t *parent = db->db_parent;
2632		int epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
2633
2634		ASSERT(dn->dn_phys->dn_nlevels > 1);
2635		if (parent == NULL) {
2636			mutex_exit(&db->db_mtx);
2637			rw_enter(&dn->dn_struct_rwlock, RW_READER);
2638			parent = dbuf_hold_level(dn, db->db_level + 1,
2639			    db->db_blkid >> epbs, db);
2640			rw_exit(&dn->dn_struct_rwlock);
2641			mutex_enter(&db->db_mtx);
2642			db->db_parent = parent;
2643		}
2644		db->db_blkptr = (blkptr_t *)parent->db.db_data +
2645		    (db->db_blkid & ((1ULL << epbs) - 1));
2646		DBUF_VERIFY(db);
2647	}
2648}
2649
2650static void
2651dbuf_sync_indirect(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
2652{
2653	dmu_buf_impl_t *db = dr->dr_dbuf;
2654	dnode_t *dn;
2655	zio_t *zio;
2656
2657	ASSERT(dmu_tx_is_syncing(tx));
2658
2659	dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
2660
2661	mutex_enter(&db->db_mtx);
2662
2663	ASSERT(db->db_level > 0);
2664	DBUF_VERIFY(db);
2665
2666	/* Read the block if it hasn't been read yet. */
2667	if (db->db_buf == NULL) {
2668		mutex_exit(&db->db_mtx);
2669		(void) dbuf_read(db, NULL, DB_RF_MUST_SUCCEED);
2670		mutex_enter(&db->db_mtx);
2671	}
2672	ASSERT3U(db->db_state, ==, DB_CACHED);
2673	ASSERT(db->db_buf != NULL);
2674
2675	DB_DNODE_ENTER(db);
2676	dn = DB_DNODE(db);
2677	/* Indirect block size must match what the dnode thinks it is. */
2678	ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
2679	dbuf_check_blkptr(dn, db);
2680	DB_DNODE_EXIT(db);
2681
2682	/* Provide the pending dirty record to child dbufs */
2683	db->db_data_pending = dr;
2684
2685	mutex_exit(&db->db_mtx);
2686	dbuf_write(dr, db->db_buf, tx);
2687
2688	zio = dr->dr_zio;
2689	mutex_enter(&dr->dt.di.dr_mtx);
2690	dbuf_sync_list(&dr->dt.di.dr_children, db->db_level - 1, tx);
2691	ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
2692	mutex_exit(&dr->dt.di.dr_mtx);
2693	zio_nowait(zio);
2694}
2695
2696static void
2697dbuf_sync_leaf(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
2698{
2699	arc_buf_t **datap = &dr->dt.dl.dr_data;
2700	dmu_buf_impl_t *db = dr->dr_dbuf;
2701	dnode_t *dn;
2702	objset_t *os;
2703	uint64_t txg = tx->tx_txg;
2704
2705	ASSERT(dmu_tx_is_syncing(tx));
2706
2707	dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
2708
2709	mutex_enter(&db->db_mtx);
2710	/*
2711	 * To be synced, we must be dirtied.  But we
2712	 * might have been freed after the dirty.
2713	 */
2714	if (db->db_state == DB_UNCACHED) {
2715		/* This buffer has been freed since it was dirtied */
2716		ASSERT(db->db.db_data == NULL);
2717	} else if (db->db_state == DB_FILL) {
2718		/* This buffer was freed and is now being re-filled */
2719		ASSERT(db->db.db_data != dr->dt.dl.dr_data);
2720	} else {
2721		ASSERT(db->db_state == DB_CACHED || db->db_state == DB_NOFILL);
2722	}
2723	DBUF_VERIFY(db);
2724
2725	DB_DNODE_ENTER(db);
2726	dn = DB_DNODE(db);
2727
2728	if (db->db_blkid == DMU_SPILL_BLKID) {
2729		mutex_enter(&dn->dn_mtx);
2730		dn->dn_phys->dn_flags |= DNODE_FLAG_SPILL_BLKPTR;
2731		mutex_exit(&dn->dn_mtx);
2732	}
2733
2734	/*
2735	 * If this is a bonus buffer, simply copy the bonus data into the
2736	 * dnode.  It will be written out when the dnode is synced (and it
2737	 * will be synced, since it must have been dirty for dbuf_sync to
2738	 * be called).
2739	 */
2740	if (db->db_blkid == DMU_BONUS_BLKID) {
2741		dbuf_dirty_record_t **drp;
2742
2743		ASSERT(*datap != NULL);
2744		ASSERT0(db->db_level);
2745		ASSERT3U(dn->dn_phys->dn_bonuslen, <=, DN_MAX_BONUSLEN);
2746		bcopy(*datap, DN_BONUS(dn->dn_phys), dn->dn_phys->dn_bonuslen);
2747		DB_DNODE_EXIT(db);
2748
2749		if (*datap != db->db.db_data) {
2750			zio_buf_free(*datap, DN_MAX_BONUSLEN);
2751			arc_space_return(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
2752		}
2753		db->db_data_pending = NULL;
2754		drp = &db->db_last_dirty;
2755		while (*drp != dr)
2756			drp = &(*drp)->dr_next;
2757		ASSERT(dr->dr_next == NULL);
2758		ASSERT(dr->dr_dbuf == db);
2759		*drp = dr->dr_next;
2760		if (dr->dr_dbuf->db_level != 0) {
2761			list_destroy(&dr->dt.di.dr_children);
2762			mutex_destroy(&dr->dt.di.dr_mtx);
2763		}
2764		kmem_free(dr, sizeof (dbuf_dirty_record_t));
2765		ASSERT(db->db_dirtycnt > 0);
2766		db->db_dirtycnt -= 1;
2767		dbuf_rele_and_unlock(db, (void *)(uintptr_t)txg);
2768		return;
2769	}
2770
2771	os = dn->dn_objset;
2772
2773	/*
2774	 * This function may have dropped the db_mtx lock allowing a dmu_sync
2775	 * operation to sneak in. As a result, we need to ensure that we
2776	 * don't check the dr_override_state until we have returned from
2777	 * dbuf_check_blkptr.
2778	 */
2779	dbuf_check_blkptr(dn, db);
2780
2781	/*
2782	 * If this buffer is in the middle of an immediate write,
2783	 * wait for the synchronous IO to complete.
2784	 */
2785	while (dr->dt.dl.dr_override_state == DR_IN_DMU_SYNC) {
2786		ASSERT(dn->dn_object != DMU_META_DNODE_OBJECT);
2787		cv_wait(&db->db_changed, &db->db_mtx);
2788		ASSERT(dr->dt.dl.dr_override_state != DR_NOT_OVERRIDDEN);
2789	}
2790
2791	if (db->db_state != DB_NOFILL &&
2792	    dn->dn_object != DMU_META_DNODE_OBJECT &&
2793	    refcount_count(&db->db_holds) > 1 &&
2794	    dr->dt.dl.dr_override_state != DR_OVERRIDDEN &&
2795	    *datap == db->db_buf) {
2796		/*
2797		 * If this buffer is currently "in use" (i.e., there
2798		 * are active holds and db_data still references it),
2799		 * then make a copy before we start the write so that
2800		 * any modifications from the open txg will not leak
2801		 * into this write.
2802		 *
2803		 * NOTE: this copy does not need to be made for
2804		 * objects only modified in the syncing context (e.g.
2805		 * DNONE_DNODE blocks).
2806		 */
2807		int blksz = arc_buf_size(*datap);
2808		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
2809		*datap = arc_buf_alloc(os->os_spa, blksz, db, type);
2810		bcopy(db->db.db_data, (*datap)->b_data, blksz);
2811	}
2812	db->db_data_pending = dr;
2813
2814	mutex_exit(&db->db_mtx);
2815
2816	dbuf_write(dr, *datap, tx);
2817
2818	ASSERT(!list_link_active(&dr->dr_dirty_node));
2819	if (dn->dn_object == DMU_META_DNODE_OBJECT) {
2820		list_insert_tail(&dn->dn_dirty_records[txg&TXG_MASK], dr);
2821		DB_DNODE_EXIT(db);
2822	} else {
2823		/*
2824		 * Although zio_nowait() does not "wait for an IO", it does
2825		 * initiate the IO. If this is an empty write it seems plausible
2826		 * that the IO could actually be completed before the nowait
2827		 * returns. We need to DB_DNODE_EXIT() first in case
2828		 * zio_nowait() invalidates the dbuf.
2829		 */
2830		DB_DNODE_EXIT(db);
2831		zio_nowait(dr->dr_zio);
2832	}
2833}
2834
2835void
2836dbuf_sync_list(list_t *list, int level, dmu_tx_t *tx)
2837{
2838	dbuf_dirty_record_t *dr;
2839
2840	while (dr = list_head(list)) {
2841		if (dr->dr_zio != NULL) {
2842			/*
2843			 * If we find an already initialized zio then we
2844			 * are processing the meta-dnode, and we have finished.
2845			 * The dbufs for all dnodes are put back on the list
2846			 * during processing, so that we can zio_wait()
2847			 * these IOs after initiating all child IOs.
2848			 */
2849			ASSERT3U(dr->dr_dbuf->db.db_object, ==,
2850			    DMU_META_DNODE_OBJECT);
2851			break;
2852		}
2853		if (dr->dr_dbuf->db_blkid != DMU_BONUS_BLKID &&
2854		    dr->dr_dbuf->db_blkid != DMU_SPILL_BLKID) {
2855			VERIFY3U(dr->dr_dbuf->db_level, ==, level);
2856		}
2857		list_remove(list, dr);
2858		if (dr->dr_dbuf->db_level > 0)
2859			dbuf_sync_indirect(dr, tx);
2860		else
2861			dbuf_sync_leaf(dr, tx);
2862	}
2863}
2864
2865/* ARGSUSED */
2866static void
2867dbuf_write_ready(zio_t *zio, arc_buf_t *buf, void *vdb)
2868{
2869	dmu_buf_impl_t *db = vdb;
2870	dnode_t *dn;
2871	blkptr_t *bp = zio->io_bp;
2872	blkptr_t *bp_orig = &zio->io_bp_orig;
2873	spa_t *spa = zio->io_spa;
2874	int64_t delta;
2875	uint64_t fill = 0;
2876	int i;
2877
2878	ASSERT3P(db->db_blkptr, ==, bp);
2879
2880	DB_DNODE_ENTER(db);
2881	dn = DB_DNODE(db);
2882	delta = bp_get_dsize_sync(spa, bp) - bp_get_dsize_sync(spa, bp_orig);
2883	dnode_diduse_space(dn, delta - zio->io_prev_space_delta);
2884	zio->io_prev_space_delta = delta;
2885
2886	if (bp->blk_birth != 0) {
2887		ASSERT((db->db_blkid != DMU_SPILL_BLKID &&
2888		    BP_GET_TYPE(bp) == dn->dn_type) ||
2889		    (db->db_blkid == DMU_SPILL_BLKID &&
2890		    BP_GET_TYPE(bp) == dn->dn_bonustype) ||
2891		    BP_IS_EMBEDDED(bp));
2892		ASSERT(BP_GET_LEVEL(bp) == db->db_level);
2893	}
2894
2895	mutex_enter(&db->db_mtx);
2896
2897#ifdef ZFS_DEBUG
2898	if (db->db_blkid == DMU_SPILL_BLKID) {
2899		ASSERT(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR);
2900		ASSERT(!(BP_IS_HOLE(db->db_blkptr)) &&
2901		    db->db_blkptr == &dn->dn_phys->dn_spill);
2902	}
2903#endif
2904
2905	if (db->db_level == 0) {
2906		mutex_enter(&dn->dn_mtx);
2907		if (db->db_blkid > dn->dn_phys->dn_maxblkid &&
2908		    db->db_blkid != DMU_SPILL_BLKID)
2909			dn->dn_phys->dn_maxblkid = db->db_blkid;
2910		mutex_exit(&dn->dn_mtx);
2911
2912		if (dn->dn_type == DMU_OT_DNODE) {
2913			dnode_phys_t *dnp = db->db.db_data;
2914			for (i = db->db.db_size >> DNODE_SHIFT; i > 0;
2915			    i--, dnp++) {
2916				if (dnp->dn_type != DMU_OT_NONE)
2917					fill++;
2918			}
2919		} else {
2920			if (BP_IS_HOLE(bp)) {
2921				fill = 0;
2922			} else {
2923				fill = 1;
2924			}
2925		}
2926	} else {
2927		blkptr_t *ibp = db->db.db_data;
2928		ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
2929		for (i = db->db.db_size >> SPA_BLKPTRSHIFT; i > 0; i--, ibp++) {
2930			if (BP_IS_HOLE(ibp))
2931				continue;
2932			fill += BP_GET_FILL(ibp);
2933		}
2934	}
2935	DB_DNODE_EXIT(db);
2936
2937	if (!BP_IS_EMBEDDED(bp))
2938		bp->blk_fill = fill;
2939
2940	mutex_exit(&db->db_mtx);
2941}
2942
2943/*
2944 * The SPA will call this callback several times for each zio - once
2945 * for every physical child i/o (zio->io_phys_children times).  This
2946 * allows the DMU to monitor the progress of each logical i/o.  For example,
2947 * there may be 2 copies of an indirect block, or many fragments of a RAID-Z
2948 * block.  There may be a long delay before all copies/fragments are completed,
2949 * so this callback allows us to retire dirty space gradually, as the physical
2950 * i/os complete.
2951 */
2952/* ARGSUSED */
2953static void
2954dbuf_write_physdone(zio_t *zio, arc_buf_t *buf, void *arg)
2955{
2956	dmu_buf_impl_t *db = arg;
2957	objset_t *os = db->db_objset;
2958	dsl_pool_t *dp = dmu_objset_pool(os);
2959	dbuf_dirty_record_t *dr;
2960	int delta = 0;
2961
2962	dr = db->db_data_pending;
2963	ASSERT3U(dr->dr_txg, ==, zio->io_txg);
2964
2965	/*
2966	 * The callback will be called io_phys_children times.  Retire one
2967	 * portion of our dirty space each time we are called.  Any rounding
2968	 * error will be cleaned up by dsl_pool_sync()'s call to
2969	 * dsl_pool_undirty_space().
2970	 */
2971	delta = dr->dr_accounted / zio->io_phys_children;
2972	dsl_pool_undirty_space(dp, delta, zio->io_txg);
2973}
2974
2975/* ARGSUSED */
2976static void
2977dbuf_write_done(zio_t *zio, arc_buf_t *buf, void *vdb)
2978{
2979	dmu_buf_impl_t *db = vdb;
2980	blkptr_t *bp_orig = &zio->io_bp_orig;
2981	blkptr_t *bp = db->db_blkptr;
2982	objset_t *os = db->db_objset;
2983	dmu_tx_t *tx = os->os_synctx;
2984	dbuf_dirty_record_t **drp, *dr;
2985
2986	ASSERT0(zio->io_error);
2987	ASSERT(db->db_blkptr == bp);
2988
2989	/*
2990	 * For nopwrites and rewrites we ensure that the bp matches our
2991	 * original and bypass all the accounting.
2992	 */
2993	if (zio->io_flags & (ZIO_FLAG_IO_REWRITE | ZIO_FLAG_NOPWRITE)) {
2994		ASSERT(BP_EQUAL(bp, bp_orig));
2995	} else {
2996		dsl_dataset_t *ds = os->os_dsl_dataset;
2997		(void) dsl_dataset_block_kill(ds, bp_orig, tx, B_TRUE);
2998		dsl_dataset_block_born(ds, bp, tx);
2999	}
3000
3001	mutex_enter(&db->db_mtx);
3002
3003	DBUF_VERIFY(db);
3004
3005	drp = &db->db_last_dirty;
3006	while ((dr = *drp) != db->db_data_pending)
3007		drp = &dr->dr_next;
3008	ASSERT(!list_link_active(&dr->dr_dirty_node));
3009	ASSERT(dr->dr_dbuf == db);
3010	ASSERT(dr->dr_next == NULL);
3011	*drp = dr->dr_next;
3012
3013#ifdef ZFS_DEBUG
3014	if (db->db_blkid == DMU_SPILL_BLKID) {
3015		dnode_t *dn;
3016
3017		DB_DNODE_ENTER(db);
3018		dn = DB_DNODE(db);
3019		ASSERT(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR);
3020		ASSERT(!(BP_IS_HOLE(db->db_blkptr)) &&
3021		    db->db_blkptr == &dn->dn_phys->dn_spill);
3022		DB_DNODE_EXIT(db);
3023	}
3024#endif
3025
3026	if (db->db_level == 0) {
3027		ASSERT(db->db_blkid != DMU_BONUS_BLKID);
3028		ASSERT(dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN);
3029		if (db->db_state != DB_NOFILL) {
3030			if (dr->dt.dl.dr_data != db->db_buf)
3031				VERIFY(arc_buf_remove_ref(dr->dt.dl.dr_data,
3032				    db));
3033			else if (!arc_released(db->db_buf))
3034				arc_set_callback(db->db_buf, dbuf_do_evict, db);
3035		}
3036	} else {
3037		dnode_t *dn;
3038
3039		DB_DNODE_ENTER(db);
3040		dn = DB_DNODE(db);
3041		ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
3042		ASSERT3U(db->db.db_size, ==, 1 << dn->dn_phys->dn_indblkshift);
3043		if (!BP_IS_HOLE(db->db_blkptr)) {
3044			int epbs =
3045			    dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
3046			ASSERT3U(db->db_blkid, <=,
3047			    dn->dn_phys->dn_maxblkid >> (db->db_level * epbs));
3048			ASSERT3U(BP_GET_LSIZE(db->db_blkptr), ==,
3049			    db->db.db_size);
3050			if (!arc_released(db->db_buf))
3051				arc_set_callback(db->db_buf, dbuf_do_evict, db);
3052		}
3053		DB_DNODE_EXIT(db);
3054		mutex_destroy(&dr->dt.di.dr_mtx);
3055		list_destroy(&dr->dt.di.dr_children);
3056	}
3057	kmem_free(dr, sizeof (dbuf_dirty_record_t));
3058
3059	cv_broadcast(&db->db_changed);
3060	ASSERT(db->db_dirtycnt > 0);
3061	db->db_dirtycnt -= 1;
3062	db->db_data_pending = NULL;
3063	dbuf_rele_and_unlock(db, (void *)(uintptr_t)tx->tx_txg);
3064}
3065
3066static void
3067dbuf_write_nofill_ready(zio_t *zio)
3068{
3069	dbuf_write_ready(zio, NULL, zio->io_private);
3070}
3071
3072static void
3073dbuf_write_nofill_done(zio_t *zio)
3074{
3075	dbuf_write_done(zio, NULL, zio->io_private);
3076}
3077
3078static void
3079dbuf_write_override_ready(zio_t *zio)
3080{
3081	dbuf_dirty_record_t *dr = zio->io_private;
3082	dmu_buf_impl_t *db = dr->dr_dbuf;
3083
3084	dbuf_write_ready(zio, NULL, db);
3085}
3086
3087static void
3088dbuf_write_override_done(zio_t *zio)
3089{
3090	dbuf_dirty_record_t *dr = zio->io_private;
3091	dmu_buf_impl_t *db = dr->dr_dbuf;
3092	blkptr_t *obp = &dr->dt.dl.dr_overridden_by;
3093
3094	mutex_enter(&db->db_mtx);
3095	if (!BP_EQUAL(zio->io_bp, obp)) {
3096		if (!BP_IS_HOLE(obp))
3097			dsl_free(spa_get_dsl(zio->io_spa), zio->io_txg, obp);
3098		arc_release(dr->dt.dl.dr_data, db);
3099	}
3100	mutex_exit(&db->db_mtx);
3101
3102	dbuf_write_done(zio, NULL, db);
3103}
3104
3105/* Issue I/O to commit a dirty buffer to disk. */
3106static void
3107dbuf_write(dbuf_dirty_record_t *dr, arc_buf_t *data, dmu_tx_t *tx)
3108{
3109	dmu_buf_impl_t *db = dr->dr_dbuf;
3110	dnode_t *dn;
3111	objset_t *os;
3112	dmu_buf_impl_t *parent = db->db_parent;
3113	uint64_t txg = tx->tx_txg;
3114	zbookmark_phys_t zb;
3115	zio_prop_t zp;
3116	zio_t *zio;
3117	int wp_flag = 0;
3118
3119	DB_DNODE_ENTER(db);
3120	dn = DB_DNODE(db);
3121	os = dn->dn_objset;
3122
3123	if (db->db_state != DB_NOFILL) {
3124		if (db->db_level > 0 || dn->dn_type == DMU_OT_DNODE) {
3125			/*
3126			 * Private object buffers are released here rather
3127			 * than in dbuf_dirty() since they are only modified
3128			 * in the syncing context and we don't want the
3129			 * overhead of making multiple copies of the data.
3130			 */
3131			if (BP_IS_HOLE(db->db_blkptr)) {
3132				arc_buf_thaw(data);
3133			} else {
3134				dbuf_release_bp(db);
3135			}
3136		}
3137	}
3138
3139	if (parent != dn->dn_dbuf) {
3140		/* Our parent is an indirect block. */
3141		/* We have a dirty parent that has been scheduled for write. */
3142		ASSERT(parent && parent->db_data_pending);
3143		/* Our parent's buffer is one level closer to the dnode. */
3144		ASSERT(db->db_level == parent->db_level-1);
3145		/*
3146		 * We're about to modify our parent's db_data by modifying
3147		 * our block pointer, so the parent must be released.
3148		 */
3149		ASSERT(arc_released(parent->db_buf));
3150		zio = parent->db_data_pending->dr_zio;
3151	} else {
3152		/* Our parent is the dnode itself. */
3153		ASSERT((db->db_level == dn->dn_phys->dn_nlevels-1 &&
3154		    db->db_blkid != DMU_SPILL_BLKID) ||
3155		    (db->db_blkid == DMU_SPILL_BLKID && db->db_level == 0));
3156		if (db->db_blkid != DMU_SPILL_BLKID)
3157			ASSERT3P(db->db_blkptr, ==,
3158			    &dn->dn_phys->dn_blkptr[db->db_blkid]);
3159		zio = dn->dn_zio;
3160	}
3161
3162	ASSERT(db->db_level == 0 || data == db->db_buf);
3163	ASSERT3U(db->db_blkptr->blk_birth, <=, txg);
3164	ASSERT(zio);
3165
3166	SET_BOOKMARK(&zb, os->os_dsl_dataset ?
3167	    os->os_dsl_dataset->ds_object : DMU_META_OBJSET,
3168	    db->db.db_object, db->db_level, db->db_blkid);
3169
3170	if (db->db_blkid == DMU_SPILL_BLKID)
3171		wp_flag = WP_SPILL;
3172	wp_flag |= (db->db_state == DB_NOFILL) ? WP_NOFILL : 0;
3173
3174	dmu_write_policy(os, dn, db->db_level, wp_flag, &zp);
3175	DB_DNODE_EXIT(db);
3176
3177	if (db->db_level == 0 &&
3178	    dr->dt.dl.dr_override_state == DR_OVERRIDDEN) {
3179		/*
3180		 * The BP for this block has been provided by open context
3181		 * (by dmu_sync() or dmu_buf_write_embedded()).
3182		 */
3183		void *contents = (data != NULL) ? data->b_data : NULL;
3184
3185		dr->dr_zio = zio_write(zio, os->os_spa, txg,
3186		    db->db_blkptr, contents, db->db.db_size, &zp,
3187		    dbuf_write_override_ready, NULL, dbuf_write_override_done,
3188		    dr, ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
3189		mutex_enter(&db->db_mtx);
3190		dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
3191		zio_write_override(dr->dr_zio, &dr->dt.dl.dr_overridden_by,
3192		    dr->dt.dl.dr_copies, dr->dt.dl.dr_nopwrite);
3193		mutex_exit(&db->db_mtx);
3194	} else if (db->db_state == DB_NOFILL) {
3195		ASSERT(zp.zp_checksum == ZIO_CHECKSUM_OFF ||
3196		    zp.zp_checksum == ZIO_CHECKSUM_NOPARITY);
3197		dr->dr_zio = zio_write(zio, os->os_spa, txg,
3198		    db->db_blkptr, NULL, db->db.db_size, &zp,
3199		    dbuf_write_nofill_ready, NULL, dbuf_write_nofill_done, db,
3200		    ZIO_PRIORITY_ASYNC_WRITE,
3201		    ZIO_FLAG_MUSTSUCCEED | ZIO_FLAG_NODATA, &zb);
3202	} else {
3203		ASSERT(arc_released(data));
3204		dr->dr_zio = arc_write(zio, os->os_spa, txg,
3205		    db->db_blkptr, data, DBUF_IS_L2CACHEABLE(db),
3206		    DBUF_IS_L2COMPRESSIBLE(db), &zp, dbuf_write_ready,
3207		    dbuf_write_physdone, dbuf_write_done, db,
3208		    ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
3209	}
3210}
3211