xref: /illumos-gate/usr/src/uts/common/fs/zfs/dbuf.c (revision 7b38fab6)
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, 2018 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 #include <sys/abd.h>
50 #include <sys/vdev.h>
51 #include <sys/cityhash.h>
52 #include <sys/spa_impl.h>
53 
54 static boolean_t dbuf_undirty(dmu_buf_impl_t *db, dmu_tx_t *tx);
55 static void dbuf_write(dbuf_dirty_record_t *dr, arc_buf_t *data, dmu_tx_t *tx);
56 
57 #ifndef __lint
58 extern inline void dmu_buf_init_user(dmu_buf_user_t *dbu,
59     dmu_buf_evict_func_t *evict_func_sync,
60     dmu_buf_evict_func_t *evict_func_async,
61     dmu_buf_t **clear_on_evict_dbufp);
62 #endif /* ! __lint */
63 
64 /*
65  * Global data structures and functions for the dbuf cache.
66  */
67 static kmem_cache_t *dbuf_kmem_cache;
68 static taskq_t *dbu_evict_taskq;
69 
70 static kthread_t *dbuf_cache_evict_thread;
71 static kmutex_t dbuf_evict_lock;
72 static kcondvar_t dbuf_evict_cv;
73 static boolean_t dbuf_evict_thread_exit;
74 
75 /*
76  * There are two dbuf caches; each dbuf can only be in one of them at a time.
77  *
78  * 1. Cache of metadata dbufs, to help make read-heavy administrative commands
79  *    from /sbin/zfs run faster. The "metadata cache" specifically stores dbufs
80  *    that represent the metadata that describes filesystems/snapshots/
81  *    bookmarks/properties/etc. We only evict from this cache when we export a
82  *    pool, to short-circuit as much I/O as possible for all administrative
83  *    commands that need the metadata. There is no eviction policy for this
84  *    cache, because we try to only include types in it which would occupy a
85  *    very small amount of space per object but create a large impact on the
86  *    performance of these commands. Instead, after it reaches a maximum size
87  *    (which should only happen on very small memory systems with a very large
88  *    number of filesystem objects), we stop taking new dbufs into the
89  *    metadata cache, instead putting them in the normal dbuf cache.
90  *
91  * 2. LRU cache of dbufs. The "dbuf cache" maintains a list of dbufs that
92  *    are not currently held but have been recently released. These dbufs
93  *    are not eligible for arc eviction until they are aged out of the cache.
94  *    Dbufs that are aged out of the cache will be immediately destroyed and
95  *    become eligible for arc eviction.
96  *
97  * Dbufs are added to these caches once the last hold is released. If a dbuf is
98  * later accessed and still exists in the dbuf cache, then it will be removed
99  * from the cache and later re-added to the head of the cache.
100  *
101  * If a given dbuf meets the requirements for the metadata cache, it will go
102  * there, otherwise it will be considered for the generic LRU dbuf cache. The
103  * caches and the refcounts tracking their sizes are stored in an array indexed
104  * by those caches' matching enum values (from dbuf_cached_state_t).
105  */
106 typedef struct dbuf_cache {
107 	multilist_t *cache;
108 	zfs_refcount_t size;
109 } dbuf_cache_t;
110 dbuf_cache_t dbuf_caches[DB_CACHE_MAX];
111 
112 /* Size limits for the caches */
113 uint64_t dbuf_cache_max_bytes = 0;
114 uint64_t dbuf_metadata_cache_max_bytes = 0;
115 /* Set the default sizes of the caches to log2 fraction of arc size */
116 int dbuf_cache_shift = 5;
117 int dbuf_metadata_cache_shift = 6;
118 
119 /*
120  * For diagnostic purposes, this is incremented whenever we can't add
121  * something to the metadata cache because it's full, and instead put
122  * the data in the regular dbuf cache.
123  */
124 uint64_t dbuf_metadata_cache_overflow;
125 
126 /*
127  * The LRU dbuf cache uses a three-stage eviction policy:
128  *	- A low water marker designates when the dbuf eviction thread
129  *	should stop evicting from the dbuf cache.
130  *	- When we reach the maximum size (aka mid water mark), we
131  *	signal the eviction thread to run.
132  *	- The high water mark indicates when the eviction thread
133  *	is unable to keep up with the incoming load and eviction must
134  *	happen in the context of the calling thread.
135  *
136  * The dbuf cache:
137  *                                                 (max size)
138  *                                      low water   mid water   hi water
139  * +----------------------------------------+----------+----------+
140  * |                                        |          |          |
141  * |                                        |          |          |
142  * |                                        |          |          |
143  * |                                        |          |          |
144  * +----------------------------------------+----------+----------+
145  *                                        stop        signal     evict
146  *                                      evicting     eviction   directly
147  *                                                    thread
148  *
149  * The high and low water marks indicate the operating range for the eviction
150  * thread. The low water mark is, by default, 90% of the total size of the
151  * cache and the high water mark is at 110% (both of these percentages can be
152  * changed by setting dbuf_cache_lowater_pct and dbuf_cache_hiwater_pct,
153  * respectively). The eviction thread will try to ensure that the cache remains
154  * within this range by waking up every second and checking if the cache is
155  * above the low water mark. The thread can also be woken up by callers adding
156  * elements into the cache if the cache is larger than the mid water (i.e max
157  * cache size). Once the eviction thread is woken up and eviction is required,
158  * it will continue evicting buffers until it's able to reduce the cache size
159  * to the low water mark. If the cache size continues to grow and hits the high
160  * water mark, then callers adding elments to the cache will begin to evict
161  * directly from the cache until the cache is no longer above the high water
162  * mark.
163  */
164 
165 /*
166  * The percentage above and below the maximum cache size.
167  */
168 uint_t dbuf_cache_hiwater_pct = 10;
169 uint_t dbuf_cache_lowater_pct = 10;
170 
171 /* ARGSUSED */
172 static int
173 dbuf_cons(void *vdb, void *unused, int kmflag)
174 {
175 	dmu_buf_impl_t *db = vdb;
176 	bzero(db, sizeof (dmu_buf_impl_t));
177 
178 	mutex_init(&db->db_mtx, NULL, MUTEX_DEFAULT, NULL);
179 	cv_init(&db->db_changed, NULL, CV_DEFAULT, NULL);
180 	multilist_link_init(&db->db_cache_link);
181 	zfs_refcount_create(&db->db_holds);
182 
183 	return (0);
184 }
185 
186 /* ARGSUSED */
187 static void
188 dbuf_dest(void *vdb, void *unused)
189 {
190 	dmu_buf_impl_t *db = vdb;
191 	mutex_destroy(&db->db_mtx);
192 	cv_destroy(&db->db_changed);
193 	ASSERT(!multilist_link_active(&db->db_cache_link));
194 	zfs_refcount_destroy(&db->db_holds);
195 }
196 
197 /*
198  * dbuf hash table routines
199  */
200 static dbuf_hash_table_t dbuf_hash_table;
201 
202 static uint64_t dbuf_hash_count;
203 
204 /*
205  * We use Cityhash for this. It's fast, and has good hash properties without
206  * requiring any large static buffers.
207  */
208 static uint64_t
209 dbuf_hash(void *os, uint64_t obj, uint8_t lvl, uint64_t blkid)
210 {
211 	return (cityhash4((uintptr_t)os, obj, (uint64_t)lvl, blkid));
212 }
213 
214 #define	DBUF_EQUAL(dbuf, os, obj, level, blkid)		\
215 	((dbuf)->db.db_object == (obj) &&		\
216 	(dbuf)->db_objset == (os) &&			\
217 	(dbuf)->db_level == (level) &&			\
218 	(dbuf)->db_blkid == (blkid))
219 
220 dmu_buf_impl_t *
221 dbuf_find(objset_t *os, uint64_t obj, uint8_t level, uint64_t blkid)
222 {
223 	dbuf_hash_table_t *h = &dbuf_hash_table;
224 	uint64_t hv = dbuf_hash(os, obj, level, blkid);
225 	uint64_t idx = hv & h->hash_table_mask;
226 	dmu_buf_impl_t *db;
227 
228 	mutex_enter(DBUF_HASH_MUTEX(h, idx));
229 	for (db = h->hash_table[idx]; db != NULL; db = db->db_hash_next) {
230 		if (DBUF_EQUAL(db, os, obj, level, blkid)) {
231 			mutex_enter(&db->db_mtx);
232 			if (db->db_state != DB_EVICTING) {
233 				mutex_exit(DBUF_HASH_MUTEX(h, idx));
234 				return (db);
235 			}
236 			mutex_exit(&db->db_mtx);
237 		}
238 	}
239 	mutex_exit(DBUF_HASH_MUTEX(h, idx));
240 	return (NULL);
241 }
242 
243 static dmu_buf_impl_t *
244 dbuf_find_bonus(objset_t *os, uint64_t object)
245 {
246 	dnode_t *dn;
247 	dmu_buf_impl_t *db = NULL;
248 
249 	if (dnode_hold(os, object, FTAG, &dn) == 0) {
250 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
251 		if (dn->dn_bonus != NULL) {
252 			db = dn->dn_bonus;
253 			mutex_enter(&db->db_mtx);
254 		}
255 		rw_exit(&dn->dn_struct_rwlock);
256 		dnode_rele(dn, FTAG);
257 	}
258 	return (db);
259 }
260 
261 /*
262  * Insert an entry into the hash table.  If there is already an element
263  * equal to elem in the hash table, then the already existing element
264  * will be returned and the new element will not be inserted.
265  * Otherwise returns NULL.
266  */
267 static dmu_buf_impl_t *
268 dbuf_hash_insert(dmu_buf_impl_t *db)
269 {
270 	dbuf_hash_table_t *h = &dbuf_hash_table;
271 	objset_t *os = db->db_objset;
272 	uint64_t obj = db->db.db_object;
273 	int level = db->db_level;
274 	uint64_t blkid = db->db_blkid;
275 	uint64_t hv = dbuf_hash(os, obj, level, blkid);
276 	uint64_t idx = hv & h->hash_table_mask;
277 	dmu_buf_impl_t *dbf;
278 
279 	mutex_enter(DBUF_HASH_MUTEX(h, idx));
280 	for (dbf = h->hash_table[idx]; dbf != NULL; dbf = dbf->db_hash_next) {
281 		if (DBUF_EQUAL(dbf, os, obj, level, blkid)) {
282 			mutex_enter(&dbf->db_mtx);
283 			if (dbf->db_state != DB_EVICTING) {
284 				mutex_exit(DBUF_HASH_MUTEX(h, idx));
285 				return (dbf);
286 			}
287 			mutex_exit(&dbf->db_mtx);
288 		}
289 	}
290 
291 	mutex_enter(&db->db_mtx);
292 	db->db_hash_next = h->hash_table[idx];
293 	h->hash_table[idx] = db;
294 	mutex_exit(DBUF_HASH_MUTEX(h, idx));
295 	atomic_inc_64(&dbuf_hash_count);
296 
297 	return (NULL);
298 }
299 
300 /*
301  * Remove an entry from the hash table.  It must be in the EVICTING state.
302  */
303 static void
304 dbuf_hash_remove(dmu_buf_impl_t *db)
305 {
306 	dbuf_hash_table_t *h = &dbuf_hash_table;
307 	uint64_t hv = dbuf_hash(db->db_objset, db->db.db_object,
308 	    db->db_level, db->db_blkid);
309 	uint64_t idx = hv & h->hash_table_mask;
310 	dmu_buf_impl_t *dbf, **dbp;
311 
312 	/*
313 	 * We musn't hold db_mtx to maintain lock ordering:
314 	 * DBUF_HASH_MUTEX > db_mtx.
315 	 */
316 	ASSERT(zfs_refcount_is_zero(&db->db_holds));
317 	ASSERT(db->db_state == DB_EVICTING);
318 	ASSERT(!MUTEX_HELD(&db->db_mtx));
319 
320 	mutex_enter(DBUF_HASH_MUTEX(h, idx));
321 	dbp = &h->hash_table[idx];
322 	while ((dbf = *dbp) != db) {
323 		dbp = &dbf->db_hash_next;
324 		ASSERT(dbf != NULL);
325 	}
326 	*dbp = db->db_hash_next;
327 	db->db_hash_next = NULL;
328 	mutex_exit(DBUF_HASH_MUTEX(h, idx));
329 	atomic_dec_64(&dbuf_hash_count);
330 }
331 
332 typedef enum {
333 	DBVU_EVICTING,
334 	DBVU_NOT_EVICTING
335 } dbvu_verify_type_t;
336 
337 static void
338 dbuf_verify_user(dmu_buf_impl_t *db, dbvu_verify_type_t verify_type)
339 {
340 #ifdef ZFS_DEBUG
341 	int64_t holds;
342 
343 	if (db->db_user == NULL)
344 		return;
345 
346 	/* Only data blocks support the attachment of user data. */
347 	ASSERT(db->db_level == 0);
348 
349 	/* Clients must resolve a dbuf before attaching user data. */
350 	ASSERT(db->db.db_data != NULL);
351 	ASSERT3U(db->db_state, ==, DB_CACHED);
352 
353 	holds = zfs_refcount_count(&db->db_holds);
354 	if (verify_type == DBVU_EVICTING) {
355 		/*
356 		 * Immediate eviction occurs when holds == dirtycnt.
357 		 * For normal eviction buffers, holds is zero on
358 		 * eviction, except when dbuf_fix_old_data() calls
359 		 * dbuf_clear_data().  However, the hold count can grow
360 		 * during eviction even though db_mtx is held (see
361 		 * dmu_bonus_hold() for an example), so we can only
362 		 * test the generic invariant that holds >= dirtycnt.
363 		 */
364 		ASSERT3U(holds, >=, db->db_dirtycnt);
365 	} else {
366 		if (db->db_user_immediate_evict == TRUE)
367 			ASSERT3U(holds, >=, db->db_dirtycnt);
368 		else
369 			ASSERT3U(holds, >, 0);
370 	}
371 #endif
372 }
373 
374 static void
375 dbuf_evict_user(dmu_buf_impl_t *db)
376 {
377 	dmu_buf_user_t *dbu = db->db_user;
378 
379 	ASSERT(MUTEX_HELD(&db->db_mtx));
380 
381 	if (dbu == NULL)
382 		return;
383 
384 	dbuf_verify_user(db, DBVU_EVICTING);
385 	db->db_user = NULL;
386 
387 #ifdef ZFS_DEBUG
388 	if (dbu->dbu_clear_on_evict_dbufp != NULL)
389 		*dbu->dbu_clear_on_evict_dbufp = NULL;
390 #endif
391 
392 	/*
393 	 * There are two eviction callbacks - one that we call synchronously
394 	 * and one that we invoke via a taskq.  The async one is useful for
395 	 * avoiding lock order reversals and limiting stack depth.
396 	 *
397 	 * Note that if we have a sync callback but no async callback,
398 	 * it's likely that the sync callback will free the structure
399 	 * containing the dbu.  In that case we need to take care to not
400 	 * dereference dbu after calling the sync evict func.
401 	 */
402 	boolean_t has_async = (dbu->dbu_evict_func_async != NULL);
403 
404 	if (dbu->dbu_evict_func_sync != NULL)
405 		dbu->dbu_evict_func_sync(dbu);
406 
407 	if (has_async) {
408 		taskq_dispatch_ent(dbu_evict_taskq, dbu->dbu_evict_func_async,
409 		    dbu, 0, &dbu->dbu_tqent);
410 	}
411 }
412 
413 boolean_t
414 dbuf_is_metadata(dmu_buf_impl_t *db)
415 {
416 	if (db->db_level > 0) {
417 		return (B_TRUE);
418 	} else {
419 		boolean_t is_metadata;
420 
421 		DB_DNODE_ENTER(db);
422 		is_metadata = DMU_OT_IS_METADATA(DB_DNODE(db)->dn_type);
423 		DB_DNODE_EXIT(db);
424 
425 		return (is_metadata);
426 	}
427 }
428 
429 /*
430  * This returns whether this dbuf should be stored in the metadata cache, which
431  * is based on whether it's from one of the dnode types that store data related
432  * to traversing dataset hierarchies.
433  */
434 static boolean_t
435 dbuf_include_in_metadata_cache(dmu_buf_impl_t *db)
436 {
437 	DB_DNODE_ENTER(db);
438 	dmu_object_type_t type = DB_DNODE(db)->dn_type;
439 	DB_DNODE_EXIT(db);
440 
441 	/* Check if this dbuf is one of the types we care about */
442 	if (DMU_OT_IS_METADATA_CACHED(type)) {
443 		/* If we hit this, then we set something up wrong in dmu_ot */
444 		ASSERT(DMU_OT_IS_METADATA(type));
445 
446 		/*
447 		 * Sanity check for small-memory systems: don't allocate too
448 		 * much memory for this purpose.
449 		 */
450 		if (zfs_refcount_count(
451 		    &dbuf_caches[DB_DBUF_METADATA_CACHE].size) >
452 		    dbuf_metadata_cache_max_bytes) {
453 			dbuf_metadata_cache_overflow++;
454 			DTRACE_PROBE1(dbuf__metadata__cache__overflow,
455 			    dmu_buf_impl_t *, db);
456 			return (B_FALSE);
457 		}
458 
459 		return (B_TRUE);
460 	}
461 
462 	return (B_FALSE);
463 }
464 
465 /*
466  * This function *must* return indices evenly distributed between all
467  * sublists of the multilist. This is needed due to how the dbuf eviction
468  * code is laid out; dbuf_evict_thread() assumes dbufs are evenly
469  * distributed between all sublists and uses this assumption when
470  * deciding which sublist to evict from and how much to evict from it.
471  */
472 unsigned int
473 dbuf_cache_multilist_index_func(multilist_t *ml, void *obj)
474 {
475 	dmu_buf_impl_t *db = obj;
476 
477 	/*
478 	 * The assumption here, is the hash value for a given
479 	 * dmu_buf_impl_t will remain constant throughout it's lifetime
480 	 * (i.e. it's objset, object, level and blkid fields don't change).
481 	 * Thus, we don't need to store the dbuf's sublist index
482 	 * on insertion, as this index can be recalculated on removal.
483 	 *
484 	 * Also, the low order bits of the hash value are thought to be
485 	 * distributed evenly. Otherwise, in the case that the multilist
486 	 * has a power of two number of sublists, each sublists' usage
487 	 * would not be evenly distributed.
488 	 */
489 	return (dbuf_hash(db->db_objset, db->db.db_object,
490 	    db->db_level, db->db_blkid) %
491 	    multilist_get_num_sublists(ml));
492 }
493 
494 static inline boolean_t
495 dbuf_cache_above_hiwater(void)
496 {
497 	uint64_t dbuf_cache_hiwater_bytes =
498 	    (dbuf_cache_max_bytes * dbuf_cache_hiwater_pct) / 100;
499 
500 	return (zfs_refcount_count(&dbuf_caches[DB_DBUF_CACHE].size) >
501 	    dbuf_cache_max_bytes + dbuf_cache_hiwater_bytes);
502 }
503 
504 static inline boolean_t
505 dbuf_cache_above_lowater(void)
506 {
507 	uint64_t dbuf_cache_lowater_bytes =
508 	    (dbuf_cache_max_bytes * dbuf_cache_lowater_pct) / 100;
509 
510 	return (zfs_refcount_count(&dbuf_caches[DB_DBUF_CACHE].size) >
511 	    dbuf_cache_max_bytes - dbuf_cache_lowater_bytes);
512 }
513 
514 /*
515  * Evict the oldest eligible dbuf from the dbuf cache.
516  */
517 static void
518 dbuf_evict_one(void)
519 {
520 	int idx = multilist_get_random_index(dbuf_caches[DB_DBUF_CACHE].cache);
521 	multilist_sublist_t *mls = multilist_sublist_lock(
522 	    dbuf_caches[DB_DBUF_CACHE].cache, idx);
523 
524 	ASSERT(!MUTEX_HELD(&dbuf_evict_lock));
525 
526 	dmu_buf_impl_t *db = multilist_sublist_tail(mls);
527 	while (db != NULL && mutex_tryenter(&db->db_mtx) == 0) {
528 		db = multilist_sublist_prev(mls, db);
529 	}
530 
531 	DTRACE_PROBE2(dbuf__evict__one, dmu_buf_impl_t *, db,
532 	    multilist_sublist_t *, mls);
533 
534 	if (db != NULL) {
535 		multilist_sublist_remove(mls, db);
536 		multilist_sublist_unlock(mls);
537 		(void) zfs_refcount_remove_many(
538 		    &dbuf_caches[DB_DBUF_CACHE].size,
539 		    db->db.db_size, db);
540 		ASSERT3U(db->db_caching_status, ==, DB_DBUF_CACHE);
541 		db->db_caching_status = DB_NO_CACHE;
542 		dbuf_destroy(db);
543 	} else {
544 		multilist_sublist_unlock(mls);
545 	}
546 }
547 
548 /*
549  * The dbuf evict thread is responsible for aging out dbufs from the
550  * cache. Once the cache has reached it's maximum size, dbufs are removed
551  * and destroyed. The eviction thread will continue running until the size
552  * of the dbuf cache is at or below the maximum size. Once the dbuf is aged
553  * out of the cache it is destroyed and becomes eligible for arc eviction.
554  */
555 /* ARGSUSED */
556 static void
557 dbuf_evict_thread(void *unused)
558 {
559 	callb_cpr_t cpr;
560 
561 	CALLB_CPR_INIT(&cpr, &dbuf_evict_lock, callb_generic_cpr, FTAG);
562 
563 	mutex_enter(&dbuf_evict_lock);
564 	while (!dbuf_evict_thread_exit) {
565 		while (!dbuf_cache_above_lowater() && !dbuf_evict_thread_exit) {
566 			CALLB_CPR_SAFE_BEGIN(&cpr);
567 			(void) cv_timedwait_hires(&dbuf_evict_cv,
568 			    &dbuf_evict_lock, SEC2NSEC(1), MSEC2NSEC(1), 0);
569 			CALLB_CPR_SAFE_END(&cpr, &dbuf_evict_lock);
570 		}
571 		mutex_exit(&dbuf_evict_lock);
572 
573 		/*
574 		 * Keep evicting as long as we're above the low water mark
575 		 * for the cache. We do this without holding the locks to
576 		 * minimize lock contention.
577 		 */
578 		while (dbuf_cache_above_lowater() && !dbuf_evict_thread_exit) {
579 			dbuf_evict_one();
580 		}
581 
582 		mutex_enter(&dbuf_evict_lock);
583 	}
584 
585 	dbuf_evict_thread_exit = B_FALSE;
586 	cv_broadcast(&dbuf_evict_cv);
587 	CALLB_CPR_EXIT(&cpr);	/* drops dbuf_evict_lock */
588 	thread_exit();
589 }
590 
591 /*
592  * Wake up the dbuf eviction thread if the dbuf cache is at its max size.
593  * If the dbuf cache is at its high water mark, then evict a dbuf from the
594  * dbuf cache using the callers context.
595  */
596 static void
597 dbuf_evict_notify(void)
598 {
599 	/*
600 	 * We check if we should evict without holding the dbuf_evict_lock,
601 	 * because it's OK to occasionally make the wrong decision here,
602 	 * and grabbing the lock results in massive lock contention.
603 	 */
604 	if (zfs_refcount_count(&dbuf_caches[DB_DBUF_CACHE].size) >
605 	    dbuf_cache_max_bytes) {
606 		if (dbuf_cache_above_hiwater())
607 			dbuf_evict_one();
608 		cv_signal(&dbuf_evict_cv);
609 	}
610 }
611 
612 void
613 dbuf_init(void)
614 {
615 	uint64_t hsize = 1ULL << 16;
616 	dbuf_hash_table_t *h = &dbuf_hash_table;
617 	int i;
618 
619 	/*
620 	 * The hash table is big enough to fill all of physical memory
621 	 * with an average 4K block size.  The table will take up
622 	 * totalmem*sizeof(void*)/4K (i.e. 2MB/GB with 8-byte pointers).
623 	 */
624 	while (hsize * 4096 < physmem * PAGESIZE)
625 		hsize <<= 1;
626 
627 retry:
628 	h->hash_table_mask = hsize - 1;
629 	h->hash_table = kmem_zalloc(hsize * sizeof (void *), KM_NOSLEEP);
630 	if (h->hash_table == NULL) {
631 		/* XXX - we should really return an error instead of assert */
632 		ASSERT(hsize > (1ULL << 10));
633 		hsize >>= 1;
634 		goto retry;
635 	}
636 
637 	dbuf_kmem_cache = kmem_cache_create("dmu_buf_impl_t",
638 	    sizeof (dmu_buf_impl_t),
639 	    0, dbuf_cons, dbuf_dest, NULL, NULL, NULL, 0);
640 
641 	for (i = 0; i < DBUF_MUTEXES; i++)
642 		mutex_init(&h->hash_mutexes[i], NULL, MUTEX_DEFAULT, NULL);
643 
644 	/*
645 	 * Setup the parameters for the dbuf caches. We set the sizes of the
646 	 * dbuf cache and the metadata cache to 1/32nd and 1/16th (default)
647 	 * of the size of the ARC, respectively. If the values are set in
648 	 * /etc/system and they're not greater than the size of the ARC, then
649 	 * we honor that value.
650 	 */
651 	if (dbuf_cache_max_bytes == 0 ||
652 	    dbuf_cache_max_bytes >= arc_max_bytes())  {
653 		dbuf_cache_max_bytes = arc_max_bytes() >> dbuf_cache_shift;
654 	}
655 	if (dbuf_metadata_cache_max_bytes == 0 ||
656 	    dbuf_metadata_cache_max_bytes >= arc_max_bytes()) {
657 		dbuf_metadata_cache_max_bytes =
658 		    arc_max_bytes() >> dbuf_metadata_cache_shift;
659 	}
660 
661 	/*
662 	 * All entries are queued via taskq_dispatch_ent(), so min/maxalloc
663 	 * configuration is not required.
664 	 */
665 	dbu_evict_taskq = taskq_create("dbu_evict", 1, minclsyspri, 0, 0, 0);
666 
667 	for (dbuf_cached_state_t dcs = 0; dcs < DB_CACHE_MAX; dcs++) {
668 		dbuf_caches[dcs].cache =
669 		    multilist_create(sizeof (dmu_buf_impl_t),
670 		    offsetof(dmu_buf_impl_t, db_cache_link),
671 		    dbuf_cache_multilist_index_func);
672 		zfs_refcount_create(&dbuf_caches[dcs].size);
673 	}
674 
675 	dbuf_evict_thread_exit = B_FALSE;
676 	mutex_init(&dbuf_evict_lock, NULL, MUTEX_DEFAULT, NULL);
677 	cv_init(&dbuf_evict_cv, NULL, CV_DEFAULT, NULL);
678 	dbuf_cache_evict_thread = thread_create(NULL, 0, dbuf_evict_thread,
679 	    NULL, 0, &p0, TS_RUN, minclsyspri);
680 }
681 
682 void
683 dbuf_fini(void)
684 {
685 	dbuf_hash_table_t *h = &dbuf_hash_table;
686 	int i;
687 
688 	for (i = 0; i < DBUF_MUTEXES; i++)
689 		mutex_destroy(&h->hash_mutexes[i]);
690 	kmem_free(h->hash_table, (h->hash_table_mask + 1) * sizeof (void *));
691 	kmem_cache_destroy(dbuf_kmem_cache);
692 	taskq_destroy(dbu_evict_taskq);
693 
694 	mutex_enter(&dbuf_evict_lock);
695 	dbuf_evict_thread_exit = B_TRUE;
696 	while (dbuf_evict_thread_exit) {
697 		cv_signal(&dbuf_evict_cv);
698 		cv_wait(&dbuf_evict_cv, &dbuf_evict_lock);
699 	}
700 	mutex_exit(&dbuf_evict_lock);
701 
702 	mutex_destroy(&dbuf_evict_lock);
703 	cv_destroy(&dbuf_evict_cv);
704 
705 	for (dbuf_cached_state_t dcs = 0; dcs < DB_CACHE_MAX; dcs++) {
706 		zfs_refcount_destroy(&dbuf_caches[dcs].size);
707 		multilist_destroy(dbuf_caches[dcs].cache);
708 	}
709 }
710 
711 /*
712  * Other stuff.
713  */
714 
715 #ifdef ZFS_DEBUG
716 static void
717 dbuf_verify(dmu_buf_impl_t *db)
718 {
719 	dnode_t *dn;
720 	dbuf_dirty_record_t *dr;
721 
722 	ASSERT(MUTEX_HELD(&db->db_mtx));
723 
724 	if (!(zfs_flags & ZFS_DEBUG_DBUF_VERIFY))
725 		return;
726 
727 	ASSERT(db->db_objset != NULL);
728 	DB_DNODE_ENTER(db);
729 	dn = DB_DNODE(db);
730 	if (dn == NULL) {
731 		ASSERT(db->db_parent == NULL);
732 		ASSERT(db->db_blkptr == NULL);
733 	} else {
734 		ASSERT3U(db->db.db_object, ==, dn->dn_object);
735 		ASSERT3P(db->db_objset, ==, dn->dn_objset);
736 		ASSERT3U(db->db_level, <, dn->dn_nlevels);
737 		ASSERT(db->db_blkid == DMU_BONUS_BLKID ||
738 		    db->db_blkid == DMU_SPILL_BLKID ||
739 		    !avl_is_empty(&dn->dn_dbufs));
740 	}
741 	if (db->db_blkid == DMU_BONUS_BLKID) {
742 		ASSERT(dn != NULL);
743 		ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
744 		ASSERT3U(db->db.db_offset, ==, DMU_BONUS_BLKID);
745 	} else if (db->db_blkid == DMU_SPILL_BLKID) {
746 		ASSERT(dn != NULL);
747 		ASSERT0(db->db.db_offset);
748 	} else {
749 		ASSERT3U(db->db.db_offset, ==, db->db_blkid * db->db.db_size);
750 	}
751 
752 	for (dr = db->db_data_pending; dr != NULL; dr = dr->dr_next)
753 		ASSERT(dr->dr_dbuf == db);
754 
755 	for (dr = db->db_last_dirty; dr != NULL; dr = dr->dr_next)
756 		ASSERT(dr->dr_dbuf == db);
757 
758 	/*
759 	 * We can't assert that db_size matches dn_datablksz because it
760 	 * can be momentarily different when another thread is doing
761 	 * dnode_set_blksz().
762 	 */
763 	if (db->db_level == 0 && db->db.db_object == DMU_META_DNODE_OBJECT) {
764 		dr = db->db_data_pending;
765 		/*
766 		 * It should only be modified in syncing context, so
767 		 * make sure we only have one copy of the data.
768 		 */
769 		ASSERT(dr == NULL || dr->dt.dl.dr_data == db->db_buf);
770 	}
771 
772 	/* verify db->db_blkptr */
773 	if (db->db_blkptr) {
774 		if (db->db_parent == dn->dn_dbuf) {
775 			/* db is pointed to by the dnode */
776 			/* ASSERT3U(db->db_blkid, <, dn->dn_nblkptr); */
777 			if (DMU_OBJECT_IS_SPECIAL(db->db.db_object))
778 				ASSERT(db->db_parent == NULL);
779 			else
780 				ASSERT(db->db_parent != NULL);
781 			if (db->db_blkid != DMU_SPILL_BLKID)
782 				ASSERT3P(db->db_blkptr, ==,
783 				    &dn->dn_phys->dn_blkptr[db->db_blkid]);
784 		} else {
785 			/* db is pointed to by an indirect block */
786 			int epb = db->db_parent->db.db_size >> SPA_BLKPTRSHIFT;
787 			ASSERT3U(db->db_parent->db_level, ==, db->db_level+1);
788 			ASSERT3U(db->db_parent->db.db_object, ==,
789 			    db->db.db_object);
790 			/*
791 			 * dnode_grow_indblksz() can make this fail if we don't
792 			 * have the struct_rwlock.  XXX indblksz no longer
793 			 * grows.  safe to do this now?
794 			 */
795 			if (RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
796 				ASSERT3P(db->db_blkptr, ==,
797 				    ((blkptr_t *)db->db_parent->db.db_data +
798 				    db->db_blkid % epb));
799 			}
800 		}
801 	}
802 	if ((db->db_blkptr == NULL || BP_IS_HOLE(db->db_blkptr)) &&
803 	    (db->db_buf == NULL || db->db_buf->b_data) &&
804 	    db->db.db_data && db->db_blkid != DMU_BONUS_BLKID &&
805 	    db->db_state != DB_FILL && !dn->dn_free_txg) {
806 		/*
807 		 * If the blkptr isn't set but they have nonzero data,
808 		 * it had better be dirty, otherwise we'll lose that
809 		 * data when we evict this buffer.
810 		 *
811 		 * There is an exception to this rule for indirect blocks; in
812 		 * this case, if the indirect block is a hole, we fill in a few
813 		 * fields on each of the child blocks (importantly, birth time)
814 		 * to prevent hole birth times from being lost when you
815 		 * partially fill in a hole.
816 		 */
817 		if (db->db_dirtycnt == 0) {
818 			if (db->db_level == 0) {
819 				uint64_t *buf = db->db.db_data;
820 				int i;
821 
822 				for (i = 0; i < db->db.db_size >> 3; i++) {
823 					ASSERT(buf[i] == 0);
824 				}
825 			} else {
826 				blkptr_t *bps = db->db.db_data;
827 				ASSERT3U(1 << DB_DNODE(db)->dn_indblkshift, ==,
828 				    db->db.db_size);
829 				/*
830 				 * We want to verify that all the blkptrs in the
831 				 * indirect block are holes, but we may have
832 				 * automatically set up a few fields for them.
833 				 * We iterate through each blkptr and verify
834 				 * they only have those fields set.
835 				 */
836 				for (int i = 0;
837 				    i < db->db.db_size / sizeof (blkptr_t);
838 				    i++) {
839 					blkptr_t *bp = &bps[i];
840 					ASSERT(ZIO_CHECKSUM_IS_ZERO(
841 					    &bp->blk_cksum));
842 					ASSERT(
843 					    DVA_IS_EMPTY(&bp->blk_dva[0]) &&
844 					    DVA_IS_EMPTY(&bp->blk_dva[1]) &&
845 					    DVA_IS_EMPTY(&bp->blk_dva[2]));
846 					ASSERT0(bp->blk_fill);
847 					ASSERT0(bp->blk_pad[0]);
848 					ASSERT0(bp->blk_pad[1]);
849 					ASSERT(!BP_IS_EMBEDDED(bp));
850 					ASSERT(BP_IS_HOLE(bp));
851 					ASSERT0(bp->blk_phys_birth);
852 				}
853 			}
854 		}
855 	}
856 	DB_DNODE_EXIT(db);
857 }
858 #endif
859 
860 static void
861 dbuf_clear_data(dmu_buf_impl_t *db)
862 {
863 	ASSERT(MUTEX_HELD(&db->db_mtx));
864 	dbuf_evict_user(db);
865 	ASSERT3P(db->db_buf, ==, NULL);
866 	db->db.db_data = NULL;
867 	if (db->db_state != DB_NOFILL)
868 		db->db_state = DB_UNCACHED;
869 }
870 
871 static void
872 dbuf_set_data(dmu_buf_impl_t *db, arc_buf_t *buf)
873 {
874 	ASSERT(MUTEX_HELD(&db->db_mtx));
875 	ASSERT(buf != NULL);
876 
877 	db->db_buf = buf;
878 	ASSERT(buf->b_data != NULL);
879 	db->db.db_data = buf->b_data;
880 }
881 
882 /*
883  * Loan out an arc_buf for read.  Return the loaned arc_buf.
884  */
885 arc_buf_t *
886 dbuf_loan_arcbuf(dmu_buf_impl_t *db)
887 {
888 	arc_buf_t *abuf;
889 
890 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
891 	mutex_enter(&db->db_mtx);
892 	if (arc_released(db->db_buf) || zfs_refcount_count(&db->db_holds) > 1) {
893 		int blksz = db->db.db_size;
894 		spa_t *spa = db->db_objset->os_spa;
895 
896 		mutex_exit(&db->db_mtx);
897 		abuf = arc_loan_buf(spa, B_FALSE, blksz);
898 		bcopy(db->db.db_data, abuf->b_data, blksz);
899 	} else {
900 		abuf = db->db_buf;
901 		arc_loan_inuse_buf(abuf, db);
902 		db->db_buf = NULL;
903 		dbuf_clear_data(db);
904 		mutex_exit(&db->db_mtx);
905 	}
906 	return (abuf);
907 }
908 
909 /*
910  * Calculate which level n block references the data at the level 0 offset
911  * provided.
912  */
913 uint64_t
914 dbuf_whichblock(dnode_t *dn, int64_t level, uint64_t offset)
915 {
916 	if (dn->dn_datablkshift != 0 && dn->dn_indblkshift != 0) {
917 		/*
918 		 * The level n blkid is equal to the level 0 blkid divided by
919 		 * the number of level 0s in a level n block.
920 		 *
921 		 * The level 0 blkid is offset >> datablkshift =
922 		 * offset / 2^datablkshift.
923 		 *
924 		 * The number of level 0s in a level n is the number of block
925 		 * pointers in an indirect block, raised to the power of level.
926 		 * This is 2^(indblkshift - SPA_BLKPTRSHIFT)^level =
927 		 * 2^(level*(indblkshift - SPA_BLKPTRSHIFT)).
928 		 *
929 		 * Thus, the level n blkid is: offset /
930 		 * ((2^datablkshift)*(2^(level*(indblkshift - SPA_BLKPTRSHIFT)))
931 		 * = offset / 2^(datablkshift + level *
932 		 *   (indblkshift - SPA_BLKPTRSHIFT))
933 		 * = offset >> (datablkshift + level *
934 		 *   (indblkshift - SPA_BLKPTRSHIFT))
935 		 */
936 		return (offset >> (dn->dn_datablkshift + level *
937 		    (dn->dn_indblkshift - SPA_BLKPTRSHIFT)));
938 	} else {
939 		ASSERT3U(offset, <, dn->dn_datablksz);
940 		return (0);
941 	}
942 }
943 
944 static void
945 dbuf_read_done(zio_t *zio, arc_buf_t *buf, void *vdb)
946 {
947 	dmu_buf_impl_t *db = vdb;
948 
949 	mutex_enter(&db->db_mtx);
950 	ASSERT3U(db->db_state, ==, DB_READ);
951 	/*
952 	 * All reads are synchronous, so we must have a hold on the dbuf
953 	 */
954 	ASSERT(zfs_refcount_count(&db->db_holds) > 0);
955 	ASSERT(db->db_buf == NULL);
956 	ASSERT(db->db.db_data == NULL);
957 	if (buf == NULL) {
958 		/* i/o error */
959 		ASSERT(zio == NULL || zio->io_error != 0);
960 		ASSERT(db->db_blkid != DMU_BONUS_BLKID);
961 		ASSERT3P(db->db_buf, ==, NULL);
962 		db->db_state = DB_UNCACHED;
963 	} else if (db->db_level == 0 && db->db_freed_in_flight) {
964 		/* freed in flight */
965 		ASSERT(zio == NULL || zio->io_error == 0);
966 		arc_release(buf, db);
967 		bzero(buf->b_data, db->db.db_size);
968 		arc_buf_freeze(buf);
969 		db->db_freed_in_flight = FALSE;
970 		dbuf_set_data(db, buf);
971 		db->db_state = DB_CACHED;
972 	} else {
973 		/* success */
974 		ASSERT(zio == NULL || zio->io_error == 0);
975 		dbuf_set_data(db, buf);
976 		db->db_state = DB_CACHED;
977 	}
978 	cv_broadcast(&db->db_changed);
979 	dbuf_rele_and_unlock(db, NULL, B_FALSE);
980 }
981 
982 static void
983 dbuf_read_impl(dmu_buf_impl_t *db, zio_t *zio, uint32_t flags)
984 {
985 	dnode_t *dn;
986 	zbookmark_phys_t zb;
987 	arc_flags_t aflags = ARC_FLAG_NOWAIT;
988 
989 	DB_DNODE_ENTER(db);
990 	dn = DB_DNODE(db);
991 	ASSERT(!zfs_refcount_is_zero(&db->db_holds));
992 	/* We need the struct_rwlock to prevent db_blkptr from changing. */
993 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
994 	ASSERT(MUTEX_HELD(&db->db_mtx));
995 	ASSERT(db->db_state == DB_UNCACHED);
996 	ASSERT(db->db_buf == NULL);
997 
998 	if (db->db_blkid == DMU_BONUS_BLKID) {
999 		/*
1000 		 * The bonus length stored in the dnode may be less than
1001 		 * the maximum available space in the bonus buffer.
1002 		 */
1003 		int bonuslen = MIN(dn->dn_bonuslen, dn->dn_phys->dn_bonuslen);
1004 		int max_bonuslen = DN_SLOTS_TO_BONUSLEN(dn->dn_num_slots);
1005 
1006 		ASSERT3U(bonuslen, <=, db->db.db_size);
1007 		db->db.db_data = zio_buf_alloc(max_bonuslen);
1008 		arc_space_consume(max_bonuslen, ARC_SPACE_BONUS);
1009 		if (bonuslen < max_bonuslen)
1010 			bzero(db->db.db_data, max_bonuslen);
1011 		if (bonuslen)
1012 			bcopy(DN_BONUS(dn->dn_phys), db->db.db_data, bonuslen);
1013 		DB_DNODE_EXIT(db);
1014 		db->db_state = DB_CACHED;
1015 		mutex_exit(&db->db_mtx);
1016 		return;
1017 	}
1018 
1019 	/*
1020 	 * Recheck BP_IS_HOLE() after dnode_block_freed() in case dnode_sync()
1021 	 * processes the delete record and clears the bp while we are waiting
1022 	 * for the dn_mtx (resulting in a "no" from block_freed).
1023 	 */
1024 	if (db->db_blkptr == NULL || BP_IS_HOLE(db->db_blkptr) ||
1025 	    (db->db_level == 0 && (dnode_block_freed(dn, db->db_blkid) ||
1026 	    BP_IS_HOLE(db->db_blkptr)))) {
1027 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1028 
1029 		dbuf_set_data(db, arc_alloc_buf(db->db_objset->os_spa, db, type,
1030 		    db->db.db_size));
1031 		bzero(db->db.db_data, db->db.db_size);
1032 
1033 		if (db->db_blkptr != NULL && db->db_level > 0 &&
1034 		    BP_IS_HOLE(db->db_blkptr) &&
1035 		    db->db_blkptr->blk_birth != 0) {
1036 			blkptr_t *bps = db->db.db_data;
1037 			for (int i = 0; i < ((1 <<
1038 			    DB_DNODE(db)->dn_indblkshift) / sizeof (blkptr_t));
1039 			    i++) {
1040 				blkptr_t *bp = &bps[i];
1041 				ASSERT3U(BP_GET_LSIZE(db->db_blkptr), ==,
1042 				    1 << dn->dn_indblkshift);
1043 				BP_SET_LSIZE(bp,
1044 				    BP_GET_LEVEL(db->db_blkptr) == 1 ?
1045 				    dn->dn_datablksz :
1046 				    BP_GET_LSIZE(db->db_blkptr));
1047 				BP_SET_TYPE(bp, BP_GET_TYPE(db->db_blkptr));
1048 				BP_SET_LEVEL(bp,
1049 				    BP_GET_LEVEL(db->db_blkptr) - 1);
1050 				BP_SET_BIRTH(bp, db->db_blkptr->blk_birth, 0);
1051 			}
1052 		}
1053 		DB_DNODE_EXIT(db);
1054 		db->db_state = DB_CACHED;
1055 		mutex_exit(&db->db_mtx);
1056 		return;
1057 	}
1058 
1059 	DB_DNODE_EXIT(db);
1060 
1061 	db->db_state = DB_READ;
1062 	mutex_exit(&db->db_mtx);
1063 
1064 	if (DBUF_IS_L2CACHEABLE(db))
1065 		aflags |= ARC_FLAG_L2CACHE;
1066 
1067 	SET_BOOKMARK(&zb, db->db_objset->os_dsl_dataset ?
1068 	    db->db_objset->os_dsl_dataset->ds_object : DMU_META_OBJSET,
1069 	    db->db.db_object, db->db_level, db->db_blkid);
1070 
1071 	dbuf_add_ref(db, NULL);
1072 
1073 	(void) arc_read(zio, db->db_objset->os_spa, db->db_blkptr,
1074 	    dbuf_read_done, db, ZIO_PRIORITY_SYNC_READ,
1075 	    (flags & DB_RF_CANFAIL) ? ZIO_FLAG_CANFAIL : ZIO_FLAG_MUSTSUCCEED,
1076 	    &aflags, &zb);
1077 }
1078 
1079 /*
1080  * This is our just-in-time copy function.  It makes a copy of buffers that
1081  * have been modified in a previous transaction group before we access them in
1082  * the current active group.
1083  *
1084  * This function is used in three places: when we are dirtying a buffer for the
1085  * first time in a txg, when we are freeing a range in a dnode that includes
1086  * this buffer, and when we are accessing a buffer which was received compressed
1087  * and later referenced in a WRITE_BYREF record.
1088  *
1089  * Note that when we are called from dbuf_free_range() we do not put a hold on
1090  * the buffer, we just traverse the active dbuf list for the dnode.
1091  */
1092 static void
1093 dbuf_fix_old_data(dmu_buf_impl_t *db, uint64_t txg)
1094 {
1095 	dbuf_dirty_record_t *dr = db->db_last_dirty;
1096 
1097 	ASSERT(MUTEX_HELD(&db->db_mtx));
1098 	ASSERT(db->db.db_data != NULL);
1099 	ASSERT(db->db_level == 0);
1100 	ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT);
1101 
1102 	if (dr == NULL ||
1103 	    (dr->dt.dl.dr_data !=
1104 	    ((db->db_blkid  == DMU_BONUS_BLKID) ? db->db.db_data : db->db_buf)))
1105 		return;
1106 
1107 	/*
1108 	 * If the last dirty record for this dbuf has not yet synced
1109 	 * and its referencing the dbuf data, either:
1110 	 *	reset the reference to point to a new copy,
1111 	 * or (if there a no active holders)
1112 	 *	just null out the current db_data pointer.
1113 	 */
1114 	ASSERT(dr->dr_txg >= txg - 2);
1115 	if (db->db_blkid == DMU_BONUS_BLKID) {
1116 		/* Note that the data bufs here are zio_bufs */
1117 		dnode_t *dn = DB_DNODE(db);
1118 		int bonuslen = DN_SLOTS_TO_BONUSLEN(dn->dn_num_slots);
1119 		dr->dt.dl.dr_data = zio_buf_alloc(bonuslen);
1120 		arc_space_consume(bonuslen, ARC_SPACE_BONUS);
1121 		bcopy(db->db.db_data, dr->dt.dl.dr_data, bonuslen);
1122 	} else if (zfs_refcount_count(&db->db_holds) > db->db_dirtycnt) {
1123 		int size = arc_buf_size(db->db_buf);
1124 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1125 		spa_t *spa = db->db_objset->os_spa;
1126 		enum zio_compress compress_type =
1127 		    arc_get_compression(db->db_buf);
1128 
1129 		if (compress_type == ZIO_COMPRESS_OFF) {
1130 			dr->dt.dl.dr_data = arc_alloc_buf(spa, db, type, size);
1131 		} else {
1132 			ASSERT3U(type, ==, ARC_BUFC_DATA);
1133 			dr->dt.dl.dr_data = arc_alloc_compressed_buf(spa, db,
1134 			    size, arc_buf_lsize(db->db_buf), compress_type);
1135 		}
1136 		bcopy(db->db.db_data, dr->dt.dl.dr_data->b_data, size);
1137 	} else {
1138 		db->db_buf = NULL;
1139 		dbuf_clear_data(db);
1140 	}
1141 }
1142 
1143 int
1144 dbuf_read(dmu_buf_impl_t *db, zio_t *zio, uint32_t flags)
1145 {
1146 	int err = 0;
1147 	boolean_t prefetch;
1148 	dnode_t *dn;
1149 
1150 	/*
1151 	 * We don't have to hold the mutex to check db_state because it
1152 	 * can't be freed while we have a hold on the buffer.
1153 	 */
1154 	ASSERT(!zfs_refcount_is_zero(&db->db_holds));
1155 
1156 	if (db->db_state == DB_NOFILL)
1157 		return (SET_ERROR(EIO));
1158 
1159 	DB_DNODE_ENTER(db);
1160 	dn = DB_DNODE(db);
1161 	if ((flags & DB_RF_HAVESTRUCT) == 0)
1162 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
1163 
1164 	prefetch = db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
1165 	    (flags & DB_RF_NOPREFETCH) == 0 && dn != NULL &&
1166 	    DBUF_IS_CACHEABLE(db);
1167 
1168 	mutex_enter(&db->db_mtx);
1169 	if (db->db_state == DB_CACHED) {
1170 		/*
1171 		 * If the arc buf is compressed, we need to decompress it to
1172 		 * read the data. This could happen during the "zfs receive" of
1173 		 * a stream which is compressed and deduplicated.
1174 		 */
1175 		if (db->db_buf != NULL &&
1176 		    arc_get_compression(db->db_buf) != ZIO_COMPRESS_OFF) {
1177 			dbuf_fix_old_data(db,
1178 			    spa_syncing_txg(dmu_objset_spa(db->db_objset)));
1179 			err = arc_decompress(db->db_buf);
1180 			dbuf_set_data(db, db->db_buf);
1181 		}
1182 		mutex_exit(&db->db_mtx);
1183 		if (prefetch)
1184 			dmu_zfetch(&dn->dn_zfetch, db->db_blkid, 1, B_TRUE);
1185 		if ((flags & DB_RF_HAVESTRUCT) == 0)
1186 			rw_exit(&dn->dn_struct_rwlock);
1187 		DB_DNODE_EXIT(db);
1188 	} else if (db->db_state == DB_UNCACHED) {
1189 		spa_t *spa = dn->dn_objset->os_spa;
1190 		boolean_t need_wait = B_FALSE;
1191 
1192 		if (zio == NULL &&
1193 		    db->db_blkptr != NULL && !BP_IS_HOLE(db->db_blkptr)) {
1194 			zio = zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL);
1195 			need_wait = B_TRUE;
1196 		}
1197 		dbuf_read_impl(db, zio, flags);
1198 
1199 		/* dbuf_read_impl has dropped db_mtx for us */
1200 
1201 		if (prefetch)
1202 			dmu_zfetch(&dn->dn_zfetch, db->db_blkid, 1, B_TRUE);
1203 
1204 		if ((flags & DB_RF_HAVESTRUCT) == 0)
1205 			rw_exit(&dn->dn_struct_rwlock);
1206 		DB_DNODE_EXIT(db);
1207 
1208 		if (need_wait)
1209 			err = zio_wait(zio);
1210 	} else {
1211 		/*
1212 		 * Another reader came in while the dbuf was in flight
1213 		 * between UNCACHED and CACHED.  Either a writer will finish
1214 		 * writing the buffer (sending the dbuf to CACHED) or the
1215 		 * first reader's request will reach the read_done callback
1216 		 * and send the dbuf to CACHED.  Otherwise, a failure
1217 		 * occurred and the dbuf went to UNCACHED.
1218 		 */
1219 		mutex_exit(&db->db_mtx);
1220 		if (prefetch)
1221 			dmu_zfetch(&dn->dn_zfetch, db->db_blkid, 1, B_TRUE);
1222 		if ((flags & DB_RF_HAVESTRUCT) == 0)
1223 			rw_exit(&dn->dn_struct_rwlock);
1224 		DB_DNODE_EXIT(db);
1225 
1226 		/* Skip the wait per the caller's request. */
1227 		mutex_enter(&db->db_mtx);
1228 		if ((flags & DB_RF_NEVERWAIT) == 0) {
1229 			while (db->db_state == DB_READ ||
1230 			    db->db_state == DB_FILL) {
1231 				ASSERT(db->db_state == DB_READ ||
1232 				    (flags & DB_RF_HAVESTRUCT) == 0);
1233 				DTRACE_PROBE2(blocked__read, dmu_buf_impl_t *,
1234 				    db, zio_t *, zio);
1235 				cv_wait(&db->db_changed, &db->db_mtx);
1236 			}
1237 			if (db->db_state == DB_UNCACHED)
1238 				err = SET_ERROR(EIO);
1239 		}
1240 		mutex_exit(&db->db_mtx);
1241 	}
1242 
1243 	return (err);
1244 }
1245 
1246 static void
1247 dbuf_noread(dmu_buf_impl_t *db)
1248 {
1249 	ASSERT(!zfs_refcount_is_zero(&db->db_holds));
1250 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1251 	mutex_enter(&db->db_mtx);
1252 	while (db->db_state == DB_READ || db->db_state == DB_FILL)
1253 		cv_wait(&db->db_changed, &db->db_mtx);
1254 	if (db->db_state == DB_UNCACHED) {
1255 		arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1256 		spa_t *spa = db->db_objset->os_spa;
1257 
1258 		ASSERT(db->db_buf == NULL);
1259 		ASSERT(db->db.db_data == NULL);
1260 		dbuf_set_data(db, arc_alloc_buf(spa, db, type, db->db.db_size));
1261 		db->db_state = DB_FILL;
1262 	} else if (db->db_state == DB_NOFILL) {
1263 		dbuf_clear_data(db);
1264 	} else {
1265 		ASSERT3U(db->db_state, ==, DB_CACHED);
1266 	}
1267 	mutex_exit(&db->db_mtx);
1268 }
1269 
1270 void
1271 dbuf_unoverride(dbuf_dirty_record_t *dr)
1272 {
1273 	dmu_buf_impl_t *db = dr->dr_dbuf;
1274 	blkptr_t *bp = &dr->dt.dl.dr_overridden_by;
1275 	uint64_t txg = dr->dr_txg;
1276 
1277 	ASSERT(MUTEX_HELD(&db->db_mtx));
1278 	/*
1279 	 * This assert is valid because dmu_sync() expects to be called by
1280 	 * a zilog's get_data while holding a range lock.  This call only
1281 	 * comes from dbuf_dirty() callers who must also hold a range lock.
1282 	 */
1283 	ASSERT(dr->dt.dl.dr_override_state != DR_IN_DMU_SYNC);
1284 	ASSERT(db->db_level == 0);
1285 
1286 	if (db->db_blkid == DMU_BONUS_BLKID ||
1287 	    dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN)
1288 		return;
1289 
1290 	ASSERT(db->db_data_pending != dr);
1291 
1292 	/* free this block */
1293 	if (!BP_IS_HOLE(bp) && !dr->dt.dl.dr_nopwrite)
1294 		zio_free(db->db_objset->os_spa, txg, bp);
1295 
1296 	dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
1297 	dr->dt.dl.dr_nopwrite = B_FALSE;
1298 
1299 	/*
1300 	 * Release the already-written buffer, so we leave it in
1301 	 * a consistent dirty state.  Note that all callers are
1302 	 * modifying the buffer, so they will immediately do
1303 	 * another (redundant) arc_release().  Therefore, leave
1304 	 * the buf thawed to save the effort of freezing &
1305 	 * immediately re-thawing it.
1306 	 */
1307 	arc_release(dr->dt.dl.dr_data, db);
1308 }
1309 
1310 /*
1311  * Evict (if its unreferenced) or clear (if its referenced) any level-0
1312  * data blocks in the free range, so that any future readers will find
1313  * empty blocks.
1314  */
1315 void
1316 dbuf_free_range(dnode_t *dn, uint64_t start_blkid, uint64_t end_blkid,
1317     dmu_tx_t *tx)
1318 {
1319 	dmu_buf_impl_t db_search;
1320 	dmu_buf_impl_t *db, *db_next;
1321 	uint64_t txg = tx->tx_txg;
1322 	avl_index_t where;
1323 
1324 	if (end_blkid > dn->dn_maxblkid &&
1325 	    !(start_blkid == DMU_SPILL_BLKID || end_blkid == DMU_SPILL_BLKID))
1326 		end_blkid = dn->dn_maxblkid;
1327 	dprintf_dnode(dn, "start=%llu end=%llu\n", start_blkid, end_blkid);
1328 
1329 	db_search.db_level = 0;
1330 	db_search.db_blkid = start_blkid;
1331 	db_search.db_state = DB_SEARCH;
1332 
1333 	mutex_enter(&dn->dn_dbufs_mtx);
1334 	db = avl_find(&dn->dn_dbufs, &db_search, &where);
1335 	ASSERT3P(db, ==, NULL);
1336 
1337 	db = avl_nearest(&dn->dn_dbufs, where, AVL_AFTER);
1338 
1339 	for (; db != NULL; db = db_next) {
1340 		db_next = AVL_NEXT(&dn->dn_dbufs, db);
1341 		ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1342 
1343 		if (db->db_level != 0 || db->db_blkid > end_blkid) {
1344 			break;
1345 		}
1346 		ASSERT3U(db->db_blkid, >=, start_blkid);
1347 
1348 		/* found a level 0 buffer in the range */
1349 		mutex_enter(&db->db_mtx);
1350 		if (dbuf_undirty(db, tx)) {
1351 			/* mutex has been dropped and dbuf destroyed */
1352 			continue;
1353 		}
1354 
1355 		if (db->db_state == DB_UNCACHED ||
1356 		    db->db_state == DB_NOFILL ||
1357 		    db->db_state == DB_EVICTING) {
1358 			ASSERT(db->db.db_data == NULL);
1359 			mutex_exit(&db->db_mtx);
1360 			continue;
1361 		}
1362 		if (db->db_state == DB_READ || db->db_state == DB_FILL) {
1363 			/* will be handled in dbuf_read_done or dbuf_rele */
1364 			db->db_freed_in_flight = TRUE;
1365 			mutex_exit(&db->db_mtx);
1366 			continue;
1367 		}
1368 		if (zfs_refcount_count(&db->db_holds) == 0) {
1369 			ASSERT(db->db_buf);
1370 			dbuf_destroy(db);
1371 			continue;
1372 		}
1373 		/* The dbuf is referenced */
1374 
1375 		if (db->db_last_dirty != NULL) {
1376 			dbuf_dirty_record_t *dr = db->db_last_dirty;
1377 
1378 			if (dr->dr_txg == txg) {
1379 				/*
1380 				 * This buffer is "in-use", re-adjust the file
1381 				 * size to reflect that this buffer may
1382 				 * contain new data when we sync.
1383 				 */
1384 				if (db->db_blkid != DMU_SPILL_BLKID &&
1385 				    db->db_blkid > dn->dn_maxblkid)
1386 					dn->dn_maxblkid = db->db_blkid;
1387 				dbuf_unoverride(dr);
1388 			} else {
1389 				/*
1390 				 * This dbuf is not dirty in the open context.
1391 				 * Either uncache it (if its not referenced in
1392 				 * the open context) or reset its contents to
1393 				 * empty.
1394 				 */
1395 				dbuf_fix_old_data(db, txg);
1396 			}
1397 		}
1398 		/* clear the contents if its cached */
1399 		if (db->db_state == DB_CACHED) {
1400 			ASSERT(db->db.db_data != NULL);
1401 			arc_release(db->db_buf, db);
1402 			bzero(db->db.db_data, db->db.db_size);
1403 			arc_buf_freeze(db->db_buf);
1404 		}
1405 
1406 		mutex_exit(&db->db_mtx);
1407 	}
1408 	mutex_exit(&dn->dn_dbufs_mtx);
1409 }
1410 
1411 void
1412 dbuf_new_size(dmu_buf_impl_t *db, int size, dmu_tx_t *tx)
1413 {
1414 	arc_buf_t *buf, *obuf;
1415 	int osize = db->db.db_size;
1416 	arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
1417 	dnode_t *dn;
1418 
1419 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1420 
1421 	DB_DNODE_ENTER(db);
1422 	dn = DB_DNODE(db);
1423 
1424 	/* XXX does *this* func really need the lock? */
1425 	ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
1426 
1427 	/*
1428 	 * This call to dmu_buf_will_dirty() with the dn_struct_rwlock held
1429 	 * is OK, because there can be no other references to the db
1430 	 * when we are changing its size, so no concurrent DB_FILL can
1431 	 * be happening.
1432 	 */
1433 	/*
1434 	 * XXX we should be doing a dbuf_read, checking the return
1435 	 * value and returning that up to our callers
1436 	 */
1437 	dmu_buf_will_dirty(&db->db, tx);
1438 
1439 	/* create the data buffer for the new block */
1440 	buf = arc_alloc_buf(dn->dn_objset->os_spa, db, type, size);
1441 
1442 	/* copy old block data to the new block */
1443 	obuf = db->db_buf;
1444 	bcopy(obuf->b_data, buf->b_data, MIN(osize, size));
1445 	/* zero the remainder */
1446 	if (size > osize)
1447 		bzero((uint8_t *)buf->b_data + osize, size - osize);
1448 
1449 	mutex_enter(&db->db_mtx);
1450 	dbuf_set_data(db, buf);
1451 	arc_buf_destroy(obuf, db);
1452 	db->db.db_size = size;
1453 
1454 	if (db->db_level == 0) {
1455 		ASSERT3U(db->db_last_dirty->dr_txg, ==, tx->tx_txg);
1456 		db->db_last_dirty->dt.dl.dr_data = buf;
1457 	}
1458 	mutex_exit(&db->db_mtx);
1459 
1460 	dmu_objset_willuse_space(dn->dn_objset, size - osize, tx);
1461 	DB_DNODE_EXIT(db);
1462 }
1463 
1464 void
1465 dbuf_release_bp(dmu_buf_impl_t *db)
1466 {
1467 	objset_t *os = db->db_objset;
1468 
1469 	ASSERT(dsl_pool_sync_context(dmu_objset_pool(os)));
1470 	ASSERT(arc_released(os->os_phys_buf) ||
1471 	    list_link_active(&os->os_dsl_dataset->ds_synced_link));
1472 	ASSERT(db->db_parent == NULL || arc_released(db->db_parent->db_buf));
1473 
1474 	(void) arc_release(db->db_buf, db);
1475 }
1476 
1477 /*
1478  * We already have a dirty record for this TXG, and we are being
1479  * dirtied again.
1480  */
1481 static void
1482 dbuf_redirty(dbuf_dirty_record_t *dr)
1483 {
1484 	dmu_buf_impl_t *db = dr->dr_dbuf;
1485 
1486 	ASSERT(MUTEX_HELD(&db->db_mtx));
1487 
1488 	if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID) {
1489 		/*
1490 		 * If this buffer has already been written out,
1491 		 * we now need to reset its state.
1492 		 */
1493 		dbuf_unoverride(dr);
1494 		if (db->db.db_object != DMU_META_DNODE_OBJECT &&
1495 		    db->db_state != DB_NOFILL) {
1496 			/* Already released on initial dirty, so just thaw. */
1497 			ASSERT(arc_released(db->db_buf));
1498 			arc_buf_thaw(db->db_buf);
1499 		}
1500 	}
1501 }
1502 
1503 dbuf_dirty_record_t *
1504 dbuf_dirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
1505 {
1506 	dnode_t *dn;
1507 	objset_t *os;
1508 	dbuf_dirty_record_t **drp, *dr;
1509 	int drop_struct_lock = FALSE;
1510 	int txgoff = tx->tx_txg & TXG_MASK;
1511 
1512 	ASSERT(tx->tx_txg != 0);
1513 	ASSERT(!zfs_refcount_is_zero(&db->db_holds));
1514 	DMU_TX_DIRTY_BUF(tx, db);
1515 
1516 	DB_DNODE_ENTER(db);
1517 	dn = DB_DNODE(db);
1518 	/*
1519 	 * Shouldn't dirty a regular buffer in syncing context.  Private
1520 	 * objects may be dirtied in syncing context, but only if they
1521 	 * were already pre-dirtied in open context.
1522 	 */
1523 #ifdef DEBUG
1524 	if (dn->dn_objset->os_dsl_dataset != NULL) {
1525 		rrw_enter(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock,
1526 		    RW_READER, FTAG);
1527 	}
1528 	ASSERT(!dmu_tx_is_syncing(tx) ||
1529 	    BP_IS_HOLE(dn->dn_objset->os_rootbp) ||
1530 	    DMU_OBJECT_IS_SPECIAL(dn->dn_object) ||
1531 	    dn->dn_objset->os_dsl_dataset == NULL);
1532 	if (dn->dn_objset->os_dsl_dataset != NULL)
1533 		rrw_exit(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock, FTAG);
1534 #endif
1535 	/*
1536 	 * We make this assert for private objects as well, but after we
1537 	 * check if we're already dirty.  They are allowed to re-dirty
1538 	 * in syncing context.
1539 	 */
1540 	ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
1541 	    dn->dn_dirtyctx == DN_UNDIRTIED || dn->dn_dirtyctx ==
1542 	    (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN));
1543 
1544 	mutex_enter(&db->db_mtx);
1545 	/*
1546 	 * XXX make this true for indirects too?  The problem is that
1547 	 * transactions created with dmu_tx_create_assigned() from
1548 	 * syncing context don't bother holding ahead.
1549 	 */
1550 	ASSERT(db->db_level != 0 ||
1551 	    db->db_state == DB_CACHED || db->db_state == DB_FILL ||
1552 	    db->db_state == DB_NOFILL);
1553 
1554 	mutex_enter(&dn->dn_mtx);
1555 	/*
1556 	 * Don't set dirtyctx to SYNC if we're just modifying this as we
1557 	 * initialize the objset.
1558 	 */
1559 	if (dn->dn_dirtyctx == DN_UNDIRTIED) {
1560 		if (dn->dn_objset->os_dsl_dataset != NULL) {
1561 			rrw_enter(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock,
1562 			    RW_READER, FTAG);
1563 		}
1564 		if (!BP_IS_HOLE(dn->dn_objset->os_rootbp)) {
1565 			dn->dn_dirtyctx = (dmu_tx_is_syncing(tx) ?
1566 			    DN_DIRTY_SYNC : DN_DIRTY_OPEN);
1567 			ASSERT(dn->dn_dirtyctx_firstset == NULL);
1568 			dn->dn_dirtyctx_firstset = kmem_alloc(1, KM_SLEEP);
1569 		}
1570 		if (dn->dn_objset->os_dsl_dataset != NULL) {
1571 			rrw_exit(&dn->dn_objset->os_dsl_dataset->ds_bp_rwlock,
1572 			    FTAG);
1573 		}
1574 	}
1575 	mutex_exit(&dn->dn_mtx);
1576 
1577 	if (db->db_blkid == DMU_SPILL_BLKID)
1578 		dn->dn_have_spill = B_TRUE;
1579 
1580 	/*
1581 	 * If this buffer is already dirty, we're done.
1582 	 */
1583 	drp = &db->db_last_dirty;
1584 	ASSERT(*drp == NULL || (*drp)->dr_txg <= tx->tx_txg ||
1585 	    db->db.db_object == DMU_META_DNODE_OBJECT);
1586 	while ((dr = *drp) != NULL && dr->dr_txg > tx->tx_txg)
1587 		drp = &dr->dr_next;
1588 	if (dr && dr->dr_txg == tx->tx_txg) {
1589 		DB_DNODE_EXIT(db);
1590 
1591 		dbuf_redirty(dr);
1592 		mutex_exit(&db->db_mtx);
1593 		return (dr);
1594 	}
1595 
1596 	/*
1597 	 * Only valid if not already dirty.
1598 	 */
1599 	ASSERT(dn->dn_object == 0 ||
1600 	    dn->dn_dirtyctx == DN_UNDIRTIED || dn->dn_dirtyctx ==
1601 	    (dmu_tx_is_syncing(tx) ? DN_DIRTY_SYNC : DN_DIRTY_OPEN));
1602 
1603 	ASSERT3U(dn->dn_nlevels, >, db->db_level);
1604 
1605 	/*
1606 	 * We should only be dirtying in syncing context if it's the
1607 	 * mos or we're initializing the os or it's a special object.
1608 	 * However, we are allowed to dirty in syncing context provided
1609 	 * we already dirtied it in open context.  Hence we must make
1610 	 * this assertion only if we're not already dirty.
1611 	 */
1612 	os = dn->dn_objset;
1613 	VERIFY3U(tx->tx_txg, <=, spa_final_dirty_txg(os->os_spa));
1614 #ifdef DEBUG
1615 	if (dn->dn_objset->os_dsl_dataset != NULL)
1616 		rrw_enter(&os->os_dsl_dataset->ds_bp_rwlock, RW_READER, FTAG);
1617 	ASSERT(!dmu_tx_is_syncing(tx) || DMU_OBJECT_IS_SPECIAL(dn->dn_object) ||
1618 	    os->os_dsl_dataset == NULL || BP_IS_HOLE(os->os_rootbp));
1619 	if (dn->dn_objset->os_dsl_dataset != NULL)
1620 		rrw_exit(&os->os_dsl_dataset->ds_bp_rwlock, FTAG);
1621 #endif
1622 	ASSERT(db->db.db_size != 0);
1623 
1624 	dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
1625 
1626 	if (db->db_blkid != DMU_BONUS_BLKID) {
1627 		dmu_objset_willuse_space(os, db->db.db_size, tx);
1628 	}
1629 
1630 	/*
1631 	 * If this buffer is dirty in an old transaction group we need
1632 	 * to make a copy of it so that the changes we make in this
1633 	 * transaction group won't leak out when we sync the older txg.
1634 	 */
1635 	dr = kmem_zalloc(sizeof (dbuf_dirty_record_t), KM_SLEEP);
1636 	if (db->db_level == 0) {
1637 		void *data_old = db->db_buf;
1638 
1639 		if (db->db_state != DB_NOFILL) {
1640 			if (db->db_blkid == DMU_BONUS_BLKID) {
1641 				dbuf_fix_old_data(db, tx->tx_txg);
1642 				data_old = db->db.db_data;
1643 			} else if (db->db.db_object != DMU_META_DNODE_OBJECT) {
1644 				/*
1645 				 * Release the data buffer from the cache so
1646 				 * that we can modify it without impacting
1647 				 * possible other users of this cached data
1648 				 * block.  Note that indirect blocks and
1649 				 * private objects are not released until the
1650 				 * syncing state (since they are only modified
1651 				 * then).
1652 				 */
1653 				arc_release(db->db_buf, db);
1654 				dbuf_fix_old_data(db, tx->tx_txg);
1655 				data_old = db->db_buf;
1656 			}
1657 			ASSERT(data_old != NULL);
1658 		}
1659 		dr->dt.dl.dr_data = data_old;
1660 	} else {
1661 		mutex_init(&dr->dt.di.dr_mtx, NULL, MUTEX_DEFAULT, NULL);
1662 		list_create(&dr->dt.di.dr_children,
1663 		    sizeof (dbuf_dirty_record_t),
1664 		    offsetof(dbuf_dirty_record_t, dr_dirty_node));
1665 	}
1666 	if (db->db_blkid != DMU_BONUS_BLKID && os->os_dsl_dataset != NULL)
1667 		dr->dr_accounted = db->db.db_size;
1668 	dr->dr_dbuf = db;
1669 	dr->dr_txg = tx->tx_txg;
1670 	dr->dr_next = *drp;
1671 	*drp = dr;
1672 
1673 	/*
1674 	 * We could have been freed_in_flight between the dbuf_noread
1675 	 * and dbuf_dirty.  We win, as though the dbuf_noread() had
1676 	 * happened after the free.
1677 	 */
1678 	if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
1679 	    db->db_blkid != DMU_SPILL_BLKID) {
1680 		mutex_enter(&dn->dn_mtx);
1681 		if (dn->dn_free_ranges[txgoff] != NULL) {
1682 			range_tree_clear(dn->dn_free_ranges[txgoff],
1683 			    db->db_blkid, 1);
1684 		}
1685 		mutex_exit(&dn->dn_mtx);
1686 		db->db_freed_in_flight = FALSE;
1687 	}
1688 
1689 	/*
1690 	 * This buffer is now part of this txg
1691 	 */
1692 	dbuf_add_ref(db, (void *)(uintptr_t)tx->tx_txg);
1693 	db->db_dirtycnt += 1;
1694 	ASSERT3U(db->db_dirtycnt, <=, 3);
1695 
1696 	mutex_exit(&db->db_mtx);
1697 
1698 	if (db->db_blkid == DMU_BONUS_BLKID ||
1699 	    db->db_blkid == DMU_SPILL_BLKID) {
1700 		mutex_enter(&dn->dn_mtx);
1701 		ASSERT(!list_link_active(&dr->dr_dirty_node));
1702 		list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
1703 		mutex_exit(&dn->dn_mtx);
1704 		dnode_setdirty(dn, tx);
1705 		DB_DNODE_EXIT(db);
1706 		return (dr);
1707 	}
1708 
1709 	/*
1710 	 * The dn_struct_rwlock prevents db_blkptr from changing
1711 	 * due to a write from syncing context completing
1712 	 * while we are running, so we want to acquire it before
1713 	 * looking at db_blkptr.
1714 	 */
1715 	if (!RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
1716 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
1717 		drop_struct_lock = TRUE;
1718 	}
1719 
1720 	/*
1721 	 * We need to hold the dn_struct_rwlock to make this assertion,
1722 	 * because it protects dn_phys / dn_next_nlevels from changing.
1723 	 */
1724 	ASSERT((dn->dn_phys->dn_nlevels == 0 && db->db_level == 0) ||
1725 	    dn->dn_phys->dn_nlevels > db->db_level ||
1726 	    dn->dn_next_nlevels[txgoff] > db->db_level ||
1727 	    dn->dn_next_nlevels[(tx->tx_txg-1) & TXG_MASK] > db->db_level ||
1728 	    dn->dn_next_nlevels[(tx->tx_txg-2) & TXG_MASK] > db->db_level);
1729 
1730 	/*
1731 	 * If we are overwriting a dedup BP, then unless it is snapshotted,
1732 	 * when we get to syncing context we will need to decrement its
1733 	 * refcount in the DDT.  Prefetch the relevant DDT block so that
1734 	 * syncing context won't have to wait for the i/o.
1735 	 */
1736 	ddt_prefetch(os->os_spa, db->db_blkptr);
1737 
1738 	if (db->db_level == 0) {
1739 		dnode_new_blkid(dn, db->db_blkid, tx, drop_struct_lock);
1740 		ASSERT(dn->dn_maxblkid >= db->db_blkid);
1741 	}
1742 
1743 	if (db->db_level+1 < dn->dn_nlevels) {
1744 		dmu_buf_impl_t *parent = db->db_parent;
1745 		dbuf_dirty_record_t *di;
1746 		int parent_held = FALSE;
1747 
1748 		if (db->db_parent == NULL || db->db_parent == dn->dn_dbuf) {
1749 			int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
1750 
1751 			parent = dbuf_hold_level(dn, db->db_level+1,
1752 			    db->db_blkid >> epbs, FTAG);
1753 			ASSERT(parent != NULL);
1754 			parent_held = TRUE;
1755 		}
1756 		if (drop_struct_lock)
1757 			rw_exit(&dn->dn_struct_rwlock);
1758 		ASSERT3U(db->db_level+1, ==, parent->db_level);
1759 		di = dbuf_dirty(parent, tx);
1760 		if (parent_held)
1761 			dbuf_rele(parent, FTAG);
1762 
1763 		mutex_enter(&db->db_mtx);
1764 		/*
1765 		 * Since we've dropped the mutex, it's possible that
1766 		 * dbuf_undirty() might have changed this out from under us.
1767 		 */
1768 		if (db->db_last_dirty == dr ||
1769 		    dn->dn_object == DMU_META_DNODE_OBJECT) {
1770 			mutex_enter(&di->dt.di.dr_mtx);
1771 			ASSERT3U(di->dr_txg, ==, tx->tx_txg);
1772 			ASSERT(!list_link_active(&dr->dr_dirty_node));
1773 			list_insert_tail(&di->dt.di.dr_children, dr);
1774 			mutex_exit(&di->dt.di.dr_mtx);
1775 			dr->dr_parent = di;
1776 		}
1777 		mutex_exit(&db->db_mtx);
1778 	} else {
1779 		ASSERT(db->db_level+1 == dn->dn_nlevels);
1780 		ASSERT(db->db_blkid < dn->dn_nblkptr);
1781 		ASSERT(db->db_parent == NULL || db->db_parent == dn->dn_dbuf);
1782 		mutex_enter(&dn->dn_mtx);
1783 		ASSERT(!list_link_active(&dr->dr_dirty_node));
1784 		list_insert_tail(&dn->dn_dirty_records[txgoff], dr);
1785 		mutex_exit(&dn->dn_mtx);
1786 		if (drop_struct_lock)
1787 			rw_exit(&dn->dn_struct_rwlock);
1788 	}
1789 
1790 	dnode_setdirty(dn, tx);
1791 	DB_DNODE_EXIT(db);
1792 	return (dr);
1793 }
1794 
1795 /*
1796  * Undirty a buffer in the transaction group referenced by the given
1797  * transaction.  Return whether this evicted the dbuf.
1798  */
1799 static boolean_t
1800 dbuf_undirty(dmu_buf_impl_t *db, dmu_tx_t *tx)
1801 {
1802 	dnode_t *dn;
1803 	uint64_t txg = tx->tx_txg;
1804 	dbuf_dirty_record_t *dr, **drp;
1805 
1806 	ASSERT(txg != 0);
1807 
1808 	/*
1809 	 * Due to our use of dn_nlevels below, this can only be called
1810 	 * in open context, unless we are operating on the MOS.
1811 	 * From syncing context, dn_nlevels may be different from the
1812 	 * dn_nlevels used when dbuf was dirtied.
1813 	 */
1814 	ASSERT(db->db_objset ==
1815 	    dmu_objset_pool(db->db_objset)->dp_meta_objset ||
1816 	    txg != spa_syncing_txg(dmu_objset_spa(db->db_objset)));
1817 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1818 	ASSERT0(db->db_level);
1819 	ASSERT(MUTEX_HELD(&db->db_mtx));
1820 
1821 	/*
1822 	 * If this buffer is not dirty, we're done.
1823 	 */
1824 	for (drp = &db->db_last_dirty; (dr = *drp) != NULL; drp = &dr->dr_next)
1825 		if (dr->dr_txg <= txg)
1826 			break;
1827 	if (dr == NULL || dr->dr_txg < txg)
1828 		return (B_FALSE);
1829 	ASSERT(dr->dr_txg == txg);
1830 	ASSERT(dr->dr_dbuf == db);
1831 
1832 	DB_DNODE_ENTER(db);
1833 	dn = DB_DNODE(db);
1834 
1835 	dprintf_dbuf(db, "size=%llx\n", (u_longlong_t)db->db.db_size);
1836 
1837 	ASSERT(db->db.db_size != 0);
1838 
1839 	dsl_pool_undirty_space(dmu_objset_pool(dn->dn_objset),
1840 	    dr->dr_accounted, txg);
1841 
1842 	*drp = dr->dr_next;
1843 
1844 	/*
1845 	 * Note that there are three places in dbuf_dirty()
1846 	 * where this dirty record may be put on a list.
1847 	 * Make sure to do a list_remove corresponding to
1848 	 * every one of those list_insert calls.
1849 	 */
1850 	if (dr->dr_parent) {
1851 		mutex_enter(&dr->dr_parent->dt.di.dr_mtx);
1852 		list_remove(&dr->dr_parent->dt.di.dr_children, dr);
1853 		mutex_exit(&dr->dr_parent->dt.di.dr_mtx);
1854 	} else if (db->db_blkid == DMU_SPILL_BLKID ||
1855 	    db->db_level + 1 == dn->dn_nlevels) {
1856 		ASSERT(db->db_blkptr == NULL || db->db_parent == dn->dn_dbuf);
1857 		mutex_enter(&dn->dn_mtx);
1858 		list_remove(&dn->dn_dirty_records[txg & TXG_MASK], dr);
1859 		mutex_exit(&dn->dn_mtx);
1860 	}
1861 	DB_DNODE_EXIT(db);
1862 
1863 	if (db->db_state != DB_NOFILL) {
1864 		dbuf_unoverride(dr);
1865 
1866 		ASSERT(db->db_buf != NULL);
1867 		ASSERT(dr->dt.dl.dr_data != NULL);
1868 		if (dr->dt.dl.dr_data != db->db_buf)
1869 			arc_buf_destroy(dr->dt.dl.dr_data, db);
1870 	}
1871 
1872 	kmem_free(dr, sizeof (dbuf_dirty_record_t));
1873 
1874 	ASSERT(db->db_dirtycnt > 0);
1875 	db->db_dirtycnt -= 1;
1876 
1877 	if (zfs_refcount_remove(&db->db_holds, (void *)(uintptr_t)txg) == 0) {
1878 		ASSERT(db->db_state == DB_NOFILL || arc_released(db->db_buf));
1879 		dbuf_destroy(db);
1880 		return (B_TRUE);
1881 	}
1882 
1883 	return (B_FALSE);
1884 }
1885 
1886 void
1887 dmu_buf_will_dirty(dmu_buf_t *db_fake, dmu_tx_t *tx)
1888 {
1889 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1890 	int rf = DB_RF_MUST_SUCCEED | DB_RF_NOPREFETCH;
1891 
1892 	ASSERT(tx->tx_txg != 0);
1893 	ASSERT(!zfs_refcount_is_zero(&db->db_holds));
1894 
1895 	/*
1896 	 * Quick check for dirtyness.  For already dirty blocks, this
1897 	 * reduces runtime of this function by >90%, and overall performance
1898 	 * by 50% for some workloads (e.g. file deletion with indirect blocks
1899 	 * cached).
1900 	 */
1901 	mutex_enter(&db->db_mtx);
1902 	dbuf_dirty_record_t *dr;
1903 	for (dr = db->db_last_dirty;
1904 	    dr != NULL && dr->dr_txg >= tx->tx_txg; dr = dr->dr_next) {
1905 		/*
1906 		 * It's possible that it is already dirty but not cached,
1907 		 * because there are some calls to dbuf_dirty() that don't
1908 		 * go through dmu_buf_will_dirty().
1909 		 */
1910 		if (dr->dr_txg == tx->tx_txg && db->db_state == DB_CACHED) {
1911 			/* This dbuf is already dirty and cached. */
1912 			dbuf_redirty(dr);
1913 			mutex_exit(&db->db_mtx);
1914 			return;
1915 		}
1916 	}
1917 	mutex_exit(&db->db_mtx);
1918 
1919 	DB_DNODE_ENTER(db);
1920 	if (RW_WRITE_HELD(&DB_DNODE(db)->dn_struct_rwlock))
1921 		rf |= DB_RF_HAVESTRUCT;
1922 	DB_DNODE_EXIT(db);
1923 	(void) dbuf_read(db, NULL, rf);
1924 	(void) dbuf_dirty(db, tx);
1925 }
1926 
1927 void
1928 dmu_buf_will_not_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
1929 {
1930 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1931 
1932 	db->db_state = DB_NOFILL;
1933 
1934 	dmu_buf_will_fill(db_fake, tx);
1935 }
1936 
1937 void
1938 dmu_buf_will_fill(dmu_buf_t *db_fake, dmu_tx_t *tx)
1939 {
1940 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
1941 
1942 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1943 	ASSERT(tx->tx_txg != 0);
1944 	ASSERT(db->db_level == 0);
1945 	ASSERT(!zfs_refcount_is_zero(&db->db_holds));
1946 
1947 	ASSERT(db->db.db_object != DMU_META_DNODE_OBJECT ||
1948 	    dmu_tx_private_ok(tx));
1949 
1950 	dbuf_noread(db);
1951 	(void) dbuf_dirty(db, tx);
1952 }
1953 
1954 #pragma weak dmu_buf_fill_done = dbuf_fill_done
1955 /* ARGSUSED */
1956 void
1957 dbuf_fill_done(dmu_buf_impl_t *db, dmu_tx_t *tx)
1958 {
1959 	mutex_enter(&db->db_mtx);
1960 	DBUF_VERIFY(db);
1961 
1962 	if (db->db_state == DB_FILL) {
1963 		if (db->db_level == 0 && db->db_freed_in_flight) {
1964 			ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1965 			/* we were freed while filling */
1966 			/* XXX dbuf_undirty? */
1967 			bzero(db->db.db_data, db->db.db_size);
1968 			db->db_freed_in_flight = FALSE;
1969 		}
1970 		db->db_state = DB_CACHED;
1971 		cv_broadcast(&db->db_changed);
1972 	}
1973 	mutex_exit(&db->db_mtx);
1974 }
1975 
1976 void
1977 dmu_buf_write_embedded(dmu_buf_t *dbuf, void *data,
1978     bp_embedded_type_t etype, enum zio_compress comp,
1979     int uncompressed_size, int compressed_size, int byteorder,
1980     dmu_tx_t *tx)
1981 {
1982 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbuf;
1983 	struct dirty_leaf *dl;
1984 	dmu_object_type_t type;
1985 
1986 	if (etype == BP_EMBEDDED_TYPE_DATA) {
1987 		ASSERT(spa_feature_is_active(dmu_objset_spa(db->db_objset),
1988 		    SPA_FEATURE_EMBEDDED_DATA));
1989 	}
1990 
1991 	DB_DNODE_ENTER(db);
1992 	type = DB_DNODE(db)->dn_type;
1993 	DB_DNODE_EXIT(db);
1994 
1995 	ASSERT0(db->db_level);
1996 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
1997 
1998 	dmu_buf_will_not_fill(dbuf, tx);
1999 
2000 	ASSERT3U(db->db_last_dirty->dr_txg, ==, tx->tx_txg);
2001 	dl = &db->db_last_dirty->dt.dl;
2002 	encode_embedded_bp_compressed(&dl->dr_overridden_by,
2003 	    data, comp, uncompressed_size, compressed_size);
2004 	BPE_SET_ETYPE(&dl->dr_overridden_by, etype);
2005 	BP_SET_TYPE(&dl->dr_overridden_by, type);
2006 	BP_SET_LEVEL(&dl->dr_overridden_by, 0);
2007 	BP_SET_BYTEORDER(&dl->dr_overridden_by, byteorder);
2008 
2009 	dl->dr_override_state = DR_OVERRIDDEN;
2010 	dl->dr_overridden_by.blk_birth = db->db_last_dirty->dr_txg;
2011 }
2012 
2013 /*
2014  * Directly assign a provided arc buf to a given dbuf if it's not referenced
2015  * by anybody except our caller. Otherwise copy arcbuf's contents to dbuf.
2016  */
2017 void
2018 dbuf_assign_arcbuf(dmu_buf_impl_t *db, arc_buf_t *buf, dmu_tx_t *tx)
2019 {
2020 	ASSERT(!zfs_refcount_is_zero(&db->db_holds));
2021 	ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2022 	ASSERT(db->db_level == 0);
2023 	ASSERT3U(dbuf_is_metadata(db), ==, arc_is_metadata(buf));
2024 	ASSERT(buf != NULL);
2025 	ASSERT(arc_buf_lsize(buf) == db->db.db_size);
2026 	ASSERT(tx->tx_txg != 0);
2027 
2028 	arc_return_buf(buf, db);
2029 	ASSERT(arc_released(buf));
2030 
2031 	mutex_enter(&db->db_mtx);
2032 
2033 	while (db->db_state == DB_READ || db->db_state == DB_FILL)
2034 		cv_wait(&db->db_changed, &db->db_mtx);
2035 
2036 	ASSERT(db->db_state == DB_CACHED || db->db_state == DB_UNCACHED);
2037 
2038 	if (db->db_state == DB_CACHED &&
2039 	    zfs_refcount_count(&db->db_holds) - 1 > db->db_dirtycnt) {
2040 		mutex_exit(&db->db_mtx);
2041 		(void) dbuf_dirty(db, tx);
2042 		bcopy(buf->b_data, db->db.db_data, db->db.db_size);
2043 		arc_buf_destroy(buf, db);
2044 		xuio_stat_wbuf_copied();
2045 		return;
2046 	}
2047 
2048 	xuio_stat_wbuf_nocopy();
2049 	if (db->db_state == DB_CACHED) {
2050 		dbuf_dirty_record_t *dr = db->db_last_dirty;
2051 
2052 		ASSERT(db->db_buf != NULL);
2053 		if (dr != NULL && dr->dr_txg == tx->tx_txg) {
2054 			ASSERT(dr->dt.dl.dr_data == db->db_buf);
2055 			if (!arc_released(db->db_buf)) {
2056 				ASSERT(dr->dt.dl.dr_override_state ==
2057 				    DR_OVERRIDDEN);
2058 				arc_release(db->db_buf, db);
2059 			}
2060 			dr->dt.dl.dr_data = buf;
2061 			arc_buf_destroy(db->db_buf, db);
2062 		} else if (dr == NULL || dr->dt.dl.dr_data != db->db_buf) {
2063 			arc_release(db->db_buf, db);
2064 			arc_buf_destroy(db->db_buf, db);
2065 		}
2066 		db->db_buf = NULL;
2067 	}
2068 	ASSERT(db->db_buf == NULL);
2069 	dbuf_set_data(db, buf);
2070 	db->db_state = DB_FILL;
2071 	mutex_exit(&db->db_mtx);
2072 	(void) dbuf_dirty(db, tx);
2073 	dmu_buf_fill_done(&db->db, tx);
2074 }
2075 
2076 void
2077 dbuf_destroy(dmu_buf_impl_t *db)
2078 {
2079 	dnode_t *dn;
2080 	dmu_buf_impl_t *parent = db->db_parent;
2081 	dmu_buf_impl_t *dndb;
2082 
2083 	ASSERT(MUTEX_HELD(&db->db_mtx));
2084 	ASSERT(zfs_refcount_is_zero(&db->db_holds));
2085 
2086 	if (db->db_buf != NULL) {
2087 		arc_buf_destroy(db->db_buf, db);
2088 		db->db_buf = NULL;
2089 	}
2090 
2091 	if (db->db_blkid == DMU_BONUS_BLKID) {
2092 		int slots = DB_DNODE(db)->dn_num_slots;
2093 		int bonuslen = DN_SLOTS_TO_BONUSLEN(slots);
2094 		if (db->db.db_data != NULL) {
2095 			zio_buf_free(db->db.db_data, bonuslen);
2096 			arc_space_return(bonuslen, ARC_SPACE_BONUS);
2097 			db->db_state = DB_UNCACHED;
2098 		}
2099 	}
2100 
2101 	dbuf_clear_data(db);
2102 
2103 	if (multilist_link_active(&db->db_cache_link)) {
2104 		ASSERT(db->db_caching_status == DB_DBUF_CACHE ||
2105 		    db->db_caching_status == DB_DBUF_METADATA_CACHE);
2106 
2107 		multilist_remove(dbuf_caches[db->db_caching_status].cache, db);
2108 		(void) zfs_refcount_remove_many(
2109 		    &dbuf_caches[db->db_caching_status].size,
2110 		    db->db.db_size, db);
2111 
2112 		db->db_caching_status = DB_NO_CACHE;
2113 	}
2114 
2115 	ASSERT(db->db_state == DB_UNCACHED || db->db_state == DB_NOFILL);
2116 	ASSERT(db->db_data_pending == NULL);
2117 
2118 	db->db_state = DB_EVICTING;
2119 	db->db_blkptr = NULL;
2120 
2121 	/*
2122 	 * Now that db_state is DB_EVICTING, nobody else can find this via
2123 	 * the hash table.  We can now drop db_mtx, which allows us to
2124 	 * acquire the dn_dbufs_mtx.
2125 	 */
2126 	mutex_exit(&db->db_mtx);
2127 
2128 	DB_DNODE_ENTER(db);
2129 	dn = DB_DNODE(db);
2130 	dndb = dn->dn_dbuf;
2131 	if (db->db_blkid != DMU_BONUS_BLKID) {
2132 		boolean_t needlock = !MUTEX_HELD(&dn->dn_dbufs_mtx);
2133 		if (needlock)
2134 			mutex_enter(&dn->dn_dbufs_mtx);
2135 		avl_remove(&dn->dn_dbufs, db);
2136 		atomic_dec_32(&dn->dn_dbufs_count);
2137 		membar_producer();
2138 		DB_DNODE_EXIT(db);
2139 		if (needlock)
2140 			mutex_exit(&dn->dn_dbufs_mtx);
2141 		/*
2142 		 * Decrementing the dbuf count means that the hold corresponding
2143 		 * to the removed dbuf is no longer discounted in dnode_move(),
2144 		 * so the dnode cannot be moved until after we release the hold.
2145 		 * The membar_producer() ensures visibility of the decremented
2146 		 * value in dnode_move(), since DB_DNODE_EXIT doesn't actually
2147 		 * release any lock.
2148 		 */
2149 		mutex_enter(&dn->dn_mtx);
2150 		dnode_rele_and_unlock(dn, db, B_TRUE);
2151 		db->db_dnode_handle = NULL;
2152 
2153 		dbuf_hash_remove(db);
2154 	} else {
2155 		DB_DNODE_EXIT(db);
2156 	}
2157 
2158 	ASSERT(zfs_refcount_is_zero(&db->db_holds));
2159 
2160 	db->db_parent = NULL;
2161 
2162 	ASSERT(db->db_buf == NULL);
2163 	ASSERT(db->db.db_data == NULL);
2164 	ASSERT(db->db_hash_next == NULL);
2165 	ASSERT(db->db_blkptr == NULL);
2166 	ASSERT(db->db_data_pending == NULL);
2167 	ASSERT3U(db->db_caching_status, ==, DB_NO_CACHE);
2168 	ASSERT(!multilist_link_active(&db->db_cache_link));
2169 
2170 	kmem_cache_free(dbuf_kmem_cache, db);
2171 	arc_space_return(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
2172 
2173 	/*
2174 	 * If this dbuf is referenced from an indirect dbuf,
2175 	 * decrement the ref count on the indirect dbuf.
2176 	 */
2177 	if (parent && parent != dndb) {
2178 		mutex_enter(&parent->db_mtx);
2179 		dbuf_rele_and_unlock(parent, db, B_TRUE);
2180 	}
2181 }
2182 
2183 /*
2184  * Note: While bpp will always be updated if the function returns success,
2185  * parentp will not be updated if the dnode does not have dn_dbuf filled in;
2186  * this happens when the dnode is the meta-dnode, or a userused or groupused
2187  * object.
2188  */
2189 static int
2190 dbuf_findbp(dnode_t *dn, int level, uint64_t blkid, int fail_sparse,
2191     dmu_buf_impl_t **parentp, blkptr_t **bpp)
2192 {
2193 	*parentp = NULL;
2194 	*bpp = NULL;
2195 
2196 	ASSERT(blkid != DMU_BONUS_BLKID);
2197 
2198 	if (blkid == DMU_SPILL_BLKID) {
2199 		mutex_enter(&dn->dn_mtx);
2200 		if (dn->dn_have_spill &&
2201 		    (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR))
2202 			*bpp = DN_SPILL_BLKPTR(dn->dn_phys);
2203 		else
2204 			*bpp = NULL;
2205 		dbuf_add_ref(dn->dn_dbuf, NULL);
2206 		*parentp = dn->dn_dbuf;
2207 		mutex_exit(&dn->dn_mtx);
2208 		return (0);
2209 	}
2210 
2211 	int nlevels =
2212 	    (dn->dn_phys->dn_nlevels == 0) ? 1 : dn->dn_phys->dn_nlevels;
2213 	int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
2214 
2215 	ASSERT3U(level * epbs, <, 64);
2216 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2217 	/*
2218 	 * This assertion shouldn't trip as long as the max indirect block size
2219 	 * is less than 1M.  The reason for this is that up to that point,
2220 	 * the number of levels required to address an entire object with blocks
2221 	 * of size SPA_MINBLOCKSIZE satisfies nlevels * epbs + 1 <= 64.  In
2222 	 * other words, if N * epbs + 1 > 64, then if (N-1) * epbs + 1 > 55
2223 	 * (i.e. we can address the entire object), objects will all use at most
2224 	 * N-1 levels and the assertion won't overflow.  However, once epbs is
2225 	 * 13, 4 * 13 + 1 = 53, but 5 * 13 + 1 = 66.  Then, 4 levels will not be
2226 	 * enough to address an entire object, so objects will have 5 levels,
2227 	 * but then this assertion will overflow.
2228 	 *
2229 	 * All this is to say that if we ever increase DN_MAX_INDBLKSHIFT, we
2230 	 * need to redo this logic to handle overflows.
2231 	 */
2232 	ASSERT(level >= nlevels ||
2233 	    ((nlevels - level - 1) * epbs) +
2234 	    highbit64(dn->dn_phys->dn_nblkptr) <= 64);
2235 	if (level >= nlevels ||
2236 	    blkid >= ((uint64_t)dn->dn_phys->dn_nblkptr <<
2237 	    ((nlevels - level - 1) * epbs)) ||
2238 	    (fail_sparse &&
2239 	    blkid > (dn->dn_phys->dn_maxblkid >> (level * epbs)))) {
2240 		/* the buffer has no parent yet */
2241 		return (SET_ERROR(ENOENT));
2242 	} else if (level < nlevels-1) {
2243 		/* this block is referenced from an indirect block */
2244 		int err = dbuf_hold_impl(dn, level+1,
2245 		    blkid >> epbs, fail_sparse, FALSE, NULL, parentp);
2246 		if (err)
2247 			return (err);
2248 		err = dbuf_read(*parentp, NULL,
2249 		    (DB_RF_HAVESTRUCT | DB_RF_NOPREFETCH | DB_RF_CANFAIL));
2250 		if (err) {
2251 			dbuf_rele(*parentp, NULL);
2252 			*parentp = NULL;
2253 			return (err);
2254 		}
2255 		*bpp = ((blkptr_t *)(*parentp)->db.db_data) +
2256 		    (blkid & ((1ULL << epbs) - 1));
2257 		if (blkid > (dn->dn_phys->dn_maxblkid >> (level * epbs)))
2258 			ASSERT(BP_IS_HOLE(*bpp));
2259 		return (0);
2260 	} else {
2261 		/* the block is referenced from the dnode */
2262 		ASSERT3U(level, ==, nlevels-1);
2263 		ASSERT(dn->dn_phys->dn_nblkptr == 0 ||
2264 		    blkid < dn->dn_phys->dn_nblkptr);
2265 		if (dn->dn_dbuf) {
2266 			dbuf_add_ref(dn->dn_dbuf, NULL);
2267 			*parentp = dn->dn_dbuf;
2268 		}
2269 		*bpp = &dn->dn_phys->dn_blkptr[blkid];
2270 		return (0);
2271 	}
2272 }
2273 
2274 static dmu_buf_impl_t *
2275 dbuf_create(dnode_t *dn, uint8_t level, uint64_t blkid,
2276     dmu_buf_impl_t *parent, blkptr_t *blkptr)
2277 {
2278 	objset_t *os = dn->dn_objset;
2279 	dmu_buf_impl_t *db, *odb;
2280 
2281 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2282 	ASSERT(dn->dn_type != DMU_OT_NONE);
2283 
2284 	db = kmem_cache_alloc(dbuf_kmem_cache, KM_SLEEP);
2285 
2286 	db->db_objset = os;
2287 	db->db.db_object = dn->dn_object;
2288 	db->db_level = level;
2289 	db->db_blkid = blkid;
2290 	db->db_last_dirty = NULL;
2291 	db->db_dirtycnt = 0;
2292 	db->db_dnode_handle = dn->dn_handle;
2293 	db->db_parent = parent;
2294 	db->db_blkptr = blkptr;
2295 
2296 	db->db_user = NULL;
2297 	db->db_user_immediate_evict = FALSE;
2298 	db->db_freed_in_flight = FALSE;
2299 	db->db_pending_evict = FALSE;
2300 
2301 	if (blkid == DMU_BONUS_BLKID) {
2302 		ASSERT3P(parent, ==, dn->dn_dbuf);
2303 		db->db.db_size = DN_SLOTS_TO_BONUSLEN(dn->dn_num_slots) -
2304 		    (dn->dn_nblkptr-1) * sizeof (blkptr_t);
2305 		ASSERT3U(db->db.db_size, >=, dn->dn_bonuslen);
2306 		db->db.db_offset = DMU_BONUS_BLKID;
2307 		db->db_state = DB_UNCACHED;
2308 		db->db_caching_status = DB_NO_CACHE;
2309 		/* the bonus dbuf is not placed in the hash table */
2310 		arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
2311 		return (db);
2312 	} else if (blkid == DMU_SPILL_BLKID) {
2313 		db->db.db_size = (blkptr != NULL) ?
2314 		    BP_GET_LSIZE(blkptr) : SPA_MINBLOCKSIZE;
2315 		db->db.db_offset = 0;
2316 	} else {
2317 		int blocksize =
2318 		    db->db_level ? 1 << dn->dn_indblkshift : dn->dn_datablksz;
2319 		db->db.db_size = blocksize;
2320 		db->db.db_offset = db->db_blkid * blocksize;
2321 	}
2322 
2323 	/*
2324 	 * Hold the dn_dbufs_mtx while we get the new dbuf
2325 	 * in the hash table *and* added to the dbufs list.
2326 	 * This prevents a possible deadlock with someone
2327 	 * trying to look up this dbuf before its added to the
2328 	 * dn_dbufs list.
2329 	 */
2330 	mutex_enter(&dn->dn_dbufs_mtx);
2331 	db->db_state = DB_EVICTING;
2332 	if ((odb = dbuf_hash_insert(db)) != NULL) {
2333 		/* someone else inserted it first */
2334 		kmem_cache_free(dbuf_kmem_cache, db);
2335 		mutex_exit(&dn->dn_dbufs_mtx);
2336 		return (odb);
2337 	}
2338 	avl_add(&dn->dn_dbufs, db);
2339 
2340 	db->db_state = DB_UNCACHED;
2341 	db->db_caching_status = DB_NO_CACHE;
2342 	mutex_exit(&dn->dn_dbufs_mtx);
2343 	arc_space_consume(sizeof (dmu_buf_impl_t), ARC_SPACE_OTHER);
2344 
2345 	if (parent && parent != dn->dn_dbuf)
2346 		dbuf_add_ref(parent, db);
2347 
2348 	ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT ||
2349 	    zfs_refcount_count(&dn->dn_holds) > 0);
2350 	(void) zfs_refcount_add(&dn->dn_holds, db);
2351 	atomic_inc_32(&dn->dn_dbufs_count);
2352 
2353 	dprintf_dbuf(db, "db=%p\n", db);
2354 
2355 	return (db);
2356 }
2357 
2358 typedef struct dbuf_prefetch_arg {
2359 	spa_t *dpa_spa;	/* The spa to issue the prefetch in. */
2360 	zbookmark_phys_t dpa_zb; /* The target block to prefetch. */
2361 	int dpa_epbs; /* Entries (blkptr_t's) Per Block Shift. */
2362 	int dpa_curlevel; /* The current level that we're reading */
2363 	dnode_t *dpa_dnode; /* The dnode associated with the prefetch */
2364 	zio_priority_t dpa_prio; /* The priority I/Os should be issued at. */
2365 	zio_t *dpa_zio; /* The parent zio_t for all prefetches. */
2366 	arc_flags_t dpa_aflags; /* Flags to pass to the final prefetch. */
2367 } dbuf_prefetch_arg_t;
2368 
2369 /*
2370  * Actually issue the prefetch read for the block given.
2371  */
2372 static void
2373 dbuf_issue_final_prefetch(dbuf_prefetch_arg_t *dpa, blkptr_t *bp)
2374 {
2375 	if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
2376 		return;
2377 
2378 	arc_flags_t aflags =
2379 	    dpa->dpa_aflags | ARC_FLAG_NOWAIT | ARC_FLAG_PREFETCH;
2380 
2381 	ASSERT3U(dpa->dpa_curlevel, ==, BP_GET_LEVEL(bp));
2382 	ASSERT3U(dpa->dpa_curlevel, ==, dpa->dpa_zb.zb_level);
2383 	ASSERT(dpa->dpa_zio != NULL);
2384 	(void) arc_read(dpa->dpa_zio, dpa->dpa_spa, bp, NULL, NULL,
2385 	    dpa->dpa_prio, ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
2386 	    &aflags, &dpa->dpa_zb);
2387 }
2388 
2389 /*
2390  * Called when an indirect block above our prefetch target is read in.  This
2391  * will either read in the next indirect block down the tree or issue the actual
2392  * prefetch if the next block down is our target.
2393  */
2394 static void
2395 dbuf_prefetch_indirect_done(zio_t *zio, arc_buf_t *abuf, void *private)
2396 {
2397 	dbuf_prefetch_arg_t *dpa = private;
2398 
2399 	ASSERT3S(dpa->dpa_zb.zb_level, <, dpa->dpa_curlevel);
2400 	ASSERT3S(dpa->dpa_curlevel, >, 0);
2401 
2402 	if (abuf == NULL) {
2403 		ASSERT(zio == NULL || zio->io_error != 0);
2404 		kmem_free(dpa, sizeof (*dpa));
2405 		return;
2406 	}
2407 	ASSERT(zio == NULL || zio->io_error == 0);
2408 
2409 	/*
2410 	 * The dpa_dnode is only valid if we are called with a NULL
2411 	 * zio. This indicates that the arc_read() returned without
2412 	 * first calling zio_read() to issue a physical read. Once
2413 	 * a physical read is made the dpa_dnode must be invalidated
2414 	 * as the locks guarding it may have been dropped. If the
2415 	 * dpa_dnode is still valid, then we want to add it to the dbuf
2416 	 * cache. To do so, we must hold the dbuf associated with the block
2417 	 * we just prefetched, read its contents so that we associate it
2418 	 * with an arc_buf_t, and then release it.
2419 	 */
2420 	if (zio != NULL) {
2421 		ASSERT3S(BP_GET_LEVEL(zio->io_bp), ==, dpa->dpa_curlevel);
2422 		if (zio->io_flags & ZIO_FLAG_RAW) {
2423 			ASSERT3U(BP_GET_PSIZE(zio->io_bp), ==, zio->io_size);
2424 		} else {
2425 			ASSERT3U(BP_GET_LSIZE(zio->io_bp), ==, zio->io_size);
2426 		}
2427 		ASSERT3P(zio->io_spa, ==, dpa->dpa_spa);
2428 
2429 		dpa->dpa_dnode = NULL;
2430 	} else if (dpa->dpa_dnode != NULL) {
2431 		uint64_t curblkid = dpa->dpa_zb.zb_blkid >>
2432 		    (dpa->dpa_epbs * (dpa->dpa_curlevel -
2433 		    dpa->dpa_zb.zb_level));
2434 		dmu_buf_impl_t *db = dbuf_hold_level(dpa->dpa_dnode,
2435 		    dpa->dpa_curlevel, curblkid, FTAG);
2436 		(void) dbuf_read(db, NULL,
2437 		    DB_RF_MUST_SUCCEED | DB_RF_NOPREFETCH | DB_RF_HAVESTRUCT);
2438 		dbuf_rele(db, FTAG);
2439 	}
2440 
2441 	dpa->dpa_curlevel--;
2442 
2443 	uint64_t nextblkid = dpa->dpa_zb.zb_blkid >>
2444 	    (dpa->dpa_epbs * (dpa->dpa_curlevel - dpa->dpa_zb.zb_level));
2445 	blkptr_t *bp = ((blkptr_t *)abuf->b_data) +
2446 	    P2PHASE(nextblkid, 1ULL << dpa->dpa_epbs);
2447 	if (BP_IS_HOLE(bp)) {
2448 		kmem_free(dpa, sizeof (*dpa));
2449 	} else if (dpa->dpa_curlevel == dpa->dpa_zb.zb_level) {
2450 		ASSERT3U(nextblkid, ==, dpa->dpa_zb.zb_blkid);
2451 		dbuf_issue_final_prefetch(dpa, bp);
2452 		kmem_free(dpa, sizeof (*dpa));
2453 	} else {
2454 		arc_flags_t iter_aflags = ARC_FLAG_NOWAIT;
2455 		zbookmark_phys_t zb;
2456 
2457 		/* flag if L2ARC eligible, l2arc_noprefetch then decides */
2458 		if (dpa->dpa_aflags & ARC_FLAG_L2CACHE)
2459 			iter_aflags |= ARC_FLAG_L2CACHE;
2460 
2461 		ASSERT3U(dpa->dpa_curlevel, ==, BP_GET_LEVEL(bp));
2462 
2463 		SET_BOOKMARK(&zb, dpa->dpa_zb.zb_objset,
2464 		    dpa->dpa_zb.zb_object, dpa->dpa_curlevel, nextblkid);
2465 
2466 		(void) arc_read(dpa->dpa_zio, dpa->dpa_spa,
2467 		    bp, dbuf_prefetch_indirect_done, dpa, dpa->dpa_prio,
2468 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
2469 		    &iter_aflags, &zb);
2470 	}
2471 
2472 	arc_buf_destroy(abuf, private);
2473 }
2474 
2475 /*
2476  * Issue prefetch reads for the given block on the given level.  If the indirect
2477  * blocks above that block are not in memory, we will read them in
2478  * asynchronously.  As a result, this call never blocks waiting for a read to
2479  * complete.
2480  */
2481 void
2482 dbuf_prefetch(dnode_t *dn, int64_t level, uint64_t blkid, zio_priority_t prio,
2483     arc_flags_t aflags)
2484 {
2485 	blkptr_t bp;
2486 	int epbs, nlevels, curlevel;
2487 	uint64_t curblkid;
2488 
2489 	ASSERT(blkid != DMU_BONUS_BLKID);
2490 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2491 
2492 	if (blkid > dn->dn_maxblkid)
2493 		return;
2494 
2495 	if (dnode_block_freed(dn, blkid))
2496 		return;
2497 
2498 	/*
2499 	 * This dnode hasn't been written to disk yet, so there's nothing to
2500 	 * prefetch.
2501 	 */
2502 	nlevels = dn->dn_phys->dn_nlevels;
2503 	if (level >= nlevels || dn->dn_phys->dn_nblkptr == 0)
2504 		return;
2505 
2506 	epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
2507 	if (dn->dn_phys->dn_maxblkid < blkid << (epbs * level))
2508 		return;
2509 
2510 	dmu_buf_impl_t *db = dbuf_find(dn->dn_objset, dn->dn_object,
2511 	    level, blkid);
2512 	if (db != NULL) {
2513 		mutex_exit(&db->db_mtx);
2514 		/*
2515 		 * This dbuf already exists.  It is either CACHED, or
2516 		 * (we assume) about to be read or filled.
2517 		 */
2518 		return;
2519 	}
2520 
2521 	/*
2522 	 * Find the closest ancestor (indirect block) of the target block
2523 	 * that is present in the cache.  In this indirect block, we will
2524 	 * find the bp that is at curlevel, curblkid.
2525 	 */
2526 	curlevel = level;
2527 	curblkid = blkid;
2528 	while (curlevel < nlevels - 1) {
2529 		int parent_level = curlevel + 1;
2530 		uint64_t parent_blkid = curblkid >> epbs;
2531 		dmu_buf_impl_t *db;
2532 
2533 		if (dbuf_hold_impl(dn, parent_level, parent_blkid,
2534 		    FALSE, TRUE, FTAG, &db) == 0) {
2535 			blkptr_t *bpp = db->db_buf->b_data;
2536 			bp = bpp[P2PHASE(curblkid, 1 << epbs)];
2537 			dbuf_rele(db, FTAG);
2538 			break;
2539 		}
2540 
2541 		curlevel = parent_level;
2542 		curblkid = parent_blkid;
2543 	}
2544 
2545 	if (curlevel == nlevels - 1) {
2546 		/* No cached indirect blocks found. */
2547 		ASSERT3U(curblkid, <, dn->dn_phys->dn_nblkptr);
2548 		bp = dn->dn_phys->dn_blkptr[curblkid];
2549 	}
2550 	if (BP_IS_HOLE(&bp))
2551 		return;
2552 
2553 	ASSERT3U(curlevel, ==, BP_GET_LEVEL(&bp));
2554 
2555 	zio_t *pio = zio_root(dmu_objset_spa(dn->dn_objset), NULL, NULL,
2556 	    ZIO_FLAG_CANFAIL);
2557 
2558 	dbuf_prefetch_arg_t *dpa = kmem_zalloc(sizeof (*dpa), KM_SLEEP);
2559 	dsl_dataset_t *ds = dn->dn_objset->os_dsl_dataset;
2560 	SET_BOOKMARK(&dpa->dpa_zb, ds != NULL ? ds->ds_object : DMU_META_OBJSET,
2561 	    dn->dn_object, level, blkid);
2562 	dpa->dpa_curlevel = curlevel;
2563 	dpa->dpa_prio = prio;
2564 	dpa->dpa_aflags = aflags;
2565 	dpa->dpa_spa = dn->dn_objset->os_spa;
2566 	dpa->dpa_dnode = dn;
2567 	dpa->dpa_epbs = epbs;
2568 	dpa->dpa_zio = pio;
2569 
2570 	/* flag if L2ARC eligible, l2arc_noprefetch then decides */
2571 	if (DNODE_LEVEL_IS_L2CACHEABLE(dn, level))
2572 		dpa->dpa_aflags |= ARC_FLAG_L2CACHE;
2573 
2574 	/*
2575 	 * If we have the indirect just above us, no need to do the asynchronous
2576 	 * prefetch chain; we'll just run the last step ourselves.  If we're at
2577 	 * a higher level, though, we want to issue the prefetches for all the
2578 	 * indirect blocks asynchronously, so we can go on with whatever we were
2579 	 * doing.
2580 	 */
2581 	if (curlevel == level) {
2582 		ASSERT3U(curblkid, ==, blkid);
2583 		dbuf_issue_final_prefetch(dpa, &bp);
2584 		kmem_free(dpa, sizeof (*dpa));
2585 	} else {
2586 		arc_flags_t iter_aflags = ARC_FLAG_NOWAIT;
2587 		zbookmark_phys_t zb;
2588 
2589 		/* flag if L2ARC eligible, l2arc_noprefetch then decides */
2590 		if (DNODE_LEVEL_IS_L2CACHEABLE(dn, level))
2591 			iter_aflags |= ARC_FLAG_L2CACHE;
2592 
2593 		SET_BOOKMARK(&zb, ds != NULL ? ds->ds_object : DMU_META_OBJSET,
2594 		    dn->dn_object, curlevel, curblkid);
2595 		(void) arc_read(dpa->dpa_zio, dpa->dpa_spa,
2596 		    &bp, dbuf_prefetch_indirect_done, dpa, prio,
2597 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
2598 		    &iter_aflags, &zb);
2599 	}
2600 	/*
2601 	 * We use pio here instead of dpa_zio since it's possible that
2602 	 * dpa may have already been freed.
2603 	 */
2604 	zio_nowait(pio);
2605 }
2606 
2607 /*
2608  * Returns with db_holds incremented, and db_mtx not held.
2609  * Note: dn_struct_rwlock must be held.
2610  */
2611 int
2612 dbuf_hold_impl(dnode_t *dn, uint8_t level, uint64_t blkid,
2613     boolean_t fail_sparse, boolean_t fail_uncached,
2614     void *tag, dmu_buf_impl_t **dbp)
2615 {
2616 	dmu_buf_impl_t *db, *parent = NULL;
2617 
2618 	ASSERT(blkid != DMU_BONUS_BLKID);
2619 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2620 	ASSERT3U(dn->dn_nlevels, >, level);
2621 
2622 	*dbp = NULL;
2623 top:
2624 	/* dbuf_find() returns with db_mtx held */
2625 	db = dbuf_find(dn->dn_objset, dn->dn_object, level, blkid);
2626 
2627 	if (db == NULL) {
2628 		blkptr_t *bp = NULL;
2629 		int err;
2630 
2631 		if (fail_uncached)
2632 			return (SET_ERROR(ENOENT));
2633 
2634 		ASSERT3P(parent, ==, NULL);
2635 		err = dbuf_findbp(dn, level, blkid, fail_sparse, &parent, &bp);
2636 		if (fail_sparse) {
2637 			if (err == 0 && bp && BP_IS_HOLE(bp))
2638 				err = SET_ERROR(ENOENT);
2639 			if (err) {
2640 				if (parent)
2641 					dbuf_rele(parent, NULL);
2642 				return (err);
2643 			}
2644 		}
2645 		if (err && err != ENOENT)
2646 			return (err);
2647 		db = dbuf_create(dn, level, blkid, parent, bp);
2648 	}
2649 
2650 	if (fail_uncached && db->db_state != DB_CACHED) {
2651 		mutex_exit(&db->db_mtx);
2652 		return (SET_ERROR(ENOENT));
2653 	}
2654 
2655 	if (db->db_buf != NULL) {
2656 		arc_buf_access(db->db_buf);
2657 		ASSERT3P(db->db.db_data, ==, db->db_buf->b_data);
2658 	}
2659 
2660 	ASSERT(db->db_buf == NULL || arc_referenced(db->db_buf));
2661 
2662 	/*
2663 	 * If this buffer is currently syncing out, and we are are
2664 	 * still referencing it from db_data, we need to make a copy
2665 	 * of it in case we decide we want to dirty it again in this txg.
2666 	 */
2667 	if (db->db_level == 0 && db->db_blkid != DMU_BONUS_BLKID &&
2668 	    dn->dn_object != DMU_META_DNODE_OBJECT &&
2669 	    db->db_state == DB_CACHED && db->db_data_pending) {
2670 		dbuf_dirty_record_t *dr = db->db_data_pending;
2671 
2672 		if (dr->dt.dl.dr_data == db->db_buf) {
2673 			arc_buf_contents_t type = DBUF_GET_BUFC_TYPE(db);
2674 
2675 			dbuf_set_data(db,
2676 			    arc_alloc_buf(dn->dn_objset->os_spa, db, type,
2677 			    db->db.db_size));
2678 			bcopy(dr->dt.dl.dr_data->b_data, db->db.db_data,
2679 			    db->db.db_size);
2680 		}
2681 	}
2682 
2683 	if (multilist_link_active(&db->db_cache_link)) {
2684 		ASSERT(zfs_refcount_is_zero(&db->db_holds));
2685 		ASSERT(db->db_caching_status == DB_DBUF_CACHE ||
2686 		    db->db_caching_status == DB_DBUF_METADATA_CACHE);
2687 
2688 		multilist_remove(dbuf_caches[db->db_caching_status].cache, db);
2689 		(void) zfs_refcount_remove_many(
2690 		    &dbuf_caches[db->db_caching_status].size,
2691 		    db->db.db_size, db);
2692 
2693 		db->db_caching_status = DB_NO_CACHE;
2694 	}
2695 	(void) zfs_refcount_add(&db->db_holds, tag);
2696 	DBUF_VERIFY(db);
2697 	mutex_exit(&db->db_mtx);
2698 
2699 	/* NOTE: we can't rele the parent until after we drop the db_mtx */
2700 	if (parent)
2701 		dbuf_rele(parent, NULL);
2702 
2703 	ASSERT3P(DB_DNODE(db), ==, dn);
2704 	ASSERT3U(db->db_blkid, ==, blkid);
2705 	ASSERT3U(db->db_level, ==, level);
2706 	*dbp = db;
2707 
2708 	return (0);
2709 }
2710 
2711 dmu_buf_impl_t *
2712 dbuf_hold(dnode_t *dn, uint64_t blkid, void *tag)
2713 {
2714 	return (dbuf_hold_level(dn, 0, blkid, tag));
2715 }
2716 
2717 dmu_buf_impl_t *
2718 dbuf_hold_level(dnode_t *dn, int level, uint64_t blkid, void *tag)
2719 {
2720 	dmu_buf_impl_t *db;
2721 	int err = dbuf_hold_impl(dn, level, blkid, FALSE, FALSE, tag, &db);
2722 	return (err ? NULL : db);
2723 }
2724 
2725 void
2726 dbuf_create_bonus(dnode_t *dn)
2727 {
2728 	ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
2729 
2730 	ASSERT(dn->dn_bonus == NULL);
2731 	dn->dn_bonus = dbuf_create(dn, 0, DMU_BONUS_BLKID, dn->dn_dbuf, NULL);
2732 }
2733 
2734 int
2735 dbuf_spill_set_blksz(dmu_buf_t *db_fake, uint64_t blksz, dmu_tx_t *tx)
2736 {
2737 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2738 	dnode_t *dn;
2739 
2740 	if (db->db_blkid != DMU_SPILL_BLKID)
2741 		return (SET_ERROR(ENOTSUP));
2742 	if (blksz == 0)
2743 		blksz = SPA_MINBLOCKSIZE;
2744 	ASSERT3U(blksz, <=, spa_maxblocksize(dmu_objset_spa(db->db_objset)));
2745 	blksz = P2ROUNDUP(blksz, SPA_MINBLOCKSIZE);
2746 
2747 	DB_DNODE_ENTER(db);
2748 	dn = DB_DNODE(db);
2749 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
2750 	dbuf_new_size(db, blksz, tx);
2751 	rw_exit(&dn->dn_struct_rwlock);
2752 	DB_DNODE_EXIT(db);
2753 
2754 	return (0);
2755 }
2756 
2757 void
2758 dbuf_rm_spill(dnode_t *dn, dmu_tx_t *tx)
2759 {
2760 	dbuf_free_range(dn, DMU_SPILL_BLKID, DMU_SPILL_BLKID, tx);
2761 }
2762 
2763 #pragma weak dmu_buf_add_ref = dbuf_add_ref
2764 void
2765 dbuf_add_ref(dmu_buf_impl_t *db, void *tag)
2766 {
2767 	int64_t holds = zfs_refcount_add(&db->db_holds, tag);
2768 	ASSERT3S(holds, >, 1);
2769 }
2770 
2771 #pragma weak dmu_buf_try_add_ref = dbuf_try_add_ref
2772 boolean_t
2773 dbuf_try_add_ref(dmu_buf_t *db_fake, objset_t *os, uint64_t obj, uint64_t blkid,
2774     void *tag)
2775 {
2776 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
2777 	dmu_buf_impl_t *found_db;
2778 	boolean_t result = B_FALSE;
2779 
2780 	if (db->db_blkid == DMU_BONUS_BLKID)
2781 		found_db = dbuf_find_bonus(os, obj);
2782 	else
2783 		found_db = dbuf_find(os, obj, 0, blkid);
2784 
2785 	if (found_db != NULL) {
2786 		if (db == found_db && dbuf_refcount(db) > db->db_dirtycnt) {
2787 			(void) zfs_refcount_add(&db->db_holds, tag);
2788 			result = B_TRUE;
2789 		}
2790 		mutex_exit(&db->db_mtx);
2791 	}
2792 	return (result);
2793 }
2794 
2795 /*
2796  * If you call dbuf_rele() you had better not be referencing the dnode handle
2797  * unless you have some other direct or indirect hold on the dnode. (An indirect
2798  * hold is a hold on one of the dnode's dbufs, including the bonus buffer.)
2799  * Without that, the dbuf_rele() could lead to a dnode_rele() followed by the
2800  * dnode's parent dbuf evicting its dnode handles.
2801  */
2802 void
2803 dbuf_rele(dmu_buf_impl_t *db, void *tag)
2804 {
2805 	mutex_enter(&db->db_mtx);
2806 	dbuf_rele_and_unlock(db, tag, B_FALSE);
2807 }
2808 
2809 void
2810 dmu_buf_rele(dmu_buf_t *db, void *tag)
2811 {
2812 	dbuf_rele((dmu_buf_impl_t *)db, tag);
2813 }
2814 
2815 /*
2816  * dbuf_rele() for an already-locked dbuf.  This is necessary to allow
2817  * db_dirtycnt and db_holds to be updated atomically.  The 'evicting'
2818  * argument should be set if we are already in the dbuf-evicting code
2819  * path, in which case we don't want to recursively evict.  This allows us to
2820  * avoid deeply nested stacks that would have a call flow similar to this:
2821  *
2822  * dbuf_rele()-->dbuf_rele_and_unlock()-->dbuf_evict_notify()
2823  *	^						|
2824  *	|						|
2825  *	+-----dbuf_destroy()<--dbuf_evict_one()<--------+
2826  *
2827  */
2828 void
2829 dbuf_rele_and_unlock(dmu_buf_impl_t *db, void *tag, boolean_t evicting)
2830 {
2831 	int64_t holds;
2832 
2833 	ASSERT(MUTEX_HELD(&db->db_mtx));
2834 	DBUF_VERIFY(db);
2835 
2836 	/*
2837 	 * Remove the reference to the dbuf before removing its hold on the
2838 	 * dnode so we can guarantee in dnode_move() that a referenced bonus
2839 	 * buffer has a corresponding dnode hold.
2840 	 */
2841 	holds = zfs_refcount_remove(&db->db_holds, tag);
2842 	ASSERT(holds >= 0);
2843 
2844 	/*
2845 	 * We can't freeze indirects if there is a possibility that they
2846 	 * may be modified in the current syncing context.
2847 	 */
2848 	if (db->db_buf != NULL &&
2849 	    holds == (db->db_level == 0 ? db->db_dirtycnt : 0)) {
2850 		arc_buf_freeze(db->db_buf);
2851 	}
2852 
2853 	if (holds == db->db_dirtycnt &&
2854 	    db->db_level == 0 && db->db_user_immediate_evict)
2855 		dbuf_evict_user(db);
2856 
2857 	if (holds == 0) {
2858 		if (db->db_blkid == DMU_BONUS_BLKID) {
2859 			dnode_t *dn;
2860 			boolean_t evict_dbuf = db->db_pending_evict;
2861 
2862 			/*
2863 			 * If the dnode moves here, we cannot cross this
2864 			 * barrier until the move completes.
2865 			 */
2866 			DB_DNODE_ENTER(db);
2867 
2868 			dn = DB_DNODE(db);
2869 			atomic_dec_32(&dn->dn_dbufs_count);
2870 
2871 			/*
2872 			 * Decrementing the dbuf count means that the bonus
2873 			 * buffer's dnode hold is no longer discounted in
2874 			 * dnode_move(). The dnode cannot move until after
2875 			 * the dnode_rele() below.
2876 			 */
2877 			DB_DNODE_EXIT(db);
2878 
2879 			/*
2880 			 * Do not reference db after its lock is dropped.
2881 			 * Another thread may evict it.
2882 			 */
2883 			mutex_exit(&db->db_mtx);
2884 
2885 			if (evict_dbuf)
2886 				dnode_evict_bonus(dn);
2887 
2888 			dnode_rele(dn, db);
2889 		} else if (db->db_buf == NULL) {
2890 			/*
2891 			 * This is a special case: we never associated this
2892 			 * dbuf with any data allocated from the ARC.
2893 			 */
2894 			ASSERT(db->db_state == DB_UNCACHED ||
2895 			    db->db_state == DB_NOFILL);
2896 			dbuf_destroy(db);
2897 		} else if (arc_released(db->db_buf)) {
2898 			/*
2899 			 * This dbuf has anonymous data associated with it.
2900 			 */
2901 			dbuf_destroy(db);
2902 		} else {
2903 			boolean_t do_arc_evict = B_FALSE;
2904 			blkptr_t bp;
2905