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