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