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