xref: /titanic_50/usr/src/uts/common/fs/zfs/dnode.c (revision d73ae94e59c019f5cc3221ee0a0012d02091b40e)
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_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_dbufs[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_dbufs[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 		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 	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 
859 		dn->dn_nlevels = new_nlevels;
860 
861 		ASSERT3U(new_nlevels, >, dn->dn_next_nlevels[txgoff]);
862 		dn->dn_next_nlevels[txgoff] = new_nlevels;
863 
864 		/* Dirty the left indirects.  */
865 		db = dbuf_hold_level(dn, old_nlevels, 0, FTAG);
866 		dbuf_dirty(db, tx);
867 		dbuf_rele(db, FTAG);
868 
869 	}
870 
871 out:
872 	if (drop_struct_lock)
873 		rw_exit(&dn->dn_struct_rwlock);
874 }
875 
876 void
877 dnode_clear_range(dnode_t *dn, uint64_t blkid, uint64_t nblks, dmu_tx_t *tx)
878 {
879 	avl_tree_t *tree = &dn->dn_ranges[tx->tx_txg&TXG_MASK];
880 	avl_index_t where;
881 	free_range_t *rp;
882 	free_range_t rp_tofind;
883 	uint64_t endblk = blkid + nblks;
884 
885 	ASSERT(MUTEX_HELD(&dn->dn_mtx));
886 	ASSERT(nblks <= UINT64_MAX - blkid); /* no overflow */
887 
888 	dprintf_dnode(dn, "blkid=%llu nblks=%llu txg=%llu\n",
889 	    blkid, nblks, tx->tx_txg);
890 	rp_tofind.fr_blkid = blkid;
891 	rp = avl_find(tree, &rp_tofind, &where);
892 	if (rp == NULL)
893 		rp = avl_nearest(tree, where, AVL_BEFORE);
894 	if (rp == NULL)
895 		rp = avl_nearest(tree, where, AVL_AFTER);
896 
897 	while (rp && (rp->fr_blkid <= blkid + nblks)) {
898 		uint64_t fr_endblk = rp->fr_blkid + rp->fr_nblks;
899 		free_range_t *nrp = AVL_NEXT(tree, rp);
900 
901 		if (blkid <= rp->fr_blkid && endblk >= fr_endblk) {
902 			/* clear this entire range */
903 			avl_remove(tree, rp);
904 			kmem_free(rp, sizeof (free_range_t));
905 		} else if (blkid <= rp->fr_blkid &&
906 		    endblk > rp->fr_blkid && endblk < fr_endblk) {
907 			/* clear the beginning of this range */
908 			rp->fr_blkid = endblk;
909 			rp->fr_nblks = fr_endblk - endblk;
910 		} else if (blkid > rp->fr_blkid && blkid < fr_endblk &&
911 		    endblk >= fr_endblk) {
912 			/* clear the end of this range */
913 			rp->fr_nblks = blkid - rp->fr_blkid;
914 		} else if (blkid > rp->fr_blkid && endblk < fr_endblk) {
915 			/* clear a chunk out of this range */
916 			free_range_t *new_rp =
917 			    kmem_alloc(sizeof (free_range_t), KM_SLEEP);
918 
919 			new_rp->fr_blkid = endblk;
920 			new_rp->fr_nblks = fr_endblk - endblk;
921 			avl_insert_here(tree, new_rp, rp, AVL_AFTER);
922 			rp->fr_nblks = blkid - rp->fr_blkid;
923 		}
924 		/* there may be no overlap */
925 		rp = nrp;
926 	}
927 }
928 
929 void
930 dnode_free_range(dnode_t *dn, uint64_t off, uint64_t len, dmu_tx_t *tx)
931 {
932 	dmu_buf_impl_t *db;
933 	uint64_t blkoff, blkid, nblks;
934 	int blksz, head;
935 	int trunc = FALSE;
936 
937 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
938 	blksz = dn->dn_datablksz;
939 
940 	/* If the range is past the end of the file, this is a no-op */
941 	if (off >= blksz * (dn->dn_maxblkid+1))
942 		goto out;
943 	if (len == -1ULL) {
944 		len = UINT64_MAX - off;
945 		trunc = TRUE;
946 	}
947 
948 	/*
949 	 * First, block align the region to free:
950 	 */
951 	if (ISP2(blksz)) {
952 		head = P2NPHASE(off, blksz);
953 		blkoff = P2PHASE(off, blksz);
954 	} else {
955 		ASSERT(dn->dn_maxblkid == 0);
956 		if (off == 0 && len >= blksz) {
957 			/* Freeing the whole block; don't do any head. */
958 			head = 0;
959 		} else {
960 			/* Freeing part of the block. */
961 			head = blksz - off;
962 			ASSERT3U(head, >, 0);
963 		}
964 		blkoff = off;
965 	}
966 	/* zero out any partial block data at the start of the range */
967 	if (head) {
968 		ASSERT3U(blkoff + head, ==, blksz);
969 		if (len < head)
970 			head = len;
971 		if (dbuf_hold_impl(dn, 0, dbuf_whichblock(dn, off), TRUE,
972 		    FTAG, &db) == 0) {
973 			caddr_t data;
974 
975 			/* don't dirty if it isn't on disk and isn't dirty */
976 			if (db->db_dirtied ||
977 			    (db->db_blkptr && !BP_IS_HOLE(db->db_blkptr))) {
978 				rw_exit(&dn->dn_struct_rwlock);
979 				dbuf_will_dirty(db, tx);
980 				rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
981 				data = db->db.db_data;
982 				bzero(data + blkoff, head);
983 			}
984 			dbuf_rele(db, FTAG);
985 		}
986 		off += head;
987 		len -= head;
988 	}
989 
990 	/* If the range was less than one block, we're done */
991 	if (len == 0 || off >= blksz * (dn->dn_maxblkid+1))
992 		goto out;
993 
994 	if (!ISP2(blksz)) {
995 		/*
996 		 * They are freeing the whole block of a
997 		 * non-power-of-two blocksize file.  Skip all the messy
998 		 * math.
999 		 */
1000 		ASSERT3U(off, ==, 0);
1001 		ASSERT3U(len, >=, blksz);
1002 		blkid = 0;
1003 		nblks = 1;
1004 	} else {
1005 		int tail;
1006 		int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
1007 		int blkshift = dn->dn_datablkshift;
1008 
1009 		/* If the remaining range is past end of file, we're done */
1010 		if (off > dn->dn_maxblkid << blkshift)
1011 			goto out;
1012 
1013 		if (off + len == UINT64_MAX)
1014 			tail = 0;
1015 		else
1016 			tail = P2PHASE(len, blksz);
1017 
1018 		ASSERT3U(P2PHASE(off, blksz), ==, 0);
1019 		/* zero out any partial block data at the end of the range */
1020 		if (tail) {
1021 			if (len < tail)
1022 				tail = len;
1023 			if (dbuf_hold_impl(dn, 0, dbuf_whichblock(dn, off+len),
1024 			    TRUE, FTAG, &db) == 0) {
1025 				/* don't dirty if not on disk and not dirty */
1026 				if (db->db_dirtied ||
1027 				    (db->db_blkptr &&
1028 				    !BP_IS_HOLE(db->db_blkptr))) {
1029 					rw_exit(&dn->dn_struct_rwlock);
1030 					dbuf_will_dirty(db, tx);
1031 					rw_enter(&dn->dn_struct_rwlock,
1032 					    RW_WRITER);
1033 					bzero(db->db.db_data, tail);
1034 				}
1035 				dbuf_rele(db, FTAG);
1036 			}
1037 			len -= tail;
1038 		}
1039 		/* If the range did not include a full block, we are done */
1040 		if (len == 0)
1041 			goto out;
1042 
1043 		/* dirty the left indirects */
1044 		if (dn->dn_nlevels > 1 && off != 0) {
1045 			db = dbuf_hold_level(dn, 1,
1046 			    (off - head) >> (blkshift + epbs), FTAG);
1047 			dbuf_will_dirty(db, tx);
1048 			dbuf_rele(db, FTAG);
1049 		}
1050 
1051 		/* dirty the right indirects */
1052 		if (dn->dn_nlevels > 1 && !trunc) {
1053 			db = dbuf_hold_level(dn, 1,
1054 			    (off + len + tail - 1) >> (blkshift + epbs), FTAG);
1055 			dbuf_will_dirty(db, tx);
1056 			dbuf_rele(db, FTAG);
1057 		}
1058 
1059 		/*
1060 		 * Finally, add this range to the dnode range list, we
1061 		 * will finish up this free operation in the syncing phase.
1062 		 */
1063 		ASSERT(IS_P2ALIGNED(off, 1<<blkshift));
1064 		ASSERT(off + len == UINT64_MAX ||
1065 		    IS_P2ALIGNED(len, 1<<blkshift));
1066 		blkid = off >> blkshift;
1067 		nblks = len >> blkshift;
1068 
1069 		if (trunc)
1070 			dn->dn_maxblkid = (blkid ? blkid - 1 : 0);
1071 	}
1072 
1073 	mutex_enter(&dn->dn_mtx);
1074 	dnode_clear_range(dn, blkid, nblks, tx);
1075 	{
1076 		free_range_t *rp, *found;
1077 		avl_index_t where;
1078 		avl_tree_t *tree = &dn->dn_ranges[tx->tx_txg&TXG_MASK];
1079 
1080 		/* Add new range to dn_ranges */
1081 		rp = kmem_alloc(sizeof (free_range_t), KM_SLEEP);
1082 		rp->fr_blkid = blkid;
1083 		rp->fr_nblks = nblks;
1084 		found = avl_find(tree, rp, &where);
1085 		ASSERT(found == NULL);
1086 		avl_insert(tree, rp, where);
1087 		dprintf_dnode(dn, "blkid=%llu nblks=%llu txg=%llu\n",
1088 		    blkid, nblks, tx->tx_txg);
1089 	}
1090 	mutex_exit(&dn->dn_mtx);
1091 
1092 	dbuf_free_range(dn, blkid, nblks, tx);
1093 	dnode_setdirty(dn, tx);
1094 out:
1095 	rw_exit(&dn->dn_struct_rwlock);
1096 }
1097 
1098 /* return TRUE if this blkid was freed in a recent txg, or FALSE if it wasn't */
1099 uint64_t
1100 dnode_block_freed(dnode_t *dn, uint64_t blkid)
1101 {
1102 	free_range_t range_tofind;
1103 	void *dp = spa_get_dsl(dn->dn_objset->os_spa);
1104 	int i;
1105 
1106 	if (blkid == DB_BONUS_BLKID)
1107 		return (FALSE);
1108 
1109 	/*
1110 	 * If we're in the process of opening the pool, dp will not be
1111 	 * set yet, but there shouldn't be anything dirty.
1112 	 */
1113 	if (dp == NULL)
1114 		return (FALSE);
1115 
1116 	if (dn->dn_free_txg)
1117 		return (TRUE);
1118 
1119 	/*
1120 	 * If dn_datablkshift is not set, then there's only a single
1121 	 * block, in which case there will never be a free range so it
1122 	 * won't matter.
1123 	 */
1124 	range_tofind.fr_blkid = blkid;
1125 	mutex_enter(&dn->dn_mtx);
1126 	for (i = 0; i < TXG_SIZE; i++) {
1127 		free_range_t *range_found;
1128 		avl_index_t idx;
1129 
1130 		range_found = avl_find(&dn->dn_ranges[i], &range_tofind, &idx);
1131 		if (range_found) {
1132 			ASSERT(range_found->fr_nblks > 0);
1133 			break;
1134 		}
1135 		range_found = avl_nearest(&dn->dn_ranges[i], idx, AVL_BEFORE);
1136 		if (range_found &&
1137 		    range_found->fr_blkid + range_found->fr_nblks > blkid)
1138 			break;
1139 	}
1140 	mutex_exit(&dn->dn_mtx);
1141 	return (i < TXG_SIZE);
1142 }
1143 
1144 /* call from syncing context when we actually write/free space for this dnode */
1145 void
1146 dnode_diduse_space(dnode_t *dn, int64_t delta)
1147 {
1148 	uint64_t space;
1149 	dprintf_dnode(dn, "dn=%p dnp=%p used=%llu delta=%lld\n",
1150 	    dn, dn->dn_phys,
1151 	    (u_longlong_t)dn->dn_phys->dn_used,
1152 	    (longlong_t)delta);
1153 
1154 	mutex_enter(&dn->dn_mtx);
1155 	space = DN_USED_BYTES(dn->dn_phys);
1156 	if (delta > 0) {
1157 		ASSERT3U(space + delta, >=, space); /* no overflow */
1158 	} else {
1159 		ASSERT3U(space, >=, -delta); /* no underflow */
1160 	}
1161 	space += delta;
1162 	if (spa_version(dn->dn_objset->os_spa) < ZFS_VERSION_DNODE_BYTES) {
1163 		ASSERT((dn->dn_phys->dn_flags & DNODE_FLAG_USED_BYTES) == 0);
1164 		ASSERT3U(P2PHASE(space, 1<<DEV_BSHIFT), ==, 0);
1165 		dn->dn_phys->dn_used = space >> DEV_BSHIFT;
1166 	} else {
1167 		dn->dn_phys->dn_used = space;
1168 		dn->dn_phys->dn_flags |= DNODE_FLAG_USED_BYTES;
1169 	}
1170 	mutex_exit(&dn->dn_mtx);
1171 }
1172 
1173 /*
1174  * Call when we think we're going to write/free space in open context.
1175  * Be conservative (ie. OK to write less than this or free more than
1176  * this, but don't write more or free less).
1177  */
1178 void
1179 dnode_willuse_space(dnode_t *dn, int64_t space, dmu_tx_t *tx)
1180 {
1181 	objset_impl_t *os = dn->dn_objset;
1182 	dsl_dataset_t *ds = os->os_dsl_dataset;
1183 
1184 	if (space > 0)
1185 		space = spa_get_asize(os->os_spa, space);
1186 
1187 	if (ds)
1188 		dsl_dir_willuse_space(ds->ds_dir, space, tx);
1189 
1190 	dmu_tx_willuse_space(tx, space);
1191 }
1192 
1193 static int
1194 dnode_next_offset_level(dnode_t *dn, boolean_t hole, uint64_t *offset,
1195 	int lvl, uint64_t blkfill, uint64_t txg)
1196 {
1197 	dmu_buf_impl_t *db = NULL;
1198 	void *data = NULL;
1199 	uint64_t epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
1200 	uint64_t epb = 1ULL << epbs;
1201 	uint64_t minfill, maxfill;
1202 	int i, error, span;
1203 
1204 	dprintf("probing object %llu offset %llx level %d of %u\n",
1205 	    dn->dn_object, *offset, lvl, dn->dn_phys->dn_nlevels);
1206 
1207 	if (lvl == dn->dn_phys->dn_nlevels) {
1208 		error = 0;
1209 		epb = dn->dn_phys->dn_nblkptr;
1210 		data = dn->dn_phys->dn_blkptr;
1211 	} else {
1212 		uint64_t blkid = dbuf_whichblock(dn, *offset) >> (epbs * lvl);
1213 		error = dbuf_hold_impl(dn, lvl, blkid, TRUE, FTAG, &db);
1214 		if (error) {
1215 			if (error == ENOENT)
1216 				return (hole ? 0 : ESRCH);
1217 			return (error);
1218 		}
1219 		error = dbuf_read(db, NULL, DB_RF_CANFAIL | DB_RF_HAVESTRUCT);
1220 		if (error) {
1221 			dbuf_rele(db, FTAG);
1222 			return (error);
1223 		}
1224 		data = db->db.db_data;
1225 	}
1226 
1227 	if (db && txg &&
1228 	    (db->db_blkptr == NULL || db->db_blkptr->blk_birth <= txg)) {
1229 		error = ESRCH;
1230 	} else if (lvl == 0) {
1231 		dnode_phys_t *dnp = data;
1232 		span = DNODE_SHIFT;
1233 		ASSERT(dn->dn_type == DMU_OT_DNODE);
1234 
1235 		for (i = (*offset >> span) & (blkfill - 1); i < blkfill; i++) {
1236 			boolean_t newcontents = B_TRUE;
1237 			if (txg) {
1238 				int j;
1239 				newcontents = B_FALSE;
1240 				for (j = 0; j < dnp[i].dn_nblkptr; j++) {
1241 					if (dnp[i].dn_blkptr[j].blk_birth > txg)
1242 						newcontents = B_TRUE;
1243 				}
1244 			}
1245 			if (!dnp[i].dn_type == hole && newcontents)
1246 				break;
1247 			*offset += 1ULL << span;
1248 		}
1249 		if (i == blkfill)
1250 			error = ESRCH;
1251 	} else {
1252 		blkptr_t *bp = data;
1253 		span = (lvl - 1) * epbs + dn->dn_datablkshift;
1254 		minfill = 0;
1255 		maxfill = blkfill << ((lvl - 1) * epbs);
1256 
1257 		if (hole)
1258 			maxfill--;
1259 		else
1260 			minfill++;
1261 
1262 		for (i = (*offset >> span) & ((1ULL << epbs) - 1);
1263 		    i < epb; i++) {
1264 			if (bp[i].blk_fill >= minfill &&
1265 			    bp[i].blk_fill <= maxfill &&
1266 			    bp[i].blk_birth > txg)
1267 				break;
1268 			*offset += 1ULL << span;
1269 		}
1270 		if (i >= epb)
1271 			error = ESRCH;
1272 	}
1273 
1274 	if (db)
1275 		dbuf_rele(db, FTAG);
1276 
1277 	return (error);
1278 }
1279 
1280 /*
1281  * Find the next hole, data, or sparse region at or after *offset.
1282  * The value 'blkfill' tells us how many items we expect to find
1283  * in an L0 data block; this value is 1 for normal objects,
1284  * DNODES_PER_BLOCK for the meta dnode, and some fraction of
1285  * DNODES_PER_BLOCK when searching for sparse regions thereof.
1286  *
1287  * Examples:
1288  *
1289  * dnode_next_offset(dn, hole, offset, 1, 1, 0);
1290  *	Finds the next hole/data in a file.
1291  *	Used in dmu_offset_next().
1292  *
1293  * dnode_next_offset(mdn, hole, offset, 0, DNODES_PER_BLOCK, txg);
1294  *	Finds the next free/allocated dnode an objset's meta-dnode.
1295  *	Only finds objects that have new contents since txg (ie.
1296  *	bonus buffer changes and content removal are ignored).
1297  *	Used in dmu_object_next().
1298  *
1299  * dnode_next_offset(mdn, TRUE, offset, 2, DNODES_PER_BLOCK >> 2, 0);
1300  *	Finds the next L2 meta-dnode bp that's at most 1/4 full.
1301  *	Used in dmu_object_alloc().
1302  */
1303 int
1304 dnode_next_offset(dnode_t *dn, boolean_t hole, uint64_t *offset,
1305     int minlvl, uint64_t blkfill, uint64_t txg)
1306 {
1307 	int lvl, maxlvl;
1308 	int error = 0;
1309 	uint64_t initial_offset = *offset;
1310 
1311 	rw_enter(&dn->dn_struct_rwlock, RW_READER);
1312 
1313 	if (dn->dn_phys->dn_nlevels == 0) {
1314 		rw_exit(&dn->dn_struct_rwlock);
1315 		return (ESRCH);
1316 	}
1317 
1318 	if (dn->dn_datablkshift == 0) {
1319 		if (*offset < dn->dn_datablksz) {
1320 			if (hole)
1321 				*offset = dn->dn_datablksz;
1322 		} else {
1323 			error = ESRCH;
1324 		}
1325 		rw_exit(&dn->dn_struct_rwlock);
1326 		return (error);
1327 	}
1328 
1329 	maxlvl = dn->dn_phys->dn_nlevels;
1330 
1331 	for (lvl = minlvl; lvl <= maxlvl; lvl++) {
1332 		error = dnode_next_offset_level(dn,
1333 		    hole, offset, lvl, blkfill, txg);
1334 		if (error != ESRCH)
1335 			break;
1336 	}
1337 
1338 	while (--lvl >= minlvl && error == 0) {
1339 		error = dnode_next_offset_level(dn,
1340 		    hole, offset, lvl, blkfill, txg);
1341 	}
1342 
1343 	rw_exit(&dn->dn_struct_rwlock);
1344 
1345 	if (error == 0 && initial_offset > *offset)
1346 		error = ESRCH;
1347 
1348 	return (error);
1349 }
1350