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