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