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