xref: /freebsd/sys/contrib/openzfs/module/zfs/dnode.c (revision b197d4b893974c9eb4d7b38704c6d5c486235d6f)
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 https://opensource.org/licenses/CDDL-1.0.
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 (c) 2012, 2020 by Delphix. All rights reserved.
24  * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
25  */
26 
27 #include <sys/zfs_context.h>
28 #include <sys/dbuf.h>
29 #include <sys/dnode.h>
30 #include <sys/dmu.h>
31 #include <sys/dmu_impl.h>
32 #include <sys/dmu_tx.h>
33 #include <sys/dmu_objset.h>
34 #include <sys/dsl_dir.h>
35 #include <sys/dsl_dataset.h>
36 #include <sys/spa.h>
37 #include <sys/zio.h>
38 #include <sys/dmu_zfetch.h>
39 #include <sys/range_tree.h>
40 #include <sys/trace_zfs.h>
41 #include <sys/zfs_project.h>
42 
43 dnode_stats_t dnode_stats = {
44 	{ "dnode_hold_dbuf_hold",		KSTAT_DATA_UINT64 },
45 	{ "dnode_hold_dbuf_read",		KSTAT_DATA_UINT64 },
46 	{ "dnode_hold_alloc_hits",		KSTAT_DATA_UINT64 },
47 	{ "dnode_hold_alloc_misses",		KSTAT_DATA_UINT64 },
48 	{ "dnode_hold_alloc_interior",		KSTAT_DATA_UINT64 },
49 	{ "dnode_hold_alloc_lock_retry",	KSTAT_DATA_UINT64 },
50 	{ "dnode_hold_alloc_lock_misses",	KSTAT_DATA_UINT64 },
51 	{ "dnode_hold_alloc_type_none",		KSTAT_DATA_UINT64 },
52 	{ "dnode_hold_free_hits",		KSTAT_DATA_UINT64 },
53 	{ "dnode_hold_free_misses",		KSTAT_DATA_UINT64 },
54 	{ "dnode_hold_free_lock_misses",	KSTAT_DATA_UINT64 },
55 	{ "dnode_hold_free_lock_retry",		KSTAT_DATA_UINT64 },
56 	{ "dnode_hold_free_overflow",		KSTAT_DATA_UINT64 },
57 	{ "dnode_hold_free_refcount",		KSTAT_DATA_UINT64 },
58 	{ "dnode_free_interior_lock_retry",	KSTAT_DATA_UINT64 },
59 	{ "dnode_allocate",			KSTAT_DATA_UINT64 },
60 	{ "dnode_reallocate",			KSTAT_DATA_UINT64 },
61 	{ "dnode_buf_evict",			KSTAT_DATA_UINT64 },
62 	{ "dnode_alloc_next_chunk",		KSTAT_DATA_UINT64 },
63 	{ "dnode_alloc_race",			KSTAT_DATA_UINT64 },
64 	{ "dnode_alloc_next_block",		KSTAT_DATA_UINT64 },
65 	{ "dnode_move_invalid",			KSTAT_DATA_UINT64 },
66 	{ "dnode_move_recheck1",		KSTAT_DATA_UINT64 },
67 	{ "dnode_move_recheck2",		KSTAT_DATA_UINT64 },
68 	{ "dnode_move_special",			KSTAT_DATA_UINT64 },
69 	{ "dnode_move_handle",			KSTAT_DATA_UINT64 },
70 	{ "dnode_move_rwlock",			KSTAT_DATA_UINT64 },
71 	{ "dnode_move_active",			KSTAT_DATA_UINT64 },
72 };
73 
74 static kstat_t *dnode_ksp;
75 static kmem_cache_t *dnode_cache;
76 
77 static dnode_phys_t dnode_phys_zero __maybe_unused;
78 
79 int zfs_default_bs = SPA_MINBLOCKSHIFT;
80 int zfs_default_ibs = DN_MAX_INDBLKSHIFT;
81 
82 #ifdef	_KERNEL
83 static kmem_cbrc_t dnode_move(void *, void *, size_t, void *);
84 #endif /* _KERNEL */
85 
86 static int
87 dbuf_compare(const void *x1, const void *x2)
88 {
89 	const dmu_buf_impl_t *d1 = x1;
90 	const dmu_buf_impl_t *d2 = x2;
91 
92 	int cmp = TREE_CMP(d1->db_level, d2->db_level);
93 	if (likely(cmp))
94 		return (cmp);
95 
96 	cmp = TREE_CMP(d1->db_blkid, d2->db_blkid);
97 	if (likely(cmp))
98 		return (cmp);
99 
100 	if (d1->db_state == DB_SEARCH) {
101 		ASSERT3S(d2->db_state, !=, DB_SEARCH);
102 		return (-1);
103 	} else if (d2->db_state == DB_SEARCH) {
104 		ASSERT3S(d1->db_state, !=, DB_SEARCH);
105 		return (1);
106 	}
107 
108 	return (TREE_PCMP(d1, d2));
109 }
110 
111 static int
112 dnode_cons(void *arg, void *unused, int kmflag)
113 {
114 	(void) unused, (void) kmflag;
115 	dnode_t *dn = arg;
116 
117 	rw_init(&dn->dn_struct_rwlock, NULL, RW_NOLOCKDEP, NULL);
118 	mutex_init(&dn->dn_mtx, NULL, MUTEX_DEFAULT, NULL);
119 	mutex_init(&dn->dn_dbufs_mtx, NULL, MUTEX_DEFAULT, NULL);
120 	cv_init(&dn->dn_notxholds, NULL, CV_DEFAULT, NULL);
121 	cv_init(&dn->dn_nodnholds, NULL, CV_DEFAULT, NULL);
122 
123 	/*
124 	 * Every dbuf has a reference, and dropping a tracked reference is
125 	 * O(number of references), so don't track dn_holds.
126 	 */
127 	zfs_refcount_create_untracked(&dn->dn_holds);
128 	zfs_refcount_create(&dn->dn_tx_holds);
129 	list_link_init(&dn->dn_link);
130 
131 	memset(dn->dn_next_type, 0, sizeof (dn->dn_next_type));
132 	memset(dn->dn_next_nblkptr, 0, sizeof (dn->dn_next_nblkptr));
133 	memset(dn->dn_next_nlevels, 0, sizeof (dn->dn_next_nlevels));
134 	memset(dn->dn_next_indblkshift, 0, sizeof (dn->dn_next_indblkshift));
135 	memset(dn->dn_next_bonustype, 0, sizeof (dn->dn_next_bonustype));
136 	memset(dn->dn_rm_spillblk, 0, sizeof (dn->dn_rm_spillblk));
137 	memset(dn->dn_next_bonuslen, 0, sizeof (dn->dn_next_bonuslen));
138 	memset(dn->dn_next_blksz, 0, sizeof (dn->dn_next_blksz));
139 	memset(dn->dn_next_maxblkid, 0, sizeof (dn->dn_next_maxblkid));
140 
141 	for (int i = 0; i < TXG_SIZE; i++) {
142 		multilist_link_init(&dn->dn_dirty_link[i]);
143 		dn->dn_free_ranges[i] = NULL;
144 		list_create(&dn->dn_dirty_records[i],
145 		    sizeof (dbuf_dirty_record_t),
146 		    offsetof(dbuf_dirty_record_t, dr_dirty_node));
147 	}
148 
149 	dn->dn_allocated_txg = 0;
150 	dn->dn_free_txg = 0;
151 	dn->dn_assigned_txg = 0;
152 	dn->dn_dirty_txg = 0;
153 	dn->dn_dirtyctx = 0;
154 	dn->dn_dirtyctx_firstset = NULL;
155 	dn->dn_bonus = NULL;
156 	dn->dn_have_spill = B_FALSE;
157 	dn->dn_zio = NULL;
158 	dn->dn_oldused = 0;
159 	dn->dn_oldflags = 0;
160 	dn->dn_olduid = 0;
161 	dn->dn_oldgid = 0;
162 	dn->dn_oldprojid = ZFS_DEFAULT_PROJID;
163 	dn->dn_newuid = 0;
164 	dn->dn_newgid = 0;
165 	dn->dn_newprojid = ZFS_DEFAULT_PROJID;
166 	dn->dn_id_flags = 0;
167 
168 	dn->dn_dbufs_count = 0;
169 	avl_create(&dn->dn_dbufs, dbuf_compare, sizeof (dmu_buf_impl_t),
170 	    offsetof(dmu_buf_impl_t, db_link));
171 
172 	dn->dn_moved = 0;
173 	return (0);
174 }
175 
176 static void
177 dnode_dest(void *arg, void *unused)
178 {
179 	(void) unused;
180 	dnode_t *dn = arg;
181 
182 	rw_destroy(&dn->dn_struct_rwlock);
183 	mutex_destroy(&dn->dn_mtx);
184 	mutex_destroy(&dn->dn_dbufs_mtx);
185 	cv_destroy(&dn->dn_notxholds);
186 	cv_destroy(&dn->dn_nodnholds);
187 	zfs_refcount_destroy(&dn->dn_holds);
188 	zfs_refcount_destroy(&dn->dn_tx_holds);
189 	ASSERT(!list_link_active(&dn->dn_link));
190 
191 	for (int i = 0; i < TXG_SIZE; i++) {
192 		ASSERT(!multilist_link_active(&dn->dn_dirty_link[i]));
193 		ASSERT3P(dn->dn_free_ranges[i], ==, NULL);
194 		list_destroy(&dn->dn_dirty_records[i]);
195 		ASSERT0(dn->dn_next_nblkptr[i]);
196 		ASSERT0(dn->dn_next_nlevels[i]);
197 		ASSERT0(dn->dn_next_indblkshift[i]);
198 		ASSERT0(dn->dn_next_bonustype[i]);
199 		ASSERT0(dn->dn_rm_spillblk[i]);
200 		ASSERT0(dn->dn_next_bonuslen[i]);
201 		ASSERT0(dn->dn_next_blksz[i]);
202 		ASSERT0(dn->dn_next_maxblkid[i]);
203 	}
204 
205 	ASSERT0(dn->dn_allocated_txg);
206 	ASSERT0(dn->dn_free_txg);
207 	ASSERT0(dn->dn_assigned_txg);
208 	ASSERT0(dn->dn_dirty_txg);
209 	ASSERT0(dn->dn_dirtyctx);
210 	ASSERT3P(dn->dn_dirtyctx_firstset, ==, NULL);
211 	ASSERT3P(dn->dn_bonus, ==, NULL);
212 	ASSERT(!dn->dn_have_spill);
213 	ASSERT3P(dn->dn_zio, ==, NULL);
214 	ASSERT0(dn->dn_oldused);
215 	ASSERT0(dn->dn_oldflags);
216 	ASSERT0(dn->dn_olduid);
217 	ASSERT0(dn->dn_oldgid);
218 	ASSERT0(dn->dn_oldprojid);
219 	ASSERT0(dn->dn_newuid);
220 	ASSERT0(dn->dn_newgid);
221 	ASSERT0(dn->dn_newprojid);
222 	ASSERT0(dn->dn_id_flags);
223 
224 	ASSERT0(dn->dn_dbufs_count);
225 	avl_destroy(&dn->dn_dbufs);
226 }
227 
228 void
229 dnode_init(void)
230 {
231 	ASSERT(dnode_cache == NULL);
232 	dnode_cache = kmem_cache_create("dnode_t", sizeof (dnode_t),
233 	    0, dnode_cons, dnode_dest, NULL, NULL, NULL, 0);
234 	kmem_cache_set_move(dnode_cache, dnode_move);
235 
236 	dnode_ksp = kstat_create("zfs", 0, "dnodestats", "misc",
237 	    KSTAT_TYPE_NAMED, sizeof (dnode_stats) / sizeof (kstat_named_t),
238 	    KSTAT_FLAG_VIRTUAL);
239 	if (dnode_ksp != NULL) {
240 		dnode_ksp->ks_data = &dnode_stats;
241 		kstat_install(dnode_ksp);
242 	}
243 }
244 
245 void
246 dnode_fini(void)
247 {
248 	if (dnode_ksp != NULL) {
249 		kstat_delete(dnode_ksp);
250 		dnode_ksp = NULL;
251 	}
252 
253 	kmem_cache_destroy(dnode_cache);
254 	dnode_cache = NULL;
255 }
256 
257 
258 #ifdef ZFS_DEBUG
259 void
260 dnode_verify(dnode_t *dn)
261 {
262 	int drop_struct_lock = FALSE;
263 
264 	ASSERT(dn->dn_phys);
265 	ASSERT(dn->dn_objset);
266 	ASSERT(dn->dn_handle->dnh_dnode == dn);
267 
268 	ASSERT(DMU_OT_IS_VALID(dn->dn_phys->dn_type));
269 
270 	if (!(zfs_flags & ZFS_DEBUG_DNODE_VERIFY))
271 		return;
272 
273 	if (!RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
274 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
275 		drop_struct_lock = TRUE;
276 	}
277 	if (dn->dn_phys->dn_type != DMU_OT_NONE || dn->dn_allocated_txg != 0) {
278 		int i;
279 		int max_bonuslen = DN_SLOTS_TO_BONUSLEN(dn->dn_num_slots);
280 		ASSERT3U(dn->dn_indblkshift, <=, SPA_MAXBLOCKSHIFT);
281 		if (dn->dn_datablkshift) {
282 			ASSERT3U(dn->dn_datablkshift, >=, SPA_MINBLOCKSHIFT);
283 			ASSERT3U(dn->dn_datablkshift, <=, SPA_MAXBLOCKSHIFT);
284 			ASSERT3U(1<<dn->dn_datablkshift, ==, dn->dn_datablksz);
285 		}
286 		ASSERT3U(dn->dn_nlevels, <=, 30);
287 		ASSERT(DMU_OT_IS_VALID(dn->dn_type));
288 		ASSERT3U(dn->dn_nblkptr, >=, 1);
289 		ASSERT3U(dn->dn_nblkptr, <=, DN_MAX_NBLKPTR);
290 		ASSERT3U(dn->dn_bonuslen, <=, max_bonuslen);
291 		ASSERT3U(dn->dn_datablksz, ==,
292 		    dn->dn_datablkszsec << SPA_MINBLOCKSHIFT);
293 		ASSERT3U(ISP2(dn->dn_datablksz), ==, dn->dn_datablkshift != 0);
294 		ASSERT3U((dn->dn_nblkptr - 1) * sizeof (blkptr_t) +
295 		    dn->dn_bonuslen, <=, max_bonuslen);
296 		for (i = 0; i < TXG_SIZE; i++) {
297 			ASSERT3U(dn->dn_next_nlevels[i], <=, dn->dn_nlevels);
298 		}
299 	}
300 	if (dn->dn_phys->dn_type != DMU_OT_NONE)
301 		ASSERT3U(dn->dn_phys->dn_nlevels, <=, dn->dn_nlevels);
302 	ASSERT(DMU_OBJECT_IS_SPECIAL(dn->dn_object) || dn->dn_dbuf != NULL);
303 	if (dn->dn_dbuf != NULL) {
304 		ASSERT3P(dn->dn_phys, ==,
305 		    (dnode_phys_t *)dn->dn_dbuf->db.db_data +
306 		    (dn->dn_object % (dn->dn_dbuf->db.db_size >> DNODE_SHIFT)));
307 	}
308 	if (drop_struct_lock)
309 		rw_exit(&dn->dn_struct_rwlock);
310 }
311 #endif
312 
313 void
314 dnode_byteswap(dnode_phys_t *dnp)
315 {
316 	uint64_t *buf64 = (void*)&dnp->dn_blkptr;
317 	int i;
318 
319 	if (dnp->dn_type == DMU_OT_NONE) {
320 		memset(dnp, 0, sizeof (dnode_phys_t));
321 		return;
322 	}
323 
324 	dnp->dn_datablkszsec = BSWAP_16(dnp->dn_datablkszsec);
325 	dnp->dn_bonuslen = BSWAP_16(dnp->dn_bonuslen);
326 	dnp->dn_extra_slots = BSWAP_8(dnp->dn_extra_slots);
327 	dnp->dn_maxblkid = BSWAP_64(dnp->dn_maxblkid);
328 	dnp->dn_used = BSWAP_64(dnp->dn_used);
329 
330 	/*
331 	 * dn_nblkptr is only one byte, so it's OK to read it in either
332 	 * byte order.  We can't read dn_bouslen.
333 	 */
334 	ASSERT(dnp->dn_indblkshift <= SPA_MAXBLOCKSHIFT);
335 	ASSERT(dnp->dn_nblkptr <= DN_MAX_NBLKPTR);
336 	for (i = 0; i < dnp->dn_nblkptr * sizeof (blkptr_t)/8; i++)
337 		buf64[i] = BSWAP_64(buf64[i]);
338 
339 	/*
340 	 * OK to check dn_bonuslen for zero, because it won't matter if
341 	 * we have the wrong byte order.  This is necessary because the
342 	 * dnode dnode is smaller than a regular dnode.
343 	 */
344 	if (dnp->dn_bonuslen != 0) {
345 		dmu_object_byteswap_t byteswap;
346 		ASSERT(DMU_OT_IS_VALID(dnp->dn_bonustype));
347 		byteswap = DMU_OT_BYTESWAP(dnp->dn_bonustype);
348 		dmu_ot_byteswap[byteswap].ob_func(DN_BONUS(dnp),
349 		    DN_MAX_BONUS_LEN(dnp));
350 	}
351 
352 	/* Swap SPILL block if we have one */
353 	if (dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR)
354 		byteswap_uint64_array(DN_SPILL_BLKPTR(dnp), sizeof (blkptr_t));
355 }
356 
357 void
358 dnode_buf_byteswap(void *vbuf, size_t size)
359 {
360 	int i = 0;
361 
362 	ASSERT3U(sizeof (dnode_phys_t), ==, (1<<DNODE_SHIFT));
363 	ASSERT((size & (sizeof (dnode_phys_t)-1)) == 0);
364 
365 	while (i < size) {
366 		dnode_phys_t *dnp = (void *)(((char *)vbuf) + i);
367 		dnode_byteswap(dnp);
368 
369 		i += DNODE_MIN_SIZE;
370 		if (dnp->dn_type != DMU_OT_NONE)
371 			i += dnp->dn_extra_slots * DNODE_MIN_SIZE;
372 	}
373 }
374 
375 void
376 dnode_setbonuslen(dnode_t *dn, int newsize, dmu_tx_t *tx)
377 {
378 	ASSERT3U(zfs_refcount_count(&dn->dn_holds), >=, 1);
379 
380 	dnode_setdirty(dn, tx);
381 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
382 	ASSERT3U(newsize, <=, DN_SLOTS_TO_BONUSLEN(dn->dn_num_slots) -
383 	    (dn->dn_nblkptr-1) * sizeof (blkptr_t));
384 
385 	if (newsize < dn->dn_bonuslen) {
386 		/* clear any data after the end of the new size */
387 		size_t diff = dn->dn_bonuslen - newsize;
388 		char *data_end = ((char *)dn->dn_bonus->db.db_data) + newsize;
389 		memset(data_end, 0, diff);
390 	}
391 
392 	dn->dn_bonuslen = newsize;
393 	if (newsize == 0)
394 		dn->dn_next_bonuslen[tx->tx_txg & TXG_MASK] = DN_ZERO_BONUSLEN;
395 	else
396 		dn->dn_next_bonuslen[tx->tx_txg & TXG_MASK] = dn->dn_bonuslen;
397 	rw_exit(&dn->dn_struct_rwlock);
398 }
399 
400 void
401 dnode_setbonus_type(dnode_t *dn, dmu_object_type_t newtype, dmu_tx_t *tx)
402 {
403 	ASSERT3U(zfs_refcount_count(&dn->dn_holds), >=, 1);
404 	dnode_setdirty(dn, tx);
405 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
406 	dn->dn_bonustype = newtype;
407 	dn->dn_next_bonustype[tx->tx_txg & TXG_MASK] = dn->dn_bonustype;
408 	rw_exit(&dn->dn_struct_rwlock);
409 }
410 
411 void
412 dnode_rm_spill(dnode_t *dn, dmu_tx_t *tx)
413 {
414 	ASSERT3U(zfs_refcount_count(&dn->dn_holds), >=, 1);
415 	ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
416 	dnode_setdirty(dn, tx);
417 	dn->dn_rm_spillblk[tx->tx_txg & TXG_MASK] = DN_KILL_SPILLBLK;
418 	dn->dn_have_spill = B_FALSE;
419 }
420 
421 static void
422 dnode_setdblksz(dnode_t *dn, int size)
423 {
424 	ASSERT0(P2PHASE(size, SPA_MINBLOCKSIZE));
425 	ASSERT3U(size, <=, SPA_MAXBLOCKSIZE);
426 	ASSERT3U(size, >=, SPA_MINBLOCKSIZE);
427 	ASSERT3U(size >> SPA_MINBLOCKSHIFT, <,
428 	    1<<(sizeof (dn->dn_phys->dn_datablkszsec) * 8));
429 	dn->dn_datablksz = size;
430 	dn->dn_datablkszsec = size >> SPA_MINBLOCKSHIFT;
431 	dn->dn_datablkshift = ISP2(size) ? highbit64(size - 1) : 0;
432 }
433 
434 static dnode_t *
435 dnode_create(objset_t *os, dnode_phys_t *dnp, dmu_buf_impl_t *db,
436     uint64_t object, dnode_handle_t *dnh)
437 {
438 	dnode_t *dn;
439 
440 	dn = kmem_cache_alloc(dnode_cache, KM_SLEEP);
441 	dn->dn_moved = 0;
442 
443 	/*
444 	 * Defer setting dn_objset until the dnode is ready to be a candidate
445 	 * for the dnode_move() callback.
446 	 */
447 	dn->dn_object = object;
448 	dn->dn_dbuf = db;
449 	dn->dn_handle = dnh;
450 	dn->dn_phys = dnp;
451 
452 	if (dnp->dn_datablkszsec) {
453 		dnode_setdblksz(dn, dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT);
454 	} else {
455 		dn->dn_datablksz = 0;
456 		dn->dn_datablkszsec = 0;
457 		dn->dn_datablkshift = 0;
458 	}
459 	dn->dn_indblkshift = dnp->dn_indblkshift;
460 	dn->dn_nlevels = dnp->dn_nlevels;
461 	dn->dn_type = dnp->dn_type;
462 	dn->dn_nblkptr = dnp->dn_nblkptr;
463 	dn->dn_checksum = dnp->dn_checksum;
464 	dn->dn_compress = dnp->dn_compress;
465 	dn->dn_bonustype = dnp->dn_bonustype;
466 	dn->dn_bonuslen = dnp->dn_bonuslen;
467 	dn->dn_num_slots = dnp->dn_extra_slots + 1;
468 	dn->dn_maxblkid = dnp->dn_maxblkid;
469 	dn->dn_have_spill = ((dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR) != 0);
470 	dn->dn_id_flags = 0;
471 
472 	dmu_zfetch_init(&dn->dn_zfetch, dn);
473 
474 	ASSERT(DMU_OT_IS_VALID(dn->dn_phys->dn_type));
475 	ASSERT(zrl_is_locked(&dnh->dnh_zrlock));
476 	ASSERT(!DN_SLOT_IS_PTR(dnh->dnh_dnode));
477 
478 	mutex_enter(&os->os_lock);
479 
480 	/*
481 	 * Exclude special dnodes from os_dnodes so an empty os_dnodes
482 	 * signifies that the special dnodes have no references from
483 	 * their children (the entries in os_dnodes).  This allows
484 	 * dnode_destroy() to easily determine if the last child has
485 	 * been removed and then complete eviction of the objset.
486 	 */
487 	if (!DMU_OBJECT_IS_SPECIAL(object))
488 		list_insert_head(&os->os_dnodes, dn);
489 	membar_producer();
490 
491 	/*
492 	 * Everything else must be valid before assigning dn_objset
493 	 * makes the dnode eligible for dnode_move().
494 	 */
495 	dn->dn_objset = os;
496 
497 	dnh->dnh_dnode = dn;
498 	mutex_exit(&os->os_lock);
499 
500 	arc_space_consume(sizeof (dnode_t), ARC_SPACE_DNODE);
501 
502 	return (dn);
503 }
504 
505 /*
506  * Caller must be holding the dnode handle, which is released upon return.
507  */
508 static void
509 dnode_destroy(dnode_t *dn)
510 {
511 	objset_t *os = dn->dn_objset;
512 	boolean_t complete_os_eviction = B_FALSE;
513 
514 	ASSERT((dn->dn_id_flags & DN_ID_NEW_EXIST) == 0);
515 
516 	mutex_enter(&os->os_lock);
517 	POINTER_INVALIDATE(&dn->dn_objset);
518 	if (!DMU_OBJECT_IS_SPECIAL(dn->dn_object)) {
519 		list_remove(&os->os_dnodes, dn);
520 		complete_os_eviction =
521 		    list_is_empty(&os->os_dnodes) &&
522 		    list_link_active(&os->os_evicting_node);
523 	}
524 	mutex_exit(&os->os_lock);
525 
526 	/* the dnode can no longer move, so we can release the handle */
527 	if (!zrl_is_locked(&dn->dn_handle->dnh_zrlock))
528 		zrl_remove(&dn->dn_handle->dnh_zrlock);
529 
530 	dn->dn_allocated_txg = 0;
531 	dn->dn_free_txg = 0;
532 	dn->dn_assigned_txg = 0;
533 	dn->dn_dirty_txg = 0;
534 
535 	dn->dn_dirtyctx = 0;
536 	dn->dn_dirtyctx_firstset = NULL;
537 	if (dn->dn_bonus != NULL) {
538 		mutex_enter(&dn->dn_bonus->db_mtx);
539 		dbuf_destroy(dn->dn_bonus);
540 		dn->dn_bonus = NULL;
541 	}
542 	dn->dn_zio = NULL;
543 
544 	dn->dn_have_spill = B_FALSE;
545 	dn->dn_oldused = 0;
546 	dn->dn_oldflags = 0;
547 	dn->dn_olduid = 0;
548 	dn->dn_oldgid = 0;
549 	dn->dn_oldprojid = ZFS_DEFAULT_PROJID;
550 	dn->dn_newuid = 0;
551 	dn->dn_newgid = 0;
552 	dn->dn_newprojid = ZFS_DEFAULT_PROJID;
553 	dn->dn_id_flags = 0;
554 
555 	dmu_zfetch_fini(&dn->dn_zfetch);
556 	kmem_cache_free(dnode_cache, dn);
557 	arc_space_return(sizeof (dnode_t), ARC_SPACE_DNODE);
558 
559 	if (complete_os_eviction)
560 		dmu_objset_evict_done(os);
561 }
562 
563 void
564 dnode_allocate(dnode_t *dn, dmu_object_type_t ot, int blocksize, int ibs,
565     dmu_object_type_t bonustype, int bonuslen, int dn_slots, dmu_tx_t *tx)
566 {
567 	int i;
568 
569 	ASSERT3U(dn_slots, >, 0);
570 	ASSERT3U(dn_slots << DNODE_SHIFT, <=,
571 	    spa_maxdnodesize(dmu_objset_spa(dn->dn_objset)));
572 	ASSERT3U(blocksize, <=,
573 	    spa_maxblocksize(dmu_objset_spa(dn->dn_objset)));
574 	if (blocksize == 0)
575 		blocksize = 1 << zfs_default_bs;
576 	else
577 		blocksize = P2ROUNDUP(blocksize, SPA_MINBLOCKSIZE);
578 
579 	if (ibs == 0)
580 		ibs = zfs_default_ibs;
581 
582 	ibs = MIN(MAX(ibs, DN_MIN_INDBLKSHIFT), DN_MAX_INDBLKSHIFT);
583 
584 	dprintf("os=%p obj=%llu txg=%llu blocksize=%d ibs=%d dn_slots=%d\n",
585 	    dn->dn_objset, (u_longlong_t)dn->dn_object,
586 	    (u_longlong_t)tx->tx_txg, blocksize, ibs, dn_slots);
587 	DNODE_STAT_BUMP(dnode_allocate);
588 
589 	ASSERT(dn->dn_type == DMU_OT_NONE);
590 	ASSERT0(memcmp(dn->dn_phys, &dnode_phys_zero, sizeof (dnode_phys_t)));
591 	ASSERT(dn->dn_phys->dn_type == DMU_OT_NONE);
592 	ASSERT(ot != DMU_OT_NONE);
593 	ASSERT(DMU_OT_IS_VALID(ot));
594 	ASSERT((bonustype == DMU_OT_NONE && bonuslen == 0) ||
595 	    (bonustype == DMU_OT_SA && bonuslen == 0) ||
596 	    (bonustype != DMU_OT_NONE && bonuslen != 0));
597 	ASSERT(DMU_OT_IS_VALID(bonustype));
598 	ASSERT3U(bonuslen, <=, DN_SLOTS_TO_BONUSLEN(dn_slots));
599 	ASSERT(dn->dn_type == DMU_OT_NONE);
600 	ASSERT0(dn->dn_maxblkid);
601 	ASSERT0(dn->dn_allocated_txg);
602 	ASSERT0(dn->dn_assigned_txg);
603 	ASSERT(zfs_refcount_is_zero(&dn->dn_tx_holds));
604 	ASSERT3U(zfs_refcount_count(&dn->dn_holds), <=, 1);
605 	ASSERT(avl_is_empty(&dn->dn_dbufs));
606 
607 	for (i = 0; i < TXG_SIZE; i++) {
608 		ASSERT0(dn->dn_next_nblkptr[i]);
609 		ASSERT0(dn->dn_next_nlevels[i]);
610 		ASSERT0(dn->dn_next_indblkshift[i]);
611 		ASSERT0(dn->dn_next_bonuslen[i]);
612 		ASSERT0(dn->dn_next_bonustype[i]);
613 		ASSERT0(dn->dn_rm_spillblk[i]);
614 		ASSERT0(dn->dn_next_blksz[i]);
615 		ASSERT0(dn->dn_next_maxblkid[i]);
616 		ASSERT(!multilist_link_active(&dn->dn_dirty_link[i]));
617 		ASSERT3P(list_head(&dn->dn_dirty_records[i]), ==, NULL);
618 		ASSERT3P(dn->dn_free_ranges[i], ==, NULL);
619 	}
620 
621 	dn->dn_type = ot;
622 	dnode_setdblksz(dn, blocksize);
623 	dn->dn_indblkshift = ibs;
624 	dn->dn_nlevels = 1;
625 	dn->dn_num_slots = dn_slots;
626 	if (bonustype == DMU_OT_SA) /* Maximize bonus space for SA */
627 		dn->dn_nblkptr = 1;
628 	else {
629 		dn->dn_nblkptr = MIN(DN_MAX_NBLKPTR,
630 		    1 + ((DN_SLOTS_TO_BONUSLEN(dn_slots) - bonuslen) >>
631 		    SPA_BLKPTRSHIFT));
632 	}
633 
634 	dn->dn_bonustype = bonustype;
635 	dn->dn_bonuslen = bonuslen;
636 	dn->dn_checksum = ZIO_CHECKSUM_INHERIT;
637 	dn->dn_compress = ZIO_COMPRESS_INHERIT;
638 	dn->dn_dirtyctx = 0;
639 
640 	dn->dn_free_txg = 0;
641 	dn->dn_dirtyctx_firstset = NULL;
642 	dn->dn_dirty_txg = 0;
643 
644 	dn->dn_allocated_txg = tx->tx_txg;
645 	dn->dn_id_flags = 0;
646 
647 	dnode_setdirty(dn, tx);
648 	dn->dn_next_indblkshift[tx->tx_txg & TXG_MASK] = ibs;
649 	dn->dn_next_bonuslen[tx->tx_txg & TXG_MASK] = dn->dn_bonuslen;
650 	dn->dn_next_bonustype[tx->tx_txg & TXG_MASK] = dn->dn_bonustype;
651 	dn->dn_next_blksz[tx->tx_txg & TXG_MASK] = dn->dn_datablksz;
652 }
653 
654 void
655 dnode_reallocate(dnode_t *dn, dmu_object_type_t ot, int blocksize,
656     dmu_object_type_t bonustype, int bonuslen, int dn_slots,
657     boolean_t keep_spill, dmu_tx_t *tx)
658 {
659 	int nblkptr;
660 
661 	ASSERT3U(blocksize, >=, SPA_MINBLOCKSIZE);
662 	ASSERT3U(blocksize, <=,
663 	    spa_maxblocksize(dmu_objset_spa(dn->dn_objset)));
664 	ASSERT0(blocksize % SPA_MINBLOCKSIZE);
665 	ASSERT(dn->dn_object != DMU_META_DNODE_OBJECT || dmu_tx_private_ok(tx));
666 	ASSERT(tx->tx_txg != 0);
667 	ASSERT((bonustype == DMU_OT_NONE && bonuslen == 0) ||
668 	    (bonustype != DMU_OT_NONE && bonuslen != 0) ||
669 	    (bonustype == DMU_OT_SA && bonuslen == 0));
670 	ASSERT(DMU_OT_IS_VALID(bonustype));
671 	ASSERT3U(bonuslen, <=,
672 	    DN_BONUS_SIZE(spa_maxdnodesize(dmu_objset_spa(dn->dn_objset))));
673 	ASSERT3U(bonuslen, <=, DN_BONUS_SIZE(dn_slots << DNODE_SHIFT));
674 
675 	dnode_free_interior_slots(dn);
676 	DNODE_STAT_BUMP(dnode_reallocate);
677 
678 	/* clean up any unreferenced dbufs */
679 	dnode_evict_dbufs(dn);
680 
681 	dn->dn_id_flags = 0;
682 
683 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
684 	dnode_setdirty(dn, tx);
685 	if (dn->dn_datablksz != blocksize) {
686 		/* change blocksize */
687 		ASSERT0(dn->dn_maxblkid);
688 		ASSERT(BP_IS_HOLE(&dn->dn_phys->dn_blkptr[0]) ||
689 		    dnode_block_freed(dn, 0));
690 
691 		dnode_setdblksz(dn, blocksize);
692 		dn->dn_next_blksz[tx->tx_txg & TXG_MASK] = blocksize;
693 	}
694 	if (dn->dn_bonuslen != bonuslen)
695 		dn->dn_next_bonuslen[tx->tx_txg & TXG_MASK] = bonuslen;
696 
697 	if (bonustype == DMU_OT_SA) /* Maximize bonus space for SA */
698 		nblkptr = 1;
699 	else
700 		nblkptr = MIN(DN_MAX_NBLKPTR,
701 		    1 + ((DN_SLOTS_TO_BONUSLEN(dn_slots) - bonuslen) >>
702 		    SPA_BLKPTRSHIFT));
703 	if (dn->dn_bonustype != bonustype)
704 		dn->dn_next_bonustype[tx->tx_txg & TXG_MASK] = bonustype;
705 	if (dn->dn_nblkptr != nblkptr)
706 		dn->dn_next_nblkptr[tx->tx_txg & TXG_MASK] = nblkptr;
707 	if (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR && !keep_spill) {
708 		dbuf_rm_spill(dn, tx);
709 		dnode_rm_spill(dn, tx);
710 	}
711 
712 	rw_exit(&dn->dn_struct_rwlock);
713 
714 	/* change type */
715 	dn->dn_type = ot;
716 
717 	/* change bonus size and type */
718 	mutex_enter(&dn->dn_mtx);
719 	dn->dn_bonustype = bonustype;
720 	dn->dn_bonuslen = bonuslen;
721 	dn->dn_num_slots = dn_slots;
722 	dn->dn_nblkptr = nblkptr;
723 	dn->dn_checksum = ZIO_CHECKSUM_INHERIT;
724 	dn->dn_compress = ZIO_COMPRESS_INHERIT;
725 	ASSERT3U(dn->dn_nblkptr, <=, DN_MAX_NBLKPTR);
726 
727 	/* fix up the bonus db_size */
728 	if (dn->dn_bonus) {
729 		dn->dn_bonus->db.db_size =
730 		    DN_SLOTS_TO_BONUSLEN(dn->dn_num_slots) -
731 		    (dn->dn_nblkptr-1) * sizeof (blkptr_t);
732 		ASSERT(dn->dn_bonuslen <= dn->dn_bonus->db.db_size);
733 	}
734 
735 	dn->dn_allocated_txg = tx->tx_txg;
736 	mutex_exit(&dn->dn_mtx);
737 }
738 
739 #ifdef	_KERNEL
740 static void
741 dnode_move_impl(dnode_t *odn, dnode_t *ndn)
742 {
743 	ASSERT(!RW_LOCK_HELD(&odn->dn_struct_rwlock));
744 	ASSERT(MUTEX_NOT_HELD(&odn->dn_mtx));
745 	ASSERT(MUTEX_NOT_HELD(&odn->dn_dbufs_mtx));
746 
747 	/* Copy fields. */
748 	ndn->dn_objset = odn->dn_objset;
749 	ndn->dn_object = odn->dn_object;
750 	ndn->dn_dbuf = odn->dn_dbuf;
751 	ndn->dn_handle = odn->dn_handle;
752 	ndn->dn_phys = odn->dn_phys;
753 	ndn->dn_type = odn->dn_type;
754 	ndn->dn_bonuslen = odn->dn_bonuslen;
755 	ndn->dn_bonustype = odn->dn_bonustype;
756 	ndn->dn_nblkptr = odn->dn_nblkptr;
757 	ndn->dn_checksum = odn->dn_checksum;
758 	ndn->dn_compress = odn->dn_compress;
759 	ndn->dn_nlevels = odn->dn_nlevels;
760 	ndn->dn_indblkshift = odn->dn_indblkshift;
761 	ndn->dn_datablkshift = odn->dn_datablkshift;
762 	ndn->dn_datablkszsec = odn->dn_datablkszsec;
763 	ndn->dn_datablksz = odn->dn_datablksz;
764 	ndn->dn_maxblkid = odn->dn_maxblkid;
765 	ndn->dn_num_slots = odn->dn_num_slots;
766 	memcpy(ndn->dn_next_type, odn->dn_next_type,
767 	    sizeof (odn->dn_next_type));
768 	memcpy(ndn->dn_next_nblkptr, odn->dn_next_nblkptr,
769 	    sizeof (odn->dn_next_nblkptr));
770 	memcpy(ndn->dn_next_nlevels, odn->dn_next_nlevels,
771 	    sizeof (odn->dn_next_nlevels));
772 	memcpy(ndn->dn_next_indblkshift, odn->dn_next_indblkshift,
773 	    sizeof (odn->dn_next_indblkshift));
774 	memcpy(ndn->dn_next_bonustype, odn->dn_next_bonustype,
775 	    sizeof (odn->dn_next_bonustype));
776 	memcpy(ndn->dn_rm_spillblk, odn->dn_rm_spillblk,
777 	    sizeof (odn->dn_rm_spillblk));
778 	memcpy(ndn->dn_next_bonuslen, odn->dn_next_bonuslen,
779 	    sizeof (odn->dn_next_bonuslen));
780 	memcpy(ndn->dn_next_blksz, odn->dn_next_blksz,
781 	    sizeof (odn->dn_next_blksz));
782 	memcpy(ndn->dn_next_maxblkid, odn->dn_next_maxblkid,
783 	    sizeof (odn->dn_next_maxblkid));
784 	for (int i = 0; i < TXG_SIZE; i++) {
785 		list_move_tail(&ndn->dn_dirty_records[i],
786 		    &odn->dn_dirty_records[i]);
787 	}
788 	memcpy(ndn->dn_free_ranges, odn->dn_free_ranges,
789 	    sizeof (odn->dn_free_ranges));
790 	ndn->dn_allocated_txg = odn->dn_allocated_txg;
791 	ndn->dn_free_txg = odn->dn_free_txg;
792 	ndn->dn_assigned_txg = odn->dn_assigned_txg;
793 	ndn->dn_dirty_txg = odn->dn_dirty_txg;
794 	ndn->dn_dirtyctx = odn->dn_dirtyctx;
795 	ndn->dn_dirtyctx_firstset = odn->dn_dirtyctx_firstset;
796 	ASSERT(zfs_refcount_count(&odn->dn_tx_holds) == 0);
797 	zfs_refcount_transfer(&ndn->dn_holds, &odn->dn_holds);
798 	ASSERT(avl_is_empty(&ndn->dn_dbufs));
799 	avl_swap(&ndn->dn_dbufs, &odn->dn_dbufs);
800 	ndn->dn_dbufs_count = odn->dn_dbufs_count;
801 	ndn->dn_bonus = odn->dn_bonus;
802 	ndn->dn_have_spill = odn->dn_have_spill;
803 	ndn->dn_zio = odn->dn_zio;
804 	ndn->dn_oldused = odn->dn_oldused;
805 	ndn->dn_oldflags = odn->dn_oldflags;
806 	ndn->dn_olduid = odn->dn_olduid;
807 	ndn->dn_oldgid = odn->dn_oldgid;
808 	ndn->dn_oldprojid = odn->dn_oldprojid;
809 	ndn->dn_newuid = odn->dn_newuid;
810 	ndn->dn_newgid = odn->dn_newgid;
811 	ndn->dn_newprojid = odn->dn_newprojid;
812 	ndn->dn_id_flags = odn->dn_id_flags;
813 	dmu_zfetch_init(&ndn->dn_zfetch, ndn);
814 
815 	/*
816 	 * Update back pointers. Updating the handle fixes the back pointer of
817 	 * every descendant dbuf as well as the bonus dbuf.
818 	 */
819 	ASSERT(ndn->dn_handle->dnh_dnode == odn);
820 	ndn->dn_handle->dnh_dnode = ndn;
821 
822 	/*
823 	 * Invalidate the original dnode by clearing all of its back pointers.
824 	 */
825 	odn->dn_dbuf = NULL;
826 	odn->dn_handle = NULL;
827 	avl_create(&odn->dn_dbufs, dbuf_compare, sizeof (dmu_buf_impl_t),
828 	    offsetof(dmu_buf_impl_t, db_link));
829 	odn->dn_dbufs_count = 0;
830 	odn->dn_bonus = NULL;
831 	dmu_zfetch_fini(&odn->dn_zfetch);
832 
833 	/*
834 	 * Set the low bit of the objset pointer to ensure that dnode_move()
835 	 * recognizes the dnode as invalid in any subsequent callback.
836 	 */
837 	POINTER_INVALIDATE(&odn->dn_objset);
838 
839 	/*
840 	 * Satisfy the destructor.
841 	 */
842 	for (int i = 0; i < TXG_SIZE; i++) {
843 		list_create(&odn->dn_dirty_records[i],
844 		    sizeof (dbuf_dirty_record_t),
845 		    offsetof(dbuf_dirty_record_t, dr_dirty_node));
846 		odn->dn_free_ranges[i] = NULL;
847 		odn->dn_next_nlevels[i] = 0;
848 		odn->dn_next_indblkshift[i] = 0;
849 		odn->dn_next_bonustype[i] = 0;
850 		odn->dn_rm_spillblk[i] = 0;
851 		odn->dn_next_bonuslen[i] = 0;
852 		odn->dn_next_blksz[i] = 0;
853 	}
854 	odn->dn_allocated_txg = 0;
855 	odn->dn_free_txg = 0;
856 	odn->dn_assigned_txg = 0;
857 	odn->dn_dirty_txg = 0;
858 	odn->dn_dirtyctx = 0;
859 	odn->dn_dirtyctx_firstset = NULL;
860 	odn->dn_have_spill = B_FALSE;
861 	odn->dn_zio = NULL;
862 	odn->dn_oldused = 0;
863 	odn->dn_oldflags = 0;
864 	odn->dn_olduid = 0;
865 	odn->dn_oldgid = 0;
866 	odn->dn_oldprojid = ZFS_DEFAULT_PROJID;
867 	odn->dn_newuid = 0;
868 	odn->dn_newgid = 0;
869 	odn->dn_newprojid = ZFS_DEFAULT_PROJID;
870 	odn->dn_id_flags = 0;
871 
872 	/*
873 	 * Mark the dnode.
874 	 */
875 	ndn->dn_moved = 1;
876 	odn->dn_moved = (uint8_t)-1;
877 }
878 
879 static kmem_cbrc_t
880 dnode_move(void *buf, void *newbuf, size_t size, void *arg)
881 {
882 	dnode_t *odn = buf, *ndn = newbuf;
883 	objset_t *os;
884 	int64_t refcount;
885 	uint32_t dbufs;
886 
887 	/*
888 	 * The dnode is on the objset's list of known dnodes if the objset
889 	 * pointer is valid. We set the low bit of the objset pointer when
890 	 * freeing the dnode to invalidate it, and the memory patterns written
891 	 * by kmem (baddcafe and deadbeef) set at least one of the two low bits.
892 	 * A newly created dnode sets the objset pointer last of all to indicate
893 	 * that the dnode is known and in a valid state to be moved by this
894 	 * function.
895 	 */
896 	os = odn->dn_objset;
897 	if (!POINTER_IS_VALID(os)) {
898 		DNODE_STAT_BUMP(dnode_move_invalid);
899 		return (KMEM_CBRC_DONT_KNOW);
900 	}
901 
902 	/*
903 	 * Ensure that the objset does not go away during the move.
904 	 */
905 	rw_enter(&os_lock, RW_WRITER);
906 	if (os != odn->dn_objset) {
907 		rw_exit(&os_lock);
908 		DNODE_STAT_BUMP(dnode_move_recheck1);
909 		return (KMEM_CBRC_DONT_KNOW);
910 	}
911 
912 	/*
913 	 * If the dnode is still valid, then so is the objset. We know that no
914 	 * valid objset can be freed while we hold os_lock, so we can safely
915 	 * ensure that the objset remains in use.
916 	 */
917 	mutex_enter(&os->os_lock);
918 
919 	/*
920 	 * Recheck the objset pointer in case the dnode was removed just before
921 	 * acquiring the lock.
922 	 */
923 	if (os != odn->dn_objset) {
924 		mutex_exit(&os->os_lock);
925 		rw_exit(&os_lock);
926 		DNODE_STAT_BUMP(dnode_move_recheck2);
927 		return (KMEM_CBRC_DONT_KNOW);
928 	}
929 
930 	/*
931 	 * At this point we know that as long as we hold os->os_lock, the dnode
932 	 * cannot be freed and fields within the dnode can be safely accessed.
933 	 * The objset listing this dnode cannot go away as long as this dnode is
934 	 * on its list.
935 	 */
936 	rw_exit(&os_lock);
937 	if (DMU_OBJECT_IS_SPECIAL(odn->dn_object)) {
938 		mutex_exit(&os->os_lock);
939 		DNODE_STAT_BUMP(dnode_move_special);
940 		return (KMEM_CBRC_NO);
941 	}
942 	ASSERT(odn->dn_dbuf != NULL); /* only "special" dnodes have no parent */
943 
944 	/*
945 	 * Lock the dnode handle to prevent the dnode from obtaining any new
946 	 * holds. This also prevents the descendant dbufs and the bonus dbuf
947 	 * from accessing the dnode, so that we can discount their holds. The
948 	 * handle is safe to access because we know that while the dnode cannot
949 	 * go away, neither can its handle. Once we hold dnh_zrlock, we can
950 	 * safely move any dnode referenced only by dbufs.
951 	 */
952 	if (!zrl_tryenter(&odn->dn_handle->dnh_zrlock)) {
953 		mutex_exit(&os->os_lock);
954 		DNODE_STAT_BUMP(dnode_move_handle);
955 		return (KMEM_CBRC_LATER);
956 	}
957 
958 	/*
959 	 * Ensure a consistent view of the dnode's holds and the dnode's dbufs.
960 	 * We need to guarantee that there is a hold for every dbuf in order to
961 	 * determine whether the dnode is actively referenced. Falsely matching
962 	 * a dbuf to an active hold would lead to an unsafe move. It's possible
963 	 * that a thread already having an active dnode hold is about to add a
964 	 * dbuf, and we can't compare hold and dbuf counts while the add is in
965 	 * progress.
966 	 */
967 	if (!rw_tryenter(&odn->dn_struct_rwlock, RW_WRITER)) {
968 		zrl_exit(&odn->dn_handle->dnh_zrlock);
969 		mutex_exit(&os->os_lock);
970 		DNODE_STAT_BUMP(dnode_move_rwlock);
971 		return (KMEM_CBRC_LATER);
972 	}
973 
974 	/*
975 	 * A dbuf may be removed (evicted) without an active dnode hold. In that
976 	 * case, the dbuf count is decremented under the handle lock before the
977 	 * dbuf's hold is released. This order ensures that if we count the hold
978 	 * after the dbuf is removed but before its hold is released, we will
979 	 * treat the unmatched hold as active and exit safely. If we count the
980 	 * hold before the dbuf is removed, the hold is discounted, and the
981 	 * removal is blocked until the move completes.
982 	 */
983 	refcount = zfs_refcount_count(&odn->dn_holds);
984 	ASSERT(refcount >= 0);
985 	dbufs = DN_DBUFS_COUNT(odn);
986 
987 	/* We can't have more dbufs than dnode holds. */
988 	ASSERT3U(dbufs, <=, refcount);
989 	DTRACE_PROBE3(dnode__move, dnode_t *, odn, int64_t, refcount,
990 	    uint32_t, dbufs);
991 
992 	if (refcount > dbufs) {
993 		rw_exit(&odn->dn_struct_rwlock);
994 		zrl_exit(&odn->dn_handle->dnh_zrlock);
995 		mutex_exit(&os->os_lock);
996 		DNODE_STAT_BUMP(dnode_move_active);
997 		return (KMEM_CBRC_LATER);
998 	}
999 
1000 	rw_exit(&odn->dn_struct_rwlock);
1001 
1002 	/*
1003 	 * At this point we know that anyone with a hold on the dnode is not
1004 	 * actively referencing it. The dnode is known and in a valid state to
1005 	 * move. We're holding the locks needed to execute the critical section.
1006 	 */
1007 	dnode_move_impl(odn, ndn);
1008 
1009 	list_link_replace(&odn->dn_link, &ndn->dn_link);
1010 	/* If the dnode was safe to move, the refcount cannot have changed. */
1011 	ASSERT(refcount == zfs_refcount_count(&ndn->dn_holds));
1012 	ASSERT(dbufs == DN_DBUFS_COUNT(ndn));
1013 	zrl_exit(&ndn->dn_handle->dnh_zrlock); /* handle has moved */
1014 	mutex_exit(&os->os_lock);
1015 
1016 	return (KMEM_CBRC_YES);
1017 }
1018 #endif	/* _KERNEL */
1019 
1020 static void
1021 dnode_slots_hold(dnode_children_t *children, int idx, int slots)
1022 {
1023 	ASSERT3S(idx + slots, <=, DNODES_PER_BLOCK);
1024 
1025 	for (int i = idx; i < idx + slots; i++) {
1026 		dnode_handle_t *dnh = &children->dnc_children[i];
1027 		zrl_add(&dnh->dnh_zrlock);
1028 	}
1029 }
1030 
1031 static void
1032 dnode_slots_rele(dnode_children_t *children, int idx, int slots)
1033 {
1034 	ASSERT3S(idx + slots, <=, DNODES_PER_BLOCK);
1035 
1036 	for (int i = idx; i < idx + slots; i++) {
1037 		dnode_handle_t *dnh = &children->dnc_children[i];
1038 
1039 		if (zrl_is_locked(&dnh->dnh_zrlock))
1040 			zrl_exit(&dnh->dnh_zrlock);
1041 		else
1042 			zrl_remove(&dnh->dnh_zrlock);
1043 	}
1044 }
1045 
1046 static int
1047 dnode_slots_tryenter(dnode_children_t *children, int idx, int slots)
1048 {
1049 	ASSERT3S(idx + slots, <=, DNODES_PER_BLOCK);
1050 
1051 	for (int i = idx; i < idx + slots; i++) {
1052 		dnode_handle_t *dnh = &children->dnc_children[i];
1053 
1054 		if (!zrl_tryenter(&dnh->dnh_zrlock)) {
1055 			for (int j = idx; j < i; j++) {
1056 				dnh = &children->dnc_children[j];
1057 				zrl_exit(&dnh->dnh_zrlock);
1058 			}
1059 
1060 			return (0);
1061 		}
1062 	}
1063 
1064 	return (1);
1065 }
1066 
1067 static void
1068 dnode_set_slots(dnode_children_t *children, int idx, int slots, void *ptr)
1069 {
1070 	ASSERT3S(idx + slots, <=, DNODES_PER_BLOCK);
1071 
1072 	for (int i = idx; i < idx + slots; i++) {
1073 		dnode_handle_t *dnh = &children->dnc_children[i];
1074 		dnh->dnh_dnode = ptr;
1075 	}
1076 }
1077 
1078 static boolean_t
1079 dnode_check_slots_free(dnode_children_t *children, int idx, int slots)
1080 {
1081 	ASSERT3S(idx + slots, <=, DNODES_PER_BLOCK);
1082 
1083 	/*
1084 	 * If all dnode slots are either already free or
1085 	 * evictable return B_TRUE.
1086 	 */
1087 	for (int i = idx; i < idx + slots; i++) {
1088 		dnode_handle_t *dnh = &children->dnc_children[i];
1089 		dnode_t *dn = dnh->dnh_dnode;
1090 
1091 		if (dn == DN_SLOT_FREE) {
1092 			continue;
1093 		} else if (DN_SLOT_IS_PTR(dn)) {
1094 			mutex_enter(&dn->dn_mtx);
1095 			boolean_t can_free = (dn->dn_type == DMU_OT_NONE &&
1096 			    zfs_refcount_is_zero(&dn->dn_holds) &&
1097 			    !DNODE_IS_DIRTY(dn));
1098 			mutex_exit(&dn->dn_mtx);
1099 
1100 			if (!can_free)
1101 				return (B_FALSE);
1102 			else
1103 				continue;
1104 		} else {
1105 			return (B_FALSE);
1106 		}
1107 	}
1108 
1109 	return (B_TRUE);
1110 }
1111 
1112 static void
1113 dnode_reclaim_slots(dnode_children_t *children, int idx, int slots)
1114 {
1115 	ASSERT3S(idx + slots, <=, DNODES_PER_BLOCK);
1116 
1117 	for (int i = idx; i < idx + slots; i++) {
1118 		dnode_handle_t *dnh = &children->dnc_children[i];
1119 
1120 		ASSERT(zrl_is_locked(&dnh->dnh_zrlock));
1121 
1122 		if (DN_SLOT_IS_PTR(dnh->dnh_dnode)) {
1123 			ASSERT3S(dnh->dnh_dnode->dn_type, ==, DMU_OT_NONE);
1124 			dnode_destroy(dnh->dnh_dnode);
1125 			dnh->dnh_dnode = DN_SLOT_FREE;
1126 		}
1127 	}
1128 }
1129 
1130 void
1131 dnode_free_interior_slots(dnode_t *dn)
1132 {
1133 	dnode_children_t *children = dmu_buf_get_user(&dn->dn_dbuf->db);
1134 	int epb = dn->dn_dbuf->db.db_size >> DNODE_SHIFT;
1135 	int idx = (dn->dn_object & (epb - 1)) + 1;
1136 	int slots = dn->dn_num_slots - 1;
1137 
1138 	if (slots == 0)
1139 		return;
1140 
1141 	ASSERT3S(idx + slots, <=, DNODES_PER_BLOCK);
1142 
1143 	while (!dnode_slots_tryenter(children, idx, slots)) {
1144 		DNODE_STAT_BUMP(dnode_free_interior_lock_retry);
1145 		cond_resched();
1146 	}
1147 
1148 	dnode_set_slots(children, idx, slots, DN_SLOT_FREE);
1149 	dnode_slots_rele(children, idx, slots);
1150 }
1151 
1152 void
1153 dnode_special_close(dnode_handle_t *dnh)
1154 {
1155 	dnode_t *dn = dnh->dnh_dnode;
1156 
1157 	/*
1158 	 * Ensure dnode_rele_and_unlock() has released dn_mtx, after final
1159 	 * zfs_refcount_remove()
1160 	 */
1161 	mutex_enter(&dn->dn_mtx);
1162 	if (zfs_refcount_count(&dn->dn_holds) > 0)
1163 		cv_wait(&dn->dn_nodnholds, &dn->dn_mtx);
1164 	mutex_exit(&dn->dn_mtx);
1165 	ASSERT3U(zfs_refcount_count(&dn->dn_holds), ==, 0);
1166 
1167 	ASSERT(dn->dn_dbuf == NULL ||
1168 	    dmu_buf_get_user(&dn->dn_dbuf->db) == NULL);
1169 	zrl_add(&dnh->dnh_zrlock);
1170 	dnode_destroy(dn); /* implicit zrl_remove() */
1171 	zrl_destroy(&dnh->dnh_zrlock);
1172 	dnh->dnh_dnode = NULL;
1173 }
1174 
1175 void
1176 dnode_special_open(objset_t *os, dnode_phys_t *dnp, uint64_t object,
1177     dnode_handle_t *dnh)
1178 {
1179 	dnode_t *dn;
1180 
1181 	zrl_init(&dnh->dnh_zrlock);
1182 	VERIFY3U(1, ==, zrl_tryenter(&dnh->dnh_zrlock));
1183 
1184 	dn = dnode_create(os, dnp, NULL, object, dnh);
1185 	DNODE_VERIFY(dn);
1186 
1187 	zrl_exit(&dnh->dnh_zrlock);
1188 }
1189 
1190 static void
1191 dnode_buf_evict_async(void *dbu)
1192 {
1193 	dnode_children_t *dnc = dbu;
1194 
1195 	DNODE_STAT_BUMP(dnode_buf_evict);
1196 
1197 	for (int i = 0; i < dnc->dnc_count; i++) {
1198 		dnode_handle_t *dnh = &dnc->dnc_children[i];
1199 		dnode_t *dn;
1200 
1201 		/*
1202 		 * The dnode handle lock guards against the dnode moving to
1203 		 * another valid address, so there is no need here to guard
1204 		 * against changes to or from NULL.
1205 		 */
1206 		if (!DN_SLOT_IS_PTR(dnh->dnh_dnode)) {
1207 			zrl_destroy(&dnh->dnh_zrlock);
1208 			dnh->dnh_dnode = DN_SLOT_UNINIT;
1209 			continue;
1210 		}
1211 
1212 		zrl_add(&dnh->dnh_zrlock);
1213 		dn = dnh->dnh_dnode;
1214 		/*
1215 		 * If there are holds on this dnode, then there should
1216 		 * be holds on the dnode's containing dbuf as well; thus
1217 		 * it wouldn't be eligible for eviction and this function
1218 		 * would not have been called.
1219 		 */
1220 		ASSERT(zfs_refcount_is_zero(&dn->dn_holds));
1221 		ASSERT(zfs_refcount_is_zero(&dn->dn_tx_holds));
1222 
1223 		dnode_destroy(dn); /* implicit zrl_remove() for first slot */
1224 		zrl_destroy(&dnh->dnh_zrlock);
1225 		dnh->dnh_dnode = DN_SLOT_UNINIT;
1226 	}
1227 	kmem_free(dnc, sizeof (dnode_children_t) +
1228 	    dnc->dnc_count * sizeof (dnode_handle_t));
1229 }
1230 
1231 /*
1232  * When the DNODE_MUST_BE_FREE flag is set, the "slots" parameter is used
1233  * to ensure the hole at the specified object offset is large enough to
1234  * hold the dnode being created. The slots parameter is also used to ensure
1235  * a dnode does not span multiple dnode blocks. In both of these cases, if
1236  * a failure occurs, ENOSPC is returned. Keep in mind, these failure cases
1237  * are only possible when using DNODE_MUST_BE_FREE.
1238  *
1239  * If the DNODE_MUST_BE_ALLOCATED flag is set, "slots" must be 0.
1240  * dnode_hold_impl() will check if the requested dnode is already consumed
1241  * as an extra dnode slot by an large dnode, in which case it returns
1242  * ENOENT.
1243  *
1244  * If the DNODE_DRY_RUN flag is set, we don't actually hold the dnode, just
1245  * return whether the hold would succeed or not. tag and dnp should set to
1246  * NULL in this case.
1247  *
1248  * errors:
1249  * EINVAL - Invalid object number or flags.
1250  * ENOSPC - Hole too small to fulfill "slots" request (DNODE_MUST_BE_FREE)
1251  * EEXIST - Refers to an allocated dnode (DNODE_MUST_BE_FREE)
1252  *        - Refers to a freeing dnode (DNODE_MUST_BE_FREE)
1253  *        - Refers to an interior dnode slot (DNODE_MUST_BE_ALLOCATED)
1254  * ENOENT - The requested dnode is not allocated (DNODE_MUST_BE_ALLOCATED)
1255  *        - The requested dnode is being freed (DNODE_MUST_BE_ALLOCATED)
1256  * EIO    - I/O error when reading the meta dnode dbuf.
1257  *
1258  * succeeds even for free dnodes.
1259  */
1260 int
1261 dnode_hold_impl(objset_t *os, uint64_t object, int flag, int slots,
1262     const void *tag, dnode_t **dnp)
1263 {
1264 	int epb, idx, err;
1265 	int drop_struct_lock = FALSE;
1266 	int type;
1267 	uint64_t blk;
1268 	dnode_t *mdn, *dn;
1269 	dmu_buf_impl_t *db;
1270 	dnode_children_t *dnc;
1271 	dnode_phys_t *dn_block;
1272 	dnode_handle_t *dnh;
1273 
1274 	ASSERT(!(flag & DNODE_MUST_BE_ALLOCATED) || (slots == 0));
1275 	ASSERT(!(flag & DNODE_MUST_BE_FREE) || (slots > 0));
1276 	IMPLY(flag & DNODE_DRY_RUN, (tag == NULL) && (dnp == NULL));
1277 
1278 	/*
1279 	 * If you are holding the spa config lock as writer, you shouldn't
1280 	 * be asking the DMU to do *anything* unless it's the root pool
1281 	 * which may require us to read from the root filesystem while
1282 	 * holding some (not all) of the locks as writer.
1283 	 */
1284 	ASSERT(spa_config_held(os->os_spa, SCL_ALL, RW_WRITER) == 0 ||
1285 	    (spa_is_root(os->os_spa) &&
1286 	    spa_config_held(os->os_spa, SCL_STATE, RW_WRITER)));
1287 
1288 	ASSERT((flag & DNODE_MUST_BE_ALLOCATED) || (flag & DNODE_MUST_BE_FREE));
1289 
1290 	if (object == DMU_USERUSED_OBJECT || object == DMU_GROUPUSED_OBJECT ||
1291 	    object == DMU_PROJECTUSED_OBJECT) {
1292 		if (object == DMU_USERUSED_OBJECT)
1293 			dn = DMU_USERUSED_DNODE(os);
1294 		else if (object == DMU_GROUPUSED_OBJECT)
1295 			dn = DMU_GROUPUSED_DNODE(os);
1296 		else
1297 			dn = DMU_PROJECTUSED_DNODE(os);
1298 		if (dn == NULL)
1299 			return (SET_ERROR(ENOENT));
1300 		type = dn->dn_type;
1301 		if ((flag & DNODE_MUST_BE_ALLOCATED) && type == DMU_OT_NONE)
1302 			return (SET_ERROR(ENOENT));
1303 		if ((flag & DNODE_MUST_BE_FREE) && type != DMU_OT_NONE)
1304 			return (SET_ERROR(EEXIST));
1305 		DNODE_VERIFY(dn);
1306 		/* Don't actually hold if dry run, just return 0 */
1307 		if (!(flag & DNODE_DRY_RUN)) {
1308 			(void) zfs_refcount_add(&dn->dn_holds, tag);
1309 			*dnp = dn;
1310 		}
1311 		return (0);
1312 	}
1313 
1314 	if (object == 0 || object >= DN_MAX_OBJECT)
1315 		return (SET_ERROR(EINVAL));
1316 
1317 	mdn = DMU_META_DNODE(os);
1318 	ASSERT(mdn->dn_object == DMU_META_DNODE_OBJECT);
1319 
1320 	DNODE_VERIFY(mdn);
1321 
1322 	if (!RW_WRITE_HELD(&mdn->dn_struct_rwlock)) {
1323 		rw_enter(&mdn->dn_struct_rwlock, RW_READER);
1324 		drop_struct_lock = TRUE;
1325 	}
1326 
1327 	blk = dbuf_whichblock(mdn, 0, object * sizeof (dnode_phys_t));
1328 	db = dbuf_hold(mdn, blk, FTAG);
1329 	if (drop_struct_lock)
1330 		rw_exit(&mdn->dn_struct_rwlock);
1331 	if (db == NULL) {
1332 		DNODE_STAT_BUMP(dnode_hold_dbuf_hold);
1333 		return (SET_ERROR(EIO));
1334 	}
1335 
1336 	/*
1337 	 * We do not need to decrypt to read the dnode so it doesn't matter
1338 	 * if we get the encrypted or decrypted version.
1339 	 */
1340 	err = dbuf_read(db, NULL, DB_RF_CANFAIL |
1341 	    DB_RF_NO_DECRYPT | DB_RF_NOPREFETCH);
1342 	if (err) {
1343 		DNODE_STAT_BUMP(dnode_hold_dbuf_read);
1344 		dbuf_rele(db, FTAG);
1345 		return (err);
1346 	}
1347 
1348 	ASSERT3U(db->db.db_size, >=, 1<<DNODE_SHIFT);
1349 	epb = db->db.db_size >> DNODE_SHIFT;
1350 
1351 	idx = object & (epb - 1);
1352 	dn_block = (dnode_phys_t *)db->db.db_data;
1353 
1354 	ASSERT(DB_DNODE(db)->dn_type == DMU_OT_DNODE);
1355 	dnc = dmu_buf_get_user(&db->db);
1356 	dnh = NULL;
1357 	if (dnc == NULL) {
1358 		dnode_children_t *winner;
1359 		int skip = 0;
1360 
1361 		dnc = kmem_zalloc(sizeof (dnode_children_t) +
1362 		    epb * sizeof (dnode_handle_t), KM_SLEEP);
1363 		dnc->dnc_count = epb;
1364 		dnh = &dnc->dnc_children[0];
1365 
1366 		/* Initialize dnode slot status from dnode_phys_t */
1367 		for (int i = 0; i < epb; i++) {
1368 			zrl_init(&dnh[i].dnh_zrlock);
1369 
1370 			if (skip) {
1371 				skip--;
1372 				continue;
1373 			}
1374 
1375 			if (dn_block[i].dn_type != DMU_OT_NONE) {
1376 				int interior = dn_block[i].dn_extra_slots;
1377 
1378 				dnode_set_slots(dnc, i, 1, DN_SLOT_ALLOCATED);
1379 				dnode_set_slots(dnc, i + 1, interior,
1380 				    DN_SLOT_INTERIOR);
1381 				skip = interior;
1382 			} else {
1383 				dnh[i].dnh_dnode = DN_SLOT_FREE;
1384 				skip = 0;
1385 			}
1386 		}
1387 
1388 		dmu_buf_init_user(&dnc->dnc_dbu, NULL,
1389 		    dnode_buf_evict_async, NULL);
1390 		winner = dmu_buf_set_user(&db->db, &dnc->dnc_dbu);
1391 		if (winner != NULL) {
1392 
1393 			for (int i = 0; i < epb; i++)
1394 				zrl_destroy(&dnh[i].dnh_zrlock);
1395 
1396 			kmem_free(dnc, sizeof (dnode_children_t) +
1397 			    epb * sizeof (dnode_handle_t));
1398 			dnc = winner;
1399 		}
1400 	}
1401 
1402 	ASSERT(dnc->dnc_count == epb);
1403 
1404 	if (flag & DNODE_MUST_BE_ALLOCATED) {
1405 		slots = 1;
1406 
1407 		dnode_slots_hold(dnc, idx, slots);
1408 		dnh = &dnc->dnc_children[idx];
1409 
1410 		if (DN_SLOT_IS_PTR(dnh->dnh_dnode)) {
1411 			dn = dnh->dnh_dnode;
1412 		} else if (dnh->dnh_dnode == DN_SLOT_INTERIOR) {
1413 			DNODE_STAT_BUMP(dnode_hold_alloc_interior);
1414 			dnode_slots_rele(dnc, idx, slots);
1415 			dbuf_rele(db, FTAG);
1416 			return (SET_ERROR(EEXIST));
1417 		} else if (dnh->dnh_dnode != DN_SLOT_ALLOCATED) {
1418 			DNODE_STAT_BUMP(dnode_hold_alloc_misses);
1419 			dnode_slots_rele(dnc, idx, slots);
1420 			dbuf_rele(db, FTAG);
1421 			return (SET_ERROR(ENOENT));
1422 		} else {
1423 			dnode_slots_rele(dnc, idx, slots);
1424 			while (!dnode_slots_tryenter(dnc, idx, slots)) {
1425 				DNODE_STAT_BUMP(dnode_hold_alloc_lock_retry);
1426 				cond_resched();
1427 			}
1428 
1429 			/*
1430 			 * Someone else won the race and called dnode_create()
1431 			 * after we checked DN_SLOT_IS_PTR() above but before
1432 			 * we acquired the lock.
1433 			 */
1434 			if (DN_SLOT_IS_PTR(dnh->dnh_dnode)) {
1435 				DNODE_STAT_BUMP(dnode_hold_alloc_lock_misses);
1436 				dn = dnh->dnh_dnode;
1437 			} else {
1438 				dn = dnode_create(os, dn_block + idx, db,
1439 				    object, dnh);
1440 			}
1441 		}
1442 
1443 		mutex_enter(&dn->dn_mtx);
1444 		if (dn->dn_type == DMU_OT_NONE || dn->dn_free_txg != 0) {
1445 			DNODE_STAT_BUMP(dnode_hold_alloc_type_none);
1446 			mutex_exit(&dn->dn_mtx);
1447 			dnode_slots_rele(dnc, idx, slots);
1448 			dbuf_rele(db, FTAG);
1449 			return (SET_ERROR(ENOENT));
1450 		}
1451 
1452 		/* Don't actually hold if dry run, just return 0 */
1453 		if (flag & DNODE_DRY_RUN) {
1454 			mutex_exit(&dn->dn_mtx);
1455 			dnode_slots_rele(dnc, idx, slots);
1456 			dbuf_rele(db, FTAG);
1457 			return (0);
1458 		}
1459 
1460 		DNODE_STAT_BUMP(dnode_hold_alloc_hits);
1461 	} else if (flag & DNODE_MUST_BE_FREE) {
1462 
1463 		if (idx + slots - 1 >= DNODES_PER_BLOCK) {
1464 			DNODE_STAT_BUMP(dnode_hold_free_overflow);
1465 			dbuf_rele(db, FTAG);
1466 			return (SET_ERROR(ENOSPC));
1467 		}
1468 
1469 		dnode_slots_hold(dnc, idx, slots);
1470 
1471 		if (!dnode_check_slots_free(dnc, idx, slots)) {
1472 			DNODE_STAT_BUMP(dnode_hold_free_misses);
1473 			dnode_slots_rele(dnc, idx, slots);
1474 			dbuf_rele(db, FTAG);
1475 			return (SET_ERROR(ENOSPC));
1476 		}
1477 
1478 		dnode_slots_rele(dnc, idx, slots);
1479 		while (!dnode_slots_tryenter(dnc, idx, slots)) {
1480 			DNODE_STAT_BUMP(dnode_hold_free_lock_retry);
1481 			cond_resched();
1482 		}
1483 
1484 		if (!dnode_check_slots_free(dnc, idx, slots)) {
1485 			DNODE_STAT_BUMP(dnode_hold_free_lock_misses);
1486 			dnode_slots_rele(dnc, idx, slots);
1487 			dbuf_rele(db, FTAG);
1488 			return (SET_ERROR(ENOSPC));
1489 		}
1490 
1491 		/*
1492 		 * Allocated but otherwise free dnodes which would
1493 		 * be in the interior of a multi-slot dnodes need
1494 		 * to be freed.  Single slot dnodes can be safely
1495 		 * re-purposed as a performance optimization.
1496 		 */
1497 		if (slots > 1)
1498 			dnode_reclaim_slots(dnc, idx + 1, slots - 1);
1499 
1500 		dnh = &dnc->dnc_children[idx];
1501 		if (DN_SLOT_IS_PTR(dnh->dnh_dnode)) {
1502 			dn = dnh->dnh_dnode;
1503 		} else {
1504 			dn = dnode_create(os, dn_block + idx, db,
1505 			    object, dnh);
1506 		}
1507 
1508 		mutex_enter(&dn->dn_mtx);
1509 		if (!zfs_refcount_is_zero(&dn->dn_holds) || dn->dn_free_txg) {
1510 			DNODE_STAT_BUMP(dnode_hold_free_refcount);
1511 			mutex_exit(&dn->dn_mtx);
1512 			dnode_slots_rele(dnc, idx, slots);
1513 			dbuf_rele(db, FTAG);
1514 			return (SET_ERROR(EEXIST));
1515 		}
1516 
1517 		/* Don't actually hold if dry run, just return 0 */
1518 		if (flag & DNODE_DRY_RUN) {
1519 			mutex_exit(&dn->dn_mtx);
1520 			dnode_slots_rele(dnc, idx, slots);
1521 			dbuf_rele(db, FTAG);
1522 			return (0);
1523 		}
1524 
1525 		dnode_set_slots(dnc, idx + 1, slots - 1, DN_SLOT_INTERIOR);
1526 		DNODE_STAT_BUMP(dnode_hold_free_hits);
1527 	} else {
1528 		dbuf_rele(db, FTAG);
1529 		return (SET_ERROR(EINVAL));
1530 	}
1531 
1532 	ASSERT0(dn->dn_free_txg);
1533 
1534 	if (zfs_refcount_add(&dn->dn_holds, tag) == 1)
1535 		dbuf_add_ref(db, dnh);
1536 
1537 	mutex_exit(&dn->dn_mtx);
1538 
1539 	/* Now we can rely on the hold to prevent the dnode from moving. */
1540 	dnode_slots_rele(dnc, idx, slots);
1541 
1542 	DNODE_VERIFY(dn);
1543 	ASSERT3P(dnp, !=, NULL);
1544 	ASSERT3P(dn->dn_dbuf, ==, db);
1545 	ASSERT3U(dn->dn_object, ==, object);
1546 	dbuf_rele(db, FTAG);
1547 
1548 	*dnp = dn;
1549 	return (0);
1550 }
1551 
1552 /*
1553  * Return held dnode if the object is allocated, NULL if not.
1554  */
1555 int
1556 dnode_hold(objset_t *os, uint64_t object, const void *tag, dnode_t **dnp)
1557 {
1558 	return (dnode_hold_impl(os, object, DNODE_MUST_BE_ALLOCATED, 0, tag,
1559 	    dnp));
1560 }
1561 
1562 /*
1563  * Can only add a reference if there is already at least one
1564  * reference on the dnode.  Returns FALSE if unable to add a
1565  * new reference.
1566  */
1567 boolean_t
1568 dnode_add_ref(dnode_t *dn, const void *tag)
1569 {
1570 	mutex_enter(&dn->dn_mtx);
1571 	if (zfs_refcount_is_zero(&dn->dn_holds)) {
1572 		mutex_exit(&dn->dn_mtx);
1573 		return (FALSE);
1574 	}
1575 	VERIFY(1 < zfs_refcount_add(&dn->dn_holds, tag));
1576 	mutex_exit(&dn->dn_mtx);
1577 	return (TRUE);
1578 }
1579 
1580 void
1581 dnode_rele(dnode_t *dn, const void *tag)
1582 {
1583 	mutex_enter(&dn->dn_mtx);
1584 	dnode_rele_and_unlock(dn, tag, B_FALSE);
1585 }
1586 
1587 void
1588 dnode_rele_and_unlock(dnode_t *dn, const void *tag, boolean_t evicting)
1589 {
1590 	uint64_t refs;
1591 	/* Get while the hold prevents the dnode from moving. */
1592 	dmu_buf_impl_t *db = dn->dn_dbuf;
1593 	dnode_handle_t *dnh = dn->dn_handle;
1594 
1595 	refs = zfs_refcount_remove(&dn->dn_holds, tag);
1596 	if (refs == 0)
1597 		cv_broadcast(&dn->dn_nodnholds);
1598 	mutex_exit(&dn->dn_mtx);
1599 	/* dnode could get destroyed at this point, so don't use it anymore */
1600 
1601 	/*
1602 	 * It's unsafe to release the last hold on a dnode by dnode_rele() or
1603 	 * indirectly by dbuf_rele() while relying on the dnode handle to
1604 	 * prevent the dnode from moving, since releasing the last hold could
1605 	 * result in the dnode's parent dbuf evicting its dnode handles. For
1606 	 * that reason anyone calling dnode_rele() or dbuf_rele() without some
1607 	 * other direct or indirect hold on the dnode must first drop the dnode
1608 	 * handle.
1609 	 */
1610 #ifdef ZFS_DEBUG
1611 	ASSERT(refs > 0 || dnh->dnh_zrlock.zr_owner != curthread);
1612 #endif
1613 
1614 	/* NOTE: the DNODE_DNODE does not have a dn_dbuf */
1615 	if (refs == 0 && db != NULL) {
1616 		/*
1617 		 * Another thread could add a hold to the dnode handle in
1618 		 * dnode_hold_impl() while holding the parent dbuf. Since the
1619 		 * hold on the parent dbuf prevents the handle from being
1620 		 * destroyed, the hold on the handle is OK. We can't yet assert
1621 		 * that the handle has zero references, but that will be
1622 		 * asserted anyway when the handle gets destroyed.
1623 		 */
1624 		mutex_enter(&db->db_mtx);
1625 		dbuf_rele_and_unlock(db, dnh, evicting);
1626 	}
1627 }
1628 
1629 /*
1630  * Test whether we can create a dnode at the specified location.
1631  */
1632 int
1633 dnode_try_claim(objset_t *os, uint64_t object, int slots)
1634 {
1635 	return (dnode_hold_impl(os, object, DNODE_MUST_BE_FREE | DNODE_DRY_RUN,
1636 	    slots, NULL, NULL));
1637 }
1638 
1639 /*
1640  * Checks if the dnode contains any uncommitted dirty records.
1641  */
1642 boolean_t
1643 dnode_is_dirty(dnode_t *dn)
1644 {
1645 	mutex_enter(&dn->dn_mtx);
1646 
1647 	for (int i = 0; i < TXG_SIZE; i++) {
1648 		if (multilist_link_active(&dn->dn_dirty_link[i])) {
1649 			mutex_exit(&dn->dn_mtx);
1650 			return (B_TRUE);
1651 		}
1652 	}
1653 
1654 	mutex_exit(&dn->dn_mtx);
1655 
1656 	return (B_FALSE);
1657 }
1658 
1659 void
1660 dnode_setdirty(dnode_t *dn, dmu_tx_t *tx)
1661 {
1662 	objset_t *os = dn->dn_objset;
1663 	uint64_t txg = tx->tx_txg;
1664 
1665 	if (DMU_OBJECT_IS_SPECIAL(dn->dn_object)) {
1666 		dsl_dataset_dirty(os->os_dsl_dataset, tx);
1667 		return;
1668 	}
1669 
1670 	DNODE_VERIFY(dn);
1671 
1672 #ifdef ZFS_DEBUG
1673 	mutex_enter(&dn->dn_mtx);
1674 	ASSERT(dn->dn_phys->dn_type || dn->dn_allocated_txg);
1675 	ASSERT(dn->dn_free_txg == 0 || dn->dn_free_txg >= txg);
1676 	mutex_exit(&dn->dn_mtx);
1677 #endif
1678 
1679 	/*
1680 	 * Determine old uid/gid when necessary
1681 	 */
1682 	dmu_objset_userquota_get_ids(dn, B_TRUE, tx);
1683 
1684 	multilist_t *dirtylist = &os->os_dirty_dnodes[txg & TXG_MASK];
1685 	multilist_sublist_t *mls = multilist_sublist_lock_obj(dirtylist, dn);
1686 
1687 	/*
1688 	 * If we are already marked dirty, we're done.
1689 	 */
1690 	if (multilist_link_active(&dn->dn_dirty_link[txg & TXG_MASK])) {
1691 		multilist_sublist_unlock(mls);
1692 		return;
1693 	}
1694 
1695 	ASSERT(!zfs_refcount_is_zero(&dn->dn_holds) ||
1696 	    !avl_is_empty(&dn->dn_dbufs));
1697 	ASSERT(dn->dn_datablksz != 0);
1698 	ASSERT0(dn->dn_next_bonuslen[txg & TXG_MASK]);
1699 	ASSERT0(dn->dn_next_blksz[txg & TXG_MASK]);
1700 	ASSERT0(dn->dn_next_bonustype[txg & TXG_MASK]);
1701 
1702 	dprintf_ds(os->os_dsl_dataset, "obj=%llu txg=%llu\n",
1703 	    (u_longlong_t)dn->dn_object, (u_longlong_t)txg);
1704 
1705 	multilist_sublist_insert_head(mls, dn);
1706 
1707 	multilist_sublist_unlock(mls);
1708 
1709 	/*
1710 	 * The dnode maintains a hold on its containing dbuf as
1711 	 * long as there are holds on it.  Each instantiated child
1712 	 * dbuf maintains a hold on the dnode.  When the last child
1713 	 * drops its hold, the dnode will drop its hold on the
1714 	 * containing dbuf. We add a "dirty hold" here so that the
1715 	 * dnode will hang around after we finish processing its
1716 	 * children.
1717 	 */
1718 	VERIFY(dnode_add_ref(dn, (void *)(uintptr_t)tx->tx_txg));
1719 
1720 	(void) dbuf_dirty(dn->dn_dbuf, tx);
1721 
1722 	dsl_dataset_dirty(os->os_dsl_dataset, tx);
1723 }
1724 
1725 void
1726 dnode_free(dnode_t *dn, dmu_tx_t *tx)
1727 {
1728 	mutex_enter(&dn->dn_mtx);
1729 	if (dn->dn_type == DMU_OT_NONE || dn->dn_free_txg) {
1730 		mutex_exit(&dn->dn_mtx);
1731 		return;
1732 	}
1733 	dn->dn_free_txg = tx->tx_txg;
1734 	mutex_exit(&dn->dn_mtx);
1735 
1736 	dnode_setdirty(dn, tx);
1737 }
1738 
1739 /*
1740  * Try to change the block size for the indicated dnode.  This can only
1741  * succeed if there are no blocks allocated or dirty beyond first block
1742  */
1743 int
1744 dnode_set_blksz(dnode_t *dn, uint64_t size, int ibs, dmu_tx_t *tx)
1745 {
1746 	dmu_buf_impl_t *db;
1747 	int err;
1748 
1749 	ASSERT3U(size, <=, spa_maxblocksize(dmu_objset_spa(dn->dn_objset)));
1750 	if (size == 0)
1751 		size = SPA_MINBLOCKSIZE;
1752 	else
1753 		size = P2ROUNDUP(size, SPA_MINBLOCKSIZE);
1754 
1755 	if (ibs == dn->dn_indblkshift)
1756 		ibs = 0;
1757 
1758 	if (size >> SPA_MINBLOCKSHIFT == dn->dn_datablkszsec && ibs == 0)
1759 		return (0);
1760 
1761 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
1762 
1763 	/* Check for any allocated blocks beyond the first */
1764 	if (dn->dn_maxblkid != 0)
1765 		goto fail;
1766 
1767 	mutex_enter(&dn->dn_dbufs_mtx);
1768 	for (db = avl_first(&dn->dn_dbufs); db != NULL;
1769 	    db = AVL_NEXT(&dn->dn_dbufs, db)) {
1770 		if (db->db_blkid != 0 && db->db_blkid != DMU_BONUS_BLKID &&
1771 		    db->db_blkid != DMU_SPILL_BLKID) {
1772 			mutex_exit(&dn->dn_dbufs_mtx);
1773 			goto fail;
1774 		}
1775 	}
1776 	mutex_exit(&dn->dn_dbufs_mtx);
1777 
1778 	if (ibs && dn->dn_nlevels != 1)
1779 		goto fail;
1780 
1781 	/* resize the old block */
1782 	err = dbuf_hold_impl(dn, 0, 0, TRUE, FALSE, FTAG, &db);
1783 	if (err == 0) {
1784 		dbuf_new_size(db, size, tx);
1785 	} else if (err != ENOENT) {
1786 		goto fail;
1787 	}
1788 
1789 	dnode_setdblksz(dn, size);
1790 	dnode_setdirty(dn, tx);
1791 	dn->dn_next_blksz[tx->tx_txg&TXG_MASK] = size;
1792 	if (ibs) {
1793 		dn->dn_indblkshift = ibs;
1794 		dn->dn_next_indblkshift[tx->tx_txg&TXG_MASK] = ibs;
1795 	}
1796 	/* release after we have fixed the blocksize in the dnode */
1797 	if (db)
1798 		dbuf_rele(db, FTAG);
1799 
1800 	rw_exit(&dn->dn_struct_rwlock);
1801 	return (0);
1802 
1803 fail:
1804 	rw_exit(&dn->dn_struct_rwlock);
1805 	return (SET_ERROR(ENOTSUP));
1806 }
1807 
1808 static void
1809 dnode_set_nlevels_impl(dnode_t *dn, int new_nlevels, dmu_tx_t *tx)
1810 {
1811 	uint64_t txgoff = tx->tx_txg & TXG_MASK;
1812 	int old_nlevels = dn->dn_nlevels;
1813 	dmu_buf_impl_t *db;
1814 	list_t *list;
1815 	dbuf_dirty_record_t *new, *dr, *dr_next;
1816 
1817 	ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
1818 
1819 	ASSERT3U(new_nlevels, >, dn->dn_nlevels);
1820 	dn->dn_nlevels = new_nlevels;
1821 
1822 	ASSERT3U(new_nlevels, >, dn->dn_next_nlevels[txgoff]);
1823 	dn->dn_next_nlevels[txgoff] = new_nlevels;
1824 
1825 	/* dirty the left indirects */
1826 	db = dbuf_hold_level(dn, old_nlevels, 0, FTAG);
1827 	ASSERT(db != NULL);
1828 	new = dbuf_dirty(db, tx);
1829 	dbuf_rele(db, FTAG);
1830 
1831 	/* transfer the dirty records to the new indirect */
1832 	mutex_enter(&dn->dn_mtx);
1833 	mutex_enter(&new->dt.di.dr_mtx);
1834 	list = &dn->dn_dirty_records[txgoff];
1835 	for (dr = list_head(list); dr; dr = dr_next) {
1836 		dr_next = list_next(&dn->dn_dirty_records[txgoff], dr);
1837 
1838 		IMPLY(dr->dr_dbuf == NULL, old_nlevels == 1);
1839 		if (dr->dr_dbuf == NULL ||
1840 		    (dr->dr_dbuf->db_level == old_nlevels - 1 &&
1841 		    dr->dr_dbuf->db_blkid != DMU_BONUS_BLKID &&
1842 		    dr->dr_dbuf->db_blkid != DMU_SPILL_BLKID)) {
1843 			list_remove(&dn->dn_dirty_records[txgoff], dr);
1844 			list_insert_tail(&new->dt.di.dr_children, dr);
1845 			dr->dr_parent = new;
1846 		}
1847 	}
1848 	mutex_exit(&new->dt.di.dr_mtx);
1849 	mutex_exit(&dn->dn_mtx);
1850 }
1851 
1852 int
1853 dnode_set_nlevels(dnode_t *dn, int nlevels, dmu_tx_t *tx)
1854 {
1855 	int ret = 0;
1856 
1857 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
1858 
1859 	if (dn->dn_nlevels == nlevels) {
1860 		ret = 0;
1861 		goto out;
1862 	} else if (nlevels < dn->dn_nlevels) {
1863 		ret = SET_ERROR(EINVAL);
1864 		goto out;
1865 	}
1866 
1867 	dnode_set_nlevels_impl(dn, nlevels, tx);
1868 
1869 out:
1870 	rw_exit(&dn->dn_struct_rwlock);
1871 	return (ret);
1872 }
1873 
1874 /* read-holding callers must not rely on the lock being continuously held */
1875 void
1876 dnode_new_blkid(dnode_t *dn, uint64_t blkid, dmu_tx_t *tx, boolean_t have_read,
1877     boolean_t force)
1878 {
1879 	int epbs, new_nlevels;
1880 	uint64_t sz;
1881 
1882 	ASSERT(blkid != DMU_BONUS_BLKID);
1883 
1884 	ASSERT(have_read ?
1885 	    RW_READ_HELD(&dn->dn_struct_rwlock) :
1886 	    RW_WRITE_HELD(&dn->dn_struct_rwlock));
1887 
1888 	/*
1889 	 * if we have a read-lock, check to see if we need to do any work
1890 	 * before upgrading to a write-lock.
1891 	 */
1892 	if (have_read) {
1893 		if (blkid <= dn->dn_maxblkid)
1894 			return;
1895 
1896 		if (!rw_tryupgrade(&dn->dn_struct_rwlock)) {
1897 			rw_exit(&dn->dn_struct_rwlock);
1898 			rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
1899 		}
1900 	}
1901 
1902 	/*
1903 	 * Raw sends (indicated by the force flag) require that we take the
1904 	 * given blkid even if the value is lower than the current value.
1905 	 */
1906 	if (!force && blkid <= dn->dn_maxblkid)
1907 		goto out;
1908 
1909 	/*
1910 	 * We use the (otherwise unused) top bit of dn_next_maxblkid[txgoff]
1911 	 * to indicate that this field is set. This allows us to set the
1912 	 * maxblkid to 0 on an existing object in dnode_sync().
1913 	 */
1914 	dn->dn_maxblkid = blkid;
1915 	dn->dn_next_maxblkid[tx->tx_txg & TXG_MASK] =
1916 	    blkid | DMU_NEXT_MAXBLKID_SET;
1917 
1918 	/*
1919 	 * Compute the number of levels necessary to support the new maxblkid.
1920 	 * Raw sends will ensure nlevels is set correctly for us.
1921 	 */
1922 	new_nlevels = 1;
1923 	epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
1924 	for (sz = dn->dn_nblkptr;
1925 	    sz <= blkid && sz >= dn->dn_nblkptr; sz <<= epbs)
1926 		new_nlevels++;
1927 
1928 	ASSERT3U(new_nlevels, <=, DN_MAX_LEVELS);
1929 
1930 	if (!force) {
1931 		if (new_nlevels > dn->dn_nlevels)
1932 			dnode_set_nlevels_impl(dn, new_nlevels, tx);
1933 	} else {
1934 		ASSERT3U(dn->dn_nlevels, >=, new_nlevels);
1935 	}
1936 
1937 out:
1938 	if (have_read)
1939 		rw_downgrade(&dn->dn_struct_rwlock);
1940 }
1941 
1942 static void
1943 dnode_dirty_l1(dnode_t *dn, uint64_t l1blkid, dmu_tx_t *tx)
1944 {
1945 	dmu_buf_impl_t *db = dbuf_hold_level(dn, 1, l1blkid, FTAG);
1946 	if (db != NULL) {
1947 		dmu_buf_will_dirty(&db->db, tx);
1948 		dbuf_rele(db, FTAG);
1949 	}
1950 }
1951 
1952 /*
1953  * Dirty all the in-core level-1 dbufs in the range specified by start_blkid
1954  * and end_blkid.
1955  */
1956 static void
1957 dnode_dirty_l1range(dnode_t *dn, uint64_t start_blkid, uint64_t end_blkid,
1958     dmu_tx_t *tx)
1959 {
1960 	dmu_buf_impl_t *db_search;
1961 	dmu_buf_impl_t *db;
1962 	avl_index_t where;
1963 
1964 	db_search = kmem_zalloc(sizeof (dmu_buf_impl_t), KM_SLEEP);
1965 
1966 	mutex_enter(&dn->dn_dbufs_mtx);
1967 
1968 	db_search->db_level = 1;
1969 	db_search->db_blkid = start_blkid + 1;
1970 	db_search->db_state = DB_SEARCH;
1971 	for (;;) {
1972 
1973 		db = avl_find(&dn->dn_dbufs, db_search, &where);
1974 		if (db == NULL)
1975 			db = avl_nearest(&dn->dn_dbufs, where, AVL_AFTER);
1976 
1977 		if (db == NULL || db->db_level != 1 ||
1978 		    db->db_blkid >= end_blkid) {
1979 			break;
1980 		}
1981 
1982 		/*
1983 		 * Setup the next blkid we want to search for.
1984 		 */
1985 		db_search->db_blkid = db->db_blkid + 1;
1986 		ASSERT3U(db->db_blkid, >=, start_blkid);
1987 
1988 		/*
1989 		 * If the dbuf transitions to DB_EVICTING while we're trying
1990 		 * to dirty it, then we will be unable to discover it in
1991 		 * the dbuf hash table. This will result in a call to
1992 		 * dbuf_create() which needs to acquire the dn_dbufs_mtx
1993 		 * lock. To avoid a deadlock, we drop the lock before
1994 		 * dirtying the level-1 dbuf.
1995 		 */
1996 		mutex_exit(&dn->dn_dbufs_mtx);
1997 		dnode_dirty_l1(dn, db->db_blkid, tx);
1998 		mutex_enter(&dn->dn_dbufs_mtx);
1999 	}
2000 
2001 #ifdef ZFS_DEBUG
2002 	/*
2003 	 * Walk all the in-core level-1 dbufs and verify they have been dirtied.
2004 	 */
2005 	db_search->db_level = 1;
2006 	db_search->db_blkid = start_blkid + 1;
2007 	db_search->db_state = DB_SEARCH;
2008 	db = avl_find(&dn->dn_dbufs, db_search, &where);
2009 	if (db == NULL)
2010 		db = avl_nearest(&dn->dn_dbufs, where, AVL_AFTER);
2011 	for (; db != NULL; db = AVL_NEXT(&dn->dn_dbufs, db)) {
2012 		if (db->db_level != 1 || db->db_blkid >= end_blkid)
2013 			break;
2014 		if (db->db_state != DB_EVICTING)
2015 			ASSERT(db->db_dirtycnt > 0);
2016 	}
2017 #endif
2018 	kmem_free(db_search, sizeof (dmu_buf_impl_t));
2019 	mutex_exit(&dn->dn_dbufs_mtx);
2020 }
2021 
2022 void
2023 dnode_set_dirtyctx(dnode_t *dn, dmu_tx_t *tx, const void *tag)
2024 {
2025 	/*
2026 	 * Don't set dirtyctx to SYNC if we're just modifying this as we
2027 	 * initialize the objset.
2028 	 */
2029 	if (dn->dn_dirtyctx == DN_UNDIRTIED) {
2030 		dsl_dataset_t *ds = dn->dn_objset->os_dsl_dataset;
2031 
2032 		if (ds != NULL) {
2033 			rrw_enter(&ds->ds_bp_rwlock, RW_READER, tag);
2034 		}
2035 		if (!BP_IS_HOLE(dn->dn_objset->os_rootbp)) {
2036 			if (dmu_tx_is_syncing(tx))
2037 				dn->dn_dirtyctx = DN_DIRTY_SYNC;
2038 			else
2039 				dn->dn_dirtyctx = DN_DIRTY_OPEN;
2040 			dn->dn_dirtyctx_firstset = tag;
2041 		}
2042 		if (ds != NULL) {
2043 			rrw_exit(&ds->ds_bp_rwlock, tag);
2044 		}
2045 	}
2046 }
2047 
2048 static void
2049 dnode_partial_zero(dnode_t *dn, uint64_t off, uint64_t blkoff, uint64_t len,
2050     dmu_tx_t *tx)
2051 {
2052 	dmu_buf_impl_t *db;
2053 	int res;
2054 
2055 	rw_enter(&dn->dn_struct_rwlock, RW_READER);
2056 	res = dbuf_hold_impl(dn, 0, dbuf_whichblock(dn, 0, off), TRUE, FALSE,
2057 	    FTAG, &db);
2058 	rw_exit(&dn->dn_struct_rwlock);
2059 	if (res == 0) {
2060 		db_lock_type_t dblt;
2061 		boolean_t dirty;
2062 
2063 		dblt = dmu_buf_lock_parent(db, RW_READER, FTAG);
2064 		/* don't dirty if not on disk and not dirty */
2065 		dirty = !list_is_empty(&db->db_dirty_records) ||
2066 		    (db->db_blkptr && !BP_IS_HOLE(db->db_blkptr));
2067 		dmu_buf_unlock_parent(db, dblt, FTAG);
2068 		if (dirty) {
2069 			caddr_t data;
2070 
2071 			dmu_buf_will_dirty(&db->db, tx);
2072 			data = db->db.db_data;
2073 			memset(data + blkoff, 0, len);
2074 		}
2075 		dbuf_rele(db, FTAG);
2076 	}
2077 }
2078 
2079 void
2080 dnode_free_range(dnode_t *dn, uint64_t off, uint64_t len, dmu_tx_t *tx)
2081 {
2082 	uint64_t blkoff, blkid, nblks;
2083 	int blksz, blkshift, head, tail;
2084 	int trunc = FALSE;
2085 	int epbs;
2086 
2087 	blksz = dn->dn_datablksz;
2088 	blkshift = dn->dn_datablkshift;
2089 	epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
2090 
2091 	if (len == DMU_OBJECT_END) {
2092 		len = UINT64_MAX - off;
2093 		trunc = TRUE;
2094 	}
2095 
2096 	/*
2097 	 * First, block align the region to free:
2098 	 */
2099 	if (ISP2(blksz)) {
2100 		head = P2NPHASE(off, blksz);
2101 		blkoff = P2PHASE(off, blksz);
2102 		if ((off >> blkshift) > dn->dn_maxblkid)
2103 			return;
2104 	} else {
2105 		ASSERT(dn->dn_maxblkid == 0);
2106 		if (off == 0 && len >= blksz) {
2107 			/*
2108 			 * Freeing the whole block; fast-track this request.
2109 			 */
2110 			blkid = 0;
2111 			nblks = 1;
2112 			if (dn->dn_nlevels > 1) {
2113 				rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
2114 				dnode_dirty_l1(dn, 0, tx);
2115 				rw_exit(&dn->dn_struct_rwlock);
2116 			}
2117 			goto done;
2118 		} else if (off >= blksz) {
2119 			/* Freeing past end-of-data */
2120 			return;
2121 		} else {
2122 			/* Freeing part of the block. */
2123 			head = blksz - off;
2124 			ASSERT3U(head, >, 0);
2125 		}
2126 		blkoff = off;
2127 	}
2128 	/* zero out any partial block data at the start of the range */
2129 	if (head) {
2130 		ASSERT3U(blkoff + head, ==, blksz);
2131 		if (len < head)
2132 			head = len;
2133 		dnode_partial_zero(dn, off, blkoff, head, tx);
2134 		off += head;
2135 		len -= head;
2136 	}
2137 
2138 	/* If the range was less than one block, we're done */
2139 	if (len == 0)
2140 		return;
2141 
2142 	/* If the remaining range is past end of file, we're done */
2143 	if ((off >> blkshift) > dn->dn_maxblkid)
2144 		return;
2145 
2146 	ASSERT(ISP2(blksz));
2147 	if (trunc)
2148 		tail = 0;
2149 	else
2150 		tail = P2PHASE(len, blksz);
2151 
2152 	ASSERT0(P2PHASE(off, blksz));
2153 	/* zero out any partial block data at the end of the range */
2154 	if (tail) {
2155 		if (len < tail)
2156 			tail = len;
2157 		dnode_partial_zero(dn, off + len, 0, tail, tx);
2158 		len -= tail;
2159 	}
2160 
2161 	/* If the range did not include a full block, we are done */
2162 	if (len == 0)
2163 		return;
2164 
2165 	ASSERT(IS_P2ALIGNED(off, blksz));
2166 	ASSERT(trunc || IS_P2ALIGNED(len, blksz));
2167 	blkid = off >> blkshift;
2168 	nblks = len >> blkshift;
2169 	if (trunc)
2170 		nblks += 1;
2171 
2172 	/*
2173 	 * Dirty all the indirect blocks in this range.  Note that only
2174 	 * the first and last indirect blocks can actually be written
2175 	 * (if they were partially freed) -- they must be dirtied, even if
2176 	 * they do not exist on disk yet.  The interior blocks will
2177 	 * be freed by free_children(), so they will not actually be written.
2178 	 * Even though these interior blocks will not be written, we
2179 	 * dirty them for two reasons:
2180 	 *
2181 	 *  - It ensures that the indirect blocks remain in memory until
2182 	 *    syncing context.  (They have already been prefetched by
2183 	 *    dmu_tx_hold_free(), so we don't have to worry about reading
2184 	 *    them serially here.)
2185 	 *
2186 	 *  - The dirty space accounting will put pressure on the txg sync
2187 	 *    mechanism to begin syncing, and to delay transactions if there
2188 	 *    is a large amount of freeing.  Even though these indirect
2189 	 *    blocks will not be written, we could need to write the same
2190 	 *    amount of space if we copy the freed BPs into deadlists.
2191 	 */
2192 	if (dn->dn_nlevels > 1) {
2193 		rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
2194 		uint64_t first, last;
2195 
2196 		first = blkid >> epbs;
2197 		dnode_dirty_l1(dn, first, tx);
2198 		if (trunc)
2199 			last = dn->dn_maxblkid >> epbs;
2200 		else
2201 			last = (blkid + nblks - 1) >> epbs;
2202 		if (last != first)
2203 			dnode_dirty_l1(dn, last, tx);
2204 
2205 		dnode_dirty_l1range(dn, first, last, tx);
2206 
2207 		int shift = dn->dn_datablkshift + dn->dn_indblkshift -
2208 		    SPA_BLKPTRSHIFT;
2209 		for (uint64_t i = first + 1; i < last; i++) {
2210 			/*
2211 			 * Set i to the blockid of the next non-hole
2212 			 * level-1 indirect block at or after i.  Note
2213 			 * that dnode_next_offset() operates in terms of
2214 			 * level-0-equivalent bytes.
2215 			 */
2216 			uint64_t ibyte = i << shift;
2217 			int err = dnode_next_offset(dn, DNODE_FIND_HAVELOCK,
2218 			    &ibyte, 2, 1, 0);
2219 			i = ibyte >> shift;
2220 			if (i >= last)
2221 				break;
2222 
2223 			/*
2224 			 * Normally we should not see an error, either
2225 			 * from dnode_next_offset() or dbuf_hold_level()
2226 			 * (except for ESRCH from dnode_next_offset).
2227 			 * If there is an i/o error, then when we read
2228 			 * this block in syncing context, it will use
2229 			 * ZIO_FLAG_MUSTSUCCEED, and thus hang/panic according
2230 			 * to the "failmode" property.  dnode_next_offset()
2231 			 * doesn't have a flag to indicate MUSTSUCCEED.
2232 			 */
2233 			if (err != 0)
2234 				break;
2235 
2236 			dnode_dirty_l1(dn, i, tx);
2237 		}
2238 		rw_exit(&dn->dn_struct_rwlock);
2239 	}
2240 
2241 done:
2242 	/*
2243 	 * Add this range to the dnode range list.
2244 	 * We will finish up this free operation in the syncing phase.
2245 	 */
2246 	mutex_enter(&dn->dn_mtx);
2247 	{
2248 		int txgoff = tx->tx_txg & TXG_MASK;
2249 		if (dn->dn_free_ranges[txgoff] == NULL) {
2250 			dn->dn_free_ranges[txgoff] = range_tree_create(NULL,
2251 			    RANGE_SEG64, NULL, 0, 0);
2252 		}
2253 		range_tree_clear(dn->dn_free_ranges[txgoff], blkid, nblks);
2254 		range_tree_add(dn->dn_free_ranges[txgoff], blkid, nblks);
2255 	}
2256 	dprintf_dnode(dn, "blkid=%llu nblks=%llu txg=%llu\n",
2257 	    (u_longlong_t)blkid, (u_longlong_t)nblks,
2258 	    (u_longlong_t)tx->tx_txg);
2259 	mutex_exit(&dn->dn_mtx);
2260 
2261 	dbuf_free_range(dn, blkid, blkid + nblks - 1, tx);
2262 	dnode_setdirty(dn, tx);
2263 }
2264 
2265 static boolean_t
2266 dnode_spill_freed(dnode_t *dn)
2267 {
2268 	int i;
2269 
2270 	mutex_enter(&dn->dn_mtx);
2271 	for (i = 0; i < TXG_SIZE; i++) {
2272 		if (dn->dn_rm_spillblk[i] == DN_KILL_SPILLBLK)
2273 			break;
2274 	}
2275 	mutex_exit(&dn->dn_mtx);
2276 	return (i < TXG_SIZE);
2277 }
2278 
2279 /* return TRUE if this blkid was freed in a recent txg, or FALSE if it wasn't */
2280 uint64_t
2281 dnode_block_freed(dnode_t *dn, uint64_t blkid)
2282 {
2283 	void *dp = spa_get_dsl(dn->dn_objset->os_spa);
2284 	int i;
2285 
2286 	if (blkid == DMU_BONUS_BLKID)
2287 		return (FALSE);
2288 
2289 	/*
2290 	 * If we're in the process of opening the pool, dp will not be
2291 	 * set yet, but there shouldn't be anything dirty.
2292 	 */
2293 	if (dp == NULL)
2294 		return (FALSE);
2295 
2296 	if (dn->dn_free_txg)
2297 		return (TRUE);
2298 
2299 	if (blkid == DMU_SPILL_BLKID)
2300 		return (dnode_spill_freed(dn));
2301 
2302 	mutex_enter(&dn->dn_mtx);
2303 	for (i = 0; i < TXG_SIZE; i++) {
2304 		if (dn->dn_free_ranges[i] != NULL &&
2305 		    range_tree_contains(dn->dn_free_ranges[i], blkid, 1))
2306 			break;
2307 	}
2308 	mutex_exit(&dn->dn_mtx);
2309 	return (i < TXG_SIZE);
2310 }
2311 
2312 /* call from syncing context when we actually write/free space for this dnode */
2313 void
2314 dnode_diduse_space(dnode_t *dn, int64_t delta)
2315 {
2316 	uint64_t space;
2317 	dprintf_dnode(dn, "dn=%p dnp=%p used=%llu delta=%lld\n",
2318 	    dn, dn->dn_phys,
2319 	    (u_longlong_t)dn->dn_phys->dn_used,
2320 	    (longlong_t)delta);
2321 
2322 	mutex_enter(&dn->dn_mtx);
2323 	space = DN_USED_BYTES(dn->dn_phys);
2324 	if (delta > 0) {
2325 		ASSERT3U(space + delta, >=, space); /* no overflow */
2326 	} else {
2327 		ASSERT3U(space, >=, -delta); /* no underflow */
2328 	}
2329 	space += delta;
2330 	if (spa_version(dn->dn_objset->os_spa) < SPA_VERSION_DNODE_BYTES) {
2331 		ASSERT((dn->dn_phys->dn_flags & DNODE_FLAG_USED_BYTES) == 0);
2332 		ASSERT0(P2PHASE(space, 1<<DEV_BSHIFT));
2333 		dn->dn_phys->dn_used = space >> DEV_BSHIFT;
2334 	} else {
2335 		dn->dn_phys->dn_used = space;
2336 		dn->dn_phys->dn_flags |= DNODE_FLAG_USED_BYTES;
2337 	}
2338 	mutex_exit(&dn->dn_mtx);
2339 }
2340 
2341 /*
2342  * Scans a block at the indicated "level" looking for a hole or data,
2343  * depending on 'flags'.
2344  *
2345  * If level > 0, then we are scanning an indirect block looking at its
2346  * pointers.  If level == 0, then we are looking at a block of dnodes.
2347  *
2348  * If we don't find what we are looking for in the block, we return ESRCH.
2349  * Otherwise, return with *offset pointing to the beginning (if searching
2350  * forwards) or end (if searching backwards) of the range covered by the
2351  * block pointer we matched on (or dnode).
2352  *
2353  * The basic search algorithm used below by dnode_next_offset() is to
2354  * use this function to search up the block tree (widen the search) until
2355  * we find something (i.e., we don't return ESRCH) and then search back
2356  * down the tree (narrow the search) until we reach our original search
2357  * level.
2358  */
2359 static int
2360 dnode_next_offset_level(dnode_t *dn, int flags, uint64_t *offset,
2361     int lvl, uint64_t blkfill, uint64_t txg)
2362 {
2363 	dmu_buf_impl_t *db = NULL;
2364 	void *data = NULL;
2365 	uint64_t epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
2366 	uint64_t epb = 1ULL << epbs;
2367 	uint64_t minfill, maxfill;
2368 	boolean_t hole;
2369 	int i, inc, error, span;
2370 
2371 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
2372 
2373 	hole = ((flags & DNODE_FIND_HOLE) != 0);
2374 	inc = (flags & DNODE_FIND_BACKWARDS) ? -1 : 1;
2375 	ASSERT(txg == 0 || !hole);
2376 
2377 	if (lvl == dn->dn_phys->dn_nlevels) {
2378 		error = 0;
2379 		epb = dn->dn_phys->dn_nblkptr;
2380 		data = dn->dn_phys->dn_blkptr;
2381 	} else {
2382 		uint64_t blkid = dbuf_whichblock(dn, lvl, *offset);
2383 		error = dbuf_hold_impl(dn, lvl, blkid, TRUE, FALSE, FTAG, &db);
2384 		if (error) {
2385 			if (error != ENOENT)
2386 				return (error);
2387 			if (hole)
2388 				return (0);
2389 			/*
2390 			 * This can only happen when we are searching up
2391 			 * the block tree for data.  We don't really need to
2392 			 * adjust the offset, as we will just end up looking
2393 			 * at the pointer to this block in its parent, and its
2394 			 * going to be unallocated, so we will skip over it.
2395 			 */
2396 			return (SET_ERROR(ESRCH));
2397 		}
2398 		error = dbuf_read(db, NULL,
2399 		    DB_RF_CANFAIL | DB_RF_HAVESTRUCT |
2400 		    DB_RF_NO_DECRYPT | DB_RF_NOPREFETCH);
2401 		if (error) {
2402 			dbuf_rele(db, FTAG);
2403 			return (error);
2404 		}
2405 		data = db->db.db_data;
2406 		rw_enter(&db->db_rwlock, RW_READER);
2407 	}
2408 
2409 	if (db != NULL && txg != 0 && (db->db_blkptr == NULL ||
2410 	    db->db_blkptr->blk_birth <= txg ||
2411 	    BP_IS_HOLE(db->db_blkptr))) {
2412 		/*
2413 		 * This can only happen when we are searching up the tree
2414 		 * and these conditions mean that we need to keep climbing.
2415 		 */
2416 		error = SET_ERROR(ESRCH);
2417 	} else if (lvl == 0) {
2418 		dnode_phys_t *dnp = data;
2419 
2420 		ASSERT(dn->dn_type == DMU_OT_DNODE);
2421 		ASSERT(!(flags & DNODE_FIND_BACKWARDS));
2422 
2423 		for (i = (*offset >> DNODE_SHIFT) & (blkfill - 1);
2424 		    i < blkfill; i += dnp[i].dn_extra_slots + 1) {
2425 			if ((dnp[i].dn_type == DMU_OT_NONE) == hole)
2426 				break;
2427 		}
2428 
2429 		if (i == blkfill)
2430 			error = SET_ERROR(ESRCH);
2431 
2432 		*offset = (*offset & ~(DNODE_BLOCK_SIZE - 1)) +
2433 		    (i << DNODE_SHIFT);
2434 	} else {
2435 		blkptr_t *bp = data;
2436 		uint64_t start = *offset;
2437 		span = (lvl - 1) * epbs + dn->dn_datablkshift;
2438 		minfill = 0;
2439 		maxfill = blkfill << ((lvl - 1) * epbs);
2440 
2441 		if (hole)
2442 			maxfill--;
2443 		else
2444 			minfill++;
2445 
2446 		if (span >= 8 * sizeof (*offset)) {
2447 			/* This only happens on the highest indirection level */
2448 			ASSERT3U((lvl - 1), ==, dn->dn_phys->dn_nlevels - 1);
2449 			*offset = 0;
2450 		} else {
2451 			*offset = *offset >> span;
2452 		}
2453 
2454 		for (i = BF64_GET(*offset, 0, epbs);
2455 		    i >= 0 && i < epb; i += inc) {
2456 			if (BP_GET_FILL(&bp[i]) >= minfill &&
2457 			    BP_GET_FILL(&bp[i]) <= maxfill &&
2458 			    (hole || bp[i].blk_birth > txg))
2459 				break;
2460 			if (inc > 0 || *offset > 0)
2461 				*offset += inc;
2462 		}
2463 
2464 		if (span >= 8 * sizeof (*offset)) {
2465 			*offset = start;
2466 		} else {
2467 			*offset = *offset << span;
2468 		}
2469 
2470 		if (inc < 0) {
2471 			/* traversing backwards; position offset at the end */
2472 			ASSERT3U(*offset, <=, start);
2473 			*offset = MIN(*offset + (1ULL << span) - 1, start);
2474 		} else if (*offset < start) {
2475 			*offset = start;
2476 		}
2477 		if (i < 0 || i >= epb)
2478 			error = SET_ERROR(ESRCH);
2479 	}
2480 
2481 	if (db != NULL) {
2482 		rw_exit(&db->db_rwlock);
2483 		dbuf_rele(db, FTAG);
2484 	}
2485 
2486 	return (error);
2487 }
2488 
2489 /*
2490  * Find the next hole, data, or sparse region at or after *offset.
2491  * The value 'blkfill' tells us how many items we expect to find
2492  * in an L0 data block; this value is 1 for normal objects,
2493  * DNODES_PER_BLOCK for the meta dnode, and some fraction of
2494  * DNODES_PER_BLOCK when searching for sparse regions thereof.
2495  *
2496  * Examples:
2497  *
2498  * dnode_next_offset(dn, flags, offset, 1, 1, 0);
2499  *	Finds the next/previous hole/data in a file.
2500  *	Used in dmu_offset_next().
2501  *
2502  * dnode_next_offset(mdn, flags, offset, 0, DNODES_PER_BLOCK, txg);
2503  *	Finds the next free/allocated dnode an objset's meta-dnode.
2504  *	Only finds objects that have new contents since txg (ie.
2505  *	bonus buffer changes and content removal are ignored).
2506  *	Used in dmu_object_next().
2507  *
2508  * dnode_next_offset(mdn, DNODE_FIND_HOLE, offset, 2, DNODES_PER_BLOCK >> 2, 0);
2509  *	Finds the next L2 meta-dnode bp that's at most 1/4 full.
2510  *	Used in dmu_object_alloc().
2511  */
2512 int
2513 dnode_next_offset(dnode_t *dn, int flags, uint64_t *offset,
2514     int minlvl, uint64_t blkfill, uint64_t txg)
2515 {
2516 	uint64_t initial_offset = *offset;
2517 	int lvl, maxlvl;
2518 	int error = 0;
2519 
2520 	if (!(flags & DNODE_FIND_HAVELOCK))
2521 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
2522 
2523 	if (dn->dn_phys->dn_nlevels == 0) {
2524 		error = SET_ERROR(ESRCH);
2525 		goto out;
2526 	}
2527 
2528 	if (dn->dn_datablkshift == 0) {
2529 		if (*offset < dn->dn_datablksz) {
2530 			if (flags & DNODE_FIND_HOLE)
2531 				*offset = dn->dn_datablksz;
2532 		} else {
2533 			error = SET_ERROR(ESRCH);
2534 		}
2535 		goto out;
2536 	}
2537 
2538 	maxlvl = dn->dn_phys->dn_nlevels;
2539 
2540 	for (lvl = minlvl; lvl <= maxlvl; lvl++) {
2541 		error = dnode_next_offset_level(dn,
2542 		    flags, offset, lvl, blkfill, txg);
2543 		if (error != ESRCH)
2544 			break;
2545 	}
2546 
2547 	while (error == 0 && --lvl >= minlvl) {
2548 		error = dnode_next_offset_level(dn,
2549 		    flags, offset, lvl, blkfill, txg);
2550 	}
2551 
2552 	/*
2553 	 * There's always a "virtual hole" at the end of the object, even
2554 	 * if all BP's which physically exist are non-holes.
2555 	 */
2556 	if ((flags & DNODE_FIND_HOLE) && error == ESRCH && txg == 0 &&
2557 	    minlvl == 1 && blkfill == 1 && !(flags & DNODE_FIND_BACKWARDS)) {
2558 		error = 0;
2559 	}
2560 
2561 	if (error == 0 && (flags & DNODE_FIND_BACKWARDS ?
2562 	    initial_offset < *offset : initial_offset > *offset))
2563 		error = SET_ERROR(ESRCH);
2564 out:
2565 	if (!(flags & DNODE_FIND_HAVELOCK))
2566 		rw_exit(&dn->dn_struct_rwlock);
2567 
2568 	return (error);
2569 }
2570 
2571 #if defined(_KERNEL)
2572 EXPORT_SYMBOL(dnode_hold);
2573 EXPORT_SYMBOL(dnode_rele);
2574 EXPORT_SYMBOL(dnode_set_nlevels);
2575 EXPORT_SYMBOL(dnode_set_blksz);
2576 EXPORT_SYMBOL(dnode_free_range);
2577 EXPORT_SYMBOL(dnode_evict_dbufs);
2578 EXPORT_SYMBOL(dnode_evict_bonus);
2579 #endif
2580