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