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