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