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