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