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