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