xref: /linux/fs/xfs/scrub/repair.c (revision f0100363d8c374bd8e9ea7c9ba02744f0b802ca4)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (C) 2018-2023 Oracle.  All Rights Reserved.
4  * Author: Darrick J. Wong <djwong@kernel.org>
5  */
6 #include "xfs_platform.h"
7 #include "xfs_fs.h"
8 #include "xfs_shared.h"
9 #include "xfs_format.h"
10 #include "xfs_trans_resv.h"
11 #include "xfs_mount.h"
12 #include "xfs_btree.h"
13 #include "xfs_log_format.h"
14 #include "xfs_trans.h"
15 #include "xfs_sb.h"
16 #include "xfs_inode.h"
17 #include "xfs_alloc.h"
18 #include "xfs_alloc_btree.h"
19 #include "xfs_ialloc.h"
20 #include "xfs_ialloc_btree.h"
21 #include "xfs_rmap.h"
22 #include "xfs_rmap_btree.h"
23 #include "xfs_refcount_btree.h"
24 #include "xfs_rtbitmap.h"
25 #include "xfs_extent_busy.h"
26 #include "xfs_ag.h"
27 #include "xfs_ag_resv.h"
28 #include "xfs_quota.h"
29 #include "xfs_qm.h"
30 #include "xfs_defer.h"
31 #include "xfs_errortag.h"
32 #include "xfs_error.h"
33 #include "xfs_reflink.h"
34 #include "xfs_health.h"
35 #include "xfs_buf_mem.h"
36 #include "xfs_da_format.h"
37 #include "xfs_da_btree.h"
38 #include "xfs_attr.h"
39 #include "xfs_dir2.h"
40 #include "xfs_rtrmap_btree.h"
41 #include "xfs_rtbitmap.h"
42 #include "xfs_rtgroup.h"
43 #include "xfs_rtalloc.h"
44 #include "xfs_metafile.h"
45 #include "xfs_rtrefcount_btree.h"
46 #include "xfs_zone_alloc.h"
47 #include "scrub/scrub.h"
48 #include "scrub/common.h"
49 #include "scrub/trace.h"
50 #include "scrub/repair.h"
51 #include "scrub/bitmap.h"
52 #include "scrub/stats.h"
53 #include "scrub/xfile.h"
54 #include "scrub/attr_repair.h"
55 
56 /*
57  * Attempt to repair some metadata, if the metadata is corrupt and userspace
58  * told us to fix it.  This function returns -EAGAIN to mean "re-run scrub",
59  * and will set *fixed to true if it thinks it repaired anything.
60  */
61 int
xrep_attempt(struct xfs_scrub * sc,struct xchk_stats_run * run)62 xrep_attempt(
63 	struct xfs_scrub	*sc,
64 	struct xchk_stats_run	*run)
65 {
66 	u64			repair_start;
67 	int			error = 0;
68 
69 	trace_xrep_attempt(XFS_I(file_inode(sc->file)), sc->sm, error);
70 
71 	xchk_ag_btcur_free(&sc->sa);
72 	xchk_rtgroup_btcur_free(&sc->sr);
73 
74 	/* Repair whatever's broken. */
75 	ASSERT(sc->ops->repair);
76 	run->repair_attempted = true;
77 	repair_start = xchk_stats_now();
78 	error = sc->ops->repair(sc);
79 	trace_xrep_done(XFS_I(file_inode(sc->file)), sc->sm, error);
80 	run->repair_ns += xchk_stats_elapsed_ns(repair_start);
81 	switch (error) {
82 	case 0:
83 		/*
84 		 * Repair succeeded.  Commit the fixes and perform a second
85 		 * scrub so that we can tell userspace if we fixed the problem.
86 		 */
87 		sc->sm->sm_flags &= ~XFS_SCRUB_FLAGS_OUT;
88 		sc->flags |= XREP_ALREADY_FIXED;
89 		run->repair_succeeded = true;
90 		return -EAGAIN;
91 	case -ECHRNG:
92 		sc->flags |= XCHK_NEED_DRAIN;
93 		run->retries++;
94 		return -EAGAIN;
95 	case -EDEADLOCK:
96 		/* Tell the caller to try again having grabbed all the locks. */
97 		if (!(sc->flags & XCHK_TRY_HARDER)) {
98 			sc->flags |= XCHK_TRY_HARDER;
99 			run->retries++;
100 			return -EAGAIN;
101 		}
102 		/*
103 		 * We tried harder but still couldn't grab all the resources
104 		 * we needed to fix it.  The corruption has not been fixed,
105 		 * so exit to userspace with the scan's output flags unchanged.
106 		 */
107 		return 0;
108 	default:
109 		/*
110 		 * EAGAIN tells the caller to re-scrub, so we cannot return
111 		 * that here.
112 		 */
113 		ASSERT(error != -EAGAIN);
114 		return error;
115 	}
116 }
117 
118 /*
119  * Complain about unfixable problems in the filesystem.  We don't log
120  * corruptions when IFLAG_REPAIR wasn't set on the assumption that the driver
121  * program is xfs_scrub, which will call back with IFLAG_REPAIR set if the
122  * administrator isn't running xfs_scrub in no-repairs mode.
123  *
124  * Use this helper function because _ratelimited silently declares a static
125  * structure to track rate limiting information.
126  */
127 void
xrep_failure(struct xfs_mount * mp)128 xrep_failure(
129 	struct xfs_mount	*mp)
130 {
131 	xfs_alert_ratelimited(mp,
132 "Corruption not fixed during online repair.  Unmount and run xfs_repair.");
133 }
134 
135 /*
136  * Repair probe -- userspace uses this to probe if we're willing to repair a
137  * given mountpoint.
138  */
139 int
xrep_probe(struct xfs_scrub * sc)140 xrep_probe(
141 	struct xfs_scrub	*sc)
142 {
143 	int			error = 0;
144 
145 	if (xchk_should_terminate(sc, &error))
146 		return error;
147 
148 	return 0;
149 }
150 
151 /*
152  * Roll a transaction, keeping the AG headers locked and reinitializing
153  * the btree cursors.
154  */
155 int
xrep_roll_ag_trans(struct xfs_scrub * sc)156 xrep_roll_ag_trans(
157 	struct xfs_scrub	*sc)
158 {
159 	int			error;
160 
161 	/*
162 	 * Keep the AG header buffers locked while we roll the transaction.
163 	 * Ensure that both AG buffers are dirty and held when we roll the
164 	 * transaction so that they move forward in the log without losing the
165 	 * bli (and hence the bli type) when the transaction commits.
166 	 *
167 	 * Normal code would never hold clean buffers across a roll, but repair
168 	 * needs both buffers to maintain a total lock on the AG.
169 	 */
170 	if (sc->sa.agi_bp) {
171 		xfs_ialloc_log_agi(sc->tp, sc->sa.agi_bp, XFS_AGI_MAGICNUM);
172 		xfs_trans_bhold(sc->tp, sc->sa.agi_bp);
173 	}
174 
175 	if (sc->sa.agf_bp) {
176 		xfs_alloc_log_agf(sc->tp, sc->sa.agf_bp, XFS_AGF_MAGICNUM);
177 		xfs_trans_bhold(sc->tp, sc->sa.agf_bp);
178 	}
179 
180 	/*
181 	 * Roll the transaction.  We still hold the AG header buffers locked
182 	 * regardless of whether or not that succeeds.  On failure, the buffers
183 	 * will be released during teardown on our way out of the kernel.  If
184 	 * successful, join the buffers to the new transaction and move on.
185 	 */
186 	error = xfs_trans_roll(&sc->tp);
187 	if (error)
188 		return error;
189 
190 	/* Join the AG headers to the new transaction. */
191 	if (sc->sa.agi_bp)
192 		xfs_trans_bjoin(sc->tp, sc->sa.agi_bp);
193 	if (sc->sa.agf_bp)
194 		xfs_trans_bjoin(sc->tp, sc->sa.agf_bp);
195 
196 	return 0;
197 }
198 
199 /* Roll the scrub transaction, holding the primary metadata locked. */
200 int
xrep_roll_trans(struct xfs_scrub * sc)201 xrep_roll_trans(
202 	struct xfs_scrub	*sc)
203 {
204 	if (!sc->ip)
205 		return xrep_roll_ag_trans(sc);
206 	return xfs_trans_roll_inode(&sc->tp, sc->ip);
207 }
208 
209 /* Finish all deferred work attached to the repair transaction. */
210 int
xrep_defer_finish(struct xfs_scrub * sc)211 xrep_defer_finish(
212 	struct xfs_scrub	*sc)
213 {
214 	int			error;
215 
216 	/*
217 	 * Keep the AG header buffers locked while we complete deferred work
218 	 * items.  Ensure that both AG buffers are dirty and held when we roll
219 	 * the transaction so that they move forward in the log without losing
220 	 * the bli (and hence the bli type) when the transaction commits.
221 	 *
222 	 * Normal code would never hold clean buffers across a roll, but repair
223 	 * needs both buffers to maintain a total lock on the AG.
224 	 */
225 	if (sc->sa.agi_bp) {
226 		xfs_ialloc_log_agi(sc->tp, sc->sa.agi_bp, XFS_AGI_MAGICNUM);
227 		xfs_trans_bhold(sc->tp, sc->sa.agi_bp);
228 	}
229 
230 	if (sc->sa.agf_bp) {
231 		xfs_alloc_log_agf(sc->tp, sc->sa.agf_bp, XFS_AGF_MAGICNUM);
232 		xfs_trans_bhold(sc->tp, sc->sa.agf_bp);
233 	}
234 
235 	/*
236 	 * Finish all deferred work items.  We still hold the AG header buffers
237 	 * locked regardless of whether or not that succeeds.  On failure, the
238 	 * buffers will be released during teardown on our way out of the
239 	 * kernel.  If successful, join the buffers to the new transaction
240 	 * and move on.
241 	 */
242 	error = xfs_defer_finish(&sc->tp);
243 	if (error)
244 		return error;
245 
246 	/*
247 	 * Release the hold that we set above because defer_finish won't do
248 	 * that for us.  The defer roll code redirties held buffers after each
249 	 * roll, so the AG header buffers should be ready for logging.
250 	 */
251 	if (sc->sa.agi_bp)
252 		xfs_trans_bhold_release(sc->tp, sc->sa.agi_bp);
253 	if (sc->sa.agf_bp)
254 		xfs_trans_bhold_release(sc->tp, sc->sa.agf_bp);
255 
256 	return 0;
257 }
258 
259 /*
260  * Does the given AG have enough space to rebuild a btree?  Neither AG
261  * reservation can be critical, and we must have enough space (factoring
262  * in AG reservations) to construct a whole btree.
263  */
264 bool
xrep_ag_has_space(struct xfs_perag * pag,xfs_extlen_t nr_blocks,enum xfs_ag_resv_type type)265 xrep_ag_has_space(
266 	struct xfs_perag	*pag,
267 	xfs_extlen_t		nr_blocks,
268 	enum xfs_ag_resv_type	type)
269 {
270 	return  !xfs_ag_resv_critical(pag, XFS_AG_RESV_RMAPBT) &&
271 		!xfs_ag_resv_critical(pag, XFS_AG_RESV_METADATA) &&
272 		pag->pagf_freeblks > xfs_ag_resv_needed(pag, type) + nr_blocks;
273 }
274 
275 /*
276  * Figure out how many blocks to reserve for an AG repair.  We calculate the
277  * worst case estimate for the number of blocks we'd need to rebuild one of
278  * any type of per-AG btree.
279  */
280 xfs_extlen_t
xrep_calc_ag_resblks(struct xfs_scrub * sc)281 xrep_calc_ag_resblks(
282 	struct xfs_scrub		*sc)
283 {
284 	struct xfs_mount		*mp = sc->mp;
285 	struct xfs_scrub_metadata	*sm = sc->sm;
286 	struct xfs_perag		*pag;
287 	struct xfs_buf			*bp;
288 	xfs_agino_t			icount = NULLAGINO;
289 	xfs_extlen_t			aglen = NULLAGBLOCK;
290 	xfs_extlen_t			usedlen;
291 	xfs_extlen_t			freelen;
292 	xfs_extlen_t			bnobt_sz;
293 	xfs_extlen_t			inobt_sz;
294 	xfs_extlen_t			rmapbt_sz;
295 	xfs_extlen_t			refcbt_sz;
296 	int				error;
297 
298 	if (!(sm->sm_flags & XFS_SCRUB_IFLAG_REPAIR))
299 		return 0;
300 
301 	pag = xfs_perag_get(mp, sm->sm_agno);
302 	if (xfs_perag_initialised_agi(pag)) {
303 		/* Use in-core icount if possible. */
304 		icount = pag->pagi_count;
305 	} else {
306 		/* Try to get the actual counters from disk. */
307 		error = xfs_ialloc_read_agi(pag, NULL, 0, &bp);
308 		if (!error) {
309 			icount = pag->pagi_count;
310 			xfs_buf_relse(bp);
311 		}
312 	}
313 
314 	/* Now grab the block counters from the AGF. */
315 	error = xfs_alloc_read_agf(pag, NULL, 0, &bp);
316 	if (error) {
317 		aglen = pag_group(pag)->xg_block_count;
318 		freelen = aglen;
319 		usedlen = aglen;
320 	} else {
321 		struct xfs_agf	*agf = bp->b_addr;
322 
323 		aglen = be32_to_cpu(agf->agf_length);
324 		freelen = be32_to_cpu(agf->agf_freeblks);
325 		usedlen = aglen - freelen;
326 		xfs_buf_relse(bp);
327 	}
328 
329 	/* If the icount is impossible, make some worst-case assumptions. */
330 	if (icount == NULLAGINO ||
331 	    !xfs_verify_agino(pag, icount)) {
332 		icount = pag->agino_max - pag->agino_min + 1;
333 	}
334 
335 	/* If the block counts are impossible, make worst-case assumptions. */
336 	if (aglen == NULLAGBLOCK ||
337 	    aglen != pag_group(pag)->xg_block_count ||
338 	    freelen >= aglen) {
339 		aglen = pag_group(pag)->xg_block_count;
340 		freelen = aglen;
341 		usedlen = aglen;
342 	}
343 
344 	trace_xrep_calc_ag_resblks(pag, icount, aglen, freelen, usedlen);
345 
346 	/*
347 	 * Figure out how many blocks we'd need worst case to rebuild
348 	 * each type of btree.  Note that we can only rebuild the
349 	 * bnobt/cntbt or inobt/finobt as pairs.
350 	 */
351 	bnobt_sz = 2 * xfs_allocbt_calc_size(mp, freelen);
352 	if (xfs_has_sparseinodes(mp))
353 		inobt_sz = xfs_iallocbt_calc_size(mp, icount /
354 				XFS_INODES_PER_HOLEMASK_BIT);
355 	else
356 		inobt_sz = xfs_iallocbt_calc_size(mp, icount /
357 				XFS_INODES_PER_CHUNK);
358 	if (xfs_has_finobt(mp))
359 		inobt_sz *= 2;
360 	if (xfs_has_reflink(mp))
361 		refcbt_sz = xfs_refcountbt_calc_size(mp, usedlen);
362 	else
363 		refcbt_sz = 0;
364 	if (xfs_has_rmapbt(mp)) {
365 		/*
366 		 * Guess how many blocks we need to rebuild the rmapbt.
367 		 * For non-reflink filesystems we can't have more records than
368 		 * used blocks.  However, with reflink it's possible to have
369 		 * more than one rmap record per AG block.  We don't know how
370 		 * many rmaps there could be in the AG, so we start off with
371 		 * what we hope is an generous over-estimation.
372 		 */
373 		if (xfs_has_reflink(mp))
374 			rmapbt_sz = xfs_rmapbt_calc_size(mp,
375 					(unsigned long long)aglen * 2);
376 		else
377 			rmapbt_sz = xfs_rmapbt_calc_size(mp, usedlen);
378 	} else {
379 		rmapbt_sz = 0;
380 	}
381 
382 	trace_xrep_calc_ag_resblks_btsize(pag, bnobt_sz, inobt_sz, rmapbt_sz,
383 			refcbt_sz);
384 	xfs_perag_put(pag);
385 
386 	return max(max(bnobt_sz, inobt_sz), max(rmapbt_sz, refcbt_sz));
387 }
388 
389 #ifdef CONFIG_XFS_RT
390 /*
391  * Figure out how many blocks to reserve for a rtgroup repair.  We calculate
392  * the worst case estimate for the number of blocks we'd need to rebuild one of
393  * any type of per-rtgroup btree.
394  */
395 xfs_extlen_t
xrep_calc_rtgroup_resblks(struct xfs_scrub * sc)396 xrep_calc_rtgroup_resblks(
397 	struct xfs_scrub		*sc)
398 {
399 	struct xfs_mount		*mp = sc->mp;
400 	struct xfs_scrub_metadata	*sm = sc->sm;
401 	uint64_t			usedlen;
402 	xfs_extlen_t			refcbt_sz = 0;
403 	xfs_extlen_t			rmapbt_sz = 0;
404 
405 	if (!(sm->sm_flags & XFS_SCRUB_IFLAG_REPAIR))
406 		return 0;
407 	if (!xfs_has_rtgroups(mp)) {
408 		ASSERT(0);
409 		return -EFSCORRUPTED;
410 	}
411 
412 	usedlen = xfs_rtbxlen_to_blen(mp, xfs_rtgroup_extents(mp, sm->sm_agno));
413 	ASSERT(usedlen <= XFS_MAX_RGBLOCKS);
414 
415 	if (xfs_has_reflink(mp))
416 		refcbt_sz = xfs_rtrefcountbt_calc_size(mp, usedlen);
417 
418 	if (xfs_has_rmapbt(mp))
419 		rmapbt_sz = xfs_rtrmapbt_calc_size(mp, usedlen);
420 
421 	/*
422 	 * Guess how many blocks we need to rebuild the rmapbt.  For
423 	 * non-reflink filesystems we can't have more records than used blocks.
424 	 * However, with reflink it's possible to have more than one rmap
425 	 * record per rtgroup block.  We don't know how many rmaps there could
426 	 * be in the rtgroup, so we start off with what we hope is an generous
427 	 * over-estimation.
428 	 */
429 	if (refcbt_sz > 0 && rmapbt_sz > 0)
430 		rmapbt_sz *= 2;
431 
432 	trace_xrep_calc_rtgroup_resblks_btsize(mp, sm->sm_agno, usedlen,
433 			rmapbt_sz, refcbt_sz);
434 
435 	return max(rmapbt_sz, refcbt_sz);
436 }
437 #endif /* CONFIG_XFS_RT */
438 
439 /*
440  * Reconstructing per-AG Btrees
441  *
442  * When a space btree is corrupt, we don't bother trying to fix it.  Instead,
443  * we scan secondary space metadata to derive the records that should be in
444  * the damaged btree, initialize a fresh btree root, and insert the records.
445  * Note that for rebuilding the rmapbt we scan all the primary data to
446  * generate the new records.
447  *
448  * However, that leaves the matter of removing all the metadata describing the
449  * old broken structure.  For primary metadata we use the rmap data to collect
450  * every extent with a matching rmap owner (bitmap); we then iterate all other
451  * metadata structures with the same rmap owner to collect the extents that
452  * cannot be removed (sublist).  We then subtract sublist from bitmap to
453  * derive the blocks that were used by the old btree.  These blocks can be
454  * reaped.
455  *
456  * For rmapbt reconstructions we must use different tactics for extent
457  * collection.  First we iterate all primary metadata (this excludes the old
458  * rmapbt, obviously) to generate new rmap records.  The gaps in the rmap
459  * records are collected as bitmap.  The bnobt records are collected as
460  * sublist.  As with the other btrees we subtract sublist from bitmap, and the
461  * result (since the rmapbt lives in the free space) are the blocks from the
462  * old rmapbt.
463  */
464 
465 /* Ensure the freelist is the correct size. */
466 int
xrep_fix_freelist(struct xfs_scrub * sc,int alloc_flags)467 xrep_fix_freelist(
468 	struct xfs_scrub	*sc,
469 	int			alloc_flags)
470 {
471 	struct xfs_alloc_arg	args = {0};
472 
473 	args.mp = sc->mp;
474 	args.tp = sc->tp;
475 	args.agno = pag_agno(sc->sa.pag);
476 	args.alignment = 1;
477 	args.pag = sc->sa.pag;
478 
479 	return xfs_alloc_fix_freelist(&args, alloc_flags);
480 }
481 
482 /*
483  * Finding per-AG Btree Roots for AGF/AGI Reconstruction
484  *
485  * If the AGF or AGI become slightly corrupted, it may be necessary to rebuild
486  * the AG headers by using the rmap data to rummage through the AG looking for
487  * btree roots.  This is not guaranteed to work if the AG is heavily damaged
488  * or the rmap data are corrupt.
489  *
490  * Callers of xrep_find_ag_btree_roots must lock the AGF and AGFL
491  * buffers if the AGF is being rebuilt; or the AGF and AGI buffers if the
492  * AGI is being rebuilt.  It must maintain these locks until it's safe for
493  * other threads to change the btrees' shapes.  The caller provides
494  * information about the btrees to look for by passing in an array of
495  * xrep_find_ag_btree with the (rmap owner, buf_ops, magic) fields set.
496  * The (root, height) fields will be set on return if anything is found.  The
497  * last element of the array should have a NULL buf_ops to mark the end of the
498  * array.
499  *
500  * For every rmapbt record matching any of the rmap owners in btree_info,
501  * read each block referenced by the rmap record.  If the block is a btree
502  * block from this filesystem matching any of the magic numbers and has a
503  * level higher than what we've already seen, remember the block and the
504  * height of the tree required to have such a block.  When the call completes,
505  * we return the highest block we've found for each btree description; those
506  * should be the roots.
507  */
508 
509 struct xrep_findroot {
510 	struct xfs_scrub		*sc;
511 	struct xfs_buf			*agfl_bp;
512 	struct xfs_agf			*agf;
513 	struct xrep_find_ag_btree	*btree_info;
514 };
515 
516 /* See if our block is in the AGFL. */
517 STATIC int
xrep_findroot_agfl_walk(struct xfs_mount * mp,xfs_agblock_t bno,void * priv)518 xrep_findroot_agfl_walk(
519 	struct xfs_mount	*mp,
520 	xfs_agblock_t		bno,
521 	void			*priv)
522 {
523 	xfs_agblock_t		*agbno = priv;
524 
525 	return (*agbno == bno) ? -ECANCELED : 0;
526 }
527 
528 /* Does this block match the btree information passed in? */
529 STATIC int
xrep_findroot_block(struct xrep_findroot * ri,struct xrep_find_ag_btree * fab,uint64_t owner,xfs_agblock_t agbno,bool * done_with_block)530 xrep_findroot_block(
531 	struct xrep_findroot		*ri,
532 	struct xrep_find_ag_btree	*fab,
533 	uint64_t			owner,
534 	xfs_agblock_t			agbno,
535 	bool				*done_with_block)
536 {
537 	struct xfs_mount		*mp = ri->sc->mp;
538 	struct xfs_buf			*bp;
539 	struct xfs_btree_block		*btblock;
540 	xfs_daddr_t			daddr;
541 	int				block_level;
542 	int				error = 0;
543 
544 	daddr = xfs_agbno_to_daddr(ri->sc->sa.pag, agbno);
545 
546 	/*
547 	 * Blocks in the AGFL have stale contents that might just happen to
548 	 * have a matching magic and uuid.  We don't want to pull these blocks
549 	 * in as part of a tree root, so we have to filter out the AGFL stuff
550 	 * here.  If the AGFL looks insane we'll just refuse to repair.
551 	 */
552 	if (owner == XFS_RMAP_OWN_AG) {
553 		error = xfs_agfl_walk(mp, ri->agf, ri->agfl_bp,
554 				xrep_findroot_agfl_walk, &agbno);
555 		if (error == -ECANCELED)
556 			return 0;
557 		if (error)
558 			return error;
559 	}
560 
561 	/*
562 	 * Read the buffer into memory so that we can see if it's a match for
563 	 * our btree type.  We have no clue if it is beforehand, and we want to
564 	 * avoid xfs_trans_read_buf's behavior of dumping the DONE state (which
565 	 * will cause needless disk reads in subsequent calls to this function)
566 	 * and logging metadata verifier failures.
567 	 *
568 	 * Therefore, pass in NULL buffer ops.  If the buffer was already in
569 	 * memory from some other caller it will already have b_ops assigned.
570 	 * If it was in memory from a previous unsuccessful findroot_block
571 	 * call, the buffer won't have b_ops but it should be clean and ready
572 	 * for us to try to verify if the read call succeeds.  The same applies
573 	 * if the buffer wasn't in memory at all.
574 	 *
575 	 * Note: If we never match a btree type with this buffer, it will be
576 	 * left in memory with NULL b_ops.  This shouldn't be a problem unless
577 	 * the buffer gets written.
578 	 */
579 	error = xfs_trans_read_buf(mp, ri->sc->tp, mp->m_ddev_targp, daddr,
580 			mp->m_bsize, 0, &bp, NULL);
581 	if (error)
582 		return error;
583 
584 	/* Ensure the block magic matches the btree type we're looking for. */
585 	btblock = XFS_BUF_TO_BLOCK(bp);
586 	ASSERT(fab->buf_ops->magic[1] != 0);
587 	if (btblock->bb_magic != fab->buf_ops->magic[1])
588 		goto out;
589 
590 	/*
591 	 * If the buffer already has ops applied and they're not the ones for
592 	 * this btree type, we know this block doesn't match the btree and we
593 	 * can bail out.
594 	 *
595 	 * If the buffer ops match ours, someone else has already validated
596 	 * the block for us, so we can move on to checking if this is a root
597 	 * block candidate.
598 	 *
599 	 * If the buffer does not have ops, nobody has successfully validated
600 	 * the contents and the buffer cannot be dirty.  If the magic, uuid,
601 	 * and structure match this btree type then we'll move on to checking
602 	 * if it's a root block candidate.  If there is no match, bail out.
603 	 */
604 	if (bp->b_ops) {
605 		if (bp->b_ops != fab->buf_ops)
606 			goto out;
607 	} else {
608 		ASSERT(!xfs_trans_buf_is_dirty(bp));
609 		if (!uuid_equal(&btblock->bb_u.s.bb_uuid,
610 				&mp->m_sb.sb_meta_uuid))
611 			goto out;
612 		/*
613 		 * Read verifiers can reference b_ops, so we set the pointer
614 		 * here.  If the verifier fails we'll reset the buffer state
615 		 * to what it was before we touched the buffer.
616 		 */
617 		bp->b_ops = fab->buf_ops;
618 		fab->buf_ops->verify_read(bp);
619 		if (bp->b_error) {
620 			bp->b_ops = NULL;
621 			bp->b_error = 0;
622 			goto out;
623 		}
624 
625 		/*
626 		 * Some read verifiers will (re)set b_ops, so we must be
627 		 * careful not to change b_ops after running the verifier.
628 		 */
629 	}
630 
631 	/*
632 	 * This block passes the magic/uuid and verifier tests for this btree
633 	 * type.  We don't need the caller to try the other tree types.
634 	 */
635 	*done_with_block = true;
636 
637 	/*
638 	 * Compare this btree block's level to the height of the current
639 	 * candidate root block.
640 	 *
641 	 * If the level matches the root we found previously, throw away both
642 	 * blocks because there can't be two candidate roots.
643 	 *
644 	 * If level is lower in the tree than the root we found previously,
645 	 * ignore this block.
646 	 */
647 	block_level = xfs_btree_get_level(btblock);
648 	if (block_level + 1 == fab->height) {
649 		fab->root = NULLAGBLOCK;
650 		goto out;
651 	} else if (block_level < fab->height) {
652 		goto out;
653 	}
654 
655 	/*
656 	 * This is the highest block in the tree that we've found so far.
657 	 * Update the btree height to reflect what we've learned from this
658 	 * block.
659 	 */
660 	fab->height = block_level + 1;
661 
662 	/*
663 	 * If this block doesn't have sibling pointers, then it's the new root
664 	 * block candidate.  Otherwise, the root will be found farther up the
665 	 * tree.
666 	 */
667 	if (btblock->bb_u.s.bb_leftsib == cpu_to_be32(NULLAGBLOCK) &&
668 	    btblock->bb_u.s.bb_rightsib == cpu_to_be32(NULLAGBLOCK))
669 		fab->root = agbno;
670 	else
671 		fab->root = NULLAGBLOCK;
672 
673 	trace_xrep_findroot_block(ri->sc->sa.pag, agbno,
674 			be32_to_cpu(btblock->bb_magic), fab->height - 1);
675 out:
676 	xfs_trans_brelse(ri->sc->tp, bp);
677 	return error;
678 }
679 
680 /*
681  * Do any of the blocks in this rmap record match one of the btrees we're
682  * looking for?
683  */
684 STATIC int
xrep_findroot_rmap(struct xfs_btree_cur * cur,const struct xfs_rmap_irec * rec,void * priv)685 xrep_findroot_rmap(
686 	struct xfs_btree_cur		*cur,
687 	const struct xfs_rmap_irec	*rec,
688 	void				*priv)
689 {
690 	struct xrep_findroot		*ri = priv;
691 	struct xrep_find_ag_btree	*fab;
692 	xfs_agblock_t			b;
693 	bool				done;
694 	int				error = 0;
695 
696 	/* Ignore anything that isn't AG metadata. */
697 	if (!XFS_RMAP_NON_INODE_OWNER(rec->rm_owner))
698 		return 0;
699 
700 	/* Otherwise scan each block + btree type. */
701 	for (b = 0; b < rec->rm_blockcount; b++) {
702 		done = false;
703 		for (fab = ri->btree_info; fab->buf_ops; fab++) {
704 			if (rec->rm_owner != fab->rmap_owner)
705 				continue;
706 			error = xrep_findroot_block(ri, fab,
707 					rec->rm_owner, rec->rm_startblock + b,
708 					&done);
709 			if (error)
710 				return error;
711 			if (done)
712 				break;
713 		}
714 	}
715 
716 	return 0;
717 }
718 
719 /* Find the roots of the per-AG btrees described in btree_info. */
720 int
xrep_find_ag_btree_roots(struct xfs_scrub * sc,struct xfs_buf * agf_bp,struct xrep_find_ag_btree * btree_info,struct xfs_buf * agfl_bp)721 xrep_find_ag_btree_roots(
722 	struct xfs_scrub		*sc,
723 	struct xfs_buf			*agf_bp,
724 	struct xrep_find_ag_btree	*btree_info,
725 	struct xfs_buf			*agfl_bp)
726 {
727 	struct xfs_mount		*mp = sc->mp;
728 	struct xrep_findroot		ri;
729 	struct xrep_find_ag_btree	*fab;
730 	struct xfs_btree_cur		*cur;
731 	int				error;
732 
733 	ASSERT(xfs_buf_islocked(agf_bp));
734 	ASSERT(agfl_bp == NULL || xfs_buf_islocked(agfl_bp));
735 
736 	ri.sc = sc;
737 	ri.btree_info = btree_info;
738 	ri.agf = agf_bp->b_addr;
739 	ri.agfl_bp = agfl_bp;
740 	for (fab = btree_info; fab->buf_ops; fab++) {
741 		ASSERT(agfl_bp || fab->rmap_owner != XFS_RMAP_OWN_AG);
742 		ASSERT(XFS_RMAP_NON_INODE_OWNER(fab->rmap_owner));
743 		fab->root = NULLAGBLOCK;
744 		fab->height = 0;
745 	}
746 
747 	cur = xfs_rmapbt_init_cursor(mp, sc->tp, agf_bp, sc->sa.pag);
748 	error = xfs_rmap_query_all(cur, xrep_findroot_rmap, &ri);
749 	xfs_btree_del_cursor(cur, error);
750 
751 	return error;
752 }
753 
754 #ifdef CONFIG_XFS_QUOTA
755 /* Update some quota flags in the superblock. */
756 void
xrep_update_qflags(struct xfs_scrub * sc,unsigned int clear_flags,unsigned int set_flags)757 xrep_update_qflags(
758 	struct xfs_scrub	*sc,
759 	unsigned int		clear_flags,
760 	unsigned int		set_flags)
761 {
762 	struct xfs_mount	*mp = sc->mp;
763 	struct xfs_buf		*bp;
764 
765 	mutex_lock(&mp->m_quotainfo->qi_quotaofflock);
766 	if ((mp->m_qflags & clear_flags) == 0 &&
767 	    (mp->m_qflags & set_flags) == set_flags)
768 		goto no_update;
769 
770 	mp->m_qflags &= ~clear_flags;
771 	mp->m_qflags |= set_flags;
772 
773 	spin_lock(&mp->m_sb_lock);
774 	mp->m_sb.sb_qflags &= ~clear_flags;
775 	mp->m_sb.sb_qflags |= set_flags;
776 	spin_unlock(&mp->m_sb_lock);
777 
778 	/*
779 	 * Update the quota flags in the ondisk superblock without touching
780 	 * the summary counters.  We have not quiesced inode chunk allocation,
781 	 * so we cannot coordinate with updates to the icount and ifree percpu
782 	 * counters.
783 	 */
784 	bp = xfs_trans_getsb(sc->tp);
785 	xfs_sb_to_disk(bp->b_addr, &mp->m_sb);
786 	xfs_trans_buf_set_type(sc->tp, bp, XFS_BLFT_SB_BUF);
787 	xfs_trans_log_buf(sc->tp, bp, 0, sizeof(struct xfs_dsb) - 1);
788 
789 no_update:
790 	mutex_unlock(&mp->m_quotainfo->qi_quotaofflock);
791 }
792 
793 /* Force a quotacheck the next time we mount. */
794 void
xrep_force_quotacheck(struct xfs_scrub * sc,xfs_dqtype_t type)795 xrep_force_quotacheck(
796 	struct xfs_scrub	*sc,
797 	xfs_dqtype_t		type)
798 {
799 	uint			flag;
800 
801 	flag = xfs_quota_chkd_flag(type);
802 	if (!(flag & sc->mp->m_qflags))
803 		return;
804 
805 	xrep_update_qflags(sc, flag, 0);
806 }
807 
808 /*
809  * Attach dquots to this inode, or schedule quotacheck to fix them.
810  *
811  * This function ensures that the appropriate dquots are attached to an inode.
812  * We cannot allow the dquot code to allocate an on-disk dquot block here
813  * because we're already in transaction context.  The on-disk dquot should
814  * already exist anyway.  If the quota code signals corruption or missing quota
815  * information, schedule quotacheck, which will repair corruptions in the quota
816  * metadata.
817  */
818 int
xrep_ino_dqattach(struct xfs_scrub * sc)819 xrep_ino_dqattach(
820 	struct xfs_scrub	*sc)
821 {
822 	int			error;
823 
824 	ASSERT(sc->tp != NULL);
825 	ASSERT(sc->ip != NULL);
826 
827 	error = xfs_qm_dqattach(sc->ip);
828 	switch (error) {
829 	case -EFSBADCRC:
830 	case -EFSCORRUPTED:
831 	case -ENOENT:
832 		xfs_err_ratelimited(sc->mp,
833 "inode %llu repair encountered quota error %d, quotacheck forced.",
834 				(unsigned long long)I_INO(sc->ip), error);
835 		if (XFS_IS_UQUOTA_ON(sc->mp) && !sc->ip->i_udquot)
836 			xrep_force_quotacheck(sc, XFS_DQTYPE_USER);
837 		if (XFS_IS_GQUOTA_ON(sc->mp) && !sc->ip->i_gdquot)
838 			xrep_force_quotacheck(sc, XFS_DQTYPE_GROUP);
839 		if (XFS_IS_PQUOTA_ON(sc->mp) && !sc->ip->i_pdquot)
840 			xrep_force_quotacheck(sc, XFS_DQTYPE_PROJ);
841 		fallthrough;
842 	case -ESRCH:
843 		error = 0;
844 		break;
845 	default:
846 		break;
847 	}
848 
849 	return error;
850 }
851 #endif /* CONFIG_XFS_QUOTA */
852 
853 /*
854  * Ensure that the inode being repaired is ready to handle a certain number of
855  * extents, or return EFSCORRUPTED.  Caller must hold the ILOCK of the inode
856  * being repaired and have joined it to the scrub transaction.
857  */
858 int
xrep_ino_ensure_extent_count(struct xfs_scrub * sc,int whichfork,xfs_extnum_t nextents)859 xrep_ino_ensure_extent_count(
860 	struct xfs_scrub	*sc,
861 	int			whichfork,
862 	xfs_extnum_t		nextents)
863 {
864 	xfs_extnum_t		max_extents;
865 	bool			inode_has_nrext64;
866 
867 	inode_has_nrext64 = xfs_inode_has_large_extent_counts(sc->ip);
868 	max_extents = xfs_iext_max_nextents(inode_has_nrext64, whichfork);
869 	if (nextents <= max_extents)
870 		return 0;
871 	if (inode_has_nrext64)
872 		return -EFSCORRUPTED;
873 	if (!xfs_has_large_extent_counts(sc->mp))
874 		return -EFSCORRUPTED;
875 
876 	max_extents = xfs_iext_max_nextents(true, whichfork);
877 	if (nextents > max_extents)
878 		return -EFSCORRUPTED;
879 
880 	sc->ip->i_diflags2 |= XFS_DIFLAG2_NREXT64;
881 	xfs_trans_log_inode(sc->tp, sc->ip, XFS_ILOG_CORE);
882 	return 0;
883 }
884 
885 /*
886  * Initialize all the btree cursors for an AG repair except for the btree that
887  * we're rebuilding.
888  */
889 void
xrep_ag_btcur_init(struct xfs_scrub * sc,struct xchk_ag * sa)890 xrep_ag_btcur_init(
891 	struct xfs_scrub	*sc,
892 	struct xchk_ag		*sa)
893 {
894 	struct xfs_mount	*mp = sc->mp;
895 
896 	/* Set up a bnobt cursor for cross-referencing. */
897 	if (sc->sm->sm_type != XFS_SCRUB_TYPE_BNOBT &&
898 	    sc->sm->sm_type != XFS_SCRUB_TYPE_CNTBT) {
899 		sa->bno_cur = xfs_bnobt_init_cursor(mp, sc->tp, sa->agf_bp,
900 				sc->sa.pag);
901 		sa->cnt_cur = xfs_cntbt_init_cursor(mp, sc->tp, sa->agf_bp,
902 				sc->sa.pag);
903 	}
904 
905 	/* Set up a inobt cursor for cross-referencing. */
906 	if (sc->sm->sm_type != XFS_SCRUB_TYPE_INOBT &&
907 	    sc->sm->sm_type != XFS_SCRUB_TYPE_FINOBT) {
908 		sa->ino_cur = xfs_inobt_init_cursor(sc->sa.pag, sc->tp,
909 				sa->agi_bp);
910 		if (xfs_has_finobt(mp))
911 			sa->fino_cur = xfs_finobt_init_cursor(sc->sa.pag,
912 					sc->tp, sa->agi_bp);
913 	}
914 
915 	/* Set up a rmapbt cursor for cross-referencing. */
916 	if (sc->sm->sm_type != XFS_SCRUB_TYPE_RMAPBT &&
917 	    xfs_has_rmapbt(mp))
918 		sa->rmap_cur = xfs_rmapbt_init_cursor(mp, sc->tp, sa->agf_bp,
919 				sc->sa.pag);
920 
921 	/* Set up a refcountbt cursor for cross-referencing. */
922 	if (sc->sm->sm_type != XFS_SCRUB_TYPE_REFCNTBT &&
923 	    xfs_has_reflink(mp))
924 		sa->refc_cur = xfs_refcountbt_init_cursor(mp, sc->tp,
925 				sa->agf_bp, sc->sa.pag);
926 }
927 
928 /*
929  * Reinitialize the in-core AG state after a repair by rereading the AGF
930  * buffer.  We had better get the same AGF buffer as the one that's attached
931  * to the scrub context.
932  */
933 int
xrep_reinit_pagf(struct xfs_scrub * sc)934 xrep_reinit_pagf(
935 	struct xfs_scrub	*sc)
936 {
937 	struct xfs_perag	*pag = sc->sa.pag;
938 	struct xfs_buf		*bp;
939 	int			error;
940 
941 	ASSERT(pag);
942 	ASSERT(xfs_perag_initialised_agf(pag));
943 
944 	clear_bit(XFS_AGSTATE_AGF_INIT, &pag->pag_opstate);
945 	error = xfs_alloc_read_agf(pag, sc->tp, 0, &bp);
946 	if (error)
947 		return error;
948 
949 	if (bp != sc->sa.agf_bp) {
950 		ASSERT(bp == sc->sa.agf_bp);
951 		return -EFSCORRUPTED;
952 	}
953 
954 	return 0;
955 }
956 
957 /*
958  * Reinitialize the in-core AG state after a repair by rereading the AGI
959  * buffer.  We had better get the same AGI buffer as the one that's attached
960  * to the scrub context.
961  */
962 int
xrep_reinit_pagi(struct xfs_scrub * sc)963 xrep_reinit_pagi(
964 	struct xfs_scrub	*sc)
965 {
966 	struct xfs_perag	*pag = sc->sa.pag;
967 	struct xfs_buf		*bp;
968 	int			error;
969 
970 	ASSERT(pag);
971 	ASSERT(xfs_perag_initialised_agi(pag));
972 
973 	clear_bit(XFS_AGSTATE_AGI_INIT, &pag->pag_opstate);
974 	error = xfs_ialloc_read_agi(pag, sc->tp, 0, &bp);
975 	if (error)
976 		return error;
977 
978 	if (bp != sc->sa.agi_bp) {
979 		ASSERT(bp == sc->sa.agi_bp);
980 		return -EFSCORRUPTED;
981 	}
982 
983 	return 0;
984 }
985 
986 /*
987  * Given an active reference to a perag structure, load AG headers and cursors.
988  * This should only be called to scan an AG while repairing file-based metadata.
989  */
990 int
xrep_ag_init(struct xfs_scrub * sc,struct xfs_perag * pag,struct xchk_ag * sa)991 xrep_ag_init(
992 	struct xfs_scrub	*sc,
993 	struct xfs_perag	*pag,
994 	struct xchk_ag		*sa)
995 {
996 	int			error;
997 
998 	ASSERT(!sa->pag);
999 
1000 	error = xfs_ialloc_read_agi(pag, sc->tp, 0, &sa->agi_bp);
1001 	if (error)
1002 		return error;
1003 
1004 	error = xfs_alloc_read_agf(pag, sc->tp, 0, &sa->agf_bp);
1005 	if (error)
1006 		return error;
1007 
1008 	/* Grab our own passive reference from the caller's ref. */
1009 	sa->pag = xfs_perag_hold(pag);
1010 	xrep_ag_btcur_init(sc, sa);
1011 	return 0;
1012 }
1013 
1014 #ifdef CONFIG_XFS_RT
1015 /* Initialize all the btree cursors for a RT repair. */
1016 void
xrep_rtgroup_btcur_init(struct xfs_scrub * sc,struct xchk_rt * sr)1017 xrep_rtgroup_btcur_init(
1018 	struct xfs_scrub	*sc,
1019 	struct xchk_rt		*sr)
1020 {
1021 	struct xfs_mount	*mp = sc->mp;
1022 
1023 	ASSERT(sr->rtg != NULL);
1024 
1025 	if (sc->sm->sm_type != XFS_SCRUB_TYPE_RTRMAPBT &&
1026 	    (sr->rtlock_flags & XFS_RTGLOCK_RMAP) &&
1027 	    xfs_has_rtrmapbt(mp))
1028 		sr->rmap_cur = xfs_rtrmapbt_init_cursor(sc->tp, sr->rtg);
1029 
1030 	if (sc->sm->sm_type != XFS_SCRUB_TYPE_RTREFCBT &&
1031 	    (sr->rtlock_flags & XFS_RTGLOCK_REFCOUNT) &&
1032 	    xfs_has_rtreflink(mp))
1033 		sr->refc_cur = xfs_rtrefcountbt_init_cursor(sc->tp, sr->rtg);
1034 }
1035 
1036 /*
1037  * Given a reference to a rtgroup structure, lock rtgroup btree inodes and
1038  * create btree cursors.  Must only be called to repair a regular rt file.
1039  */
1040 int
xrep_rtgroup_init(struct xfs_scrub * sc,struct xfs_rtgroup * rtg,struct xchk_rt * sr,unsigned int rtglock_flags)1041 xrep_rtgroup_init(
1042 	struct xfs_scrub	*sc,
1043 	struct xfs_rtgroup	*rtg,
1044 	struct xchk_rt		*sr,
1045 	unsigned int		rtglock_flags)
1046 {
1047 	ASSERT(sr->rtg == NULL);
1048 
1049 	xfs_rtgroup_lock(rtg, rtglock_flags);
1050 	sr->rtlock_flags = rtglock_flags;
1051 
1052 	/* Grab our own passive reference from the caller's ref. */
1053 	sr->rtg = xfs_rtgroup_hold(rtg);
1054 	xrep_rtgroup_btcur_init(sc, sr);
1055 	return 0;
1056 }
1057 
1058 /* Ensure that all rt blocks in the given range are not marked free. */
1059 int
xrep_require_rtext_inuse(struct xfs_scrub * sc,xfs_rgblock_t rgbno,xfs_filblks_t len)1060 xrep_require_rtext_inuse(
1061 	struct xfs_scrub	*sc,
1062 	xfs_rgblock_t		rgbno,
1063 	xfs_filblks_t		len)
1064 {
1065 	struct xfs_mount	*mp = sc->mp;
1066 	xfs_rtxnum_t		startrtx;
1067 	xfs_rtxnum_t		endrtx;
1068 	bool			is_free = false;
1069 	int			error = 0;
1070 
1071 	if (xfs_has_zoned(mp)) {
1072 		if (!xfs_zone_rgbno_is_valid(sc->sr.rtg, rgbno + len - 1))
1073 			return -EFSCORRUPTED;
1074 		return 0;
1075 	}
1076 
1077 	startrtx = xfs_rgbno_to_rtx(mp, rgbno);
1078 	endrtx = xfs_rgbno_to_rtx(mp, rgbno + len - 1);
1079 
1080 	error = xfs_rtalloc_extent_is_free(sc->sr.rtg, sc->tp, startrtx,
1081 			endrtx - startrtx + 1, &is_free);
1082 	if (error)
1083 		return error;
1084 	if (is_free)
1085 		return -EFSCORRUPTED;
1086 
1087 	return 0;
1088 }
1089 #endif /* CONFIG_XFS_RT */
1090 
1091 /* Reinitialize the per-AG block reservation for the AG we just fixed. */
1092 int
xrep_reset_perag_resv(struct xfs_scrub * sc)1093 xrep_reset_perag_resv(
1094 	struct xfs_scrub	*sc)
1095 {
1096 	int			error;
1097 
1098 	if (!(sc->flags & XREP_RESET_PERAG_RESV))
1099 		return 0;
1100 
1101 	ASSERT(sc->sa.pag != NULL);
1102 	ASSERT(sc->ops->type == ST_PERAG);
1103 	ASSERT(sc->tp);
1104 
1105 	sc->flags &= ~XREP_RESET_PERAG_RESV;
1106 	xfs_ag_resv_free(sc->sa.pag);
1107 	error = xfs_ag_resv_init(sc->sa.pag, sc->tp);
1108 	if (error == -ENOSPC) {
1109 		xfs_err(sc->mp,
1110 "Insufficient free space to reset per-AG reservation for AG %u after repair.",
1111 				pag_agno(sc->sa.pag));
1112 		error = 0;
1113 	}
1114 
1115 	return error;
1116 }
1117 
1118 /* Decide if we are going to call the repair function for a scrub type. */
1119 bool
xrep_will_attempt(struct xfs_scrub * sc)1120 xrep_will_attempt(
1121 	struct xfs_scrub	*sc)
1122 {
1123 	/* Userspace asked us to rebuild the structure regardless. */
1124 	if (sc->sm->sm_flags & XFS_SCRUB_IFLAG_FORCE_REBUILD)
1125 		return true;
1126 
1127 	/* Let debug users force us into the repair routines. */
1128 	if (XFS_TEST_ERROR(sc->mp, XFS_ERRTAG_FORCE_SCRUB_REPAIR))
1129 		return true;
1130 
1131 	/* Metadata is corrupt or failed cross-referencing. */
1132 	if (xchk_needs_repair(sc->sm))
1133 		return true;
1134 
1135 	return false;
1136 }
1137 
1138 /* Try to fix some part of a metadata inode by calling another scrubber. */
1139 STATIC int
xrep_metadata_inode_subtype(struct xfs_scrub * sc,unsigned int scrub_type)1140 xrep_metadata_inode_subtype(
1141 	struct xfs_scrub	*sc,
1142 	unsigned int		scrub_type)
1143 {
1144 	struct xfs_scrub_subord	*sub;
1145 	int			error;
1146 
1147 	/*
1148 	 * Let's see if the inode needs repair.  Use a subordinate scrub context
1149 	 * to call the scrub and repair functions so that we can hang on to the
1150 	 * resources that we already acquired instead of using the standard
1151 	 * setup/teardown routines.
1152 	 */
1153 	sub = xchk_scrub_create_subord(sc, scrub_type);
1154 	if (!sub)
1155 		return -ENOMEM;
1156 
1157 	error = sub->sc.ops->scrub(&sub->sc);
1158 	if (error)
1159 		goto out;
1160 	if (!xrep_will_attempt(&sub->sc))
1161 		goto out;
1162 
1163 	/*
1164 	 * Repair some part of the inode.  This will potentially join the inode
1165 	 * to the transaction.
1166 	 */
1167 	error = sub->sc.ops->repair(&sub->sc);
1168 	if (error)
1169 		goto out;
1170 
1171 	/*
1172 	 * Finish all deferred intent items and then roll the transaction so
1173 	 * that the inode will not be joined to the transaction when we exit
1174 	 * the function.
1175 	 */
1176 	error = xfs_defer_finish(&sub->sc.tp);
1177 	if (error)
1178 		goto out;
1179 	error = xfs_trans_roll(&sub->sc.tp);
1180 	if (error)
1181 		goto out;
1182 
1183 	/*
1184 	 * Clear the corruption flags and re-check the metadata that we just
1185 	 * repaired.
1186 	 */
1187 	sub->sc.sm->sm_flags &= ~XFS_SCRUB_FLAGS_OUT;
1188 	error = sub->sc.ops->scrub(&sub->sc);
1189 	if (error)
1190 		goto out;
1191 
1192 	/* If corruption persists, the repair has failed. */
1193 	if (xchk_needs_repair(sub->sc.sm)) {
1194 		error = -EFSCORRUPTED;
1195 		goto out;
1196 	}
1197 out:
1198 	xchk_scrub_free_subord(sub);
1199 	return error;
1200 }
1201 
1202 /*
1203  * Repair the ondisk forks of a metadata inode.  The caller must ensure that
1204  * sc->ip points to the metadata inode and the ILOCK is held on that inode.
1205  * The inode must not be joined to the transaction before the call, and will
1206  * not be afterwards.
1207  */
1208 int
xrep_metadata_inode_forks(struct xfs_scrub * sc)1209 xrep_metadata_inode_forks(
1210 	struct xfs_scrub	*sc)
1211 {
1212 	bool			dirty = false;
1213 	int			error;
1214 
1215 	/* Repair the inode record and the data fork. */
1216 	error = xrep_metadata_inode_subtype(sc, XFS_SCRUB_TYPE_INODE);
1217 	if (error)
1218 		return error;
1219 
1220 	error = xrep_metadata_inode_subtype(sc, XFS_SCRUB_TYPE_BMBTD);
1221 	if (error)
1222 		return error;
1223 
1224 	/*
1225 	 * Metadata files can only have extended attributes on metadir
1226 	 * filesystems, either for parent pointers or for actual xattr data.
1227 	 * For a non-metadir filesystem, make sure the attr fork looks ok
1228 	 * before we delete it.
1229 	 */
1230 	if (xfs_inode_hasattr(sc->ip)) {
1231 		error = xrep_metadata_inode_subtype(sc, XFS_SCRUB_TYPE_BMBTA);
1232 		if (error)
1233 			return error;
1234 	}
1235 
1236 	/* Clear the reflink flag since metadata never shares. */
1237 	if (xfs_is_reflink_inode(sc->ip)) {
1238 		dirty = true;
1239 		xfs_trans_ijoin(sc->tp, sc->ip, 0);
1240 		error = xfs_reflink_clear_inode_flag(sc->ip, &sc->tp);
1241 		if (error)
1242 			return error;
1243 	}
1244 
1245 	/*
1246 	 * Metadata files on non-metadir filesystems cannot have attr forks,
1247 	 * so clear them now.
1248 	 */
1249 	if (xfs_inode_hasattr(sc->ip) && !xfs_has_metadir(sc->mp)) {
1250 		if (!dirty) {
1251 			dirty = true;
1252 			xfs_trans_ijoin(sc->tp, sc->ip, 0);
1253 		}
1254 		error = xrep_xattr_reset_fork(sc);
1255 		if (error)
1256 			return error;
1257 	}
1258 
1259 	/*
1260 	 * If we modified the inode, roll the transaction but don't rejoin the
1261 	 * inode to the new transaction because xrep_bmap_data can do that.
1262 	 */
1263 	if (dirty) {
1264 		error = xfs_trans_roll(&sc->tp);
1265 		if (error)
1266 			return error;
1267 		dirty = false;
1268 	}
1269 
1270 	return 0;
1271 }
1272 
1273 /*
1274  * Set up an in-memory buffer cache so that we can use the xfbtree.  Allocating
1275  * a shmem file might take loks, so we cannot be in transaction context.  Park
1276  * our resources in the scrub context and let the teardown function take care
1277  * of them at the right time.
1278  */
1279 int
xrep_setup_xfbtree(struct xfs_scrub * sc,const char * descr)1280 xrep_setup_xfbtree(
1281 	struct xfs_scrub	*sc,
1282 	const char		*descr)
1283 {
1284 	ASSERT(sc->tp == NULL);
1285 
1286 	return xmbuf_alloc(sc->mp, descr, &sc->xmbtp);
1287 }
1288 
1289 /*
1290  * See if this buffer can pass the given ->verify_struct() function.
1291  *
1292  * If the buffer already has ops attached and they're not the ones that were
1293  * passed in, we reject the buffer.  Otherwise, we perform the structure test
1294  * (note that we do not check CRCs) and return the outcome of the test.  The
1295  * buffer ops and error state are left unchanged.
1296  */
1297 bool
xrep_buf_verify_struct(struct xfs_buf * bp,const struct xfs_buf_ops * ops)1298 xrep_buf_verify_struct(
1299 	struct xfs_buf			*bp,
1300 	const struct xfs_buf_ops	*ops)
1301 {
1302 	const struct xfs_buf_ops	*old_ops = bp->b_ops;
1303 	xfs_failaddr_t			fa;
1304 	int				old_error;
1305 
1306 	if (old_ops) {
1307 		if (old_ops != ops)
1308 			return false;
1309 	}
1310 
1311 	old_error = bp->b_error;
1312 	bp->b_ops = ops;
1313 	fa = bp->b_ops->verify_struct(bp);
1314 	bp->b_ops = old_ops;
1315 	bp->b_error = old_error;
1316 
1317 	return fa == NULL;
1318 }
1319 
1320 /* Check the sanity of a rmap record for a metadata btree inode. */
1321 int
xrep_check_ino_btree_mapping(struct xfs_scrub * sc,const struct xfs_rmap_irec * rec)1322 xrep_check_ino_btree_mapping(
1323 	struct xfs_scrub		*sc,
1324 	const struct xfs_rmap_irec	*rec)
1325 {
1326 	enum xbtree_recpacking		outcome;
1327 	int				error;
1328 
1329 	/*
1330 	 * Metadata btree inodes never have extended attributes, and all blocks
1331 	 * should have the bmbt block flag set.
1332 	 */
1333 	if ((rec->rm_flags & XFS_RMAP_ATTR_FORK) ||
1334 	    !(rec->rm_flags & XFS_RMAP_BMBT_BLOCK))
1335 		return -EFSCORRUPTED;
1336 
1337 	/* Make sure the block is within the AG. */
1338 	if (!xfs_verify_agbext(sc->sa.pag, rec->rm_startblock,
1339 				rec->rm_blockcount))
1340 		return -EFSCORRUPTED;
1341 
1342 	/* Make sure this isn't free space. */
1343 	error = xfs_alloc_has_records(sc->sa.bno_cur, rec->rm_startblock,
1344 			rec->rm_blockcount, &outcome);
1345 	if (error)
1346 		return error;
1347 	if (outcome != XBTREE_RECPACKING_EMPTY)
1348 		return -EFSCORRUPTED;
1349 
1350 	return 0;
1351 }
1352 
1353 /*
1354  * Reset the block count of the inode being repaired, and adjust the dquot
1355  * block usage to match.  The inode must not have an xattr fork.
1356  */
1357 void
xrep_inode_set_nblocks(struct xfs_scrub * sc,int64_t new_blocks)1358 xrep_inode_set_nblocks(
1359 	struct xfs_scrub	*sc,
1360 	int64_t			new_blocks)
1361 {
1362 	int64_t			delta =
1363 		new_blocks - sc->ip->i_nblocks;
1364 
1365 	sc->ip->i_nblocks = new_blocks;
1366 
1367 	xfs_trans_log_inode(sc->tp, sc->ip, XFS_ILOG_CORE);
1368 	if (delta != 0)
1369 		xfs_trans_mod_dquot_byino(sc->tp, sc->ip, XFS_TRANS_DQ_BCOUNT,
1370 				delta);
1371 }
1372 
1373 /* Reset the block reservation for a metadata inode. */
1374 int
xrep_reset_metafile_resv(struct xfs_scrub * sc)1375 xrep_reset_metafile_resv(
1376 	struct xfs_scrub	*sc)
1377 {
1378 	struct xfs_mount	*mp = sc->mp;
1379 	int64_t			delta;
1380 	int			error;
1381 
1382 	delta = mp->m_metafile_resv_used + mp->m_metafile_resv_avail -
1383 		mp->m_metafile_resv_target;
1384 	if (delta == 0)
1385 		return 0;
1386 
1387 	/*
1388 	 * Too many blocks have been reserved, transfer some from the incore
1389 	 * reservation back to the filesystem.
1390 	 */
1391 	if (delta > 0) {
1392 		int64_t		give_back;
1393 
1394 		give_back = min_t(uint64_t, delta, mp->m_metafile_resv_avail);
1395 		if (give_back > 0) {
1396 			xfs_mod_sb_delalloc(mp, -give_back);
1397 			xfs_add_fdblocks(mp, give_back);
1398 			mp->m_metafile_resv_avail -= give_back;
1399 		}
1400 
1401 		return 0;
1402 	}
1403 
1404 	/*
1405 	 * Not enough reservation; try to take some blocks from the filesystem
1406 	 * to the metabtree reservation.
1407 	 */
1408 	delta = -delta; /* delta is negative here, so invert the sign. */
1409 	error = xfs_dec_fdblocks(mp, delta, true);
1410 	while (error == -ENOSPC) {
1411 		delta--;
1412 		if (delta == 0) {
1413 			xfs_warn(sc->mp,
1414 "Insufficient free space to reset metabtree reservation after repair.");
1415 			return 0;
1416 		}
1417 		error = xfs_dec_fdblocks(mp, delta, true);
1418 	}
1419 	if (error)
1420 		return error;
1421 
1422 	xfs_mod_sb_delalloc(mp, delta);
1423 	mp->m_metafile_resv_avail += delta;
1424 	return 0;
1425 }
1426