Home | History | Annotate | Line # | Download | only in zfs
dbuf.c revision 1.1.1.3
      1 /*
      2  * CDDL HEADER START
      3  *
      4  * The contents of this file are subject to the terms of the
      5  * Common Development and Distribution License (the "License").
      6  * You may not use this file except in compliance with the License.
      7  *
      8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
      9  * or http://www.opensolaris.org/os/licensing.
     10  * See the License for the specific language governing permissions
     11  * and limitations under the License.
     12  *
     13  * When distributing Covered Code, include this CDDL HEADER in each
     14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
     15  * If applicable, add the following below this CDDL HEADER, with the
     16  * fields enclosed by brackets "[]" replaced with your own identifying
     17  * information: Portions Copyright [yyyy] [name of copyright owner]
     18  *
     19  * CDDL HEADER END
     20  */
     21 /*
     22  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
     23  * Copyright 2011 Nexenta Systems, Inc.  All rights reserved.
     24  * Copyright (c) 2012, 2016 by Delphix. All rights reserved.
     25  * Copyright (c) 2013 by Saso Kiselkov. All rights reserved.
     26  * Copyright (c) 2013, Joyent, Inc. All rights reserved.
     27  * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
     28  * Copyright (c) 2014 Integros [integros.com]
     29  */
     30 
     31 #include <sys/zfs_context.h>
     32 #include <sys/dmu.h>
     33 #include <sys/dmu_send.h>
     34 #include <sys/dmu_impl.h>
     35 #include <sys/dbuf.h>
     36 #include <sys/dmu_objset.h>
     37 #include <sys/dsl_dataset.h>
     38 #include <sys/dsl_dir.h>
     39 #include <sys/dmu_tx.h>
     40 #include <sys/spa.h>
     41 #include <sys/zio.h>
     42 #include <sys/dmu_zfetch.h>
     43 #include <sys/sa.h>
     44 #include <sys/sa_impl.h>
     45 #include <sys/zfeature.h>
     46 #include <sys/blkptr.h>
     47 #include <sys/range_tree.h>
     48 #include <sys/callb.h>
     49 
     50 uint_t zfs_dbuf_evict_key;
     51 
     52 static boolean_t dbuf_undirty(dmu_buf_impl_t *db, dmu_tx_t *tx);
     53 static void dbuf_write(dbuf_dirty_record_t *dr, arc_buf_t *data, dmu_tx_t *tx);
     54 
     55 #ifndef __lint
     56 extern inline void dmu_buf_init_user(dmu_buf_user_t *dbu,
     57     dmu_buf_evict_func_t *evict_func_sync,
     58     dmu_buf_evict_func_t *evict_func_async,
     59     dmu_buf_t **clear_on_evict_dbufp);
     60 #endif /* ! __lint */
     61 
     62 /*
     63  * Global data structures and functions for the dbuf cache.
     64  */
     65 static kmem_cache_t *dbuf_kmem_cache;
     66 static taskq_t *dbu_evict_taskq;
     67 
     68 static kthread_t *dbuf_cache_evict_thread;
     69 static kmutex_t dbuf_evict_lock;
     70 static kcondvar_t dbuf_evict_cv;
     71 static boolean_t dbuf_evict_thread_exit;
     72 
     73 /*
     74  * LRU cache of dbufs. The dbuf cache maintains a list of dbufs that
     75  * are not currently held but have been recently released. These dbufs
     76  * are not eligible for arc eviction until they are aged out of the cache.
     77  * Dbufs are added to the dbuf cache once the last hold is released. If a
     78  * dbuf is later accessed and still exists in the dbuf cache, then it will
     79  * be removed from the cache and later re-added to the head of the cache.
     80  * Dbufs that are aged out of the cache will be immediately destroyed and
     81  * become eligible for arc eviction.
     82  */
     83 static multilist_t dbuf_cache;
     84 static refcount_t dbuf_cache_size;
     85 uint64_t dbuf_cache_max_bytes = 100 * 1024 * 1024;
     86 
     87 /* Cap the size of the dbuf cache to log2 fraction of arc size. */
     88 int dbuf_cache_max_shift = 5;
     89 
     90 /*
     91  * The dbuf cache uses a three-stage eviction policy:
     92  *	- A low water marker designates when the dbuf eviction thread
     93  *	should stop evicting from the dbuf cache.
     94  *	- When we reach the maximum size (aka mid water mark), we
     95  *	signal the eviction thread to run.
     96  *	- The high water mark indicates when the eviction thread
     97  *	is unable to keep up with the incoming load and eviction must
     98  *	happen in the context of the calling thread.
     99  *
    100  * The dbuf cache:
    101  *                                                 (max size)
    102  *                                      low water   mid water   hi water
    103  * +----------------------------------------+----------+----------+
    104  * |                                        |          |          |
    105  * |                                        |          |          |
    106  * |                                        |          |          |
    107  * |                                        |          |          |
    108  * +----------------------------------------+----------+----------+
    109  *                                        stop        signal     evict
    110  *                                      evicting     eviction   directly
    111  *                                                    thread
    112  *
    113  * The high and low water marks indicate the operating range for the eviction
    114  * thread. The low water mark is, by default, 90% of the total size of the
    115  * cache and the high water mark is at 110% (both of these percentages can be
    116  * changed by setting dbuf_cache_lowater_pct and dbuf_cache_hiwater_pct,
    117  * respectively). The eviction thread will try to ensure that the cache remains
    118  * within this range by waking up every second and checking if the cache is
    119  * above the low water mark. The thread can also be woken up by callers adding
    120  * elements into the cache if the cache is larger than the mid water (i.e max
    121  * cache size). Once the eviction thread is woken up and eviction is required,
    122  * it will continue evicting buffers until it's able to reduce the cache size
    123  * to the low water mark. If the cache size continues to grow and hits the high
    124  * water mark, then callers adding elments to the cache will begin to evict
    125  * directly from the cache until the cache is no longer above the high water
    126  * mark.
    127  */
    128 
    129 /*
    130  * The percentage above and below the maximum cache size.
    131  */
    132 uint_t dbuf_cache_hiwater_pct = 10;
    133 uint_t dbuf_cache_lowater_pct = 10;
    134 
    135 /* ARGSUSED */
    136 static int
    137 dbuf_cons(void *vdb, void *unused, int kmflag)
    138 {
    139 	dmu_buf_impl_t *db = vdb;
    140 	bzero(db, sizeof (dmu_buf_impl_t));
    141 
    142 	mutex_init(&db->db_mtx, NULL, MUTEX_DEFAULT, NULL);
    143 	cv_init(&db->db_changed, NULL, CV_DEFAULT, NULL);
    144 	multilist_link_init(&db->db_cache_link);
    145 	refcount_create(&db->db_holds);
    146 
    147 	return (0);
    148 }
    149 
    150 /* ARGSUSED */
    151 static void
    152 dbuf_dest(void *vdb, void *unused)
    153 {
    154 	dmu_buf_impl_t *db = vdb;
    155 	mutex_destroy(&db->db_mtx);
    156 	cv_destroy(&db->db_changed);
    157 	ASSERT(!multilist_link_active(&db->db_cache_link));
    158 	refcount_destroy(&db->db_holds);
    159 }
    160 
    161 /*
    162  * dbuf hash table routines
    163  */
    164 static dbuf_hash_table_t dbuf_hash_table;
    165 
    166 static uint64_t dbuf_hash_count;
    167 
    168 static uint64_t
    169 dbuf_hash(void *os, uint64_t obj, uint8_t lvl, uint64_t blkid)
    170 {
    171 	uintptr_t osv = (uintptr_t)os;
    172 	uint64_t crc = -1ULL;
    173 
    174 	ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
    175 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (lvl)) & 0xFF];
    176 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (osv >> 6)) & 0xFF];
    177 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (obj >> 0)) & 0xFF];
    178 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (obj >> 8)) & 0xFF];
    179 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (blkid >> 0)) & 0xFF];
    180 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (blkid >> 8)) & 0xFF];
    181 
    182 	crc ^= (osv>>14) ^ (obj>>16) ^ (blkid>>16);
    183 
    184 	return (crc);
    185 }
    186 
    187 #define	DBUF_EQUAL(dbuf, os, obj, level, blkid)		\
    188 	((dbuf)->db.db_object == (obj) &&		\
    189 	(dbuf)->db_objset == (os) &&			\
    190 	(dbuf)->db_level == (level) &&			\
    191 	(dbuf)->db_blkid == (blkid))
    192 
    193 dmu_buf_impl_t *
    194 dbuf_find(objset_t *os, uint64_t obj, uint8_t level, uint64_t blkid)
    195 {
    196 	dbuf_hash_table_t *h = &dbuf_hash_table;
    197 	uint64_t hv = dbuf_hash(os, obj, level, blkid);
    198 	uint64_t idx = hv & h->hash_table_mask;
    199 	dmu_buf_impl_t *db;
    200 
    201 	mutex_enter(DBUF_HASH_MUTEX(h, idx));
    202 	for (db = h->hash_table[idx]; db != NULL; db = db->db_hash_next) {
    203 		if (DBUF_EQUAL(db, os, obj, level, blkid)) {
    204 			mutex_enter(&db->db_mtx);
    205 			if (db->db_state != DB_EVICTING) {
    206 				mutex_exit(DBUF_HASH_MUTEX(h, idx));
    207 				return (db);
    208 			}
    209 			mutex_exit(&db->db_mtx);
    210 		}
    211 	}
    212 	mutex_exit(DBUF_HASH_MUTEX(h, idx));
    213 	return (NULL);
    214 }
    215 
    216 static dmu_buf_impl_t *
    217 dbuf_find_bonus(objset_t *os, uint64_t object)
    218 {
    219 	dnode_t *dn;
    220 	dmu_buf_impl_t *db = NULL;
    221 
    222 	if (dnode_hold(os, object, FTAG, &dn) == 0) {
    223 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
    224 		if (dn->dn_bonus != NULL) {
    225 			db = dn->dn_bonus;
    226 			mutex_enter(&db->db_mtx);
    227 		}
    228 		rw_exit(&dn->dn_struct_rwlock);
    229 		dnode_rele(dn, FTAG);
    230 	}
    231 	return (db);
    232 }
    233 
    234 /*
    235  * Insert an entry into the hash table.  If there is already an element
    236  * equal to elem in the hash table, then the already existing element
    237  * will be returned and the new element will not be inserted.
    238  * Otherwise returns NULL.
    239  */
    240 static dmu_buf_impl_t *
    241 dbuf_hash_insert(dmu_buf_impl_t *db)
    242 {
    243 	dbuf_hash_table_t *h = &dbuf_hash_table;
    244 	objset_t *os = db->db_objset;
    245 	uint64_t obj = db->db.db_object;
    246 	int level = db->db_level;
    247 	uint64_t blkid = db->db_blkid;
    248 	uint64_t hv = dbuf_hash(os, obj, level, blkid);
    249 	uint64_t idx = hv & h->hash_table_mask;
    250 	dmu_buf_impl_t *dbf;
    251 
    252 	mutex_enter(DBUF_HASH_MUTEX(h, idx));
    253 	for (dbf = h->hash_table[idx]; dbf != NULL; dbf = dbf->db_hash_next) {
    254 		if (DBUF_EQUAL(dbf, os, obj, level, blkid)) {
    255 			mutex_enter(&dbf->db_mtx);
    256 			if (dbf->db_state != DB_EVICTING) {
    257 				mutex_exit(DBUF_HASH_MUTEX(h, idx));
    258 				return (dbf);
    259 			}
    260 			mutex_exit(&dbf->db_mtx);
    261 		}
    262 	}
    263 
    264 	mutex_enter(&db->db_mtx);
    265 	db->db_hash_next = h->hash_table[idx];
    266 	h->hash_table[idx] = db;
    267 	mutex_exit(DBUF_HASH_MUTEX(h, idx));
    268 	atomic_inc_64(&dbuf_hash_count);
    269 
    270 	return (NULL);
    271 }
    272 
    273 /*
    274  * Remove an entry from the hash table.  It must be in the EVICTING state.
    275  */
    276 static void
    277 dbuf_hash_remove(dmu_buf_impl_t *db)
    278 {
    279 	dbuf_hash_table_t *h = &dbuf_hash_table;
    280 	uint64_t hv = dbuf_hash(db->db_objset, db->db.db_object,
    281 	    db->db_level, db->db_blkid);
    282 	uint64_t idx = hv & h->hash_table_mask;
    283 	dmu_buf_impl_t *dbf, **dbp;
    284 
    285 	/*
    286 	 * We musn't hold db_mtx to maintain lock ordering:
    287 	 * DBUF_HASH_MUTEX > db_mtx.
    288 	 */
    289 	ASSERT(refcount_is_zero(&db->db_holds));
    290 	ASSERT(db->db_state == DB_EVICTING);
    291 	ASSERT(!MUTEX_HELD(&db->db_mtx));
    292 
    293 	mutex_enter(DBUF_HASH_MUTEX(h, idx));
    294 	dbp = &h->hash_table[idx];
    295 	while ((dbf = *dbp) != db) {
    296 		dbp = &dbf->db_hash_next;
    297 		ASSERT(dbf != NULL);
    298 	}
    299 	*dbp = db->db_hash_next;
    300 	db->db_hash_next = NULL;
    301 	mutex_exit(DBUF_HASH_MUTEX(h, idx));
    302 	atomic_dec_64(&dbuf_hash_count);
    303 }
    304 
    305 typedef enum {
    306 	DBVU_EVICTING,
    307 	DBVU_NOT_EVICTING
    308 } dbvu_verify_type_t;
    309 
    310 static void
    311 dbuf_verify_user(dmu_buf_impl_t *db, dbvu_verify_type_t verify_type)
    312 {
    313 #ifdef ZFS_DEBUG
    314 	int64_t holds;
    315 
    316 	if (db->db_user == NULL)
    317 		return;
    318 
    319 	/* Only data blocks support the attachment of user data. */
    320 	ASSERT(db->db_level == 0);
    321 
    322 	/* Clients must resolve a dbuf before attaching user data. */
    323 	ASSERT(db->db.db_data != NULL);
    324 	ASSERT3U(db->db_state, ==, DB_CACHED);
    325 
    326 	holds = refcount_count(&db->db_holds);
    327 	if (verify_type == DBVU_EVICTING) {
    328 		/*
    329 		 * Immediate eviction occurs when holds == dirtycnt.
    330 		 * For normal eviction buffers, holds is zero on
    331 		 * eviction, except when dbuf_fix_old_data() calls
    332 		 * dbuf_clear_data().  However, the hold count can grow
    333 		 * during eviction even though db_mtx is held (see
    334 		 * dmu_bonus_hold() for an example), so we can only
    335 		 * test the generic invariant that holds >= dirtycnt.
    336 		 */
    337 		ASSERT3U(holds, >=, db->db_dirtycnt);
    338 	} else {
    339 		if (db->db_user_immediate_evict == TRUE)
    340 			ASSERT3U(holds, >=, db->db_dirtycnt);
    341 		else
    342 			ASSERT3U(holds, >, 0);
    343 	}
    344 #endif
    345 }
    346 
    347 static void
    348 dbuf_evict_user(dmu_buf_impl_t *db)
    349 {
    350 	dmu_buf_user_t *dbu = db->db_user;
    351 
    352 	ASSERT(MUTEX_HELD(&db->db_mtx));
    353 
    354 	if (dbu == NULL)
    355 		return;
    356 
    357 	dbuf_verify_user(db, DBVU_EVICTING);
    358 	db->db_user = NULL;
    359 
    360 #ifdef ZFS_DEBUG
    361 	if (dbu->dbu_clear_on_evict_dbufp != NULL)
    362 		*dbu->dbu_clear_on_evict_dbufp = NULL;
    363 #endif
    364 
    365 	/*
    366 	 * There are two eviction callbacks - one that we call synchronously
    367 	 * and one that we invoke via a taskq.  The async one is useful for
    368 	 * avoiding lock order reversals and limiting stack depth.
    369 	 *
    370 	 * Note that if we have a sync callback but no async callback,
    371 	 * it's likely that the sync callback will free the structure
    372 	 * containing the dbu.  In that case we need to take care to not
    373 	 * dereference dbu after calling the sync evict func.
    374 	 */
    375 	boolean_t has_async = (dbu->dbu_evict_func_async != NULL);
    376 
    377 	if (dbu->dbu_evict_func_sync != NULL)
    378 		dbu->dbu_evict_func_sync(dbu);
    379 
    380 	if (has_async) {
    381 		taskq_dispatch_ent(dbu_evict_taskq, dbu->dbu_evict_func_async,
    382 		    dbu, 0, &dbu->dbu_tqent);
    383 	}
    384 }
    385 
    386 boolean_t
    387 dbuf_is_metadata(dmu_buf_impl_t *db)
    388 {
    389 	if (db->db_level > 0) {
    390 		return (B_TRUE);
    391 	} else {
    392 		boolean_t is_metadata;
    393 
    394 		DB_DNODE_ENTER(db);
    395 		is_metadata = DMU_OT_IS_METADATA(DB_DNODE(db)->dn_type);
    396 		DB_DNODE_EXIT(db);
    397 
    398 		return (is_metadata);
    399 	}
    400 }
    401 
    402 /*
    403  * This function *must* return indices evenly distributed between all
    404  * sublists of the multilist. This is needed due to how the dbuf eviction
    405  * code is laid out; dbuf_evict_thread() assumes dbufs are evenly
    406  * distributed between all sublists and uses this assumption when
    407  * deciding which sublist to evict from and how much to evict from it.
    408  */
    409 unsigned int
    410 dbuf_cache_multilist_index_func(multilist_t *ml, void *obj)
    411 {
    412 	dmu_buf_impl_t *db = obj;
    413 
    414 	/*
    415 	 * The assumption here, is the hash value for a given
    416 	 * dmu_buf_impl_t will remain constant throughout it's lifetime
    417 	 * (i.e. it's objset, object, level and blkid fields don't change).
    418 	 * Thus, we don't need to store the dbuf's sublist index
    419 	 * on insertion, as this index can be recalculated on removal.
    420 	 *
    421 	 * Also, the low order bits of the hash value are thought to be
    422 	 * distributed evenly. Otherwise, in the case that the multilist
    423 	 * has a power of two number of sublists, each sublists' usage
    424 	 * would not be evenly distributed.
    425 	 */
    426 	return (dbuf_hash(db->db_objset, db->db.db_object,
    427 	    db->db_level, db->db_blkid) %
    428 	    multilist_get_num_sublists(ml));
    429 }
    430 
    431 static inline boolean_t
    432 dbuf_cache_above_hiwater(void)
    433 {
    434 	uint64_t dbuf_cache_hiwater_bytes =
    435 	    (dbuf_cache_max_bytes * dbuf_cache_hiwater_pct) / 100;
    436 
    437 	return (refcount_count(&dbuf_cache_size) >
    438 	    dbuf_cache_max_bytes + dbuf_cache_hiwater_bytes);
    439 }
    440 
    441 static inline boolean_t
    442 dbuf_cache_above_lowater(void)
    443 {
    444 	uint64_t dbuf_cache_lowater_bytes =
    445 	    (dbuf_cache_max_bytes * dbuf_cache_lowater_pct) / 100;
    446 
    447 	return (refcount_count(&dbuf_cache_size) >
    448 	    dbuf_cache_max_bytes - dbuf_cache_lowater_bytes);
    449 }
    450 
    451 /*
    452  * Evict the oldest eligible dbuf from the dbuf cache.
    453  */
    454 static void
    455 dbuf_evict_one(void)
    456 {
    457 	int idx = multilist_get_random_index(&dbuf_cache);
    458 	multilist_sublist_t *mls = multilist_sublist_lock(&dbuf_cache, idx);
    459 
    460 	ASSERT(!MUTEX_HELD(&dbuf_evict_lock));
    461 
    462 	/*
    463 	 * Set the thread's tsd to indicate that it's processing evictions.
    464 	 * Once a thread stops evicting from the dbuf cache it will
    465 	 * reset its tsd to NULL.
    466 	 */
    467 	ASSERT3P(tsd_get(zfs_dbuf_evict_key), ==, NULL);
    468 	(void) tsd_set(zfs_dbuf_evict_key, (void *)B_TRUE);
    469 
    470 	dmu_buf_impl_t *db = multilist_sublist_tail(mls);
    471 	while (db != NULL && mutex_tryenter(&db->db_mtx) == 0) {
    472 		db = multilist_sublist_prev(mls, db);
    473 	}
    474 
    475 	DTRACE_PROBE2(dbuf__evict__one, dmu_buf_impl_t *, db,
    476 	    multilist_sublist_t *, mls);
    477 
    478 	if (db != NULL) {
    479 		multilist_sublist_remove(mls, db);
    480 		multilist_sublist_unlock(mls);
    481 		(void) refcount_remove_many(&dbuf_cache_size,
    482 		    db->db.db_size, db);
    483 		dbuf_destroy(db);
    484 	} else {
    485 		multilist_sublist_unlock(mls);
    486 	}
    487 	(void) tsd_set(zfs_dbuf_evict_key, NULL);
    488 }
    489 
    490 /*
    491  * The dbuf evict thread is responsible for aging out dbufs from the
    492  * cache. Once the cache has reached it's maximum size, dbufs are removed
    493  * and destroyed. The eviction thread will continue running until the size
    494  * of the dbuf cache is at or below the maximum size. Once the dbuf is aged
    495  * out of the cache it is destroyed and becomes eligible for arc eviction.
    496  */
    497 static void
    498 dbuf_evict_thread(void *dummy __unused)
    499 {
    500 	callb_cpr_t cpr;
    501 
    502 	CALLB_CPR_INIT(&cpr, &dbuf_evict_lock, callb_generic_cpr, FTAG);
    503 
    504 	mutex_enter(&dbuf_evict_lock);
    505 	while (!dbuf_evict_thread_exit) {
    506 		while (!dbuf_cache_above_lowater() && !dbuf_evict_thread_exit) {
    507 			CALLB_CPR_SAFE_BEGIN(&cpr);
    508 			(void) cv_timedwait_hires(&dbuf_evict_cv,
    509 			    &dbuf_evict_lock, SEC2NSEC(1), MSEC2NSEC(1), 0);
    510 			CALLB_CPR_SAFE_END(&cpr, &dbuf_evict_lock);
    511 		}
    512 		mutex_exit(&dbuf_evict_lock);
    513 
    514 		/*
    515 		 * Keep evicting as long as we're above the low water mark
    516 		 * for the cache. We do this without holding the locks to
    517 		 * minimize lock contention.
    518 		 */
    519 		while (dbuf_cache_above_lowater() && !dbuf_evict_thread_exit) {
    520 			dbuf_evict_one();
    521 		}
    522 
    523 		mutex_enter(&dbuf_evict_lock);
    524 	}
    525 
    526 	dbuf_evict_thread_exit = B_FALSE;
    527 	cv_broadcast(&dbuf_evict_cv);
    528 	CALLB_CPR_EXIT(&cpr);	/* drops dbuf_evict_lock */
    529 	thread_exit();
    530 }
    531 
    532 /*
    533  * Wake up the dbuf eviction thread if the dbuf cache is at its max size.
    534  * If the dbuf cache is at its high water mark, then evict a dbuf from the
    535  * dbuf cache using the callers context.
    536  */
    537 static void
    538 dbuf_evict_notify(void)
    539 {
    540 
    541 	/*
    542 	 * We use thread specific data to track when a thread has
    543 	 * started processing evictions. This allows us to avoid deeply
    544 	 * nested stacks that would have a call flow similar to this:
    545 	 *
    546 	 * dbuf_rele()-->dbuf_rele_and_unlock()-->dbuf_evict_notify()
    547 	 *	^						|
    548 	 *	|						|
    549 	 *	+-----dbuf_destroy()<--dbuf_evict_one()<--------+
    550 	 *
    551 	 * The dbuf_eviction_thread will always have its tsd set until
    552 	 * that thread exits. All other threads will only set their tsd
    553 	 * if they are participating in the eviction process. This only
    554 	 * happens if the eviction thread is unable to process evictions
    555 	 * fast enough. To keep the dbuf cache size in check, other threads
    556 	 * can evict from the dbuf cache directly. Those threads will set
    557 	 * their tsd values so that we ensure that they only evict one dbuf
    558 	 * from the dbuf cache.
    559 	 */
    560 	if (tsd_get(zfs_dbuf_evict_key) != NULL)
    561 		return;
    562 
    563 	if (refcount_count(&dbuf_cache_size) > dbuf_cache_max_bytes) {
    564 		boolean_t evict_now = B_FALSE;
    565 
    566 		mutex_enter(&dbuf_evict_lock);
    567 		if (refcount_count(&dbuf_cache_size) > dbuf_cache_max_bytes) {
    568 			evict_now = dbuf_cache_above_hiwater();
    569 			cv_signal(&dbuf_evict_cv);
    570 		}
    571 		mutex_exit(&dbuf_evict_lock);
    572 
    573 		if (evict_now) {
    574 			dbuf_evict_one();
    575 		}
    576 	}
    577 }
    578 
    579 void
    580 dbuf_init(void)
    581 {
    582 	uint64_t hsize = 1ULL << 16;
    583 	dbuf_hash_table_t *h = &dbuf_hash_table;
    584 	int i;
    585 
    586 	/*
    587 	 * The hash table is big enough to fill all of physical memory
    588 	 * with an average 4K block size.  The table will take up
    589 	 * totalmem*sizeof(void*)/4K (i.e. 2MB/GB with 8-byte pointers).
    590 	 */
    591 	while (hsize * 4096 < (uint64_t)physmem * PAGESIZE)
    592 		hsize <<= 1;
    593 
    594 retry:
    595 	h->hash_table_mask = hsize - 1;
    596 	h->hash_table = kmem_zalloc(hsize * sizeof (void *), KM_NOSLEEP);
    597 	if (h->hash_table == NULL) {
    598 		/* XXX - we should really return an error instead of assert */
    599 		ASSERT(hsize > (1ULL << 10));
    600 		hsize >>= 1;
    601 		goto retry;
    602 	}
    603 
    604 	dbuf_kmem_cache = kmem_cache_create("dmu_buf_impl_t",
    605 	    sizeof (dmu_buf_impl_t),
    606 	    0, dbuf_cons, dbuf_dest, NULL, NULL, NULL, 0);
    607 
    608 	for (i = 0; i < DBUF_MUTEXES; i++)
    609 		mutex_init(&h->hash_mutexes[i], NULL, MUTEX_DEFAULT, NULL);
    610 
    611 	/*
    612 	 * Setup the parameters for the dbuf cache. We cap the size of the
    613 	 * dbuf cache to 1/32nd (default) of the size of the ARC.
    614 	 */
    615 	dbuf_cache_max_bytes = MIN(dbuf_cache_max_bytes,
    616 	    arc_max_bytes() >> dbuf_cache_max_shift);
    617 
    618 	/*
    619 	 * All entries are queued via taskq_dispatch_ent(), so min/maxalloc
    620 	 * configuration is not required.
    621 	 */
    622 	dbu_evict_taskq = taskq_create("dbu_evict", 1, minclsyspri, 0, 0, 0);
    623 
    624 	multilist_create(&dbuf_cache, sizeof (dmu_buf_impl_t),
    625 	    offsetof(dmu_buf_impl_t, db_cache_link),
    626 	    zfs_arc_num_sublists_per_state,
    627 	    dbuf_cache_multilist_index_func);
    628 	refcount_create(&dbuf_cache_size);
    629 
    630 	tsd_create(&zfs_dbuf_evict_key, NULL);
    631 	dbuf_evict_thread_exit = B_FALSE;
    632 	mutex_init(&dbuf_evict_lock, NULL, MUTEX_DEFAULT, NULL);
    633 	cv_init(&dbuf_evict_cv, NULL, CV_DEFAULT, NULL);
    634 	dbuf_cache_evict_thread = thread_create(NULL, 0, dbuf_evict_thread,
    635 	    NULL, 0, &p0, TS_RUN, minclsyspri);
    636 }
    637 
    638 void
    639 dbuf_fini(void)
    640 {
    641 	dbuf_hash_table_t *h = &dbuf_hash_table;
    642 	int i;
    643 
    644 	for (i = 0; i < DBUF_MUTEXES; i++)
    645 		mutex_destroy(&h->hash_mutexes[i]);
    646 	kmem_free(h->hash_table, (h->hash_table_mask + 1) * sizeof (void *));
    647 	kmem_cache_destroy(dbuf_kmem_cache);
    648 	taskq_destroy(dbu_evict_taskq);
    649 
    650 	mutex_enter(&dbuf_evict_lock);
    651 	dbuf_evict_thread_exit = B_TRUE;
    652 	while (dbuf_evict_thread_exit) {
    653 		cv_signal(&dbuf_evict_cv);
    654 		cv_wait(&dbuf_evict_cv, &dbuf_evict_lock);
    655 	}
    656 	mutex_exit(&dbuf_evict_lock);
    657 	tsd_destroy(&zfs_dbuf_evict_key);
    658 
    659 	mutex_destroy(&dbuf_evict_lock);
    660 	cv_destroy(&dbuf_evict_cv);
    661 
    662 	refcount_destroy(&dbuf_cache_size);
    663 	multilist_destroy(&dbuf_cache);
    664 }
    665 
    666 /*
    667  * Other stuff.
    668  */
    669 
    670 #ifdef ZFS_DEBUG
    671 static void
    672 dbuf_verify(dmu_buf_impl_t *db)
    673 {
    674 	dnode_t *dn;
    675 	dbuf_dirty_record_t *dr;
    676 
    677 	ASSERT(MUTEX_HELD(&db->db_mtx));
    678 
    679 	if (!(zfs_flags & ZFS_DEBUG_DBUF_VERIFY))
    680 		return;
    681 
    682 	ASSERT(db->db_objset != NULL);
    683 	DB_DNODE_ENTER(db);
    684 	dn = DB_DNODE(db);
    685 	if (dn == NULL) {
    686 		ASSERT(db->db_parent == NULL);
    687 		ASSERT(db->db_blkptr == NULL);
    688 	} else {
    689 		ASSERT3U(db->db.db_object, ==, dn->dn_object);
    690 		ASSERT3P(db->db_objset, ==, dn->dn_objset);
    691 		ASSERT3U(db->db_level, <, dn->dn_nlevels);
    692 		ASSERT(db->db_blkid == DMU_BONUS_BLKID ||
    693 		    db->db_blkid == DMU_SPILL_BLKID ||
    694 		    !avl_is_empty(&dn->dn_dbufs));
    695 	}
    696 	if (db->db_blkid == DMU_BONUS_BLKID) {
    697 		ASSERT(dn != NULL);
    698 		ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
    699 		ASSERT3U(db->db.db_offset, ==, DMU_BONUS_BLKID);
    700 	} else if (db->db_blkid == DMU_SPILL_BLKID) {
    701 		ASSERT(dn != NULL);
    702 		ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
    703 		ASSERT0(db->db.db_offset);
    704 	} else {
    705 		ASSERT3U(db->db.db_offset, ==, db->db_blkid * db->db.db_size);
    706 	}
    707 
    708 	for (dr = db->db_data_pending; dr != NULL; dr = dr->dr_next)
    709 		ASSERT(dr->dr_dbuf == db);
    710 
    711 	for (dr = db->db_last_dirty; dr != NULL; dr = dr->dr_next)
    712 		ASSERT(dr->dr_dbuf == db);
    713 
    714 	/*
    715 	 * We can't assert that db_size matches dn_datablksz because it
    716 	 * can be momentarily different when another thread is doing
    717 	 * dnode_set_blksz().
    718 	 */
    719 	if (db->db_level == 0 && db->db.db_object == DMU_META_DNODE_OBJECT) {
    720 		dr = db->db_data_pending;
    721 		/*
    722 		 * It should only be modified in syncing context, so
    723 		 * make sure we only have one copy of the data.
    724 		 */
    725 		ASSERT(dr == NULL || dr->dt.dl.dr_data == db->db_buf);
    726 	}
    727 
    728 	/* verify db->db_blkptr */
    729 	if (db->db_blkptr) {
    730 		if (db->db_parent == dn->dn_dbuf) {
    731 			/* db is pointed to by the dnode */
    732 			/* ASSERT3U(db->db_blkid, <, dn->dn_nblkptr); */
    733 			if (DMU_OBJECT_IS_SPECIAL(db->db.db_object))
    734 				ASSERT(db->db_parent == NULL);
    735 			else
    736 				ASSERT(db->db_parent != NULL);
    737 			if (db->db_blkid != DMU_SPILL_BLKID)
    738 				ASSERT3P(db->db_blkptr, ==,
    739 				    &dn->dn_phys->dn_blkptr[db->db_blkid]);
    740 		} else {
    741 			/* db is pointed to by an indirect block */
    742 			int epb = db->db_parent->db.db_size >> SPA_BLKPTRSHIFT;
    743 			ASSERT3U(db->db_parent->db_level, ==, db->db_level+1);
    744 			ASSERT3U(db->db_parent->db.db_object, ==,
    745 			    db->db.db_object);
    746 			/*
    747 			 * dnode_grow_indblksz() can make this fail if we don't
    748 			 * have the struct_rwlock.  XXX indblksz no longer
    749 			 * grows.  safe to do this now?
    750 			 */
    751 			if (RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
    752 				ASSERT3P(db->db_blkptr, ==,
    753 				    ((blkptr_t *)db->db_parent->db.db_data +
    754 				    db->db_blkid % epb));
    755 			}
    756 		}
    757 	}
    758 	if ((db->db_blkptr == NULL || BP_IS_HOLE(db->db_blkptr)) &&
    759 	    (db->db_buf == NULL || db->db_buf->b_data) &&
    760 	    db->db.db_data && db->db_blkid != DMU_BONUS_BLKID &&
    761 	    db->db_state != DB_FILL && !dn->dn_free_txg) {
    762 		/*
    763 		 * If the blkptr isn't set but they have nonzero data,
    764 		 * it had better be dirty, otherwise we'll lose that
    765 		 * data when we evict this buffer.
    766 		 *
    767 		 * There is an exception to this rule for indirect blocks; in
    768 		 * this case, if the indirect block is a hole, we fill in a few
    769 		 * fields on each of the child blocks (importantly, birth time)
    770 		 * to prevent hole birth times from being lost when you
    771 		 * partially fill in a hole.
    772 		 */
    773 		if (db->db_dirtycnt == 0) {
    774 			if (db->db_level == 0) {
    775 				uint64_t *buf = db->db.db_data;
    776 				int i;
    777 
    778 				for (i = 0; i < db->db.db_size >> 3; i++) {
    779 					ASSERT(buf[i] == 0);
    780 				}
    781 			} else {
    782 				blkptr_t *bps = db->db.db_data;
    783 				ASSERT3U(1 << DB_DNODE(db)->dn_indblkshift, ==,
    784 				    db->db.db_size);
    785 				/*
    786 				 * We want to verify that all the blkptrs in the
    787 				 * indirect block are holes, but we may have
    788 				 * automatically set up a few fields for them.
    789 				 * We iterate through each blkptr and verify
    790 				 * they only have those fields set.
    791 				 */
    792 				for (int i = 0;
    793 				    i < db->db.db_size / sizeof (blkptr_t);
    794 				    i++) {
    795 					blkptr_t *bp = &bps[i];
    796 					ASSERT(ZIO_CHECKSUM_IS_ZERO(
    797 					    &bp->blk_cksum));
    798 					ASSERT(
    799 					    DVA_IS_EMPTY(&bp->blk_dva[0]) &&
    800 					    DVA_IS_EMPTY(&bp->blk_dva[1]) &&
    801 					    DVA_IS_EMPTY(&bp->blk_dva[2]));
    802 					ASSERT0(bp->blk_fill);
    803 					ASSERT0(bp->blk_pad[0]);
    804 					ASSERT0(bp->blk_pad[1]);
    805 					ASSERT(!BP_IS_EMBEDDED(bp));
    806 					ASSERT(BP_IS_HOLE(bp));
    807 					ASSERT0(bp->blk_phys_birth);
    808 				}
    809 			}
    810 		}
    811 	}
    812 	DB_DNODE_EXIT(db);
    813 }
    814 #endif
    815 
    816 static void
    817 dbuf_clear_data(dmu_buf_impl_t *db)
    818 {
    819 	ASSERT(MUTEX_HELD(&db->db_mtx));
    820 	dbuf_evict_user(db);
    821 	ASSERT3P(db->db_buf, ==, NULL);
    822 	db->db.db_data = NULL;
    823 	if (db->db_state != DB_NOFILL)
    824 		db->db_state = DB_UNCACHED;
    825 }
    826 
    827 static void
    828 dbuf_set_data(dmu_buf_impl_t *db, arc_buf_t *buf)
    829 {
    830 	ASSERT(MUTEX_HELD(&db->db_mtx));
    831 	ASSERT(buf != NULL);
    832 
    833 	db->db_buf = buf;
    834 	ASSERT(buf->b_data != NULL);
    835 	db->db.db_data = buf->b_data;
    836 }
    837 
    838 /*
    839  * Loan out an arc_buf for read.  Return the loaned arc_buf.
    840  */
    841 arc_buf_t *
    842 dbuf_loan_arcbuf(dmu_buf_impl_t *db)
    843 {
    844 	arc_buf_t *abuf;
    845 
    846 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
    847 	mutex_enter(&db->db_mtx);
    848 	if (arc_released(db->db_buf) || refcount_count(&db->db_holds) > 1) {
    849 		int blksz = db->db.db_size;
    850 		spa_t *spa = db->db_objset->os_spa;
    851 
    852 		mutex_exit(&db->db_mtx);
    853 		abuf = arc_loan_buf(spa, blksz);
    854 		bcopy(db->db.db_data, abuf->b_data, blksz);
    855 	} else {
    856 		abuf = db->db_buf;
    857 		arc_loan_inuse_buf(abuf, db);
    858 		db->db_buf = NULL;
    859 		dbuf_clear_data(db);
    860 		mutex_exit(&db->db_mtx);
    861 	}
    862 	return (abuf);
    863 }
    864 
    865 /*
    866  * Calculate which level n block references the data at the level 0 offset
    867  * provided.
    868  */
    869 uint64_t
    870 dbuf_whichblock(dnode_t *dn, int64_t level, uint64_t offset)
    871 {
    872 	if (dn->dn_datablkshift != 0 && dn->dn_indblkshift != 0) {
    873 		/*
    874 		 * The level n blkid is equal to the level 0 blkid divided by
    875 		 * the number of level 0s in a level n block.
    876 		 *
    877 		 * The level 0 blkid is offset >> datablkshift =
    878 		 * offset / 2^datablkshift.
    879 		 *
    880 		 * The number of level 0s in a level n is the number of block
    881 		 * pointers in an indirect block, raised to the power of level.
    882 		 * This is 2^(indblkshift - SPA_BLKPTRSHIFT)^level =
    883 		 * 2^(level*(indblkshift - SPA_BLKPTRSHIFT)).
    884 		 *
    885 		 * Thus, the level n blkid is: offset /
    886 		 * ((2^datablkshift)*(2^(level*(indblkshift - SPA_BLKPTRSHIFT)))
    887 		 * = offset / 2^(datablkshift + level *
    888 		 *   (indblkshift - SPA_BLKPTRSHIFT))
    889 		 * = offset >> (datablkshift + level *
    890 		 *   (indblkshift - SPA_BLKPTRSHIFT))
    891 		 */
    892 		return (offset >> (dn->dn_datablkshift + level *
    893 		    (dn->dn_indblkshift - SPA_BLKPTRSHIFT)));
    894 	} else {
    895 		ASSERT3U(offset, <, dn->dn_datablksz);
    896 		return (0);
    897 	}
    898 }
    899 
    900 static void
    901 dbuf_read_done(zio_t *zio, arc_buf_t *buf, void *vdb)
    902 {
    903 	dmu_buf_impl_t *db = vdb;
    904 
    905 	mutex_enter(&db->db_mtx);
    906 	ASSERT3U(db->db_state, ==, DB_READ);
    907 	/*
    908 	 * All reads are synchronous, so we must have a hold on the dbuf
    909 	 */
    910 	ASSERT(refcount_count(&db->db_holds) > 0);
    911 	ASSERT(db->db_buf == NULL);
    912 	ASSERT(db->db.db_data == NULL);
    913 	if (db->db_level == 0 && db->db_freed_in_flight) {
    914 		/* we were freed in flight; disregard any error */
    915 		arc_release(buf, db);
    916 		bzero(buf->b_data, db->db.db_size);
    917 		arc_buf_freeze(buf);
    918 		db->db_freed_in_flight = FALSE;
    919 		dbuf_set_data(db, buf);
    920 		db->db_state = DB_CACHED;
    921 	} else if (zio == NULL || zio->io_error == 0) {
    922 		dbuf_set_data(db, buf);
    923 		db->db_state = DB_CACHED;
    924 	} else {
    925 		ASSERT(db->db_blkid != DMU_BONUS_BLKID);
    926 		ASSERT3P(db->db_buf, ==, NULL);
    927 		arc_buf_destroy(buf, db);
    928 		db->db_state = DB_UNCACHED;
    929 	}
    930 	cv_broadcast(&db->db_changed);
    931 	dbuf_rele_and_unlock(db, NULL);
    932 }
    933 
    934 static void
    935 dbuf_read_impl(dmu_buf_impl_t *db, zio_t *zio, uint32_t flags)
    936 {
    937 	dnode_t *dn;
    938 	zbookmark_phys_t zb;
    939 	arc_flags_t aflags = ARC_FLAG_NOWAIT;
    940 
    941 	DB_DNODE_ENTER(db);
    942 	dn = DB_DNODE(db);
    943 	ASSERT(!refcount_is_zero(&db->db_holds));
    944 	/* We need the struct_rwlock to prevent db_blkptr from changing. */
    945 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
    946 	ASSERT(MUTEX_HELD(&db->db_mtx));
    947 	ASSERT(db->db_state == DB_UNCACHED);
    948 	ASSERT(db->db_buf == NULL);
    949 
    950 	if (db->db_blkid == DMU_BONUS_BLKID) {
    951 		int bonuslen = MIN(dn->dn_bonuslen, dn->dn_phys->dn_bonuslen);
    952 
    953 		ASSERT3U(bonuslen, <=, db->db.db_size);
    954 		db->db.db_data = zio_buf_alloc(DN_MAX_BONUSLEN);
    955 		arc_space_consume(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
    956 		if (bonuslen < DN_MAX_BONUSLEN)
    957 			bzero(db->db.db_data, DN_MAX_BONUSLEN);
    958 		if (bonuslen)
    959 			bcopy(DN_BONUS(dn->dn_phys), db->db.db_data, bonuslen);
    960 		DB_DNODE_EXIT(db);
    961 		db->db_state = DB_CACHED;
    962 		mutex_exit(&db->db_mtx);
    963 		return;
    964 	}
    965 
    966 	/*
    967 	 * Recheck BP_IS_HOLE() after dnode_block_freed() in case dnode_sync()
    968 	 * processes the delete record and clears the bp while we are waiting
    969 	 * for the dn_mtx (resulting in a "no" from block_freed).
    970 	 */
    971 	if (db->db_blkptr == NULL || BP_IS_HOLE(db->db_blkptr) ||
    972 	    (db->db_level == 0 && (dnode_block_freed(dn, db->db_blkid) ||
    973 	    BP_IS_HOLE(db->db_blkptr)))) {
    974 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
    975 
    976 		dbuf_set_data(db, arc_alloc_buf(db->db_objset->os_spa,
    977 		    db->db.db_size, db, type));
    978 		bzero(db->db.db_data, db->db.db_size);
    979 
    980 		if (db->db_blkptr != NULL && db->db_level > 0 &&
    981 		    BP_IS_HOLE(db->db_blkptr) &&
    982 		    db->db_blkptr->blk_birth != 0) {
    983 			blkptr_t *bps = db->db.db_data;
    984 			for (int i = 0; i < ((1 <<
    985 			    DB_DNODE(db)->dn_indblkshift) / sizeof (blkptr_t));
    986 			    i++) {
    987 				blkptr_t *bp = &bps[i];
    988 				ASSERT3U(BP_GET_LSIZE(db->db_blkptr), ==,
    989 				    1 << dn->dn_indblkshift);
    990 				BP_SET_LSIZE(bp,
    991 				    BP_GET_LEVEL(db->db_blkptr) == 1 ?
    992 				    dn->dn_datablksz :
    993 				    BP_GET_LSIZE(db->db_blkptr));
    994 				BP_SET_TYPE(bp, BP_GET_TYPE(db->db_blkptr));
    995 				BP_SET_LEVEL(bp,
    996 				    BP_GET_LEVEL(db->db_blkptr) - 1);
    997 				BP_SET_BIRTH(bp, db->db_blkptr->blk_birth, 0);
    998 			}
    999 		}
   1000 		DB_DNODE_EXIT(db);
   1001 		db->db_state = DB_CACHED;
   1002 		mutex_exit(&db->db_mtx);
   1003 		return;
   1004 	}
   1005 
   1006 	DB_DNODE_EXIT(db);
   1007 
   1008 	db->db_state = DB_READ;
   1009 	mutex_exit(&db->db_mtx);
   1010 
   1011 	if (DBUF_IS_L2CACHEABLE(db))
   1012 		aflags |= ARC_FLAG_L2CACHE;
   1013 
   1014 	SET_BOOKMARK(&zb, db->db_objset->os_dsl_dataset ?
   1015 	    db->db_objset->os_dsl_dataset->ds_object : DMU_META_OBJSET,
   1016 	    db->db.db_object, db->db_level, db->db_blkid);
   1017 
   1018 	dbuf_add_ref(db, NULL);
   1019 
   1020 	(void) arc_read(zio, db->db_objset->os_spa, db->db_blkptr,
   1021 	    dbuf_read_done, db, ZIO_PRIORITY_SYNC_READ,
   1022 	    (flags & DB_RF_CANFAIL) ? ZIO_FLAG_CANFAIL : ZIO_FLAG_MUSTSUCCEED,
   1023 	    &aflags, &zb);
   1024 }
   1025 
   1026 int
   1027 dbuf_read(dmu_buf_impl_t *db, zio_t *zio, uint32_t flags)
   1028 {
   1029 	int err = 0;
   1030 	boolean_t havepzio = (zio != NULL);
   1031 	boolean_t prefetch;
   1032 	dnode_t *dn;
   1033 
   1034 	/*
   1035 	 * We don't have to hold the mutex to check db_state because it
   1036 	 * can't be freed while we have a hold on the buffer.
   1037 	 */
   1038 	ASSERT(!refcount_is_zero(&db->db_holds));
   1039 
   1040 	if (db->db_state == DB_NOFILL)
   1041 		return (SET_ERROR(EIO));
   1042 
   1043 	DB_DNODE_ENTER(db);
   1044 	dn = DB_DNODE(db);
   1045 	if ((flags & DB_RF_HAVESTRUCT) == 0)
   1046 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
   1047 
   1048 	prefetch = db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
   1049 	    (flags & DB_RF_NOPREFETCH) == 0 && dn != NULL &&
   1050 	    DBUF_IS_CACHEABLE(db);
   1051 
   1052 	mutex_enter(&db->db_mtx);
   1053 	if (db->db_state == DB_CACHED) {
   1054 		mutex_exit(&db->db_mtx);
   1055 		if (prefetch)
   1056 			dmu_zfetch(&dn->dn_zfetch, db->db_blkid, 1, B_TRUE);
   1057 		if ((flags & DB_RF_HAVESTRUCT) == 0)
   1058 			rw_exit(&dn->dn_struct_rwlock);
   1059 		DB_DNODE_EXIT(db);
   1060 	} else if (db->db_state == DB_UNCACHED) {
   1061 		spa_t *spa = dn->dn_objset->os_spa;
   1062 
   1063 		if (zio == NULL)
   1064 			zio = zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL);
   1065 		dbuf_read_impl(db, zio, flags);
   1066 
   1067 		/* dbuf_read_impl has dropped db_mtx for us */
   1068 
   1069 		if (prefetch)
   1070 			dmu_zfetch(&dn->dn_zfetch, db->db_blkid, 1, B_TRUE);
   1071 
   1072 		if ((flags & DB_RF_HAVESTRUCT) == 0)
   1073 			rw_exit(&dn->dn_struct_rwlock);
   1074 		DB_DNODE_EXIT(db);
   1075 
   1076 		if (!havepzio)
   1077 			err = zio_wait(zio);
   1078 	} else {
   1079 		/*
   1080 		 * Another reader came in while the dbuf was in flight
   1081 		 * between UNCACHED and CACHED.  Either a writer will finish
   1082 		 * writing the buffer (sending the dbuf to CACHED) or the
   1083 		 * first reader's request will reach the read_done callback
   1084 		 * and send the dbuf to CACHED.  Otherwise, a failure
   1085 		 * occurred and the dbuf went to UNCACHED.
   1086 		 */
   1087 		mutex_exit(&db->db_mtx);
   1088 		if (prefetch)
   1089 			dmu_zfetch(&dn->dn_zfetch, db->db_blkid, 1, B_TRUE);
   1090 		if ((flags & DB_RF_HAVESTRUCT) == 0)
   1091 			rw_exit(&dn->dn_struct_rwlock);
   1092 		DB_DNODE_EXIT(db);
   1093 
   1094 		/* Skip the wait per the caller's request. */
   1095 		mutex_enter(&db->db_mtx);
   1096 		if ((flags & DB_RF_NEVERWAIT) == 0) {
   1097 			while (db->db_state == DB_READ ||
   1098 			    db->db_state == DB_FILL) {
   1099 				ASSERT(db->db_state == DB_READ ||
   1100 				    (flags & DB_RF_HAVESTRUCT) == 0);
   1101 				DTRACE_PROBE2(blocked__read, dmu_buf_impl_t *,
   1102 				    db, zio_t *, zio);
   1103 				cv_wait(&db->db_changed, &db->db_mtx);
   1104 			}
   1105 			if (db->db_state == DB_UNCACHED)
   1106 				err = SET_ERROR(EIO);
   1107 		}
   1108 		mutex_exit(&db->db_mtx);
   1109 	}
   1110 
   1111 	ASSERT(err || havepzio || db->db_state == DB_CACHED);
   1112 	return (err);
   1113 }
   1114 
   1115 static void
   1116 dbuf_noread(dmu_buf_impl_t *db)
   1117 {
   1118 	ASSERT(!refcount_is_zero(&db->db_holds));
   1119 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
   1120 	mutex_enter(&db->db_mtx);
   1121 	while (db->db_state == DB_READ || db->db_state == DB_FILL)
   1122 		cv_wait(&db->db_changed, &db->db_mtx);
   1123 	if (db->db_state == DB_UNCACHED) {
   1124 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
   1125 		spa_t *spa = db->db_objset->os_spa;
   1126 
   1127 		ASSERT(db->db_buf == NULL);
   1128 		ASSERT(db->db.db_data == NULL);
   1129 		dbuf_set_data(db, arc_alloc_buf(spa, db->db.db_size, db, type));
   1130 		db->db_state = DB_FILL;
   1131 	} else if (db->db_state == DB_NOFILL) {
   1132 		dbuf_clear_data(db);
   1133 	} else {
   1134 		ASSERT3U(db->db_state, ==, DB_CACHED);
   1135 	}
   1136 	mutex_exit(&db->db_mtx);
   1137 }
   1138 
   1139 /*
   1140  * This is our just-in-time copy function.  It makes a copy of
   1141  * buffers, that have been modified in a previous transaction
   1142  * group, before we modify them in the current active group.
   1143  *
   1144  * This function is used in two places: when we are dirtying a
   1145  * buffer for the first time in a txg, and when we are freeing
   1146  * a range in a dnode that includes this buffer.
   1147  *
   1148  * Note that when we are called from dbuf_free_range() we do
   1149  * not put a hold on the buffer, we just traverse the active
   1150  * dbuf list for the dnode.
   1151  */
   1152 static void
   1153 dbuf_fix_old_data(dmu_buf_impl_t *db, uint64_t txg)
   1154 {
   1155 	dbuf_dirty_record_t *dr = db->db_last_dirty;
   1156 
   1157 	ASSERT(MUTEX_HELD(&db->db_mtx));
   1158 	ASSERT(db->db.db_data != NULL);
   1159 	ASSERT(db->db_level == 0);
   1160 	ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT);
   1161 
   1162 	if (dr == NULL ||
   1163 	    (dr->dt.dl.dr_data !=
   1164 	    ((db->db_blkid  == DMU_BONUS_BLKID) ? db->db.db_data : db->db_buf)))
   1165 		return;
   1166 
   1167 	/*
   1168 	 * If the last dirty record for this dbuf has not yet synced
   1169 	 * and its referencing the dbuf data, either:
   1170 	 *	reset the reference to point to a new copy,
   1171 	 * or (if there a no active holders)
   1172 	 *	just null out the current db_data pointer.
   1173 	 */
   1174 	ASSERT(dr->dr_txg >= txg - 2);
   1175 	if (db->db_blkid == DMU_BONUS_BLKID) {
   1176 		/* Note that the data bufs here are zio_bufs */
   1177 		dr->dt.dl.dr_data = zio_buf_alloc(DN_MAX_BONUSLEN);
   1178 		arc_space_consume(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
   1179 		bcopy(db->db.db_data, dr->dt.dl.dr_data, DN_MAX_BONUSLEN);
   1180 	} else if (refcount_count(&db->db_holds) > db->db_dirtycnt) {
   1181 		int size = db->db.db_size;
   1182 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
   1183 		spa_t *spa = db->db_objset->os_spa;
   1184 
   1185 		dr->dt.dl.dr_data = arc_alloc_buf(spa, size, db, type);
   1186 		bcopy(db->db.db_data, dr->dt.dl.dr_data->b_data, size);
   1187 	} else {
   1188 		db->db_buf = NULL;
   1189 		dbuf_clear_data(db);
   1190 	}
   1191 }
   1192 
   1193 void
   1194 dbuf_unoverride(dbuf_dirty_record_t *dr)
   1195 {
   1196 	dmu_buf_impl_t *db = dr->dr_dbuf;
   1197 	blkptr_t *bp = &dr->dt.dl.dr_overridden_by;
   1198 	uint64_t txg = dr->dr_txg;
   1199 
   1200 	ASSERT(MUTEX_HELD(&db->db_mtx));
   1201 	ASSERT(dr->dt.dl.dr_override_state != DR_IN_DMU_SYNC);
   1202 	ASSERT(db->db_level == 0);
   1203 
   1204 	if (db->db_blkid == DMU_BONUS_BLKID ||
   1205 	    dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN)
   1206 		return;
   1207 
   1208 	ASSERT(db->db_data_pending != dr);
   1209 
   1210 	/* free this block */
   1211 	if (!BP_IS_HOLE(bp) && !dr->dt.dl.dr_nopwrite)
   1212 		zio_free(db->db_objset->os_spa, txg, bp);
   1213 
   1214 	dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
   1215 	dr->dt.dl.dr_nopwrite = B_FALSE;
   1216 
   1217 	/*
   1218 	 * Release the already-written buffer, so we leave it in
   1219 	 * a consistent dirty state.  Note that all callers are
   1220 	 * modifying the buffer, so they will immediately do
   1221 	 * another (redundant) arc_release().  Therefore, leave
   1222 	 * the buf thawed to save the effort of freezing &
   1223 	 * immediately re-thawing it.
   1224 	 */
   1225 	arc_release(dr->dt.dl.dr_data, db);
   1226 }
   1227 
   1228 /*
   1229  * Evict (if its unreferenced) or clear (if its referenced) any level-0
   1230  * data blocks in the free range, so that any future readers will find
   1231  * empty blocks.
   1232  */
   1233 void
   1234 dbuf_free_range(dnode_t *dn, uint64_t start_blkid, uint64_t end_blkid,
   1235     dmu_tx_t *tx)
   1236 {
   1237 	dmu_buf_impl_t db_search;
   1238 	dmu_buf_impl_t *db, *db_next;
   1239 	uint64_t txg = tx->tx_txg;
   1240 	avl_index_t where;
   1241 
   1242 	if (end_blkid > dn->dn_maxblkid &&
   1243 	    !(start_blkid == DMU_SPILL_BLKID || end_blkid == DMU_SPILL_BLKID))
   1244 		end_blkid = dn->dn_maxblkid;
   1245 	dprintf_dnode(dn, "start=%llu end=%llu\n", start_blkid, end_blkid);
   1246 
   1247 	db_search.db_level = 0;
   1248 	db_search.db_blkid = start_blkid;
   1249 	db_search.db_state = DB_SEARCH;
   1250 
   1251 	mutex_enter(&dn->dn_dbufs_mtx);
   1252 	db = avl_find(&dn->dn_dbufs, &db_search, &where);
   1253 	ASSERT3P(db, ==, NULL);
   1254 
   1255 	db = avl_nearest(&dn->dn_dbufs, where, AVL_AFTER);
   1256 
   1257 	for (; db != NULL; db = db_next) {
   1258 		db_next = AVL_NEXT(&dn->dn_dbufs, db);
   1259 		ASSERT(db->db_blkid != DMU_BONUS_BLKID);
   1260 
   1261 		if (db->db_level != 0 || db->db_blkid > end_blkid) {
   1262 			break;
   1263 		}
   1264 		ASSERT3U(db->db_blkid, >=, start_blkid);
   1265 
   1266 		/* found a level 0 buffer in the range */
   1267 		mutex_enter(&db->db_mtx);
   1268 		if (dbuf_undirty(db, tx)) {
   1269 			/* mutex has been dropped and dbuf destroyed */
   1270 			continue;
   1271 		}
   1272 
   1273 		if (db->db_state == DB_UNCACHED ||
   1274 		    db->db_state == DB_NOFILL ||
   1275 		    db->db_state == DB_EVICTING) {
   1276 			ASSERT(db->db.db_data == NULL);
   1277 			mutex_exit(&db->db_mtx);
   1278 			continue;
   1279 		}
   1280 		if (db->db_state == DB_READ || db->db_state == DB_FILL) {
   1281 			/* will be handled in dbuf_read_done or dbuf_rele */
   1282 			db->db_freed_in_flight = TRUE;
   1283 			mutex_exit(&db->db_mtx);
   1284 			continue;
   1285 		}
   1286 		if (refcount_count(&db->db_holds) == 0) {
   1287 			ASSERT(db->db_buf);
   1288 			dbuf_destroy(db);
   1289 			continue;
   1290 		}
   1291 		/* The dbuf is referenced */
   1292 
   1293 		if (db->db_last_dirty != NULL) {
   1294 			dbuf_dirty_record_t *dr = db->db_last_dirty;
   1295 
   1296 			if (dr->dr_txg == txg) {
   1297 				/*
   1298 				 * This buffer is "in-use", re-adjust the file
   1299 				 * size to reflect that this buffer may
   1300 				 * contain new data when we sync.
   1301 				 */
   1302 				if (db->db_blkid != DMU_SPILL_BLKID &&
   1303 				    db->db_blkid > dn->dn_maxblkid)
   1304 					dn->dn_maxblkid = db->db_blkid;
   1305 				dbuf_unoverride(dr);
   1306 			} else {
   1307 				/*
   1308 				 * This dbuf is not dirty in the open context.
   1309 				 * Either uncache it (if its not referenced in
   1310 				 * the open context) or reset its contents to
   1311 				 * empty.
   1312 				 */
   1313 				dbuf_fix_old_data(db, txg);
   1314 			}
   1315 		}
   1316 		/* clear the contents if its cached */
   1317 		if (db->db_state == DB_CACHED) {
   1318 			ASSERT(db->db.db_data != NULL);
   1319 			arc_release(db->db_buf, db);
   1320 			bzero(db->db.db_data, db->db.db_size);
   1321 			arc_buf_freeze(db->db_buf);
   1322 		}
   1323 
   1324 		mutex_exit(&db->db_mtx);
   1325 	}
   1326 	mutex_exit(&dn->dn_dbufs_mtx);
   1327 }
   1328 
   1329 static int
   1330 dbuf_block_freeable(dmu_buf_impl_t *db)
   1331 {
   1332 	dsl_dataset_t *ds = db->db_objset->os_dsl_dataset;
   1333 	uint64_t birth_txg = 0;
   1334 
   1335 	/*
   1336 	 * We don't need any locking to protect db_blkptr:
   1337 	 * If it's syncing, then db_last_dirty will be set
   1338 	 * so we'll ignore db_blkptr.
   1339 	 *
   1340 	 * This logic ensures that only block births for
   1341 	 * filled blocks are considered.
   1342 	 */
   1343 	ASSERT(MUTEX_HELD(&db->db_mtx));
   1344 	if (db->db_last_dirty && (db->db_blkptr == NULL ||
   1345 	    !BP_IS_HOLE(db->db_blkptr))) {
   1346 		birth_txg = db->db_last_dirty->dr_txg;
   1347 	} else if (db->db_blkptr != NULL && !BP_IS_HOLE(db->db_blkptr)) {
   1348 		birth_txg = db->db_blkptr->blk_birth;
   1349 	}
   1350 
   1351 	/*
   1352 	 * If this block don't exist or is in a snapshot, it can't be freed.
   1353 	 * Don't pass the bp to dsl_dataset_block_freeable() since we
   1354 	 * are holding the db_mtx lock and might deadlock if we are
   1355 	 * prefetching a dedup-ed block.
   1356 	 */
   1357 	if (birth_txg != 0)
   1358 		return (ds == NULL ||
   1359 		    dsl_dataset_block_freeable(ds, NULL, birth_txg));
   1360 	else
   1361 		return (B_FALSE);
   1362 }
   1363 
   1364 void
   1365 dbuf_new_size(dmu_buf_impl_t *db, int size, dmu_tx_t *tx)
   1366 {
   1367 	arc_buf_t *buf, *obuf;
   1368 	int osize = db->db.db_size;
   1369 	arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
   1370 	dnode_t *dn;
   1371 
   1372 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
   1373 
   1374 	DB_DNODE_ENTER(db);
   1375 	dn = DB_DNODE(db);
   1376 
   1377 	/* XXX does *this* func really need the lock? */
   1378 	ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
   1379 
   1380 	/*
   1381 	 * This call to dmu_buf_will_dirty() with the dn_struct_rwlock held
   1382 	 * is OK, because there can be no other references to the db
   1383 	 * when we are changing its size, so no concurrent DB_FILL can
   1384 	 * be happening.
   1385 	 */
   1386 	/*
   1387 	 * XXX we should be doing a dbuf_read, checking the return
   1388 	 * value and returning that up to our callers
   1389 	 */
   1390 	dmu_buf_will_dirty(&db->db, tx);
   1391 
   1392 	/* create the data buffer for the new block */
   1393 	buf = arc_alloc_buf(dn->dn_objset->os_spa, size, db, type);
   1394 
   1395 	/* copy old block data to the new block */
   1396 	obuf = db->db_buf;
   1397 	bcopy(obuf->b_data, buf->b_data, MIN(osize, size));
   1398 	/* zero the remainder */
   1399 	if (size > osize)
   1400 		bzero((uint8_t *)buf->b_data + osize, size - osize);
   1401 
   1402 	mutex_enter(&db->db_mtx);
   1403 	dbuf_set_data(db, buf);
   1404 	arc_buf_destroy(obuf, db);
   1405 	db->db.db_size = size;
   1406 
   1407 	if (db->db_level == 0) {
   1408 		ASSERT3U(db->db_last_dirty->dr_txg, ==, tx->tx_txg);
   1409 		db->db_last_dirty->dt.dl.dr_data = buf;
   1410 	}
   1411 	mutex_exit(&db->db_mtx);
   1412 
   1413 	dnode_willuse_space(dn, size-osize, tx);
   1414 	DB_DNODE_EXIT(db);
   1415 }
   1416 
   1417 void
   1418 dbuf_release_bp(dmu_buf_impl_t *db)
   1419 {
   1420 	objset_t *os = db->db_objset;
   1421 
   1422 	ASSERT(dsl_pool_sync_context(dmu_objset_pool(os)));
   1423 	ASSERT(arc_released(os->os_phys_buf) ||
   1424 	    list_link_active(&os->os_dsl_dataset->ds_synced_link));
   1425 	ASSERT(db->db_parent == NULL || arc_released(db->db_parent->db_buf));
   1426 
   1427 	(void) arc_release(db->db_buf, db);
   1428 }
   1429 
   1430 /*
   1431  * We already have a dirty record for this TXG, and we are being
   1432  * dirtied again.
   1433  */
   1434 static void
   1435 dbuf_redirty(dbuf_dirty_record_t *dr)
   1436 {
   1437 	dmu_buf_impl_t *db = dr->dr_dbuf;
   1438 
   1439 	ASSERT(MUTEX_HELD(&db->db_mtx));
   1440 
   1441 	if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID) {
   1442 		/*
   1443 		 * If this buffer has already been written out,
   1444 		 * we now need to reset its state.
   1445 		 */
   1446 		dbuf_unoverride(dr);
   1447 		if (db->db.db_object != DMU_META_DNODE_OBJECT &&
   1448 		    db->db_state != DB_NOFILL) {
   1449 			/* Already released on initial dirty, so just thaw. */
   1450 			ASSERT(arc_released(db->db_buf));
   1451 			arc_buf_thaw(db->db_buf);
   1452 		}
   1453 	}
   1454 }
   1455 
   1456 dbuf_dirty_record_t *
   1457 dbuf_dirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
   1458 {
   1459 	dnode_t *dn;
   1460 	objset_t *os;
   1461 	dbuf_dirty_record_t **drp, *dr;
   1462 	int drop_struct_lock = FALSE;
   1463 	boolean_t do_free_accounting = B_FALSE;
   1464 	int txgoff = tx->tx_txg & TXG_MASK;
   1465 
   1466 	ASSERT(tx->tx_txg != 0);
   1467 	ASSERT(!refcount_is_zero(&db->db_holds));
   1468 	DMU_TX_DIRTY_BUF(tx, db);
   1469 
   1470 	DB_DNODE_ENTER(db);
   1471 	dn = DB_DNODE(db);
   1472 	/*
   1473 	 * Shouldn't dirty a regular buffer in syncing context.  Private
   1474 	 * objects may be dirtied in syncing context, but only if they
   1475 	 * were already pre-dirtied in open context.
   1476 	 */
   1477 #ifdef DEBUG
   1478 	if (dn->dn_objset->os_dsl_dataset != NULL) {
   1479 		rrw_enter(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock,
   1480 		    RW_READER, FTAG);
   1481 	}
   1482 	ASSERT(!dmu_tx_is_syncing(tx) ||
   1483 	    BP_IS_HOLE(dn->dn_objset->os_rootbp) ||
   1484 	    DMU_OBJECT_IS_SPECIAL(dn->dn_object) ||
   1485 	    dn->dn_objset->os_dsl_dataset == NULL);
   1486 	if (dn->dn_objset->os_dsl_dataset != NULL)
   1487 		rrw_exit(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock, FTAG);
   1488 #endif
   1489 	/*
   1490 	 * We make this assert for private objects as well, but after we
   1491 	 * check if we're already dirty.  They are allowed to re-dirty
   1492 	 * in syncing context.
   1493 	 */
   1494 	ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
   1495 	    dn->dn_dirtyctx == DN_UNDIRTIED || dn->dn_dirtyctx ==
   1496 	    (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN));
   1497 
   1498 	mutex_enter(&db->db_mtx);
   1499 	/*
   1500 	 * XXX make this true for indirects too?  The problem is that
   1501 	 * transactions created with dmu_tx_create_assigned() from
   1502 	 * syncing context don't bother holding ahead.
   1503 	 */
   1504 	ASSERT(db->db_level != 0 ||
   1505 	    db->db_state == DB_CACHED || db->db_state == DB_FILL ||
   1506 	    db->db_state == DB_NOFILL);
   1507 
   1508 	mutex_enter(&dn->dn_mtx);
   1509 	/*
   1510 	 * Don't set dirtyctx to SYNC if we're just modifying this as we
   1511 	 * initialize the objset.
   1512 	 */
   1513 	if (dn->dn_dirtyctx == DN_UNDIRTIED) {
   1514 		if (dn->dn_objset->os_dsl_dataset != NULL) {
   1515 			rrw_enter(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock,
   1516 			    RW_READER, FTAG);
   1517 		}
   1518 		if (!BP_IS_HOLE(dn->dn_objset->os_rootbp)) {
   1519 			dn->dn_dirtyctx = (dmu_tx_is_syncing(tx) ?
   1520 			    DN_DIRTY_SYNC : DN_DIRTY_OPEN);
   1521 			ASSERT(dn->dn_dirtyctx_firstset == NULL);
   1522 			dn->dn_dirtyctx_firstset = kmem_alloc(1, KM_SLEEP);
   1523 		}
   1524 		if (dn->dn_objset->os_dsl_dataset != NULL) {
   1525 			rrw_exit(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock,
   1526 			    FTAG);
   1527 		}
   1528 	}
   1529 	mutex_exit(&dn->dn_mtx);
   1530 
   1531 	if (db->db_blkid == DMU_SPILL_BLKID)
   1532 		dn->dn_have_spill = B_TRUE;
   1533 
   1534 	/*
   1535 	 * If this buffer is already dirty, we're done.
   1536 	 */
   1537 	drp = &db->db_last_dirty;
   1538 	ASSERT(*drp == NULL || (*drp)->dr_txg <= tx->tx_txg ||
   1539 	    db->db.db_object == DMU_META_DNODE_OBJECT);
   1540 	while ((dr = *drp) != NULL && dr->dr_txg > tx->tx_txg)
   1541 		drp = &dr->dr_next;
   1542 	if (dr && dr->dr_txg == tx->tx_txg) {
   1543 		DB_DNODE_EXIT(db);
   1544 
   1545 		dbuf_redirty(dr);
   1546 		mutex_exit(&db->db_mtx);
   1547 		return (dr);
   1548 	}
   1549 
   1550 	/*
   1551 	 * Only valid if not already dirty.
   1552 	 */
   1553 	ASSERT(dn->dn_object == 0 ||
   1554 	    dn->dn_dirtyctx == DN_UNDIRTIED || dn->dn_dirtyctx ==
   1555 	    (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN));
   1556 
   1557 	ASSERT3U(dn->dn_nlevels, >, db->db_level);
   1558 	ASSERT((dn->dn_phys->dn_nlevels == 0 && db->db_level == 0) ||
   1559 	    dn->dn_phys->dn_nlevels > db->db_level ||
   1560 	    dn->dn_next_nlevels[txgoff] > db->db_level ||
   1561 	    dn->dn_next_nlevels[(tx->tx_txg-1) & TXG_MASK] > db->db_level ||
   1562 	    dn->dn_next_nlevels[(tx->tx_txg-2) & TXG_MASK] > db->db_level);
   1563 
   1564 	/*
   1565 	 * We should only be dirtying in syncing context if it's the
   1566 	 * mos or we're initializing the os or it's a special object.
   1567 	 * However, we are allowed to dirty in syncing context provided
   1568 	 * we already dirtied it in open context.  Hence we must make
   1569 	 * this assertion only if we're not already dirty.
   1570 	 */
   1571 	os = dn->dn_objset;
   1572 #ifdef DEBUG
   1573 	if (dn->dn_objset->os_dsl_dataset != NULL)
   1574 		rrw_enter(&os->os_dsl_dataset->ds_bp_rwlock, RW_READER, FTAG);
   1575 	ASSERT(!dmu_tx_is_syncing(tx) || DMU_OBJECT_IS_SPECIAL(dn->dn_object) ||
   1576 	    os->os_dsl_dataset == NULL || BP_IS_HOLE(os->os_rootbp));
   1577 	if (dn->dn_objset->os_dsl_dataset != NULL)
   1578 		rrw_exit(&os->os_dsl_dataset->ds_bp_rwlock, FTAG);
   1579 #endif
   1580 	ASSERT(db->db.db_size != 0);
   1581 
   1582 	dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
   1583 
   1584 	if (db->db_blkid != DMU_BONUS_BLKID) {
   1585 		/*
   1586 		 * Update the accounting.
   1587 		 * Note: we delay "free accounting" until after we drop
   1588 		 * the db_mtx.  This keeps us from grabbing other locks
   1589 		 * (and possibly deadlocking) in bp_get_dsize() while
   1590 		 * also holding the db_mtx.
   1591 		 */
   1592 		dnode_willuse_space(dn, db->db.db_size, tx);
   1593 		do_free_accounting = dbuf_block_freeable(db);
   1594 	}
   1595 
   1596 	/*
   1597 	 * If this buffer is dirty in an old transaction group we need
   1598 	 * to make a copy of it so that the changes we make in this
   1599 	 * transaction group won't leak out when we sync the older txg.
   1600 	 */
   1601 	dr = kmem_zalloc(sizeof (dbuf_dirty_record_t), KM_SLEEP);
   1602 	if (db->db_level == 0) {
   1603 		void *data_old = db->db_buf;
   1604 
   1605 		if (db->db_state != DB_NOFILL) {
   1606 			if (db->db_blkid == DMU_BONUS_BLKID) {
   1607 				dbuf_fix_old_data(db, tx->tx_txg);
   1608 				data_old = db->db.db_data;
   1609 			} else if (db->db.db_object != DMU_META_DNODE_OBJECT) {
   1610 				/*
   1611 				 * Release the data buffer from the cache so
   1612 				 * that we can modify it without impacting
   1613 				 * possible other users of this cached data
   1614 				 * block.  Note that indirect blocks and
   1615 				 * private objects are not released until the
   1616 				 * syncing state (since they are only modified
   1617 				 * then).
   1618 				 */
   1619 				arc_release(db->db_buf, db);
   1620 				dbuf_fix_old_data(db, tx->tx_txg);
   1621 				data_old = db->db_buf;
   1622 			}
   1623 			ASSERT(data_old != NULL);
   1624 		}
   1625 		dr->dt.dl.dr_data = data_old;
   1626 	} else {
   1627 		mutex_init(&dr->dt.di.dr_mtx, NULL, MUTEX_DEFAULT, NULL);
   1628 		list_create(&dr->dt.di.dr_children,
   1629 		    sizeof (dbuf_dirty_record_t),
   1630 		    offsetof(dbuf_dirty_record_t, dr_dirty_node));
   1631 	}
   1632 	if (db->db_blkid != DMU_BONUS_BLKID && os->os_dsl_dataset != NULL)
   1633 		dr->dr_accounted = db->db.db_size;
   1634 	dr->dr_dbuf = db;
   1635 	dr->dr_txg = tx->tx_txg;
   1636 	dr->dr_next = *drp;
   1637 	*drp = dr;
   1638 
   1639 	/*
   1640 	 * We could have been freed_in_flight between the dbuf_noread
   1641 	 * and dbuf_dirty.  We win, as though the dbuf_noread() had
   1642 	 * happened after the free.
   1643 	 */
   1644 	if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
   1645 	    db->db_blkid != DMU_SPILL_BLKID) {
   1646 		mutex_enter(&dn->dn_mtx);
   1647 		if (dn->dn_free_ranges[txgoff] != NULL) {
   1648 			range_tree_clear(dn->dn_free_ranges[txgoff],
   1649 			    db->db_blkid, 1);
   1650 		}
   1651 		mutex_exit(&dn->dn_mtx);
   1652 		db->db_freed_in_flight = FALSE;
   1653 	}
   1654 
   1655 	/*
   1656 	 * This buffer is now part of this txg
   1657 	 */
   1658 	dbuf_add_ref(db, (void *)(uintptr_t)tx->tx_txg);
   1659 	db->db_dirtycnt += 1;
   1660 	ASSERT3U(db->db_dirtycnt, <=, 3);
   1661 
   1662 	mutex_exit(&db->db_mtx);
   1663 
   1664 	if (db->db_blkid == DMU_BONUS_BLKID ||
   1665 	    db->db_blkid == DMU_SPILL_BLKID) {
   1666 		mutex_enter(&dn->dn_mtx);
   1667 		ASSERT(!list_link_active(&dr->dr_dirty_node));
   1668 		list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
   1669 		mutex_exit(&dn->dn_mtx);
   1670 		dnode_setdirty(dn, tx);
   1671 		DB_DNODE_EXIT(db);
   1672 		return (dr);
   1673 	}
   1674 
   1675 	/*
   1676 	 * The dn_struct_rwlock prevents db_blkptr from changing
   1677 	 * due to a write from syncing context completing
   1678 	 * while we are running, so we want to acquire it before
   1679 	 * looking at db_blkptr.
   1680 	 */
   1681 	if (!RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
   1682 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
   1683 		drop_struct_lock = TRUE;
   1684 	}
   1685 
   1686 	if (do_free_accounting) {
   1687 		blkptr_t *bp = db->db_blkptr;
   1688 		int64_t willfree = (bp && !BP_IS_HOLE(bp)) ?
   1689 		    bp_get_dsize(os->os_spa, bp) : db->db.db_size;
   1690 		/*
   1691 		 * This is only a guess -- if the dbuf is dirty
   1692 		 * in a previous txg, we don't know how much
   1693 		 * space it will use on disk yet.  We should
   1694 		 * really have the struct_rwlock to access
   1695 		 * db_blkptr, but since this is just a guess,
   1696 		 * it's OK if we get an odd answer.
   1697 		 */
   1698 		ddt_prefetch(os->os_spa, bp);
   1699 		dnode_willuse_space(dn, -willfree, tx);
   1700 	}
   1701 
   1702 	if (db->db_level == 0) {
   1703 		dnode_new_blkid(dn, db->db_blkid, tx, drop_struct_lock);
   1704 		ASSERT(dn->dn_maxblkid >= db->db_blkid);
   1705 	}
   1706 
   1707 	if (db->db_level+1 < dn->dn_nlevels) {
   1708 		dmu_buf_impl_t *parent = db->db_parent;
   1709 		dbuf_dirty_record_t *di;
   1710 		int parent_held = FALSE;
   1711 
   1712 		if (db->db_parent == NULL || db->db_parent == dn->dn_dbuf) {
   1713 			int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
   1714 
   1715 			parent = dbuf_hold_level(dn, db->db_level+1,
   1716 			    db->db_blkid >> epbs, FTAG);
   1717 			ASSERT(parent != NULL);
   1718 			parent_held = TRUE;
   1719 		}
   1720 		if (drop_struct_lock)
   1721 			rw_exit(&dn->dn_struct_rwlock);
   1722 		ASSERT3U(db->db_level+1, ==, parent->db_level);
   1723 		di = dbuf_dirty(parent, tx);
   1724 		if (parent_held)
   1725 			dbuf_rele(parent, FTAG);
   1726 
   1727 		mutex_enter(&db->db_mtx);
   1728 		/*
   1729 		 * Since we've dropped the mutex, it's possible that
   1730 		 * dbuf_undirty() might have changed this out from under us.
   1731 		 */
   1732 		if (db->db_last_dirty == dr ||
   1733 		    dn->dn_object == DMU_META_DNODE_OBJECT) {
   1734 			mutex_enter(&di->dt.di.dr_mtx);
   1735 			ASSERT3U(di->dr_txg, ==, tx->tx_txg);
   1736 			ASSERT(!list_link_active(&dr->dr_dirty_node));
   1737 			list_insert_tail(&di->dt.di.dr_children, dr);
   1738 			mutex_exit(&di->dt.di.dr_mtx);
   1739 			dr->dr_parent = di;
   1740 		}
   1741 		mutex_exit(&db->db_mtx);
   1742 	} else {
   1743 		ASSERT(db->db_level+1 == dn->dn_nlevels);
   1744 		ASSERT(db->db_blkid < dn->dn_nblkptr);
   1745 		ASSERT(db->db_parent == NULL || db->db_parent == dn->dn_dbuf);
   1746 		mutex_enter(&dn->dn_mtx);
   1747 		ASSERT(!list_link_active(&dr->dr_dirty_node));
   1748 		list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
   1749 		mutex_exit(&dn->dn_mtx);
   1750 		if (drop_struct_lock)
   1751 			rw_exit(&dn->dn_struct_rwlock);
   1752 	}
   1753 
   1754 	dnode_setdirty(dn, tx);
   1755 	DB_DNODE_EXIT(db);
   1756 	return (dr);
   1757 }
   1758 
   1759 /*
   1760  * Undirty a buffer in the transaction group referenced by the given
   1761  * transaction.  Return whether this evicted the dbuf.
   1762  */
   1763 static boolean_t
   1764 dbuf_undirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
   1765 {
   1766 	dnode_t *dn;
   1767 	uint64_t txg = tx->tx_txg;
   1768 	dbuf_dirty_record_t *dr, **drp;
   1769 
   1770 	ASSERT(txg != 0);
   1771 
   1772 	/*
   1773 	 * Due to our use of dn_nlevels below, this can only be called
   1774 	 * in open context, unless we are operating on the MOS.
   1775 	 * From syncing context, dn_nlevels may be different from the
   1776 	 * dn_nlevels used when dbuf was dirtied.
   1777 	 */
   1778 	ASSERT(db->db_objset ==
   1779 	    dmu_objset_pool(db->db_objset)->dp_meta_objset ||
   1780 	    txg != spa_syncing_txg(dmu_objset_spa(db->db_objset)));
   1781 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
   1782 	ASSERT0(db->db_level);
   1783 	ASSERT(MUTEX_HELD(&db->db_mtx));
   1784 
   1785 	/*
   1786 	 * If this buffer is not dirty, we're done.
   1787 	 */
   1788 	for (drp = &db->db_last_dirty; (dr = *drp) != NULL; drp = &dr->dr_next)
   1789 		if (dr->dr_txg <= txg)
   1790 			break;
   1791 	if (dr == NULL || dr->dr_txg < txg)
   1792 		return (B_FALSE);
   1793 	ASSERT(dr->dr_txg == txg);
   1794 	ASSERT(dr->dr_dbuf == db);
   1795 
   1796 	DB_DNODE_ENTER(db);
   1797 	dn = DB_DNODE(db);
   1798 
   1799 	dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
   1800 
   1801 	ASSERT(db->db.db_size != 0);
   1802 
   1803 	dsl_pool_undirty_space(dmu_objset_pool(dn->dn_objset),
   1804 	    dr->dr_accounted, txg);
   1805 
   1806 	*drp = dr->dr_next;
   1807 
   1808 	/*
   1809 	 * Note that there are three places in dbuf_dirty()
   1810 	 * where this dirty record may be put on a list.
   1811 	 * Make sure to do a list_remove corresponding to
   1812 	 * every one of those list_insert calls.
   1813 	 */
   1814 	if (dr->dr_parent) {
   1815 		mutex_enter(&dr->dr_parent->dt.di.dr_mtx);
   1816 		list_remove(&dr->dr_parent->dt.di.dr_children, dr);
   1817 		mutex_exit(&dr->dr_parent->dt.di.dr_mtx);
   1818 	} else if (db->db_blkid == DMU_SPILL_BLKID ||
   1819 	    db->db_level + 1 == dn->dn_nlevels) {
   1820 		ASSERT(db->db_blkptr == NULL || db->db_parent == dn->dn_dbuf);
   1821 		mutex_enter(&dn->dn_mtx);
   1822 		list_remove(&dn->dn_dirty_records[txg & TXG_MASK], dr);
   1823 		mutex_exit(&dn->dn_mtx);
   1824 	}
   1825 	DB_DNODE_EXIT(db);
   1826 
   1827 	if (db->db_state != DB_NOFILL) {
   1828 		dbuf_unoverride(dr);
   1829 
   1830 		ASSERT(db->db_buf != NULL);
   1831 		ASSERT(dr->dt.dl.dr_data != NULL);
   1832 		if (dr->dt.dl.dr_data != db->db_buf)
   1833 			arc_buf_destroy(dr->dt.dl.dr_data, db);
   1834 	}
   1835 
   1836 	kmem_free(dr, sizeof (dbuf_dirty_record_t));
   1837 
   1838 	ASSERT(db->db_dirtycnt > 0);
   1839 	db->db_dirtycnt -= 1;
   1840 
   1841 	if (refcount_remove(&db->db_holds, (void *)(uintptr_t)txg) == 0) {
   1842 		ASSERT(db->db_state == DB_NOFILL || arc_released(db->db_buf));
   1843 		dbuf_destroy(db);
   1844 		return (B_TRUE);
   1845 	}
   1846 
   1847 	return (B_FALSE);
   1848 }
   1849 
   1850 void
   1851 dmu_buf_will_dirty(dmu_buf_t *db_fake, dmu_tx_t *tx)
   1852 {
   1853 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
   1854 	int rf = DB_RF_MUST_SUCCEED | DB_RF_NOPREFETCH;
   1855 
   1856 	ASSERT(tx->tx_txg != 0);
   1857 	ASSERT(!refcount_is_zero(&db->db_holds));
   1858 
   1859 	/*
   1860 	 * Quick check for dirtyness.  For already dirty blocks, this
   1861 	 * reduces runtime of this function by >90%, and overall performance
   1862 	 * by 50% for some workloads (e.g. file deletion with indirect blocks
   1863 	 * cached).
   1864 	 */
   1865 	mutex_enter(&db->db_mtx);
   1866 	dbuf_dirty_record_t *dr;
   1867 	for (dr = db->db_last_dirty;
   1868 	    dr != NULL && dr->dr_txg >= tx->tx_txg; dr = dr->dr_next) {
   1869 		/*
   1870 		 * It's possible that it is already dirty but not cached,
   1871 		 * because there are some calls to dbuf_dirty() that don't
   1872 		 * go through dmu_buf_will_dirty().
   1873 		 */
   1874 		if (dr->dr_txg == tx->tx_txg && db->db_state == DB_CACHED) {
   1875 			/* This dbuf is already dirty and cached. */
   1876 			dbuf_redirty(dr);
   1877 			mutex_exit(&db->db_mtx);
   1878 			return;
   1879 		}
   1880 	}
   1881 	mutex_exit(&db->db_mtx);
   1882 
   1883 	DB_DNODE_ENTER(db);
   1884 	if (RW_WRITE_HELD(&DB_DNODE(db)->dn_struct_rwlock))
   1885 		rf |= DB_RF_HAVESTRUCT;
   1886 	DB_DNODE_EXIT(db);
   1887 	(void) dbuf_read(db, NULL, rf);
   1888 	(void) dbuf_dirty(db, tx);
   1889 }
   1890 
   1891 void
   1892 dmu_buf_will_not_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
   1893 {
   1894 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
   1895 
   1896 	db->db_state = DB_NOFILL;
   1897 
   1898 	dmu_buf_will_fill(db_fake, tx);
   1899 }
   1900 
   1901 void
   1902 dmu_buf_will_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
   1903 {
   1904 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
   1905 
   1906 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
   1907 	ASSERT(tx->tx_txg != 0);
   1908 	ASSERT(db->db_level == 0);
   1909 	ASSERT(!refcount_is_zero(&db->db_holds));
   1910 
   1911 	ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT ||
   1912 	    dmu_tx_private_ok(tx));
   1913 
   1914 	dbuf_noread(db);
   1915 	(void) dbuf_dirty(db, tx);
   1916 }
   1917 
   1918 #pragma weak dmu_buf_fill_done = dbuf_fill_done
   1919 /* ARGSUSED */
   1920 void
   1921 dbuf_fill_done(dmu_buf_impl_t *db, dmu_tx_t *tx)
   1922 {
   1923 	mutex_enter(&db->db_mtx);
   1924 	DBUF_VERIFY(db);
   1925 
   1926 	if (db->db_state == DB_FILL) {
   1927 		if (db->db_level == 0 && db->db_freed_in_flight) {
   1928 			ASSERT(db->db_blkid != DMU_BONUS_BLKID);
   1929 			/* we were freed while filling */
   1930 			/* XXX dbuf_undirty? */
   1931 			bzero(db->db.db_data, db->db.db_size);
   1932 			db->db_freed_in_flight = FALSE;
   1933 		}
   1934 		db->db_state = DB_CACHED;
   1935 		cv_broadcast(&db->db_changed);
   1936 	}
   1937 	mutex_exit(&db->db_mtx);
   1938 }
   1939 
   1940 void
   1941 dmu_buf_write_embedded(dmu_buf_t *dbuf, void *data,
   1942     bp_embedded_type_t etype, enum zio_compress comp,
   1943     int uncompressed_size, int compressed_size, int byteorder,
   1944     dmu_tx_t *tx)
   1945 {
   1946 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbuf;
   1947 	struct dirty_leaf *dl;
   1948 	dmu_object_type_t type;
   1949 
   1950 	if (etype == BP_EMBEDDED_TYPE_DATA) {
   1951 		ASSERT(spa_feature_is_active(dmu_objset_spa(db->db_objset),
   1952 		    SPA_FEATURE_EMBEDDED_DATA));
   1953 	}
   1954 
   1955 	DB_DNODE_ENTER(db);
   1956 	type = DB_DNODE(db)->dn_type;
   1957 	DB_DNODE_EXIT(db);
   1958 
   1959 	ASSERT0(db->db_level);
   1960 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
   1961 
   1962 	dmu_buf_will_not_fill(dbuf, tx);
   1963 
   1964 	ASSERT3U(db->db_last_dirty->dr_txg, ==, tx->tx_txg);
   1965 	dl = &db->db_last_dirty->dt.dl;
   1966 	encode_embedded_bp_compressed(&dl->dr_overridden_by,
   1967 	    data, comp, uncompressed_size, compressed_size);
   1968 	BPE_SET_ETYPE(&dl->dr_overridden_by, etype);
   1969 	BP_SET_TYPE(&dl->dr_overridden_by, type);
   1970 	BP_SET_LEVEL(&dl->dr_overridden_by, 0);
   1971 	BP_SET_BYTEORDER(&dl->dr_overridden_by, byteorder);
   1972 
   1973 	dl->dr_override_state = DR_OVERRIDDEN;
   1974 	dl->dr_overridden_by.blk_birth = db->db_last_dirty->dr_txg;
   1975 }
   1976 
   1977 /*
   1978  * Directly assign a provided arc buf to a given dbuf if it's not referenced
   1979  * by anybody except our caller. Otherwise copy arcbuf's contents to dbuf.
   1980  */
   1981 void
   1982 dbuf_assign_arcbuf(dmu_buf_impl_t *db, arc_buf_t *buf, dmu_tx_t *tx)
   1983 {
   1984 	ASSERT(!refcount_is_zero(&db->db_holds));
   1985 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
   1986 	ASSERT(db->db_level == 0);
   1987 	ASSERT(DBUF_GET_BUFC_TYPE(db) == ARC_BUFC_DATA);
   1988 	ASSERT(buf != NULL);
   1989 	ASSERT(arc_buf_size(buf) == db->db.db_size);
   1990 	ASSERT(tx->tx_txg != 0);
   1991 
   1992 	arc_return_buf(buf, db);
   1993 	ASSERT(arc_released(buf));
   1994 
   1995 	mutex_enter(&db->db_mtx);
   1996 
   1997 	while (db->db_state == DB_READ || db->db_state == DB_FILL)
   1998 		cv_wait(&db->db_changed, &db->db_mtx);
   1999 
   2000 	ASSERT(db->db_state == DB_CACHED || db->db_state == DB_UNCACHED);
   2001 
   2002 	if (db->db_state == DB_CACHED &&
   2003 	    refcount_count(&db->db_holds) - 1 > db->db_dirtycnt) {
   2004 		mutex_exit(&db->db_mtx);
   2005 		(void) dbuf_dirty(db, tx);
   2006 		bcopy(buf->b_data, db->db.db_data, db->db.db_size);
   2007 		arc_buf_destroy(buf, db);
   2008 		xuio_stat_wbuf_copied();
   2009 		return;
   2010 	}
   2011 
   2012 	xuio_stat_wbuf_nocopy();
   2013 	if (db->db_state == DB_CACHED) {
   2014 		dbuf_dirty_record_t *dr = db->db_last_dirty;
   2015 
   2016 		ASSERT(db->db_buf != NULL);
   2017 		if (dr != NULL && dr->dr_txg == tx->tx_txg) {
   2018 			ASSERT(dr->dt.dl.dr_data == db->db_buf);
   2019 			if (!arc_released(db->db_buf)) {
   2020 				ASSERT(dr->dt.dl.dr_override_state ==
   2021 				    DR_OVERRIDDEN);
   2022 				arc_release(db->db_buf, db);
   2023 			}
   2024 			dr->dt.dl.dr_data = buf;
   2025 			arc_buf_destroy(db->db_buf, db);
   2026 		} else if (dr == NULL || dr->dt.dl.dr_data != db->db_buf) {
   2027 			arc_release(db->db_buf, db);
   2028 			arc_buf_destroy(db->db_buf, db);
   2029 		}
   2030 		db->db_buf = NULL;
   2031 	}
   2032 	ASSERT(db->db_buf == NULL);
   2033 	dbuf_set_data(db, buf);
   2034 	db->db_state = DB_FILL;
   2035 	mutex_exit(&db->db_mtx);
   2036 	(void) dbuf_dirty(db, tx);
   2037 	dmu_buf_fill_done(&db->db, tx);
   2038 }
   2039 
   2040 void
   2041 dbuf_destroy(dmu_buf_impl_t *db)
   2042 {
   2043 	dnode_t *dn;
   2044 	dmu_buf_impl_t *parent = db->db_parent;
   2045 	dmu_buf_impl_t *dndb;
   2046 
   2047 	ASSERT(MUTEX_HELD(&db->db_mtx));
   2048 	ASSERT(refcount_is_zero(&db->db_holds));
   2049 
   2050 	if (db->db_buf != NULL) {
   2051 		arc_buf_destroy(db->db_buf, db);
   2052 		db->db_buf = NULL;
   2053 	}
   2054 
   2055 	if (db->db_blkid == DMU_BONUS_BLKID) {
   2056 		ASSERT(db->db.db_data != NULL);
   2057 		zio_buf_free(db->db.db_data, DN_MAX_BONUSLEN);
   2058 		arc_space_return(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
   2059 		db->db_state = DB_UNCACHED;
   2060 	}
   2061 
   2062 	dbuf_clear_data(db);
   2063 
   2064 	if (multilist_link_active(&db->db_cache_link)) {
   2065 		multilist_remove(&dbuf_cache, db);
   2066 		(void) refcount_remove_many(&dbuf_cache_size,
   2067 		    db->db.db_size, db);
   2068 	}
   2069 
   2070 	ASSERT(db->db_state == DB_UNCACHED || db->db_state == DB_NOFILL);
   2071 	ASSERT(db->db_data_pending == NULL);
   2072 
   2073 	db->db_state = DB_EVICTING;
   2074 	db->db_blkptr = NULL;
   2075 
   2076 	/*
   2077 	 * Now that db_state is DB_EVICTING, nobody else can find this via
   2078 	 * the hash table.  We can now drop db_mtx, which allows us to
   2079 	 * acquire the dn_dbufs_mtx.
   2080 	 */
   2081 	mutex_exit(&db->db_mtx);
   2082 
   2083 	DB_DNODE_ENTER(db);
   2084 	dn = DB_DNODE(db);
   2085 	dndb = dn->dn_dbuf;
   2086 	if (db->db_blkid != DMU_BONUS_BLKID) {
   2087 		boolean_t needlock = !MUTEX_HELD(&dn->dn_dbufs_mtx);
   2088 		if (needlock)
   2089 			mutex_enter(&dn->dn_dbufs_mtx);
   2090 		avl_remove(&dn->dn_dbufs, db);
   2091 		atomic_dec_32(&dn->dn_dbufs_count);
   2092 		membar_producer();
   2093 		DB_DNODE_EXIT(db);
   2094 		if (needlock)
   2095 			mutex_exit(&dn->dn_dbufs_mtx);
   2096 		/*
   2097 		 * Decrementing the dbuf count means that the hold corresponding
   2098 		 * to the removed dbuf is no longer discounted in dnode_move(),
   2099 		 * so the dnode cannot be moved until after we release the hold.
   2100 		 * The membar_producer() ensures visibility of the decremented
   2101 		 * value in dnode_move(), since DB_DNODE_EXIT doesn't actually
   2102 		 * release any lock.
   2103 		 */
   2104 		dnode_rele(dn, db);
   2105 		db->db_dnode_handle = NULL;
   2106 
   2107 		dbuf_hash_remove(db);
   2108 	} else {
   2109 		DB_DNODE_EXIT(db);
   2110 	}
   2111 
   2112 	ASSERT(refcount_is_zero(&db->db_holds));
   2113 
   2114 	db->db_parent = NULL;
   2115 
   2116 	ASSERT(db->db_buf == NULL);
   2117 	ASSERT(db->db.db_data == NULL);
   2118 	ASSERT(db->db_hash_next == NULL);
   2119 	ASSERT(db->db_blkptr == NULL);
   2120 	ASSERT(db->db_data_pending == NULL);
   2121 	ASSERT(!multilist_link_active(&db->db_cache_link));
   2122 
   2123 	kmem_cache_free(dbuf_kmem_cache, db);
   2124 	arc_space_return(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
   2125 
   2126 	/*
   2127 	 * If this dbuf is referenced from an indirect dbuf,
   2128 	 * decrement the ref count on the indirect dbuf.
   2129 	 */
   2130 	if (parent && parent != dndb)
   2131 		dbuf_rele(parent, db);
   2132 }
   2133 
   2134 /*
   2135  * Note: While bpp will always be updated if the function returns success,
   2136  * parentp will not be updated if the dnode does not have dn_dbuf filled in;
   2137  * this happens when the dnode is the meta-dnode, or a userused or groupused
   2138  * object.
   2139  */
   2140 static int
   2141 dbuf_findbp(dnode_t *dn, int level, uint64_t blkid, int fail_sparse,
   2142     dmu_buf_impl_t **parentp, blkptr_t **bpp)
   2143 {
   2144 	int nlevels, epbs;
   2145 
   2146 	*parentp = NULL;
   2147 	*bpp = NULL;
   2148 
   2149 	ASSERT(blkid != DMU_BONUS_BLKID);
   2150 
   2151 	if (blkid == DMU_SPILL_BLKID) {
   2152 		mutex_enter(&dn->dn_mtx);
   2153 		if (dn->dn_have_spill &&
   2154 		    (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR))
   2155 			*bpp = &dn->dn_phys->dn_spill;
   2156 		else
   2157 			*bpp = NULL;
   2158 		dbuf_add_ref(dn->dn_dbuf, NULL);
   2159 		*parentp = dn->dn_dbuf;
   2160 		mutex_exit(&dn->dn_mtx);
   2161 		return (0);
   2162 	}
   2163 
   2164 	if (dn->dn_phys->dn_nlevels == 0)
   2165 		nlevels = 1;
   2166 	else
   2167 		nlevels = dn->dn_phys->dn_nlevels;
   2168 
   2169 	epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
   2170 
   2171 	ASSERT3U(level * epbs, <, 64);
   2172 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
   2173 	if (level >= nlevels ||
   2174 	    (blkid > (dn->dn_phys->dn_maxblkid >> (level * epbs)))) {
   2175 		/* the buffer has no parent yet */
   2176 		return (SET_ERROR(ENOENT));
   2177 	} else if (level < nlevels-1) {
   2178 		/* this block is referenced from an indirect block */
   2179 		int err = dbuf_hold_impl(dn, level+1,
   2180 		    blkid >> epbs, fail_sparse, FALSE, NULL, parentp);
   2181 		if (err)
   2182 			return (err);
   2183 		err = dbuf_read(*parentp, NULL,
   2184 		    (DB_RF_HAVESTRUCT | DB_RF_NOPREFETCH | DB_RF_CANFAIL));
   2185 		if (err) {
   2186 			dbuf_rele(*parentp, NULL);
   2187 			*parentp = NULL;
   2188 			return (err);
   2189 		}
   2190 		*bpp = ((blkptr_t *)(*parentp)->db.db_data) +
   2191 		    (blkid & ((1ULL << epbs) - 1));
   2192 		return (0);
   2193 	} else {
   2194 		/* the block is referenced from the dnode */
   2195 		ASSERT3U(level, ==, nlevels-1);
   2196 		ASSERT(dn->dn_phys->dn_nblkptr == 0 ||
   2197 		    blkid < dn->dn_phys->dn_nblkptr);
   2198 		if (dn->dn_dbuf) {
   2199 			dbuf_add_ref(dn->dn_dbuf, NULL);
   2200 			*parentp = dn->dn_dbuf;
   2201 		}
   2202 		*bpp = &dn->dn_phys->dn_blkptr[blkid];
   2203 		return (0);
   2204 	}
   2205 }
   2206 
   2207 static dmu_buf_impl_t *
   2208 dbuf_create(dnode_t *dn, uint8_t level, uint64_t blkid,
   2209     dmu_buf_impl_t *parent, blkptr_t *blkptr)
   2210 {
   2211 	objset_t *os = dn->dn_objset;
   2212 	dmu_buf_impl_t *db, *odb;
   2213 
   2214 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
   2215 	ASSERT(dn->dn_type != DMU_OT_NONE);
   2216 
   2217 	db = kmem_cache_alloc(dbuf_kmem_cache, KM_SLEEP);
   2218 
   2219 	db->db_objset = os;
   2220 	db->db.db_object = dn->dn_object;
   2221 	db->db_level = level;
   2222 	db->db_blkid = blkid;
   2223 	db->db_last_dirty = NULL;
   2224 	db->db_dirtycnt = 0;
   2225 	db->db_dnode_handle = dn->dn_handle;
   2226 	db->db_parent = parent;
   2227 	db->db_blkptr = blkptr;
   2228 
   2229 	db->db_user = NULL;
   2230 	db->db_user_immediate_evict = FALSE;
   2231 	db->db_freed_in_flight = FALSE;
   2232 	db->db_pending_evict = FALSE;
   2233 
   2234 	if (blkid == DMU_BONUS_BLKID) {
   2235 		ASSERT3P(parent, ==, dn->dn_dbuf);
   2236 		db->db.db_size = DN_MAX_BONUSLEN -
   2237 		    (dn->dn_nblkptr-1) * sizeof (blkptr_t);
   2238 		ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
   2239 		db->db.db_offset = DMU_BONUS_BLKID;
   2240 		db->db_state = DB_UNCACHED;
   2241 		/* the bonus dbuf is not placed in the hash table */
   2242 		arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
   2243 		return (db);
   2244 	} else if (blkid == DMU_SPILL_BLKID) {
   2245 		db->db.db_size = (blkptr != NULL) ?
   2246 		    BP_GET_LSIZE(blkptr) : SPA_MINBLOCKSIZE;
   2247 		db->db.db_offset = 0;
   2248 	} else {
   2249 		int blocksize =
   2250 		    db->db_level ? 1 << dn->dn_indblkshift : dn->dn_datablksz;
   2251 		db->db.db_size = blocksize;
   2252 		db->db.db_offset = db->db_blkid * blocksize;
   2253 	}
   2254 
   2255 	/*
   2256 	 * Hold the dn_dbufs_mtx while we get the new dbuf
   2257 	 * in the hash table *and* added to the dbufs list.
   2258 	 * This prevents a possible deadlock with someone
   2259 	 * trying to look up this dbuf before its added to the
   2260 	 * dn_dbufs list.
   2261 	 */
   2262 	mutex_enter(&dn->dn_dbufs_mtx);
   2263 	db->db_state = DB_EVICTING;
   2264 	if ((odb = dbuf_hash_insert(db)) != NULL) {
   2265 		/* someone else inserted it first */
   2266 		kmem_cache_free(dbuf_kmem_cache, db);
   2267 		mutex_exit(&dn->dn_dbufs_mtx);
   2268 		return (odb);
   2269 	}
   2270 	avl_add(&dn->dn_dbufs, db);
   2271 
   2272 	db->db_state = DB_UNCACHED;
   2273 	mutex_exit(&dn->dn_dbufs_mtx);
   2274 	arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
   2275 
   2276 	if (parent && parent != dn->dn_dbuf)
   2277 		dbuf_add_ref(parent, db);
   2278 
   2279 	ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
   2280 	    refcount_count(&dn->dn_holds) > 0);
   2281 	(void) refcount_add(&dn->dn_holds, db);
   2282 	atomic_inc_32(&dn->dn_dbufs_count);
   2283 
   2284 	dprintf_dbuf(db, "db=%p\n", db);
   2285 
   2286 	return (db);
   2287 }
   2288 
   2289 typedef struct dbuf_prefetch_arg {
   2290 	spa_t *dpa_spa;	/* The spa to issue the prefetch in. */
   2291 	zbookmark_phys_t dpa_zb; /* The target block to prefetch. */
   2292 	int dpa_epbs; /* Entries (blkptr_t's) Per Block Shift. */
   2293 	int dpa_curlevel; /* The current level that we're reading */
   2294 	dnode_t *dpa_dnode; /* The dnode associated with the prefetch */
   2295 	zio_priority_t dpa_prio; /* The priority I/Os should be issued at. */
   2296 	zio_t *dpa_zio; /* The parent zio_t for all prefetches. */
   2297 	arc_flags_t dpa_aflags; /* Flags to pass to the final prefetch. */
   2298 } dbuf_prefetch_arg_t;
   2299 
   2300 /*
   2301  * Actually issue the prefetch read for the block given.
   2302  */
   2303 static void
   2304 dbuf_issue_final_prefetch(dbuf_prefetch_arg_t *dpa, blkptr_t *bp)
   2305 {
   2306 	if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
   2307 		return;
   2308 
   2309 	arc_flags_t aflags =
   2310 	    dpa->dpa_aflags | ARC_FLAG_NOWAIT | ARC_FLAG_PREFETCH;
   2311 
   2312 	ASSERT3U(dpa->dpa_curlevel, ==, BP_GET_LEVEL(bp));
   2313 	ASSERT3U(dpa->dpa_curlevel, ==, dpa->dpa_zb.zb_level);
   2314 	ASSERT(dpa->dpa_zio != NULL);
   2315 	(void) arc_read(dpa->dpa_zio, dpa->dpa_spa, bp, NULL, NULL,
   2316 	    dpa->dpa_prio, ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
   2317 	    &aflags, &dpa->dpa_zb);
   2318 }
   2319 
   2320 /*
   2321  * Called when an indirect block above our prefetch target is read in.  This
   2322  * will either read in the next indirect block down the tree or issue the actual
   2323  * prefetch if the next block down is our target.
   2324  */
   2325 static void
   2326 dbuf_prefetch_indirect_done(zio_t *zio, arc_buf_t *abuf, void *private)
   2327 {
   2328 	dbuf_prefetch_arg_t *dpa = private;
   2329 
   2330 	ASSERT3S(dpa->dpa_zb.zb_level, <, dpa->dpa_curlevel);
   2331 	ASSERT3S(dpa->dpa_curlevel, >, 0);
   2332 
   2333 	/*
   2334 	 * The dpa_dnode is only valid if we are called with a NULL
   2335 	 * zio. This indicates that the arc_read() returned without
   2336 	 * first calling zio_read() to issue a physical read. Once
   2337 	 * a physical read is made the dpa_dnode must be invalidated
   2338 	 * as the locks guarding it may have been dropped. If the
   2339 	 * dpa_dnode is still valid, then we want to add it to the dbuf
   2340 	 * cache. To do so, we must hold the dbuf associated with the block
   2341 	 * we just prefetched, read its contents so that we associate it
   2342 	 * with an arc_buf_t, and then release it.
   2343 	 */
   2344 	if (zio != NULL) {
   2345 		ASSERT3S(BP_GET_LEVEL(zio->io_bp), ==, dpa->dpa_curlevel);
   2346 		if (zio->io_flags & ZIO_FLAG_RAW) {
   2347 			ASSERT3U(BP_GET_PSIZE(zio->io_bp), ==, zio->io_size);
   2348 		} else {
   2349 			ASSERT3U(BP_GET_LSIZE(zio->io_bp), ==, zio->io_size);
   2350 		}
   2351 		ASSERT3P(zio->io_spa, ==, dpa->dpa_spa);
   2352 
   2353 		dpa->dpa_dnode = NULL;
   2354 	} else if (dpa->dpa_dnode != NULL) {
   2355 		uint64_t curblkid = dpa->dpa_zb.zb_blkid >>
   2356 		    (dpa->dpa_epbs * (dpa->dpa_curlevel -
   2357 		    dpa->dpa_zb.zb_level));
   2358 		dmu_buf_impl_t *db = dbuf_hold_level(dpa->dpa_dnode,
   2359 		    dpa->dpa_curlevel, curblkid, FTAG);
   2360 		(void) dbuf_read(db, NULL,
   2361 		    DB_RF_MUST_SUCCEED | DB_RF_NOPREFETCH | DB_RF_HAVESTRUCT);
   2362 		dbuf_rele(db, FTAG);
   2363 	}
   2364 
   2365 	dpa->dpa_curlevel--;
   2366 
   2367 	uint64_t nextblkid = dpa->dpa_zb.zb_blkid >>
   2368 	    (dpa->dpa_epbs * (dpa->dpa_curlevel - dpa->dpa_zb.zb_level));
   2369 	blkptr_t *bp = ((blkptr_t *)abuf->b_data) +
   2370 	    P2PHASE(nextblkid, 1ULL << dpa->dpa_epbs);
   2371 	if (BP_IS_HOLE(bp) || (zio != NULL && zio->io_error != 0)) {
   2372 		kmem_free(dpa, sizeof (*dpa));
   2373 	} else if (dpa->dpa_curlevel == dpa->dpa_zb.zb_level) {
   2374 		ASSERT3U(nextblkid, ==, dpa->dpa_zb.zb_blkid);
   2375 		dbuf_issue_final_prefetch(dpa, bp);
   2376 		kmem_free(dpa, sizeof (*dpa));
   2377 	} else {
   2378 		arc_flags_t iter_aflags = ARC_FLAG_NOWAIT;
   2379 		zbookmark_phys_t zb;
   2380 
   2381 		ASSERT3U(dpa->dpa_curlevel, ==, BP_GET_LEVEL(bp));
   2382 
   2383 		SET_BOOKMARK(&zb, dpa->dpa_zb.zb_objset,
   2384 		    dpa->dpa_zb.zb_object, dpa->dpa_curlevel, nextblkid);
   2385 
   2386 		(void) arc_read(dpa->dpa_zio, dpa->dpa_spa,
   2387 		    bp, dbuf_prefetch_indirect_done, dpa, dpa->dpa_prio,
   2388 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
   2389 		    &iter_aflags, &zb);
   2390 	}
   2391 
   2392 	arc_buf_destroy(abuf, private);
   2393 }
   2394 
   2395 /*
   2396  * Issue prefetch reads for the given block on the given level.  If the indirect
   2397  * blocks above that block are not in memory, we will read them in
   2398  * asynchronously.  As a result, this call never blocks waiting for a read to
   2399  * complete.
   2400  */
   2401 void
   2402 dbuf_prefetch(dnode_t *dn, int64_t level, uint64_t blkid, zio_priority_t prio,
   2403     arc_flags_t aflags)
   2404 {
   2405 	blkptr_t bp;
   2406 	int epbs, nlevels, curlevel;
   2407 	uint64_t curblkid;
   2408 
   2409 	ASSERT(blkid != DMU_BONUS_BLKID);
   2410 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
   2411 
   2412 	if (blkid > dn->dn_maxblkid)
   2413 		return;
   2414 
   2415 	if (dnode_block_freed(dn, blkid))
   2416 		return;
   2417 
   2418 	/*
   2419 	 * This dnode hasn't been written to disk yet, so there's nothing to
   2420 	 * prefetch.
   2421 	 */
   2422 	nlevels = dn->dn_phys->dn_nlevels;
   2423 	if (level >= nlevels || dn->dn_phys->dn_nblkptr == 0)
   2424 		return;
   2425 
   2426 	epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
   2427 	if (dn->dn_phys->dn_maxblkid < blkid << (epbs * level))
   2428 		return;
   2429 
   2430 	dmu_buf_impl_t *db = dbuf_find(dn->dn_objset, dn->dn_object,
   2431 	    level, blkid);
   2432 	if (db != NULL) {
   2433 		mutex_exit(&db->db_mtx);
   2434 		/*
   2435 		 * This dbuf already exists.  It is either CACHED, or
   2436 		 * (we assume) about to be read or filled.
   2437 		 */
   2438 		return;
   2439 	}
   2440 
   2441 	/*
   2442 	 * Find the closest ancestor (indirect block) of the target block
   2443 	 * that is present in the cache.  In this indirect block, we will
   2444 	 * find the bp that is at curlevel, curblkid.
   2445 	 */
   2446 	curlevel = level;
   2447 	curblkid = blkid;
   2448 	while (curlevel < nlevels - 1) {
   2449 		int parent_level = curlevel + 1;
   2450 		uint64_t parent_blkid = curblkid >> epbs;
   2451 		dmu_buf_impl_t *db;
   2452 
   2453 		if (dbuf_hold_impl(dn, parent_level, parent_blkid,
   2454 		    FALSE, TRUE, FTAG, &db) == 0) {
   2455 			blkptr_t *bpp = db->db_buf->b_data;
   2456 			bp = bpp[P2PHASE(curblkid, 1 << epbs)];
   2457 			dbuf_rele(db, FTAG);
   2458 			break;
   2459 		}
   2460 
   2461 		curlevel = parent_level;
   2462 		curblkid = parent_blkid;
   2463 	}
   2464 
   2465 	if (curlevel == nlevels - 1) {
   2466 		/* No cached indirect blocks found. */
   2467 		ASSERT3U(curblkid, <, dn->dn_phys->dn_nblkptr);
   2468 		bp = dn->dn_phys->dn_blkptr[curblkid];
   2469 	}
   2470 	if (BP_IS_HOLE(&bp))
   2471 		return;
   2472 
   2473 	ASSERT3U(curlevel, ==, BP_GET_LEVEL(&bp));
   2474 
   2475 	zio_t *pio = zio_root(dmu_objset_spa(dn->dn_objset), NULL, NULL,
   2476 	    ZIO_FLAG_CANFAIL);
   2477 
   2478 	dbuf_prefetch_arg_t *dpa = kmem_zalloc(sizeof (*dpa), KM_SLEEP);
   2479 	dsl_dataset_t *ds = dn->dn_objset->os_dsl_dataset;
   2480 	SET_BOOKMARK(&dpa->dpa_zb, ds != NULL ? ds->ds_object : DMU_META_OBJSET,
   2481 	    dn->dn_object, level, blkid);
   2482 	dpa->dpa_curlevel = curlevel;
   2483 	dpa->dpa_prio = prio;
   2484 	dpa->dpa_aflags = aflags;
   2485 	dpa->dpa_spa = dn->dn_objset->os_spa;
   2486 	dpa->dpa_dnode = dn;
   2487 	dpa->dpa_epbs = epbs;
   2488 	dpa->dpa_zio = pio;
   2489 
   2490 	/*
   2491 	 * If we have the indirect just above us, no need to do the asynchronous
   2492 	 * prefetch chain; we'll just run the last step ourselves.  If we're at
   2493 	 * a higher level, though, we want to issue the prefetches for all the
   2494 	 * indirect blocks asynchronously, so we can go on with whatever we were
   2495 	 * doing.
   2496 	 */
   2497 	if (curlevel == level) {
   2498 		ASSERT3U(curblkid, ==, blkid);
   2499 		dbuf_issue_final_prefetch(dpa, &bp);
   2500 		kmem_free(dpa, sizeof (*dpa));
   2501 	} else {
   2502 		arc_flags_t iter_aflags = ARC_FLAG_NOWAIT;
   2503 		zbookmark_phys_t zb;
   2504 
   2505 		SET_BOOKMARK(&zb, ds != NULL ? ds->ds_object : DMU_META_OBJSET,
   2506 		    dn->dn_object, curlevel, curblkid);
   2507 		(void) arc_read(dpa->dpa_zio, dpa->dpa_spa,
   2508 		    &bp, dbuf_prefetch_indirect_done, dpa, prio,
   2509 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
   2510 		    &iter_aflags, &zb);
   2511 	}
   2512 	/*
   2513 	 * We use pio here instead of dpa_zio since it's possible that
   2514 	 * dpa may have already been freed.
   2515 	 */
   2516 	zio_nowait(pio);
   2517 }
   2518 
   2519 /*
   2520  * Returns with db_holds incremented, and db_mtx not held.
   2521  * Note: dn_struct_rwlock must be held.
   2522  */
   2523 int
   2524 dbuf_hold_impl(dnode_t *dn, uint8_t level, uint64_t blkid,
   2525     boolean_t fail_sparse, boolean_t fail_uncached,
   2526     void *tag, dmu_buf_impl_t **dbp)
   2527 {
   2528 	dmu_buf_impl_t *db, *parent = NULL;
   2529 
   2530 	ASSERT(blkid != DMU_BONUS_BLKID);
   2531 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
   2532 	ASSERT3U(dn->dn_nlevels, >, level);
   2533 
   2534 	*dbp = NULL;
   2535 top:
   2536 	/* dbuf_find() returns with db_mtx held */
   2537 	db = dbuf_find(dn->dn_objset, dn->dn_object, level, blkid);
   2538 
   2539 	if (db == NULL) {
   2540 		blkptr_t *bp = NULL;
   2541 		int err;
   2542 
   2543 		if (fail_uncached)
   2544 			return (SET_ERROR(ENOENT));
   2545 
   2546 		ASSERT3P(parent, ==, NULL);
   2547 		err = dbuf_findbp(dn, level, blkid, fail_sparse, &parent, &bp);
   2548 		if (fail_sparse) {
   2549 			if (err == 0 && bp && BP_IS_HOLE(bp))
   2550 				err = SET_ERROR(ENOENT);
   2551 			if (err) {
   2552 				if (parent)
   2553 					dbuf_rele(parent, NULL);
   2554 				return (err);
   2555 			}
   2556 		}
   2557 		if (err && err != ENOENT)
   2558 			return (err);
   2559 		db = dbuf_create(dn, level, blkid, parent, bp);
   2560 	}
   2561 
   2562 	if (fail_uncached && db->db_state != DB_CACHED) {
   2563 		mutex_exit(&db->db_mtx);
   2564 		return (SET_ERROR(ENOENT));
   2565 	}
   2566 
   2567 	if (db->db_buf != NULL)
   2568 		ASSERT3P(db->db.db_data, ==, db->db_buf->b_data);
   2569 
   2570 	ASSERT(db->db_buf == NULL || arc_referenced(db->db_buf));
   2571 
   2572 	/*
   2573 	 * If this buffer is currently syncing out, and we are are
   2574 	 * still referencing it from db_data, we need to make a copy
   2575 	 * of it in case we decide we want to dirty it again in this txg.
   2576 	 */
   2577 	if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
   2578 	    dn->dn_object != DMU_META_DNODE_OBJECT &&
   2579 	    db->db_state == DB_CACHED && db->db_data_pending) {
   2580 		dbuf_dirty_record_t *dr = db->db_data_pending;
   2581 
   2582 		if (dr->dt.dl.dr_data == db->db_buf) {
   2583 			arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
   2584 
   2585 			dbuf_set_data(db,
   2586 			    arc_alloc_buf(dn->dn_objset->os_spa,
   2587 			    db->db.db_size, db, type));
   2588 			bcopy(dr->dt.dl.dr_data->b_data, db->db.db_data,
   2589 			    db->db.db_size);
   2590 		}
   2591 	}
   2592 
   2593 	if (multilist_link_active(&db->db_cache_link)) {
   2594 		ASSERT(refcount_is_zero(&db->db_holds));
   2595 		multilist_remove(&dbuf_cache, db);
   2596 		(void) refcount_remove_many(&dbuf_cache_size,
   2597 		    db->db.db_size, db);
   2598 	}
   2599 	(void) refcount_add(&db->db_holds, tag);
   2600 	DBUF_VERIFY(db);
   2601 	mutex_exit(&db->db_mtx);
   2602 
   2603 	/* NOTE: we can't rele the parent until after we drop the db_mtx */
   2604 	if (parent)
   2605 		dbuf_rele(parent, NULL);
   2606 
   2607 	ASSERT3P(DB_DNODE(db), ==, dn);
   2608 	ASSERT3U(db->db_blkid, ==, blkid);
   2609 	ASSERT3U(db->db_level, ==, level);
   2610 	*dbp = db;
   2611 
   2612 	return (0);
   2613 }
   2614 
   2615 dmu_buf_impl_t *
   2616 dbuf_hold(dnode_t *dn, uint64_t blkid, void *tag)
   2617 {
   2618 	return (dbuf_hold_level(dn, 0, blkid, tag));
   2619 }
   2620 
   2621 dmu_buf_impl_t *
   2622 dbuf_hold_level(dnode_t *dn, int level, uint64_t blkid, void *tag)
   2623 {
   2624 	dmu_buf_impl_t *db;
   2625 	int err = dbuf_hold_impl(dn, level, blkid, FALSE, FALSE, tag, &db);
   2626 	return (err ? NULL : db);
   2627 }
   2628 
   2629 void
   2630 dbuf_create_bonus(dnode_t *dn)
   2631 {
   2632 	ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
   2633 
   2634 	ASSERT(dn->dn_bonus == NULL);
   2635 	dn->dn_bonus = dbuf_create(dn, 0, DMU_BONUS_BLKID, dn->dn_dbuf, NULL);
   2636 }
   2637 
   2638 int
   2639 dbuf_spill_set_blksz(dmu_buf_t *db_fake, uint64_t blksz, dmu_tx_t *tx)
   2640 {
   2641 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
   2642 	dnode_t *dn;
   2643 
   2644 	if (db->db_blkid != DMU_SPILL_BLKID)
   2645 		return (SET_ERROR(ENOTSUP));
   2646 	if (blksz == 0)
   2647 		blksz = SPA_MINBLOCKSIZE;
   2648 	ASSERT3U(blksz, <=, spa_maxblocksize(dmu_objset_spa(db->db_objset)));
   2649 	blksz = P2ROUNDUP(blksz, SPA_MINBLOCKSIZE);
   2650 
   2651 	DB_DNODE_ENTER(db);
   2652 	dn = DB_DNODE(db);
   2653 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
   2654 	dbuf_new_size(db, blksz, tx);
   2655 	rw_exit(&dn->dn_struct_rwlock);
   2656 	DB_DNODE_EXIT(db);
   2657 
   2658 	return (0);
   2659 }
   2660 
   2661 void
   2662 dbuf_rm_spill(dnode_t *dn, dmu_tx_t *tx)
   2663 {
   2664 	dbuf_free_range(dn, DMU_SPILL_BLKID, DMU_SPILL_BLKID, tx);
   2665 }
   2666 
   2667 #pragma weak dmu_buf_add_ref = dbuf_add_ref
   2668 void
   2669 dbuf_add_ref(dmu_buf_impl_t *db, void *tag)
   2670 {
   2671 	int64_t holds = refcount_add(&db->db_holds, tag);
   2672 	ASSERT3S(holds, >, 1);
   2673 }
   2674 
   2675 #pragma weak dmu_buf_try_add_ref = dbuf_try_add_ref
   2676 boolean_t
   2677 dbuf_try_add_ref(dmu_buf_t *db_fake, objset_t *os, uint64_t obj, uint64_t blkid,
   2678     void *tag)
   2679 {
   2680 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
   2681 	dmu_buf_impl_t *found_db;
   2682 	boolean_t result = B_FALSE;
   2683 
   2684 	if (db->db_blkid == DMU_BONUS_BLKID)
   2685 		found_db = dbuf_find_bonus(os, obj);
   2686 	else
   2687 		found_db = dbuf_find(os, obj, 0, blkid);
   2688 
   2689 	if (found_db != NULL) {
   2690 		if (db == found_db && dbuf_refcount(db) > db->db_dirtycnt) {
   2691 			(void) refcount_add(&db->db_holds, tag);
   2692 			result = B_TRUE;
   2693 		}
   2694 		mutex_exit(&db->db_mtx);
   2695 	}
   2696 	return (result);
   2697 }
   2698 
   2699 /*
   2700  * If you call dbuf_rele() you had better not be referencing the dnode handle
   2701  * unless you have some other direct or indirect hold on the dnode. (An indirect
   2702  * hold is a hold on one of the dnode's dbufs, including the bonus buffer.)
   2703  * Without that, the dbuf_rele() could lead to a dnode_rele() followed by the
   2704  * dnode's parent dbuf evicting its dnode handles.
   2705  */
   2706 void
   2707 dbuf_rele(dmu_buf_impl_t *db, void *tag)
   2708 {
   2709 	mutex_enter(&db->db_mtx);
   2710 	dbuf_rele_and_unlock(db, tag);
   2711 }
   2712 
   2713 void
   2714 dmu_buf_rele(dmu_buf_t *db, void *tag)
   2715 {
   2716 	dbuf_rele((dmu_buf_impl_t *)db, tag);
   2717 }
   2718 
   2719 /*
   2720  * dbuf_rele() for an already-locked dbuf.  This is necessary to allow
   2721  * db_dirtycnt and db_holds to be updated atomically.
   2722  */
   2723 void
   2724 dbuf_rele_and_unlock(dmu_buf_impl_t *db, void *tag)
   2725 {
   2726 	int64_t holds;
   2727 
   2728 	ASSERT(MUTEX_HELD(&db->db_mtx));
   2729 	DBUF_VERIFY(db);
   2730 
   2731 	/*
   2732 	 * Remove the reference to the dbuf before removing its hold on the
   2733 	 * dnode so we can guarantee in dnode_move() that a referenced bonus
   2734 	 * buffer has a corresponding dnode hold.
   2735 	 */
   2736 	holds = refcount_remove(&db->db_holds, tag);
   2737 	ASSERT(holds >= 0);
   2738 
   2739 	/*
   2740 	 * We can't freeze indirects if there is a possibility that they
   2741 	 * may be modified in the current syncing context.
   2742 	 */
   2743 	if (db->db_buf != NULL &&
   2744 	    holds == (db->db_level == 0 ? db->db_dirtycnt : 0)) {
   2745 		arc_buf_freeze(db->db_buf);
   2746 	}
   2747 
   2748 	if (holds == db->db_dirtycnt &&
   2749 	    db->db_level == 0 && db->db_user_immediate_evict)
   2750 		dbuf_evict_user(db);
   2751 
   2752 	if (holds == 0) {
   2753 		if (db->db_blkid == DMU_BONUS_BLKID) {
   2754 			dnode_t *dn;
   2755 			boolean_t evict_dbuf = db->db_pending_evict;
   2756 
   2757 			/*
   2758 			 * If the dnode moves here, we cannot cross this
   2759 			 * barrier until the move completes.
   2760 			 */
   2761 			DB_DNODE_ENTER(db);
   2762 
   2763 			dn = DB_DNODE(db);
   2764 			atomic_dec_32(&dn->dn_dbufs_count);
   2765 
   2766 			/*
   2767 			 * Decrementing the dbuf count means that the bonus
   2768 			 * buffer's dnode hold is no longer discounted in
   2769 			 * dnode_move(). The dnode cannot move until after
   2770 			 * the dnode_rele() below.
   2771 			 */
   2772 			DB_DNODE_EXIT(db);
   2773 
   2774 			/*
   2775 			 * Do not reference db after its lock is dropped.
   2776 			 * Another thread may evict it.
   2777 			 */
   2778 			mutex_exit(&db->db_mtx);
   2779 
   2780 			if (evict_dbuf)
   2781 				dnode_evict_bonus(dn);
   2782 
   2783 			dnode_rele(dn, db);
   2784 		} else if (db->db_buf == NULL) {
   2785 			/*
   2786 			 * This is a special case: we never associated this
   2787 			 * dbuf with any data allocated from the ARC.
   2788 			 */
   2789 			ASSERT(db->db_state == DB_UNCACHED ||
   2790 			    db->db_state == DB_NOFILL);
   2791 			dbuf_destroy(db);
   2792 		} else if (arc_released(db->db_buf)) {
   2793 			/*
   2794 			 * This dbuf has anonymous data associated with it.
   2795 			 */
   2796 			dbuf_destroy(db);
   2797 		} else {
   2798 			boolean_t do_arc_evict = B_FALSE;
   2799 			blkptr_t bp;
   2800 			spa_t *spa = dmu_objset_spa(db->db_objset);
   2801 
   2802 			if (!DBUF_IS_CACHEABLE(db) &&
   2803 			    db->db_blkptr != NULL &&
   2804 			    !BP_IS_HOLE(db->db_blkptr) &&
   2805 			    !BP_IS_EMBEDDED(db->db_blkptr)) {
   2806 				do_arc_evict = B_TRUE;
   2807 				bp = *db->db_blkptr;
   2808 			}
   2809 
   2810 			if (!DBUF_IS_CACHEABLE(db) ||
   2811 			    db->db_pending_evict) {
   2812 				dbuf_destroy(db);
   2813 			} else if (!multilist_link_active(&db->db_cache_link)) {
   2814 				multilist_insert(&dbuf_cache, db);
   2815 				(void) refcount_add_many(&dbuf_cache_size,
   2816 				    db->db.db_size, db);
   2817 				mutex_exit(&db->db_mtx);
   2818 
   2819 				dbuf_evict_notify();
   2820 			}
   2821 
   2822 			if (do_arc_evict)
   2823 				arc_freed(spa, &bp);
   2824 		}
   2825 	} else {
   2826 		mutex_exit(&db->db_mtx);
   2827 	}
   2828 
   2829 }
   2830 
   2831 #pragma weak dmu_buf_refcount = dbuf_refcount
   2832 uint64_t
   2833 dbuf_refcount(dmu_buf_impl_t *db)
   2834 {
   2835 	return (refcount_count(&db->db_holds));
   2836 }
   2837 
   2838 void *
   2839 dmu_buf_replace_user(dmu_buf_t *db_fake, dmu_buf_user_t *old_user,
   2840     dmu_buf_user_t *new_user)
   2841 {
   2842 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
   2843 
   2844 	mutex_enter(&db->db_mtx);
   2845 	dbuf_verify_user(db, DBVU_NOT_EVICTING);
   2846 	if (db->db_user == old_user)
   2847 		db->db_user = new_user;
   2848 	else
   2849 		old_user = db->db_user;
   2850 	dbuf_verify_user(db, DBVU_NOT_EVICTING);
   2851 	mutex_exit(&db->db_mtx);
   2852 
   2853 	return (old_user);
   2854 }
   2855 
   2856 void *
   2857 dmu_buf_set_user(dmu_buf_t *db_fake, dmu_buf_user_t *user)
   2858 {
   2859 	return (dmu_buf_replace_user(db_fake, NULL, user));
   2860 }
   2861 
   2862 void *
   2863 dmu_buf_set_user_ie(dmu_buf_t *db_fake, dmu_buf_user_t *user)
   2864 {
   2865 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
   2866 
   2867 	db->db_user_immediate_evict = TRUE;
   2868 	return (dmu_buf_set_user(db_fake, user));
   2869 }
   2870 
   2871 void *
   2872 dmu_buf_remove_user(dmu_buf_t *db_fake, dmu_buf_user_t *user)
   2873 {
   2874 	return (dmu_buf_replace_user(db_fake, user, NULL));
   2875 }
   2876 
   2877 void *
   2878 dmu_buf_get_user(dmu_buf_t *db_fake)
   2879 {
   2880 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
   2881 
   2882 	dbuf_verify_user(db, DBVU_NOT_EVICTING);
   2883 	return (db->db_user);
   2884 }
   2885 
   2886 void
   2887 dmu_buf_user_evict_wait()
   2888 {
   2889 	taskq_wait(dbu_evict_taskq);
   2890 }
   2891 
   2892 boolean_t
   2893 dmu_buf_freeable(dmu_buf_t *dbuf)
   2894 {
   2895 	boolean_t res = B_FALSE;
   2896 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbuf;
   2897 
   2898 	if (db->db_blkptr)
   2899 		res = dsl_dataset_block_freeable(db->db_objset->os_dsl_dataset,
   2900 		    db->db_blkptr, db->db_blkptr->blk_birth);
   2901 
   2902 	return (res);
   2903 }
   2904 
   2905 blkptr_t *
   2906 dmu_buf_get_blkptr(dmu_buf_t *db)
   2907 {
   2908 	dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
   2909 	return (dbi->db_blkptr);
   2910 }
   2911 
   2912 objset_t *
   2913 dmu_buf_get_objset(dmu_buf_t *db)
   2914 {
   2915 	dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
   2916 	return (dbi->db_objset);
   2917 }
   2918 
   2919 dnode_t *
   2920 dmu_buf_dnode_enter(dmu_buf_t *db)
   2921 {
   2922 	dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
   2923 	DB_DNODE_ENTER(dbi);
   2924 	return (DB_DNODE(dbi));
   2925 }
   2926 
   2927 void
   2928 dmu_buf_dnode_exit(dmu_buf_t *db)
   2929 {
   2930 	dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
   2931 	DB_DNODE_EXIT(dbi);
   2932 }
   2933 
   2934 static void
   2935 dbuf_check_blkptr(dnode_t *dn, dmu_buf_impl_t *db)
   2936 {
   2937 	/* ASSERT(dmu_tx_is_syncing(tx) */
   2938 	ASSERT(MUTEX_HELD(&db->db_mtx));
   2939 
   2940 	if (db->db_blkptr != NULL)
   2941 		return;
   2942 
   2943 	if (db->db_blkid == DMU_SPILL_BLKID) {
   2944 		db->db_blkptr = &dn->dn_phys->dn_spill;
   2945 		BP_ZERO(db->db_blkptr);
   2946 		return;
   2947 	}
   2948 	if (db->db_level == dn->dn_phys->dn_nlevels-1) {
   2949 		/*
   2950 		 * This buffer was allocated at a time when there was
   2951 		 * no available blkptrs from the dnode, or it was
   2952 		 * inappropriate to hook it in (i.e., nlevels mis-match).
   2953 		 */
   2954 		ASSERT(db->db_blkid < dn->dn_phys->dn_nblkptr);
   2955 		ASSERT(db->db_parent == NULL);
   2956 		db->db_parent = dn->dn_dbuf;
   2957 		db->db_blkptr = &dn->dn_phys->dn_blkptr[db->db_blkid];
   2958 		DBUF_VERIFY(db);
   2959 	} else {
   2960 		dmu_buf_impl_t *parent = db->db_parent;
   2961 		int epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
   2962 
   2963 		ASSERT(dn->dn_phys->dn_nlevels > 1);
   2964 		if (parent == NULL) {
   2965 			mutex_exit(&db->db_mtx);
   2966 			rw_enter(&dn->dn_struct_rwlock, RW_READER);
   2967 			parent = dbuf_hold_level(dn, db->db_level + 1,
   2968 			    db->db_blkid >> epbs, db);
   2969 			rw_exit(&dn->dn_struct_rwlock);
   2970 			mutex_enter(&db->db_mtx);
   2971 			db->db_parent = parent;
   2972 		}
   2973 		db->db_blkptr = (blkptr_t *)parent->db.db_data +
   2974 		    (db->db_blkid & ((1ULL << epbs) - 1));
   2975 		DBUF_VERIFY(db);
   2976 	}
   2977 }
   2978 
   2979 static void
   2980 dbuf_sync_indirect(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
   2981 {
   2982 	dmu_buf_impl_t *db = dr->dr_dbuf;
   2983 	dnode_t *dn;
   2984 	zio_t *zio;
   2985 
   2986 	ASSERT(dmu_tx_is_syncing(tx));
   2987 
   2988 	dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
   2989 
   2990 	mutex_enter(&db->db_mtx);
   2991 
   2992 	ASSERT(db->db_level > 0);
   2993 	DBUF_VERIFY(db);
   2994 
   2995 	/* Read the block if it hasn't been read yet. */
   2996 	if (db->db_buf == NULL) {
   2997 		mutex_exit(&db->db_mtx);
   2998 		(void) dbuf_read(db, NULL, DB_RF_MUST_SUCCEED);
   2999 		mutex_enter(&db->db_mtx);
   3000 	}
   3001 	ASSERT3U(db->db_state, ==, DB_CACHED);
   3002 	ASSERT(db->db_buf != NULL);
   3003 
   3004 	DB_DNODE_ENTER(db);
   3005 	dn = DB_DNODE(db);
   3006 	/* Indirect block size must match what the dnode thinks it is. */
   3007 	ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
   3008 	dbuf_check_blkptr(dn, db);
   3009 	DB_DNODE_EXIT(db);
   3010 
   3011 	/* Provide the pending dirty record to child dbufs */
   3012 	db->db_data_pending = dr;
   3013 
   3014 	mutex_exit(&db->db_mtx);
   3015 	dbuf_write(dr, db->db_buf, tx);
   3016 
   3017 	zio = dr->dr_zio;
   3018 	mutex_enter(&dr->dt.di.dr_mtx);
   3019 	dbuf_sync_list(&dr->dt.di.dr_children, db->db_level - 1, tx);
   3020 	ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
   3021 	mutex_exit(&dr->dt.di.dr_mtx);
   3022 	zio_nowait(zio);
   3023 }
   3024 
   3025 static void
   3026 dbuf_sync_leaf(dbuf_dirty_record_t *dr, dmu_tx_t *tx)
   3027 {
   3028 	arc_buf_t **datap = &dr->dt.dl.dr_data;
   3029 	dmu_buf_impl_t *db = dr->dr_dbuf;
   3030 	dnode_t *dn;
   3031 	objset_t *os;
   3032 	uint64_t txg = tx->tx_txg;
   3033 
   3034 	ASSERT(dmu_tx_is_syncing(tx));
   3035 
   3036 	dprintf_dbuf_bp(db, db->db_blkptr, "blkptr=%p", db->db_blkptr);
   3037 
   3038 	mutex_enter(&db->db_mtx);
   3039 	/*
   3040 	 * To be synced, we must be dirtied.  But we
   3041 	 * might have been freed after the dirty.
   3042 	 */
   3043 	if (db->db_state == DB_UNCACHED) {
   3044 		/* This buffer has been freed since it was dirtied */
   3045 		ASSERT(db->db.db_data == NULL);
   3046 	} else if (db->db_state == DB_FILL) {
   3047 		/* This buffer was freed and is now being re-filled */
   3048 		ASSERT(db->db.db_data != dr->dt.dl.dr_data);
   3049 	} else {
   3050 		ASSERT(db->db_state == DB_CACHED || db->db_state == DB_NOFILL);
   3051 	}
   3052 	DBUF_VERIFY(db);
   3053 
   3054 	DB_DNODE_ENTER(db);
   3055 	dn = DB_DNODE(db);
   3056 
   3057 	if (db->db_blkid == DMU_SPILL_BLKID) {
   3058 		mutex_enter(&dn->dn_mtx);
   3059 		dn->dn_phys->dn_flags |= DNODE_FLAG_SPILL_BLKPTR;
   3060 		mutex_exit(&dn->dn_mtx);
   3061 	}
   3062 
   3063 	/*
   3064 	 * If this is a bonus buffer, simply copy the bonus data into the
   3065 	 * dnode.  It will be written out when the dnode is synced (and it
   3066 	 * will be synced, since it must have been dirty for dbuf_sync to
   3067 	 * be called).
   3068 	 */
   3069 	if (db->db_blkid == DMU_BONUS_BLKID) {
   3070 		dbuf_dirty_record_t **drp;
   3071 
   3072 		ASSERT(*datap != NULL);
   3073 		ASSERT0(db->db_level);
   3074 		ASSERT3U(dn->dn_phys->dn_bonuslen, <=, DN_MAX_BONUSLEN);
   3075 		bcopy(*datap, DN_BONUS(dn->dn_phys), dn->dn_phys->dn_bonuslen);
   3076 		DB_DNODE_EXIT(db);
   3077 
   3078 		if (*datap != db->db.db_data) {
   3079 			zio_buf_free(*datap, DN_MAX_BONUSLEN);
   3080 			arc_space_return(DN_MAX_BONUSLEN, ARC_SPACE_OTHER);
   3081 		}
   3082 		db->db_data_pending = NULL;
   3083 		drp = &db->db_last_dirty;
   3084 		while (*drp != dr)
   3085 			drp = &(*drp)->dr_next;
   3086 		ASSERT(dr->dr_next == NULL);
   3087 		ASSERT(dr->dr_dbuf == db);
   3088 		*drp = dr->dr_next;
   3089 		if (dr->dr_dbuf->db_level != 0) {
   3090 			list_destroy(&dr->dt.di.dr_children);
   3091 			mutex_destroy(&dr->dt.di.dr_mtx);
   3092 		}
   3093 		kmem_free(dr, sizeof (dbuf_dirty_record_t));
   3094 		ASSERT(db->db_dirtycnt > 0);
   3095 		db->db_dirtycnt -= 1;
   3096 		dbuf_rele_and_unlock(db, (void *)(uintptr_t)txg);
   3097 		return;
   3098 	}
   3099 
   3100 	os = dn->dn_objset;
   3101 
   3102 	/*
   3103 	 * This function may have dropped the db_mtx lock allowing a dmu_sync
   3104 	 * operation to sneak in. As a result, we need to ensure that we
   3105 	 * don't check the dr_override_state until we have returned from
   3106 	 * dbuf_check_blkptr.
   3107 	 */
   3108 	dbuf_check_blkptr(dn, db);
   3109 
   3110 	/*
   3111 	 * If this buffer is in the middle of an immediate write,
   3112 	 * wait for the synchronous IO to complete.
   3113 	 */
   3114 	while (dr->dt.dl.dr_override_state == DR_IN_DMU_SYNC) {
   3115 		ASSERT(dn->dn_object != DMU_META_DNODE_OBJECT);
   3116 		cv_wait(&db->db_changed, &db->db_mtx);
   3117 		ASSERT(dr->dt.dl.dr_override_state != DR_NOT_OVERRIDDEN);
   3118 	}
   3119 
   3120 	if (db->db_state != DB_NOFILL &&
   3121 	    dn->dn_object != DMU_META_DNODE_OBJECT &&
   3122 	    refcount_count(&db->db_holds) > 1 &&
   3123 	    dr->dt.dl.dr_override_state != DR_OVERRIDDEN &&
   3124 	    *datap == db->db_buf) {
   3125 		/*
   3126 		 * If this buffer is currently "in use" (i.e., there
   3127 		 * are active holds and db_data still references it),
   3128 		 * then make a copy before we start the write so that
   3129 		 * any modifications from the open txg will not leak
   3130 		 * into this write.
   3131 		 *
   3132 		 * NOTE: this copy does not need to be made for
   3133 		 * objects only modified in the syncing context (e.g.
   3134 		 * DNONE_DNODE blocks).
   3135 		 */
   3136 		int blksz = arc_buf_size(*datap);
   3137 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
   3138 		*datap = arc_alloc_buf(os->os_spa, blksz, db, type);
   3139 		bcopy(db->db.db_data, (*datap)->b_data, blksz);
   3140 	}
   3141 	db->db_data_pending = dr;
   3142 
   3143 	mutex_exit(&db->db_mtx);
   3144 
   3145 	dbuf_write(dr, *datap, tx);
   3146 
   3147 	ASSERT(!list_link_active(&dr->dr_dirty_node));
   3148 	if (dn->dn_object == DMU_META_DNODE_OBJECT) {
   3149 		list_insert_tail(&dn->dn_dirty_records[txg&TXG_MASK], dr);
   3150 		DB_DNODE_EXIT(db);
   3151 	} else {
   3152 		/*
   3153 		 * Although zio_nowait() does not "wait for an IO", it does
   3154 		 * initiate the IO. If this is an empty write it seems plausible
   3155 		 * that the IO could actually be completed before the nowait
   3156 		 * returns. We need to DB_DNODE_EXIT() first in case
   3157 		 * zio_nowait() invalidates the dbuf.
   3158 		 */
   3159 		DB_DNODE_EXIT(db);
   3160 		zio_nowait(dr->dr_zio);
   3161 	}
   3162 }
   3163 
   3164 void
   3165 dbuf_sync_list(list_t *list, int level, dmu_tx_t *tx)
   3166 {
   3167 	dbuf_dirty_record_t *dr;
   3168 
   3169 	while (dr = list_head(list)) {
   3170 		if (dr->dr_zio != NULL) {
   3171 			/*
   3172 			 * If we find an already initialized zio then we
   3173 			 * are processing the meta-dnode, and we have finished.
   3174 			 * The dbufs for all dnodes are put back on the list
   3175 			 * during processing, so that we can zio_wait()
   3176 			 * these IOs after initiating all child IOs.
   3177 			 */
   3178 			ASSERT3U(dr->dr_dbuf->db.db_object, ==,
   3179 			    DMU_META_DNODE_OBJECT);
   3180 			break;
   3181 		}
   3182 		if (dr->dr_dbuf->db_blkid != DMU_BONUS_BLKID &&
   3183 		    dr->dr_dbuf->db_blkid != DMU_SPILL_BLKID) {
   3184 			VERIFY3U(dr->dr_dbuf->db_level, ==, level);
   3185 		}
   3186 		list_remove(list, dr);
   3187 		if (dr->dr_dbuf->db_level > 0)
   3188 			dbuf_sync_indirect(dr, tx);
   3189 		else
   3190 			dbuf_sync_leaf(dr, tx);
   3191 	}
   3192 }
   3193 
   3194 /* ARGSUSED */
   3195 static void
   3196 dbuf_write_ready(zio_t *zio, arc_buf_t *buf, void *vdb)
   3197 {
   3198 	dmu_buf_impl_t *db = vdb;
   3199 	dnode_t *dn;
   3200 	blkptr_t *bp = zio->io_bp;
   3201 	blkptr_t *bp_orig = &zio->io_bp_orig;
   3202 	spa_t *spa = zio->io_spa;
   3203 	int64_t delta;
   3204 	uint64_t fill = 0;
   3205 	int i;
   3206 
   3207 	ASSERT3P(db->db_blkptr, !=, NULL);
   3208 	ASSERT3P(&db->db_data_pending->dr_bp_copy, ==, bp);
   3209 
   3210 	DB_DNODE_ENTER(db);
   3211 	dn = DB_DNODE(db);
   3212 	delta = bp_get_dsize_sync(spa, bp) - bp_get_dsize_sync(spa, bp_orig);
   3213 	dnode_diduse_space(dn, delta - zio->io_prev_space_delta);
   3214 	zio->io_prev_space_delta = delta;
   3215 
   3216 	if (bp->blk_birth != 0) {
   3217 		ASSERT((db->db_blkid != DMU_SPILL_BLKID &&
   3218 		    BP_GET_TYPE(bp) == dn->dn_type) ||
   3219 		    (db->db_blkid == DMU_SPILL_BLKID &&
   3220 		    BP_GET_TYPE(bp) == dn->dn_bonustype) ||
   3221 		    BP_IS_EMBEDDED(bp));
   3222 		ASSERT(BP_GET_LEVEL(bp) == db->db_level);
   3223 	}
   3224 
   3225 	mutex_enter(&db->db_mtx);
   3226 
   3227 #ifdef ZFS_DEBUG
   3228 	if (db->db_blkid == DMU_SPILL_BLKID) {
   3229 		ASSERT(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR);
   3230 		ASSERT(!(BP_IS_HOLE(bp)) &&
   3231 		    db->db_blkptr == &dn->dn_phys->dn_spill);
   3232 	}
   3233 #endif
   3234 
   3235 	if (db->db_level == 0) {
   3236 		mutex_enter(&dn->dn_mtx);
   3237 		if (db->db_blkid > dn->dn_phys->dn_maxblkid &&
   3238 		    db->db_blkid != DMU_SPILL_BLKID)
   3239 			dn->dn_phys->dn_maxblkid = db->db_blkid;
   3240 		mutex_exit(&dn->dn_mtx);
   3241 
   3242 		if (dn->dn_type == DMU_OT_DNODE) {
   3243 			dnode_phys_t *dnp = db->db.db_data;
   3244 			for (i = db->db.db_size >> DNODE_SHIFT; i > 0;
   3245 			    i--, dnp++) {
   3246 				if (dnp->dn_type != DMU_OT_NONE)
   3247 					fill++;
   3248 			}
   3249 		} else {
   3250 			if (BP_IS_HOLE(bp)) {
   3251 				fill = 0;
   3252 			} else {
   3253 				fill = 1;
   3254 			}
   3255 		}
   3256 	} else {
   3257 		blkptr_t *ibp = db->db.db_data;
   3258 		ASSERT3U(db->db.db_size, ==, 1<<dn->dn_phys->dn_indblkshift);
   3259 		for (i = db->db.db_size >> SPA_BLKPTRSHIFT; i > 0; i--, ibp++) {
   3260 			if (BP_IS_HOLE(ibp))
   3261 				continue;
   3262 			fill += BP_GET_FILL(ibp);
   3263 		}
   3264 	}
   3265 	DB_DNODE_EXIT(db);
   3266 
   3267 	if (!BP_IS_EMBEDDED(bp))
   3268 		bp->blk_fill = fill;
   3269 
   3270 	mutex_exit(&db->db_mtx);
   3271 
   3272 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
   3273 	*db->db_blkptr = *bp;
   3274 	rw_exit(&dn->dn_struct_rwlock);
   3275 }
   3276 
   3277 /* ARGSUSED */
   3278 /*
   3279  * This function gets called just prior to running through the compression
   3280  * stage of the zio pipeline. If we're an indirect block comprised of only
   3281  * holes, then we want this indirect to be compressed away to a hole. In
   3282  * order to do that we must zero out any information about the holes that
   3283  * this indirect points to prior to before we try to compress it.
   3284  */
   3285 static void
   3286 dbuf_write_children_ready(zio_t *zio, arc_buf_t *buf, void *vdb)
   3287 {
   3288 	dmu_buf_impl_t *db = vdb;
   3289 	dnode_t *dn;
   3290 	blkptr_t *bp;
   3291 	uint64_t i;
   3292 	int epbs;
   3293 
   3294 	ASSERT3U(db->db_level, >, 0);
   3295 	DB_DNODE_ENTER(db);
   3296 	dn = DB_DNODE(db);
   3297 	epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
   3298 
   3299 	/* Determine if all our children are holes */
   3300 	for (i = 0, bp = db->db.db_data; i < 1 << epbs; i++, bp++) {
   3301 		if (!BP_IS_HOLE(bp))
   3302 			break;
   3303 	}
   3304 
   3305 	/*
   3306 	 * If all the children are holes, then zero them all out so that
   3307 	 * we may get compressed away.
   3308 	 */
   3309 	if (i == 1 << epbs) {
   3310 		/* didn't find any non-holes */
   3311 		bzero(db->db.db_data, db->db.db_size);
   3312 	}
   3313 	DB_DNODE_EXIT(db);
   3314 }
   3315 
   3316 /*
   3317  * The SPA will call this callback several times for each zio - once
   3318  * for every physical child i/o (zio->io_phys_children times).  This
   3319  * allows the DMU to monitor the progress of each logical i/o.  For example,
   3320  * there may be 2 copies of an indirect block, or many fragments of a RAID-Z
   3321  * block.  There may be a long delay before all copies/fragments are completed,
   3322  * so this callback allows us to retire dirty space gradually, as the physical
   3323  * i/os complete.
   3324  */
   3325 /* ARGSUSED */
   3326 static void
   3327 dbuf_write_physdone(zio_t *zio, arc_buf_t *buf, void *arg)
   3328 {
   3329 	dmu_buf_impl_t *db = arg;
   3330 	objset_t *os = db->db_objset;
   3331 	dsl_pool_t *dp = dmu_objset_pool(os);
   3332 	dbuf_dirty_record_t *dr;
   3333 	int delta = 0;
   3334 
   3335 	dr = db->db_data_pending;
   3336 	ASSERT3U(dr->dr_txg, ==, zio->io_txg);
   3337 
   3338 	/*
   3339 	 * The callback will be called io_phys_children times.  Retire one
   3340 	 * portion of our dirty space each time we are called.  Any rounding
   3341 	 * error will be cleaned up by dsl_pool_sync()'s call to
   3342 	 * dsl_pool_undirty_space().
   3343 	 */
   3344 	delta = dr->dr_accounted / zio->io_phys_children;
   3345 	dsl_pool_undirty_space(dp, delta, zio->io_txg);
   3346 }
   3347 
   3348 /* ARGSUSED */
   3349 static void
   3350 dbuf_write_done(zio_t *zio, arc_buf_t *buf, void *vdb)
   3351 {
   3352 	dmu_buf_impl_t *db = vdb;
   3353 	blkptr_t *bp_orig = &zio->io_bp_orig;
   3354 	blkptr_t *bp = db->db_blkptr;
   3355 	objset_t *os = db->db_objset;
   3356 	dmu_tx_t *tx = os->os_synctx;
   3357 	dbuf_dirty_record_t **drp, *dr;
   3358 
   3359 	ASSERT0(zio->io_error);
   3360 	ASSERT(db->db_blkptr == bp);
   3361 
   3362 	/*
   3363 	 * For nopwrites and rewrites we ensure that the bp matches our
   3364 	 * original and bypass all the accounting.
   3365 	 */
   3366 	if (zio->io_flags & (ZIO_FLAG_IO_REWRITE | ZIO_FLAG_NOPWRITE)) {
   3367 		ASSERT(BP_EQUAL(bp, bp_orig));
   3368 	} else {
   3369 		dsl_dataset_t *ds = os->os_dsl_dataset;
   3370 		(void) dsl_dataset_block_kill(ds, bp_orig, tx, B_TRUE);
   3371 		dsl_dataset_block_born(ds, bp, tx);
   3372 	}
   3373 
   3374 	mutex_enter(&db->db_mtx);
   3375 
   3376 	DBUF_VERIFY(db);
   3377 
   3378 	drp = &db->db_last_dirty;
   3379 	while ((dr = *drp) != db->db_data_pending)
   3380 		drp = &dr->dr_next;
   3381 	ASSERT(!list_link_active(&dr->dr_dirty_node));
   3382 	ASSERT(dr->dr_dbuf == db);
   3383 	ASSERT(dr->dr_next == NULL);
   3384 	*drp = dr->dr_next;
   3385 
   3386 #ifdef ZFS_DEBUG
   3387 	if (db->db_blkid == DMU_SPILL_BLKID) {
   3388 		dnode_t *dn;
   3389 
   3390 		DB_DNODE_ENTER(db);
   3391 		dn = DB_DNODE(db);
   3392 		ASSERT(dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR);
   3393 		ASSERT(!(BP_IS_HOLE(db->db_blkptr)) &&
   3394 		    db->db_blkptr == &dn->dn_phys->dn_spill);
   3395 		DB_DNODE_EXIT(db);
   3396 	}
   3397 #endif
   3398 
   3399 	if (db->db_level == 0) {
   3400 		ASSERT(db->db_blkid != DMU_BONUS_BLKID);
   3401 		ASSERT(dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN);
   3402 		if (db->db_state != DB_NOFILL) {
   3403 			if (dr->dt.dl.dr_data != db->db_buf)
   3404 				arc_buf_destroy(dr->dt.dl.dr_data, db);
   3405 		}
   3406 	} else {
   3407 		dnode_t *dn;
   3408 
   3409 		DB_DNODE_ENTER(db);
   3410 		dn = DB_DNODE(db);
   3411 		ASSERT(list_head(&dr->dt.di.dr_children) == NULL);
   3412 		ASSERT3U(db->db.db_size, ==, 1 << dn->dn_phys->dn_indblkshift);
   3413 		if (!BP_IS_HOLE(db->db_blkptr)) {
   3414 			int epbs =
   3415 			    dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
   3416 			ASSERT3U(db->db_blkid, <=,
   3417 			    dn->dn_phys->dn_maxblkid >> (db->db_level * epbs));
   3418 			ASSERT3U(BP_GET_LSIZE(db->db_blkptr), ==,
   3419 			    db->db.db_size);
   3420 		}
   3421 		DB_DNODE_EXIT(db);
   3422 		mutex_destroy(&dr->dt.di.dr_mtx);
   3423 		list_destroy(&dr->dt.di.dr_children);
   3424 	}
   3425 	kmem_free(dr, sizeof (dbuf_dirty_record_t));
   3426 
   3427 	cv_broadcast(&db->db_changed);
   3428 	ASSERT(db->db_dirtycnt > 0);
   3429 	db->db_dirtycnt -= 1;
   3430 	db->db_data_pending = NULL;
   3431 	dbuf_rele_and_unlock(db, (void *)(uintptr_t)tx->tx_txg);
   3432 }
   3433 
   3434 static void
   3435 dbuf_write_nofill_ready(zio_t *zio)
   3436 {
   3437 	dbuf_write_ready(zio, NULL, zio->io_private);
   3438 }
   3439 
   3440 static void
   3441 dbuf_write_nofill_done(zio_t *zio)
   3442 {
   3443 	dbuf_write_done(zio, NULL, zio->io_private);
   3444 }
   3445 
   3446 static void
   3447 dbuf_write_override_ready(zio_t *zio)
   3448 {
   3449 	dbuf_dirty_record_t *dr = zio->io_private;
   3450 	dmu_buf_impl_t *db = dr->dr_dbuf;
   3451 
   3452 	dbuf_write_ready(zio, NULL, db);
   3453 }
   3454 
   3455 static void
   3456 dbuf_write_override_done(zio_t *zio)
   3457 {
   3458 	dbuf_dirty_record_t *dr = zio->io_private;
   3459 	dmu_buf_impl_t *db = dr->dr_dbuf;
   3460 	blkptr_t *obp = &dr->dt.dl.dr_overridden_by;
   3461 
   3462 	mutex_enter(&db->db_mtx);
   3463 	if (!BP_EQUAL(zio->io_bp, obp)) {
   3464 		if (!BP_IS_HOLE(obp))
   3465 			dsl_free(spa_get_dsl(zio->io_spa), zio->io_txg, obp);
   3466 		arc_release(dr->dt.dl.dr_data, db);
   3467 	}
   3468 	mutex_exit(&db->db_mtx);
   3469 
   3470 	dbuf_write_done(zio, NULL, db);
   3471 }
   3472 
   3473 /* Issue I/O to commit a dirty buffer to disk. */
   3474 static void
   3475 dbuf_write(dbuf_dirty_record_t *dr, arc_buf_t *data, dmu_tx_t *tx)
   3476 {
   3477 	dmu_buf_impl_t *db = dr->dr_dbuf;
   3478 	dnode_t *dn;
   3479 	objset_t *os;
   3480 	dmu_buf_impl_t *parent = db->db_parent;
   3481 	uint64_t txg = tx->tx_txg;
   3482 	zbookmark_phys_t zb;
   3483 	zio_prop_t zp;
   3484 	zio_t *zio;
   3485 	int wp_flag = 0;
   3486 
   3487 	ASSERT(dmu_tx_is_syncing(tx));
   3488 
   3489 	DB_DNODE_ENTER(db);
   3490 	dn = DB_DNODE(db);
   3491 	os = dn->dn_objset;
   3492 
   3493 	if (db->db_state != DB_NOFILL) {
   3494 		if (db->db_level > 0 || dn->dn_type == DMU_OT_DNODE) {
   3495 			/*
   3496 			 * Private object buffers are released here rather
   3497 			 * than in dbuf_dirty() since they are only modified
   3498 			 * in the syncing context and we don't want the
   3499 			 * overhead of making multiple copies of the data.
   3500 			 */
   3501 			if (BP_IS_HOLE(db->db_blkptr)) {
   3502 				arc_buf_thaw(data);
   3503 			} else {
   3504 				dbuf_release_bp(db);
   3505 			}
   3506 		}
   3507 	}
   3508 
   3509 	if (parent != dn->dn_dbuf) {
   3510 		/* Our parent is an indirect block. */
   3511 		/* We have a dirty parent that has been scheduled for write. */
   3512 		ASSERT(parent && parent->db_data_pending);
   3513 		/* Our parent's buffer is one level closer to the dnode. */
   3514 		ASSERT(db->db_level == parent->db_level-1);
   3515 		/*
   3516 		 * We're about to modify our parent's db_data by modifying
   3517 		 * our block pointer, so the parent must be released.
   3518 		 */
   3519 		ASSERT(arc_released(parent->db_buf));
   3520 		zio = parent->db_data_pending->dr_zio;
   3521 	} else {
   3522 		/* Our parent is the dnode itself. */
   3523 		ASSERT((db->db_level == dn->dn_phys->dn_nlevels-1 &&
   3524 		    db->db_blkid != DMU_SPILL_BLKID) ||
   3525 		    (db->db_blkid == DMU_SPILL_BLKID && db->db_level == 0));
   3526 		if (db->db_blkid != DMU_SPILL_BLKID)
   3527 			ASSERT3P(db->db_blkptr, ==,
   3528 			    &dn->dn_phys->dn_blkptr[db->db_blkid]);
   3529 		zio = dn->dn_zio;
   3530 	}
   3531 
   3532 	ASSERT(db->db_level == 0 || data == db->db_buf);
   3533 	ASSERT3U(db->db_blkptr->blk_birth, <=, txg);
   3534 	ASSERT(zio);
   3535 
   3536 	SET_BOOKMARK(&zb, os->os_dsl_dataset ?
   3537 	    os->os_dsl_dataset->ds_object : DMU_META_OBJSET,
   3538 	    db->db.db_object, db->db_level, db->db_blkid);
   3539 
   3540 	if (db->db_blkid == DMU_SPILL_BLKID)
   3541 		wp_flag = WP_SPILL;
   3542 	wp_flag |= (db->db_state == DB_NOFILL) ? WP_NOFILL : 0;
   3543 
   3544 	dmu_write_policy(os, dn, db->db_level, wp_flag, &zp);
   3545 	DB_DNODE_EXIT(db);
   3546 
   3547 	/*
   3548 	 * We copy the blkptr now (rather than when we instantiate the dirty
   3549 	 * record), because its value can change between open context and
   3550 	 * syncing context. We do not need to hold dn_struct_rwlock to read
   3551 	 * db_blkptr because we are in syncing context.
   3552 	 */
   3553 	dr->dr_bp_copy = *db->db_blkptr;
   3554 
   3555 	if (db->db_level == 0 &&
   3556 	    dr->dt.dl.dr_override_state == DR_OVERRIDDEN) {
   3557 		/*
   3558 		 * The BP for this block has been provided by open context
   3559 		 * (by dmu_sync() or dmu_buf_write_embedded()).
   3560 		 */
   3561 		void *contents = (data != NULL) ? data->b_data : NULL;
   3562 
   3563 		dr->dr_zio = zio_write(zio, os->os_spa, txg,
   3564 		    &dr->dr_bp_copy, contents, db->db.db_size, &zp,
   3565 		    dbuf_write_override_ready, NULL, NULL,
   3566 		    dbuf_write_override_done,
   3567 		    dr, ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
   3568 		mutex_enter(&db->db_mtx);
   3569 		dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
   3570 		zio_write_override(dr->dr_zio, &dr->dt.dl.dr_overridden_by,
   3571 		    dr->dt.dl.dr_copies, dr->dt.dl.dr_nopwrite);
   3572 		mutex_exit(&db->db_mtx);
   3573 	} else if (db->db_state == DB_NOFILL) {
   3574 		ASSERT(zp.zp_checksum == ZIO_CHECKSUM_OFF ||
   3575 		    zp.zp_checksum == ZIO_CHECKSUM_NOPARITY);
   3576 		dr->dr_zio = zio_write(zio, os->os_spa, txg,
   3577 		    &dr->dr_bp_copy, NULL, db->db.db_size, &zp,
   3578 		    dbuf_write_nofill_ready, NULL, NULL,
   3579 		    dbuf_write_nofill_done, db,
   3580 		    ZIO_PRIORITY_ASYNC_WRITE,
   3581 		    ZIO_FLAG_MUSTSUCCEED | ZIO_FLAG_NODATA, &zb);
   3582 	} else {
   3583 		ASSERT(arc_released(data));
   3584 
   3585 		/*
   3586 		 * For indirect blocks, we want to setup the children
   3587 		 * ready callback so that we can properly handle an indirect
   3588 		 * block that only contains holes.
   3589 		 */
   3590 		arc_done_func_t *children_ready_cb = NULL;
   3591 		if (db->db_level != 0)
   3592 			children_ready_cb = dbuf_write_children_ready;
   3593 
   3594 		dr->dr_zio = arc_write(zio, os->os_spa, txg,
   3595 		    &dr->dr_bp_copy, data, DBUF_IS_L2CACHEABLE(db),
   3596 		    &zp, dbuf_write_ready, children_ready_cb,
   3597 		    dbuf_write_physdone, dbuf_write_done, db,
   3598 		    ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
   3599 	}
   3600 }
   3601