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