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