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