xref: /titanic_52/usr/src/uts/common/fs/zfs/dnode.c (revision 69112edd987c28fa551d4f8d9362a84a45365f17)
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(DMU_OBJECT_IS_SPECIAL(dn->dn_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_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_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 	ASSERT(dn->dn_oldphys == NULL);
325 
326 	mutex_enter(&os->os_lock);
327 	list_remove(&os->os_dnodes, dn);
328 	mutex_exit(&os->os_lock);
329 
330 	if (dn->dn_dirtyctx_firstset) {
331 		kmem_free(dn->dn_dirtyctx_firstset, 1);
332 		dn->dn_dirtyctx_firstset = NULL;
333 	}
334 	dmu_zfetch_rele(&dn->dn_zfetch);
335 	if (dn->dn_bonus) {
336 		mutex_enter(&dn->dn_bonus->db_mtx);
337 		dbuf_evict(dn->dn_bonus);
338 		dn->dn_bonus = NULL;
339 	}
340 	kmem_cache_free(dnode_cache, dn);
341 	arc_space_return(sizeof (dnode_t), ARC_SPACE_OTHER);
342 }
343 
344 void
345 dnode_allocate(dnode_t *dn, dmu_object_type_t ot, int blocksize, int ibs,
346     dmu_object_type_t bonustype, int bonuslen, dmu_tx_t *tx)
347 {
348 	int i;
349 
350 	if (blocksize == 0)
351 		blocksize = 1 << zfs_default_bs;
352 	else if (blocksize > SPA_MAXBLOCKSIZE)
353 		blocksize = SPA_MAXBLOCKSIZE;
354 	else
355 		blocksize = P2ROUNDUP(blocksize, SPA_MINBLOCKSIZE);
356 
357 	if (ibs == 0)
358 		ibs = zfs_default_ibs;
359 
360 	ibs = MIN(MAX(ibs, DN_MIN_INDBLKSHIFT), DN_MAX_INDBLKSHIFT);
361 
362 	dprintf("os=%p obj=%llu txg=%llu blocksize=%d ibs=%d\n", dn->dn_objset,
363 	    dn->dn_object, tx->tx_txg, blocksize, ibs);
364 
365 	ASSERT(dn->dn_type == DMU_OT_NONE);
366 	ASSERT(bcmp(dn->dn_phys, &dnode_phys_zero, sizeof (dnode_phys_t)) == 0);
367 	ASSERT(dn->dn_phys->dn_type == DMU_OT_NONE);
368 	ASSERT(ot != DMU_OT_NONE);
369 	ASSERT3U(ot, <, DMU_OT_NUMTYPES);
370 	ASSERT((bonustype == DMU_OT_NONE && bonuslen == 0) ||
371 	    (bonustype != DMU_OT_NONE && bonuslen != 0));
372 	ASSERT3U(bonustype, <, DMU_OT_NUMTYPES);
373 	ASSERT3U(bonuslen, <=, DN_MAX_BONUSLEN);
374 	ASSERT(dn->dn_type == DMU_OT_NONE);
375 	ASSERT3U(dn->dn_maxblkid, ==, 0);
376 	ASSERT3U(dn->dn_allocated_txg, ==, 0);
377 	ASSERT3U(dn->dn_assigned_txg, ==, 0);
378 	ASSERT(refcount_is_zero(&dn->dn_tx_holds));
379 	ASSERT3U(refcount_count(&dn->dn_holds), <=, 1);
380 	ASSERT3P(list_head(&dn->dn_dbufs), ==, NULL);
381 
382 	for (i = 0; i < TXG_SIZE; i++) {
383 		ASSERT3U(dn->dn_next_nlevels[i], ==, 0);
384 		ASSERT3U(dn->dn_next_indblkshift[i], ==, 0);
385 		ASSERT3U(dn->dn_next_bonuslen[i], ==, 0);
386 		ASSERT3U(dn->dn_next_blksz[i], ==, 0);
387 		ASSERT(!list_link_active(&dn->dn_dirty_link[i]));
388 		ASSERT3P(list_head(&dn->dn_dirty_records[i]), ==, NULL);
389 		ASSERT3U(avl_numnodes(&dn->dn_ranges[i]), ==, 0);
390 	}
391 
392 	dn->dn_type = ot;
393 	dnode_setdblksz(dn, blocksize);
394 	dn->dn_indblkshift = ibs;
395 	dn->dn_nlevels = 1;
396 	dn->dn_nblkptr = 1 + ((DN_MAX_BONUSLEN - bonuslen) >> SPA_BLKPTRSHIFT);
397 	dn->dn_bonustype = bonustype;
398 	dn->dn_bonuslen = bonuslen;
399 	dn->dn_checksum = ZIO_CHECKSUM_INHERIT;
400 	dn->dn_compress = ZIO_COMPRESS_INHERIT;
401 	dn->dn_dirtyctx = 0;
402 
403 	dn->dn_free_txg = 0;
404 	if (dn->dn_dirtyctx_firstset) {
405 		kmem_free(dn->dn_dirtyctx_firstset, 1);
406 		dn->dn_dirtyctx_firstset = NULL;
407 	}
408 
409 	dn->dn_allocated_txg = tx->tx_txg;
410 
411 	dnode_setdirty(dn, tx);
412 	dn->dn_next_indblkshift[tx->tx_txg & TXG_MASK] = ibs;
413 	dn->dn_next_bonuslen[tx->tx_txg & TXG_MASK] = dn->dn_bonuslen;
414 	dn->dn_next_blksz[tx->tx_txg & TXG_MASK] = dn->dn_datablksz;
415 }
416 
417 void
418 dnode_reallocate(dnode_t *dn, dmu_object_type_t ot, int blocksize,
419     dmu_object_type_t bonustype, int bonuslen, dmu_tx_t *tx)
420 {
421 	int nblkptr;
422 
423 	ASSERT3U(blocksize, >=, SPA_MINBLOCKSIZE);
424 	ASSERT3U(blocksize, <=, SPA_MAXBLOCKSIZE);
425 	ASSERT3U(blocksize % SPA_MINBLOCKSIZE, ==, 0);
426 	ASSERT(dn->dn_object != DMU_META_DNODE_OBJECT || dmu_tx_private_ok(tx));
427 	ASSERT(tx->tx_txg != 0);
428 	ASSERT((bonustype == DMU_OT_NONE && bonuslen == 0) ||
429 	    (bonustype != DMU_OT_NONE && bonuslen != 0));
430 	ASSERT3U(bonustype, <, DMU_OT_NUMTYPES);
431 	ASSERT3U(bonuslen, <=, DN_MAX_BONUSLEN);
432 
433 	/* clean up any unreferenced dbufs */
434 	dnode_evict_dbufs(dn);
435 
436 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
437 	dnode_setdirty(dn, tx);
438 	if (dn->dn_datablksz != blocksize) {
439 		/* change blocksize */
440 		ASSERT(dn->dn_maxblkid == 0 &&
441 		    (BP_IS_HOLE(&dn->dn_phys->dn_blkptr[0]) ||
442 		    dnode_block_freed(dn, 0)));
443 		dnode_setdblksz(dn, blocksize);
444 		dn->dn_next_blksz[tx->tx_txg&TXG_MASK] = blocksize;
445 	}
446 	if (dn->dn_bonuslen != bonuslen)
447 		dn->dn_next_bonuslen[tx->tx_txg&TXG_MASK] = bonuslen;
448 	nblkptr = 1 + ((DN_MAX_BONUSLEN - bonuslen) >> SPA_BLKPTRSHIFT);
449 	if (dn->dn_nblkptr != nblkptr)
450 		dn->dn_next_nblkptr[tx->tx_txg&TXG_MASK] = nblkptr;
451 	rw_exit(&dn->dn_struct_rwlock);
452 
453 	/* change type */
454 	dn->dn_type = ot;
455 
456 	/* change bonus size and type */
457 	mutex_enter(&dn->dn_mtx);
458 	dn->dn_bonustype = bonustype;
459 	dn->dn_bonuslen = bonuslen;
460 	dn->dn_nblkptr = nblkptr;
461 	dn->dn_checksum = ZIO_CHECKSUM_INHERIT;
462 	dn->dn_compress = ZIO_COMPRESS_INHERIT;
463 	ASSERT3U(dn->dn_nblkptr, <=, DN_MAX_NBLKPTR);
464 
465 	/* fix up the bonus db_size */
466 	if (dn->dn_bonus) {
467 		dn->dn_bonus->db.db_size =
468 		    DN_MAX_BONUSLEN - (dn->dn_nblkptr-1) * sizeof (blkptr_t);
469 		ASSERT(dn->dn_bonuslen <= dn->dn_bonus->db.db_size);
470 	}
471 
472 	dn->dn_allocated_txg = tx->tx_txg;
473 	mutex_exit(&dn->dn_mtx);
474 }
475 
476 void
477 dnode_special_close(dnode_t *dn)
478 {
479 	/*
480 	 * Wait for final references to the dnode to clear.  This can
481 	 * only happen if the arc is asyncronously evicting state that
482 	 * has a hold on this dnode while we are trying to evict this
483 	 * dnode.
484 	 */
485 	while (refcount_count(&dn->dn_holds) > 0)
486 		delay(1);
487 	dnode_destroy(dn);
488 }
489 
490 dnode_t *
491 dnode_special_open(objset_t *os, dnode_phys_t *dnp, uint64_t object)
492 {
493 	dnode_t *dn = dnode_create(os, dnp, NULL, object);
494 	DNODE_VERIFY(dn);
495 	return (dn);
496 }
497 
498 static void
499 dnode_buf_pageout(dmu_buf_t *db, void *arg)
500 {
501 	dnode_t **children_dnodes = arg;
502 	int i;
503 	int epb = db->db_size >> DNODE_SHIFT;
504 
505 	for (i = 0; i < epb; i++) {
506 		dnode_t *dn = children_dnodes[i];
507 		int n;
508 
509 		if (dn == NULL)
510 			continue;
511 #ifdef ZFS_DEBUG
512 		/*
513 		 * If there are holds on this dnode, then there should
514 		 * be holds on the dnode's containing dbuf as well; thus
515 		 * it wouldn't be eligable for eviction and this function
516 		 * would not have been called.
517 		 */
518 		ASSERT(refcount_is_zero(&dn->dn_holds));
519 		ASSERT(list_head(&dn->dn_dbufs) == NULL);
520 		ASSERT(refcount_is_zero(&dn->dn_tx_holds));
521 
522 		for (n = 0; n < TXG_SIZE; n++)
523 			ASSERT(!list_link_active(&dn->dn_dirty_link[n]));
524 #endif
525 		children_dnodes[i] = NULL;
526 		dnode_destroy(dn);
527 	}
528 	kmem_free(children_dnodes, epb * sizeof (dnode_t *));
529 }
530 
531 /*
532  * errors:
533  * EINVAL - invalid object number.
534  * EIO - i/o error.
535  * succeeds even for free dnodes.
536  */
537 int
538 dnode_hold_impl(objset_t *os, uint64_t object, int flag,
539     void *tag, dnode_t **dnp)
540 {
541 	int epb, idx, err;
542 	int drop_struct_lock = FALSE;
543 	int type;
544 	uint64_t blk;
545 	dnode_t *mdn, *dn;
546 	dmu_buf_impl_t *db;
547 	dnode_t **children_dnodes;
548 
549 	/*
550 	 * If you are holding the spa config lock as writer, you shouldn't
551 	 * be asking the DMU to do *anything*.
552 	 */
553 	ASSERT(spa_config_held(os->os_spa, SCL_ALL, RW_WRITER) == 0);
554 
555 	if (object == DMU_USERUSED_OBJECT || object == DMU_GROUPUSED_OBJECT) {
556 		dn = (object == DMU_USERUSED_OBJECT) ?
557 		    os->os_userused_dnode : os->os_groupused_dnode;
558 		if (dn == NULL)
559 			return (ENOENT);
560 		type = dn->dn_type;
561 		if ((flag & DNODE_MUST_BE_ALLOCATED) && type == DMU_OT_NONE)
562 			return (ENOENT);
563 		if ((flag & DNODE_MUST_BE_FREE) && type != DMU_OT_NONE)
564 			return (EEXIST);
565 		DNODE_VERIFY(dn);
566 		(void) refcount_add(&dn->dn_holds, tag);
567 		*dnp = dn;
568 		return (0);
569 	}
570 
571 	if (object == 0 || object >= DN_MAX_OBJECT)
572 		return (EINVAL);
573 
574 	mdn = os->os_meta_dnode;
575 
576 	DNODE_VERIFY(mdn);
577 
578 	if (!RW_WRITE_HELD(&mdn->dn_struct_rwlock)) {
579 		rw_enter(&mdn->dn_struct_rwlock, RW_READER);
580 		drop_struct_lock = TRUE;
581 	}
582 
583 	blk = dbuf_whichblock(mdn, object * sizeof (dnode_phys_t));
584 
585 	db = dbuf_hold(mdn, blk, FTAG);
586 	if (drop_struct_lock)
587 		rw_exit(&mdn->dn_struct_rwlock);
588 	if (db == NULL)
589 		return (EIO);
590 	err = dbuf_read(db, NULL, DB_RF_CANFAIL);
591 	if (err) {
592 		dbuf_rele(db, FTAG);
593 		return (err);
594 	}
595 
596 	ASSERT3U(db->db.db_size, >=, 1<<DNODE_SHIFT);
597 	epb = db->db.db_size >> DNODE_SHIFT;
598 
599 	idx = object & (epb-1);
600 
601 	children_dnodes = dmu_buf_get_user(&db->db);
602 	if (children_dnodes == NULL) {
603 		dnode_t **winner;
604 		children_dnodes = kmem_zalloc(epb * sizeof (dnode_t *),
605 		    KM_SLEEP);
606 		if (winner = dmu_buf_set_user(&db->db, children_dnodes, NULL,
607 		    dnode_buf_pageout)) {
608 			kmem_free(children_dnodes, epb * sizeof (dnode_t *));
609 			children_dnodes = winner;
610 		}
611 	}
612 
613 	if ((dn = children_dnodes[idx]) == NULL) {
614 		dnode_phys_t *dnp = (dnode_phys_t *)db->db.db_data+idx;
615 		dnode_t *winner;
616 
617 		dn = dnode_create(os, dnp, db, object);
618 		winner = atomic_cas_ptr(&children_dnodes[idx], NULL, dn);
619 		if (winner != NULL) {
620 			dnode_destroy(dn);
621 			dn = winner;
622 		}
623 	}
624 
625 	mutex_enter(&dn->dn_mtx);
626 	type = dn->dn_type;
627 	if (dn->dn_free_txg ||
628 	    ((flag & DNODE_MUST_BE_ALLOCATED) && type == DMU_OT_NONE) ||
629 	    ((flag & DNODE_MUST_BE_FREE) &&
630 	    (type != DMU_OT_NONE || dn->dn_oldphys))) {
631 		mutex_exit(&dn->dn_mtx);
632 		dbuf_rele(db, FTAG);
633 		return (type == DMU_OT_NONE ? ENOENT : EEXIST);
634 	}
635 	mutex_exit(&dn->dn_mtx);
636 
637 	if (refcount_add(&dn->dn_holds, tag) == 1)
638 		dbuf_add_ref(db, dn);
639 
640 	DNODE_VERIFY(dn);
641 	ASSERT3P(dn->dn_dbuf, ==, db);
642 	ASSERT3U(dn->dn_object, ==, object);
643 	dbuf_rele(db, FTAG);
644 
645 	*dnp = dn;
646 	return (0);
647 }
648 
649 /*
650  * Return held dnode if the object is allocated, NULL if not.
651  */
652 int
653 dnode_hold(objset_t *os, uint64_t object, void *tag, dnode_t **dnp)
654 {
655 	return (dnode_hold_impl(os, object, DNODE_MUST_BE_ALLOCATED, tag, dnp));
656 }
657 
658 /*
659  * Can only add a reference if there is already at least one
660  * reference on the dnode.  Returns FALSE if unable to add a
661  * new reference.
662  */
663 boolean_t
664 dnode_add_ref(dnode_t *dn, void *tag)
665 {
666 	mutex_enter(&dn->dn_mtx);
667 	if (refcount_is_zero(&dn->dn_holds)) {
668 		mutex_exit(&dn->dn_mtx);
669 		return (FALSE);
670 	}
671 	VERIFY(1 < refcount_add(&dn->dn_holds, tag));
672 	mutex_exit(&dn->dn_mtx);
673 	return (TRUE);
674 }
675 
676 void
677 dnode_rele(dnode_t *dn, void *tag)
678 {
679 	uint64_t refs;
680 
681 	mutex_enter(&dn->dn_mtx);
682 	refs = refcount_remove(&dn->dn_holds, tag);
683 	mutex_exit(&dn->dn_mtx);
684 	/* NOTE: the DNODE_DNODE does not have a dn_dbuf */
685 	if (refs == 0 && dn->dn_dbuf)
686 		dbuf_rele(dn->dn_dbuf, dn);
687 }
688 
689 void
690 dnode_setdirty(dnode_t *dn, dmu_tx_t *tx)
691 {
692 	objset_t *os = dn->dn_objset;
693 	uint64_t txg = tx->tx_txg;
694 
695 	if (DMU_OBJECT_IS_SPECIAL(dn->dn_object)) {
696 		dsl_dataset_dirty(os->os_dsl_dataset, tx);
697 		return;
698 	}
699 
700 	DNODE_VERIFY(dn);
701 
702 #ifdef ZFS_DEBUG
703 	mutex_enter(&dn->dn_mtx);
704 	ASSERT(dn->dn_phys->dn_type || dn->dn_allocated_txg);
705 	/* ASSERT(dn->dn_free_txg == 0 || dn->dn_free_txg >= txg); */
706 	mutex_exit(&dn->dn_mtx);
707 #endif
708 
709 	mutex_enter(&os->os_lock);
710 
711 	/*
712 	 * If we are already marked dirty, we're done.
713 	 */
714 	if (list_link_active(&dn->dn_dirty_link[txg & TXG_MASK])) {
715 		mutex_exit(&os->os_lock);
716 		return;
717 	}
718 
719 	ASSERT(!refcount_is_zero(&dn->dn_holds) || list_head(&dn->dn_dbufs));
720 	ASSERT(dn->dn_datablksz != 0);
721 	ASSERT3U(dn->dn_next_bonuslen[txg&TXG_MASK], ==, 0);
722 	ASSERT3U(dn->dn_next_blksz[txg&TXG_MASK], ==, 0);
723 
724 	dprintf_ds(os->os_dsl_dataset, "obj=%llu txg=%llu\n",
725 	    dn->dn_object, txg);
726 
727 	if (dn->dn_free_txg > 0 && dn->dn_free_txg <= txg) {
728 		list_insert_tail(&os->os_free_dnodes[txg&TXG_MASK], dn);
729 	} else {
730 		list_insert_tail(&os->os_dirty_dnodes[txg&TXG_MASK], dn);
731 	}
732 
733 	mutex_exit(&os->os_lock);
734 
735 	/*
736 	 * The dnode maintains a hold on its containing dbuf as
737 	 * long as there are holds on it.  Each instantiated child
738 	 * dbuf maintaines a hold on the dnode.  When the last child
739 	 * drops its hold, the dnode will drop its hold on the
740 	 * containing dbuf. We add a "dirty hold" here so that the
741 	 * dnode will hang around after we finish processing its
742 	 * children.
743 	 */
744 	VERIFY(dnode_add_ref(dn, (void *)(uintptr_t)tx->tx_txg));
745 
746 	(void) dbuf_dirty(dn->dn_dbuf, tx);
747 
748 	dsl_dataset_dirty(os->os_dsl_dataset, tx);
749 }
750 
751 void
752 dnode_free(dnode_t *dn, dmu_tx_t *tx)
753 {
754 	int txgoff = tx->tx_txg & TXG_MASK;
755 
756 	dprintf("dn=%p txg=%llu\n", dn, tx->tx_txg);
757 
758 	/* we should be the only holder... hopefully */
759 	/* ASSERT3U(refcount_count(&dn->dn_holds), ==, 1); */
760 
761 	mutex_enter(&dn->dn_mtx);
762 	if (dn->dn_type == DMU_OT_NONE || dn->dn_free_txg) {
763 		mutex_exit(&dn->dn_mtx);
764 		return;
765 	}
766 	dn->dn_free_txg = tx->tx_txg;
767 	mutex_exit(&dn->dn_mtx);
768 
769 	/*
770 	 * If the dnode is already dirty, it needs to be moved from
771 	 * the dirty list to the free list.
772 	 */
773 	mutex_enter(&dn->dn_objset->os_lock);
774 	if (list_link_active(&dn->dn_dirty_link[txgoff])) {
775 		list_remove(&dn->dn_objset->os_dirty_dnodes[txgoff], dn);
776 		list_insert_tail(&dn->dn_objset->os_free_dnodes[txgoff], dn);
777 		mutex_exit(&dn->dn_objset->os_lock);
778 	} else {
779 		mutex_exit(&dn->dn_objset->os_lock);
780 		dnode_setdirty(dn, tx);
781 	}
782 }
783 
784 /*
785  * Try to change the block size for the indicated dnode.  This can only
786  * succeed if there are no blocks allocated or dirty beyond first block
787  */
788 int
789 dnode_set_blksz(dnode_t *dn, uint64_t size, int ibs, dmu_tx_t *tx)
790 {
791 	dmu_buf_impl_t *db, *db_next;
792 	int err;
793 
794 	if (size == 0)
795 		size = SPA_MINBLOCKSIZE;
796 	if (size > SPA_MAXBLOCKSIZE)
797 		size = SPA_MAXBLOCKSIZE;
798 	else
799 		size = P2ROUNDUP(size, SPA_MINBLOCKSIZE);
800 
801 	if (ibs == dn->dn_indblkshift)
802 		ibs = 0;
803 
804 	if (size >> SPA_MINBLOCKSHIFT == dn->dn_datablkszsec && ibs == 0)
805 		return (0);
806 
807 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
808 
809 	/* Check for any allocated blocks beyond the first */
810 	if (dn->dn_phys->dn_maxblkid != 0)
811 		goto fail;
812 
813 	mutex_enter(&dn->dn_dbufs_mtx);
814 	for (db = list_head(&dn->dn_dbufs); db; db = db_next) {
815 		db_next = list_next(&dn->dn_dbufs, db);
816 
817 		if (db->db_blkid != 0 && db->db_blkid != DB_BONUS_BLKID) {
818 			mutex_exit(&dn->dn_dbufs_mtx);
819 			goto fail;
820 		}
821 	}
822 	mutex_exit(&dn->dn_dbufs_mtx);
823 
824 	if (ibs && dn->dn_nlevels != 1)
825 		goto fail;
826 
827 	/* resize the old block */
828 	err = dbuf_hold_impl(dn, 0, 0, TRUE, FTAG, &db);
829 	if (err == 0)
830 		dbuf_new_size(db, size, tx);
831 	else if (err != ENOENT)
832 		goto fail;
833 
834 	dnode_setdblksz(dn, size);
835 	dnode_setdirty(dn, tx);
836 	dn->dn_next_blksz[tx->tx_txg&TXG_MASK] = size;
837 	if (ibs) {
838 		dn->dn_indblkshift = ibs;
839 		dn->dn_next_indblkshift[tx->tx_txg&TXG_MASK] = ibs;
840 	}
841 	/* rele after we have fixed the blocksize in the dnode */
842 	if (db)
843 		dbuf_rele(db, FTAG);
844 
845 	rw_exit(&dn->dn_struct_rwlock);
846 	return (0);
847 
848 fail:
849 	rw_exit(&dn->dn_struct_rwlock);
850 	return (ENOTSUP);
851 }
852 
853 /* read-holding callers must not rely on the lock being continuously held */
854 void
855 dnode_new_blkid(dnode_t *dn, uint64_t blkid, dmu_tx_t *tx, boolean_t have_read)
856 {
857 	uint64_t txgoff = tx->tx_txg & TXG_MASK;
858 	int epbs, new_nlevels;
859 	uint64_t sz;
860 
861 	ASSERT(blkid != DB_BONUS_BLKID);
862 
863 	ASSERT(have_read ?
864 	    RW_READ_HELD(&dn->dn_struct_rwlock) :
865 	    RW_WRITE_HELD(&dn->dn_struct_rwlock));
866 
867 	/*
868 	 * if we have a read-lock, check to see if we need to do any work
869 	 * before upgrading to a write-lock.
870 	 */
871 	if (have_read) {
872 		if (blkid <= dn->dn_maxblkid)
873 			return;
874 
875 		if (!rw_tryupgrade(&dn->dn_struct_rwlock)) {
876 			rw_exit(&dn->dn_struct_rwlock);
877 			rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
878 		}
879 	}
880 
881 	if (blkid <= dn->dn_maxblkid)
882 		goto out;
883 
884 	dn->dn_maxblkid = blkid;
885 
886 	/*
887 	 * Compute the number of levels necessary to support the new maxblkid.
888 	 */
889 	new_nlevels = 1;
890 	epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
891 	for (sz = dn->dn_nblkptr;
892 	    sz <= blkid && sz >= dn->dn_nblkptr; sz <<= epbs)
893 		new_nlevels++;
894 
895 	if (new_nlevels > dn->dn_nlevels) {
896 		int old_nlevels = dn->dn_nlevels;
897 		dmu_buf_impl_t *db;
898 		list_t *list;
899 		dbuf_dirty_record_t *new, *dr, *dr_next;
900 
901 		dn->dn_nlevels = new_nlevels;
902 
903 		ASSERT3U(new_nlevels, >, dn->dn_next_nlevels[txgoff]);
904 		dn->dn_next_nlevels[txgoff] = new_nlevels;
905 
906 		/* dirty the left indirects */
907 		db = dbuf_hold_level(dn, old_nlevels, 0, FTAG);
908 		new = dbuf_dirty(db, tx);
909 		dbuf_rele(db, FTAG);
910 
911 		/* transfer the dirty records to the new indirect */
912 		mutex_enter(&dn->dn_mtx);
913 		mutex_enter(&new->dt.di.dr_mtx);
914 		list = &dn->dn_dirty_records[txgoff];
915 		for (dr = list_head(list); dr; dr = dr_next) {
916 			dr_next = list_next(&dn->dn_dirty_records[txgoff], dr);
917 			if (dr->dr_dbuf->db_level != new_nlevels-1 &&
918 			    dr->dr_dbuf->db_blkid != DB_BONUS_BLKID) {
919 				ASSERT(dr->dr_dbuf->db_level == old_nlevels-1);
920 				list_remove(&dn->dn_dirty_records[txgoff], dr);
921 				list_insert_tail(&new->dt.di.dr_children, dr);
922 				dr->dr_parent = new;
923 			}
924 		}
925 		mutex_exit(&new->dt.di.dr_mtx);
926 		mutex_exit(&dn->dn_mtx);
927 	}
928 
929 out:
930 	if (have_read)
931 		rw_downgrade(&dn->dn_struct_rwlock);
932 }
933 
934 void
935 dnode_clear_range(dnode_t *dn, uint64_t blkid, uint64_t nblks, dmu_tx_t *tx)
936 {
937 	avl_tree_t *tree = &dn->dn_ranges[tx->tx_txg&TXG_MASK];
938 	avl_index_t where;
939 	free_range_t *rp;
940 	free_range_t rp_tofind;
941 	uint64_t endblk = blkid + nblks;
942 
943 	ASSERT(MUTEX_HELD(&dn->dn_mtx));
944 	ASSERT(nblks <= UINT64_MAX - blkid); /* no overflow */
945 
946 	dprintf_dnode(dn, "blkid=%llu nblks=%llu txg=%llu\n",
947 	    blkid, nblks, tx->tx_txg);
948 	rp_tofind.fr_blkid = blkid;
949 	rp = avl_find(tree, &rp_tofind, &where);
950 	if (rp == NULL)
951 		rp = avl_nearest(tree, where, AVL_BEFORE);
952 	if (rp == NULL)
953 		rp = avl_nearest(tree, where, AVL_AFTER);
954 
955 	while (rp && (rp->fr_blkid <= blkid + nblks)) {
956 		uint64_t fr_endblk = rp->fr_blkid + rp->fr_nblks;
957 		free_range_t *nrp = AVL_NEXT(tree, rp);
958 
959 		if (blkid <= rp->fr_blkid && endblk >= fr_endblk) {
960 			/* clear this entire range */
961 			avl_remove(tree, rp);
962 			kmem_free(rp, sizeof (free_range_t));
963 		} else if (blkid <= rp->fr_blkid &&
964 		    endblk > rp->fr_blkid && endblk < fr_endblk) {
965 			/* clear the beginning of this range */
966 			rp->fr_blkid = endblk;
967 			rp->fr_nblks = fr_endblk - endblk;
968 		} else if (blkid > rp->fr_blkid && blkid < fr_endblk &&
969 		    endblk >= fr_endblk) {
970 			/* clear the end of this range */
971 			rp->fr_nblks = blkid - rp->fr_blkid;
972 		} else if (blkid > rp->fr_blkid && endblk < fr_endblk) {
973 			/* clear a chunk out of this range */
974 			free_range_t *new_rp =
975 			    kmem_alloc(sizeof (free_range_t), KM_SLEEP);
976 
977 			new_rp->fr_blkid = endblk;
978 			new_rp->fr_nblks = fr_endblk - endblk;
979 			avl_insert_here(tree, new_rp, rp, AVL_AFTER);
980 			rp->fr_nblks = blkid - rp->fr_blkid;
981 		}
982 		/* there may be no overlap */
983 		rp = nrp;
984 	}
985 }
986 
987 void
988 dnode_free_range(dnode_t *dn, uint64_t off, uint64_t len, dmu_tx_t *tx)
989 {
990 	dmu_buf_impl_t *db;
991 	uint64_t blkoff, blkid, nblks;
992 	int blksz, blkshift, head, tail;
993 	int trunc = FALSE;
994 	int epbs;
995 
996 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
997 	blksz = dn->dn_datablksz;
998 	blkshift = dn->dn_datablkshift;
999 	epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
1000 
1001 	if (len == -1ULL) {
1002 		len = UINT64_MAX - off;
1003 		trunc = TRUE;
1004 	}
1005 
1006 	/*
1007 	 * First, block align the region to free:
1008 	 */
1009 	if (ISP2(blksz)) {
1010 		head = P2NPHASE(off, blksz);
1011 		blkoff = P2PHASE(off, blksz);
1012 		if ((off >> blkshift) > dn->dn_maxblkid)
1013 			goto out;
1014 	} else {
1015 		ASSERT(dn->dn_maxblkid == 0);
1016 		if (off == 0 && len >= blksz) {
1017 			/* Freeing the whole block; fast-track this request */
1018 			blkid = 0;
1019 			nblks = 1;
1020 			goto done;
1021 		} else if (off >= blksz) {
1022 			/* Freeing past end-of-data */
1023 			goto out;
1024 		} else {
1025 			/* Freeing part of the block. */
1026 			head = blksz - off;
1027 			ASSERT3U(head, >, 0);
1028 		}
1029 		blkoff = off;
1030 	}
1031 	/* zero out any partial block data at the start of the range */
1032 	if (head) {
1033 		ASSERT3U(blkoff + head, ==, blksz);
1034 		if (len < head)
1035 			head = len;
1036 		if (dbuf_hold_impl(dn, 0, dbuf_whichblock(dn, off), TRUE,
1037 		    FTAG, &db) == 0) {
1038 			caddr_t data;
1039 
1040 			/* don't dirty if it isn't on disk and isn't dirty */
1041 			if (db->db_last_dirty ||
1042 			    (db->db_blkptr && !BP_IS_HOLE(db->db_blkptr))) {
1043 				rw_exit(&dn->dn_struct_rwlock);
1044 				dbuf_will_dirty(db, tx);
1045 				rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
1046 				data = db->db.db_data;
1047 				bzero(data + blkoff, head);
1048 			}
1049 			dbuf_rele(db, FTAG);
1050 		}
1051 		off += head;
1052 		len -= head;
1053 	}
1054 
1055 	/* If the range was less than one block, we're done */
1056 	if (len == 0)
1057 		goto out;
1058 
1059 	/* If the remaining range is past end of file, we're done */
1060 	if ((off >> blkshift) > dn->dn_maxblkid)
1061 		goto out;
1062 
1063 	ASSERT(ISP2(blksz));
1064 	if (trunc)
1065 		tail = 0;
1066 	else
1067 		tail = P2PHASE(len, blksz);
1068 
1069 	ASSERT3U(P2PHASE(off, blksz), ==, 0);
1070 	/* zero out any partial block data at the end of the range */
1071 	if (tail) {
1072 		if (len < tail)
1073 			tail = len;
1074 		if (dbuf_hold_impl(dn, 0, dbuf_whichblock(dn, off+len),
1075 		    TRUE, FTAG, &db) == 0) {
1076 			/* don't dirty if not on disk and not dirty */
1077 			if (db->db_last_dirty ||
1078 			    (db->db_blkptr && !BP_IS_HOLE(db->db_blkptr))) {
1079 				rw_exit(&dn->dn_struct_rwlock);
1080 				dbuf_will_dirty(db, tx);
1081 				rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
1082 				bzero(db->db.db_data, tail);
1083 			}
1084 			dbuf_rele(db, FTAG);
1085 		}
1086 		len -= tail;
1087 	}
1088 
1089 	/* If the range did not include a full block, we are done */
1090 	if (len == 0)
1091 		goto out;
1092 
1093 	ASSERT(IS_P2ALIGNED(off, blksz));
1094 	ASSERT(trunc || IS_P2ALIGNED(len, blksz));
1095 	blkid = off >> blkshift;
1096 	nblks = len >> blkshift;
1097 	if (trunc)
1098 		nblks += 1;
1099 
1100 	/*
1101 	 * Read in and mark all the level-1 indirects dirty,
1102 	 * so that they will stay in memory until syncing phase.
1103 	 * Always dirty the first and last indirect to make sure
1104 	 * we dirty all the partial indirects.
1105 	 */
1106 	if (dn->dn_nlevels > 1) {
1107 		uint64_t i, first, last;
1108 		int shift = epbs + dn->dn_datablkshift;
1109 
1110 		first = blkid >> epbs;
1111 		if (db = dbuf_hold_level(dn, 1, first, FTAG)) {
1112 			dbuf_will_dirty(db, tx);
1113 			dbuf_rele(db, FTAG);
1114 		}
1115 		if (trunc)
1116 			last = dn->dn_maxblkid >> epbs;
1117 		else
1118 			last = (blkid + nblks - 1) >> epbs;
1119 		if (last > first && (db = dbuf_hold_level(dn, 1, last, FTAG))) {
1120 			dbuf_will_dirty(db, tx);
1121 			dbuf_rele(db, FTAG);
1122 		}
1123 		for (i = first + 1; i < last; i++) {
1124 			uint64_t ibyte = i << shift;
1125 			int err;
1126 
1127 			err = dnode_next_offset(dn,
1128 			    DNODE_FIND_HAVELOCK, &ibyte, 1, 1, 0);
1129 			i = ibyte >> shift;
1130 			if (err == ESRCH || i >= last)
1131 				break;
1132 			ASSERT(err == 0);
1133 			db = dbuf_hold_level(dn, 1, i, FTAG);
1134 			if (db) {
1135 				dbuf_will_dirty(db, tx);
1136 				dbuf_rele(db, FTAG);
1137 			}
1138 		}
1139 	}
1140 done:
1141 	/*
1142 	 * Add this range to the dnode range list.
1143 	 * We will finish up this free operation in the syncing phase.
1144 	 */
1145 	mutex_enter(&dn->dn_mtx);
1146 	dnode_clear_range(dn, blkid, nblks, tx);
1147 	{
1148 		free_range_t *rp, *found;
1149 		avl_index_t where;
1150 		avl_tree_t *tree = &dn->dn_ranges[tx->tx_txg&TXG_MASK];
1151 
1152 		/* Add new range to dn_ranges */
1153 		rp = kmem_alloc(sizeof (free_range_t), KM_SLEEP);
1154 		rp->fr_blkid = blkid;
1155 		rp->fr_nblks = nblks;
1156 		found = avl_find(tree, rp, &where);
1157 		ASSERT(found == NULL);
1158 		avl_insert(tree, rp, where);
1159 		dprintf_dnode(dn, "blkid=%llu nblks=%llu txg=%llu\n",
1160 		    blkid, nblks, tx->tx_txg);
1161 	}
1162 	mutex_exit(&dn->dn_mtx);
1163 
1164 	dbuf_free_range(dn, blkid, blkid + nblks - 1, tx);
1165 	dnode_setdirty(dn, tx);
1166 out:
1167 	if (trunc && dn->dn_maxblkid >= (off >> blkshift))
1168 		dn->dn_maxblkid = (off >> blkshift ? (off >> blkshift) - 1 : 0);
1169 
1170 	rw_exit(&dn->dn_struct_rwlock);
1171 }
1172 
1173 /* return TRUE if this blkid was freed in a recent txg, or FALSE if it wasn't */
1174 uint64_t
1175 dnode_block_freed(dnode_t *dn, uint64_t blkid)
1176 {
1177 	free_range_t range_tofind;
1178 	void *dp = spa_get_dsl(dn->dn_objset->os_spa);
1179 	int i;
1180 
1181 	if (blkid == DB_BONUS_BLKID)
1182 		return (FALSE);
1183 
1184 	/*
1185 	 * If we're in the process of opening the pool, dp will not be
1186 	 * set yet, but there shouldn't be anything dirty.
1187 	 */
1188 	if (dp == NULL)
1189 		return (FALSE);
1190 
1191 	if (dn->dn_free_txg)
1192 		return (TRUE);
1193 
1194 	range_tofind.fr_blkid = blkid;
1195 	mutex_enter(&dn->dn_mtx);
1196 	for (i = 0; i < TXG_SIZE; i++) {
1197 		free_range_t *range_found;
1198 		avl_index_t idx;
1199 
1200 		range_found = avl_find(&dn->dn_ranges[i], &range_tofind, &idx);
1201 		if (range_found) {
1202 			ASSERT(range_found->fr_nblks > 0);
1203 			break;
1204 		}
1205 		range_found = avl_nearest(&dn->dn_ranges[i], idx, AVL_BEFORE);
1206 		if (range_found &&
1207 		    range_found->fr_blkid + range_found->fr_nblks > blkid)
1208 			break;
1209 	}
1210 	mutex_exit(&dn->dn_mtx);
1211 	return (i < TXG_SIZE);
1212 }
1213 
1214 /* call from syncing context when we actually write/free space for this dnode */
1215 void
1216 dnode_diduse_space(dnode_t *dn, int64_t delta)
1217 {
1218 	uint64_t space;
1219 	dprintf_dnode(dn, "dn=%p dnp=%p used=%llu delta=%lld\n",
1220 	    dn, dn->dn_phys,
1221 	    (u_longlong_t)dn->dn_phys->dn_used,
1222 	    (longlong_t)delta);
1223 
1224 	mutex_enter(&dn->dn_mtx);
1225 	space = DN_USED_BYTES(dn->dn_phys);
1226 	if (delta > 0) {
1227 		ASSERT3U(space + delta, >=, space); /* no overflow */
1228 	} else {
1229 		ASSERT3U(space, >=, -delta); /* no underflow */
1230 	}
1231 	space += delta;
1232 	if (spa_version(dn->dn_objset->os_spa) < SPA_VERSION_DNODE_BYTES) {
1233 		ASSERT((dn->dn_phys->dn_flags & DNODE_FLAG_USED_BYTES) == 0);
1234 		ASSERT3U(P2PHASE(space, 1<<DEV_BSHIFT), ==, 0);
1235 		dn->dn_phys->dn_used = space >> DEV_BSHIFT;
1236 	} else {
1237 		dn->dn_phys->dn_used = space;
1238 		dn->dn_phys->dn_flags |= DNODE_FLAG_USED_BYTES;
1239 	}
1240 	mutex_exit(&dn->dn_mtx);
1241 }
1242 
1243 /*
1244  * Call when we think we're going to write/free space in open context.
1245  * Be conservative (ie. OK to write less than this or free more than
1246  * this, but don't write more or free less).
1247  */
1248 void
1249 dnode_willuse_space(dnode_t *dn, int64_t space, dmu_tx_t *tx)
1250 {
1251 	objset_t *os = dn->dn_objset;
1252 	dsl_dataset_t *ds = os->os_dsl_dataset;
1253 
1254 	if (space > 0)
1255 		space = spa_get_asize(os->os_spa, space);
1256 
1257 	if (ds)
1258 		dsl_dir_willuse_space(ds->ds_dir, space, tx);
1259 
1260 	dmu_tx_willuse_space(tx, space);
1261 }
1262 
1263 /*
1264  * This function scans a block at the indicated "level" looking for
1265  * a hole or data (depending on 'flags').  If level > 0, then we are
1266  * scanning an indirect block looking at its pointers.  If level == 0,
1267  * then we are looking at a block of dnodes.  If we don't find what we
1268  * are looking for in the block, we return ESRCH.  Otherwise, return
1269  * with *offset pointing to the beginning (if searching forwards) or
1270  * end (if searching backwards) of the range covered by the block
1271  * pointer we matched on (or dnode).
1272  *
1273  * The basic search algorithm used below by dnode_next_offset() is to
1274  * use this function to search up the block tree (widen the search) until
1275  * we find something (i.e., we don't return ESRCH) and then search back
1276  * down the tree (narrow the search) until we reach our original search
1277  * level.
1278  */
1279 static int
1280 dnode_next_offset_level(dnode_t *dn, int flags, uint64_t *offset,
1281 	int lvl, uint64_t blkfill, uint64_t txg)
1282 {
1283 	dmu_buf_impl_t *db = NULL;
1284 	void *data = NULL;
1285 	uint64_t epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
1286 	uint64_t epb = 1ULL << epbs;
1287 	uint64_t minfill, maxfill;
1288 	boolean_t hole;
1289 	int i, inc, error, span;
1290 
1291 	dprintf("probing object %llu offset %llx level %d of %u\n",
1292 	    dn->dn_object, *offset, lvl, dn->dn_phys->dn_nlevels);
1293 
1294 	hole = ((flags & DNODE_FIND_HOLE) != 0);
1295 	inc = (flags & DNODE_FIND_BACKWARDS) ? -1 : 1;
1296 	ASSERT(txg == 0 || !hole);
1297 
1298 	if (lvl == dn->dn_phys->dn_nlevels) {
1299 		error = 0;
1300 		epb = dn->dn_phys->dn_nblkptr;
1301 		data = dn->dn_phys->dn_blkptr;
1302 	} else {
1303 		uint64_t blkid = dbuf_whichblock(dn, *offset) >> (epbs * lvl);
1304 		error = dbuf_hold_impl(dn, lvl, blkid, TRUE, FTAG, &db);
1305 		if (error) {
1306 			if (error != ENOENT)
1307 				return (error);
1308 			if (hole)
1309 				return (0);
1310 			/*
1311 			 * This can only happen when we are searching up
1312 			 * the block tree for data.  We don't really need to
1313 			 * adjust the offset, as we will just end up looking
1314 			 * at the pointer to this block in its parent, and its
1315 			 * going to be unallocated, so we will skip over it.
1316 			 */
1317 			return (ESRCH);
1318 		}
1319 		error = dbuf_read(db, NULL, DB_RF_CANFAIL | DB_RF_HAVESTRUCT);
1320 		if (error) {
1321 			dbuf_rele(db, FTAG);
1322 			return (error);
1323 		}
1324 		data = db->db.db_data;
1325 	}
1326 
1327 	if (db && txg &&
1328 	    (db->db_blkptr == NULL || db->db_blkptr->blk_birth <= txg)) {
1329 		/*
1330 		 * This can only happen when we are searching up the tree
1331 		 * and these conditions mean that we need to keep climbing.
1332 		 */
1333 		error = ESRCH;
1334 	} else if (lvl == 0) {
1335 		dnode_phys_t *dnp = data;
1336 		span = DNODE_SHIFT;
1337 		ASSERT(dn->dn_type == DMU_OT_DNODE);
1338 
1339 		for (i = (*offset >> span) & (blkfill - 1);
1340 		    i >= 0 && i < blkfill; i += inc) {
1341 			if ((dnp[i].dn_type == DMU_OT_NONE) == hole)
1342 				break;
1343 			*offset += (1ULL << span) * inc;
1344 		}
1345 		if (i < 0 || i == blkfill)
1346 			error = ESRCH;
1347 	} else {
1348 		blkptr_t *bp = data;
1349 		uint64_t start = *offset;
1350 		span = (lvl - 1) * epbs + dn->dn_datablkshift;
1351 		minfill = 0;
1352 		maxfill = blkfill << ((lvl - 1) * epbs);
1353 
1354 		if (hole)
1355 			maxfill--;
1356 		else
1357 			minfill++;
1358 
1359 		*offset = *offset >> span;
1360 		for (i = BF64_GET(*offset, 0, epbs);
1361 		    i >= 0 && i < epb; i += inc) {
1362 			if (bp[i].blk_fill >= minfill &&
1363 			    bp[i].blk_fill <= maxfill &&
1364 			    (hole || bp[i].blk_birth > txg))
1365 				break;
1366 			if (inc > 0 || *offset > 0)
1367 				*offset += inc;
1368 		}
1369 		*offset = *offset << span;
1370 		if (inc < 0) {
1371 			/* traversing backwards; position offset at the end */
1372 			ASSERT3U(*offset, <=, start);
1373 			*offset = MIN(*offset + (1ULL << span) - 1, start);
1374 		} else if (*offset < start) {
1375 			*offset = start;
1376 		}
1377 		if (i < 0 || i >= epb)
1378 			error = ESRCH;
1379 	}
1380 
1381 	if (db)
1382 		dbuf_rele(db, FTAG);
1383 
1384 	return (error);
1385 }
1386 
1387 /*
1388  * Find the next hole, data, or sparse region at or after *offset.
1389  * The value 'blkfill' tells us how many items we expect to find
1390  * in an L0 data block; this value is 1 for normal objects,
1391  * DNODES_PER_BLOCK for the meta dnode, and some fraction of
1392  * DNODES_PER_BLOCK when searching for sparse regions thereof.
1393  *
1394  * Examples:
1395  *
1396  * dnode_next_offset(dn, flags, offset, 1, 1, 0);
1397  *	Finds the next/previous hole/data in a file.
1398  *	Used in dmu_offset_next().
1399  *
1400  * dnode_next_offset(mdn, flags, offset, 0, DNODES_PER_BLOCK, txg);
1401  *	Finds the next free/allocated dnode an objset's meta-dnode.
1402  *	Only finds objects that have new contents since txg (ie.
1403  *	bonus buffer changes and content removal are ignored).
1404  *	Used in dmu_object_next().
1405  *
1406  * dnode_next_offset(mdn, DNODE_FIND_HOLE, offset, 2, DNODES_PER_BLOCK >> 2, 0);
1407  *	Finds the next L2 meta-dnode bp that's at most 1/4 full.
1408  *	Used in dmu_object_alloc().
1409  */
1410 int
1411 dnode_next_offset(dnode_t *dn, int flags, uint64_t *offset,
1412     int minlvl, uint64_t blkfill, uint64_t txg)
1413 {
1414 	uint64_t initial_offset = *offset;
1415 	int lvl, maxlvl;
1416 	int error = 0;
1417 
1418 	if (!(flags & DNODE_FIND_HAVELOCK))
1419 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
1420 
1421 	if (dn->dn_phys->dn_nlevels == 0) {
1422 		error = ESRCH;
1423 		goto out;
1424 	}
1425 
1426 	if (dn->dn_datablkshift == 0) {
1427 		if (*offset < dn->dn_datablksz) {
1428 			if (flags & DNODE_FIND_HOLE)
1429 				*offset = dn->dn_datablksz;
1430 		} else {
1431 			error = ESRCH;
1432 		}
1433 		goto out;
1434 	}
1435 
1436 	maxlvl = dn->dn_phys->dn_nlevels;
1437 
1438 	for (lvl = minlvl; lvl <= maxlvl; lvl++) {
1439 		error = dnode_next_offset_level(dn,
1440 		    flags, offset, lvl, blkfill, txg);
1441 		if (error != ESRCH)
1442 			break;
1443 	}
1444 
1445 	while (error == 0 && --lvl >= minlvl) {
1446 		error = dnode_next_offset_level(dn,
1447 		    flags, offset, lvl, blkfill, txg);
1448 	}
1449 
1450 	if (error == 0 && (flags & DNODE_FIND_BACKWARDS ?
1451 	    initial_offset < *offset : initial_offset > *offset))
1452 		error = ESRCH;
1453 out:
1454 	if (!(flags & DNODE_FIND_HAVELOCK))
1455 		rw_exit(&dn->dn_struct_rwlock);
1456 
1457 	return (error);
1458 }
1459