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