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