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