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