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