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