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