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