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