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