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