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