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