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  * Copyright (c) 2012, 2017 by Delphix. All rights reserved.
24  * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
25  * Copyright (c) 2014 Integros [integros.com]
26  * Copyright 2017 RackTop Systems.
27  */
28 
29 #include <sys/zfs_context.h>
30 #include <sys/dbuf.h>
31 #include <sys/dnode.h>
32 #include <sys/dmu.h>
33 #include <sys/dmu_impl.h>
34 #include <sys/dmu_tx.h>
35 #include <sys/dmu_objset.h>
36 #include <sys/dsl_dir.h>
37 #include <sys/dsl_dataset.h>
38 #include <sys/spa.h>
39 #include <sys/zio.h>
40 #include <sys/dmu_zfetch.h>
41 #include <sys/range_tree.h>
42 
43 static kmem_cache_t *dnode_cache;
44 /*
45  * Define DNODE_STATS to turn on statistic gathering. By default, it is only
46  * turned on when DEBUG is also defined.
47  */
48 #ifdef	DEBUG
49 #define	DNODE_STATS
50 #endif	/* DEBUG */
51 
52 #ifdef	DNODE_STATS
53 #define	DNODE_STAT_ADD(stat)			((stat)++)
54 #else
55 #define	DNODE_STAT_ADD(stat)			/* nothing */
56 #endif	/* DNODE_STATS */
57 
58 static dnode_phys_t dnode_phys_zero;
59 
60 int zfs_default_bs = SPA_MINBLOCKSHIFT;
61 int zfs_default_ibs = DN_MAX_INDBLKSHIFT;
62 
63 SYSCTL_DECL(_vfs_zfs);
64 SYSCTL_INT(_vfs_zfs, OID_AUTO, default_bs, CTLFLAG_RWTUN,
65     &zfs_default_bs, 0, "Default dnode block shift");
66 SYSCTL_INT(_vfs_zfs, OID_AUTO, default_ibs, CTLFLAG_RWTUN,
67     &zfs_default_ibs, 0, "Default dnode indirect block shift");
68 
69 #ifdef illumos
70 #ifdef	_KERNEL
71 static kmem_cbrc_t dnode_move(void *, void *, size_t, void *);
72 #endif	/* _KERNEL */
73 #endif
74 
75 static int
dbuf_compare(const void * x1,const void * x2)76 dbuf_compare(const void *x1, const void *x2)
77 {
78 	const dmu_buf_impl_t *d1 = x1;
79 	const dmu_buf_impl_t *d2 = x2;
80 
81 	int cmp = AVL_CMP(d1->db_level, d2->db_level);
82 	if (likely(cmp))
83 		return (cmp);
84 
85 	cmp = AVL_CMP(d1->db_blkid, d2->db_blkid);
86 	if (likely(cmp))
87 		return (cmp);
88 
89 	if (d1->db_state == DB_SEARCH) {
90 		ASSERT3S(d2->db_state, !=, DB_SEARCH);
91 		return (-1);
92 	} else if (d2->db_state == DB_SEARCH) {
93 		ASSERT3S(d1->db_state, !=, DB_SEARCH);
94 		return (1);
95 	}
96 
97 	return (AVL_PCMP(d1, d2));
98 }
99 
100 /* ARGSUSED */
101 static int
dnode_cons(void * arg,void * unused,int kmflag)102 dnode_cons(void *arg, void *unused, int kmflag)
103 {
104 	dnode_t *dn = arg;
105 	int i;
106 
107 	rw_init(&dn->dn_struct_rwlock, NULL, RW_DEFAULT, NULL);
108 	mutex_init(&dn->dn_mtx, NULL, MUTEX_DEFAULT, NULL);
109 	mutex_init(&dn->dn_dbufs_mtx, NULL, MUTEX_DEFAULT, NULL);
110 	cv_init(&dn->dn_notxholds, NULL, CV_DEFAULT, NULL);
111 
112 	/*
113 	 * Every dbuf has a reference, and dropping a tracked reference is
114 	 * O(number of references), so don't track dn_holds.
115 	 */
116 	refcount_create_untracked(&dn->dn_holds);
117 	refcount_create(&dn->dn_tx_holds);
118 	list_link_init(&dn->dn_link);
119 
120 	bzero(&dn->dn_next_nblkptr[0], sizeof (dn->dn_next_nblkptr));
121 	bzero(&dn->dn_next_nlevels[0], sizeof (dn->dn_next_nlevels));
122 	bzero(&dn->dn_next_indblkshift[0], sizeof (dn->dn_next_indblkshift));
123 	bzero(&dn->dn_next_bonustype[0], sizeof (dn->dn_next_bonustype));
124 	bzero(&dn->dn_rm_spillblk[0], sizeof (dn->dn_rm_spillblk));
125 	bzero(&dn->dn_next_bonuslen[0], sizeof (dn->dn_next_bonuslen));
126 	bzero(&dn->dn_next_blksz[0], sizeof (dn->dn_next_blksz));
127 
128 	for (i = 0; i < TXG_SIZE; i++) {
129 		list_link_init(&dn->dn_dirty_link[i]);
130 		dn->dn_free_ranges[i] = NULL;
131 		list_create(&dn->dn_dirty_records[i],
132 		    sizeof (dbuf_dirty_record_t),
133 		    offsetof(dbuf_dirty_record_t, dr_dirty_node));
134 	}
135 
136 	dn->dn_allocated_txg = 0;
137 	dn->dn_free_txg = 0;
138 	dn->dn_assigned_txg = 0;
139 	dn->dn_dirtyctx = 0;
140 	dn->dn_dirtyctx_firstset = NULL;
141 	dn->dn_bonus = NULL;
142 	dn->dn_have_spill = B_FALSE;
143 	dn->dn_zio = NULL;
144 	dn->dn_oldused = 0;
145 	dn->dn_oldflags = 0;
146 	dn->dn_olduid = 0;
147 	dn->dn_oldgid = 0;
148 	dn->dn_newuid = 0;
149 	dn->dn_newgid = 0;
150 	dn->dn_id_flags = 0;
151 
152 	dn->dn_dbufs_count = 0;
153 	avl_create(&dn->dn_dbufs, dbuf_compare, sizeof (dmu_buf_impl_t),
154 	    offsetof(dmu_buf_impl_t, db_link));
155 
156 	dn->dn_moved = 0;
157 	POINTER_INVALIDATE(&dn->dn_objset);
158 	return (0);
159 }
160 
161 /* ARGSUSED */
162 static void
dnode_dest(void * arg,void * unused)163 dnode_dest(void *arg, void *unused)
164 {
165 	int i;
166 	dnode_t *dn = arg;
167 
168 	rw_destroy(&dn->dn_struct_rwlock);
169 	mutex_destroy(&dn->dn_mtx);
170 	mutex_destroy(&dn->dn_dbufs_mtx);
171 	cv_destroy(&dn->dn_notxholds);
172 	refcount_destroy(&dn->dn_holds);
173 	refcount_destroy(&dn->dn_tx_holds);
174 	ASSERT(!list_link_active(&dn->dn_link));
175 
176 	for (i = 0; i < TXG_SIZE; i++) {
177 		ASSERT(!list_link_active(&dn->dn_dirty_link[i]));
178 		ASSERT3P(dn->dn_free_ranges[i], ==, NULL);
179 		list_destroy(&dn->dn_dirty_records[i]);
180 		ASSERT0(dn->dn_next_nblkptr[i]);
181 		ASSERT0(dn->dn_next_nlevels[i]);
182 		ASSERT0(dn->dn_next_indblkshift[i]);
183 		ASSERT0(dn->dn_next_bonustype[i]);
184 		ASSERT0(dn->dn_rm_spillblk[i]);
185 		ASSERT0(dn->dn_next_bonuslen[i]);
186 		ASSERT0(dn->dn_next_blksz[i]);
187 	}
188 
189 	ASSERT0(dn->dn_allocated_txg);
190 	ASSERT0(dn->dn_free_txg);
191 	ASSERT0(dn->dn_assigned_txg);
192 	ASSERT0(dn->dn_dirtyctx);
193 	ASSERT3P(dn->dn_dirtyctx_firstset, ==, NULL);
194 	ASSERT3P(dn->dn_bonus, ==, NULL);
195 	ASSERT(!dn->dn_have_spill);
196 	ASSERT3P(dn->dn_zio, ==, NULL);
197 	ASSERT0(dn->dn_oldused);
198 	ASSERT0(dn->dn_oldflags);
199 	ASSERT0(dn->dn_olduid);
200 	ASSERT0(dn->dn_oldgid);
201 	ASSERT0(dn->dn_newuid);
202 	ASSERT0(dn->dn_newgid);
203 	ASSERT0(dn->dn_id_flags);
204 
205 	ASSERT0(dn->dn_dbufs_count);
206 	avl_destroy(&dn->dn_dbufs);
207 }
208 
209 void
dnode_init(void)210 dnode_init(void)
211 {
212 	ASSERT(dnode_cache == NULL);
213 	dnode_cache = kmem_cache_create("dnode_t",
214 	    sizeof (dnode_t),
215 	    0, dnode_cons, dnode_dest, NULL, NULL, NULL, 0);
216 #ifdef	_KERNEL
217 	kmem_cache_set_move(dnode_cache, dnode_move);
218 #endif	/* _KERNEL */
219 }
220 
221 void
dnode_fini(void)222 dnode_fini(void)
223 {
224 	kmem_cache_destroy(dnode_cache);
225 	dnode_cache = NULL;
226 }
227 
228 
229 #ifdef ZFS_DEBUG
230 void
dnode_verify(dnode_t * dn)231 dnode_verify(dnode_t *dn)
232 {
233 	int drop_struct_lock = FALSE;
234 
235 	ASSERT(dn->dn_phys);
236 	ASSERT(dn->dn_objset);
237 	ASSERT(dn->dn_handle->dnh_dnode == dn);
238 
239 	ASSERT(DMU_OT_IS_VALID(dn->dn_phys->dn_type));
240 
241 	if (!(zfs_flags & ZFS_DEBUG_DNODE_VERIFY))
242 		return;
243 
244 	if (!RW_WRITE_HELD(&dn->dn_struct_rwlock)) {
245 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
246 		drop_struct_lock = TRUE;
247 	}
248 	if (dn->dn_phys->dn_type != DMU_OT_NONE || dn->dn_allocated_txg != 0) {
249 		int i;
250 		int max_bonuslen = DN_SLOTS_TO_BONUSLEN(dn->dn_num_slots);
251 		ASSERT3U(dn->dn_indblkshift, >=, 0);
252 		ASSERT3U(dn->dn_indblkshift, <=, SPA_MAXBLOCKSHIFT);
253 		if (dn->dn_datablkshift) {
254 			ASSERT3U(dn->dn_datablkshift, >=, SPA_MINBLOCKSHIFT);
255 			ASSERT3U(dn->dn_datablkshift, <=, SPA_MAXBLOCKSHIFT);
256 			ASSERT3U(1<<dn->dn_datablkshift, ==, dn->dn_datablksz);
257 		}
258 		ASSERT3U(dn->dn_nlevels, <=, 30);
259 		ASSERT(DMU_OT_IS_VALID(dn->dn_type));
260 		ASSERT3U(dn->dn_nblkptr, >=, 1);
261 		ASSERT3U(dn->dn_nblkptr, <=, DN_MAX_NBLKPTR);
262 		ASSERT3U(dn->dn_bonuslen, <=, max_bonuslen);
263 		ASSERT3U(dn->dn_datablksz, ==,
264 		    dn->dn_datablkszsec << SPA_MINBLOCKSHIFT);
265 		ASSERT3U(ISP2(dn->dn_datablksz), ==, dn->dn_datablkshift != 0);
266 		ASSERT3U((dn->dn_nblkptr - 1) * sizeof (blkptr_t) +
267 		    dn->dn_bonuslen, <=, max_bonuslen);
268 		for (i = 0; i < TXG_SIZE; i++) {
269 			ASSERT3U(dn->dn_next_nlevels[i], <=, dn->dn_nlevels);
270 		}
271 	}
272 	if (dn->dn_phys->dn_type != DMU_OT_NONE)
273 		ASSERT3U(dn->dn_phys->dn_nlevels, <=, dn->dn_nlevels);
274 	ASSERT(DMU_OBJECT_IS_SPECIAL(dn->dn_object) || dn->dn_dbuf != NULL);
275 	if (dn->dn_dbuf != NULL) {
276 		ASSERT3P(dn->dn_phys, ==,
277 		    (dnode_phys_t *)dn->dn_dbuf->db.db_data +
278 		    (dn->dn_object % (dn->dn_dbuf->db.db_size >> DNODE_SHIFT)));
279 	}
280 	if (drop_struct_lock)
281 		rw_exit(&dn->dn_struct_rwlock);
282 }
283 #endif
284 
285 void
dnode_byteswap(dnode_phys_t * dnp)286 dnode_byteswap(dnode_phys_t *dnp)
287 {
288 	uint64_t *buf64 = (void*)&dnp->dn_blkptr;
289 	int i;
290 
291 	if (dnp->dn_type == DMU_OT_NONE) {
292 		bzero(dnp, sizeof (dnode_phys_t));
293 		return;
294 	}
295 
296 	dnp->dn_datablkszsec = BSWAP_16(dnp->dn_datablkszsec);
297 	dnp->dn_bonuslen = BSWAP_16(dnp->dn_bonuslen);
298 	dnp->dn_extra_slots = BSWAP_8(dnp->dn_extra_slots);
299 	dnp->dn_maxblkid = BSWAP_64(dnp->dn_maxblkid);
300 	dnp->dn_used = BSWAP_64(dnp->dn_used);
301 
302 	/*
303 	 * dn_nblkptr is only one byte, so it's OK to read it in either
304 	 * byte order.  We can't read dn_bouslen.
305 	 */
306 	ASSERT(dnp->dn_indblkshift <= SPA_MAXBLOCKSHIFT);
307 	ASSERT(dnp->dn_nblkptr <= DN_MAX_NBLKPTR);
308 	for (i = 0; i < dnp->dn_nblkptr * sizeof (blkptr_t)/8; i++)
309 		buf64[i] = BSWAP_64(buf64[i]);
310 
311 	/*
312 	 * OK to check dn_bonuslen for zero, because it won't matter if
313 	 * we have the wrong byte order.  This is necessary because the
314 	 * dnode dnode is smaller than a regular dnode.
315 	 */
316 	if (dnp->dn_bonuslen != 0) {
317 		/*
318 		 * Note that the bonus length calculated here may be
319 		 * longer than the actual bonus buffer.  This is because
320 		 * we always put the bonus buffer after the last block
321 		 * pointer (instead of packing it against the end of the
322 		 * dnode buffer).
323 		 */
324 		int off = (dnp->dn_nblkptr-1) * sizeof (blkptr_t);
325 		int slots = dnp->dn_extra_slots + 1;
326 		size_t len = DN_SLOTS_TO_BONUSLEN(slots) - off;
327 		ASSERT(DMU_OT_IS_VALID(dnp->dn_bonustype));
328 		dmu_object_byteswap_t byteswap =
329 		    DMU_OT_BYTESWAP(dnp->dn_bonustype);
330 		dmu_ot_byteswap[byteswap].ob_func(dnp->dn_bonus + off, len);
331 	}
332 
333 	/* Swap SPILL block if we have one */
334 	if (dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR)
335 		byteswap_uint64_array(DN_SPILL_BLKPTR(dnp), sizeof (blkptr_t));
336 }
337 
338 void
dnode_buf_byteswap(void * vbuf,size_t size)339 dnode_buf_byteswap(void *vbuf, size_t size)
340 {
341 	int i = 0;
342 
343 	ASSERT3U(sizeof (dnode_phys_t), ==, (1<<DNODE_SHIFT));
344 	ASSERT((size & (sizeof (dnode_phys_t)-1)) == 0);
345 
346 	while (i < size) {
347 		dnode_phys_t *dnp = vbuf + i;
348 		dnode_byteswap(dnp);
349 
350 		i += DNODE_MIN_SIZE;
351 		if (dnp->dn_type != DMU_OT_NONE)
352 			i += dnp->dn_extra_slots * DNODE_MIN_SIZE;
353 	}
354 }
355 
356 void
dnode_setbonuslen(dnode_t * dn,int newsize,dmu_tx_t * tx)357 dnode_setbonuslen(dnode_t *dn, int newsize, dmu_tx_t *tx)
358 {
359 	ASSERT3U(refcount_count(&dn->dn_holds), >=, 1);
360 
361 	dnode_setdirty(dn, tx);
362 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
363 	ASSERT3U(newsize, <=, DN_SLOTS_TO_BONUSLEN(dn->dn_num_slots) -
364 	    (dn->dn_nblkptr-1) * sizeof (blkptr_t));
365 	dn->dn_bonuslen = newsize;
366 	if (newsize == 0)
367 		dn->dn_next_bonuslen[tx->tx_txg & TXG_MASK] = DN_ZERO_BONUSLEN;
368 	else
369 		dn->dn_next_bonuslen[tx->tx_txg & TXG_MASK] = dn->dn_bonuslen;
370 	rw_exit(&dn->dn_struct_rwlock);
371 }
372 
373 void
dnode_setbonus_type(dnode_t * dn,dmu_object_type_t newtype,dmu_tx_t * tx)374 dnode_setbonus_type(dnode_t *dn, dmu_object_type_t newtype, dmu_tx_t *tx)
375 {
376 	ASSERT3U(refcount_count(&dn->dn_holds), >=, 1);
377 	dnode_setdirty(dn, tx);
378 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
379 	dn->dn_bonustype = newtype;
380 	dn->dn_next_bonustype[tx->tx_txg & TXG_MASK] = dn->dn_bonustype;
381 	rw_exit(&dn->dn_struct_rwlock);
382 }
383 
384 void
dnode_rm_spill(dnode_t * dn,dmu_tx_t * tx)385 dnode_rm_spill(dnode_t *dn, dmu_tx_t *tx)
386 {
387 	ASSERT3U(refcount_count(&dn->dn_holds), >=, 1);
388 	ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
389 	dnode_setdirty(dn, tx);
390 	dn->dn_rm_spillblk[tx->tx_txg&TXG_MASK] = DN_KILL_SPILLBLK;
391 	dn->dn_have_spill = B_FALSE;
392 }
393 
394 static void
dnode_setdblksz(dnode_t * dn,int size)395 dnode_setdblksz(dnode_t *dn, int size)
396 {
397 	ASSERT0(P2PHASE(size, SPA_MINBLOCKSIZE));
398 	ASSERT3U(size, <=, SPA_MAXBLOCKSIZE);
399 	ASSERT3U(size, >=, SPA_MINBLOCKSIZE);
400 	ASSERT3U(size >> SPA_MINBLOCKSHIFT, <,
401 	    1<<(sizeof (dn->dn_phys->dn_datablkszsec) * 8));
402 	dn->dn_datablksz = size;
403 	dn->dn_datablkszsec = size >> SPA_MINBLOCKSHIFT;
404 	dn->dn_datablkshift = ISP2(size) ? highbit64(size - 1) : 0;
405 }
406 
407 static dnode_t *
dnode_create(objset_t * os,dnode_phys_t * dnp,dmu_buf_impl_t * db,uint64_t object,dnode_handle_t * dnh)408 dnode_create(objset_t *os, dnode_phys_t *dnp, dmu_buf_impl_t *db,
409     uint64_t object, dnode_handle_t *dnh)
410 {
411 	dnode_t *dn;
412 
413 	dn = kmem_cache_alloc(dnode_cache, KM_SLEEP);
414 #ifdef _KERNEL
415 	ASSERT(!POINTER_IS_VALID(dn->dn_objset));
416 #endif /* _KERNEL */
417 	dn->dn_moved = 0;
418 
419 	/*
420 	 * Defer setting dn_objset until the dnode is ready to be a candidate
421 	 * for the dnode_move() callback.
422 	 */
423 	dn->dn_object = object;
424 	dn->dn_dbuf = db;
425 	dn->dn_handle = dnh;
426 	dn->dn_phys = dnp;
427 
428 	if (dnp->dn_datablkszsec) {
429 		dnode_setdblksz(dn, dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT);
430 	} else {
431 		dn->dn_datablksz = 0;
432 		dn->dn_datablkszsec = 0;
433 		dn->dn_datablkshift = 0;
434 	}
435 	dn->dn_indblkshift = dnp->dn_indblkshift;
436 	dn->dn_nlevels = dnp->dn_nlevels;
437 	dn->dn_type = dnp->dn_type;
438 	dn->dn_nblkptr = dnp->dn_nblkptr;
439 	dn->dn_checksum = dnp->dn_checksum;
440 	dn->dn_compress = dnp->dn_compress;
441 	dn->dn_bonustype = dnp->dn_bonustype;
442 	dn->dn_bonuslen = dnp->dn_bonuslen;
443 	dn->dn_num_slots = dnp->dn_extra_slots + 1;
444 	dn->dn_maxblkid = dnp->dn_maxblkid;
445 	dn->dn_have_spill = ((dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR) != 0);
446 	dn->dn_id_flags = 0;
447 
448 	dmu_zfetch_init(&dn->dn_zfetch, dn);
449 
450 	ASSERT(DMU_OT_IS_VALID(dn->dn_phys->dn_type));
451 
452 	mutex_enter(&os->os_lock);
453 	if (dnh->dnh_dnode != NULL) {
454 		/* Lost the allocation race. */
455 		mutex_exit(&os->os_lock);
456 		kmem_cache_free(dnode_cache, dn);
457 		return (dnh->dnh_dnode);
458 	}
459 
460 	/*
461 	 * Exclude special dnodes from os_dnodes so an empty os_dnodes
462 	 * signifies that the special dnodes have no references from
463 	 * their children (the entries in os_dnodes).  This allows
464 	 * dnode_destroy() to easily determine if the last child has
465 	 * been removed and then complete eviction of the objset.
466 	 */
467 	if (!DMU_OBJECT_IS_SPECIAL(object))
468 		list_insert_head(&os->os_dnodes, dn);
469 	membar_producer();
470 
471 	/*
472 	 * Everything else must be valid before assigning dn_objset
473 	 * makes the dnode eligible for dnode_move().
474 	 */
475 	dn->dn_objset = os;
476 
477 	dnh->dnh_dnode = dn;
478 	mutex_exit(&os->os_lock);
479 
480 	arc_space_consume(sizeof (dnode_t), ARC_SPACE_DNODE);
481 	return (dn);
482 }
483 
484 /*
485  * Caller must be holding the dnode handle, which is released upon return.
486  */
487 static void
dnode_destroy(dnode_t * dn)488 dnode_destroy(dnode_t *dn)
489 {
490 	objset_t *os = dn->dn_objset;
491 	boolean_t complete_os_eviction = B_FALSE;
492 
493 	ASSERT((dn->dn_id_flags & DN_ID_NEW_EXIST) == 0);
494 
495 	mutex_enter(&os->os_lock);
496 	POINTER_INVALIDATE(&dn->dn_objset);
497 	if (!DMU_OBJECT_IS_SPECIAL(dn->dn_object)) {
498 		list_remove(&os->os_dnodes, dn);
499 		complete_os_eviction =
500 		    list_is_empty(&os->os_dnodes) &&
501 		    list_link_active(&os->os_evicting_node);
502 	}
503 	mutex_exit(&os->os_lock);
504 
505 	/* the dnode can no longer move, so we can release the handle */
506 	zrl_remove(&dn->dn_handle->dnh_zrlock);
507 
508 	dn->dn_allocated_txg = 0;
509 	dn->dn_free_txg = 0;
510 	dn->dn_assigned_txg = 0;
511 
512 	dn->dn_dirtyctx = 0;
513 	if (dn->dn_dirtyctx_firstset != NULL) {
514 		kmem_free(dn->dn_dirtyctx_firstset, 1);
515 		dn->dn_dirtyctx_firstset = NULL;
516 	}
517 	if (dn->dn_bonus != NULL) {
518 		mutex_enter(&dn->dn_bonus->db_mtx);
519 		dbuf_destroy(dn->dn_bonus);
520 		dn->dn_bonus = NULL;
521 	}
522 	dn->dn_zio = NULL;
523 
524 	dn->dn_have_spill = B_FALSE;
525 	dn->dn_oldused = 0;
526 	dn->dn_oldflags = 0;
527 	dn->dn_olduid = 0;
528 	dn->dn_oldgid = 0;
529 	dn->dn_newuid = 0;
530 	dn->dn_newgid = 0;
531 	dn->dn_id_flags = 0;
532 
533 	dmu_zfetch_fini(&dn->dn_zfetch);
534 	kmem_cache_free(dnode_cache, dn);
535 	arc_space_return(sizeof (dnode_t), ARC_SPACE_DNODE);
536 
537 	if (complete_os_eviction)
538 		dmu_objset_evict_done(os);
539 }
540 
541 void
dnode_allocate(dnode_t * dn,dmu_object_type_t ot,int blocksize,int ibs,dmu_object_type_t bonustype,int bonuslen,int dn_slots,dmu_tx_t * tx)542 dnode_allocate(dnode_t *dn, dmu_object_type_t ot, int blocksize, int ibs,
543     dmu_object_type_t bonustype, int bonuslen, int dn_slots, dmu_tx_t *tx)
544 {
545 	int i;
546 
547 	ASSERT3U(dn_slots, >, 0);
548 	ASSERT3U(dn_slots << DNODE_SHIFT, <=,
549 	    spa_maxdnodesize(dmu_objset_spa(dn->dn_objset)));
550 	ASSERT3U(blocksize, <=,
551 	    spa_maxblocksize(dmu_objset_spa(dn->dn_objset)));
552 	if (blocksize == 0)
553 		blocksize = 1 << zfs_default_bs;
554 	else
555 		blocksize = P2ROUNDUP(blocksize, SPA_MINBLOCKSIZE);
556 
557 	if (ibs == 0)
558 		ibs = zfs_default_ibs;
559 
560 	ibs = MIN(MAX(ibs, DN_MIN_INDBLKSHIFT), DN_MAX_INDBLKSHIFT);
561 
562 	dprintf("os=%p obj=%llu txg=%llu blocksize=%d ibs=%d dn_slots=%d\n",
563 	    dn->dn_objset, dn->dn_object, tx->tx_txg, blocksize, ibs, dn_slots);
564 
565 	ASSERT(dn->dn_type == DMU_OT_NONE);
566 	ASSERT(bcmp(dn->dn_phys, &dnode_phys_zero, sizeof (dnode_phys_t)) == 0);
567 	ASSERT(dn->dn_phys->dn_type == DMU_OT_NONE);
568 	ASSERT(ot != DMU_OT_NONE);
569 	ASSERT(DMU_OT_IS_VALID(ot));
570 	ASSERT((bonustype == DMU_OT_NONE && bonuslen == 0) ||
571 	    (bonustype == DMU_OT_SA && bonuslen == 0) ||
572 	    (bonustype != DMU_OT_NONE && bonuslen != 0));
573 	ASSERT(DMU_OT_IS_VALID(bonustype));
574 	ASSERT3U(bonuslen, <=, DN_SLOTS_TO_BONUSLEN(dn_slots));
575 	ASSERT(dn->dn_type == DMU_OT_NONE);
576 	ASSERT0(dn->dn_maxblkid);
577 	ASSERT0(dn->dn_allocated_txg);
578 	ASSERT0(dn->dn_assigned_txg);
579 	ASSERT(refcount_is_zero(&dn->dn_tx_holds));
580 	ASSERT3U(refcount_count(&dn->dn_holds), <=, 1);
581 	ASSERT(avl_is_empty(&dn->dn_dbufs));
582 
583 	for (i = 0; i < TXG_SIZE; i++) {
584 		ASSERT0(dn->dn_next_nblkptr[i]);
585 		ASSERT0(dn->dn_next_nlevels[i]);
586 		ASSERT0(dn->dn_next_indblkshift[i]);
587 		ASSERT0(dn->dn_next_bonuslen[i]);
588 		ASSERT0(dn->dn_next_bonustype[i]);
589 		ASSERT0(dn->dn_rm_spillblk[i]);
590 		ASSERT0(dn->dn_next_blksz[i]);
591 		ASSERT(!list_link_active(&dn->dn_dirty_link[i]));
592 		ASSERT3P(list_head(&dn->dn_dirty_records[i]), ==, NULL);
593 		ASSERT3P(dn->dn_free_ranges[i], ==, NULL);
594 	}
595 
596 	dn->dn_type = ot;
597 	dnode_setdblksz(dn, blocksize);
598 	dn->dn_indblkshift = ibs;
599 	dn->dn_nlevels = 1;
600 	dn->dn_num_slots = dn_slots;
601 	if (bonustype == DMU_OT_SA) /* Maximize bonus space for SA */
602 		dn->dn_nblkptr = 1;
603 	else {
604 		dn->dn_nblkptr = MIN(DN_MAX_NBLKPTR,
605 		    1 + ((DN_SLOTS_TO_BONUSLEN(dn_slots) - bonuslen) >>
606 		    SPA_BLKPTRSHIFT));
607 	}
608 
609 	dn->dn_bonustype = bonustype;
610 	dn->dn_bonuslen = bonuslen;
611 	dn->dn_checksum = ZIO_CHECKSUM_INHERIT;
612 	dn->dn_compress = ZIO_COMPRESS_INHERIT;
613 	dn->dn_dirtyctx = 0;
614 
615 	dn->dn_free_txg = 0;
616 	if (dn->dn_dirtyctx_firstset) {
617 		kmem_free(dn->dn_dirtyctx_firstset, 1);
618 		dn->dn_dirtyctx_firstset = NULL;
619 	}
620 
621 	dn->dn_allocated_txg = tx->tx_txg;
622 	dn->dn_id_flags = 0;
623 
624 	dnode_setdirty(dn, tx);
625 	dn->dn_next_indblkshift[tx->tx_txg & TXG_MASK] = ibs;
626 	dn->dn_next_bonuslen[tx->tx_txg & TXG_MASK] = dn->dn_bonuslen;
627 	dn->dn_next_bonustype[tx->tx_txg & TXG_MASK] = dn->dn_bonustype;
628 	dn->dn_next_blksz[tx->tx_txg & TXG_MASK] = dn->dn_datablksz;
629 }
630 
631 void
dnode_reallocate(dnode_t * dn,dmu_object_type_t ot,int blocksize,dmu_object_type_t bonustype,int bonuslen,int dn_slots,dmu_tx_t * tx)632 dnode_reallocate(dnode_t *dn, dmu_object_type_t ot, int blocksize,
633     dmu_object_type_t bonustype, int bonuslen, int dn_slots, dmu_tx_t *tx)
634 {
635 	int nblkptr;
636 
637 	ASSERT3U(blocksize, >=, SPA_MINBLOCKSIZE);
638 	ASSERT3U(blocksize, <=,
639 	    spa_maxblocksize(dmu_objset_spa(dn->dn_objset)));
640 	ASSERT0(blocksize % SPA_MINBLOCKSIZE);
641 	ASSERT(dn->dn_object != DMU_META_DNODE_OBJECT || dmu_tx_private_ok(tx));
642 	ASSERT(tx->tx_txg != 0);
643 	ASSERT((bonustype == DMU_OT_NONE && bonuslen == 0) ||
644 	    (bonustype != DMU_OT_NONE && bonuslen != 0) ||
645 	    (bonustype == DMU_OT_SA && bonuslen == 0));
646 	ASSERT(DMU_OT_IS_VALID(bonustype));
647 	ASSERT3U(bonuslen, <=,
648 		DN_BONUS_SIZE(spa_maxdnodesize(dmu_objset_spa(dn->dn_objset))));
649 
650 	dn_slots = dn_slots > 0 ? dn_slots : DNODE_MIN_SLOTS;
651 
652 	/* clean up any unreferenced dbufs */
653 	dnode_evict_dbufs(dn);
654 
655 	dn->dn_id_flags = 0;
656 
657 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
658 	dnode_setdirty(dn, tx);
659 	if (dn->dn_datablksz != blocksize) {
660 		/* change blocksize */
661 		ASSERT(dn->dn_maxblkid == 0 &&
662 		    (BP_IS_HOLE(&dn->dn_phys->dn_blkptr[0]) ||
663 		    dnode_block_freed(dn, 0)));
664 		dnode_setdblksz(dn, blocksize);
665 		dn->dn_next_blksz[tx->tx_txg&TXG_MASK] = blocksize;
666 	}
667 	if (dn->dn_bonuslen != bonuslen)
668 		dn->dn_next_bonuslen[tx->tx_txg&TXG_MASK] = bonuslen;
669 
670 	if (bonustype == DMU_OT_SA) /* Maximize bonus space for SA */
671 		nblkptr = 1;
672 	else
673 		nblkptr = MIN(DN_MAX_NBLKPTR,
674 		    1 + ((DN_SLOTS_TO_BONUSLEN(dn_slots) - bonuslen) >>
675 		    SPA_BLKPTRSHIFT));
676 	if (dn->dn_bonustype != bonustype)
677 		dn->dn_next_bonustype[tx->tx_txg&TXG_MASK] = bonustype;
678 	if (dn->dn_nblkptr != nblkptr)
679 		dn->dn_next_nblkptr[tx->tx_txg&TXG_MASK] = nblkptr;
680 	if (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR) {
681 		dbuf_rm_spill(dn, tx);
682 		dnode_rm_spill(dn, tx);
683 	}
684 	rw_exit(&dn->dn_struct_rwlock);
685 
686 	/* change type */
687 	dn->dn_type = ot;
688 
689 	/* change bonus size and type */
690 	mutex_enter(&dn->dn_mtx);
691 	dn->dn_bonustype = bonustype;
692 	dn->dn_bonuslen = bonuslen;
693 	dn->dn_num_slots = dn_slots;
694 	dn->dn_nblkptr = nblkptr;
695 	dn->dn_checksum = ZIO_CHECKSUM_INHERIT;
696 	dn->dn_compress = ZIO_COMPRESS_INHERIT;
697 	ASSERT3U(dn->dn_nblkptr, <=, DN_MAX_NBLKPTR);
698 
699 	/* fix up the bonus db_size */
700 	if (dn->dn_bonus) {
701 		dn->dn_bonus->db.db_size =
702 		    DN_SLOTS_TO_BONUSLEN(dn->dn_num_slots) -
703 		    (dn->dn_nblkptr-1) * sizeof (blkptr_t);
704 		ASSERT(dn->dn_bonuslen <= dn->dn_bonus->db.db_size);
705 	}
706 
707 	dn->dn_allocated_txg = tx->tx_txg;
708 	mutex_exit(&dn->dn_mtx);
709 }
710 
711 #ifdef	DNODE_STATS
712 static struct {
713 	uint64_t dms_dnode_invalid;
714 	uint64_t dms_dnode_recheck1;
715 	uint64_t dms_dnode_recheck2;
716 	uint64_t dms_dnode_special;
717 	uint64_t dms_dnode_handle;
718 	uint64_t dms_dnode_rwlock;
719 	uint64_t dms_dnode_active;
720 } dnode_move_stats;
721 #endif	/* DNODE_STATS */
722 
723 #ifdef	_KERNEL
724 static void
dnode_move_impl(dnode_t * odn,dnode_t * ndn)725 dnode_move_impl(dnode_t *odn, dnode_t *ndn)
726 {
727 	int i;
728 
729 	ASSERT(!RW_LOCK_HELD(&odn->dn_struct_rwlock));
730 	ASSERT(MUTEX_NOT_HELD(&odn->dn_mtx));
731 	ASSERT(MUTEX_NOT_HELD(&odn->dn_dbufs_mtx));
732 	ASSERT(!RW_LOCK_HELD(&odn->dn_zfetch.zf_rwlock));
733 
734 	/* Copy fields. */
735 	ndn->dn_objset = odn->dn_objset;
736 	ndn->dn_object = odn->dn_object;
737 	ndn->dn_dbuf = odn->dn_dbuf;
738 	ndn->dn_handle = odn->dn_handle;
739 	ndn->dn_phys = odn->dn_phys;
740 	ndn->dn_type = odn->dn_type;
741 	ndn->dn_bonuslen = odn->dn_bonuslen;
742 	ndn->dn_bonustype = odn->dn_bonustype;
743 	ndn->dn_nblkptr = odn->dn_nblkptr;
744 	ndn->dn_checksum = odn->dn_checksum;
745 	ndn->dn_compress = odn->dn_compress;
746 	ndn->dn_nlevels = odn->dn_nlevels;
747 	ndn->dn_indblkshift = odn->dn_indblkshift;
748 	ndn->dn_datablkshift = odn->dn_datablkshift;
749 	ndn->dn_datablkszsec = odn->dn_datablkszsec;
750 	ndn->dn_datablksz = odn->dn_datablksz;
751 	ndn->dn_maxblkid = odn->dn_maxblkid;
752 	bcopy(&odn->dn_next_type[0], &ndn->dn_next_type[0],
753 	    sizeof (odn->dn_next_type));
754 	bcopy(&odn->dn_next_nblkptr[0], &ndn->dn_next_nblkptr[0],
755 	    sizeof (odn->dn_next_nblkptr));
756 	bcopy(&odn->dn_next_nlevels[0], &ndn->dn_next_nlevels[0],
757 	    sizeof (odn->dn_next_nlevels));
758 	bcopy(&odn->dn_next_indblkshift[0], &ndn->dn_next_indblkshift[0],
759 	    sizeof (odn->dn_next_indblkshift));
760 	bcopy(&odn->dn_next_bonustype[0], &ndn->dn_next_bonustype[0],
761 	    sizeof (odn->dn_next_bonustype));
762 	bcopy(&odn->dn_rm_spillblk[0], &ndn->dn_rm_spillblk[0],
763 	    sizeof (odn->dn_rm_spillblk));
764 	bcopy(&odn->dn_next_bonuslen[0], &ndn->dn_next_bonuslen[0],
765 	    sizeof (odn->dn_next_bonuslen));
766 	bcopy(&odn->dn_next_blksz[0], &ndn->dn_next_blksz[0],
767 	    sizeof (odn->dn_next_blksz));
768 	for (i = 0; i < TXG_SIZE; i++) {
769 		list_move_tail(&ndn->dn_dirty_records[i],
770 		    &odn->dn_dirty_records[i]);
771 	}
772 	bcopy(&odn->dn_free_ranges[0], &ndn->dn_free_ranges[0],
773 	    sizeof (odn->dn_free_ranges));
774 	ndn->dn_allocated_txg = odn->dn_allocated_txg;
775 	ndn->dn_free_txg = odn->dn_free_txg;
776 	ndn->dn_assigned_txg = odn->dn_assigned_txg;
777 	ndn->dn_dirtyctx = odn->dn_dirtyctx;
778 	ndn->dn_dirtyctx_firstset = odn->dn_dirtyctx_firstset;
779 	ASSERT(refcount_count(&odn->dn_tx_holds) == 0);
780 	refcount_transfer(&ndn->dn_holds, &odn->dn_holds);
781 	ASSERT(avl_is_empty(&ndn->dn_dbufs));
782 	avl_swap(&ndn->dn_dbufs, &odn->dn_dbufs);
783 	ndn->dn_dbufs_count = odn->dn_dbufs_count;
784 	ndn->dn_bonus = odn->dn_bonus;
785 	ndn->dn_have_spill = odn->dn_have_spill;
786 	ndn->dn_zio = odn->dn_zio;
787 	ndn->dn_oldused = odn->dn_oldused;
788 	ndn->dn_oldflags = odn->dn_oldflags;
789 	ndn->dn_olduid = odn->dn_olduid;
790 	ndn->dn_oldgid = odn->dn_oldgid;
791 	ndn->dn_newuid = odn->dn_newuid;
792 	ndn->dn_newgid = odn->dn_newgid;
793 	ndn->dn_id_flags = odn->dn_id_flags;
794 	dmu_zfetch_init(&ndn->dn_zfetch, NULL);
795 	list_move_tail(&ndn->dn_zfetch.zf_stream, &odn->dn_zfetch.zf_stream);
796 	ndn->dn_zfetch.zf_dnode = odn->dn_zfetch.zf_dnode;
797 
798 	/*
799 	 * Update back pointers. Updating the handle fixes the back pointer of
800 	 * every descendant dbuf as well as the bonus dbuf.
801 	 */
802 	ASSERT(ndn->dn_handle->dnh_dnode == odn);
803 	ndn->dn_handle->dnh_dnode = ndn;
804 	if (ndn->dn_zfetch.zf_dnode == odn) {
805 		ndn->dn_zfetch.zf_dnode = ndn;
806 	}
807 
808 	/*
809 	 * Invalidate the original dnode by clearing all of its back pointers.
810 	 */
811 	odn->dn_dbuf = NULL;
812 	odn->dn_handle = NULL;
813 	avl_create(&odn->dn_dbufs, dbuf_compare, sizeof (dmu_buf_impl_t),
814 	    offsetof(dmu_buf_impl_t, db_link));
815 	odn->dn_dbufs_count = 0;
816 	odn->dn_bonus = NULL;
817 	odn->dn_zfetch.zf_dnode = NULL;
818 
819 	/*
820 	 * Set the low bit of the objset pointer to ensure that dnode_move()
821 	 * recognizes the dnode as invalid in any subsequent callback.
822 	 */
823 	POINTER_INVALIDATE(&odn->dn_objset);
824 
825 	/*
826 	 * Satisfy the destructor.
827 	 */
828 	for (i = 0; i < TXG_SIZE; i++) {
829 		list_create(&odn->dn_dirty_records[i],
830 		    sizeof (dbuf_dirty_record_t),
831 		    offsetof(dbuf_dirty_record_t, dr_dirty_node));
832 		odn->dn_free_ranges[i] = NULL;
833 		odn->dn_next_nlevels[i] = 0;
834 		odn->dn_next_indblkshift[i] = 0;
835 		odn->dn_next_bonustype[i] = 0;
836 		odn->dn_rm_spillblk[i] = 0;
837 		odn->dn_next_bonuslen[i] = 0;
838 		odn->dn_next_blksz[i] = 0;
839 	}
840 	odn->dn_allocated_txg = 0;
841 	odn->dn_free_txg = 0;
842 	odn->dn_assigned_txg = 0;
843 	odn->dn_dirtyctx = 0;
844 	odn->dn_dirtyctx_firstset = NULL;
845 	odn->dn_have_spill = B_FALSE;
846 	odn->dn_zio = NULL;
847 	odn->dn_oldused = 0;
848 	odn->dn_oldflags = 0;
849 	odn->dn_olduid = 0;
850 	odn->dn_oldgid = 0;
851 	odn->dn_newuid = 0;
852 	odn->dn_newgid = 0;
853 	odn->dn_id_flags = 0;
854 
855 	/*
856 	 * Mark the dnode.
857 	 */
858 	ndn->dn_moved = 1;
859 	odn->dn_moved = (uint8_t)-1;
860 }
861 
862 #ifdef illumos
863 /*ARGSUSED*/
864 static kmem_cbrc_t
dnode_move(void * buf,void * newbuf,size_t size,void * arg)865 dnode_move(void *buf, void *newbuf, size_t size, void *arg)
866 {
867 	dnode_t *odn = buf, *ndn = newbuf;
868 	objset_t *os;
869 	int64_t refcount;
870 	uint32_t dbufs;
871 
872 	/*
873 	 * The dnode is on the objset's list of known dnodes if the objset
874 	 * pointer is valid. We set the low bit of the objset pointer when
875 	 * freeing the dnode to invalidate it, and the memory patterns written
876 	 * by kmem (baddcafe and deadbeef) set at least one of the two low bits.
877 	 * A newly created dnode sets the objset pointer last of all to indicate
878 	 * that the dnode is known and in a valid state to be moved by this
879 	 * function.
880 	 */
881 	os = odn->dn_objset;
882 	if (!POINTER_IS_VALID(os)) {
883 		DNODE_STAT_ADD(dnode_move_stats.dms_dnode_invalid);
884 		return (KMEM_CBRC_DONT_KNOW);
885 	}
886 
887 	/*
888 	 * Ensure that the objset does not go away during the move.
889 	 */
890 	rw_enter(&os_lock, RW_WRITER);
891 	if (os != odn->dn_objset) {
892 		rw_exit(&os_lock);
893 		DNODE_STAT_ADD(dnode_move_stats.dms_dnode_recheck1);
894 		return (KMEM_CBRC_DONT_KNOW);
895 	}
896 
897 	/*
898 	 * If the dnode is still valid, then so is the objset. We know that no
899 	 * valid objset can be freed while we hold os_lock, so we can safely
900 	 * ensure that the objset remains in use.
901 	 */
902 	mutex_enter(&os->os_lock);
903 
904 	/*
905 	 * Recheck the objset pointer in case the dnode was removed just before
906 	 * acquiring the lock.
907 	 */
908 	if (os != odn->dn_objset) {
909 		mutex_exit(&os->os_lock);
910 		rw_exit(&os_lock);
911 		DNODE_STAT_ADD(dnode_move_stats.dms_dnode_recheck2);
912 		return (KMEM_CBRC_DONT_KNOW);
913 	}
914 
915 	/*
916 	 * At this point we know that as long as we hold os->os_lock, the dnode
917 	 * cannot be freed and fields within the dnode can be safely accessed.
918 	 * The objset listing this dnode cannot go away as long as this dnode is
919 	 * on its list.
920 	 */
921 	rw_exit(&os_lock);
922 	if (DMU_OBJECT_IS_SPECIAL(odn->dn_object)) {
923 		mutex_exit(&os->os_lock);
924 		DNODE_STAT_ADD(dnode_move_stats.dms_dnode_special);
925 		return (KMEM_CBRC_NO);
926 	}
927 	ASSERT(odn->dn_dbuf != NULL); /* only "special" dnodes have no parent */
928 
929 	/*
930 	 * Lock the dnode handle to prevent the dnode from obtaining any new
931 	 * holds. This also prevents the descendant dbufs and the bonus dbuf
932 	 * from accessing the dnode, so that we can discount their holds. The
933 	 * handle is safe to access because we know that while the dnode cannot
934 	 * go away, neither can its handle. Once we hold dnh_zrlock, we can
935 	 * safely move any dnode referenced only by dbufs.
936 	 */
937 	if (!zrl_tryenter(&odn->dn_handle->dnh_zrlock)) {
938 		mutex_exit(&os->os_lock);
939 		DNODE_STAT_ADD(dnode_move_stats.dms_dnode_handle);
940 		return (KMEM_CBRC_LATER);
941 	}
942 
943 	/*
944 	 * Ensure a consistent view of the dnode's holds and the dnode's dbufs.
945 	 * We need to guarantee that there is a hold for every dbuf in order to
946 	 * determine whether the dnode is actively referenced. Falsely matching
947 	 * a dbuf to an active hold would lead to an unsafe move. It's possible
948 	 * that a thread already having an active dnode hold is about to add a
949 	 * dbuf, and we can't compare hold and dbuf counts while the add is in
950 	 * progress.
951 	 */
952 	if (!rw_tryenter(&odn->dn_struct_rwlock, RW_WRITER)) {
953 		zrl_exit(&odn->dn_handle->dnh_zrlock);
954 		mutex_exit(&os->os_lock);
955 		DNODE_STAT_ADD(dnode_move_stats.dms_dnode_rwlock);
956 		return (KMEM_CBRC_LATER);
957 	}
958 
959 	/*
960 	 * A dbuf may be removed (evicted) without an active dnode hold. In that
961 	 * case, the dbuf count is decremented under the handle lock before the
962 	 * dbuf's hold is released. This order ensures that if we count the hold
963 	 * after the dbuf is removed but before its hold is released, we will
964 	 * treat the unmatched hold as active and exit safely. If we count the
965 	 * hold before the dbuf is removed, the hold is discounted, and the
966 	 * removal is blocked until the move completes.
967 	 */
968 	refcount = refcount_count(&odn->dn_holds);
969 	ASSERT(refcount >= 0);
970 	dbufs = odn->dn_dbufs_count;
971 
972 	/* We can't have more dbufs than dnode holds. */
973 	ASSERT3U(dbufs, <=, refcount);
974 	DTRACE_PROBE3(dnode__move, dnode_t *, odn, int64_t, refcount,
975 	    uint32_t, dbufs);
976 
977 	if (refcount > dbufs) {
978 		rw_exit(&odn->dn_struct_rwlock);
979 		zrl_exit(&odn->dn_handle->dnh_zrlock);
980 		mutex_exit(&os->os_lock);
981 		DNODE_STAT_ADD(dnode_move_stats.dms_dnode_active);
982 		return (KMEM_CBRC_LATER);
983 	}
984 
985 	rw_exit(&odn->dn_struct_rwlock);
986 
987 	/*
988 	 * At this point we know that anyone with a hold on the dnode is not
989 	 * actively referencing it. The dnode is known and in a valid state to
990 	 * move. We're holding the locks needed to execute the critical section.
991 	 */
992 	dnode_move_impl(odn, ndn);
993 
994 	list_link_replace(&odn->dn_link, &ndn->dn_link);
995 	/* If the dnode was safe to move, the refcount cannot have changed. */
996 	ASSERT(refcount == refcount_count(&ndn->dn_holds));
997 	ASSERT(dbufs == ndn->dn_dbufs_count);
998 	zrl_exit(&ndn->dn_handle->dnh_zrlock); /* handle has moved */
999 	mutex_exit(&os->os_lock);
1000 
1001 	return (KMEM_CBRC_YES);
1002 }
1003 #endif	/* illumos */
1004 #endif	/* _KERNEL */
1005 
1006 void
dnode_special_close(dnode_handle_t * dnh)1007 dnode_special_close(dnode_handle_t *dnh)
1008 {
1009 	dnode_t *dn = dnh->dnh_dnode;
1010 
1011 	/*
1012 	 * Wait for final references to the dnode to clear.  This can
1013 	 * only happen if the arc is asyncronously evicting state that
1014 	 * has a hold on this dnode while we are trying to evict this
1015 	 * dnode.
1016 	 */
1017 	while (refcount_count(&dn->dn_holds) > 0)
1018 		delay(1);
1019 	ASSERT(dn->dn_dbuf == NULL ||
1020 	    dmu_buf_get_user(&dn->dn_dbuf->db) == NULL);
1021 	zrl_add(&dnh->dnh_zrlock);
1022 	dnode_destroy(dn); /* implicit zrl_remove() */
1023 	zrl_destroy(&dnh->dnh_zrlock);
1024 	dnh->dnh_dnode = NULL;
1025 }
1026 
1027 void
dnode_special_open(objset_t * os,dnode_phys_t * dnp,uint64_t object,dnode_handle_t * dnh)1028 dnode_special_open(objset_t *os, dnode_phys_t *dnp, uint64_t object,
1029     dnode_handle_t *dnh)
1030 {
1031 	dnode_t *dn;
1032 
1033 	dn = dnode_create(os, dnp, NULL, object, dnh);
1034 	zrl_init(&dnh->dnh_zrlock);
1035 	DNODE_VERIFY(dn);
1036 }
1037 
1038 static void
dnode_buf_evict_async(void * dbu)1039 dnode_buf_evict_async(void *dbu)
1040 {
1041 	dnode_children_t *children_dnodes = dbu;
1042 	int i;
1043 
1044 	for (i = 0; i < children_dnodes->dnc_count; i++) {
1045 		dnode_handle_t *dnh = &children_dnodes->dnc_children[i];
1046 		dnode_t *dn;
1047 
1048 		/*
1049 		 * The dnode handle lock guards against the dnode moving to
1050 		 * another valid address, so there is no need here to guard
1051 		 * against changes to or from NULL.
1052 		 */
1053 		if (dnh->dnh_dnode == NULL) {
1054 			zrl_destroy(&dnh->dnh_zrlock);
1055 			continue;
1056 		}
1057 
1058 		zrl_add(&dnh->dnh_zrlock);
1059 		dn = dnh->dnh_dnode;
1060 		/*
1061 		 * If there are holds on this dnode, then there should
1062 		 * be holds on the dnode's containing dbuf as well; thus
1063 		 * it wouldn't be eligible for eviction and this function
1064 		 * would not have been called.
1065 		 */
1066 		ASSERT(refcount_is_zero(&dn->dn_holds));
1067 		ASSERT(refcount_is_zero(&dn->dn_tx_holds));
1068 
1069 		dnode_destroy(dn); /* implicit zrl_remove() */
1070 		zrl_destroy(&dnh->dnh_zrlock);
1071 		dnh->dnh_dnode = NULL;
1072 	}
1073 	kmem_free(children_dnodes, sizeof (dnode_children_t) +
1074 	    children_dnodes->dnc_count * sizeof (dnode_handle_t));
1075 }
1076 
1077 /*
1078  * Return true if the given index is interior to a dnode already
1079  * allocated in the block. That is, the index is neither free nor
1080  * allocated, but is consumed by a large dnode.
1081  *
1082  * The dnode_phys_t buffer may not be in sync with the in-core dnode
1083  * structure, so we try to check the dnode structure first and fall back
1084  * to the dnode_phys_t buffer it doesn't exist.
1085  */
1086 static boolean_t
dnode_is_consumed(dmu_buf_impl_t * db,int idx)1087 dnode_is_consumed(dmu_buf_impl_t *db, int idx)
1088 {
1089 	dnode_handle_t *dnh;
1090 	dmu_object_type_t ot;
1091 	dnode_children_t *children_dnodes;
1092 	dnode_phys_t *dn_block;
1093 	int skip;
1094 	int i;
1095 
1096 	children_dnodes = dmu_buf_get_user(&db->db);
1097 	dn_block = (dnode_phys_t *)db->db.db_data;
1098 
1099 	for (i = 0; i < idx; i += skip) {
1100 		dnh = &children_dnodes->dnc_children[i];
1101 
1102 		zrl_add(&dnh->dnh_zrlock);
1103 		if (dnh->dnh_dnode != NULL) {
1104 			ot = dnh->dnh_dnode->dn_type;
1105 			skip = dnh->dnh_dnode->dn_num_slots;
1106 		} else {
1107 			ot = dn_block[i].dn_type;
1108 			skip = dn_block[i].dn_extra_slots + 1;
1109 		}
1110 		zrl_remove(&dnh->dnh_zrlock);
1111 
1112 		if (ot == DMU_OT_NONE)
1113 			skip = 1;
1114 	}
1115 
1116 	return (i > idx);
1117 }
1118 
1119 /*
1120  * Return true if the given index in the dnode block is a valid
1121  * allocated dnode. That is, the index is not consumed by a large
1122  * dnode and is not free.
1123  *
1124  * The dnode_phys_t buffer may not be in sync with the in-core dnode
1125  * structure, so we try to check the dnode structure first and fall back
1126  * to the dnode_phys_t buffer it doesn't exist.
1127  */
1128 static boolean_t
dnode_is_allocated(dmu_buf_impl_t * db,int idx)1129 dnode_is_allocated(dmu_buf_impl_t *db, int idx)
1130 {
1131 	dnode_handle_t *dnh;
1132 	dmu_object_type_t ot;
1133 	dnode_children_t *children_dnodes;
1134 	dnode_phys_t *dn_block;
1135 
1136 	if (dnode_is_consumed(db, idx))
1137 		return (B_FALSE);
1138 
1139 	children_dnodes = dmu_buf_get_user(&db->db);
1140 	dn_block = (dnode_phys_t *)db->db.db_data;
1141 
1142 	dnh = &children_dnodes->dnc_children[idx];
1143 
1144 	zrl_add(&dnh->dnh_zrlock);
1145 	if (dnh->dnh_dnode != NULL)
1146 		ot = dnh->dnh_dnode->dn_type;
1147 	else
1148 		ot = dn_block[idx].dn_type;
1149 	zrl_remove(&dnh->dnh_zrlock);
1150 
1151 	return (ot != DMU_OT_NONE);
1152 }
1153 
1154 /*
1155  * Return true if the given range of indices in the dnode block are
1156  * free. That is, the starting index is not consumed by a large dnode
1157  * and none of the indices are allocated.
1158  *
1159  * The dnode_phys_t buffer may not be in sync with the in-core dnode
1160  * structure, so we try to check the dnode structure first and fall back
1161  * to the dnode_phys_t buffer it doesn't exist.
1162  */
1163 static boolean_t
dnode_is_free(dmu_buf_impl_t * db,int idx,int slots)1164 dnode_is_free(dmu_buf_impl_t *db, int idx, int slots)
1165 {
1166 	dnode_handle_t *dnh;
1167 	dmu_object_type_t ot;
1168 	dnode_children_t *children_dnodes;
1169 	dnode_phys_t *dn_block;
1170 	int i;
1171 
1172 	if (idx + slots > DNODES_PER_BLOCK)
1173 		return (B_FALSE);
1174 
1175 	children_dnodes = dmu_buf_get_user(&db->db);
1176 	dn_block = (dnode_phys_t *)db->db.db_data;
1177 
1178 	if (dnode_is_consumed(db, idx))
1179 		return (B_FALSE);
1180 
1181 	for (i = idx; i < idx + slots; i++) {
1182 		dnh = &children_dnodes->dnc_children[i];
1183 
1184 		zrl_add(&dnh->dnh_zrlock);
1185 		if (dnh->dnh_dnode != NULL)
1186 			ot = dnh->dnh_dnode->dn_type;
1187 		else
1188 			ot = dn_block[i].dn_type;
1189 		zrl_remove(&dnh->dnh_zrlock);
1190 
1191 		if (ot != DMU_OT_NONE)
1192 			return (B_FALSE);
1193 	}
1194 
1195 	return (B_TRUE);
1196 }
1197 
1198 /*
1199  * errors:
1200  * EINVAL - invalid object number.
1201  * ENOSPC - hole too small to fulfill "slots" request
1202  * EIO - i/o error.
1203  * succeeds even for free dnodes.
1204  */
1205 int
dnode_hold_impl(objset_t * os,uint64_t object,int flag,int slots,void * tag,dnode_t ** dnp)1206 dnode_hold_impl(objset_t *os, uint64_t object, int flag, int slots,
1207     void *tag, dnode_t **dnp)
1208 {
1209 	int epb, idx, err, i;
1210 	int drop_struct_lock = FALSE;
1211 	int type;
1212 	uint64_t blk;
1213 	dnode_t *mdn, *dn;
1214 	dmu_buf_impl_t *db;
1215 	dnode_children_t *children_dnodes;
1216 	dnode_phys_t *dn_block_begin;
1217 	dnode_handle_t *dnh;
1218 
1219 	ASSERT(!(flag & DNODE_MUST_BE_ALLOCATED) || (slots == 0));
1220 	ASSERT(!(flag & DNODE_MUST_BE_FREE) || (slots > 0));
1221 
1222 	/*
1223 	 * If you are holding the spa config lock as writer, you shouldn't
1224 	 * be asking the DMU to do *anything* unless it's the root pool
1225 	 * which may require us to read from the root filesystem while
1226 	 * holding some (not all) of the locks as writer.
1227 	 */
1228 	ASSERT(spa_config_held(os->os_spa, SCL_ALL, RW_WRITER) == 0 ||
1229 	    (spa_is_root(os->os_spa) &&
1230 	    spa_config_held(os->os_spa, SCL_STATE, RW_WRITER)));
1231 
1232 	ASSERT((flag & DNODE_MUST_BE_ALLOCATED) || (flag & DNODE_MUST_BE_FREE));
1233 
1234 	if (object == DMU_USERUSED_OBJECT || object == DMU_GROUPUSED_OBJECT) {
1235 		dn = (object == DMU_USERUSED_OBJECT) ?
1236 		    DMU_USERUSED_DNODE(os) : DMU_GROUPUSED_DNODE(os);
1237 		if (dn == NULL)
1238 			return (SET_ERROR(ENOENT));
1239 		type = dn->dn_type;
1240 		if ((flag & DNODE_MUST_BE_ALLOCATED) && type == DMU_OT_NONE)
1241 			return (SET_ERROR(ENOENT));
1242 		if ((flag & DNODE_MUST_BE_FREE) && type != DMU_OT_NONE)
1243 			return (SET_ERROR(EEXIST));
1244 		DNODE_VERIFY(dn);
1245 		(void) refcount_add(&dn->dn_holds, tag);
1246 		*dnp = dn;
1247 		return (0);
1248 	}
1249 
1250 	if (object == 0 || object >= DN_MAX_OBJECT)
1251 		return (SET_ERROR(EINVAL));
1252 
1253 	mdn = DMU_META_DNODE(os);
1254 	ASSERT(mdn->dn_object == DMU_META_DNODE_OBJECT);
1255 
1256 	DNODE_VERIFY(mdn);
1257 
1258 	if (!RW_WRITE_HELD(&mdn->dn_struct_rwlock)) {
1259 		rw_enter(&mdn->dn_struct_rwlock, RW_READER);
1260 		drop_struct_lock = TRUE;
1261 	}
1262 
1263 	blk = dbuf_whichblock(mdn, 0, object * sizeof (dnode_phys_t));
1264 
1265 	db = dbuf_hold(mdn, blk, FTAG);
1266 	if (drop_struct_lock)
1267 		rw_exit(&mdn->dn_struct_rwlock);
1268 	if (db == NULL)
1269 		return (SET_ERROR(EIO));
1270 	err = dbuf_read(db, NULL, DB_RF_CANFAIL);
1271 	if (err) {
1272 		dbuf_rele(db, FTAG);
1273 		return (err);
1274 	}
1275 
1276 	ASSERT3U(db->db.db_size, >=, 1<<DNODE_SHIFT);
1277 	epb = db->db.db_size >> DNODE_SHIFT;
1278 
1279 	ASSERT(DB_DNODE(db)->dn_type == DMU_OT_DNODE);
1280 	children_dnodes = dmu_buf_get_user(&db->db);
1281 	if (children_dnodes == NULL) {
1282 		dnode_children_t *winner;
1283 		children_dnodes = kmem_zalloc(sizeof (dnode_children_t) +
1284 		    epb * sizeof (dnode_handle_t), KM_SLEEP);
1285 		children_dnodes->dnc_count = epb;
1286 		dnh = &children_dnodes->dnc_children[0];
1287 		for (i = 0; i < epb; i++) {
1288 			zrl_init(&dnh[i].dnh_zrlock);
1289 		}
1290 		dmu_buf_init_user(&children_dnodes->dnc_dbu, NULL,
1291 		    dnode_buf_evict_async, NULL);
1292 		winner = dmu_buf_set_user(&db->db, &children_dnodes->dnc_dbu);
1293 		if (winner != NULL) {
1294 
1295 			for (i = 0; i < epb; i++) {
1296 				zrl_destroy(&dnh[i].dnh_zrlock);
1297 			}
1298 
1299 			kmem_free(children_dnodes, sizeof (dnode_children_t) +
1300 			    epb * sizeof (dnode_handle_t));
1301 			children_dnodes = winner;
1302 		}
1303 	}
1304 	ASSERT(children_dnodes->dnc_count == epb);
1305 
1306 	idx = object & (epb - 1);
1307 	dn_block_begin = (dnode_phys_t *)db->db.db_data;
1308 
1309 	if ((flag & DNODE_MUST_BE_FREE) && !dnode_is_free(db, idx, slots)) {
1310 		dbuf_rele(db, FTAG);
1311 		return (ENOSPC);
1312 	} else if ((flag & DNODE_MUST_BE_ALLOCATED) &&
1313 	    !dnode_is_allocated(db, idx)) {
1314 		dbuf_rele(db, FTAG);
1315 		return (ENOENT);
1316 	}
1317 
1318 	dnh = &children_dnodes->dnc_children[idx];
1319 	zrl_add(&dnh->dnh_zrlock);
1320 	dn = dnh->dnh_dnode;
1321 	if (dn == NULL)
1322 		dn = dnode_create(os, dn_block_begin + idx, db, object, dnh);
1323 
1324 	mutex_enter(&dn->dn_mtx);
1325 	type = dn->dn_type;
1326 	if (dn->dn_free_txg ||
1327 	    ((flag & DNODE_MUST_BE_ALLOCATED) && type == DMU_OT_NONE) ||
1328 	    ((flag & DNODE_MUST_BE_FREE) &&
1329 	    (type != DMU_OT_NONE || !refcount_is_zero(&dn->dn_holds)))) {
1330 		mutex_exit(&dn->dn_mtx);
1331 		zrl_remove(&dnh->dnh_zrlock);
1332 		dbuf_rele(db, FTAG);
1333 		return ((flag & DNODE_MUST_BE_ALLOCATED) ? ENOENT : EEXIST);
1334 	}
1335 	if (refcount_add(&dn->dn_holds, tag) == 1)
1336 		dbuf_add_ref(db, dnh);
1337 	mutex_exit(&dn->dn_mtx);
1338 
1339 	/* Now we can rely on the hold to prevent the dnode from moving. */
1340 	zrl_remove(&dnh->dnh_zrlock);
1341 
1342 	DNODE_VERIFY(dn);
1343 	ASSERT3P(dn->dn_dbuf, ==, db);
1344 	ASSERT3U(dn->dn_object, ==, object);
1345 	dbuf_rele(db, FTAG);
1346 
1347 	*dnp = dn;
1348 	return (0);
1349 }
1350 
1351 /*
1352  * Return held dnode if the object is allocated, NULL if not.
1353  */
1354 int
dnode_hold(objset_t * os,uint64_t object,void * tag,dnode_t ** dnp)1355 dnode_hold(objset_t *os, uint64_t object, void *tag, dnode_t **dnp)
1356 {
1357 	return (dnode_hold_impl(os, object, DNODE_MUST_BE_ALLOCATED, 0, tag,
1358 	    dnp));
1359 }
1360 
1361 /*
1362  * Can only add a reference if there is already at least one
1363  * reference on the dnode.  Returns FALSE if unable to add a
1364  * new reference.
1365  */
1366 boolean_t
dnode_add_ref(dnode_t * dn,void * tag)1367 dnode_add_ref(dnode_t *dn, void *tag)
1368 {
1369 	mutex_enter(&dn->dn_mtx);
1370 	if (refcount_is_zero(&dn->dn_holds)) {
1371 		mutex_exit(&dn->dn_mtx);
1372 		return (FALSE);
1373 	}
1374 	VERIFY(1 < refcount_add(&dn->dn_holds, tag));
1375 	mutex_exit(&dn->dn_mtx);
1376 	return (TRUE);
1377 }
1378 
1379 void
dnode_rele(dnode_t * dn,void * tag)1380 dnode_rele(dnode_t *dn, void *tag)
1381 {
1382 	mutex_enter(&dn->dn_mtx);
1383 	dnode_rele_and_unlock(dn, tag, B_FALSE);
1384 }
1385 
1386 void
dnode_rele_and_unlock(dnode_t * dn,void * tag,boolean_t evicting)1387 dnode_rele_and_unlock(dnode_t *dn, void *tag, boolean_t evicting)
1388 {
1389 	uint64_t refs;
1390 	/* Get while the hold prevents the dnode from moving. */
1391 	dmu_buf_impl_t *db = dn->dn_dbuf;
1392 	dnode_handle_t *dnh = dn->dn_handle;
1393 
1394 	refs = refcount_remove(&dn->dn_holds, tag);
1395 	mutex_exit(&dn->dn_mtx);
1396 
1397 	/*
1398 	 * It's unsafe to release the last hold on a dnode by dnode_rele() or
1399 	 * indirectly by dbuf_rele() while relying on the dnode handle to
1400 	 * prevent the dnode from moving, since releasing the last hold could
1401 	 * result in the dnode's parent dbuf evicting its dnode handles. For
1402 	 * that reason anyone calling dnode_rele() or dbuf_rele() without some
1403 	 * other direct or indirect hold on the dnode must first drop the dnode
1404 	 * handle.
1405 	 */
1406 	ASSERT(refs > 0 || dnh->dnh_zrlock.zr_owner != curthread);
1407 
1408 	/* NOTE: the DNODE_DNODE does not have a dn_dbuf */
1409 	if (refs == 0 && db != NULL) {
1410 		/*
1411 		 * Another thread could add a hold to the dnode handle in
1412 		 * dnode_hold_impl() while holding the parent dbuf. Since the
1413 		 * hold on the parent dbuf prevents the handle from being
1414 		 * destroyed, the hold on the handle is OK. We can't yet assert
1415 		 * that the handle has zero references, but that will be
1416 		 * asserted anyway when the handle gets destroyed.
1417 		 */
1418 		mutex_enter(&db->db_mtx);
1419 		dbuf_rele_and_unlock(db, dnh, evicting);
1420 	}
1421 }
1422 
1423 void
dnode_setdirty(dnode_t * dn,dmu_tx_t * tx)1424 dnode_setdirty(dnode_t *dn, dmu_tx_t *tx)
1425 {
1426 	objset_t *os = dn->dn_objset;
1427 	uint64_t txg = tx->tx_txg;
1428 
1429 	if (DMU_OBJECT_IS_SPECIAL(dn->dn_object)) {
1430 		dsl_dataset_dirty(os->os_dsl_dataset, tx);
1431 		return;
1432 	}
1433 
1434 	DNODE_VERIFY(dn);
1435 
1436 #ifdef ZFS_DEBUG
1437 	mutex_enter(&dn->dn_mtx);
1438 	ASSERT(dn->dn_phys->dn_type || dn->dn_allocated_txg);
1439 	ASSERT(dn->dn_free_txg == 0 || dn->dn_free_txg >= txg);
1440 	mutex_exit(&dn->dn_mtx);
1441 #endif
1442 
1443 	/*
1444 	 * Determine old uid/gid when necessary
1445 	 */
1446 	dmu_objset_userquota_get_ids(dn, B_TRUE, tx);
1447 
1448 	multilist_t *dirtylist = os->os_dirty_dnodes[txg & TXG_MASK];
1449 	multilist_sublist_t *mls = multilist_sublist_lock_obj(dirtylist, dn);
1450 
1451 	/*
1452 	 * If we are already marked dirty, we're done.
1453 	 */
1454 	if (list_link_active(&dn->dn_dirty_link[txg & TXG_MASK])) {
1455 		multilist_sublist_unlock(mls);
1456 		return;
1457 	}
1458 
1459 	ASSERT(!refcount_is_zero(&dn->dn_holds) ||
1460 	    !avl_is_empty(&dn->dn_dbufs));
1461 	ASSERT(dn->dn_datablksz != 0);
1462 	ASSERT0(dn->dn_next_bonuslen[txg&TXG_MASK]);
1463 	ASSERT0(dn->dn_next_blksz[txg&TXG_MASK]);
1464 	ASSERT0(dn->dn_next_bonustype[txg&TXG_MASK]);
1465 
1466 	dprintf_ds(os->os_dsl_dataset, "obj=%llu txg=%llu\n",
1467 	    dn->dn_object, txg);
1468 
1469 	multilist_sublist_insert_head(mls, dn);
1470 
1471 	multilist_sublist_unlock(mls);
1472 
1473 	/*
1474 	 * The dnode maintains a hold on its containing dbuf as
1475 	 * long as there are holds on it.  Each instantiated child
1476 	 * dbuf maintains a hold on the dnode.  When the last child
1477 	 * drops its hold, the dnode will drop its hold on the
1478 	 * containing dbuf. We add a "dirty hold" here so that the
1479 	 * dnode will hang around after we finish processing its
1480 	 * children.
1481 	 */
1482 	VERIFY(dnode_add_ref(dn, (void *)(uintptr_t)tx->tx_txg));
1483 
1484 	(void) dbuf_dirty(dn->dn_dbuf, tx);
1485 
1486 	dsl_dataset_dirty(os->os_dsl_dataset, tx);
1487 }
1488 
1489 void
dnode_free(dnode_t * dn,dmu_tx_t * tx)1490 dnode_free(dnode_t *dn, dmu_tx_t *tx)
1491 {
1492 	mutex_enter(&dn->dn_mtx);
1493 	if (dn->dn_type == DMU_OT_NONE || dn->dn_free_txg) {
1494 		mutex_exit(&dn->dn_mtx);
1495 		return;
1496 	}
1497 	dn->dn_free_txg = tx->tx_txg;
1498 	mutex_exit(&dn->dn_mtx);
1499 
1500 	dnode_setdirty(dn, tx);
1501 }
1502 
1503 /*
1504  * Try to change the block size for the indicated dnode.  This can only
1505  * succeed if there are no blocks allocated or dirty beyond first block
1506  */
1507 int
dnode_set_blksz(dnode_t * dn,uint64_t size,int ibs,dmu_tx_t * tx)1508 dnode_set_blksz(dnode_t *dn, uint64_t size, int ibs, dmu_tx_t *tx)
1509 {
1510 	dmu_buf_impl_t *db;
1511 	int err;
1512 
1513 	ASSERT3U(size, <=, spa_maxblocksize(dmu_objset_spa(dn->dn_objset)));
1514 	if (size == 0)
1515 		size = SPA_MINBLOCKSIZE;
1516 	else
1517 		size = P2ROUNDUP(size, SPA_MINBLOCKSIZE);
1518 
1519 	if (ibs == dn->dn_indblkshift)
1520 		ibs = 0;
1521 
1522 	if (size >> SPA_MINBLOCKSHIFT == dn->dn_datablkszsec && ibs == 0)
1523 		return (0);
1524 
1525 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
1526 
1527 	/* Check for any allocated blocks beyond the first */
1528 	if (dn->dn_maxblkid != 0)
1529 		goto fail;
1530 
1531 	mutex_enter(&dn->dn_dbufs_mtx);
1532 	for (db = avl_first(&dn->dn_dbufs); db != NULL;
1533 	    db = AVL_NEXT(&dn->dn_dbufs, db)) {
1534 		if (db->db_blkid != 0 && db->db_blkid != DMU_BONUS_BLKID &&
1535 		    db->db_blkid != DMU_SPILL_BLKID) {
1536 			mutex_exit(&dn->dn_dbufs_mtx);
1537 			goto fail;
1538 		}
1539 	}
1540 	mutex_exit(&dn->dn_dbufs_mtx);
1541 
1542 	if (ibs && dn->dn_nlevels != 1)
1543 		goto fail;
1544 
1545 	/* resize the old block */
1546 	err = dbuf_hold_impl(dn, 0, 0, TRUE, FALSE, FTAG, &db);
1547 	if (err == 0)
1548 		dbuf_new_size(db, size, tx);
1549 	else if (err != ENOENT)
1550 		goto fail;
1551 
1552 	dnode_setdblksz(dn, size);
1553 	dnode_setdirty(dn, tx);
1554 	dn->dn_next_blksz[tx->tx_txg&TXG_MASK] = size;
1555 	if (ibs) {
1556 		dn->dn_indblkshift = ibs;
1557 		dn->dn_next_indblkshift[tx->tx_txg&TXG_MASK] = ibs;
1558 	}
1559 	/* rele after we have fixed the blocksize in the dnode */
1560 	if (db)
1561 		dbuf_rele(db, FTAG);
1562 
1563 	rw_exit(&dn->dn_struct_rwlock);
1564 	return (0);
1565 
1566 fail:
1567 	rw_exit(&dn->dn_struct_rwlock);
1568 	return (SET_ERROR(ENOTSUP));
1569 }
1570 
1571 /* read-holding callers must not rely on the lock being continuously held */
1572 void
dnode_new_blkid(dnode_t * dn,uint64_t blkid,dmu_tx_t * tx,boolean_t have_read)1573 dnode_new_blkid(dnode_t *dn, uint64_t blkid, dmu_tx_t *tx, boolean_t have_read)
1574 {
1575 	uint64_t txgoff = tx->tx_txg & TXG_MASK;
1576 	int epbs, new_nlevels;
1577 	uint64_t sz;
1578 
1579 	ASSERT(blkid != DMU_BONUS_BLKID);
1580 
1581 	ASSERT(have_read ?
1582 	    RW_READ_HELD(&dn->dn_struct_rwlock) :
1583 	    RW_WRITE_HELD(&dn->dn_struct_rwlock));
1584 
1585 	/*
1586 	 * if we have a read-lock, check to see if we need to do any work
1587 	 * before upgrading to a write-lock.
1588 	 */
1589 	if (have_read) {
1590 		if (blkid <= dn->dn_maxblkid)
1591 			return;
1592 
1593 		if (!rw_tryupgrade(&dn->dn_struct_rwlock)) {
1594 			rw_exit(&dn->dn_struct_rwlock);
1595 			rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
1596 		}
1597 	}
1598 
1599 	if (blkid <= dn->dn_maxblkid)
1600 		goto out;
1601 
1602 	dn->dn_maxblkid = blkid;
1603 
1604 	/*
1605 	 * Compute the number of levels necessary to support the new maxblkid.
1606 	 */
1607 	new_nlevels = 1;
1608 	epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
1609 	for (sz = dn->dn_nblkptr;
1610 	    sz <= blkid && sz >= dn->dn_nblkptr; sz <<= epbs)
1611 		new_nlevels++;
1612 
1613 	if (new_nlevels > dn->dn_nlevels) {
1614 		int old_nlevels = dn->dn_nlevels;
1615 		dmu_buf_impl_t *db;
1616 		list_t *list;
1617 		dbuf_dirty_record_t *new, *dr, *dr_next;
1618 
1619 		dn->dn_nlevels = new_nlevels;
1620 
1621 		ASSERT3U(new_nlevels, >, dn->dn_next_nlevels[txgoff]);
1622 		dn->dn_next_nlevels[txgoff] = new_nlevels;
1623 
1624 		/* dirty the left indirects */
1625 		db = dbuf_hold_level(dn, old_nlevels, 0, FTAG);
1626 		ASSERT(db != NULL);
1627 		new = dbuf_dirty(db, tx);
1628 		dbuf_rele(db, FTAG);
1629 
1630 		/* transfer the dirty records to the new indirect */
1631 		mutex_enter(&dn->dn_mtx);
1632 		mutex_enter(&new->dt.di.dr_mtx);
1633 		list = &dn->dn_dirty_records[txgoff];
1634 		for (dr = list_head(list); dr; dr = dr_next) {
1635 			dr_next = list_next(&dn->dn_dirty_records[txgoff], dr);
1636 			if (dr->dr_dbuf->db_level != new_nlevels-1 &&
1637 			    dr->dr_dbuf->db_blkid != DMU_BONUS_BLKID &&
1638 			    dr->dr_dbuf->db_blkid != DMU_SPILL_BLKID) {
1639 				ASSERT(dr->dr_dbuf->db_level == old_nlevels-1);
1640 				list_remove(&dn->dn_dirty_records[txgoff], dr);
1641 				list_insert_tail(&new->dt.di.dr_children, dr);
1642 				dr->dr_parent = new;
1643 			}
1644 		}
1645 		mutex_exit(&new->dt.di.dr_mtx);
1646 		mutex_exit(&dn->dn_mtx);
1647 	}
1648 
1649 out:
1650 	if (have_read)
1651 		rw_downgrade(&dn->dn_struct_rwlock);
1652 }
1653 
1654 static void
dnode_dirty_l1(dnode_t * dn,uint64_t l1blkid,dmu_tx_t * tx)1655 dnode_dirty_l1(dnode_t *dn, uint64_t l1blkid, dmu_tx_t *tx)
1656 {
1657 	dmu_buf_impl_t *db = dbuf_hold_level(dn, 1, l1blkid, FTAG);
1658 	if (db != NULL) {
1659 		dmu_buf_will_dirty(&db->db, tx);
1660 		dbuf_rele(db, FTAG);
1661 	}
1662 }
1663 
1664 /*
1665  * Dirty all the in-core level-1 dbufs in the range specified by start_blkid
1666  * and end_blkid.
1667  */
1668 static void
dnode_dirty_l1range(dnode_t * dn,uint64_t start_blkid,uint64_t end_blkid,dmu_tx_t * tx)1669 dnode_dirty_l1range(dnode_t *dn, uint64_t start_blkid, uint64_t end_blkid,
1670     dmu_tx_t *tx)
1671 {
1672 	dmu_buf_impl_t db_search;
1673 	dmu_buf_impl_t *db;
1674 	avl_index_t where;
1675 
1676 	mutex_enter(&dn->dn_dbufs_mtx);
1677 
1678 	db_search.db_level = 1;
1679 	db_search.db_blkid = start_blkid + 1;
1680 	db_search.db_state = DB_SEARCH;
1681 	for (;;) {
1682 
1683 		db = avl_find(&dn->dn_dbufs, &db_search, &where);
1684 		if (db == NULL)
1685 			db = avl_nearest(&dn->dn_dbufs, where, AVL_AFTER);
1686 
1687 		if (db == NULL || db->db_level != 1 ||
1688 		    db->db_blkid >= end_blkid) {
1689 			break;
1690 		}
1691 
1692 		/*
1693 		 * Setup the next blkid we want to search for.
1694 		 */
1695 		db_search.db_blkid = db->db_blkid + 1;
1696 		ASSERT3U(db->db_blkid, >=, start_blkid);
1697 
1698 		/*
1699 		 * If the dbuf transitions to DB_EVICTING while we're trying
1700 		 * to dirty it, then we will be unable to discover it in
1701 		 * the dbuf hash table. This will result in a call to
1702 		 * dbuf_create() which needs to acquire the dn_dbufs_mtx
1703 		 * lock. To avoid a deadlock, we drop the lock before
1704 		 * dirtying the level-1 dbuf.
1705 		 */
1706 		mutex_exit(&dn->dn_dbufs_mtx);
1707 		dnode_dirty_l1(dn, db->db_blkid, tx);
1708 		mutex_enter(&dn->dn_dbufs_mtx);
1709 	}
1710 
1711 #ifdef ZFS_DEBUG
1712 	/*
1713 	 * Walk all the in-core level-1 dbufs and verify they have been dirtied.
1714 	 */
1715 	db_search.db_level = 1;
1716 	db_search.db_blkid = start_blkid + 1;
1717 	db_search.db_state = DB_SEARCH;
1718 	db = avl_find(&dn->dn_dbufs, &db_search, &where);
1719 	if (db == NULL)
1720 		db = avl_nearest(&dn->dn_dbufs, where, AVL_AFTER);
1721 	for (; db != NULL; db = AVL_NEXT(&dn->dn_dbufs, db)) {
1722 		if (db->db_level != 1 || db->db_blkid >= end_blkid)
1723 			break;
1724 		ASSERT(db->db_dirtycnt > 0);
1725 	}
1726 #endif
1727 	mutex_exit(&dn->dn_dbufs_mtx);
1728 }
1729 
1730 void
dnode_free_range(dnode_t * dn,uint64_t off,uint64_t len,dmu_tx_t * tx)1731 dnode_free_range(dnode_t *dn, uint64_t off, uint64_t len, dmu_tx_t *tx)
1732 {
1733 	dmu_buf_impl_t *db;
1734 	uint64_t blkoff, blkid, nblks;
1735 	int blksz, blkshift, head, tail;
1736 	int trunc = FALSE;
1737 	int epbs;
1738 
1739 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
1740 	blksz = dn->dn_datablksz;
1741 	blkshift = dn->dn_datablkshift;
1742 	epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
1743 
1744 	if (len == DMU_OBJECT_END) {
1745 		len = UINT64_MAX - off;
1746 		trunc = TRUE;
1747 	}
1748 
1749 	/*
1750 	 * First, block align the region to free:
1751 	 */
1752 	if (ISP2(blksz)) {
1753 		head = P2NPHASE(off, blksz);
1754 		blkoff = P2PHASE(off, blksz);
1755 		if ((off >> blkshift) > dn->dn_maxblkid)
1756 			goto out;
1757 	} else {
1758 		ASSERT(dn->dn_maxblkid == 0);
1759 		if (off == 0 && len >= blksz) {
1760 			/*
1761 			 * Freeing the whole block; fast-track this request.
1762 			 */
1763 			blkid = 0;
1764 			nblks = 1;
1765 			if (dn->dn_nlevels > 1)
1766 				dnode_dirty_l1(dn, 0, tx);
1767 			goto done;
1768 		} else if (off >= blksz) {
1769 			/* Freeing past end-of-data */
1770 			goto out;
1771 		} else {
1772 			/* Freeing part of the block. */
1773 			head = blksz - off;
1774 			ASSERT3U(head, >, 0);
1775 		}
1776 		blkoff = off;
1777 	}
1778 	/* zero out any partial block data at the start of the range */
1779 	if (head) {
1780 		ASSERT3U(blkoff + head, ==, blksz);
1781 		if (len < head)
1782 			head = len;
1783 		if (dbuf_hold_impl(dn, 0, dbuf_whichblock(dn, 0, off),
1784 		    TRUE, FALSE, FTAG, &db) == 0) {
1785 			caddr_t data;
1786 
1787 			/* don't dirty if it isn't on disk and isn't dirty */
1788 			if (db->db_last_dirty ||
1789 			    (db->db_blkptr && !BP_IS_HOLE(db->db_blkptr))) {
1790 				rw_exit(&dn->dn_struct_rwlock);
1791 				dmu_buf_will_dirty(&db->db, tx);
1792 				rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
1793 				data = db->db.db_data;
1794 				bzero(data + blkoff, head);
1795 			}
1796 			dbuf_rele(db, FTAG);
1797 		}
1798 		off += head;
1799 		len -= head;
1800 	}
1801 
1802 	/* If the range was less than one block, we're done */
1803 	if (len == 0)
1804 		goto out;
1805 
1806 	/* If the remaining range is past end of file, we're done */
1807 	if ((off >> blkshift) > dn->dn_maxblkid)
1808 		goto out;
1809 
1810 	ASSERT(ISP2(blksz));
1811 	if (trunc)
1812 		tail = 0;
1813 	else
1814 		tail = P2PHASE(len, blksz);
1815 
1816 	ASSERT0(P2PHASE(off, blksz));
1817 	/* zero out any partial block data at the end of the range */
1818 	if (tail) {
1819 		if (len < tail)
1820 			tail = len;
1821 		if (dbuf_hold_impl(dn, 0, dbuf_whichblock(dn, 0, off+len),
1822 		    TRUE, FALSE, FTAG, &db) == 0) {
1823 			/* don't dirty if not on disk and not dirty */
1824 			if (db->db_last_dirty ||
1825 			    (db->db_blkptr && !BP_IS_HOLE(db->db_blkptr))) {
1826 				rw_exit(&dn->dn_struct_rwlock);
1827 				dmu_buf_will_dirty(&db->db, tx);
1828 				rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
1829 				bzero(db->db.db_data, tail);
1830 			}
1831 			dbuf_rele(db, FTAG);
1832 		}
1833 		len -= tail;
1834 	}
1835 
1836 	/* If the range did not include a full block, we are done */
1837 	if (len == 0)
1838 		goto out;
1839 
1840 	ASSERT(IS_P2ALIGNED(off, blksz));
1841 	ASSERT(trunc || IS_P2ALIGNED(len, blksz));
1842 	blkid = off >> blkshift;
1843 	nblks = len >> blkshift;
1844 	if (trunc)
1845 		nblks += 1;
1846 
1847 	/*
1848 	 * Dirty all the indirect blocks in this range.  Note that only
1849 	 * the first and last indirect blocks can actually be written
1850 	 * (if they were partially freed) -- they must be dirtied, even if
1851 	 * they do not exist on disk yet.  The interior blocks will
1852 	 * be freed by free_children(), so they will not actually be written.
1853 	 * Even though these interior blocks will not be written, we
1854 	 * dirty them for two reasons:
1855 	 *
1856 	 *  - It ensures that the indirect blocks remain in memory until
1857 	 *    syncing context.  (They have already been prefetched by
1858 	 *    dmu_tx_hold_free(), so we don't have to worry about reading
1859 	 *    them serially here.)
1860 	 *
1861 	 *  - The dirty space accounting will put pressure on the txg sync
1862 	 *    mechanism to begin syncing, and to delay transactions if there
1863 	 *    is a large amount of freeing.  Even though these indirect
1864 	 *    blocks will not be written, we could need to write the same
1865 	 *    amount of space if we copy the freed BPs into deadlists.
1866 	 */
1867 	if (dn->dn_nlevels > 1) {
1868 		uint64_t first, last;
1869 
1870 		first = blkid >> epbs;
1871 		dnode_dirty_l1(dn, first, tx);
1872 		if (trunc)
1873 			last = dn->dn_maxblkid >> epbs;
1874 		else
1875 			last = (blkid + nblks - 1) >> epbs;
1876 		if (last != first)
1877 			dnode_dirty_l1(dn, last, tx);
1878 
1879 		dnode_dirty_l1range(dn, first, last, tx);
1880 
1881 		int shift = dn->dn_datablkshift + dn->dn_indblkshift -
1882 		    SPA_BLKPTRSHIFT;
1883 		for (uint64_t i = first + 1; i < last; i++) {
1884 			/*
1885 			 * Set i to the blockid of the next non-hole
1886 			 * level-1 indirect block at or after i.  Note
1887 			 * that dnode_next_offset() operates in terms of
1888 			 * level-0-equivalent bytes.
1889 			 */
1890 			uint64_t ibyte = i << shift;
1891 			int err = dnode_next_offset(dn, DNODE_FIND_HAVELOCK,
1892 			    &ibyte, 2, 1, 0);
1893 			i = ibyte >> shift;
1894 			if (i >= last)
1895 				break;
1896 
1897 			/*
1898 			 * Normally we should not see an error, either
1899 			 * from dnode_next_offset() or dbuf_hold_level()
1900 			 * (except for ESRCH from dnode_next_offset).
1901 			 * If there is an i/o error, then when we read
1902 			 * this block in syncing context, it will use
1903 			 * ZIO_FLAG_MUSTSUCCEED, and thus hang/panic according
1904 			 * to the "failmode" property.  dnode_next_offset()
1905 			 * doesn't have a flag to indicate MUSTSUCCEED.
1906 			 */
1907 			if (err != 0)
1908 				break;
1909 
1910 			dnode_dirty_l1(dn, i, tx);
1911 		}
1912 	}
1913 
1914 done:
1915 	/*
1916 	 * Add this range to the dnode range list.
1917 	 * We will finish up this free operation in the syncing phase.
1918 	 */
1919 	mutex_enter(&dn->dn_mtx);
1920 	int txgoff = tx->tx_txg & TXG_MASK;
1921 	if (dn->dn_free_ranges[txgoff] == NULL) {
1922 		dn->dn_free_ranges[txgoff] = range_tree_create(NULL, NULL);
1923 	}
1924 	range_tree_clear(dn->dn_free_ranges[txgoff], blkid, nblks);
1925 	range_tree_add(dn->dn_free_ranges[txgoff], blkid, nblks);
1926 	dprintf_dnode(dn, "blkid=%llu nblks=%llu txg=%llu\n",
1927 	    blkid, nblks, tx->tx_txg);
1928 	mutex_exit(&dn->dn_mtx);
1929 
1930 	dbuf_free_range(dn, blkid, blkid + nblks - 1, tx);
1931 	dnode_setdirty(dn, tx);
1932 out:
1933 
1934 	rw_exit(&dn->dn_struct_rwlock);
1935 }
1936 
1937 static boolean_t
dnode_spill_freed(dnode_t * dn)1938 dnode_spill_freed(dnode_t *dn)
1939 {
1940 	int i;
1941 
1942 	mutex_enter(&dn->dn_mtx);
1943 	for (i = 0; i < TXG_SIZE; i++) {
1944 		if (dn->dn_rm_spillblk[i] == DN_KILL_SPILLBLK)
1945 			break;
1946 	}
1947 	mutex_exit(&dn->dn_mtx);
1948 	return (i < TXG_SIZE);
1949 }
1950 
1951 /* return TRUE if this blkid was freed in a recent txg, or FALSE if it wasn't */
1952 uint64_t
dnode_block_freed(dnode_t * dn,uint64_t blkid)1953 dnode_block_freed(dnode_t *dn, uint64_t blkid)
1954 {
1955 	void *dp = spa_get_dsl(dn->dn_objset->os_spa);
1956 	int i;
1957 
1958 	if (blkid == DMU_BONUS_BLKID)
1959 		return (FALSE);
1960 
1961 	/*
1962 	 * If we're in the process of opening the pool, dp will not be
1963 	 * set yet, but there shouldn't be anything dirty.
1964 	 */
1965 	if (dp == NULL)
1966 		return (FALSE);
1967 
1968 	if (dn->dn_free_txg)
1969 		return (TRUE);
1970 
1971 	if (blkid == DMU_SPILL_BLKID)
1972 		return (dnode_spill_freed(dn));
1973 
1974 	mutex_enter(&dn->dn_mtx);
1975 	for (i = 0; i < TXG_SIZE; i++) {
1976 		if (dn->dn_free_ranges[i] != NULL &&
1977 		    range_tree_contains(dn->dn_free_ranges[i], blkid, 1))
1978 			break;
1979 	}
1980 	mutex_exit(&dn->dn_mtx);
1981 	return (i < TXG_SIZE);
1982 }
1983 
1984 /* call from syncing context when we actually write/free space for this dnode */
1985 void
dnode_diduse_space(dnode_t * dn,int64_t delta)1986 dnode_diduse_space(dnode_t *dn, int64_t delta)
1987 {
1988 	uint64_t space;
1989 	dprintf_dnode(dn, "dn=%p dnp=%p used=%llu delta=%lld\n",
1990 	    dn, dn->dn_phys,
1991 	    (u_longlong_t)dn->dn_phys->dn_used,
1992 	    (longlong_t)delta);
1993 
1994 	mutex_enter(&dn->dn_mtx);
1995 	space = DN_USED_BYTES(dn->dn_phys);
1996 	if (delta > 0) {
1997 		ASSERT3U(space + delta, >=, space); /* no overflow */
1998 	} else {
1999 		ASSERT3U(space, >=, -delta); /* no underflow */
2000 	}
2001 	space += delta;
2002 	if (spa_version(dn->dn_objset->os_spa) < SPA_VERSION_DNODE_BYTES) {
2003 		ASSERT((dn->dn_phys->dn_flags & DNODE_FLAG_USED_BYTES) == 0);
2004 		ASSERT0(P2PHASE(space, 1<<DEV_BSHIFT));
2005 		dn->dn_phys->dn_used = space >> DEV_BSHIFT;
2006 	} else {
2007 		dn->dn_phys->dn_used = space;
2008 		dn->dn_phys->dn_flags |= DNODE_FLAG_USED_BYTES;
2009 	}
2010 	mutex_exit(&dn->dn_mtx);
2011 }
2012 
2013 /*
2014  * Scans a block at the indicated "level" looking for a hole or data,
2015  * depending on 'flags'.
2016  *
2017  * If level > 0, then we are scanning an indirect block looking at its
2018  * pointers.  If level == 0, then we are looking at a block of dnodes.
2019  *
2020  * If we don't find what we are looking for in the block, we return ESRCH.
2021  * Otherwise, return with *offset pointing to the beginning (if searching
2022  * forwards) or end (if searching backwards) of the range covered by the
2023  * block pointer we matched on (or dnode).
2024  *
2025  * The basic search algorithm used below by dnode_next_offset() is to
2026  * use this function to search up the block tree (widen the search) until
2027  * we find something (i.e., we don't return ESRCH) and then search back
2028  * down the tree (narrow the search) until we reach our original search
2029  * level.
2030  */
2031 static int
dnode_next_offset_level(dnode_t * dn,int flags,uint64_t * offset,int lvl,uint64_t blkfill,uint64_t txg)2032 dnode_next_offset_level(dnode_t *dn, int flags, uint64_t *offset,
2033     int lvl, uint64_t blkfill, uint64_t txg)
2034 {
2035 	dmu_buf_impl_t *db = NULL;
2036 	void *data = NULL;
2037 	uint64_t epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
2038 	uint64_t epb = 1ULL << epbs;
2039 	uint64_t minfill, maxfill;
2040 	boolean_t hole;
2041 	int i, inc, error, span;
2042 
2043 	dprintf("probing object %llu offset %llx level %d of %u\n",
2044 	    dn->dn_object, *offset, lvl, dn->dn_phys->dn_nlevels);
2045 
2046 	hole = ((flags & DNODE_FIND_HOLE) != 0);
2047 	inc = (flags & DNODE_FIND_BACKWARDS) ? -1 : 1;
2048 	ASSERT(txg == 0 || !hole);
2049 
2050 	if (lvl == dn->dn_phys->dn_nlevels) {
2051 		error = 0;
2052 		epb = dn->dn_phys->dn_nblkptr;
2053 		data = dn->dn_phys->dn_blkptr;
2054 	} else {
2055 		uint64_t blkid = dbuf_whichblock(dn, lvl, *offset);
2056 		error = dbuf_hold_impl(dn, lvl, blkid, TRUE, FALSE, FTAG, &db);
2057 		if (error) {
2058 			if (error != ENOENT)
2059 				return (error);
2060 			if (hole)
2061 				return (0);
2062 			/*
2063 			 * This can only happen when we are searching up
2064 			 * the block tree for data.  We don't really need to
2065 			 * adjust the offset, as we will just end up looking
2066 			 * at the pointer to this block in its parent, and its
2067 			 * going to be unallocated, so we will skip over it.
2068 			 */
2069 			return (SET_ERROR(ESRCH));
2070 		}
2071 		error = dbuf_read(db, NULL, DB_RF_CANFAIL | DB_RF_HAVESTRUCT);
2072 		if (error) {
2073 			dbuf_rele(db, FTAG);
2074 			return (error);
2075 		}
2076 		data = db->db.db_data;
2077 	}
2078 
2079 
2080 	if (db != NULL && txg != 0 && (db->db_blkptr == NULL ||
2081 	    db->db_blkptr->blk_birth <= txg ||
2082 	    BP_IS_HOLE(db->db_blkptr))) {
2083 		/*
2084 		 * This can only happen when we are searching up the tree
2085 		 * and these conditions mean that we need to keep climbing.
2086 		 */
2087 		error = SET_ERROR(ESRCH);
2088 	} else if (lvl == 0) {
2089 		dnode_phys_t *dnp = data;
2090 
2091 		ASSERT(dn->dn_type == DMU_OT_DNODE);
2092 		ASSERT(!(flags & DNODE_FIND_BACKWARDS));
2093 
2094 		for (i = (*offset >> DNODE_SHIFT) & (blkfill - 1);
2095 		    i < blkfill; i += dnp[i].dn_extra_slots + 1) {
2096 			if ((dnp[i].dn_type == DMU_OT_NONE) == hole)
2097 				break;
2098 		}
2099 
2100 		if (i == blkfill)
2101 			error = SET_ERROR(ESRCH);
2102 
2103 		*offset = (*offset & ~(DNODE_BLOCK_SIZE - 1)) +
2104 		    (i << DNODE_SHIFT);
2105 	} else {
2106 		blkptr_t *bp = data;
2107 		uint64_t start = *offset;
2108 		span = (lvl - 1) * epbs + dn->dn_datablkshift;
2109 		minfill = 0;
2110 		maxfill = blkfill << ((lvl - 1) * epbs);
2111 
2112 		if (hole)
2113 			maxfill--;
2114 		else
2115 			minfill++;
2116 
2117 		*offset = *offset >> span;
2118 		for (i = BF64_GET(*offset, 0, epbs);
2119 		    i >= 0 && i < epb; i += inc) {
2120 			if (BP_GET_FILL(&bp[i]) >= minfill &&
2121 			    BP_GET_FILL(&bp[i]) <= maxfill &&
2122 			    (hole || bp[i].blk_birth > txg))
2123 				break;
2124 			if (inc > 0 || *offset > 0)
2125 				*offset += inc;
2126 		}
2127 		*offset = *offset << span;
2128 		if (inc < 0) {
2129 			/* traversing backwards; position offset at the end */
2130 			ASSERT3U(*offset, <=, start);
2131 			*offset = MIN(*offset + (1ULL << span) - 1, start);
2132 		} else if (*offset < start) {
2133 			*offset = start;
2134 		}
2135 		if (i < 0 || i >= epb)
2136 			error = SET_ERROR(ESRCH);
2137 	}
2138 
2139 	if (db)
2140 		dbuf_rele(db, FTAG);
2141 
2142 	return (error);
2143 }
2144 
2145 /*
2146  * Find the next hole, data, or sparse region at or after *offset.
2147  * The value 'blkfill' tells us how many items we expect to find
2148  * in an L0 data block; this value is 1 for normal objects,
2149  * DNODES_PER_BLOCK for the meta dnode, and some fraction of
2150  * DNODES_PER_BLOCK when searching for sparse regions thereof.
2151  *
2152  * Examples:
2153  *
2154  * dnode_next_offset(dn, flags, offset, 1, 1, 0);
2155  *	Finds the next/previous hole/data in a file.
2156  *	Used in dmu_offset_next().
2157  *
2158  * dnode_next_offset(mdn, flags, offset, 0, DNODES_PER_BLOCK, txg);
2159  *	Finds the next free/allocated dnode an objset's meta-dnode.
2160  *	Only finds objects that have new contents since txg (ie.
2161  *	bonus buffer changes and content removal are ignored).
2162  *	Used in dmu_object_next().
2163  *
2164  * dnode_next_offset(mdn, DNODE_FIND_HOLE, offset, 2, DNODES_PER_BLOCK >> 2, 0);
2165  *	Finds the next L2 meta-dnode bp that's at most 1/4 full.
2166  *	Used in dmu_object_alloc().
2167  */
2168 int
dnode_next_offset(dnode_t * dn,int flags,uint64_t * offset,int minlvl,uint64_t blkfill,uint64_t txg)2169 dnode_next_offset(dnode_t *dn, int flags, uint64_t *offset,
2170     int minlvl, uint64_t blkfill, uint64_t txg)
2171 {
2172 	uint64_t initial_offset = *offset;
2173 	int lvl, maxlvl;
2174 	int error = 0;
2175 
2176 	if (!(flags & DNODE_FIND_HAVELOCK))
2177 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
2178 
2179 	if (dn->dn_phys->dn_nlevels == 0) {
2180 		error = SET_ERROR(ESRCH);
2181 		goto out;
2182 	}
2183 
2184 	if (dn->dn_datablkshift == 0) {
2185 		if (*offset < dn->dn_datablksz) {
2186 			if (flags & DNODE_FIND_HOLE)
2187 				*offset = dn->dn_datablksz;
2188 		} else {
2189 			error = SET_ERROR(ESRCH);
2190 		}
2191 		goto out;
2192 	}
2193 
2194 	maxlvl = dn->dn_phys->dn_nlevels;
2195 
2196 	for (lvl = minlvl; lvl <= maxlvl; lvl++) {
2197 		error = dnode_next_offset_level(dn,
2198 		    flags, offset, lvl, blkfill, txg);
2199 		if (error != ESRCH)
2200 			break;
2201 	}
2202 
2203 	while (error == 0 && --lvl >= minlvl) {
2204 		error = dnode_next_offset_level(dn,
2205 		    flags, offset, lvl, blkfill, txg);
2206 	}
2207 
2208 	/*
2209 	 * There's always a "virtual hole" at the end of the object, even
2210 	 * if all BP's which physically exist are non-holes.
2211 	 */
2212 	if ((flags & DNODE_FIND_HOLE) && error == ESRCH && txg == 0 &&
2213 	    minlvl == 1 && blkfill == 1 && !(flags & DNODE_FIND_BACKWARDS)) {
2214 		error = 0;
2215 	}
2216 
2217 	if (error == 0 && (flags & DNODE_FIND_BACKWARDS ?
2218 	    initial_offset < *offset : initial_offset > *offset))
2219 		error = SET_ERROR(ESRCH);
2220 out:
2221 	if (!(flags & DNODE_FIND_HAVELOCK))
2222 		rw_exit(&dn->dn_struct_rwlock);
2223 
2224 	return (error);
2225 }
2226