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