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