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