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