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