xref: /illumos-gate/usr/src/uts/common/fs/zfs/dnode.c (revision 2bf405a25eb25f79638fc951ff8d8857ad384417)
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 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
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 static dnode_phys_t dnode_phys_zero;
44 
45 int zfs_default_bs = SPA_MINBLOCKSHIFT;
46 int zfs_default_ibs = DN_MAX_INDBLKSHIFT;
47 
48 /* ARGSUSED */
49 static int
50 dnode_cons(void *arg, void *unused, int kmflag)
51 {
52 	int i;
53 	dnode_t *dn = arg;
54 	bzero(dn, sizeof (dnode_t));
55 
56 	rw_init(&dn->dn_struct_rwlock, NULL, RW_DEFAULT, NULL);
57 	mutex_init(&dn->dn_mtx, NULL, MUTEX_DEFAULT, NULL);
58 	mutex_init(&dn->dn_dbufs_mtx, NULL, MUTEX_DEFAULT, NULL);
59 	cv_init(&dn->dn_notxholds, NULL, CV_DEFAULT, NULL);
60 
61 	refcount_create(&dn->dn_holds);
62 	refcount_create(&dn->dn_tx_holds);
63 
64 	for (i = 0; i < TXG_SIZE; i++) {
65 		avl_create(&dn->dn_ranges[i], free_range_compar,
66 		    sizeof (free_range_t),
67 		    offsetof(struct free_range, fr_node));
68 		list_create(&dn->dn_dirty_records[i],
69 		    sizeof (dbuf_dirty_record_t),
70 		    offsetof(dbuf_dirty_record_t, dr_dirty_node));
71 	}
72 
73 	list_create(&dn->dn_dbufs, sizeof (dmu_buf_impl_t),
74 	    offsetof(dmu_buf_impl_t, db_link));
75 
76 	return (0);
77 }
78 
79 /* ARGSUSED */
80 static void
81 dnode_dest(void *arg, void *unused)
82 {
83 	int i;
84 	dnode_t *dn = arg;
85 
86 	rw_destroy(&dn->dn_struct_rwlock);
87 	mutex_destroy(&dn->dn_mtx);
88 	mutex_destroy(&dn->dn_dbufs_mtx);
89 	cv_destroy(&dn->dn_notxholds);
90 	refcount_destroy(&dn->dn_holds);
91 	refcount_destroy(&dn->dn_tx_holds);
92 
93 	for (i = 0; i < TXG_SIZE; i++) {
94 		avl_destroy(&dn->dn_ranges[i]);
95 		list_destroy(&dn->dn_dirty_records[i]);
96 	}
97 
98 	list_destroy(&dn->dn_dbufs);
99 }
100 
101 void
102 dnode_init(void)
103 {
104 	dnode_cache = kmem_cache_create("dnode_t",
105 	    sizeof (dnode_t),
106 	    0, dnode_cons, dnode_dest, NULL, NULL, NULL, 0);
107 }
108 
109 void
110 dnode_fini(void)
111 {
112 	kmem_cache_destroy(dnode_cache);
113 }
114 
115 
116 #ifdef ZFS_DEBUG
117 void
118 dnode_verify(dnode_t *dn)
119 {
120 	int drop_struct_lock = FALSE;
121 
122 	ASSERT(dn->dn_phys);
123 	ASSERT(dn->dn_objset);
124 
125 	ASSERT(dn->dn_phys->dn_type < DMU_OT_NUMTYPES);
126 
127 	if (!(zfs_flags & ZFS_DEBUG_DNODE_VERIFY))
128 		return;
129 
130 	if (!RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
131 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
132 		drop_struct_lock = TRUE;
133 	}
134 	if (dn->dn_phys->dn_type != DMU_OT_NONE || dn->dn_allocated_txg != 0) {
135 		int i;
136 		ASSERT3U(dn->dn_indblkshift, >=, 0);
137 		ASSERT3U(dn->dn_indblkshift, <=, SPA_MAXBLOCKSHIFT);
138 		if (dn->dn_datablkshift) {
139 			ASSERT3U(dn->dn_datablkshift, >=, SPA_MINBLOCKSHIFT);
140 			ASSERT3U(dn->dn_datablkshift, <=, SPA_MAXBLOCKSHIFT);
141 			ASSERT3U(1<<dn->dn_datablkshift, ==, dn->dn_datablksz);
142 		}
143 		ASSERT3U(dn->dn_nlevels, <=, 30);
144 		ASSERT3U(dn->dn_type, <=, DMU_OT_NUMTYPES);
145 		ASSERT3U(dn->dn_nblkptr, >=, 1);
146 		ASSERT3U(dn->dn_nblkptr, <=, DN_MAX_NBLKPTR);
147 		ASSERT3U(dn->dn_bonuslen, <=, DN_MAX_BONUSLEN);
148 		ASSERT3U(dn->dn_datablksz, ==,
149 		    dn->dn_datablkszsec << SPA_MINBLOCKSHIFT);
150 		ASSERT3U(ISP2(dn->dn_datablksz), ==, dn->dn_datablkshift != 0);
151 		ASSERT3U((dn->dn_nblkptr - 1) * sizeof (blkptr_t) +
152 		    dn->dn_bonuslen, <=, DN_MAX_BONUSLEN);
153 		for (i = 0; i < TXG_SIZE; i++) {
154 			ASSERT3U(dn->dn_next_nlevels[i], <=, dn->dn_nlevels);
155 		}
156 	}
157 	if (dn->dn_phys->dn_type != DMU_OT_NONE)
158 		ASSERT3U(dn->dn_phys->dn_nlevels, <=, dn->dn_nlevels);
159 	ASSERT(dn->dn_object == DMU_META_DNODE_OBJECT || dn->dn_dbuf != NULL);
160 	if (dn->dn_dbuf != NULL) {
161 		ASSERT3P(dn->dn_phys, ==,
162 		    (dnode_phys_t *)dn->dn_dbuf->db.db_data +
163 		    (dn->dn_object % (dn->dn_dbuf->db.db_size >> DNODE_SHIFT)));
164 	}
165 	if (drop_struct_lock)
166 		rw_exit(&dn->dn_struct_rwlock);
167 }
168 #endif
169 
170 void
171 dnode_byteswap(dnode_phys_t *dnp)
172 {
173 	uint64_t *buf64 = (void*)&dnp->dn_blkptr;
174 	int i;
175 
176 	if (dnp->dn_type == DMU_OT_NONE) {
177 		bzero(dnp, sizeof (dnode_phys_t));
178 		return;
179 	}
180 
181 	dnp->dn_datablkszsec = BSWAP_16(dnp->dn_datablkszsec);
182 	dnp->dn_bonuslen = BSWAP_16(dnp->dn_bonuslen);
183 	dnp->dn_maxblkid = BSWAP_64(dnp->dn_maxblkid);
184 	dnp->dn_used = BSWAP_64(dnp->dn_used);
185 
186 	/*
187 	 * dn_nblkptr is only one byte, so it's OK to read it in either
188 	 * byte order.  We can't read dn_bouslen.
189 	 */
190 	ASSERT(dnp->dn_indblkshift <= SPA_MAXBLOCKSHIFT);
191 	ASSERT(dnp->dn_nblkptr <= DN_MAX_NBLKPTR);
192 	for (i = 0; i < dnp->dn_nblkptr * sizeof (blkptr_t)/8; i++)
193 		buf64[i] = BSWAP_64(buf64[i]);
194 
195 	/*
196 	 * OK to check dn_bonuslen for zero, because it won't matter if
197 	 * we have the wrong byte order.  This is necessary because the
198 	 * dnode dnode is smaller than a regular dnode.
199 	 */
200 	if (dnp->dn_bonuslen != 0) {
201 		/*
202 		 * Note that the bonus length calculated here may be
203 		 * longer than the actual bonus buffer.  This is because
204 		 * we always put the bonus buffer after the last block
205 		 * pointer (instead of packing it against the end of the
206 		 * dnode buffer).
207 		 */
208 		int off = (dnp->dn_nblkptr-1) * sizeof (blkptr_t);
209 		size_t len = DN_MAX_BONUSLEN - off;
210 		ASSERT3U(dnp->dn_bonustype, <, DMU_OT_NUMTYPES);
211 		dmu_ot[dnp->dn_bonustype].ot_byteswap(dnp->dn_bonus + off, len);
212 	}
213 }
214 
215 void
216 dnode_buf_byteswap(void *vbuf, size_t size)
217 {
218 	dnode_phys_t *buf = vbuf;
219 	int i;
220 
221 	ASSERT3U(sizeof (dnode_phys_t), ==, (1<<DNODE_SHIFT));
222 	ASSERT((size & (sizeof (dnode_phys_t)-1)) == 0);
223 
224 	size >>= DNODE_SHIFT;
225 	for (i = 0; i < size; i++) {
226 		dnode_byteswap(buf);
227 		buf++;
228 	}
229 }
230 
231 static int
232 free_range_compar(const void *node1, const void *node2)
233 {
234 	const free_range_t *rp1 = node1;
235 	const free_range_t *rp2 = node2;
236 
237 	if (rp1->fr_blkid < rp2->fr_blkid)
238 		return (-1);
239 	else if (rp1->fr_blkid > rp2->fr_blkid)
240 		return (1);
241 	else return (0);
242 }
243 
244 void
245 dnode_setbonuslen(dnode_t *dn, int newsize, dmu_tx_t *tx)
246 {
247 	ASSERT3U(refcount_count(&dn->dn_holds), >=, 1);
248 
249 	dnode_setdirty(dn, tx);
250 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
251 	ASSERT3U(newsize, <=, DN_MAX_BONUSLEN -
252 	    (dn->dn_nblkptr-1) * sizeof (blkptr_t));
253 	dn->dn_bonuslen = newsize;
254 	if (newsize == 0)
255 		dn->dn_next_bonuslen[tx->tx_txg & TXG_MASK] = DN_ZERO_BONUSLEN;
256 	else
257 		dn->dn_next_bonuslen[tx->tx_txg & TXG_MASK] = dn->dn_bonuslen;
258 	rw_exit(&dn->dn_struct_rwlock);
259 }
260 
261 static void
262 dnode_setdblksz(dnode_t *dn, int size)
263 {
264 	ASSERT3U(P2PHASE(size, SPA_MINBLOCKSIZE), ==, 0);
265 	ASSERT3U(size, <=, SPA_MAXBLOCKSIZE);
266 	ASSERT3U(size, >=, SPA_MINBLOCKSIZE);
267 	ASSERT3U(size >> SPA_MINBLOCKSHIFT, <,
268 	    1<<(sizeof (dn->dn_phys->dn_datablkszsec) * 8));
269 	dn->dn_datablksz = size;
270 	dn->dn_datablkszsec = size >> SPA_MINBLOCKSHIFT;
271 	dn->dn_datablkshift = ISP2(size) ? highbit(size - 1) : 0;
272 }
273 
274 static dnode_t *
275 dnode_create(objset_impl_t *os, dnode_phys_t *dnp, dmu_buf_impl_t *db,
276     uint64_t object)
277 {
278 	dnode_t *dn = kmem_cache_alloc(dnode_cache, KM_SLEEP);
279 	(void) dnode_cons(dn, NULL, 0); /* XXX */
280 
281 	dn->dn_objset = os;
282 	dn->dn_object = object;
283 	dn->dn_dbuf = db;
284 	dn->dn_phys = dnp;
285 
286 	if (dnp->dn_datablkszsec)
287 		dnode_setdblksz(dn, dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT);
288 	dn->dn_indblkshift = dnp->dn_indblkshift;
289 	dn->dn_nlevels = dnp->dn_nlevels;
290 	dn->dn_type = dnp->dn_type;
291 	dn->dn_nblkptr = dnp->dn_nblkptr;
292 	dn->dn_checksum = dnp->dn_checksum;
293 	dn->dn_compress = dnp->dn_compress;
294 	dn->dn_bonustype = dnp->dn_bonustype;
295 	dn->dn_bonuslen = dnp->dn_bonuslen;
296 	dn->dn_maxblkid = dnp->dn_maxblkid;
297 
298 	dmu_zfetch_init(&dn->dn_zfetch, dn);
299 
300 	ASSERT(dn->dn_phys->dn_type < DMU_OT_NUMTYPES);
301 	mutex_enter(&os->os_lock);
302 	list_insert_head(&os->os_dnodes, dn);
303 	mutex_exit(&os->os_lock);
304 
305 	arc_space_consume(sizeof (dnode_t), ARC_SPACE_OTHER);
306 	return (dn);
307 }
308 
309 static void
310 dnode_destroy(dnode_t *dn)
311 {
312 	objset_impl_t *os = dn->dn_objset;
313 
314 #ifdef ZFS_DEBUG
315 	int i;
316 
317 	for (i = 0; i < TXG_SIZE; i++) {
318 		ASSERT(!list_link_active(&dn->dn_dirty_link[i]));
319 		ASSERT(NULL == list_head(&dn->dn_dirty_records[i]));
320 		ASSERT(0 == avl_numnodes(&dn->dn_ranges[i]));
321 	}
322 	ASSERT(NULL == list_head(&dn->dn_dbufs));
323 #endif
324 
325 	mutex_enter(&os->os_lock);
326 	list_remove(&os->os_dnodes, dn);
327 	mutex_exit(&os->os_lock);
328 
329 	if (dn->dn_dirtyctx_firstset) {
330 		kmem_free(dn->dn_dirtyctx_firstset, 1);
331 		dn->dn_dirtyctx_firstset = NULL;
332 	}
333 	dmu_zfetch_rele(&dn->dn_zfetch);
334 	if (dn->dn_bonus) {
335 		mutex_enter(&dn->dn_bonus->db_mtx);
336 		dbuf_evict(dn->dn_bonus);
337 		dn->dn_bonus = NULL;
338 	}
339 	kmem_cache_free(dnode_cache, dn);
340 	arc_space_return(sizeof (dnode_t), ARC_SPACE_OTHER);
341 }
342 
343 void
344 dnode_allocate(dnode_t *dn, dmu_object_type_t ot, int blocksize, int ibs,
345     dmu_object_type_t bonustype, int bonuslen, dmu_tx_t *tx)
346 {
347 	int i;
348 
349 	if (blocksize == 0)
350 		blocksize = 1 << zfs_default_bs;
351 	else if (blocksize > SPA_MAXBLOCKSIZE)
352 		blocksize = SPA_MAXBLOCKSIZE;
353 	else
354 		blocksize = P2ROUNDUP(blocksize, SPA_MINBLOCKSIZE);
355 
356 	if (ibs == 0)
357 		ibs = zfs_default_ibs;
358 
359 	ibs = MIN(MAX(ibs, DN_MIN_INDBLKSHIFT), DN_MAX_INDBLKSHIFT);
360 
361 	dprintf("os=%p obj=%llu txg=%llu blocksize=%d ibs=%d\n", dn->dn_objset,
362 	    dn->dn_object, tx->tx_txg, blocksize, ibs);
363 
364 	ASSERT(dn->dn_type == DMU_OT_NONE);
365 	ASSERT(bcmp(dn->dn_phys, &dnode_phys_zero, sizeof (dnode_phys_t)) == 0);
366 	ASSERT(dn->dn_phys->dn_type == DMU_OT_NONE);
367 	ASSERT(ot != DMU_OT_NONE);
368 	ASSERT3U(ot, <, DMU_OT_NUMTYPES);
369 	ASSERT((bonustype == DMU_OT_NONE && bonuslen == 0) ||
370 	    (bonustype != DMU_OT_NONE && bonuslen != 0));
371 	ASSERT3U(bonustype, <, DMU_OT_NUMTYPES);
372 	ASSERT3U(bonuslen, <=, DN_MAX_BONUSLEN);
373 	ASSERT(dn->dn_type == DMU_OT_NONE);
374 	ASSERT3U(dn->dn_maxblkid, ==, 0);
375 	ASSERT3U(dn->dn_allocated_txg, ==, 0);
376 	ASSERT3U(dn->dn_assigned_txg, ==, 0);
377 	ASSERT(refcount_is_zero(&dn->dn_tx_holds));
378 	ASSERT3U(refcount_count(&dn->dn_holds), <=, 1);
379 	ASSERT3P(list_head(&dn->dn_dbufs), ==, NULL);
380 
381 	for (i = 0; i < TXG_SIZE; i++) {
382 		ASSERT3U(dn->dn_next_nlevels[i], ==, 0);
383 		ASSERT3U(dn->dn_next_indblkshift[i], ==, 0);
384 		ASSERT3U(dn->dn_next_bonuslen[i], ==, 0);
385 		ASSERT3U(dn->dn_next_blksz[i], ==, 0);
386 		ASSERT(!list_link_active(&dn->dn_dirty_link[i]));
387 		ASSERT3P(list_head(&dn->dn_dirty_records[i]), ==, NULL);
388 		ASSERT3U(avl_numnodes(&dn->dn_ranges[i]), ==, 0);
389 	}
390 
391 	dn->dn_type = ot;
392 	dnode_setdblksz(dn, blocksize);
393 	dn->dn_indblkshift = ibs;
394 	dn->dn_nlevels = 1;
395 	dn->dn_nblkptr = 1 + ((DN_MAX_BONUSLEN - bonuslen) >> SPA_BLKPTRSHIFT);
396 	dn->dn_bonustype = bonustype;
397 	dn->dn_bonuslen = bonuslen;
398 	dn->dn_checksum = ZIO_CHECKSUM_INHERIT;
399 	dn->dn_compress = ZIO_COMPRESS_INHERIT;
400 	dn->dn_dirtyctx = 0;
401 
402 	dn->dn_free_txg = 0;
403 	if (dn->dn_dirtyctx_firstset) {
404 		kmem_free(dn->dn_dirtyctx_firstset, 1);
405 		dn->dn_dirtyctx_firstset = NULL;
406 	}
407 
408 	dn->dn_allocated_txg = tx->tx_txg;
409 
410 	dnode_setdirty(dn, tx);
411 	dn->dn_next_indblkshift[tx->tx_txg & TXG_MASK] = ibs;
412 	dn->dn_next_bonuslen[tx->tx_txg & TXG_MASK] = dn->dn_bonuslen;
413 	dn->dn_next_blksz[tx->tx_txg & TXG_MASK] = dn->dn_datablksz;
414 }
415 
416 void
417 dnode_reallocate(dnode_t *dn, dmu_object_type_t ot, int blocksize,
418     dmu_object_type_t bonustype, int bonuslen, dmu_tx_t *tx)
419 {
420 	int nblkptr;
421 
422 	ASSERT3U(blocksize, >=, SPA_MINBLOCKSIZE);
423 	ASSERT3U(blocksize, <=, SPA_MAXBLOCKSIZE);
424 	ASSERT3U(blocksize % SPA_MINBLOCKSIZE, ==, 0);
425 	ASSERT(dn->dn_object != DMU_META_DNODE_OBJECT || dmu_tx_private_ok(tx));
426 	ASSERT(tx->tx_txg != 0);
427 	ASSERT((bonustype == DMU_OT_NONE && bonuslen == 0) ||
428 	    (bonustype != DMU_OT_NONE && bonuslen != 0));
429 	ASSERT3U(bonustype, <, DMU_OT_NUMTYPES);
430 	ASSERT3U(bonuslen, <=, DN_MAX_BONUSLEN);
431 
432 	/* clean up any unreferenced dbufs */
433 	dnode_evict_dbufs(dn);
434 
435 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
436 	dnode_setdirty(dn, tx);
437 	if (dn->dn_datablksz != blocksize) {
438 		/* change blocksize */
439 		ASSERT(dn->dn_maxblkid == 0 &&
440 		    (BP_IS_HOLE(&dn->dn_phys->dn_blkptr[0]) ||
441 		    dnode_block_freed(dn, 0)));
442 		dnode_setdblksz(dn, blocksize);
443 		dn->dn_next_blksz[tx->tx_txg&TXG_MASK] = blocksize;
444 	}
445 	if (dn->dn_bonuslen != bonuslen)
446 		dn->dn_next_bonuslen[tx->tx_txg&TXG_MASK] = bonuslen;
447 	nblkptr = 1 + ((DN_MAX_BONUSLEN - bonuslen) >> SPA_BLKPTRSHIFT);
448 	if (dn->dn_nblkptr != nblkptr)
449 		dn->dn_next_nblkptr[tx->tx_txg&TXG_MASK] = nblkptr;
450 	rw_exit(&dn->dn_struct_rwlock);
451 
452 	/* change type */
453 	dn->dn_type = ot;
454 
455 	/* change bonus size and type */
456 	mutex_enter(&dn->dn_mtx);
457 	dn->dn_bonustype = bonustype;
458 	dn->dn_bonuslen = bonuslen;
459 	dn->dn_nblkptr = nblkptr;
460 	dn->dn_checksum = ZIO_CHECKSUM_INHERIT;
461 	dn->dn_compress = ZIO_COMPRESS_INHERIT;
462 	ASSERT3U(dn->dn_nblkptr, <=, DN_MAX_NBLKPTR);
463 
464 	/* fix up the bonus db_size */
465 	if (dn->dn_bonus) {
466 		dn->dn_bonus->db.db_size =
467 		    DN_MAX_BONUSLEN - (dn->dn_nblkptr-1) * sizeof (blkptr_t);
468 		ASSERT(dn->dn_bonuslen <= dn->dn_bonus->db.db_size);
469 	}
470 
471 	dn->dn_allocated_txg = tx->tx_txg;
472 	mutex_exit(&dn->dn_mtx);
473 }
474 
475 void
476 dnode_special_close(dnode_t *dn)
477 {
478 	/*
479 	 * Wait for final references to the dnode to clear.  This can
480 	 * only happen if the arc is asyncronously evicting state that
481 	 * has a hold on this dnode while we are trying to evict this
482 	 * dnode.
483 	 */
484 	while (refcount_count(&dn->dn_holds) > 0)
485 		delay(1);
486 	dnode_destroy(dn);
487 }
488 
489 dnode_t *
490 dnode_special_open(objset_impl_t *os, dnode_phys_t *dnp, uint64_t object)
491 {
492 	dnode_t *dn = dnode_create(os, dnp, NULL, object);
493 	DNODE_VERIFY(dn);
494 	return (dn);
495 }
496 
497 static void
498 dnode_buf_pageout(dmu_buf_t *db, void *arg)
499 {
500 	dnode_t **children_dnodes = arg;
501 	int i;
502 	int epb = db->db_size >> DNODE_SHIFT;
503 
504 	for (i = 0; i < epb; i++) {
505 		dnode_t *dn = children_dnodes[i];
506 		int n;
507 
508 		if (dn == NULL)
509 			continue;
510 #ifdef ZFS_DEBUG
511 		/*
512 		 * If there are holds on this dnode, then there should
513 		 * be holds on the dnode's containing dbuf as well; thus
514 		 * it wouldn't be eligable for eviction and this function
515 		 * would not have been called.
516 		 */
517 		ASSERT(refcount_is_zero(&dn->dn_holds));
518 		ASSERT(list_head(&dn->dn_dbufs) == NULL);
519 		ASSERT(refcount_is_zero(&dn->dn_tx_holds));
520 
521 		for (n = 0; n < TXG_SIZE; n++)
522 			ASSERT(!list_link_active(&dn->dn_dirty_link[n]));
523 #endif
524 		children_dnodes[i] = NULL;
525 		dnode_destroy(dn);
526 	}
527 	kmem_free(children_dnodes, epb * sizeof (dnode_t *));
528 }
529 
530 /*
531  * errors:
532  * EINVAL - invalid object number.
533  * EIO - i/o error.
534  * succeeds even for free dnodes.
535  */
536 int
537 dnode_hold_impl(objset_impl_t *os, uint64_t object, int flag,
538     void *tag, dnode_t **dnp)
539 {
540 	int epb, idx, err;
541 	int drop_struct_lock = FALSE;
542 	int type;
543 	uint64_t blk;
544 	dnode_t *mdn, *dn;
545 	dmu_buf_impl_t *db;
546 	dnode_t **children_dnodes;
547 
548 	/*
549 	 * If you are holding the spa config lock as writer, you shouldn't
550 	 * be asking the DMU to do *anything*.
551 	 */
552 	ASSERT(spa_config_held(os->os_spa, SCL_ALL, RW_WRITER) == 0);
553 
554 	if (object == 0 || object >= DN_MAX_OBJECT)
555 		return (EINVAL);
556 
557 	mdn = os->os_meta_dnode;
558 
559 	DNODE_VERIFY(mdn);
560 
561 	if (!RW_WRITE_HELD(&mdn->dn_struct_rwlock)) {
562 		rw_enter(&mdn->dn_struct_rwlock, RW_READER);
563 		drop_struct_lock = TRUE;
564 	}
565 
566 	blk = dbuf_whichblock(mdn, object * sizeof (dnode_phys_t));
567 
568 	db = dbuf_hold(mdn, blk, FTAG);
569 	if (drop_struct_lock)
570 		rw_exit(&mdn->dn_struct_rwlock);
571 	if (db == NULL)
572 		return (EIO);
573 	err = dbuf_read(db, NULL, DB_RF_CANFAIL);
574 	if (err) {
575 		dbuf_rele(db, FTAG);
576 		return (err);
577 	}
578 
579 	ASSERT3U(db->db.db_size, >=, 1<<DNODE_SHIFT);
580 	epb = db->db.db_size >> DNODE_SHIFT;
581 
582 	idx = object & (epb-1);
583 
584 	children_dnodes = dmu_buf_get_user(&db->db);
585 	if (children_dnodes == NULL) {
586 		dnode_t **winner;
587 		children_dnodes = kmem_zalloc(epb * sizeof (dnode_t *),
588 		    KM_SLEEP);
589 		if (winner = dmu_buf_set_user(&db->db, children_dnodes, NULL,
590 		    dnode_buf_pageout)) {
591 			kmem_free(children_dnodes, epb * sizeof (dnode_t *));
592 			children_dnodes = winner;
593 		}
594 	}
595 
596 	if ((dn = children_dnodes[idx]) == NULL) {
597 		dnode_phys_t *dnp = (dnode_phys_t *)db->db.db_data+idx;
598 		dnode_t *winner;
599 
600 		dn = dnode_create(os, dnp, db, object);
601 		winner = atomic_cas_ptr(&children_dnodes[idx], NULL, dn);
602 		if (winner != NULL) {
603 			dnode_destroy(dn);
604 			dn = winner;
605 		}
606 	}
607 
608 	mutex_enter(&dn->dn_mtx);
609 	type = dn->dn_type;
610 	if (dn->dn_free_txg ||
611 	    ((flag & DNODE_MUST_BE_ALLOCATED) && type == DMU_OT_NONE) ||
612 	    ((flag & DNODE_MUST_BE_FREE) && type != DMU_OT_NONE)) {
613 		mutex_exit(&dn->dn_mtx);
614 		dbuf_rele(db, FTAG);
615 		return (type == DMU_OT_NONE ? ENOENT : EEXIST);
616 	}
617 	mutex_exit(&dn->dn_mtx);
618 
619 	if (refcount_add(&dn->dn_holds, tag) == 1)
620 		dbuf_add_ref(db, dn);
621 
622 	DNODE_VERIFY(dn);
623 	ASSERT3P(dn->dn_dbuf, ==, db);
624 	ASSERT3U(dn->dn_object, ==, object);
625 	dbuf_rele(db, FTAG);
626 
627 	*dnp = dn;
628 	return (0);
629 }
630 
631 /*
632  * Return held dnode if the object is allocated, NULL if not.
633  */
634 int
635 dnode_hold(objset_impl_t *os, uint64_t object, void *tag, dnode_t **dnp)
636 {
637 	return (dnode_hold_impl(os, object, DNODE_MUST_BE_ALLOCATED, tag, dnp));
638 }
639 
640 /*
641  * Can only add a reference if there is already at least one
642  * reference on the dnode.  Returns FALSE if unable to add a
643  * new reference.
644  */
645 boolean_t
646 dnode_add_ref(dnode_t *dn, void *tag)
647 {
648 	mutex_enter(&dn->dn_mtx);
649 	if (refcount_is_zero(&dn->dn_holds)) {
650 		mutex_exit(&dn->dn_mtx);
651 		return (FALSE);
652 	}
653 	VERIFY(1 < refcount_add(&dn->dn_holds, tag));
654 	mutex_exit(&dn->dn_mtx);
655 	return (TRUE);
656 }
657 
658 void
659 dnode_rele(dnode_t *dn, void *tag)
660 {
661 	uint64_t refs;
662 
663 	mutex_enter(&dn->dn_mtx);
664 	refs = refcount_remove(&dn->dn_holds, tag);
665 	mutex_exit(&dn->dn_mtx);
666 	/* NOTE: the DNODE_DNODE does not have a dn_dbuf */
667 	if (refs == 0 && dn->dn_dbuf)
668 		dbuf_rele(dn->dn_dbuf, dn);
669 }
670 
671 void
672 dnode_setdirty(dnode_t *dn, dmu_tx_t *tx)
673 {
674 	objset_impl_t *os = dn->dn_objset;
675 	uint64_t txg = tx->tx_txg;
676 
677 	if (dn->dn_object == DMU_META_DNODE_OBJECT)
678 		return;
679 
680 	DNODE_VERIFY(dn);
681 
682 #ifdef ZFS_DEBUG
683 	mutex_enter(&dn->dn_mtx);
684 	ASSERT(dn->dn_phys->dn_type || dn->dn_allocated_txg);
685 	/* ASSERT(dn->dn_free_txg == 0 || dn->dn_free_txg >= txg); */
686 	mutex_exit(&dn->dn_mtx);
687 #endif
688 
689 	mutex_enter(&os->os_lock);
690 
691 	/*
692 	 * If we are already marked dirty, we're done.
693 	 */
694 	if (list_link_active(&dn->dn_dirty_link[txg & TXG_MASK])) {
695 		mutex_exit(&os->os_lock);
696 		return;
697 	}
698 
699 	ASSERT(!refcount_is_zero(&dn->dn_holds) || list_head(&dn->dn_dbufs));
700 	ASSERT(dn->dn_datablksz != 0);
701 	ASSERT3U(dn->dn_next_bonuslen[txg&TXG_MASK], ==, 0);
702 	ASSERT3U(dn->dn_next_blksz[txg&TXG_MASK], ==, 0);
703 
704 	dprintf_ds(os->os_dsl_dataset, "obj=%llu txg=%llu\n",
705 	    dn->dn_object, txg);
706 
707 	if (dn->dn_free_txg > 0 && dn->dn_free_txg <= txg) {
708 		list_insert_tail(&os->os_free_dnodes[txg&TXG_MASK], dn);
709 	} else {
710 		list_insert_tail(&os->os_dirty_dnodes[txg&TXG_MASK], dn);
711 	}
712 
713 	mutex_exit(&os->os_lock);
714 
715 	/*
716 	 * The dnode maintains a hold on its containing dbuf as
717 	 * long as there are holds on it.  Each instantiated child
718 	 * dbuf maintaines a hold on the dnode.  When the last child
719 	 * drops its hold, the dnode will drop its hold on the
720 	 * containing dbuf. We add a "dirty hold" here so that the
721 	 * dnode will hang around after we finish processing its
722 	 * children.
723 	 */
724 	VERIFY(dnode_add_ref(dn, (void *)(uintptr_t)tx->tx_txg));
725 
726 	(void) dbuf_dirty(dn->dn_dbuf, tx);
727 
728 	dsl_dataset_dirty(os->os_dsl_dataset, tx);
729 }
730 
731 void
732 dnode_free(dnode_t *dn, dmu_tx_t *tx)
733 {
734 	int txgoff = tx->tx_txg & TXG_MASK;
735 
736 	dprintf("dn=%p txg=%llu\n", dn, tx->tx_txg);
737 
738 	/* we should be the only holder... hopefully */
739 	/* ASSERT3U(refcount_count(&dn->dn_holds), ==, 1); */
740 
741 	mutex_enter(&dn->dn_mtx);
742 	if (dn->dn_type == DMU_OT_NONE || dn->dn_free_txg) {
743 		mutex_exit(&dn->dn_mtx);
744 		return;
745 	}
746 	dn->dn_free_txg = tx->tx_txg;
747 	mutex_exit(&dn->dn_mtx);
748 
749 	/*
750 	 * If the dnode is already dirty, it needs to be moved from
751 	 * the dirty list to the free list.
752 	 */
753 	mutex_enter(&dn->dn_objset->os_lock);
754 	if (list_link_active(&dn->dn_dirty_link[txgoff])) {
755 		list_remove(&dn->dn_objset->os_dirty_dnodes[txgoff], dn);
756 		list_insert_tail(&dn->dn_objset->os_free_dnodes[txgoff], dn);
757 		mutex_exit(&dn->dn_objset->os_lock);
758 	} else {
759 		mutex_exit(&dn->dn_objset->os_lock);
760 		dnode_setdirty(dn, tx);
761 	}
762 }
763 
764 /*
765  * Try to change the block size for the indicated dnode.  This can only
766  * succeed if there are no blocks allocated or dirty beyond first block
767  */
768 int
769 dnode_set_blksz(dnode_t *dn, uint64_t size, int ibs, dmu_tx_t *tx)
770 {
771 	dmu_buf_impl_t *db, *db_next;
772 	int err;
773 
774 	if (size == 0)
775 		size = SPA_MINBLOCKSIZE;
776 	if (size > SPA_MAXBLOCKSIZE)
777 		size = SPA_MAXBLOCKSIZE;
778 	else
779 		size = P2ROUNDUP(size, SPA_MINBLOCKSIZE);
780 
781 	if (ibs == dn->dn_indblkshift)
782 		ibs = 0;
783 
784 	if (size >> SPA_MINBLOCKSHIFT == dn->dn_datablkszsec && ibs == 0)
785 		return (0);
786 
787 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
788 
789 	/* Check for any allocated blocks beyond the first */
790 	if (dn->dn_phys->dn_maxblkid != 0)
791 		goto fail;
792 
793 	mutex_enter(&dn->dn_dbufs_mtx);
794 	for (db = list_head(&dn->dn_dbufs); db; db = db_next) {
795 		db_next = list_next(&dn->dn_dbufs, db);
796 
797 		if (db->db_blkid != 0 && db->db_blkid != DB_BONUS_BLKID) {
798 			mutex_exit(&dn->dn_dbufs_mtx);
799 			goto fail;
800 		}
801 	}
802 	mutex_exit(&dn->dn_dbufs_mtx);
803 
804 	if (ibs && dn->dn_nlevels != 1)
805 		goto fail;
806 
807 	/* resize the old block */
808 	err = dbuf_hold_impl(dn, 0, 0, TRUE, FTAG, &db);
809 	if (err == 0)
810 		dbuf_new_size(db, size, tx);
811 	else if (err != ENOENT)
812 		goto fail;
813 
814 	dnode_setdblksz(dn, size);
815 	dnode_setdirty(dn, tx);
816 	dn->dn_next_blksz[tx->tx_txg&TXG_MASK] = size;
817 	if (ibs) {
818 		dn->dn_indblkshift = ibs;
819 		dn->dn_next_indblkshift[tx->tx_txg&TXG_MASK] = ibs;
820 	}
821 	/* rele after we have fixed the blocksize in the dnode */
822 	if (db)
823 		dbuf_rele(db, FTAG);
824 
825 	rw_exit(&dn->dn_struct_rwlock);
826 	return (0);
827 
828 fail:
829 	rw_exit(&dn->dn_struct_rwlock);
830 	return (ENOTSUP);
831 }
832 
833 /* read-holding callers must not rely on the lock being continuously held */
834 void
835 dnode_new_blkid(dnode_t *dn, uint64_t blkid, dmu_tx_t *tx, boolean_t have_read)
836 {
837 	uint64_t txgoff = tx->tx_txg & TXG_MASK;
838 	int epbs, new_nlevels;
839 	uint64_t sz;
840 
841 	ASSERT(blkid != DB_BONUS_BLKID);
842 
843 	ASSERT(have_read ?
844 	    RW_READ_HELD(&dn->dn_struct_rwlock) :
845 	    RW_WRITE_HELD(&dn->dn_struct_rwlock));
846 
847 	/*
848 	 * if we have a read-lock, check to see if we need to do any work
849 	 * before upgrading to a write-lock.
850 	 */
851 	if (have_read) {
852 		if (blkid <= dn->dn_maxblkid)
853 			return;
854 
855 		if (!rw_tryupgrade(&dn->dn_struct_rwlock)) {
856 			rw_exit(&dn->dn_struct_rwlock);
857 			rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
858 		}
859 	}
860 
861 	if (blkid <= dn->dn_maxblkid)
862 		goto out;
863 
864 	dn->dn_maxblkid = blkid;
865 
866 	/*
867 	 * Compute the number of levels necessary to support the new maxblkid.
868 	 */
869 	new_nlevels = 1;
870 	epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
871 	for (sz = dn->dn_nblkptr;
872 	    sz <= blkid && sz >= dn->dn_nblkptr; sz <<= epbs)
873 		new_nlevels++;
874 
875 	if (new_nlevels > dn->dn_nlevels) {
876 		int old_nlevels = dn->dn_nlevels;
877 		dmu_buf_impl_t *db;
878 		list_t *list;
879 		dbuf_dirty_record_t *new, *dr, *dr_next;
880 
881 		dn->dn_nlevels = new_nlevels;
882 
883 		ASSERT3U(new_nlevels, >, dn->dn_next_nlevels[txgoff]);
884 		dn->dn_next_nlevels[txgoff] = new_nlevels;
885 
886 		/* dirty the left indirects */
887 		db = dbuf_hold_level(dn, old_nlevels, 0, FTAG);
888 		new = dbuf_dirty(db, tx);
889 		dbuf_rele(db, FTAG);
890 
891 		/* transfer the dirty records to the new indirect */
892 		mutex_enter(&dn->dn_mtx);
893 		mutex_enter(&new->dt.di.dr_mtx);
894 		list = &dn->dn_dirty_records[txgoff];
895 		for (dr = list_head(list); dr; dr = dr_next) {
896 			dr_next = list_next(&dn->dn_dirty_records[txgoff], dr);
897 			if (dr->dr_dbuf->db_level != new_nlevels-1 &&
898 			    dr->dr_dbuf->db_blkid != DB_BONUS_BLKID) {
899 				ASSERT(dr->dr_dbuf->db_level == old_nlevels-1);
900 				list_remove(&dn->dn_dirty_records[txgoff], dr);
901 				list_insert_tail(&new->dt.di.dr_children, dr);
902 				dr->dr_parent = new;
903 			}
904 		}
905 		mutex_exit(&new->dt.di.dr_mtx);
906 		mutex_exit(&dn->dn_mtx);
907 	}
908 
909 out:
910 	if (have_read)
911 		rw_downgrade(&dn->dn_struct_rwlock);
912 }
913 
914 void
915 dnode_clear_range(dnode_t *dn, uint64_t blkid, uint64_t nblks, dmu_tx_t *tx)
916 {
917 	avl_tree_t *tree = &dn->dn_ranges[tx->tx_txg&TXG_MASK];
918 	avl_index_t where;
919 	free_range_t *rp;
920 	free_range_t rp_tofind;
921 	uint64_t endblk = blkid + nblks;
922 
923 	ASSERT(MUTEX_HELD(&dn->dn_mtx));
924 	ASSERT(nblks <= UINT64_MAX - blkid); /* no overflow */
925 
926 	dprintf_dnode(dn, "blkid=%llu nblks=%llu txg=%llu\n",
927 	    blkid, nblks, tx->tx_txg);
928 	rp_tofind.fr_blkid = blkid;
929 	rp = avl_find(tree, &rp_tofind, &where);
930 	if (rp == NULL)
931 		rp = avl_nearest(tree, where, AVL_BEFORE);
932 	if (rp == NULL)
933 		rp = avl_nearest(tree, where, AVL_AFTER);
934 
935 	while (rp && (rp->fr_blkid <= blkid + nblks)) {
936 		uint64_t fr_endblk = rp->fr_blkid + rp->fr_nblks;
937 		free_range_t *nrp = AVL_NEXT(tree, rp);
938 
939 		if (blkid <= rp->fr_blkid && endblk >= fr_endblk) {
940 			/* clear this entire range */
941 			avl_remove(tree, rp);
942 			kmem_free(rp, sizeof (free_range_t));
943 		} else if (blkid <= rp->fr_blkid &&
944 		    endblk > rp->fr_blkid && endblk < fr_endblk) {
945 			/* clear the beginning of this range */
946 			rp->fr_blkid = endblk;
947 			rp->fr_nblks = fr_endblk - endblk;
948 		} else if (blkid > rp->fr_blkid && blkid < fr_endblk &&
949 		    endblk >= fr_endblk) {
950 			/* clear the end of this range */
951 			rp->fr_nblks = blkid - rp->fr_blkid;
952 		} else if (blkid > rp->fr_blkid && endblk < fr_endblk) {
953 			/* clear a chunk out of this range */
954 			free_range_t *new_rp =
955 			    kmem_alloc(sizeof (free_range_t), KM_SLEEP);
956 
957 			new_rp->fr_blkid = endblk;
958 			new_rp->fr_nblks = fr_endblk - endblk;
959 			avl_insert_here(tree, new_rp, rp, AVL_AFTER);
960 			rp->fr_nblks = blkid - rp->fr_blkid;
961 		}
962 		/* there may be no overlap */
963 		rp = nrp;
964 	}
965 }
966 
967 void
968 dnode_free_range(dnode_t *dn, uint64_t off, uint64_t len, dmu_tx_t *tx)
969 {
970 	dmu_buf_impl_t *db;
971 	uint64_t blkoff, blkid, nblks;
972 	int blksz, blkshift, head, tail;
973 	int trunc = FALSE;
974 	int epbs;
975 
976 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
977 	blksz = dn->dn_datablksz;
978 	blkshift = dn->dn_datablkshift;
979 	epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
980 
981 	if (len == -1ULL) {
982 		len = UINT64_MAX - off;
983 		trunc = TRUE;
984 	}
985 
986 	/*
987 	 * First, block align the region to free:
988 	 */
989 	if (ISP2(blksz)) {
990 		head = P2NPHASE(off, blksz);
991 		blkoff = P2PHASE(off, blksz);
992 		if ((off >> blkshift) > dn->dn_maxblkid)
993 			goto out;
994 	} else {
995 		ASSERT(dn->dn_maxblkid == 0);
996 		if (off == 0 && len >= blksz) {
997 			/* Freeing the whole block; fast-track this request */
998 			blkid = 0;
999 			nblks = 1;
1000 			goto done;
1001 		} else if (off >= blksz) {
1002 			/* Freeing past end-of-data */
1003 			goto out;
1004 		} else {
1005 			/* Freeing part of the block. */
1006 			head = blksz - off;
1007 			ASSERT3U(head, >, 0);
1008 		}
1009 		blkoff = off;
1010 	}
1011 	/* zero out any partial block data at the start of the range */
1012 	if (head) {
1013 		ASSERT3U(blkoff + head, ==, blksz);
1014 		if (len < head)
1015 			head = len;
1016 		if (dbuf_hold_impl(dn, 0, dbuf_whichblock(dn, off), TRUE,
1017 		    FTAG, &db) == 0) {
1018 			caddr_t data;
1019 
1020 			/* don't dirty if it isn't on disk and isn't dirty */
1021 			if (db->db_last_dirty ||
1022 			    (db->db_blkptr && !BP_IS_HOLE(db->db_blkptr))) {
1023 				rw_exit(&dn->dn_struct_rwlock);
1024 				dbuf_will_dirty(db, tx);
1025 				rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
1026 				data = db->db.db_data;
1027 				bzero(data + blkoff, head);
1028 			}
1029 			dbuf_rele(db, FTAG);
1030 		}
1031 		off += head;
1032 		len -= head;
1033 	}
1034 
1035 	/* If the range was less than one block, we're done */
1036 	if (len == 0)
1037 		goto out;
1038 
1039 	/* If the remaining range is past end of file, we're done */
1040 	if ((off >> blkshift) > dn->dn_maxblkid)
1041 		goto out;
1042 
1043 	ASSERT(ISP2(blksz));
1044 	if (trunc)
1045 		tail = 0;
1046 	else
1047 		tail = P2PHASE(len, blksz);
1048 
1049 	ASSERT3U(P2PHASE(off, blksz), ==, 0);
1050 	/* zero out any partial block data at the end of the range */
1051 	if (tail) {
1052 		if (len < tail)
1053 			tail = len;
1054 		if (dbuf_hold_impl(dn, 0, dbuf_whichblock(dn, off+len),
1055 		    TRUE, FTAG, &db) == 0) {
1056 			/* don't dirty if not on disk and not dirty */
1057 			if (db->db_last_dirty ||
1058 			    (db->db_blkptr && !BP_IS_HOLE(db->db_blkptr))) {
1059 				rw_exit(&dn->dn_struct_rwlock);
1060 				dbuf_will_dirty(db, tx);
1061 				rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
1062 				bzero(db->db.db_data, tail);
1063 			}
1064 			dbuf_rele(db, FTAG);
1065 		}
1066 		len -= tail;
1067 	}
1068 
1069 	/* If the range did not include a full block, we are done */
1070 	if (len == 0)
1071 		goto out;
1072 
1073 	ASSERT(IS_P2ALIGNED(off, blksz));
1074 	ASSERT(trunc || IS_P2ALIGNED(len, blksz));
1075 	blkid = off >> blkshift;
1076 	nblks = len >> blkshift;
1077 	if (trunc)
1078 		nblks += 1;
1079 
1080 	/*
1081 	 * Read in and mark all the level-1 indirects dirty,
1082 	 * so that they will stay in memory until syncing phase.
1083 	 * Always dirty the first and last indirect to make sure
1084 	 * we dirty all the partial indirects.
1085 	 */
1086 	if (dn->dn_nlevels > 1) {
1087 		uint64_t i, first, last;
1088 		int shift = epbs + dn->dn_datablkshift;
1089 
1090 		first = blkid >> epbs;
1091 		if (db = dbuf_hold_level(dn, 1, first, FTAG)) {
1092 			dbuf_will_dirty(db, tx);
1093 			dbuf_rele(db, FTAG);
1094 		}
1095 		if (trunc)
1096 			last = dn->dn_maxblkid >> epbs;
1097 		else
1098 			last = (blkid + nblks - 1) >> epbs;
1099 		if (last > first && (db = dbuf_hold_level(dn, 1, last, FTAG))) {
1100 			dbuf_will_dirty(db, tx);
1101 			dbuf_rele(db, FTAG);
1102 		}
1103 		for (i = first + 1; i < last; i++) {
1104 			uint64_t ibyte = i << shift;
1105 			int err;
1106 
1107 			err = dnode_next_offset(dn,
1108 			    DNODE_FIND_HAVELOCK, &ibyte, 1, 1, 0);
1109 			i = ibyte >> shift;
1110 			if (err == ESRCH || i >= last)
1111 				break;
1112 			ASSERT(err == 0);
1113 			db = dbuf_hold_level(dn, 1, i, FTAG);
1114 			if (db) {
1115 				dbuf_will_dirty(db, tx);
1116 				dbuf_rele(db, FTAG);
1117 			}
1118 		}
1119 	}
1120 done:
1121 	/*
1122 	 * Add this range to the dnode range list.
1123 	 * We will finish up this free operation in the syncing phase.
1124 	 */
1125 	mutex_enter(&dn->dn_mtx);
1126 	dnode_clear_range(dn, blkid, nblks, tx);
1127 	{
1128 		free_range_t *rp, *found;
1129 		avl_index_t where;
1130 		avl_tree_t *tree = &dn->dn_ranges[tx->tx_txg&TXG_MASK];
1131 
1132 		/* Add new range to dn_ranges */
1133 		rp = kmem_alloc(sizeof (free_range_t), KM_SLEEP);
1134 		rp->fr_blkid = blkid;
1135 		rp->fr_nblks = nblks;
1136 		found = avl_find(tree, rp, &where);
1137 		ASSERT(found == NULL);
1138 		avl_insert(tree, rp, where);
1139 		dprintf_dnode(dn, "blkid=%llu nblks=%llu txg=%llu\n",
1140 		    blkid, nblks, tx->tx_txg);
1141 	}
1142 	mutex_exit(&dn->dn_mtx);
1143 
1144 	dbuf_free_range(dn, blkid, blkid + nblks - 1, tx);
1145 	dnode_setdirty(dn, tx);
1146 out:
1147 	if (trunc && dn->dn_maxblkid >= (off >> blkshift))
1148 		dn->dn_maxblkid = (off >> blkshift ? (off >> blkshift) - 1 : 0);
1149 
1150 	rw_exit(&dn->dn_struct_rwlock);
1151 }
1152 
1153 /* return TRUE if this blkid was freed in a recent txg, or FALSE if it wasn't */
1154 uint64_t
1155 dnode_block_freed(dnode_t *dn, uint64_t blkid)
1156 {
1157 	free_range_t range_tofind;
1158 	void *dp = spa_get_dsl(dn->dn_objset->os_spa);
1159 	int i;
1160 
1161 	if (blkid == DB_BONUS_BLKID)
1162 		return (FALSE);
1163 
1164 	/*
1165 	 * If we're in the process of opening the pool, dp will not be
1166 	 * set yet, but there shouldn't be anything dirty.
1167 	 */
1168 	if (dp == NULL)
1169 		return (FALSE);
1170 
1171 	if (dn->dn_free_txg)
1172 		return (TRUE);
1173 
1174 	range_tofind.fr_blkid = blkid;
1175 	mutex_enter(&dn->dn_mtx);
1176 	for (i = 0; i < TXG_SIZE; i++) {
1177 		free_range_t *range_found;
1178 		avl_index_t idx;
1179 
1180 		range_found = avl_find(&dn->dn_ranges[i], &range_tofind, &idx);
1181 		if (range_found) {
1182 			ASSERT(range_found->fr_nblks > 0);
1183 			break;
1184 		}
1185 		range_found = avl_nearest(&dn->dn_ranges[i], idx, AVL_BEFORE);
1186 		if (range_found &&
1187 		    range_found->fr_blkid + range_found->fr_nblks > blkid)
1188 			break;
1189 	}
1190 	mutex_exit(&dn->dn_mtx);
1191 	return (i < TXG_SIZE);
1192 }
1193 
1194 /* call from syncing context when we actually write/free space for this dnode */
1195 void
1196 dnode_diduse_space(dnode_t *dn, int64_t delta)
1197 {
1198 	uint64_t space;
1199 	dprintf_dnode(dn, "dn=%p dnp=%p used=%llu delta=%lld\n",
1200 	    dn, dn->dn_phys,
1201 	    (u_longlong_t)dn->dn_phys->dn_used,
1202 	    (longlong_t)delta);
1203 
1204 	mutex_enter(&dn->dn_mtx);
1205 	space = DN_USED_BYTES(dn->dn_phys);
1206 	if (delta > 0) {
1207 		ASSERT3U(space + delta, >=, space); /* no overflow */
1208 	} else {
1209 		ASSERT3U(space, >=, -delta); /* no underflow */
1210 	}
1211 	space += delta;
1212 	if (spa_version(dn->dn_objset->os_spa) < SPA_VERSION_DNODE_BYTES) {
1213 		ASSERT((dn->dn_phys->dn_flags & DNODE_FLAG_USED_BYTES) == 0);
1214 		ASSERT3U(P2PHASE(space, 1<<DEV_BSHIFT), ==, 0);
1215 		dn->dn_phys->dn_used = space >> DEV_BSHIFT;
1216 	} else {
1217 		dn->dn_phys->dn_used = space;
1218 		dn->dn_phys->dn_flags |= DNODE_FLAG_USED_BYTES;
1219 	}
1220 	mutex_exit(&dn->dn_mtx);
1221 }
1222 
1223 /*
1224  * Call when we think we're going to write/free space in open context.
1225  * Be conservative (ie. OK to write less than this or free more than
1226  * this, but don't write more or free less).
1227  */
1228 void
1229 dnode_willuse_space(dnode_t *dn, int64_t space, dmu_tx_t *tx)
1230 {
1231 	objset_impl_t *os = dn->dn_objset;
1232 	dsl_dataset_t *ds = os->os_dsl_dataset;
1233 
1234 	if (space > 0)
1235 		space = spa_get_asize(os->os_spa, space);
1236 
1237 	if (ds)
1238 		dsl_dir_willuse_space(ds->ds_dir, space, tx);
1239 
1240 	dmu_tx_willuse_space(tx, space);
1241 }
1242 
1243 static int
1244 dnode_next_offset_level(dnode_t *dn, int flags, uint64_t *offset,
1245 	int lvl, uint64_t blkfill, uint64_t txg)
1246 {
1247 	dmu_buf_impl_t *db = NULL;
1248 	void *data = NULL;
1249 	uint64_t epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
1250 	uint64_t epb = 1ULL << epbs;
1251 	uint64_t minfill, maxfill;
1252 	boolean_t hole;
1253 	int i, inc, error, span;
1254 
1255 	dprintf("probing object %llu offset %llx level %d of %u\n",
1256 	    dn->dn_object, *offset, lvl, dn->dn_phys->dn_nlevels);
1257 
1258 	hole = flags & DNODE_FIND_HOLE;
1259 	inc = (flags & DNODE_FIND_BACKWARDS) ? -1 : 1;
1260 	ASSERT(txg == 0 || !hole);
1261 
1262 	if (lvl == dn->dn_phys->dn_nlevels) {
1263 		error = 0;
1264 		epb = dn->dn_phys->dn_nblkptr;
1265 		data = dn->dn_phys->dn_blkptr;
1266 	} else {
1267 		uint64_t blkid = dbuf_whichblock(dn, *offset) >> (epbs * lvl);
1268 		error = dbuf_hold_impl(dn, lvl, blkid, TRUE, FTAG, &db);
1269 		if (error) {
1270 			if (error != ENOENT)
1271 				return (error);
1272 			if (hole)
1273 				return (0);
1274 			/*
1275 			 * This can only happen when we are searching up
1276 			 * the block tree for data.  We don't really need to
1277 			 * adjust the offset, as we will just end up looking
1278 			 * at the pointer to this block in its parent, and its
1279 			 * going to be unallocated, so we will skip over it.
1280 			 */
1281 			return (ESRCH);
1282 		}
1283 		error = dbuf_read(db, NULL, DB_RF_CANFAIL | DB_RF_HAVESTRUCT);
1284 		if (error) {
1285 			dbuf_rele(db, FTAG);
1286 			return (error);
1287 		}
1288 		data = db->db.db_data;
1289 	}
1290 
1291 	if (db && txg &&
1292 	    (db->db_blkptr == NULL || db->db_blkptr->blk_birth <= txg)) {
1293 		/*
1294 		 * This can only happen when we are searching up the tree
1295 		 * and these conditions mean that we need to keep climbing.
1296 		 */
1297 		error = ESRCH;
1298 	} else if (lvl == 0) {
1299 		dnode_phys_t *dnp = data;
1300 		span = DNODE_SHIFT;
1301 		ASSERT(dn->dn_type == DMU_OT_DNODE);
1302 
1303 		for (i = (*offset >> span) & (blkfill - 1);
1304 		    i >= 0 && i < blkfill; i += inc) {
1305 			boolean_t newcontents = B_TRUE;
1306 			if (txg) {
1307 				int j;
1308 				newcontents = B_FALSE;
1309 				for (j = 0; j < dnp[i].dn_nblkptr; j++) {
1310 					if (dnp[i].dn_blkptr[j].blk_birth > txg)
1311 						newcontents = B_TRUE;
1312 				}
1313 			}
1314 			if (!dnp[i].dn_type == hole && newcontents)
1315 				break;
1316 			*offset += (1ULL << span) * inc;
1317 		}
1318 		if (i < 0 || i == blkfill)
1319 			error = ESRCH;
1320 	} else {
1321 		blkptr_t *bp = data;
1322 		span = (lvl - 1) * epbs + dn->dn_datablkshift;
1323 		minfill = 0;
1324 		maxfill = blkfill << ((lvl - 1) * epbs);
1325 
1326 		if (hole)
1327 			maxfill--;
1328 		else
1329 			minfill++;
1330 
1331 		for (i = (*offset >> span) & ((1ULL << epbs) - 1);
1332 		    i >= 0 && i < epb; i += inc) {
1333 			if (bp[i].blk_fill >= minfill &&
1334 			    bp[i].blk_fill <= maxfill &&
1335 			    (hole || bp[i].blk_birth > txg))
1336 				break;
1337 			if (inc < 0 && *offset < (1ULL << span))
1338 				*offset = 0;
1339 			else
1340 				*offset += (1ULL << span) * inc;
1341 		}
1342 		if (i < 0 || i == epb)
1343 			error = ESRCH;
1344 	}
1345 
1346 	if (db)
1347 		dbuf_rele(db, FTAG);
1348 
1349 	return (error);
1350 }
1351 
1352 /*
1353  * Find the next hole, data, or sparse region at or after *offset.
1354  * The value 'blkfill' tells us how many items we expect to find
1355  * in an L0 data block; this value is 1 for normal objects,
1356  * DNODES_PER_BLOCK for the meta dnode, and some fraction of
1357  * DNODES_PER_BLOCK when searching for sparse regions thereof.
1358  *
1359  * Examples:
1360  *
1361  * dnode_next_offset(dn, flags, offset, 1, 1, 0);
1362  *	Finds the next/previous hole/data in a file.
1363  *	Used in dmu_offset_next().
1364  *
1365  * dnode_next_offset(mdn, flags, offset, 0, DNODES_PER_BLOCK, txg);
1366  *	Finds the next free/allocated dnode an objset's meta-dnode.
1367  *	Only finds objects that have new contents since txg (ie.
1368  *	bonus buffer changes and content removal are ignored).
1369  *	Used in dmu_object_next().
1370  *
1371  * dnode_next_offset(mdn, DNODE_FIND_HOLE, offset, 2, DNODES_PER_BLOCK >> 2, 0);
1372  *	Finds the next L2 meta-dnode bp that's at most 1/4 full.
1373  *	Used in dmu_object_alloc().
1374  */
1375 int
1376 dnode_next_offset(dnode_t *dn, int flags, uint64_t *offset,
1377     int minlvl, uint64_t blkfill, uint64_t txg)
1378 {
1379 	uint64_t initial_offset = *offset;
1380 	int lvl, maxlvl;
1381 	int error = 0;
1382 
1383 	if (!(flags & DNODE_FIND_HAVELOCK))
1384 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
1385 
1386 	if (dn->dn_phys->dn_nlevels == 0) {
1387 		error = ESRCH;
1388 		goto out;
1389 	}
1390 
1391 	if (dn->dn_datablkshift == 0) {
1392 		if (*offset < dn->dn_datablksz) {
1393 			if (flags & DNODE_FIND_HOLE)
1394 				*offset = dn->dn_datablksz;
1395 		} else {
1396 			error = ESRCH;
1397 		}
1398 		goto out;
1399 	}
1400 
1401 	maxlvl = dn->dn_phys->dn_nlevels;
1402 
1403 	for (lvl = minlvl; lvl <= maxlvl; lvl++) {
1404 		error = dnode_next_offset_level(dn,
1405 		    flags, offset, lvl, blkfill, txg);
1406 		if (error != ESRCH)
1407 			break;
1408 	}
1409 
1410 	while (error == 0 && --lvl >= minlvl) {
1411 		error = dnode_next_offset_level(dn,
1412 		    flags, offset, lvl, blkfill, txg);
1413 	}
1414 
1415 	if (error == 0 && (flags & DNODE_FIND_BACKWARDS ?
1416 	    initial_offset < *offset : initial_offset > *offset))
1417 		error = ESRCH;
1418 out:
1419 	if (!(flags & DNODE_FIND_HAVELOCK))
1420 		rw_exit(&dn->dn_struct_rwlock);
1421 
1422 	return (error);
1423 }
1424