xref: /linux/fs/xfs/scrub/agheader_repair.c (revision 2f3c2a6f963e57cf4f0f34cbf24ab11abb64d118)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (C) 2018-2023 Oracle.  All Rights Reserved.
4  * Author: Darrick J. Wong <djwong@kernel.org>
5  */
6 #include "xfs_platform.h"
7 #include "xfs_fs.h"
8 #include "xfs_shared.h"
9 #include "xfs_format.h"
10 #include "xfs_trans_resv.h"
11 #include "xfs_mount.h"
12 #include "xfs_btree.h"
13 #include "xfs_log_format.h"
14 #include "xfs_trans.h"
15 #include "xfs_sb.h"
16 #include "xfs_alloc.h"
17 #include "xfs_alloc_btree.h"
18 #include "xfs_ialloc.h"
19 #include "xfs_ialloc_btree.h"
20 #include "xfs_rmap.h"
21 #include "xfs_rmap_btree.h"
22 #include "xfs_refcount_btree.h"
23 #include "xfs_ag.h"
24 #include "xfs_inode.h"
25 #include "xfs_iunlink_item.h"
26 #include "scrub/scrub.h"
27 #include "scrub/common.h"
28 #include "scrub/trace.h"
29 #include "scrub/repair.h"
30 #include "scrub/bitmap.h"
31 #include "scrub/agb_bitmap.h"
32 #include "scrub/agino_bitmap.h"
33 #include "scrub/reap.h"
34 #include "scrub/xfile.h"
35 #include "scrub/xfarray.h"
36 
37 /* Superblock */
38 
39 /* Repair the superblock. */
40 int
41 xrep_superblock(
42 	struct xfs_scrub	*sc)
43 {
44 	struct xfs_mount	*mp = sc->mp;
45 	struct xfs_buf		*bp;
46 	xfs_agnumber_t		agno;
47 	int			error;
48 
49 	/* Don't try to repair AG 0's sb; let xfs_repair deal with it. */
50 	agno = sc->sm->sm_agno;
51 	if (agno == 0)
52 		return -EOPNOTSUPP;
53 
54 	error = xfs_sb_get_secondary(mp, sc->tp, agno, &bp);
55 	if (error)
56 		return error;
57 
58 	/* Last chance to abort before we start committing fixes. */
59 	if (xchk_should_terminate(sc, &error))
60 		return error;
61 
62 	/* Copy AG 0's superblock to this one. */
63 	xfs_buf_zero(bp, 0, BBTOB(bp->b_length));
64 	xfs_sb_to_disk(bp->b_addr, &mp->m_sb);
65 
66 	/*
67 	 * Don't write out a secondary super with NEEDSREPAIR or log incompat
68 	 * features set, since both are ignored when set on a secondary.
69 	 */
70 	if (xfs_has_crc(mp)) {
71 		struct xfs_dsb		*sb = bp->b_addr;
72 
73 		sb->sb_features_incompat &=
74 				~cpu_to_be32(XFS_SB_FEAT_INCOMPAT_NEEDSREPAIR);
75 		sb->sb_features_log_incompat = 0;
76 	}
77 
78 	/* Write this to disk. */
79 	xfs_trans_buf_set_type(sc->tp, bp, XFS_BLFT_SB_BUF);
80 	xfs_trans_log_buf(sc->tp, bp, 0, BBTOB(bp->b_length) - 1);
81 	return 0;
82 }
83 
84 /* AGF */
85 
86 struct xrep_agf_allocbt {
87 	struct xfs_scrub	*sc;
88 	xfs_agblock_t		freeblks;
89 	xfs_agblock_t		longest;
90 };
91 
92 /* Record free space shape information. */
93 STATIC int
94 xrep_agf_walk_allocbt(
95 	struct xfs_btree_cur		*cur,
96 	const struct xfs_alloc_rec_incore *rec,
97 	void				*priv)
98 {
99 	struct xrep_agf_allocbt		*raa = priv;
100 	int				error = 0;
101 
102 	if (xchk_should_terminate(raa->sc, &error))
103 		return error;
104 
105 	raa->freeblks += rec->ar_blockcount;
106 	if (rec->ar_blockcount > raa->longest)
107 		raa->longest = rec->ar_blockcount;
108 	return error;
109 }
110 
111 /* Does this AGFL block look sane? */
112 STATIC int
113 xrep_agf_check_agfl_block(
114 	struct xfs_mount	*mp,
115 	xfs_agblock_t		agbno,
116 	void			*priv)
117 {
118 	struct xfs_scrub	*sc = priv;
119 
120 	if (!xfs_verify_agbno(sc->sa.pag, agbno))
121 		return -EFSCORRUPTED;
122 	return 0;
123 }
124 
125 /*
126  * Offset within the xrep_find_ag_btree array for each btree type.  Avoid the
127  * XFS_BTNUM_ names here to avoid creating a sparse array.
128  */
129 enum {
130 	XREP_AGF_BNOBT = 0,
131 	XREP_AGF_CNTBT,
132 	XREP_AGF_RMAPBT,
133 	XREP_AGF_REFCOUNTBT,
134 	XREP_AGF_END,
135 	XREP_AGF_MAX
136 };
137 
138 /* Check a btree root candidate. */
139 static inline bool
140 xrep_check_btree_root(
141 	struct xfs_scrub		*sc,
142 	struct xrep_find_ag_btree	*fab)
143 {
144 	return xfs_verify_agbno(sc->sa.pag, fab->root) &&
145 	       fab->height <= fab->maxlevels;
146 }
147 
148 /*
149  * Given the btree roots described by *fab, find the roots, check them for
150  * sanity, and pass the root data back out via *fab.
151  *
152  * This is /also/ a chicken and egg problem because we have to use the rmapbt
153  * (rooted in the AGF) to find the btrees rooted in the AGF.  We also have no
154  * idea if the btrees make any sense.  If we hit obvious corruptions in those
155  * btrees we'll bail out.
156  */
157 STATIC int
158 xrep_agf_find_btrees(
159 	struct xfs_scrub		*sc,
160 	struct xfs_buf			*agf_bp,
161 	struct xrep_find_ag_btree	*fab,
162 	struct xfs_buf			*agfl_bp)
163 {
164 	struct xfs_agf			*old_agf = agf_bp->b_addr;
165 	int				error;
166 
167 	/* Go find the root data. */
168 	error = xrep_find_ag_btree_roots(sc, agf_bp, fab, agfl_bp);
169 	if (error)
170 		return error;
171 
172 	/* We must find the bnobt, cntbt, and rmapbt roots. */
173 	if (!xrep_check_btree_root(sc, &fab[XREP_AGF_BNOBT]) ||
174 	    !xrep_check_btree_root(sc, &fab[XREP_AGF_CNTBT]) ||
175 	    !xrep_check_btree_root(sc, &fab[XREP_AGF_RMAPBT]))
176 		return -EFSCORRUPTED;
177 
178 	/*
179 	 * We relied on the rmapbt to reconstruct the AGF.  If we get a
180 	 * different root then something's seriously wrong.
181 	 */
182 	if (fab[XREP_AGF_RMAPBT].root != be32_to_cpu(old_agf->agf_rmap_root))
183 		return -EFSCORRUPTED;
184 
185 	/* We must find the refcountbt root if that feature is enabled. */
186 	if (xfs_has_reflink(sc->mp) &&
187 	    !xrep_check_btree_root(sc, &fab[XREP_AGF_REFCOUNTBT]))
188 		return -EFSCORRUPTED;
189 
190 	return 0;
191 }
192 
193 /*
194  * Reinitialize the AGF header, making an in-core copy of the old contents so
195  * that we know which in-core state needs to be reinitialized.
196  */
197 STATIC void
198 xrep_agf_init_header(
199 	struct xfs_scrub	*sc,
200 	struct xfs_buf		*agf_bp,
201 	struct xfs_agf		*old_agf)
202 {
203 	struct xfs_mount	*mp = sc->mp;
204 	struct xfs_perag	*pag = sc->sa.pag;
205 	struct xfs_agf		*agf = agf_bp->b_addr;
206 
207 	memcpy(old_agf, agf, sizeof(*old_agf));
208 	memset(agf, 0, BBTOB(agf_bp->b_length));
209 	agf->agf_magicnum = cpu_to_be32(XFS_AGF_MAGIC);
210 	agf->agf_versionnum = cpu_to_be32(XFS_AGF_VERSION);
211 	agf->agf_seqno = cpu_to_be32(pag_agno(pag));
212 	agf->agf_length = cpu_to_be32(pag_group(pag)->xg_block_count);
213 	agf->agf_flfirst = old_agf->agf_flfirst;
214 	agf->agf_fllast = old_agf->agf_fllast;
215 	agf->agf_flcount = old_agf->agf_flcount;
216 	if (xfs_has_crc(mp))
217 		uuid_copy(&agf->agf_uuid, &mp->m_sb.sb_meta_uuid);
218 
219 	/* Mark the incore AGF data stale until we're done fixing things. */
220 	ASSERT(xfs_perag_initialised_agf(pag));
221 	clear_bit(XFS_AGSTATE_AGF_INIT, &pag->pag_opstate);
222 }
223 
224 /* Set btree root information in an AGF. */
225 STATIC void
226 xrep_agf_set_roots(
227 	struct xfs_scrub		*sc,
228 	struct xfs_agf			*agf,
229 	struct xrep_find_ag_btree	*fab)
230 {
231 	agf->agf_bno_root = cpu_to_be32(fab[XREP_AGF_BNOBT].root);
232 	agf->agf_bno_level = cpu_to_be32(fab[XREP_AGF_BNOBT].height);
233 
234 	agf->agf_cnt_root = cpu_to_be32(fab[XREP_AGF_CNTBT].root);
235 	agf->agf_cnt_level = cpu_to_be32(fab[XREP_AGF_CNTBT].height);
236 
237 	agf->agf_rmap_root = cpu_to_be32(fab[XREP_AGF_RMAPBT].root);
238 	agf->agf_rmap_level = cpu_to_be32(fab[XREP_AGF_RMAPBT].height);
239 
240 	if (xfs_has_reflink(sc->mp)) {
241 		agf->agf_refcount_root =
242 				cpu_to_be32(fab[XREP_AGF_REFCOUNTBT].root);
243 		agf->agf_refcount_level =
244 				cpu_to_be32(fab[XREP_AGF_REFCOUNTBT].height);
245 	}
246 }
247 
248 /* Update all AGF fields which derive from btree contents. */
249 STATIC int
250 xrep_agf_calc_from_btrees(
251 	struct xfs_scrub	*sc,
252 	struct xfs_buf		*agf_bp)
253 {
254 	struct xrep_agf_allocbt	raa = { .sc = sc };
255 	struct xfs_btree_cur	*cur = NULL;
256 	struct xfs_agf		*agf = agf_bp->b_addr;
257 	struct xfs_mount	*mp = sc->mp;
258 	xfs_agblock_t		btreeblks;
259 	xfs_filblks_t		blocks;
260 	int			error;
261 
262 	/* Update the AGF counters from the bnobt. */
263 	cur = xfs_bnobt_init_cursor(mp, sc->tp, agf_bp, sc->sa.pag);
264 	error = xfs_alloc_query_all(cur, xrep_agf_walk_allocbt, &raa);
265 	if (error)
266 		goto err;
267 	error = xfs_btree_count_blocks(cur, &blocks);
268 	if (error)
269 		goto err;
270 	xfs_btree_del_cursor(cur, error);
271 	btreeblks = blocks - 1;
272 	agf->agf_freeblks = cpu_to_be32(raa.freeblks);
273 	agf->agf_longest = cpu_to_be32(raa.longest);
274 
275 	/* Update the AGF counters from the cntbt. */
276 	cur = xfs_cntbt_init_cursor(mp, sc->tp, agf_bp, sc->sa.pag);
277 	error = xfs_btree_count_blocks(cur, &blocks);
278 	if (error)
279 		goto err;
280 	xfs_btree_del_cursor(cur, error);
281 	btreeblks += blocks - 1;
282 
283 	/* Update the AGF counters from the rmapbt. */
284 	cur = xfs_rmapbt_init_cursor(mp, sc->tp, agf_bp, sc->sa.pag);
285 	error = xfs_btree_count_blocks(cur, &blocks);
286 	if (error)
287 		goto err;
288 	xfs_btree_del_cursor(cur, error);
289 	agf->agf_rmap_blocks = cpu_to_be32(blocks);
290 	btreeblks += blocks - 1;
291 
292 	agf->agf_btreeblks = cpu_to_be32(btreeblks);
293 
294 	/* Update the AGF counters from the refcountbt. */
295 	if (xfs_has_reflink(mp)) {
296 		cur = xfs_refcountbt_init_cursor(mp, sc->tp, agf_bp,
297 				sc->sa.pag);
298 		error = xfs_btree_count_blocks(cur, &blocks);
299 		if (error)
300 			goto err;
301 		xfs_btree_del_cursor(cur, error);
302 		agf->agf_refcount_blocks = cpu_to_be32(blocks);
303 	}
304 
305 	return 0;
306 err:
307 	xfs_btree_del_cursor(cur, error);
308 	return error;
309 }
310 
311 /* Commit the new AGF and reinitialize the incore state. */
312 STATIC int
313 xrep_agf_commit_new(
314 	struct xfs_scrub	*sc,
315 	struct xfs_buf		*agf_bp)
316 {
317 	struct xfs_perag	*pag;
318 	struct xfs_agf		*agf = agf_bp->b_addr;
319 
320 	/* Trigger fdblocks recalculation */
321 	xfs_force_summary_recalc(sc->mp);
322 
323 	/* Write this to disk. */
324 	xfs_trans_buf_set_type(sc->tp, agf_bp, XFS_BLFT_AGF_BUF);
325 	xfs_trans_log_buf(sc->tp, agf_bp, 0, BBTOB(agf_bp->b_length) - 1);
326 
327 	/* Now reinitialize the in-core counters we changed. */
328 	pag = sc->sa.pag;
329 	pag->pagf_btreeblks = be32_to_cpu(agf->agf_btreeblks);
330 	pag->pagf_freeblks = be32_to_cpu(agf->agf_freeblks);
331 	pag->pagf_longest = be32_to_cpu(agf->agf_longest);
332 	pag->pagf_bno_level = be32_to_cpu(agf->agf_bno_level);
333 	pag->pagf_cnt_level = be32_to_cpu(agf->agf_cnt_level);
334 	pag->pagf_rmap_level = be32_to_cpu(agf->agf_rmap_level);
335 	pag->pagf_refcount_level = be32_to_cpu(agf->agf_refcount_level);
336 	set_bit(XFS_AGSTATE_AGF_INIT, &pag->pag_opstate);
337 
338 	return xrep_roll_ag_trans(sc);
339 }
340 
341 /* Repair the AGF. v5 filesystems only. */
342 int
343 xrep_agf(
344 	struct xfs_scrub		*sc)
345 {
346 	struct xrep_find_ag_btree	fab[XREP_AGF_MAX] = {
347 		[XREP_AGF_BNOBT] = {
348 			.rmap_owner = XFS_RMAP_OWN_AG,
349 			.buf_ops = &xfs_bnobt_buf_ops,
350 			.maxlevels = sc->mp->m_alloc_maxlevels,
351 		},
352 		[XREP_AGF_CNTBT] = {
353 			.rmap_owner = XFS_RMAP_OWN_AG,
354 			.buf_ops = &xfs_cntbt_buf_ops,
355 			.maxlevels = sc->mp->m_alloc_maxlevels,
356 		},
357 		[XREP_AGF_RMAPBT] = {
358 			.rmap_owner = XFS_RMAP_OWN_AG,
359 			.buf_ops = &xfs_rmapbt_buf_ops,
360 			.maxlevels = sc->mp->m_rmap_maxlevels,
361 		},
362 		[XREP_AGF_REFCOUNTBT] = {
363 			.rmap_owner = XFS_RMAP_OWN_REFC,
364 			.buf_ops = &xfs_refcountbt_buf_ops,
365 			.maxlevels = sc->mp->m_refc_maxlevels,
366 		},
367 		[XREP_AGF_END] = {
368 			.buf_ops = NULL,
369 		},
370 	};
371 	struct xfs_agf			old_agf;
372 	struct xfs_mount		*mp = sc->mp;
373 	struct xfs_buf			*agf_bp;
374 	struct xfs_buf			*agfl_bp;
375 	struct xfs_agf			*agf;
376 	int				error;
377 
378 	/* We require the rmapbt to rebuild anything. */
379 	if (!xfs_has_rmapbt(mp))
380 		return -EOPNOTSUPP;
381 
382 	/*
383 	 * Make sure we have the AGF buffer, as scrub might have decided it
384 	 * was corrupt after xfs_alloc_read_agf failed with -EFSCORRUPTED.
385 	 */
386 	error = xfs_trans_read_buf(mp, sc->tp, mp->m_ddev_targp,
387 			XFS_AG_DADDR(mp, pag_agno(sc->sa.pag),
388 						XFS_AGF_DADDR(mp)),
389 			XFS_FSS_TO_BB(mp, 1), 0, &agf_bp, NULL);
390 	if (error)
391 		return error;
392 	agf_bp->b_ops = &xfs_agf_buf_ops;
393 	agf = agf_bp->b_addr;
394 
395 	/*
396 	 * Load the AGFL so that we can screen out OWN_AG blocks that are on
397 	 * the AGFL now; these blocks might have once been part of the
398 	 * bno/cnt/rmap btrees but are not now.  This is a chicken and egg
399 	 * problem: the AGF is corrupt, so we have to trust the AGFL contents
400 	 * because we can't do any serious cross-referencing with any of the
401 	 * btrees rooted in the AGF.  If the AGFL contents are obviously bad
402 	 * then we'll bail out.
403 	 */
404 	error = xfs_alloc_read_agfl(sc->sa.pag, sc->tp, &agfl_bp);
405 	if (error)
406 		return error;
407 
408 	/*
409 	 * Spot-check the AGFL blocks; if they're obviously corrupt then
410 	 * there's nothing we can do but bail out.
411 	 */
412 	error = xfs_agfl_walk(sc->mp, agf_bp->b_addr, agfl_bp,
413 			xrep_agf_check_agfl_block, sc);
414 	if (error)
415 		return error;
416 
417 	/*
418 	 * Find the AGF btree roots.  This is also a chicken-and-egg situation;
419 	 * see the function for more details.
420 	 */
421 	error = xrep_agf_find_btrees(sc, agf_bp, fab, agfl_bp);
422 	if (error)
423 		return error;
424 
425 	/* Last chance to abort before we start committing fixes. */
426 	if (xchk_should_terminate(sc, &error))
427 		return error;
428 
429 	/* Start rewriting the header and implant the btrees we found. */
430 	xrep_agf_init_header(sc, agf_bp, &old_agf);
431 	xrep_agf_set_roots(sc, agf, fab);
432 	error = xrep_agf_calc_from_btrees(sc, agf_bp);
433 	if (error)
434 		goto out_revert;
435 
436 	/* Commit the changes and reinitialize incore state. */
437 	return xrep_agf_commit_new(sc, agf_bp);
438 
439 out_revert:
440 	/* Mark the incore AGF state stale and revert the AGF. */
441 	clear_bit(XFS_AGSTATE_AGF_INIT, &sc->sa.pag->pag_opstate);
442 	memcpy(agf, &old_agf, sizeof(old_agf));
443 	return error;
444 }
445 
446 /* AGFL */
447 
448 struct xrep_agfl {
449 	/* Bitmap of alleged AGFL blocks that we're not going to add. */
450 	struct xagb_bitmap	crossed;
451 
452 	/* Bitmap of other OWN_AG metadata blocks. */
453 	struct xagb_bitmap	agmetablocks;
454 
455 	/* Bitmap of free space. */
456 	struct xagb_bitmap	*freesp;
457 
458 	/* rmapbt cursor for finding crosslinked blocks */
459 	struct xfs_btree_cur	*rmap_cur;
460 
461 	struct xfs_scrub	*sc;
462 };
463 
464 /* Record all OWN_AG (free space btree) information from the rmap data. */
465 STATIC int
466 xrep_agfl_walk_rmap(
467 	struct xfs_btree_cur	*cur,
468 	const struct xfs_rmap_irec *rec,
469 	void			*priv)
470 {
471 	struct xrep_agfl	*ra = priv;
472 	int			error = 0;
473 
474 	if (xchk_should_terminate(ra->sc, &error))
475 		return error;
476 
477 	/* Record all the OWN_AG blocks. */
478 	if (rec->rm_owner == XFS_RMAP_OWN_AG) {
479 		error = xagb_bitmap_set(ra->freesp, rec->rm_startblock,
480 				rec->rm_blockcount);
481 		if (error)
482 			return error;
483 	}
484 
485 	return xagb_bitmap_set_btcur_path(&ra->agmetablocks, cur);
486 }
487 
488 /* Strike out the blocks that are cross-linked according to the rmapbt. */
489 STATIC int
490 xrep_agfl_check_extent(
491 	uint32_t		agbno,
492 	uint32_t		len,
493 	void			*priv)
494 {
495 	struct xrep_agfl	*ra = priv;
496 	xfs_agblock_t		last_agbno = agbno + len - 1;
497 	int			error;
498 
499 	while (agbno <= last_agbno) {
500 		bool		other_owners;
501 
502 		error = xfs_rmap_has_other_keys(ra->rmap_cur, agbno, 1,
503 				&XFS_RMAP_OINFO_AG, &other_owners);
504 		if (error)
505 			return error;
506 
507 		if (other_owners) {
508 			error = xagb_bitmap_set(&ra->crossed, agbno, 1);
509 			if (error)
510 				return error;
511 		}
512 
513 		if (xchk_should_terminate(ra->sc, &error))
514 			return error;
515 		agbno++;
516 	}
517 
518 	return 0;
519 }
520 
521 /*
522  * Map out all the non-AGFL OWN_AG space in this AG so that we can deduce
523  * which blocks belong to the AGFL.
524  *
525  * Compute the set of old AGFL blocks by subtracting from the list of OWN_AG
526  * blocks the list of blocks owned by all other OWN_AG metadata (bnobt, cntbt,
527  * rmapbt).  These are the old AGFL blocks, so return that list and the number
528  * of blocks we're actually going to put back on the AGFL.
529  */
530 STATIC int
531 xrep_agfl_collect_blocks(
532 	struct xfs_scrub	*sc,
533 	struct xfs_buf		*agf_bp,
534 	struct xagb_bitmap	*agfl_extents,
535 	xfs_agblock_t		*flcount)
536 {
537 	struct xrep_agfl	ra;
538 	struct xfs_mount	*mp = sc->mp;
539 	struct xfs_btree_cur	*cur;
540 	int			error;
541 
542 	ra.sc = sc;
543 	ra.freesp = agfl_extents;
544 	xagb_bitmap_init(&ra.agmetablocks);
545 	xagb_bitmap_init(&ra.crossed);
546 
547 	/* Find all space used by the free space btrees & rmapbt. */
548 	cur = xfs_rmapbt_init_cursor(mp, sc->tp, agf_bp, sc->sa.pag);
549 	error = xfs_rmap_query_all(cur, xrep_agfl_walk_rmap, &ra);
550 	xfs_btree_del_cursor(cur, error);
551 	if (error)
552 		goto out_bmp;
553 
554 	/* Find all blocks currently being used by the bnobt. */
555 	cur = xfs_bnobt_init_cursor(mp, sc->tp, agf_bp, sc->sa.pag);
556 	error = xagb_bitmap_set_btblocks(&ra.agmetablocks, cur);
557 	xfs_btree_del_cursor(cur, error);
558 	if (error)
559 		goto out_bmp;
560 
561 	/* Find all blocks currently being used by the cntbt. */
562 	cur = xfs_cntbt_init_cursor(mp, sc->tp, agf_bp, sc->sa.pag);
563 	error = xagb_bitmap_set_btblocks(&ra.agmetablocks, cur);
564 	xfs_btree_del_cursor(cur, error);
565 	if (error)
566 		goto out_bmp;
567 
568 	/*
569 	 * Drop the freesp meta blocks that are in use by btrees.
570 	 * The remaining blocks /should/ be AGFL blocks.
571 	 */
572 	error = xagb_bitmap_disunion(agfl_extents, &ra.agmetablocks);
573 	if (error)
574 		goto out_bmp;
575 
576 	/* Strike out the blocks that are cross-linked. */
577 	ra.rmap_cur = xfs_rmapbt_init_cursor(mp, sc->tp, agf_bp, sc->sa.pag);
578 	error = xagb_bitmap_walk(agfl_extents, xrep_agfl_check_extent, &ra);
579 	xfs_btree_del_cursor(ra.rmap_cur, error);
580 	if (error)
581 		goto out_bmp;
582 	error = xagb_bitmap_disunion(agfl_extents, &ra.crossed);
583 	if (error)
584 		goto out_bmp;
585 
586 	/*
587 	 * Calculate the new AGFL size.  If we found more blocks than fit in
588 	 * the AGFL we'll free them later.
589 	 */
590 	*flcount = min_t(uint64_t, xagb_bitmap_hweight(agfl_extents),
591 			 xfs_agfl_size(mp));
592 
593 out_bmp:
594 	xagb_bitmap_destroy(&ra.crossed);
595 	xagb_bitmap_destroy(&ra.agmetablocks);
596 	return error;
597 }
598 
599 /* Update the AGF and reset the in-core state. */
600 STATIC void
601 xrep_agfl_update_agf(
602 	struct xfs_scrub	*sc,
603 	struct xfs_buf		*agf_bp,
604 	xfs_agblock_t		flcount)
605 {
606 	struct xfs_agf		*agf = agf_bp->b_addr;
607 
608 	ASSERT(flcount <= xfs_agfl_size(sc->mp));
609 
610 	/* Trigger fdblocks recalculation */
611 	xfs_force_summary_recalc(sc->mp);
612 
613 	/* Update the AGF counters. */
614 	if (xfs_perag_initialised_agf(sc->sa.pag)) {
615 		sc->sa.pag->pagf_flcount = flcount;
616 		clear_bit(XFS_AGSTATE_AGFL_NEEDS_RESET,
617 				&sc->sa.pag->pag_opstate);
618 	}
619 	agf->agf_flfirst = cpu_to_be32(0);
620 	agf->agf_flcount = cpu_to_be32(flcount);
621 	if (flcount)
622 		agf->agf_fllast = cpu_to_be32(flcount - 1);
623 	else
624 		agf->agf_fllast = cpu_to_be32(xfs_agfl_size(sc->mp) - 1);
625 
626 	xfs_alloc_log_agf(sc->tp, agf_bp,
627 			XFS_AGF_FLFIRST | XFS_AGF_FLLAST | XFS_AGF_FLCOUNT);
628 }
629 
630 struct xrep_agfl_fill {
631 	struct xagb_bitmap	used_extents;
632 	struct xfs_scrub	*sc;
633 	__be32			*agfl_bno;
634 	xfs_agblock_t		flcount;
635 	unsigned int		fl_off;
636 };
637 
638 /* Fill the AGFL with whatever blocks are in this extent. */
639 static int
640 xrep_agfl_fill(
641 	uint32_t		start,
642 	uint32_t		len,
643 	void			*priv)
644 {
645 	struct xrep_agfl_fill	*af = priv;
646 	struct xfs_scrub	*sc = af->sc;
647 	xfs_agblock_t		agbno = start;
648 	int			error;
649 
650 	trace_xrep_agfl_insert(pag_group(sc->sa.pag), agbno, len);
651 
652 	while (agbno < start + len && af->fl_off < af->flcount)
653 		af->agfl_bno[af->fl_off++] = cpu_to_be32(agbno++);
654 
655 	error = xagb_bitmap_set(&af->used_extents, start, agbno - start);
656 	if (error)
657 		return error;
658 
659 	if (af->fl_off == af->flcount)
660 		return -ECANCELED;
661 
662 	return 0;
663 }
664 
665 /* Write out a totally new AGFL. */
666 STATIC int
667 xrep_agfl_init_header(
668 	struct xfs_scrub	*sc,
669 	struct xfs_buf		*agfl_bp,
670 	struct xagb_bitmap	*agfl_extents,
671 	xfs_agblock_t		flcount,
672 	struct xfs_agfl		*old_agfl)
673 {
674 	struct xrep_agfl_fill	af = {
675 		.sc		= sc,
676 		.flcount	= flcount,
677 	};
678 	struct xfs_mount	*mp = sc->mp;
679 	struct xfs_agfl		*agfl = XFS_BUF_TO_AGFL(agfl_bp);
680 	const size_t		agfl_sz = BBTOB(agfl_bp->b_length);
681 	int			error;
682 
683 	ASSERT(flcount <= xfs_agfl_size(mp));
684 
685 	/*
686 	 * Start rewriting the header by setting the bno[] array to
687 	 * NULLAGBLOCK, then setting AGFL header fields.
688 	 */
689 	memcpy(old_agfl, agfl, agfl_sz);
690 	memset(agfl, 0xFF, agfl_sz);
691 	agfl->agfl_magicnum = cpu_to_be32(XFS_AGFL_MAGIC);
692 	agfl->agfl_seqno = cpu_to_be32(pag_agno(sc->sa.pag));
693 	uuid_copy(&agfl->agfl_uuid, &mp->m_sb.sb_meta_uuid);
694 
695 	/*
696 	 * Fill the AGFL with the remaining blocks.  If agfl_extents has more
697 	 * blocks than fit in the AGFL, they will be freed in a subsequent
698 	 * step.
699 	 */
700 	xagb_bitmap_init(&af.used_extents);
701 	af.agfl_bno = xfs_buf_to_agfl_bno(agfl_bp);
702 	error = xagb_bitmap_walk(agfl_extents, xrep_agfl_fill, &af);
703 	if (error && error != -ECANCELED)
704 		goto err_undo;
705 	error = xagb_bitmap_disunion(agfl_extents, &af.used_extents);
706 	if (error)
707 		goto err_undo;
708 
709 	/* Write new AGFL to disk. */
710 	xfs_trans_buf_set_type(sc->tp, agfl_bp, XFS_BLFT_AGFL_BUF);
711 	xfs_trans_log_buf(sc->tp, agfl_bp, 0, agfl_sz - 1);
712 	xagb_bitmap_destroy(&af.used_extents);
713 	return 0;
714 
715 err_undo:
716 	xagb_bitmap_destroy(&af.used_extents);
717 	memcpy(agfl, old_agfl, agfl_sz);
718 	return error;
719 }
720 
721 /* Repair the AGFL. */
722 int
723 xrep_agfl(
724 	struct xfs_scrub	*sc)
725 {
726 	struct xagb_bitmap	agfl_extents;
727 	struct xfs_mount	*mp = sc->mp;
728 	struct xfs_buf		*agf_bp;
729 	struct xfs_buf		*agfl_bp;
730 	struct xfs_agfl		*old_agfl;
731 	xfs_agblock_t		flcount;
732 	int			error;
733 
734 	/* We require the rmapbt to rebuild anything. */
735 	if (!xfs_has_rmapbt(mp))
736 		return -EOPNOTSUPP;
737 
738 	old_agfl = kzalloc(BBTOB(XFS_FSS_TO_BB(mp, 1)), XCHK_GFP_FLAGS);
739 	if (!old_agfl)
740 		return -ENOMEM;
741 
742 	xagb_bitmap_init(&agfl_extents);
743 
744 	/*
745 	 * Read the AGF so that we can query the rmapbt.  We hope that there's
746 	 * nothing wrong with the AGF, but all the AG header repair functions
747 	 * have this chicken-and-egg problem.
748 	 */
749 	error = xfs_alloc_read_agf(sc->sa.pag, sc->tp, 0, &agf_bp);
750 	if (error)
751 		goto err_old_agfl;
752 
753 	/*
754 	 * Make sure we have the AGFL buffer, as scrub might have decided it
755 	 * was corrupt after xfs_alloc_read_agfl failed with -EFSCORRUPTED.
756 	 */
757 	error = xfs_trans_read_buf(mp, sc->tp, mp->m_ddev_targp,
758 			XFS_AG_DADDR(mp, pag_agno(sc->sa.pag),
759 						XFS_AGFL_DADDR(mp)),
760 			XFS_FSS_TO_BB(mp, 1), 0, &agfl_bp, NULL);
761 	if (error)
762 		goto err_old_agfl;
763 	agfl_bp->b_ops = &xfs_agfl_buf_ops;
764 
765 	/* Gather all the extents we're going to put on the new AGFL. */
766 	error = xrep_agfl_collect_blocks(sc, agf_bp, &agfl_extents, &flcount);
767 	if (error)
768 		goto err;
769 
770 	/* Last chance to abort before we start committing fixes. */
771 	if (xchk_should_terminate(sc, &error))
772 		goto err;
773 
774 	/*
775 	 * Update AGF and AGFL.  We reset the global free block counter when
776 	 * we adjust the AGF flcount (which can fail) so avoid updating any
777 	 * buffers until we know that part works.
778 	 */
779 	error = xrep_agfl_init_header(sc, agfl_bp, &agfl_extents, flcount,
780 			old_agfl);
781 	if (error)
782 		goto err;
783 	xrep_agfl_update_agf(sc, agf_bp, flcount);
784 
785 	/*
786 	 * Ok, the AGFL should be ready to go now.  Roll the transaction to
787 	 * make the new AGFL permanent before we start using it to return
788 	 * freespace overflow to the freespace btrees.
789 	 */
790 	sc->sa.agf_bp = agf_bp;
791 	error = xrep_roll_ag_trans(sc);
792 	if (error)
793 		goto err;
794 
795 	/* Dump any AGFL overflow. */
796 	error = xrep_reap_agblocks(sc, &agfl_extents, &XFS_RMAP_OINFO_AG,
797 			XFS_AG_RESV_AGFL);
798 	if (error)
799 		goto err;
800 
801 err:
802 	xagb_bitmap_destroy(&agfl_extents);
803 err_old_agfl:
804 	kfree(old_agfl);
805 	return error;
806 }
807 
808 /* AGI */
809 
810 /*
811  * Offset within the xrep_find_ag_btree array for each btree type.  Avoid the
812  * XFS_BTNUM_ names here to avoid creating a sparse array.
813  */
814 enum {
815 	XREP_AGI_INOBT = 0,
816 	XREP_AGI_FINOBT,
817 	XREP_AGI_END,
818 	XREP_AGI_MAX
819 };
820 
821 #define XREP_AGI_LOOKUP_BATCH		32
822 
823 struct xrep_agi {
824 	struct xfs_scrub		*sc;
825 
826 	/* AGI buffer, tracked separately */
827 	struct xfs_buf			*agi_bp;
828 
829 	/* context for finding btree roots */
830 	struct xrep_find_ag_btree	fab[XREP_AGI_MAX];
831 
832 	/* old AGI contents in case we have to revert */
833 	struct xfs_agi			old_agi;
834 
835 	/* bitmap of which inodes are unlinked */
836 	struct xagino_bitmap		iunlink_bmp;
837 
838 	/* heads of the unlinked inode bucket lists */
839 	xfs_agino_t			iunlink_heads[XFS_AGI_UNLINKED_BUCKETS];
840 
841 	/* scratchpad for batched lookups of the radix tree */
842 	struct xfs_inode		*lookup_batch[XREP_AGI_LOOKUP_BATCH];
843 
844 	/* Map of ino -> next_ino for unlinked inode processing. */
845 	struct xfarray			*iunlink_next;
846 
847 	/* Map of ino -> prev_ino for unlinked inode processing. */
848 	struct xfarray			*iunlink_prev;
849 };
850 
851 static void
852 xrep_agi_buf_cleanup(
853 	void		*buf)
854 {
855 	struct xrep_agi	*ragi = buf;
856 
857 	if (ragi->iunlink_prev)
858 		xfarray_destroy(ragi->iunlink_prev);
859 	ragi->iunlink_prev = NULL;
860 	if (ragi->iunlink_next)
861 		xfarray_destroy(ragi->iunlink_next);
862 	ragi->iunlink_next = NULL;
863 	xagino_bitmap_destroy(&ragi->iunlink_bmp);
864 }
865 
866 /*
867  * Given the inode btree roots described by *fab, find the roots, check them
868  * for sanity, and pass the root data back out via *fab.
869  */
870 STATIC int
871 xrep_agi_find_btrees(
872 	struct xrep_agi			*ragi)
873 {
874 	struct xfs_scrub		*sc = ragi->sc;
875 	struct xrep_find_ag_btree	*fab = ragi->fab;
876 	struct xfs_buf			*agf_bp;
877 	struct xfs_mount		*mp = sc->mp;
878 	int				error;
879 
880 	/* Read the AGF. */
881 	error = xfs_alloc_read_agf(sc->sa.pag, sc->tp, 0, &agf_bp);
882 	if (error)
883 		return error;
884 
885 	/* Find the btree roots. */
886 	error = xrep_find_ag_btree_roots(sc, agf_bp, fab, NULL);
887 	if (error)
888 		return error;
889 
890 	/* We must find the inobt root. */
891 	if (!xrep_check_btree_root(sc, &fab[XREP_AGI_INOBT]))
892 		return -EFSCORRUPTED;
893 
894 	/* We must find the finobt root if that feature is enabled. */
895 	if (xfs_has_finobt(mp) &&
896 	    !xrep_check_btree_root(sc, &fab[XREP_AGI_FINOBT]))
897 		return -EFSCORRUPTED;
898 
899 	return 0;
900 }
901 
902 /*
903  * Reinitialize the AGI header, making an in-core copy of the old contents so
904  * that we know which in-core state needs to be reinitialized.
905  */
906 STATIC void
907 xrep_agi_init_header(
908 	struct xrep_agi		*ragi)
909 {
910 	struct xfs_scrub	*sc = ragi->sc;
911 	struct xfs_buf		*agi_bp = ragi->agi_bp;
912 	struct xfs_agi		*old_agi = &ragi->old_agi;
913 	struct xfs_agi		*agi = agi_bp->b_addr;
914 	struct xfs_perag	*pag = sc->sa.pag;
915 	struct xfs_mount	*mp = sc->mp;
916 
917 	memcpy(old_agi, agi, sizeof(*old_agi));
918 	memset(agi, 0, BBTOB(agi_bp->b_length));
919 	agi->agi_magicnum = cpu_to_be32(XFS_AGI_MAGIC);
920 	agi->agi_versionnum = cpu_to_be32(XFS_AGI_VERSION);
921 	agi->agi_seqno = cpu_to_be32(pag_agno(pag));
922 	agi->agi_length = cpu_to_be32(pag_group(pag)->xg_block_count);
923 	agi->agi_newino = cpu_to_be32(NULLAGINO);
924 	agi->agi_dirino = cpu_to_be32(NULLAGINO);
925 	if (xfs_has_crc(mp))
926 		uuid_copy(&agi->agi_uuid, &mp->m_sb.sb_meta_uuid);
927 
928 	/* Mark the incore AGF data stale until we're done fixing things. */
929 	ASSERT(xfs_perag_initialised_agi(pag));
930 	clear_bit(XFS_AGSTATE_AGI_INIT, &pag->pag_opstate);
931 }
932 
933 /* Set btree root information in an AGI. */
934 STATIC void
935 xrep_agi_set_roots(
936 	struct xrep_agi			*ragi)
937 {
938 	struct xfs_scrub		*sc = ragi->sc;
939 	struct xfs_agi			*agi = ragi->agi_bp->b_addr;
940 	struct xrep_find_ag_btree	*fab = ragi->fab;
941 
942 	agi->agi_root = cpu_to_be32(fab[XREP_AGI_INOBT].root);
943 	agi->agi_level = cpu_to_be32(fab[XREP_AGI_INOBT].height);
944 
945 	if (xfs_has_finobt(sc->mp)) {
946 		agi->agi_free_root = cpu_to_be32(fab[XREP_AGI_FINOBT].root);
947 		agi->agi_free_level = cpu_to_be32(fab[XREP_AGI_FINOBT].height);
948 	}
949 }
950 
951 /* Update the AGI counters. */
952 STATIC int
953 xrep_agi_calc_from_btrees(
954 	struct xrep_agi		*ragi)
955 {
956 	struct xfs_scrub	*sc = ragi->sc;
957 	struct xfs_buf		*agi_bp = ragi->agi_bp;
958 	struct xfs_btree_cur	*cur;
959 	struct xfs_agi		*agi = agi_bp->b_addr;
960 	struct xfs_mount	*mp = sc->mp;
961 	xfs_agino_t		count;
962 	xfs_agino_t		freecount;
963 	int			error;
964 
965 	cur = xfs_inobt_init_cursor(sc->sa.pag, sc->tp, agi_bp);
966 	error = xfs_ialloc_count_inodes(cur, &count, &freecount);
967 	if (error)
968 		goto err;
969 	if (xfs_has_inobtcounts(mp)) {
970 		xfs_filblks_t	blocks;
971 
972 		error = xfs_btree_count_blocks(cur, &blocks);
973 		if (error)
974 			goto err;
975 		agi->agi_iblocks = cpu_to_be32(blocks);
976 	}
977 	xfs_btree_del_cursor(cur, error);
978 
979 	agi->agi_count = cpu_to_be32(count);
980 	agi->agi_freecount = cpu_to_be32(freecount);
981 
982 	if (xfs_has_finobt(mp) && xfs_has_inobtcounts(mp)) {
983 		xfs_filblks_t	blocks;
984 
985 		cur = xfs_finobt_init_cursor(sc->sa.pag, sc->tp, agi_bp);
986 		error = xfs_btree_count_blocks(cur, &blocks);
987 		if (error)
988 			goto err;
989 		xfs_btree_del_cursor(cur, error);
990 		agi->agi_fblocks = cpu_to_be32(blocks);
991 	}
992 
993 	return 0;
994 err:
995 	xfs_btree_del_cursor(cur, error);
996 	return error;
997 }
998 
999 /*
1000  * Magic value that means "not unlinked" because xfarrays don't support storing
1001  * totally zeroed elements.  There can't be a cluster that starts in daddr 0 so
1002  * there can't be an inode #1 either.
1003  */
1004 #define LINKED_AGINO	(0x1)
1005 
1006 /*
1007  * Record a forwards unlinked chain pointer from agino -> next_agino in our
1008  * staging information.
1009  */
1010 static inline int
1011 xrep_iunlink_store_next(
1012 	struct xrep_agi		*ragi,
1013 	xfs_agino_t		agino,
1014 	xfs_agino_t		next_agino)
1015 {
1016 	ASSERT(next_agino != 0);
1017 
1018 	return xfarray_store(ragi->iunlink_next, agino, &next_agino);
1019 }
1020 
1021 /*
1022  * Record a backwards unlinked chain pointer from prev_ino <- agino in our
1023  * staging information.
1024  */
1025 static inline int
1026 xrep_iunlink_store_prev(
1027 	struct xrep_agi		*ragi,
1028 	xfs_agino_t		agino,
1029 	xfs_agino_t		prev_agino)
1030 {
1031 	ASSERT(prev_agino != 0);
1032 
1033 	return xfarray_store(ragi->iunlink_prev, agino, &prev_agino);
1034 }
1035 
1036 /*
1037  * Given an @agino, look up the next inode in the iunlink bucket.  Returns
1038  * NULLAGINO if we're at the end of the chain, 0 if @agino is not in memory
1039  * like it should be, or a per-AG inode number.
1040  */
1041 static inline xfs_agino_t
1042 xrep_iunlink_next(
1043 	struct xfs_scrub	*sc,
1044 	xfs_agino_t		agino)
1045 {
1046 	struct xfs_inode	*ip;
1047 
1048 	ip = xfs_iunlink_lookup(sc->sa.pag, agino);
1049 	if (!ip)
1050 		return 0;
1051 
1052 	return ip->i_next_unlinked;
1053 }
1054 
1055 /*
1056  * Load the inode @agino into memory, set its i_prev_unlinked, and drop the
1057  * inode so it can be inactivated.  Returns NULLAGINO if we're at the end of
1058  * the chain or if we should stop walking the chain due to corruption; or a
1059  * per-AG inode number.
1060  */
1061 STATIC int
1062 xrep_iunlink_reload_next(
1063 	struct xrep_agi		*ragi,
1064 	xfs_agino_t		prev_agino,
1065 	xfs_agino_t		agino,
1066 	xfs_agino_t		*next_agino)
1067 {
1068 	struct xfs_scrub	*sc = ragi->sc;
1069 	struct xfs_inode	*ip;
1070 	int			error;
1071 
1072 	*next_agino = NULLAGINO;
1073 
1074 	error = xchk_iget(ragi->sc, xfs_agino_to_ino(sc->sa.pag, agino), &ip);
1075 	if (error)
1076 		return 0;
1077 
1078 	trace_xrep_iunlink_reload_next(ip, prev_agino);
1079 
1080 	/* If this is a linked inode, stop processing the chain. */
1081 	if (VFS_I(ip)->i_nlink != 0) {
1082 		error = xrep_iunlink_store_next(ragi, agino, NULLAGINO);
1083 		if (error)
1084 			return error;
1085 
1086 		error = xrep_iunlink_store_prev(ragi, agino, LINKED_AGINO);
1087 		if (error)
1088 			return error;
1089 
1090 		goto rele;
1091 	}
1092 
1093 	ip->i_prev_unlinked = prev_agino;
1094 	*next_agino = ip->i_next_unlinked;
1095 
1096 	/*
1097 	 * Drop the inode reference that we just took.  We hold the AGI, so
1098 	 * this inode cannot move off the unlinked list and hence cannot be
1099 	 * reclaimed.
1100 	 */
1101 rele:
1102 	xchk_irele(sc, ip);
1103 	return 0;
1104 }
1105 
1106 /*
1107  * Walk an AGI unlinked bucket's list to load incore any unlinked inodes that
1108  * still existed at mount time.  This can happen if iunlink processing fails
1109  * during log recovery.
1110  */
1111 STATIC int
1112 xrep_iunlink_walk_ondisk_bucket(
1113 	struct xrep_agi		*ragi,
1114 	unsigned int		bucket)
1115 {
1116 	struct xagino_bitmap	seen;
1117 	struct xfs_scrub	*sc = ragi->sc;
1118 	struct xfs_agi		*agi = ragi->agi_bp->b_addr;
1119 	xfs_agino_t		prev_agino = NULLAGINO;
1120 	xfs_agino_t		next_agino;
1121 	int			error = 0;
1122 
1123 	xagino_bitmap_init(&seen);
1124 
1125 	next_agino = be32_to_cpu(agi->agi_unlinked[bucket]);
1126 	while (next_agino != NULLAGINO) {
1127 		xfs_agino_t	agino = next_agino;
1128 		unsigned int	len = 1;
1129 
1130 		if (xchk_should_terminate(ragi->sc, &error))
1131 			goto out_bitmap;
1132 
1133 		trace_xrep_iunlink_walk_ondisk_bucket(sc->sa.pag, bucket,
1134 				prev_agino, agino);
1135 
1136 		if (bucket != agino % XFS_AGI_UNLINKED_BUCKETS)
1137 			break;
1138 
1139 		if (xagino_bitmap_test(&seen, agino, &len))
1140 			break;
1141 
1142 		next_agino = xrep_iunlink_next(sc, agino);
1143 		if (!next_agino) {
1144 			error = xrep_iunlink_reload_next(ragi, prev_agino,
1145 					agino, &next_agino);
1146 			if (error)
1147 				break;
1148 		}
1149 
1150 		error = xagino_bitmap_set(&seen, agino, 1);
1151 		if (error)
1152 			goto out_bitmap;
1153 
1154 		prev_agino = agino;
1155 	}
1156 
1157 out_bitmap:
1158 	xagino_bitmap_destroy(&seen);
1159 	return error;
1160 }
1161 
1162 /* Decide if this is an unlinked inode in this AG. */
1163 STATIC bool
1164 xrep_iunlink_igrab(
1165 	struct xfs_perag	*pag,
1166 	struct xfs_inode	*ip)
1167 {
1168 	if (XFS_INODE_TO_AGNO(ip) != pag_agno(pag))
1169 		return false;
1170 
1171 	if (!xfs_inode_on_unlinked_list(ip))
1172 		return false;
1173 
1174 	return true;
1175 }
1176 
1177 /*
1178  * Mark the given inode in the lookup batch in our unlinked inode bitmap, and
1179  * remember if this inode is the start of the unlinked chain.
1180  */
1181 STATIC int
1182 xrep_iunlink_visit(
1183 	struct xrep_agi		*ragi,
1184 	unsigned int		batch_idx)
1185 {
1186 	struct xfs_inode	*ip = ragi->lookup_batch[batch_idx];
1187 	xfs_agino_t		agino = XFS_INODE_TO_AGINO(ip);
1188 	unsigned int		bucket = agino % XFS_AGI_UNLINKED_BUCKETS;
1189 	int			error;
1190 
1191 	ASSERT(XFS_INODE_TO_AGNO(ip) == pag_agno(ragi->sc->sa.pag));
1192 	ASSERT(xfs_inode_on_unlinked_list(ip));
1193 
1194 	trace_xrep_iunlink_visit(ragi->sc->sa.pag, bucket,
1195 			ragi->iunlink_heads[bucket], ip);
1196 
1197 	error = xagino_bitmap_set(&ragi->iunlink_bmp, agino, 1);
1198 	if (error)
1199 		return error;
1200 
1201 	if (ip->i_prev_unlinked == NULLAGINO) {
1202 		if (ragi->iunlink_heads[bucket] == NULLAGINO)
1203 			ragi->iunlink_heads[bucket] = agino;
1204 	}
1205 
1206 	return 0;
1207 }
1208 
1209 /*
1210  * Find all incore unlinked inodes so that we can rebuild the unlinked buckets.
1211  * We hold the AGI so there should not be any modifications to the unlinked
1212  * list.
1213  */
1214 STATIC int
1215 xrep_iunlink_mark_incore(
1216 	struct xrep_agi		*ragi)
1217 {
1218 	struct xfs_perag	*pag = ragi->sc->sa.pag;
1219 	struct xfs_mount	*mp = pag_mount(pag);
1220 	uint32_t		first_index = 0;
1221 	bool			done = false;
1222 	unsigned int		nr_found = 0;
1223 
1224 	do {
1225 		unsigned int	i;
1226 		int		error = 0;
1227 
1228 		if (xchk_should_terminate(ragi->sc, &error))
1229 			return error;
1230 
1231 		rcu_read_lock();
1232 
1233 		nr_found = radix_tree_gang_lookup(&pag->pag_ici_root,
1234 				(void **)&ragi->lookup_batch, first_index,
1235 				XREP_AGI_LOOKUP_BATCH);
1236 		if (!nr_found) {
1237 			rcu_read_unlock();
1238 			return 0;
1239 		}
1240 
1241 		for (i = 0; i < nr_found; i++) {
1242 			struct xfs_inode *ip = ragi->lookup_batch[i];
1243 
1244 			if (done || !xrep_iunlink_igrab(pag, ip))
1245 				ragi->lookup_batch[i] = NULL;
1246 
1247 			/*
1248 			 * Update the index for the next lookup. Catch
1249 			 * overflows into the next AG range which can occur if
1250 			 * we have inodes in the last block of the AG and we
1251 			 * are currently pointing to the last inode.
1252 			 *
1253 			 * Because we may see inodes that are from the wrong AG
1254 			 * due to RCU freeing and reallocation, only update the
1255 			 * index if it lies in this AG. It was a race that lead
1256 			 * us to see this inode, so another lookup from the
1257 			 * same index will not find it again.
1258 			 */
1259 			if (XFS_INODE_TO_AGNO(ip) != pag_agno(pag))
1260 				continue;
1261 			first_index = XFS_INO_TO_AGINO(mp, I_INO(ip) + 1);
1262 			if (first_index < XFS_INODE_TO_AGINO(ip))
1263 				done = true;
1264 		}
1265 
1266 		/* unlock now we've grabbed the inodes. */
1267 		rcu_read_unlock();
1268 
1269 		for (i = 0; i < nr_found; i++) {
1270 			if (!ragi->lookup_batch[i])
1271 				continue;
1272 			error = xrep_iunlink_visit(ragi, i);
1273 			if (error)
1274 				return error;
1275 		}
1276 	} while (!done);
1277 
1278 	return 0;
1279 }
1280 
1281 /* Mark all the unlinked ondisk inodes in this inobt record in iunlink_bmp. */
1282 STATIC int
1283 xrep_iunlink_mark_ondisk_rec(
1284 	struct xfs_btree_cur		*cur,
1285 	const union xfs_btree_rec	*rec,
1286 	void				*priv)
1287 {
1288 	struct xfs_inobt_rec_incore	irec;
1289 	struct xrep_agi			*ragi = priv;
1290 	struct xfs_scrub		*sc = ragi->sc;
1291 	struct xfs_mount		*mp = cur->bc_mp;
1292 	xfs_agino_t			agino;
1293 	unsigned int			i;
1294 	int				error = 0;
1295 
1296 	xfs_inobt_btrec_to_irec(mp, rec, &irec);
1297 
1298 	for (i = 0, agino = irec.ir_startino;
1299 	     i < XFS_INODES_PER_CHUNK;
1300 	     i++, agino++) {
1301 		struct xfs_inode	*ip;
1302 		unsigned int		len = 1;
1303 
1304 		/* Skip free inodes */
1305 		if (XFS_INOBT_MASK(i) & irec.ir_free)
1306 			continue;
1307 		/* Skip inodes we've seen before */
1308 		if (xagino_bitmap_test(&ragi->iunlink_bmp, agino, &len))
1309 			continue;
1310 
1311 		/*
1312 		 * Skip incore inodes; these were already picked up by
1313 		 * the _mark_incore step.
1314 		 */
1315 		rcu_read_lock();
1316 		ip = radix_tree_lookup(&sc->sa.pag->pag_ici_root, agino);
1317 		rcu_read_unlock();
1318 		if (ip)
1319 			continue;
1320 
1321 		/*
1322 		 * Try to look up this inode.  If we can't get it, just move
1323 		 * on because we haven't actually scrubbed the inobt or the
1324 		 * inodes yet.
1325 		 */
1326 		error = xchk_iget(ragi->sc, xfs_agino_to_ino(sc->sa.pag, agino),
1327 				&ip);
1328 		if (error)
1329 			continue;
1330 
1331 		trace_xrep_iunlink_reload_ondisk(ip);
1332 
1333 		if (VFS_I(ip)->i_nlink == 0)
1334 			error = xagino_bitmap_set(&ragi->iunlink_bmp, agino, 1);
1335 		xchk_irele(sc, ip);
1336 		if (error)
1337 			break;
1338 	}
1339 
1340 	return error;
1341 }
1342 
1343 /*
1344  * Find ondisk inodes that are unlinked and not in cache, and mark them in
1345  * iunlink_bmp.   We haven't checked the inobt yet, so we don't error out if
1346  * the btree is corrupt.
1347  */
1348 STATIC int
1349 xrep_iunlink_mark_ondisk(
1350 	struct xrep_agi		*ragi)
1351 {
1352 	struct xfs_scrub	*sc = ragi->sc;
1353 	struct xfs_buf		*agi_bp = ragi->agi_bp;
1354 	struct xfs_btree_cur	*cur;
1355 	int			error;
1356 
1357 	cur = xfs_inobt_init_cursor(sc->sa.pag, sc->tp, agi_bp);
1358 	error = xfs_btree_query_all(cur, xrep_iunlink_mark_ondisk_rec, ragi);
1359 	xfs_btree_del_cursor(cur, error);
1360 
1361 	/*
1362 	 * Don't proceed if we couldn't set a bit in the bitmap.  All other
1363 	 * errors we ignore because we haven't actually checked the inobt yet.
1364 	 */
1365 	if (error == -ENOMEM)
1366 		return -ENOMEM;
1367 	return 0;
1368 }
1369 
1370 /*
1371  * Walk an iunlink bucket's inode list.  For each inode that should be on this
1372  * chain, clear its entry in iunlink_bmp because it's ok and we don't need
1373  * to touch it further.
1374  */
1375 STATIC int
1376 xrep_iunlink_resolve_bucket(
1377 	struct xrep_agi		*ragi,
1378 	unsigned int		bucket)
1379 {
1380 	struct xagino_bitmap	seen;
1381 	struct xfs_scrub	*sc = ragi->sc;
1382 	struct xfs_inode	*ip;
1383 	xfs_agino_t		prev_agino = NULLAGINO;
1384 	xfs_agino_t		next_agino = ragi->iunlink_heads[bucket];
1385 	int			error = 0;
1386 
1387 	xagino_bitmap_init(&seen);
1388 
1389 	while (next_agino != NULLAGINO) {
1390 		unsigned int len = 1;
1391 
1392 		if (xchk_should_terminate(ragi->sc, &error))
1393 			goto out_bitmap;
1394 
1395 		/* Inode already seen?  We're stuck in a loop */
1396 		if (xagino_bitmap_test(&seen, next_agino, &len)) {
1397 			trace_xrep_iunlink_resolve_infinite_loop(sc->sa.pag,
1398 					bucket, prev_agino, next_agino);
1399 			next_agino = NULLAGINO;
1400 			break;
1401 		}
1402 
1403 		error = xagino_bitmap_set(&seen, next_agino, 1);
1404 		if (error)
1405 			goto out_bitmap;
1406 
1407 		/* Find the next inode in the chain. */
1408 		ip = xfs_iunlink_lookup(sc->sa.pag, next_agino);
1409 		if (!ip) {
1410 			/* Inode not incore?  Terminate the chain. */
1411 			trace_xrep_iunlink_resolve_uncached(sc->sa.pag,
1412 					bucket, prev_agino, next_agino);
1413 
1414 			next_agino = NULLAGINO;
1415 			break;
1416 		}
1417 
1418 		if (VFS_I(ip)->i_nlink != 0) {
1419 			/*
1420 			 * Inode is linked somewhere!  Blow out both unlinked
1421 			 * list pointers, advance the list, and pretend we
1422 			 * didn't see this inode.  Clear it from iunlink_bmp
1423 			 * because it's linked.
1424 			 */
1425 			trace_xrep_iunlink_resolve_allocated(sc->sa.pag,
1426 					bucket, prev_agino, next_agino);
1427 
1428 			error = xrep_iunlink_store_next(ragi, next_agino,
1429 					NULLAGINO);
1430 			if (error)
1431 				goto out_bitmap;
1432 
1433 			error = xrep_iunlink_store_prev(ragi, next_agino,
1434 					LINKED_AGINO);
1435 			if (error)
1436 				goto out_bitmap;
1437 
1438 			error = xagino_bitmap_clear(&ragi->iunlink_bmp,
1439 					next_agino, 1);
1440 			if (error)
1441 				goto out_bitmap;
1442 
1443 			next_agino = ip->i_next_unlinked;
1444 			continue;
1445 		}
1446 
1447 		if (next_agino % XFS_AGI_UNLINKED_BUCKETS != bucket) {
1448 			/*
1449 			 * Inode is in the wrong bucket.  Advance the list,
1450 			 * but pretend we didn't see this inode.
1451 			 */
1452 			trace_xrep_iunlink_resolve_wronglist(sc->sa.pag,
1453 					bucket, prev_agino, next_agino);
1454 
1455 			next_agino = ip->i_next_unlinked;
1456 			continue;
1457 		}
1458 
1459 		if (!xfs_inode_on_unlinked_list(ip)) {
1460 			/*
1461 			 * Incore inode doesn't think this inode is on an
1462 			 * unlinked list.  This is probably because we reloaded
1463 			 * it from disk.  Advance the list, but pretend we
1464 			 * didn't see this inode; we'll fix that later.
1465 			 */
1466 			trace_xrep_iunlink_resolve_nolist(sc->sa.pag,
1467 					bucket, prev_agino, next_agino);
1468 			next_agino = ip->i_next_unlinked;
1469 			continue;
1470 		}
1471 
1472 		trace_xrep_iunlink_resolve_ok(sc->sa.pag, bucket, prev_agino,
1473 				next_agino);
1474 
1475 		/*
1476 		 * Otherwise, this inode's unlinked pointers are ok.  Clear it
1477 		 * from the unlinked bitmap since we're done with it, and make
1478 		 * sure the chain is still correct.
1479 		 */
1480 		error = xagino_bitmap_clear(&ragi->iunlink_bmp, next_agino, 1);
1481 		if (error)
1482 			goto out_bitmap;
1483 
1484 		/* Remember the previous inode's next pointer. */
1485 		if (prev_agino != NULLAGINO) {
1486 			error = xrep_iunlink_store_next(ragi, prev_agino,
1487 					next_agino);
1488 			if (error)
1489 				goto out_bitmap;
1490 		}
1491 
1492 		/* Remember this inode's previous pointer. */
1493 		error = xrep_iunlink_store_prev(ragi, next_agino, prev_agino);
1494 		if (error)
1495 			goto out_bitmap;
1496 
1497 		/* Advance the list and remember this inode. */
1498 		prev_agino = next_agino;
1499 		next_agino = ip->i_next_unlinked;
1500 	}
1501 
1502 	/* Update the previous inode's next pointer. */
1503 	if (prev_agino != NULLAGINO) {
1504 		error = xrep_iunlink_store_next(ragi, prev_agino, next_agino);
1505 		if (error)
1506 			goto out_bitmap;
1507 	}
1508 
1509 out_bitmap:
1510 	xagino_bitmap_destroy(&seen);
1511 	return error;
1512 }
1513 
1514 /* Reinsert this unlinked inode into the head of the staged bucket list. */
1515 STATIC int
1516 xrep_iunlink_add_to_bucket(
1517 	struct xrep_agi		*ragi,
1518 	xfs_agino_t		agino)
1519 {
1520 	xfs_agino_t		current_head;
1521 	unsigned int		bucket;
1522 	int			error;
1523 
1524 	bucket = agino % XFS_AGI_UNLINKED_BUCKETS;
1525 
1526 	/* Point this inode at the current head of the bucket list. */
1527 	current_head = ragi->iunlink_heads[bucket];
1528 
1529 	trace_xrep_iunlink_add_to_bucket(ragi->sc->sa.pag, bucket, agino,
1530 			current_head);
1531 
1532 	error = xrep_iunlink_store_next(ragi, agino, current_head);
1533 	if (error)
1534 		return error;
1535 
1536 	error = xrep_iunlink_store_prev(ragi, agino, NULLAGINO);
1537 	if (error)
1538 		return error;
1539 
1540 	/* Remember the head inode's previous pointer. */
1541 	if (current_head != NULLAGINO) {
1542 		error = xrep_iunlink_store_prev(ragi, current_head, agino);
1543 		if (error)
1544 			return error;
1545 	}
1546 
1547 	ragi->iunlink_heads[bucket] = agino;
1548 	return 0;
1549 }
1550 
1551 /* Reinsert unlinked inodes into the staged iunlink buckets. */
1552 STATIC int
1553 xrep_iunlink_add_lost_inodes(
1554 	uint32_t		start,
1555 	uint32_t		len,
1556 	void			*priv)
1557 {
1558 	struct xrep_agi		*ragi = priv;
1559 	int			error;
1560 
1561 	for (; len > 0; start++, len--) {
1562 		error = xrep_iunlink_add_to_bucket(ragi, start);
1563 		if (error)
1564 			return error;
1565 	}
1566 
1567 	return 0;
1568 }
1569 
1570 /*
1571  * Figure out the iunlink bucket values and find inodes that need to be
1572  * reinserted into the list.
1573  */
1574 STATIC int
1575 xrep_iunlink_rebuild_buckets(
1576 	struct xrep_agi		*ragi)
1577 {
1578 	unsigned int		i;
1579 	int			error;
1580 
1581 	/*
1582 	 * Walk the ondisk AGI unlinked list to find inodes that are on the
1583 	 * list but aren't in memory.  This can happen if a past log recovery
1584 	 * tried to clear the iunlinked list but failed.  Our scan rebuilds the
1585 	 * unlinked list using incore inodes, so we must load and link them
1586 	 * properly.
1587 	 */
1588 	for (i = 0; i < XFS_AGI_UNLINKED_BUCKETS; i++) {
1589 		error = xrep_iunlink_walk_ondisk_bucket(ragi, i);
1590 		if (error)
1591 			return error;
1592 	}
1593 
1594 	/*
1595 	 * Record all the incore unlinked inodes in iunlink_bmp that we didn't
1596 	 * find by walking the ondisk iunlink buckets.  This shouldn't happen,
1597 	 * but we can't risk forgetting an inode somewhere.
1598 	 */
1599 	error = xrep_iunlink_mark_incore(ragi);
1600 	if (error)
1601 		return error;
1602 
1603 	/*
1604 	 * If there are ondisk inodes that are unlinked and are not been loaded
1605 	 * into cache, record them in iunlink_bmp.
1606 	 */
1607 	error = xrep_iunlink_mark_ondisk(ragi);
1608 	if (error)
1609 		return error;
1610 
1611 	/*
1612 	 * Walk each iunlink bucket to (re)construct as much of the incore list
1613 	 * as would be correct.  For each inode that survives this step, mark
1614 	 * it clear in iunlink_bmp; we're done with those inodes.
1615 	 */
1616 	for (i = 0; i < XFS_AGI_UNLINKED_BUCKETS; i++) {
1617 		error = xrep_iunlink_resolve_bucket(ragi, i);
1618 		if (error)
1619 			return error;
1620 	}
1621 
1622 	/*
1623 	 * Any unlinked inodes that we didn't find through the bucket list
1624 	 * walk (or was ignored by the walk) must be inserted into the bucket
1625 	 * list.  Stage this in memory for now.
1626 	 */
1627 	return xagino_bitmap_walk(&ragi->iunlink_bmp,
1628 			xrep_iunlink_add_lost_inodes, ragi);
1629 }
1630 
1631 static inline void
1632 set_inode_prev_unlinked(
1633 	struct xfs_inode	*ip,
1634 	xfs_agino_t		prev_agino)
1635 {
1636 	/*
1637 	 * Magic value that means "not unlinked" because xfarrays don't support
1638 	 * storing totally zeroed elements.
1639 	 */
1640 	if (prev_agino == LINKED_AGINO)
1641 		prev_agino = 0;
1642 
1643 	if (ip->i_prev_unlinked != prev_agino) {
1644 		trace_xrep_iunlink_relink_prev(ip, prev_agino);
1645 		ip->i_prev_unlinked = prev_agino;
1646 	}
1647 }
1648 
1649 /* Update i_next_iunlinked for the inode @agino. */
1650 STATIC int
1651 xrep_iunlink_relink_next(
1652 	struct xrep_agi		*ragi,
1653 	xfarray_idx_t		idx,
1654 	xfs_agino_t		next_agino)
1655 {
1656 	struct xfs_scrub	*sc = ragi->sc;
1657 	struct xfs_perag	*pag = sc->sa.pag;
1658 	struct xfs_inode	*ip;
1659 	xfarray_idx_t		agino = idx - 1;
1660 	bool			want_rele = false;
1661 	int			error = 0;
1662 
1663 	ip = xfs_iunlink_lookup(pag, agino);
1664 	if (!ip) {
1665 		xfs_agino_t	prev_agino;
1666 
1667 		/*
1668 		 * No inode exists in cache.  Load it off the disk so that we
1669 		 * can reinsert it into the incore unlinked list.
1670 		 */
1671 		error = xchk_iget(sc, xfs_agino_to_ino(pag, agino), &ip);
1672 		if (error)
1673 			return -EFSCORRUPTED;
1674 
1675 		want_rele = true;
1676 
1677 		/* Set the backward pointer since this just came off disk. */
1678 		error = xfarray_load(ragi->iunlink_prev, agino, &prev_agino);
1679 		if (error)
1680 			goto out_rele;
1681 
1682 		set_inode_prev_unlinked(ip, prev_agino);
1683 	}
1684 
1685 	/* Update the forward pointer. */
1686 	if (ip->i_next_unlinked != next_agino) {
1687 		error = xfs_iunlink_log_inode(sc->tp, ip, pag, next_agino);
1688 		if (error)
1689 			goto out_rele;
1690 
1691 		trace_xrep_iunlink_relink_next(ip, next_agino);
1692 		ip->i_next_unlinked = next_agino;
1693 	}
1694 
1695 out_rele:
1696 	/*
1697 	 * The iunlink lookup doesn't igrab because we hold the AGI buffer lock
1698 	 * and the inode cannot be reclaimed.  However, if we used iget to load
1699 	 * a missing inode, we must irele it here.
1700 	 */
1701 	if (want_rele)
1702 		xchk_irele(sc, ip);
1703 	return error;
1704 }
1705 
1706 /* Update i_prev_iunlinked for the inode @agino. */
1707 STATIC int
1708 xrep_iunlink_relink_prev(
1709 	struct xrep_agi		*ragi,
1710 	xfarray_idx_t		idx,
1711 	xfs_agino_t		prev_agino)
1712 {
1713 	struct xfs_scrub	*sc = ragi->sc;
1714 	struct xfs_perag	*pag = sc->sa.pag;
1715 	struct xfs_inode	*ip;
1716 	xfarray_idx_t		agino = idx - 1;
1717 	bool			want_rele = false;
1718 	int			error = 0;
1719 
1720 	ASSERT(prev_agino != 0);
1721 
1722 	ip = xfs_iunlink_lookup(pag, agino);
1723 	if (!ip) {
1724 		xfs_agino_t	next_agino;
1725 
1726 		/*
1727 		 * No inode exists in cache.  Load it off the disk so that we
1728 		 * can reinsert it into the incore unlinked list.
1729 		 */
1730 		error = xchk_iget(sc, xfs_agino_to_ino(pag, agino), &ip);
1731 		if (error)
1732 			return -EFSCORRUPTED;
1733 
1734 		want_rele = true;
1735 
1736 		/* Set the forward pointer since this just came off disk. */
1737 		error = xfarray_load(ragi->iunlink_next, agino, &next_agino);
1738 		if (error)
1739 			goto out_rele;
1740 
1741 		error = xfs_iunlink_log_inode(sc->tp, ip, pag, next_agino);
1742 		if (error)
1743 			goto out_rele;
1744 
1745 		trace_xrep_iunlink_relink_next(ip, next_agino);
1746 		ip->i_next_unlinked = next_agino;
1747 	}
1748 
1749 	set_inode_prev_unlinked(ip, prev_agino);
1750 
1751 out_rele:
1752 	/*
1753 	 * The iunlink lookup doesn't igrab because we hold the AGI buffer lock
1754 	 * and the inode cannot be reclaimed.  However, if we used iget to load
1755 	 * a missing inode, we must irele it here.
1756 	 */
1757 	if (want_rele)
1758 		xchk_irele(sc, ip);
1759 	return error;
1760 }
1761 
1762 /* Log all the iunlink updates we need to finish regenerating the AGI. */
1763 STATIC int
1764 xrep_iunlink_commit(
1765 	struct xrep_agi		*ragi)
1766 {
1767 	struct xfs_agi		*agi = ragi->agi_bp->b_addr;
1768 	xfarray_idx_t		idx = XFARRAY_CURSOR_INIT;
1769 	xfs_agino_t		agino;
1770 	unsigned int		i;
1771 	int			error;
1772 
1773 	/* Fix all the forward links */
1774 	while ((error = xfarray_iter(ragi->iunlink_next, &idx, &agino)) == 1) {
1775 		error = xrep_iunlink_relink_next(ragi, idx, agino);
1776 		if (error)
1777 			return error;
1778 	}
1779 	if (error < 0)
1780 		return error;
1781 
1782 	/* Fix all the back links */
1783 	idx = XFARRAY_CURSOR_INIT;
1784 	while ((error = xfarray_iter(ragi->iunlink_prev, &idx, &agino)) == 1) {
1785 		error = xrep_iunlink_relink_prev(ragi, idx, agino);
1786 		if (error)
1787 			return error;
1788 	}
1789 	if (error < 0)
1790 		return error;
1791 
1792 	/* Copy the staged iunlink buckets to the new AGI. */
1793 	for (i = 0; i < XFS_AGI_UNLINKED_BUCKETS; i++) {
1794 		trace_xrep_iunlink_commit_bucket(ragi->sc->sa.pag, i,
1795 				be32_to_cpu(ragi->old_agi.agi_unlinked[i]),
1796 				ragi->iunlink_heads[i]);
1797 
1798 		agi->agi_unlinked[i] = cpu_to_be32(ragi->iunlink_heads[i]);
1799 	}
1800 
1801 	return 0;
1802 }
1803 
1804 /* Trigger reinitialization of the in-core data. */
1805 STATIC int
1806 xrep_agi_commit_new(
1807 	struct xrep_agi		*ragi)
1808 {
1809 	struct xfs_scrub	*sc = ragi->sc;
1810 	struct xfs_buf		*agi_bp = ragi->agi_bp;
1811 	struct xfs_perag	*pag;
1812 	struct xfs_agi		*agi = agi_bp->b_addr;
1813 
1814 	/* Trigger inode count recalculation */
1815 	xfs_force_summary_recalc(sc->mp);
1816 
1817 	/* Write this to disk. */
1818 	xfs_trans_buf_set_type(sc->tp, agi_bp, XFS_BLFT_AGI_BUF);
1819 	xfs_trans_log_buf(sc->tp, agi_bp, 0, BBTOB(agi_bp->b_length) - 1);
1820 
1821 	/* Now reinitialize the in-core counters if necessary. */
1822 	pag = sc->sa.pag;
1823 	pag->pagi_count = be32_to_cpu(agi->agi_count);
1824 	pag->pagi_freecount = be32_to_cpu(agi->agi_freecount);
1825 	set_bit(XFS_AGSTATE_AGI_INIT, &pag->pag_opstate);
1826 
1827 	return xrep_roll_ag_trans(sc);
1828 }
1829 
1830 /* Repair the AGI. */
1831 int
1832 xrep_agi(
1833 	struct xfs_scrub	*sc)
1834 {
1835 	struct xrep_agi		*ragi;
1836 	struct xfs_mount	*mp = sc->mp;
1837 	unsigned int		i;
1838 	int			error;
1839 
1840 	/* We require the rmapbt to rebuild anything. */
1841 	if (!xfs_has_rmapbt(mp))
1842 		return -EOPNOTSUPP;
1843 
1844 	sc->buf = kzalloc_obj(struct xrep_agi, XCHK_GFP_FLAGS);
1845 	if (!sc->buf)
1846 		return -ENOMEM;
1847 	ragi = sc->buf;
1848 	ragi->sc = sc;
1849 
1850 	ragi->fab[XREP_AGI_INOBT] = (struct xrep_find_ag_btree){
1851 		.rmap_owner	= XFS_RMAP_OWN_INOBT,
1852 		.buf_ops	= &xfs_inobt_buf_ops,
1853 		.maxlevels	= M_IGEO(sc->mp)->inobt_maxlevels,
1854 	};
1855 	ragi->fab[XREP_AGI_FINOBT] = (struct xrep_find_ag_btree){
1856 		.rmap_owner	= XFS_RMAP_OWN_INOBT,
1857 		.buf_ops	= &xfs_finobt_buf_ops,
1858 		.maxlevels	= M_IGEO(sc->mp)->inobt_maxlevels,
1859 	};
1860 	ragi->fab[XREP_AGI_END] = (struct xrep_find_ag_btree){
1861 		.buf_ops	= NULL,
1862 	};
1863 
1864 	for (i = 0; i < XFS_AGI_UNLINKED_BUCKETS; i++)
1865 		ragi->iunlink_heads[i] = NULLAGINO;
1866 
1867 	xagino_bitmap_init(&ragi->iunlink_bmp);
1868 	sc->buf_cleanup = xrep_agi_buf_cleanup;
1869 
1870 	error = xfarray_create("iunlinked next pointers", 0,
1871 			sizeof(xfs_agino_t), &ragi->iunlink_next);
1872 	if (error)
1873 		return error;
1874 
1875 	error = xfarray_create("iunlinked prev pointers", 0,
1876 			sizeof(xfs_agino_t), &ragi->iunlink_prev);
1877 	if (error)
1878 		return error;
1879 
1880 	/*
1881 	 * Make sure we have the AGI buffer, as scrub might have decided it
1882 	 * was corrupt after xfs_ialloc_read_agi failed with -EFSCORRUPTED.
1883 	 */
1884 	error = xfs_trans_read_buf(mp, sc->tp, mp->m_ddev_targp,
1885 			XFS_AG_DADDR(mp, pag_agno(sc->sa.pag),
1886 						XFS_AGI_DADDR(mp)),
1887 			XFS_FSS_TO_BB(mp, 1), 0, &ragi->agi_bp, NULL);
1888 	if (error)
1889 		return error;
1890 	ragi->agi_bp->b_ops = &xfs_agi_buf_ops;
1891 
1892 	/* Find the AGI btree roots. */
1893 	error = xrep_agi_find_btrees(ragi);
1894 	if (error)
1895 		return error;
1896 
1897 	error = xrep_iunlink_rebuild_buckets(ragi);
1898 	if (error)
1899 		return error;
1900 
1901 	/* Last chance to abort before we start committing fixes. */
1902 	if (xchk_should_terminate(sc, &error))
1903 		return error;
1904 
1905 	/* Start rewriting the header and implant the btrees we found. */
1906 	xrep_agi_init_header(ragi);
1907 	xrep_agi_set_roots(ragi);
1908 	error = xrep_agi_calc_from_btrees(ragi);
1909 	if (error)
1910 		goto out_revert;
1911 	error = xrep_iunlink_commit(ragi);
1912 	if (error)
1913 		goto out_revert;
1914 
1915 	/* Reinitialize in-core state. */
1916 	return xrep_agi_commit_new(ragi);
1917 
1918 out_revert:
1919 	/* Mark the incore AGI state stale and revert the AGI. */
1920 	clear_bit(XFS_AGSTATE_AGI_INIT, &sc->sa.pag->pag_opstate);
1921 	memcpy(ragi->agi_bp->b_addr, &ragi->old_agi, sizeof(struct xfs_agi));
1922 	return error;
1923 }
1924