cachepc-linux

Fork of AMDESE/linux with modifications for CachePC side-channel attack
git clone https://git.sinitax.com/sinitax/cachepc-linux
Log | Files | Refs | README | LICENSE | sfeed.txt

repair.c (28474B)


      1// SPDX-License-Identifier: GPL-2.0+
      2/*
      3 * Copyright (C) 2018 Oracle.  All Rights Reserved.
      4 * Author: Darrick J. Wong <darrick.wong@oracle.com>
      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 "scrub/scrub.h"
     30#include "scrub/common.h"
     31#include "scrub/trace.h"
     32#include "scrub/repair.h"
     33#include "scrub/bitmap.h"
     34
     35/*
     36 * Attempt to repair some metadata, if the metadata is corrupt and userspace
     37 * told us to fix it.  This function returns -EAGAIN to mean "re-run scrub",
     38 * and will set *fixed to true if it thinks it repaired anything.
     39 */
     40int
     41xrep_attempt(
     42	struct xfs_scrub	*sc)
     43{
     44	int			error = 0;
     45
     46	trace_xrep_attempt(XFS_I(file_inode(sc->file)), sc->sm, error);
     47
     48	xchk_ag_btcur_free(&sc->sa);
     49
     50	/* Repair whatever's broken. */
     51	ASSERT(sc->ops->repair);
     52	error = sc->ops->repair(sc);
     53	trace_xrep_done(XFS_I(file_inode(sc->file)), sc->sm, error);
     54	switch (error) {
     55	case 0:
     56		/*
     57		 * Repair succeeded.  Commit the fixes and perform a second
     58		 * scrub so that we can tell userspace if we fixed the problem.
     59		 */
     60		sc->sm->sm_flags &= ~XFS_SCRUB_FLAGS_OUT;
     61		sc->flags |= XREP_ALREADY_FIXED;
     62		return -EAGAIN;
     63	case -EDEADLOCK:
     64	case -EAGAIN:
     65		/* Tell the caller to try again having grabbed all the locks. */
     66		if (!(sc->flags & XCHK_TRY_HARDER)) {
     67			sc->flags |= XCHK_TRY_HARDER;
     68			return -EAGAIN;
     69		}
     70		/*
     71		 * We tried harder but still couldn't grab all the resources
     72		 * we needed to fix it.  The corruption has not been fixed,
     73		 * so report back to userspace.
     74		 */
     75		return -EFSCORRUPTED;
     76	default:
     77		return error;
     78	}
     79}
     80
     81/*
     82 * Complain about unfixable problems in the filesystem.  We don't log
     83 * corruptions when IFLAG_REPAIR wasn't set on the assumption that the driver
     84 * program is xfs_scrub, which will call back with IFLAG_REPAIR set if the
     85 * administrator isn't running xfs_scrub in no-repairs mode.
     86 *
     87 * Use this helper function because _ratelimited silently declares a static
     88 * structure to track rate limiting information.
     89 */
     90void
     91xrep_failure(
     92	struct xfs_mount	*mp)
     93{
     94	xfs_alert_ratelimited(mp,
     95"Corruption not fixed during online repair.  Unmount and run xfs_repair.");
     96}
     97
     98/*
     99 * Repair probe -- userspace uses this to probe if we're willing to repair a
    100 * given mountpoint.
    101 */
    102int
    103xrep_probe(
    104	struct xfs_scrub	*sc)
    105{
    106	int			error = 0;
    107
    108	if (xchk_should_terminate(sc, &error))
    109		return error;
    110
    111	return 0;
    112}
    113
    114/*
    115 * Roll a transaction, keeping the AG headers locked and reinitializing
    116 * the btree cursors.
    117 */
    118int
    119xrep_roll_ag_trans(
    120	struct xfs_scrub	*sc)
    121{
    122	int			error;
    123
    124	/* Keep the AG header buffers locked so we can keep going. */
    125	if (sc->sa.agi_bp)
    126		xfs_trans_bhold(sc->tp, sc->sa.agi_bp);
    127	if (sc->sa.agf_bp)
    128		xfs_trans_bhold(sc->tp, sc->sa.agf_bp);
    129	if (sc->sa.agfl_bp)
    130		xfs_trans_bhold(sc->tp, sc->sa.agfl_bp);
    131
    132	/*
    133	 * Roll the transaction.  We still own the buffer and the buffer lock
    134	 * regardless of whether or not the roll succeeds.  If the roll fails,
    135	 * the buffers will be released during teardown on our way out of the
    136	 * kernel.  If it succeeds, we join them to the new transaction and
    137	 * move on.
    138	 */
    139	error = xfs_trans_roll(&sc->tp);
    140	if (error)
    141		return error;
    142
    143	/* Join AG headers to the new transaction. */
    144	if (sc->sa.agi_bp)
    145		xfs_trans_bjoin(sc->tp, sc->sa.agi_bp);
    146	if (sc->sa.agf_bp)
    147		xfs_trans_bjoin(sc->tp, sc->sa.agf_bp);
    148	if (sc->sa.agfl_bp)
    149		xfs_trans_bjoin(sc->tp, sc->sa.agfl_bp);
    150
    151	return 0;
    152}
    153
    154/*
    155 * Does the given AG have enough space to rebuild a btree?  Neither AG
    156 * reservation can be critical, and we must have enough space (factoring
    157 * in AG reservations) to construct a whole btree.
    158 */
    159bool
    160xrep_ag_has_space(
    161	struct xfs_perag	*pag,
    162	xfs_extlen_t		nr_blocks,
    163	enum xfs_ag_resv_type	type)
    164{
    165	return  !xfs_ag_resv_critical(pag, XFS_AG_RESV_RMAPBT) &&
    166		!xfs_ag_resv_critical(pag, XFS_AG_RESV_METADATA) &&
    167		pag->pagf_freeblks > xfs_ag_resv_needed(pag, type) + nr_blocks;
    168}
    169
    170/*
    171 * Figure out how many blocks to reserve for an AG repair.  We calculate the
    172 * worst case estimate for the number of blocks we'd need to rebuild one of
    173 * any type of per-AG btree.
    174 */
    175xfs_extlen_t
    176xrep_calc_ag_resblks(
    177	struct xfs_scrub		*sc)
    178{
    179	struct xfs_mount		*mp = sc->mp;
    180	struct xfs_scrub_metadata	*sm = sc->sm;
    181	struct xfs_perag		*pag;
    182	struct xfs_buf			*bp;
    183	xfs_agino_t			icount = NULLAGINO;
    184	xfs_extlen_t			aglen = NULLAGBLOCK;
    185	xfs_extlen_t			usedlen;
    186	xfs_extlen_t			freelen;
    187	xfs_extlen_t			bnobt_sz;
    188	xfs_extlen_t			inobt_sz;
    189	xfs_extlen_t			rmapbt_sz;
    190	xfs_extlen_t			refcbt_sz;
    191	int				error;
    192
    193	if (!(sm->sm_flags & XFS_SCRUB_IFLAG_REPAIR))
    194		return 0;
    195
    196	pag = xfs_perag_get(mp, sm->sm_agno);
    197	if (pag->pagi_init) {
    198		/* Use in-core icount if possible. */
    199		icount = pag->pagi_count;
    200	} else {
    201		/* Try to get the actual counters from disk. */
    202		error = xfs_ialloc_read_agi(mp, NULL, sm->sm_agno, &bp);
    203		if (!error) {
    204			icount = pag->pagi_count;
    205			xfs_buf_relse(bp);
    206		}
    207	}
    208
    209	/* Now grab the block counters from the AGF. */
    210	error = xfs_alloc_read_agf(mp, NULL, sm->sm_agno, 0, &bp);
    211	if (error) {
    212		aglen = xfs_ag_block_count(mp, sm->sm_agno);
    213		freelen = aglen;
    214		usedlen = aglen;
    215	} else {
    216		struct xfs_agf	*agf = bp->b_addr;
    217
    218		aglen = be32_to_cpu(agf->agf_length);
    219		freelen = be32_to_cpu(agf->agf_freeblks);
    220		usedlen = aglen - freelen;
    221		xfs_buf_relse(bp);
    222	}
    223	xfs_perag_put(pag);
    224
    225	/* If the icount is impossible, make some worst-case assumptions. */
    226	if (icount == NULLAGINO ||
    227	    !xfs_verify_agino(mp, sm->sm_agno, icount)) {
    228		xfs_agino_t	first, last;
    229
    230		xfs_agino_range(mp, sm->sm_agno, &first, &last);
    231		icount = last - first + 1;
    232	}
    233
    234	/* If the block counts are impossible, make worst-case assumptions. */
    235	if (aglen == NULLAGBLOCK ||
    236	    aglen != xfs_ag_block_count(mp, sm->sm_agno) ||
    237	    freelen >= aglen) {
    238		aglen = xfs_ag_block_count(mp, sm->sm_agno);
    239		freelen = aglen;
    240		usedlen = aglen;
    241	}
    242
    243	trace_xrep_calc_ag_resblks(mp, sm->sm_agno, icount, aglen,
    244			freelen, usedlen);
    245
    246	/*
    247	 * Figure out how many blocks we'd need worst case to rebuild
    248	 * each type of btree.  Note that we can only rebuild the
    249	 * bnobt/cntbt or inobt/finobt as pairs.
    250	 */
    251	bnobt_sz = 2 * xfs_allocbt_calc_size(mp, freelen);
    252	if (xfs_has_sparseinodes(mp))
    253		inobt_sz = xfs_iallocbt_calc_size(mp, icount /
    254				XFS_INODES_PER_HOLEMASK_BIT);
    255	else
    256		inobt_sz = xfs_iallocbt_calc_size(mp, icount /
    257				XFS_INODES_PER_CHUNK);
    258	if (xfs_has_finobt(mp))
    259		inobt_sz *= 2;
    260	if (xfs_has_reflink(mp))
    261		refcbt_sz = xfs_refcountbt_calc_size(mp, usedlen);
    262	else
    263		refcbt_sz = 0;
    264	if (xfs_has_rmapbt(mp)) {
    265		/*
    266		 * Guess how many blocks we need to rebuild the rmapbt.
    267		 * For non-reflink filesystems we can't have more records than
    268		 * used blocks.  However, with reflink it's possible to have
    269		 * more than one rmap record per AG block.  We don't know how
    270		 * many rmaps there could be in the AG, so we start off with
    271		 * what we hope is an generous over-estimation.
    272		 */
    273		if (xfs_has_reflink(mp))
    274			rmapbt_sz = xfs_rmapbt_calc_size(mp,
    275					(unsigned long long)aglen * 2);
    276		else
    277			rmapbt_sz = xfs_rmapbt_calc_size(mp, usedlen);
    278	} else {
    279		rmapbt_sz = 0;
    280	}
    281
    282	trace_xrep_calc_ag_resblks_btsize(mp, sm->sm_agno, bnobt_sz,
    283			inobt_sz, rmapbt_sz, refcbt_sz);
    284
    285	return max(max(bnobt_sz, inobt_sz), max(rmapbt_sz, refcbt_sz));
    286}
    287
    288/* Allocate a block in an AG. */
    289int
    290xrep_alloc_ag_block(
    291	struct xfs_scrub		*sc,
    292	const struct xfs_owner_info	*oinfo,
    293	xfs_fsblock_t			*fsbno,
    294	enum xfs_ag_resv_type		resv)
    295{
    296	struct xfs_alloc_arg		args = {0};
    297	xfs_agblock_t			bno;
    298	int				error;
    299
    300	switch (resv) {
    301	case XFS_AG_RESV_AGFL:
    302	case XFS_AG_RESV_RMAPBT:
    303		error = xfs_alloc_get_freelist(sc->tp, sc->sa.agf_bp, &bno, 1);
    304		if (error)
    305			return error;
    306		if (bno == NULLAGBLOCK)
    307			return -ENOSPC;
    308		xfs_extent_busy_reuse(sc->mp, sc->sa.pag, bno,
    309				1, false);
    310		*fsbno = XFS_AGB_TO_FSB(sc->mp, sc->sa.pag->pag_agno, bno);
    311		if (resv == XFS_AG_RESV_RMAPBT)
    312			xfs_ag_resv_rmapbt_alloc(sc->mp, sc->sa.pag->pag_agno);
    313		return 0;
    314	default:
    315		break;
    316	}
    317
    318	args.tp = sc->tp;
    319	args.mp = sc->mp;
    320	args.oinfo = *oinfo;
    321	args.fsbno = XFS_AGB_TO_FSB(args.mp, sc->sa.pag->pag_agno, 0);
    322	args.minlen = 1;
    323	args.maxlen = 1;
    324	args.prod = 1;
    325	args.type = XFS_ALLOCTYPE_THIS_AG;
    326	args.resv = resv;
    327
    328	error = xfs_alloc_vextent(&args);
    329	if (error)
    330		return error;
    331	if (args.fsbno == NULLFSBLOCK)
    332		return -ENOSPC;
    333	ASSERT(args.len == 1);
    334	*fsbno = args.fsbno;
    335
    336	return 0;
    337}
    338
    339/* Initialize a new AG btree root block with zero entries. */
    340int
    341xrep_init_btblock(
    342	struct xfs_scrub		*sc,
    343	xfs_fsblock_t			fsb,
    344	struct xfs_buf			**bpp,
    345	xfs_btnum_t			btnum,
    346	const struct xfs_buf_ops	*ops)
    347{
    348	struct xfs_trans		*tp = sc->tp;
    349	struct xfs_mount		*mp = sc->mp;
    350	struct xfs_buf			*bp;
    351	int				error;
    352
    353	trace_xrep_init_btblock(mp, XFS_FSB_TO_AGNO(mp, fsb),
    354			XFS_FSB_TO_AGBNO(mp, fsb), btnum);
    355
    356	ASSERT(XFS_FSB_TO_AGNO(mp, fsb) == sc->sa.pag->pag_agno);
    357	error = xfs_trans_get_buf(tp, mp->m_ddev_targp,
    358			XFS_FSB_TO_DADDR(mp, fsb), XFS_FSB_TO_BB(mp, 1), 0,
    359			&bp);
    360	if (error)
    361		return error;
    362	xfs_buf_zero(bp, 0, BBTOB(bp->b_length));
    363	xfs_btree_init_block(mp, bp, btnum, 0, 0, sc->sa.pag->pag_agno);
    364	xfs_trans_buf_set_type(tp, bp, XFS_BLFT_BTREE_BUF);
    365	xfs_trans_log_buf(tp, bp, 0, BBTOB(bp->b_length) - 1);
    366	bp->b_ops = ops;
    367	*bpp = bp;
    368
    369	return 0;
    370}
    371
    372/*
    373 * Reconstructing per-AG Btrees
    374 *
    375 * When a space btree is corrupt, we don't bother trying to fix it.  Instead,
    376 * we scan secondary space metadata to derive the records that should be in
    377 * the damaged btree, initialize a fresh btree root, and insert the records.
    378 * Note that for rebuilding the rmapbt we scan all the primary data to
    379 * generate the new records.
    380 *
    381 * However, that leaves the matter of removing all the metadata describing the
    382 * old broken structure.  For primary metadata we use the rmap data to collect
    383 * every extent with a matching rmap owner (bitmap); we then iterate all other
    384 * metadata structures with the same rmap owner to collect the extents that
    385 * cannot be removed (sublist).  We then subtract sublist from bitmap to
    386 * derive the blocks that were used by the old btree.  These blocks can be
    387 * reaped.
    388 *
    389 * For rmapbt reconstructions we must use different tactics for extent
    390 * collection.  First we iterate all primary metadata (this excludes the old
    391 * rmapbt, obviously) to generate new rmap records.  The gaps in the rmap
    392 * records are collected as bitmap.  The bnobt records are collected as
    393 * sublist.  As with the other btrees we subtract sublist from bitmap, and the
    394 * result (since the rmapbt lives in the free space) are the blocks from the
    395 * old rmapbt.
    396 *
    397 * Disposal of Blocks from Old per-AG Btrees
    398 *
    399 * Now that we've constructed a new btree to replace the damaged one, we want
    400 * to dispose of the blocks that (we think) the old btree was using.
    401 * Previously, we used the rmapbt to collect the extents (bitmap) with the
    402 * rmap owner corresponding to the tree we rebuilt, collected extents for any
    403 * blocks with the same rmap owner that are owned by another data structure
    404 * (sublist), and subtracted sublist from bitmap.  In theory the extents
    405 * remaining in bitmap are the old btree's blocks.
    406 *
    407 * Unfortunately, it's possible that the btree was crosslinked with other
    408 * blocks on disk.  The rmap data can tell us if there are multiple owners, so
    409 * if the rmapbt says there is an owner of this block other than @oinfo, then
    410 * the block is crosslinked.  Remove the reverse mapping and continue.
    411 *
    412 * If there is one rmap record, we can free the block, which removes the
    413 * reverse mapping but doesn't add the block to the free space.  Our repair
    414 * strategy is to hope the other metadata objects crosslinked on this block
    415 * will be rebuilt (atop different blocks), thereby removing all the cross
    416 * links.
    417 *
    418 * If there are no rmap records at all, we also free the block.  If the btree
    419 * being rebuilt lives in the free space (bnobt/cntbt/rmapbt) then there isn't
    420 * supposed to be a rmap record and everything is ok.  For other btrees there
    421 * had to have been an rmap entry for the block to have ended up on @bitmap,
    422 * so if it's gone now there's something wrong and the fs will shut down.
    423 *
    424 * Note: If there are multiple rmap records with only the same rmap owner as
    425 * the btree we're trying to rebuild and the block is indeed owned by another
    426 * data structure with the same rmap owner, then the block will be in sublist
    427 * and therefore doesn't need disposal.  If there are multiple rmap records
    428 * with only the same rmap owner but the block is not owned by something with
    429 * the same rmap owner, the block will be freed.
    430 *
    431 * The caller is responsible for locking the AG headers for the entire rebuild
    432 * operation so that nothing else can sneak in and change the AG state while
    433 * we're not looking.  We also assume that the caller already invalidated any
    434 * buffers associated with @bitmap.
    435 */
    436
    437/*
    438 * Invalidate buffers for per-AG btree blocks we're dumping.  This function
    439 * is not intended for use with file data repairs; we have bunmapi for that.
    440 */
    441int
    442xrep_invalidate_blocks(
    443	struct xfs_scrub	*sc,
    444	struct xbitmap		*bitmap)
    445{
    446	struct xbitmap_range	*bmr;
    447	struct xbitmap_range	*n;
    448	struct xfs_buf		*bp;
    449	xfs_fsblock_t		fsbno;
    450
    451	/*
    452	 * For each block in each extent, see if there's an incore buffer for
    453	 * exactly that block; if so, invalidate it.  The buffer cache only
    454	 * lets us look for one buffer at a time, so we have to look one block
    455	 * at a time.  Avoid invalidating AG headers and post-EOFS blocks
    456	 * because we never own those; and if we can't TRYLOCK the buffer we
    457	 * assume it's owned by someone else.
    458	 */
    459	for_each_xbitmap_block(fsbno, bmr, n, bitmap) {
    460		/* Skip AG headers and post-EOFS blocks */
    461		if (!xfs_verify_fsbno(sc->mp, fsbno))
    462			continue;
    463		bp = xfs_buf_incore(sc->mp->m_ddev_targp,
    464				XFS_FSB_TO_DADDR(sc->mp, fsbno),
    465				XFS_FSB_TO_BB(sc->mp, 1), XBF_TRYLOCK);
    466		if (bp) {
    467			xfs_trans_bjoin(sc->tp, bp);
    468			xfs_trans_binval(sc->tp, bp);
    469		}
    470	}
    471
    472	return 0;
    473}
    474
    475/* Ensure the freelist is the correct size. */
    476int
    477xrep_fix_freelist(
    478	struct xfs_scrub	*sc,
    479	bool			can_shrink)
    480{
    481	struct xfs_alloc_arg	args = {0};
    482
    483	args.mp = sc->mp;
    484	args.tp = sc->tp;
    485	args.agno = sc->sa.pag->pag_agno;
    486	args.alignment = 1;
    487	args.pag = sc->sa.pag;
    488
    489	return xfs_alloc_fix_freelist(&args,
    490			can_shrink ? 0 : XFS_ALLOC_FLAG_NOSHRINK);
    491}
    492
    493/*
    494 * Put a block back on the AGFL.
    495 */
    496STATIC int
    497xrep_put_freelist(
    498	struct xfs_scrub	*sc,
    499	xfs_agblock_t		agbno)
    500{
    501	int			error;
    502
    503	/* Make sure there's space on the freelist. */
    504	error = xrep_fix_freelist(sc, true);
    505	if (error)
    506		return error;
    507
    508	/*
    509	 * Since we're "freeing" a lost block onto the AGFL, we have to
    510	 * create an rmap for the block prior to merging it or else other
    511	 * parts will break.
    512	 */
    513	error = xfs_rmap_alloc(sc->tp, sc->sa.agf_bp, sc->sa.pag, agbno, 1,
    514			&XFS_RMAP_OINFO_AG);
    515	if (error)
    516		return error;
    517
    518	/* Put the block on the AGFL. */
    519	error = xfs_alloc_put_freelist(sc->tp, sc->sa.agf_bp, sc->sa.agfl_bp,
    520			agbno, 0);
    521	if (error)
    522		return error;
    523	xfs_extent_busy_insert(sc->tp, sc->sa.pag, agbno, 1,
    524			XFS_EXTENT_BUSY_SKIP_DISCARD);
    525
    526	return 0;
    527}
    528
    529/* Dispose of a single block. */
    530STATIC int
    531xrep_reap_block(
    532	struct xfs_scrub		*sc,
    533	xfs_fsblock_t			fsbno,
    534	const struct xfs_owner_info	*oinfo,
    535	enum xfs_ag_resv_type		resv)
    536{
    537	struct xfs_btree_cur		*cur;
    538	struct xfs_buf			*agf_bp = NULL;
    539	xfs_agnumber_t			agno;
    540	xfs_agblock_t			agbno;
    541	bool				has_other_rmap;
    542	int				error;
    543
    544	agno = XFS_FSB_TO_AGNO(sc->mp, fsbno);
    545	agbno = XFS_FSB_TO_AGBNO(sc->mp, fsbno);
    546
    547	/*
    548	 * If we are repairing per-inode metadata, we need to read in the AGF
    549	 * buffer.  Otherwise, we're repairing a per-AG structure, so reuse
    550	 * the AGF buffer that the setup functions already grabbed.
    551	 */
    552	if (sc->ip) {
    553		error = xfs_alloc_read_agf(sc->mp, sc->tp, agno, 0, &agf_bp);
    554		if (error)
    555			return error;
    556	} else {
    557		agf_bp = sc->sa.agf_bp;
    558	}
    559	cur = xfs_rmapbt_init_cursor(sc->mp, sc->tp, agf_bp, sc->sa.pag);
    560
    561	/* Can we find any other rmappings? */
    562	error = xfs_rmap_has_other_keys(cur, agbno, 1, oinfo, &has_other_rmap);
    563	xfs_btree_del_cursor(cur, error);
    564	if (error)
    565		goto out_free;
    566
    567	/*
    568	 * If there are other rmappings, this block is cross linked and must
    569	 * not be freed.  Remove the reverse mapping and move on.  Otherwise,
    570	 * we were the only owner of the block, so free the extent, which will
    571	 * also remove the rmap.
    572	 *
    573	 * XXX: XFS doesn't support detecting the case where a single block
    574	 * metadata structure is crosslinked with a multi-block structure
    575	 * because the buffer cache doesn't detect aliasing problems, so we
    576	 * can't fix 100% of crosslinking problems (yet).  The verifiers will
    577	 * blow on writeout, the filesystem will shut down, and the admin gets
    578	 * to run xfs_repair.
    579	 */
    580	if (has_other_rmap)
    581		error = xfs_rmap_free(sc->tp, agf_bp, sc->sa.pag, agbno,
    582					1, oinfo);
    583	else if (resv == XFS_AG_RESV_AGFL)
    584		error = xrep_put_freelist(sc, agbno);
    585	else
    586		error = xfs_free_extent(sc->tp, fsbno, 1, oinfo, resv);
    587	if (agf_bp != sc->sa.agf_bp)
    588		xfs_trans_brelse(sc->tp, agf_bp);
    589	if (error)
    590		return error;
    591
    592	if (sc->ip)
    593		return xfs_trans_roll_inode(&sc->tp, sc->ip);
    594	return xrep_roll_ag_trans(sc);
    595
    596out_free:
    597	if (agf_bp != sc->sa.agf_bp)
    598		xfs_trans_brelse(sc->tp, agf_bp);
    599	return error;
    600}
    601
    602/* Dispose of every block of every extent in the bitmap. */
    603int
    604xrep_reap_extents(
    605	struct xfs_scrub		*sc,
    606	struct xbitmap			*bitmap,
    607	const struct xfs_owner_info	*oinfo,
    608	enum xfs_ag_resv_type		type)
    609{
    610	struct xbitmap_range		*bmr;
    611	struct xbitmap_range		*n;
    612	xfs_fsblock_t			fsbno;
    613	int				error = 0;
    614
    615	ASSERT(xfs_has_rmapbt(sc->mp));
    616
    617	for_each_xbitmap_block(fsbno, bmr, n, bitmap) {
    618		ASSERT(sc->ip != NULL ||
    619		       XFS_FSB_TO_AGNO(sc->mp, fsbno) == sc->sa.pag->pag_agno);
    620		trace_xrep_dispose_btree_extent(sc->mp,
    621				XFS_FSB_TO_AGNO(sc->mp, fsbno),
    622				XFS_FSB_TO_AGBNO(sc->mp, fsbno), 1);
    623
    624		error = xrep_reap_block(sc, fsbno, oinfo, type);
    625		if (error)
    626			break;
    627	}
    628
    629	return error;
    630}
    631
    632/*
    633 * Finding per-AG Btree Roots for AGF/AGI Reconstruction
    634 *
    635 * If the AGF or AGI become slightly corrupted, it may be necessary to rebuild
    636 * the AG headers by using the rmap data to rummage through the AG looking for
    637 * btree roots.  This is not guaranteed to work if the AG is heavily damaged
    638 * or the rmap data are corrupt.
    639 *
    640 * Callers of xrep_find_ag_btree_roots must lock the AGF and AGFL
    641 * buffers if the AGF is being rebuilt; or the AGF and AGI buffers if the
    642 * AGI is being rebuilt.  It must maintain these locks until it's safe for
    643 * other threads to change the btrees' shapes.  The caller provides
    644 * information about the btrees to look for by passing in an array of
    645 * xrep_find_ag_btree with the (rmap owner, buf_ops, magic) fields set.
    646 * The (root, height) fields will be set on return if anything is found.  The
    647 * last element of the array should have a NULL buf_ops to mark the end of the
    648 * array.
    649 *
    650 * For every rmapbt record matching any of the rmap owners in btree_info,
    651 * read each block referenced by the rmap record.  If the block is a btree
    652 * block from this filesystem matching any of the magic numbers and has a
    653 * level higher than what we've already seen, remember the block and the
    654 * height of the tree required to have such a block.  When the call completes,
    655 * we return the highest block we've found for each btree description; those
    656 * should be the roots.
    657 */
    658
    659struct xrep_findroot {
    660	struct xfs_scrub		*sc;
    661	struct xfs_buf			*agfl_bp;
    662	struct xfs_agf			*agf;
    663	struct xrep_find_ag_btree	*btree_info;
    664};
    665
    666/* See if our block is in the AGFL. */
    667STATIC int
    668xrep_findroot_agfl_walk(
    669	struct xfs_mount	*mp,
    670	xfs_agblock_t		bno,
    671	void			*priv)
    672{
    673	xfs_agblock_t		*agbno = priv;
    674
    675	return (*agbno == bno) ? -ECANCELED : 0;
    676}
    677
    678/* Does this block match the btree information passed in? */
    679STATIC int
    680xrep_findroot_block(
    681	struct xrep_findroot		*ri,
    682	struct xrep_find_ag_btree	*fab,
    683	uint64_t			owner,
    684	xfs_agblock_t			agbno,
    685	bool				*done_with_block)
    686{
    687	struct xfs_mount		*mp = ri->sc->mp;
    688	struct xfs_buf			*bp;
    689	struct xfs_btree_block		*btblock;
    690	xfs_daddr_t			daddr;
    691	int				block_level;
    692	int				error = 0;
    693
    694	daddr = XFS_AGB_TO_DADDR(mp, ri->sc->sa.pag->pag_agno, agbno);
    695
    696	/*
    697	 * Blocks in the AGFL have stale contents that might just happen to
    698	 * have a matching magic and uuid.  We don't want to pull these blocks
    699	 * in as part of a tree root, so we have to filter out the AGFL stuff
    700	 * here.  If the AGFL looks insane we'll just refuse to repair.
    701	 */
    702	if (owner == XFS_RMAP_OWN_AG) {
    703		error = xfs_agfl_walk(mp, ri->agf, ri->agfl_bp,
    704				xrep_findroot_agfl_walk, &agbno);
    705		if (error == -ECANCELED)
    706			return 0;
    707		if (error)
    708			return error;
    709	}
    710
    711	/*
    712	 * Read the buffer into memory so that we can see if it's a match for
    713	 * our btree type.  We have no clue if it is beforehand, and we want to
    714	 * avoid xfs_trans_read_buf's behavior of dumping the DONE state (which
    715	 * will cause needless disk reads in subsequent calls to this function)
    716	 * and logging metadata verifier failures.
    717	 *
    718	 * Therefore, pass in NULL buffer ops.  If the buffer was already in
    719	 * memory from some other caller it will already have b_ops assigned.
    720	 * If it was in memory from a previous unsuccessful findroot_block
    721	 * call, the buffer won't have b_ops but it should be clean and ready
    722	 * for us to try to verify if the read call succeeds.  The same applies
    723	 * if the buffer wasn't in memory at all.
    724	 *
    725	 * Note: If we never match a btree type with this buffer, it will be
    726	 * left in memory with NULL b_ops.  This shouldn't be a problem unless
    727	 * the buffer gets written.
    728	 */
    729	error = xfs_trans_read_buf(mp, ri->sc->tp, mp->m_ddev_targp, daddr,
    730			mp->m_bsize, 0, &bp, NULL);
    731	if (error)
    732		return error;
    733
    734	/* Ensure the block magic matches the btree type we're looking for. */
    735	btblock = XFS_BUF_TO_BLOCK(bp);
    736	ASSERT(fab->buf_ops->magic[1] != 0);
    737	if (btblock->bb_magic != fab->buf_ops->magic[1])
    738		goto out;
    739
    740	/*
    741	 * If the buffer already has ops applied and they're not the ones for
    742	 * this btree type, we know this block doesn't match the btree and we
    743	 * can bail out.
    744	 *
    745	 * If the buffer ops match ours, someone else has already validated
    746	 * the block for us, so we can move on to checking if this is a root
    747	 * block candidate.
    748	 *
    749	 * If the buffer does not have ops, nobody has successfully validated
    750	 * the contents and the buffer cannot be dirty.  If the magic, uuid,
    751	 * and structure match this btree type then we'll move on to checking
    752	 * if it's a root block candidate.  If there is no match, bail out.
    753	 */
    754	if (bp->b_ops) {
    755		if (bp->b_ops != fab->buf_ops)
    756			goto out;
    757	} else {
    758		ASSERT(!xfs_trans_buf_is_dirty(bp));
    759		if (!uuid_equal(&btblock->bb_u.s.bb_uuid,
    760				&mp->m_sb.sb_meta_uuid))
    761			goto out;
    762		/*
    763		 * Read verifiers can reference b_ops, so we set the pointer
    764		 * here.  If the verifier fails we'll reset the buffer state
    765		 * to what it was before we touched the buffer.
    766		 */
    767		bp->b_ops = fab->buf_ops;
    768		fab->buf_ops->verify_read(bp);
    769		if (bp->b_error) {
    770			bp->b_ops = NULL;
    771			bp->b_error = 0;
    772			goto out;
    773		}
    774
    775		/*
    776		 * Some read verifiers will (re)set b_ops, so we must be
    777		 * careful not to change b_ops after running the verifier.
    778		 */
    779	}
    780
    781	/*
    782	 * This block passes the magic/uuid and verifier tests for this btree
    783	 * type.  We don't need the caller to try the other tree types.
    784	 */
    785	*done_with_block = true;
    786
    787	/*
    788	 * Compare this btree block's level to the height of the current
    789	 * candidate root block.
    790	 *
    791	 * If the level matches the root we found previously, throw away both
    792	 * blocks because there can't be two candidate roots.
    793	 *
    794	 * If level is lower in the tree than the root we found previously,
    795	 * ignore this block.
    796	 */
    797	block_level = xfs_btree_get_level(btblock);
    798	if (block_level + 1 == fab->height) {
    799		fab->root = NULLAGBLOCK;
    800		goto out;
    801	} else if (block_level < fab->height) {
    802		goto out;
    803	}
    804
    805	/*
    806	 * This is the highest block in the tree that we've found so far.
    807	 * Update the btree height to reflect what we've learned from this
    808	 * block.
    809	 */
    810	fab->height = block_level + 1;
    811
    812	/*
    813	 * If this block doesn't have sibling pointers, then it's the new root
    814	 * block candidate.  Otherwise, the root will be found farther up the
    815	 * tree.
    816	 */
    817	if (btblock->bb_u.s.bb_leftsib == cpu_to_be32(NULLAGBLOCK) &&
    818	    btblock->bb_u.s.bb_rightsib == cpu_to_be32(NULLAGBLOCK))
    819		fab->root = agbno;
    820	else
    821		fab->root = NULLAGBLOCK;
    822
    823	trace_xrep_findroot_block(mp, ri->sc->sa.pag->pag_agno, agbno,
    824			be32_to_cpu(btblock->bb_magic), fab->height - 1);
    825out:
    826	xfs_trans_brelse(ri->sc->tp, bp);
    827	return error;
    828}
    829
    830/*
    831 * Do any of the blocks in this rmap record match one of the btrees we're
    832 * looking for?
    833 */
    834STATIC int
    835xrep_findroot_rmap(
    836	struct xfs_btree_cur		*cur,
    837	const struct xfs_rmap_irec	*rec,
    838	void				*priv)
    839{
    840	struct xrep_findroot		*ri = priv;
    841	struct xrep_find_ag_btree	*fab;
    842	xfs_agblock_t			b;
    843	bool				done;
    844	int				error = 0;
    845
    846	/* Ignore anything that isn't AG metadata. */
    847	if (!XFS_RMAP_NON_INODE_OWNER(rec->rm_owner))
    848		return 0;
    849
    850	/* Otherwise scan each block + btree type. */
    851	for (b = 0; b < rec->rm_blockcount; b++) {
    852		done = false;
    853		for (fab = ri->btree_info; fab->buf_ops; fab++) {
    854			if (rec->rm_owner != fab->rmap_owner)
    855				continue;
    856			error = xrep_findroot_block(ri, fab,
    857					rec->rm_owner, rec->rm_startblock + b,
    858					&done);
    859			if (error)
    860				return error;
    861			if (done)
    862				break;
    863		}
    864	}
    865
    866	return 0;
    867}
    868
    869/* Find the roots of the per-AG btrees described in btree_info. */
    870int
    871xrep_find_ag_btree_roots(
    872	struct xfs_scrub		*sc,
    873	struct xfs_buf			*agf_bp,
    874	struct xrep_find_ag_btree	*btree_info,
    875	struct xfs_buf			*agfl_bp)
    876{
    877	struct xfs_mount		*mp = sc->mp;
    878	struct xrep_findroot		ri;
    879	struct xrep_find_ag_btree	*fab;
    880	struct xfs_btree_cur		*cur;
    881	int				error;
    882
    883	ASSERT(xfs_buf_islocked(agf_bp));
    884	ASSERT(agfl_bp == NULL || xfs_buf_islocked(agfl_bp));
    885
    886	ri.sc = sc;
    887	ri.btree_info = btree_info;
    888	ri.agf = agf_bp->b_addr;
    889	ri.agfl_bp = agfl_bp;
    890	for (fab = btree_info; fab->buf_ops; fab++) {
    891		ASSERT(agfl_bp || fab->rmap_owner != XFS_RMAP_OWN_AG);
    892		ASSERT(XFS_RMAP_NON_INODE_OWNER(fab->rmap_owner));
    893		fab->root = NULLAGBLOCK;
    894		fab->height = 0;
    895	}
    896
    897	cur = xfs_rmapbt_init_cursor(mp, sc->tp, agf_bp, sc->sa.pag);
    898	error = xfs_rmap_query_all(cur, xrep_findroot_rmap, &ri);
    899	xfs_btree_del_cursor(cur, error);
    900
    901	return error;
    902}
    903
    904/* Force a quotacheck the next time we mount. */
    905void
    906xrep_force_quotacheck(
    907	struct xfs_scrub	*sc,
    908	xfs_dqtype_t		type)
    909{
    910	uint			flag;
    911
    912	flag = xfs_quota_chkd_flag(type);
    913	if (!(flag & sc->mp->m_qflags))
    914		return;
    915
    916	mutex_lock(&sc->mp->m_quotainfo->qi_quotaofflock);
    917	sc->mp->m_qflags &= ~flag;
    918	spin_lock(&sc->mp->m_sb_lock);
    919	sc->mp->m_sb.sb_qflags &= ~flag;
    920	spin_unlock(&sc->mp->m_sb_lock);
    921	xfs_log_sb(sc->tp);
    922	mutex_unlock(&sc->mp->m_quotainfo->qi_quotaofflock);
    923}
    924
    925/*
    926 * Attach dquots to this inode, or schedule quotacheck to fix them.
    927 *
    928 * This function ensures that the appropriate dquots are attached to an inode.
    929 * We cannot allow the dquot code to allocate an on-disk dquot block here
    930 * because we're already in transaction context with the inode locked.  The
    931 * on-disk dquot should already exist anyway.  If the quota code signals
    932 * corruption or missing quota information, schedule quotacheck, which will
    933 * repair corruptions in the quota metadata.
    934 */
    935int
    936xrep_ino_dqattach(
    937	struct xfs_scrub	*sc)
    938{
    939	int			error;
    940
    941	error = xfs_qm_dqattach_locked(sc->ip, false);
    942	switch (error) {
    943	case -EFSBADCRC:
    944	case -EFSCORRUPTED:
    945	case -ENOENT:
    946		xfs_err_ratelimited(sc->mp,
    947"inode %llu repair encountered quota error %d, quotacheck forced.",
    948				(unsigned long long)sc->ip->i_ino, error);
    949		if (XFS_IS_UQUOTA_ON(sc->mp) && !sc->ip->i_udquot)
    950			xrep_force_quotacheck(sc, XFS_DQTYPE_USER);
    951		if (XFS_IS_GQUOTA_ON(sc->mp) && !sc->ip->i_gdquot)
    952			xrep_force_quotacheck(sc, XFS_DQTYPE_GROUP);
    953		if (XFS_IS_PQUOTA_ON(sc->mp) && !sc->ip->i_pdquot)
    954			xrep_force_quotacheck(sc, XFS_DQTYPE_PROJ);
    955		fallthrough;
    956	case -ESRCH:
    957		error = 0;
    958		break;
    959	default:
    960		break;
    961	}
    962
    963	return error;
    964}