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