xref: /freebsd/sys/contrib/openzfs/module/zfs/dnode_sync.c (revision 22649d4dba730d46244fd2dff4fd174903c8379f)
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 /*
14  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
15  * Copyright (c) 2012, 2020 by Delphix. All rights reserved.
16  * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
17  * Copyright 2020 Oxide Computer Company
18  */
19 
20 #include <sys/zfs_context.h>
21 #include <sys/dbuf.h>
22 #include <sys/dnode.h>
23 #include <sys/dmu.h>
24 #include <sys/dmu_tx.h>
25 #include <sys/dmu_objset.h>
26 #include <sys/dmu_recv.h>
27 #include <sys/dsl_dataset.h>
28 #include <sys/spa.h>
29 #include <sys/range_tree.h>
30 #include <sys/zfeature.h>
31 
32 static void
dnode_increase_indirection(dnode_t * dn,dmu_tx_t * tx)33 dnode_increase_indirection(dnode_t *dn, dmu_tx_t *tx)
34 {
35 	dmu_buf_impl_t *db;
36 	int txgoff = tx->tx_txg & TXG_MASK;
37 	int nblkptr = dn->dn_phys->dn_nblkptr;
38 	int old_toplvl = dn->dn_phys->dn_nlevels - 1;
39 	int new_level = dn->dn_next_nlevels[txgoff];
40 	int i;
41 
42 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
43 
44 	/* this dnode can't be paged out because it's dirty */
45 	ASSERT(dn->dn_phys->dn_type != DMU_OT_NONE);
46 	ASSERT(new_level > 1 && dn->dn_phys->dn_nlevels > 0);
47 
48 	db = dbuf_hold_level(dn, dn->dn_phys->dn_nlevels, 0, FTAG);
49 	ASSERT(db != NULL);
50 
51 	dn->dn_phys->dn_nlevels = new_level;
52 	dprintf("os=%p obj=%llu, increase to %d\n", dn->dn_objset,
53 	    (u_longlong_t)dn->dn_object, dn->dn_phys->dn_nlevels);
54 
55 	/*
56 	 * Lock ordering requires that we hold the children's db_mutexes (by
57 	 * calling dbuf_find()) before holding the parent's db_rwlock.  The lock
58 	 * order is imposed by dbuf_read's steps of "grab the lock to protect
59 	 * db_parent, get db_parent, hold db_parent's db_rwlock".
60 	 */
61 	dmu_buf_impl_t *children[DN_MAX_NBLKPTR];
62 	ASSERT3U(nblkptr, <=, DN_MAX_NBLKPTR);
63 	for (i = 0; i < nblkptr; i++) {
64 		children[i] = dbuf_find(dn->dn_objset, dn->dn_object,
65 		    old_toplvl, i, NULL);
66 	}
67 
68 	/* transfer dnode's block pointers to new indirect block */
69 	(void) dbuf_read(db, NULL, DB_RF_MUST_SUCCEED|DB_RF_HAVESTRUCT);
70 	if (dn->dn_dbuf != NULL)
71 		rw_enter(&dn->dn_dbuf->db_rwlock, RW_WRITER);
72 	rw_enter(&db->db_rwlock, RW_WRITER);
73 	ASSERT(db->db.db_data);
74 	ASSERT(arc_released(db->db_buf));
75 	ASSERT3U(sizeof (blkptr_t) * nblkptr, <=, db->db.db_size);
76 	memcpy(db->db.db_data, dn->dn_phys->dn_blkptr,
77 	    sizeof (blkptr_t) * nblkptr);
78 	arc_buf_freeze(db->db_buf);
79 
80 	/* set dbuf's parent pointers to new indirect buf */
81 	for (i = 0; i < nblkptr; i++) {
82 		dmu_buf_impl_t *child = children[i];
83 
84 		if (child == NULL)
85 			continue;
86 #ifdef	ZFS_DEBUG
87 		DB_DNODE_ENTER(child);
88 		ASSERT3P(DB_DNODE(child), ==, dn);
89 		DB_DNODE_EXIT(child);
90 #endif	/* DEBUG */
91 		if (child->db_parent && child->db_parent != dn->dn_dbuf) {
92 			ASSERT(child->db_parent->db_level == db->db_level);
93 			ASSERT(child->db_blkptr !=
94 			    &dn->dn_phys->dn_blkptr[child->db_blkid]);
95 			mutex_exit(&child->db_mtx);
96 			continue;
97 		}
98 		ASSERT(child->db_parent == NULL ||
99 		    child->db_parent == dn->dn_dbuf);
100 
101 		child->db_parent = db;
102 		dbuf_add_ref(db, child);
103 		if (db->db.db_data)
104 			child->db_blkptr = (blkptr_t *)db->db.db_data + i;
105 		else
106 			child->db_blkptr = NULL;
107 		dprintf_dbuf_bp(child, child->db_blkptr,
108 		    "changed db_blkptr to new indirect %s", "");
109 
110 		mutex_exit(&child->db_mtx);
111 	}
112 
113 	memset(dn->dn_phys->dn_blkptr, 0, sizeof (blkptr_t) * nblkptr);
114 
115 	rw_exit(&db->db_rwlock);
116 	if (dn->dn_dbuf != NULL)
117 		rw_exit(&dn->dn_dbuf->db_rwlock);
118 
119 	dbuf_rele(db, FTAG);
120 
121 	rw_exit(&dn->dn_struct_rwlock);
122 }
123 
124 static void
free_blocks(dnode_t * dn,blkptr_t * bp,int num,dmu_tx_t * tx)125 free_blocks(dnode_t *dn, blkptr_t *bp, int num, dmu_tx_t *tx)
126 {
127 	dsl_dataset_t *ds = dn->dn_objset->os_dsl_dataset;
128 	uint64_t bytesfreed = 0;
129 
130 	dprintf("ds=%p obj=%llx num=%d\n", ds, (u_longlong_t)dn->dn_object,
131 	    num);
132 
133 	for (int i = 0; i < num; i++, bp++) {
134 		if (BP_IS_HOLE(bp))
135 			continue;
136 
137 		bytesfreed += dsl_dataset_block_kill(ds, bp, tx, B_FALSE);
138 		ASSERT3U(bytesfreed, <=, DN_USED_BYTES(dn->dn_phys));
139 
140 		/*
141 		 * Save some useful information on the holes being
142 		 * punched, including logical size, type, and indirection
143 		 * level. Retaining birth time enables detection of when
144 		 * holes are punched for reducing the number of free
145 		 * records transmitted during a zfs send.
146 		 */
147 
148 		uint64_t lsize = BP_GET_LSIZE(bp);
149 		dmu_object_type_t type = BP_GET_TYPE(bp);
150 		uint64_t lvl = BP_GET_LEVEL(bp);
151 
152 		memset(bp, 0, sizeof (blkptr_t));
153 
154 		if (spa_feature_is_active(dn->dn_objset->os_spa,
155 		    SPA_FEATURE_HOLE_BIRTH)) {
156 			BP_SET_LSIZE(bp, lsize);
157 			BP_SET_TYPE(bp, type);
158 			BP_SET_LEVEL(bp, lvl);
159 			BP_SET_BIRTH(bp, dmu_tx_get_txg(tx), 0);
160 		}
161 	}
162 	dnode_diduse_space(dn, -bytesfreed);
163 }
164 
165 #ifdef ZFS_DEBUG
166 static void
free_verify(dmu_buf_impl_t * db,uint64_t start,uint64_t end,dmu_tx_t * tx)167 free_verify(dmu_buf_impl_t *db, uint64_t start, uint64_t end, dmu_tx_t *tx)
168 {
169 	uint64_t off, num, i, j;
170 	unsigned int epbs;
171 	int err;
172 	uint64_t txg = tx->tx_txg;
173 	dnode_t *dn;
174 
175 	DB_DNODE_ENTER(db);
176 	dn = DB_DNODE(db);
177 	epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
178 	off = start - (db->db_blkid << epbs);
179 	num = end - start + 1;
180 
181 	ASSERT3U(dn->dn_phys->dn_indblkshift, >=, SPA_BLKPTRSHIFT);
182 	ASSERT3U(end + 1, >=, start);
183 	ASSERT3U(start, >=, (db->db_blkid << epbs));
184 	ASSERT3U(db->db_level, >, 0);
185 	ASSERT3U(db->db.db_size, ==, 1 << dn->dn_phys->dn_indblkshift);
186 	ASSERT3U(off+num, <=, db->db.db_size >> SPA_BLKPTRSHIFT);
187 	ASSERT(db->db_blkptr != NULL);
188 
189 	for (i = off; i < off+num; i++) {
190 		uint64_t *buf;
191 		dmu_buf_impl_t *child;
192 		dbuf_dirty_record_t *dr;
193 
194 		ASSERT(db->db_level == 1);
195 
196 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
197 		err = dbuf_hold_impl(dn, db->db_level - 1,
198 		    (db->db_blkid << epbs) + i, TRUE, FALSE, FTAG, &child);
199 		rw_exit(&dn->dn_struct_rwlock);
200 		if (err == ENOENT)
201 			continue;
202 		ASSERT0(err);
203 		ASSERT0(child->db_level);
204 		dr = dbuf_find_dirty_eq(child, txg);
205 
206 		/* data_old better be zeroed */
207 		if (dr) {
208 			buf = dr->dt.dl.dr_data->b_data;
209 			for (j = 0; j < child->db.db_size >> 3; j++) {
210 				if (buf[j] != 0) {
211 					panic("freed data not zero: "
212 					    "child=%p i=%llu off=%llu "
213 					    "num=%llu\n",
214 					    (void *)child, (u_longlong_t)i,
215 					    (u_longlong_t)off,
216 					    (u_longlong_t)num);
217 				}
218 			}
219 		}
220 
221 		/*
222 		 * db_data better be zeroed unless it's dirty in a
223 		 * future txg.
224 		 */
225 		mutex_enter(&child->db_mtx);
226 		buf = child->db.db_data;
227 		if (buf != NULL && child->db_state != DB_FILL &&
228 		    list_is_empty(&child->db_dirty_records)) {
229 			for (j = 0; j < child->db.db_size >> 3; j++) {
230 				if (buf[j] != 0) {
231 					panic("freed data not zero: "
232 					    "child=%p i=%llu off=%llu "
233 					    "num=%llu\n",
234 					    (void *)child, (u_longlong_t)i,
235 					    (u_longlong_t)off,
236 					    (u_longlong_t)num);
237 				}
238 			}
239 		}
240 		mutex_exit(&child->db_mtx);
241 
242 		dbuf_rele(child, FTAG);
243 	}
244 	DB_DNODE_EXIT(db);
245 }
246 #endif
247 
248 /*
249  * We don't usually free the indirect blocks here.  If in one txg we have a
250  * free_range and a write to the same indirect block, it's important that we
251  * preserve the hole's birth times. Therefore, we don't free any any indirect
252  * blocks in free_children().  If an indirect block happens to turn into all
253  * holes, it will be freed by dbuf_write_children_ready, which happens at a
254  * point in the syncing process where we know for certain the contents of the
255  * indirect block.
256  *
257  * However, if we're freeing a dnode, its space accounting must go to zero
258  * before we actually try to free the dnode, or we will trip an assertion. In
259  * addition, we know the case described above cannot occur, because the dnode is
260  * being freed.  Therefore, we free the indirect blocks immediately in that
261  * case.
262  */
263 static void
free_children(dmu_buf_impl_t * db,uint64_t blkid,uint64_t nblks,boolean_t free_indirects,dmu_tx_t * tx)264 free_children(dmu_buf_impl_t *db, uint64_t blkid, uint64_t nblks,
265     boolean_t free_indirects, dmu_tx_t *tx)
266 {
267 	dnode_t *dn;
268 	blkptr_t *bp;
269 	dmu_buf_impl_t *subdb;
270 	uint64_t start, end, dbstart, dbend;
271 	unsigned int epbs, shift, i;
272 
273 	/*
274 	 * There is a small possibility that this block will not be cached:
275 	 *   1 - if level > 1 and there are no children with level <= 1
276 	 *   2 - if this block was evicted since we read it from
277 	 *	 dmu_tx_hold_free().
278 	 */
279 	if (db->db_state != DB_CACHED)
280 		(void) dbuf_read(db, NULL, DB_RF_MUST_SUCCEED);
281 
282 	/*
283 	 * If we modify this indirect block, and we are not freeing the
284 	 * dnode (!free_indirects), then this indirect block needs to get
285 	 * written to disk by dbuf_write().  If it is dirty, we know it will
286 	 * be written (otherwise, we would have incorrect on-disk state
287 	 * because the space would be freed but still referenced by the BP
288 	 * in this indirect block).  Therefore we VERIFY that it is
289 	 * dirty.
290 	 *
291 	 * Our VERIFY covers some cases that do not actually have to be
292 	 * dirty, but the open-context code happens to dirty.  E.g. if the
293 	 * blocks we are freeing are all holes, because in that case, we
294 	 * are only freeing part of this indirect block, so it is an
295 	 * ancestor of the first or last block to be freed.  The first and
296 	 * last L1 indirect blocks are always dirtied by dnode_free_range().
297 	 */
298 	if (!free_indirects) {
299 		db_lock_type_t dblt = dmu_buf_lock_parent(db, RW_READER, FTAG);
300 		VERIFY_IMPLY(BP_GET_FILL(db->db_blkptr) > 0,
301 		    db->db_dirtycnt > 0);
302 		dmu_buf_unlock_parent(db, dblt, FTAG);
303 	}
304 
305 	dbuf_release_bp(db);
306 	bp = db->db.db_data;
307 
308 	DB_DNODE_ENTER(db);
309 	dn = DB_DNODE(db);
310 	epbs = dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
311 	ASSERT3U(epbs, <, 31);
312 	shift = (db->db_level - 1) * epbs;
313 	dbstart = db->db_blkid << epbs;
314 	start = blkid >> shift;
315 	if (dbstart < start) {
316 		bp += start - dbstart;
317 	} else {
318 		start = dbstart;
319 	}
320 	dbend = ((db->db_blkid + 1) << epbs) - 1;
321 	end = (blkid + nblks - 1) >> shift;
322 	if (dbend <= end)
323 		end = dbend;
324 
325 	ASSERT3U(start, <=, end);
326 
327 	if (db->db_level == 1) {
328 		FREE_VERIFY(db, start, end, tx);
329 		rw_enter(&db->db_rwlock, RW_WRITER);
330 		free_blocks(dn, bp, end - start + 1, tx);
331 		rw_exit(&db->db_rwlock);
332 	} else {
333 		for (uint64_t id = start; id <= end; id++, bp++) {
334 			if (BP_IS_HOLE(bp))
335 				continue;
336 			rw_enter(&dn->dn_struct_rwlock, RW_READER);
337 			VERIFY0(dbuf_hold_impl(dn, db->db_level - 1,
338 			    id, TRUE, FALSE, FTAG, &subdb));
339 			rw_exit(&dn->dn_struct_rwlock);
340 			ASSERT3P(bp, ==, subdb->db_blkptr);
341 
342 			free_children(subdb, blkid, nblks, free_indirects, tx);
343 			dbuf_rele(subdb, FTAG);
344 		}
345 	}
346 
347 	if (free_indirects) {
348 		rw_enter(&db->db_rwlock, RW_WRITER);
349 		for (i = 0, bp = db->db.db_data; i < 1 << epbs; i++, bp++)
350 			ASSERT(BP_IS_HOLE(bp));
351 		memset(db->db.db_data, 0, db->db.db_size);
352 		free_blocks(dn, db->db_blkptr, 1, tx);
353 		rw_exit(&db->db_rwlock);
354 	}
355 
356 	DB_DNODE_EXIT(db);
357 	arc_buf_freeze(db->db_buf);
358 }
359 
360 /*
361  * Traverse the indicated range of the provided file
362  * and "free" all the blocks contained there.
363  */
364 static void
dnode_sync_free_range_impl(dnode_t * dn,uint64_t blkid,uint64_t nblks,boolean_t free_indirects,dmu_tx_t * tx)365 dnode_sync_free_range_impl(dnode_t *dn, uint64_t blkid, uint64_t nblks,
366     boolean_t free_indirects, dmu_tx_t *tx)
367 {
368 	blkptr_t *bp = dn->dn_phys->dn_blkptr;
369 	int dnlevel = dn->dn_phys->dn_nlevels;
370 	boolean_t trunc = B_FALSE;
371 
372 	if (blkid > dn->dn_phys->dn_maxblkid)
373 		return;
374 
375 	ASSERT(dn->dn_phys->dn_maxblkid < UINT64_MAX);
376 	if (blkid + nblks > dn->dn_phys->dn_maxblkid) {
377 		nblks = dn->dn_phys->dn_maxblkid - blkid + 1;
378 		trunc = B_TRUE;
379 	}
380 
381 	/* There are no indirect blocks in the object */
382 	if (dnlevel == 1) {
383 		if (blkid >= dn->dn_phys->dn_nblkptr) {
384 			/* this range was never made persistent */
385 			return;
386 		}
387 		ASSERT3U(blkid + nblks, <=, dn->dn_phys->dn_nblkptr);
388 		free_blocks(dn, bp + blkid, nblks, tx);
389 	} else {
390 		int shift = (dnlevel - 1) *
391 		    (dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT);
392 		int start = blkid >> shift;
393 		int end = (blkid + nblks - 1) >> shift;
394 		dmu_buf_impl_t *db;
395 
396 		ASSERT(start < dn->dn_phys->dn_nblkptr);
397 		bp += start;
398 		for (int i = start; i <= end; i++, bp++) {
399 			if (BP_IS_HOLE(bp))
400 				continue;
401 			rw_enter(&dn->dn_struct_rwlock, RW_READER);
402 			VERIFY0(dbuf_hold_impl(dn, dnlevel - 1, i,
403 			    TRUE, FALSE, FTAG, &db));
404 			rw_exit(&dn->dn_struct_rwlock);
405 			free_children(db, blkid, nblks, free_indirects, tx);
406 			dbuf_rele(db, FTAG);
407 		}
408 	}
409 
410 	/*
411 	 * Do not truncate the maxblkid if we are performing a raw
412 	 * receive. The raw receive sets the maxblkid manually and
413 	 * must not be overridden. Usually, the last DRR_FREE record
414 	 * will be at the maxblkid, because the source system sets
415 	 * the maxblkid when truncating. However, if the last block
416 	 * was freed by overwriting with zeros and being compressed
417 	 * away to a hole, the source system will generate a DRR_FREE
418 	 * record while leaving the maxblkid after the end of that
419 	 * record. In this case we need to leave the maxblkid as
420 	 * indicated in the DRR_OBJECT record, so that it matches the
421 	 * source system, ensuring that the cryptographic hashes will
422 	 * match.
423 	 */
424 	if (trunc && !dn->dn_objset->os_raw_receive) {
425 		uint64_t off __maybe_unused;
426 		dn->dn_phys->dn_maxblkid = blkid == 0 ? 0 : blkid - 1;
427 
428 		off = (dn->dn_phys->dn_maxblkid + 1) *
429 		    (dn->dn_phys->dn_datablkszsec << SPA_MINBLOCKSHIFT);
430 		ASSERT(off < dn->dn_phys->dn_maxblkid ||
431 		    dn->dn_phys->dn_maxblkid == 0 ||
432 		    dnode_next_offset(dn, 0, &off, 1, 1, 0) != 0);
433 	}
434 }
435 
436 /*
437  * Try to kick all the dnode's dbufs out of the cache...
438  */
439 void
dnode_evict_dbufs(dnode_t * dn)440 dnode_evict_dbufs(dnode_t *dn)
441 {
442 	dmu_buf_impl_t *db_marker;
443 	dmu_buf_impl_t *db, *db_next;
444 
445 	db_marker = kmem_alloc(sizeof (dmu_buf_impl_t), KM_SLEEP);
446 
447 	mutex_enter(&dn->dn_dbufs_mtx);
448 	for (db = avl_first(&dn->dn_dbufs); db != NULL; db = db_next) {
449 
450 #ifdef	ZFS_DEBUG
451 		DB_DNODE_ENTER(db);
452 		ASSERT3P(DB_DNODE(db), ==, dn);
453 		DB_DNODE_EXIT(db);
454 #endif	/* DEBUG */
455 
456 		mutex_enter(&db->db_mtx);
457 		if (db->db_state != DB_EVICTING &&
458 		    zfs_refcount_is_zero(&db->db_holds)) {
459 			db_marker->db_level = db->db_level;
460 			db_marker->db_blkid = db->db_blkid;
461 			/*
462 			 * Insert a MARKER node with the same level and blkid.
463 			 * And to resolve any ties in dbuf_compare() use the
464 			 * pointer of the dbuf that we are evicting. Pass the
465 			 * address in db_parent.
466 			 */
467 			db_marker->db_state = DB_MARKER;
468 			db_marker->db_parent = (void *)((uintptr_t)db - 1);
469 			avl_insert_here(&dn->dn_dbufs, db_marker, db,
470 			    AVL_BEFORE);
471 
472 			/*
473 			 * We need to use the "marker" dbuf rather than
474 			 * simply getting the next dbuf, because
475 			 * dbuf_destroy() may actually remove multiple dbufs.
476 			 * It can call itself recursively on the parent dbuf,
477 			 * which may also be removed from dn_dbufs.  The code
478 			 * flow would look like:
479 			 *
480 			 * dbuf_destroy():
481 			 *   dnode_rele_and_unlock(parent_dbuf, evicting=TRUE):
482 			 *	if (!cacheable || pending_evict)
483 			 *	  dbuf_destroy()
484 			 */
485 			dbuf_destroy(db);
486 
487 			db_next = AVL_NEXT(&dn->dn_dbufs, db_marker);
488 			avl_remove(&dn->dn_dbufs, db_marker);
489 		} else {
490 			db->db_pending_evict = TRUE;
491 			db->db_partial_read = FALSE;
492 			mutex_exit(&db->db_mtx);
493 			db_next = AVL_NEXT(&dn->dn_dbufs, db);
494 		}
495 	}
496 	mutex_exit(&dn->dn_dbufs_mtx);
497 
498 	kmem_free(db_marker, sizeof (dmu_buf_impl_t));
499 
500 	dnode_evict_bonus(dn);
501 }
502 
503 void
dnode_evict_bonus(dnode_t * dn)504 dnode_evict_bonus(dnode_t *dn)
505 {
506 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
507 	if (dn->dn_bonus != NULL) {
508 		if (zfs_refcount_is_zero(&dn->dn_bonus->db_holds)) {
509 			mutex_enter(&dn->dn_bonus->db_mtx);
510 			dbuf_destroy(dn->dn_bonus);
511 			dn->dn_bonus = NULL;
512 		} else {
513 			dn->dn_bonus->db_pending_evict = TRUE;
514 		}
515 	}
516 	rw_exit(&dn->dn_struct_rwlock);
517 }
518 
519 static void
dnode_undirty_dbufs(list_t * list)520 dnode_undirty_dbufs(list_t *list)
521 {
522 	dbuf_dirty_record_t *dr;
523 
524 	while ((dr = list_head(list))) {
525 		dmu_buf_impl_t *db = dr->dr_dbuf;
526 		uint64_t txg = dr->dr_txg;
527 
528 		if (db->db_level != 0)
529 			dnode_undirty_dbufs(&dr->dt.di.dr_children);
530 
531 		mutex_enter(&db->db_mtx);
532 		/* XXX - use dbuf_undirty()? */
533 		list_remove(list, dr);
534 		ASSERT(list_head(&db->db_dirty_records) == dr);
535 		list_remove_head(&db->db_dirty_records);
536 		ASSERT(list_is_empty(&db->db_dirty_records));
537 		db->db_dirtycnt -= 1;
538 		if (db->db_level == 0) {
539 			ASSERT(db->db_blkid == DMU_BONUS_BLKID ||
540 			    dr->dt.dl.dr_data == db->db_buf);
541 			dbuf_unoverride(dr);
542 		} else {
543 			mutex_destroy(&dr->dt.di.dr_mtx);
544 			list_destroy(&dr->dt.di.dr_children);
545 		}
546 		kmem_cache_free(dbuf_dirty_kmem_cache, dr);
547 		dbuf_rele_and_unlock(db, (void *)(uintptr_t)txg, B_FALSE);
548 	}
549 }
550 
551 static void
dnode_sync_free(dnode_t * dn,dmu_tx_t * tx)552 dnode_sync_free(dnode_t *dn, dmu_tx_t *tx)
553 {
554 	int txgoff = tx->tx_txg & TXG_MASK;
555 
556 	ASSERT(dmu_tx_is_syncing(tx));
557 
558 	/*
559 	 * Our contents should have been freed in dnode_sync() by the
560 	 * free range record inserted by the caller of dnode_free().
561 	 */
562 	ASSERT0(DN_USED_BYTES(dn->dn_phys));
563 	ASSERT(BP_IS_HOLE(dn->dn_phys->dn_blkptr));
564 
565 	dnode_undirty_dbufs(&dn->dn_dirty_records[txgoff]);
566 	dnode_evict_dbufs(dn);
567 
568 	/*
569 	 * XXX - It would be nice to assert this, but we may still
570 	 * have residual holds from async evictions from the arc...
571 	 *
572 	 * zfs_obj_to_path() also depends on this being
573 	 * commented out.
574 	 *
575 	 * ASSERT3U(zfs_refcount_count(&dn->dn_holds), ==, 1);
576 	 */
577 
578 	/* Undirty next bits */
579 	dn->dn_next_nlevels[txgoff] = 0;
580 	dn->dn_next_indblkshift[txgoff] = 0;
581 	dn->dn_next_blksz[txgoff] = 0;
582 	dn->dn_next_maxblkid[txgoff] = 0;
583 
584 	/* ASSERT(blkptrs are zero); */
585 	ASSERT(dn->dn_phys->dn_type != DMU_OT_NONE);
586 	ASSERT(dn->dn_type != DMU_OT_NONE);
587 
588 	ASSERT(dn->dn_free_txg > 0);
589 	if (dn->dn_allocated_txg != dn->dn_free_txg)
590 		dmu_buf_will_dirty(&dn->dn_dbuf->db, tx);
591 	memset(dn->dn_phys, 0, sizeof (dnode_phys_t) * dn->dn_num_slots);
592 	dnode_free_interior_slots(dn);
593 
594 	mutex_enter(&dn->dn_mtx);
595 	dn->dn_type = DMU_OT_NONE;
596 	dn->dn_maxblkid = 0;
597 	dn->dn_allocated_txg = 0;
598 	dn->dn_free_txg = 0;
599 	dn->dn_have_spill = B_FALSE;
600 	dn->dn_num_slots = 1;
601 	mutex_exit(&dn->dn_mtx);
602 
603 	ASSERT(dn->dn_object != DMU_META_DNODE_OBJECT);
604 
605 	dnode_rele(dn, (void *)(uintptr_t)tx->tx_txg);
606 	/*
607 	 * Now that we've released our hold, the dnode may
608 	 * be evicted, so we mustn't access it.
609 	 */
610 }
611 
612 /*
613  * We cannot simply detach the range tree (set dn_free_ranges to NULL)
614  * before processing it because dnode_block_freed() relies on it to
615  * correctly identify blocks that have been freed in the current TXG
616  * (for dbuf_read() calls on holes). If we detached it early, a concurrent
617  * reader might see the block as valid on disk and return stale data
618  * instead of zeros.
619  *
620  * We also can't use zfs_range_tree_walk() nor zfs_range_tree_vacate()
621  * with a callback that drops dn_mtx (dnode_sync_free_range()). This is
622  * unsafe because another thread (spa_sync_deferred_frees() ->
623  * dnode_free_range()) could acquire dn_mtx and modify the tree while the
624  * walk or vacate was in progress. This leads to tree corruption or panic
625  * when we resume.
626  *
627  * To fix the race while maintaining visibility, we process the tree
628  * incrementally. We pick a segment, drop the lock to sync it, and
629  * re-acquire the lock to remove it. By always restarting from the head
630  * of the tree, we ensure we are never using an invalid iterator.
631  * We use zfs_range_tree_clear() instead of ..._remove() because the range
632  * might have already been removed while the lock was dropped (specifically
633  * in the dbuf_dirty path mentioned above). ..._clear() handles this
634  * gracefully, while ..._remove() would panic on a missing segment.
635  */
636 static void
dnode_sync_free_ranges(dnode_t * dn,dmu_tx_t * tx)637 dnode_sync_free_ranges(dnode_t *dn, dmu_tx_t *tx)
638 {
639 	int txgoff = tx->tx_txg & TXG_MASK;
640 
641 	mutex_enter(&dn->dn_mtx);
642 	zfs_range_tree_t *rt = dn->dn_free_ranges[txgoff];
643 	if (rt != NULL) {
644 		boolean_t freeing_dnode = dn->dn_free_txg > 0 &&
645 		    dn->dn_free_txg <= tx->tx_txg;
646 		zfs_range_seg_t *rs;
647 
648 		if (freeing_dnode) {
649 			ASSERT(zfs_range_tree_contains(rt, 0,
650 			    dn->dn_maxblkid + 1));
651 		}
652 
653 		while ((rs = zfs_range_tree_first(rt)) != NULL) {
654 			uint64_t start = zfs_rs_get_start(rs, rt);
655 			uint64_t size = zfs_rs_get_end(rs, rt) - start;
656 
657 			mutex_exit(&dn->dn_mtx);
658 			dnode_sync_free_range_impl(dn, start, size,
659 			    freeing_dnode, tx);
660 			mutex_enter(&dn->dn_mtx);
661 
662 			zfs_range_tree_clear(rt, start, size);
663 		}
664 		zfs_range_tree_destroy(rt);
665 		dn->dn_free_ranges[txgoff] = NULL;
666 	}
667 	mutex_exit(&dn->dn_mtx);
668 }
669 
670 /*
671  * Write out the dnode's dirty buffers.
672  * Does not wait for zio completions.
673  */
674 void
dnode_sync(dnode_t * dn,dmu_tx_t * tx)675 dnode_sync(dnode_t *dn, dmu_tx_t *tx)
676 {
677 	objset_t *os = dn->dn_objset;
678 	dnode_phys_t *dnp = dn->dn_phys;
679 	int txgoff = tx->tx_txg & TXG_MASK;
680 	list_t *list = &dn->dn_dirty_records[txgoff];
681 	static const dnode_phys_t zerodn __maybe_unused = { 0 };
682 	boolean_t kill_spill = B_FALSE;
683 
684 	ASSERT(dmu_tx_is_syncing(tx));
685 	ASSERT(dnp->dn_type != DMU_OT_NONE || dn->dn_allocated_txg);
686 	ASSERT(dnp->dn_type != DMU_OT_NONE ||
687 	    memcmp(dnp, &zerodn, DNODE_MIN_SIZE) == 0);
688 	DNODE_VERIFY(dn);
689 
690 	ASSERT(dn->dn_dbuf == NULL || arc_released(dn->dn_dbuf->db_buf));
691 
692 	/*
693 	 * Do user accounting if it is enabled and this is not
694 	 * an encrypted receive.
695 	 */
696 	if (dmu_objset_userused_enabled(os) &&
697 	    !DMU_OBJECT_IS_SPECIAL(dn->dn_object) &&
698 	    (!os->os_encrypted || !dmu_objset_is_receiving(os))) {
699 		mutex_enter(&dn->dn_mtx);
700 		dn->dn_oldused = DN_USED_BYTES(dn->dn_phys);
701 		dn->dn_oldflags = dn->dn_phys->dn_flags;
702 		dn->dn_phys->dn_flags |= DNODE_FLAG_USERUSED_ACCOUNTED;
703 		if (dmu_objset_userobjused_enabled(dn->dn_objset))
704 			dn->dn_phys->dn_flags |=
705 			    DNODE_FLAG_USEROBJUSED_ACCOUNTED;
706 		mutex_exit(&dn->dn_mtx);
707 		dmu_objset_userquota_get_ids(dn, B_FALSE, tx);
708 	} else if (!(os->os_encrypted && dmu_objset_is_receiving(os))) {
709 		/*
710 		 * Once we account for it, we should always account for it,
711 		 * except for the case of a raw receive. We will not be able
712 		 * to account for it until the receiving dataset has been
713 		 * mounted.
714 		 */
715 		ASSERT(!(dn->dn_phys->dn_flags &
716 		    DNODE_FLAG_USERUSED_ACCOUNTED));
717 		ASSERT(!(dn->dn_phys->dn_flags &
718 		    DNODE_FLAG_USEROBJUSED_ACCOUNTED));
719 	}
720 
721 	mutex_enter(&dn->dn_mtx);
722 	if (dn->dn_allocated_txg == tx->tx_txg) {
723 		/* The dnode is newly allocated or reallocated */
724 		if (dnp->dn_type == DMU_OT_NONE) {
725 			/* this is a first alloc, not a realloc */
726 			dnp->dn_nlevels = 1;
727 			dnp->dn_nblkptr = dn->dn_nblkptr;
728 		}
729 
730 		dnp->dn_type = dn->dn_type;
731 		dnp->dn_bonustype = dn->dn_bonustype;
732 		dnp->dn_bonuslen = dn->dn_bonuslen;
733 	}
734 
735 	dnp->dn_extra_slots = dn->dn_num_slots - 1;
736 
737 	ASSERT(dnp->dn_nlevels > 1 ||
738 	    BP_IS_HOLE(&dnp->dn_blkptr[0]) ||
739 	    BP_IS_EMBEDDED(&dnp->dn_blkptr[0]) ||
740 	    BP_GET_LSIZE(&dnp->dn_blkptr[0]) ==
741 	    dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT);
742 	ASSERT(dnp->dn_nlevels < 2 ||
743 	    BP_IS_HOLE(&dnp->dn_blkptr[0]) ||
744 	    BP_GET_LSIZE(&dnp->dn_blkptr[0]) == 1 << dnp->dn_indblkshift);
745 
746 	if (dn->dn_next_type[txgoff] != 0) {
747 		dnp->dn_type = dn->dn_type;
748 		dn->dn_next_type[txgoff] = 0;
749 	}
750 
751 	if (dn->dn_next_blksz[txgoff] != 0) {
752 		ASSERT(P2PHASE(dn->dn_next_blksz[txgoff],
753 		    SPA_MINBLOCKSIZE) == 0);
754 		ASSERT(BP_IS_HOLE(&dnp->dn_blkptr[0]) ||
755 		    dn->dn_maxblkid == 0 || list_head(list) != NULL ||
756 		    dn->dn_next_blksz[txgoff] >> SPA_MINBLOCKSHIFT ==
757 		    dnp->dn_datablkszsec ||
758 		    !zfs_range_tree_is_empty(dn->dn_free_ranges[txgoff]));
759 		dnp->dn_datablkszsec =
760 		    dn->dn_next_blksz[txgoff] >> SPA_MINBLOCKSHIFT;
761 		dn->dn_next_blksz[txgoff] = 0;
762 	}
763 
764 	if (dn->dn_next_bonuslen[txgoff] != 0) {
765 		if (dn->dn_next_bonuslen[txgoff] == DN_ZERO_BONUSLEN)
766 			dnp->dn_bonuslen = 0;
767 		else
768 			dnp->dn_bonuslen = dn->dn_next_bonuslen[txgoff];
769 		ASSERT(dnp->dn_bonuslen <=
770 		    DN_SLOTS_TO_BONUSLEN(dnp->dn_extra_slots + 1));
771 		dn->dn_next_bonuslen[txgoff] = 0;
772 	}
773 
774 	if (dn->dn_next_bonustype[txgoff] != 0) {
775 		ASSERT(DMU_OT_IS_VALID(dn->dn_next_bonustype[txgoff]));
776 		dnp->dn_bonustype = dn->dn_next_bonustype[txgoff];
777 		dn->dn_next_bonustype[txgoff] = 0;
778 	}
779 
780 	boolean_t freeing_dnode = dn->dn_free_txg > 0 &&
781 	    dn->dn_free_txg <= tx->tx_txg;
782 
783 	/*
784 	 * Remove the spill block if we have been explicitly asked to
785 	 * remove it, or if the object is being removed.
786 	 */
787 	if (dn->dn_rm_spillblk[txgoff] || freeing_dnode) {
788 		if (dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR)
789 			kill_spill = B_TRUE;
790 		dn->dn_rm_spillblk[txgoff] = 0;
791 	}
792 
793 	if (dn->dn_next_indblkshift[txgoff] != 0) {
794 		ASSERT(dnp->dn_nlevels == 1);
795 		dnp->dn_indblkshift = dn->dn_next_indblkshift[txgoff];
796 		dn->dn_next_indblkshift[txgoff] = 0;
797 	}
798 
799 	/*
800 	 * Just take the live (open-context) values for checksum and compress.
801 	 * Strictly speaking it's a future leak, but nothing bad happens if we
802 	 * start using the new checksum or compress algorithm a little early.
803 	 */
804 	dnp->dn_checksum = dn->dn_checksum;
805 	dnp->dn_compress = dn->dn_compress;
806 
807 	mutex_exit(&dn->dn_mtx);
808 
809 	if (kill_spill) {
810 		free_blocks(dn, DN_SPILL_BLKPTR(dn->dn_phys), 1, tx);
811 		mutex_enter(&dn->dn_mtx);
812 		dnp->dn_flags &= ~DNODE_FLAG_SPILL_BLKPTR;
813 		mutex_exit(&dn->dn_mtx);
814 	}
815 
816 	/* process all the "freed" ranges in the file */
817 	dnode_sync_free_ranges(dn, tx);
818 
819 	if (freeing_dnode) {
820 		dn->dn_objset->os_freed_dnodes++;
821 		dnode_sync_free(dn, tx);
822 		return;
823 	}
824 
825 	if (dn->dn_num_slots > DNODE_MIN_SLOTS) {
826 		dsl_dataset_t *ds = dn->dn_objset->os_dsl_dataset;
827 		mutex_enter(&ds->ds_lock);
828 		ds->ds_feature_activation[SPA_FEATURE_LARGE_DNODE] =
829 		    (void *)B_TRUE;
830 		mutex_exit(&ds->ds_lock);
831 	}
832 
833 	if (dn->dn_next_nlevels[txgoff]) {
834 		dnode_increase_indirection(dn, tx);
835 		dn->dn_next_nlevels[txgoff] = 0;
836 	}
837 
838 	/*
839 	 * This must be done after dnode_sync_free_ranges()
840 	 * and dnode_increase_indirection(). See dnode_new_blkid()
841 	 * for an explanation of the high bit being set.
842 	 */
843 	if (dn->dn_next_maxblkid[txgoff]) {
844 		mutex_enter(&dn->dn_mtx);
845 		dnp->dn_maxblkid =
846 		    dn->dn_next_maxblkid[txgoff] & ~DMU_NEXT_MAXBLKID_SET;
847 		dn->dn_next_maxblkid[txgoff] = 0;
848 		mutex_exit(&dn->dn_mtx);
849 	}
850 
851 	if (dn->dn_next_nblkptr[txgoff]) {
852 		/* this should only happen on a realloc */
853 		ASSERT(dn->dn_allocated_txg == tx->tx_txg);
854 		if (dn->dn_next_nblkptr[txgoff] > dnp->dn_nblkptr) {
855 			/* zero the new blkptrs we are gaining */
856 			memset(dnp->dn_blkptr + dnp->dn_nblkptr, 0,
857 			    sizeof (blkptr_t) *
858 			    (dn->dn_next_nblkptr[txgoff] - dnp->dn_nblkptr));
859 #ifdef ZFS_DEBUG
860 		} else {
861 			int i;
862 			ASSERT(dn->dn_next_nblkptr[txgoff] < dnp->dn_nblkptr);
863 			/* the blkptrs we are losing better be unallocated */
864 			for (i = 0; i < dnp->dn_nblkptr; i++) {
865 				if (i >= dn->dn_next_nblkptr[txgoff])
866 					ASSERT(BP_IS_HOLE(&dnp->dn_blkptr[i]));
867 			}
868 #endif
869 		}
870 		mutex_enter(&dn->dn_mtx);
871 		dnp->dn_nblkptr = dn->dn_next_nblkptr[txgoff];
872 		dn->dn_next_nblkptr[txgoff] = 0;
873 		mutex_exit(&dn->dn_mtx);
874 	}
875 
876 	dbuf_sync_list(list, dn->dn_phys->dn_nlevels - 1, tx);
877 
878 	if (!DMU_OBJECT_IS_SPECIAL(dn->dn_object)) {
879 		ASSERT0P(list_head(list));
880 		dnode_rele(dn, (void *)(uintptr_t)tx->tx_txg);
881 	}
882 
883 	ASSERT3U(dnp->dn_bonuslen, <=, DN_MAX_BONUS_LEN(dnp));
884 
885 	/*
886 	 * Although we have dropped our reference to the dnode, it
887 	 * can't be evicted until its written, and we haven't yet
888 	 * initiated the IO for the dnode's dbuf.  Additionally, the caller
889 	 * has already added a reference to the dnode because it's on the
890 	 * os_synced_dnodes list.
891 	 */
892 }
893