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