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