xref: /linux/fs/xfs/scrub/common.c (revision bb29b957eaaa15be33243550d9ee576c2d601669)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (C) 2017-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_inode.h"
16 #include "xfs_icache.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_refcount_btree.h"
22 #include "xfs_rmap.h"
23 #include "xfs_rmap_btree.h"
24 #include "xfs_log.h"
25 #include "xfs_trans_priv.h"
26 #include "xfs_da_format.h"
27 #include "xfs_da_btree.h"
28 #include "xfs_dir2_priv.h"
29 #include "xfs_dir2.h"
30 #include "xfs_attr.h"
31 #include "xfs_reflink.h"
32 #include "xfs_ag.h"
33 #include "xfs_error.h"
34 #include "xfs_quota.h"
35 #include "xfs_exchmaps.h"
36 #include "xfs_rtbitmap.h"
37 #include "xfs_rtgroup.h"
38 #include "xfs_rtrmap_btree.h"
39 #include "xfs_bmap_util.h"
40 #include "xfs_rtrefcount_btree.h"
41 #include "scrub/scrub.h"
42 #include "scrub/common.h"
43 #include "scrub/trace.h"
44 #include "scrub/repair.h"
45 #include "scrub/health.h"
46 #include "scrub/tempfile.h"
47 
48 /* Common code for the metadata scrubbers. */
49 
50 /*
51  * Handling operational errors.
52  *
53  * The *_process_error() family of functions are used to process error return
54  * codes from functions called as part of a scrub operation.
55  *
56  * If there's no error, we return true to tell the caller that it's ok
57  * to move on to the next check in its list.
58  *
59  * For non-verifier errors (e.g. ENOMEM) we return false to tell the
60  * caller that something bad happened, and we preserve *error so that
61  * the caller can return the *error up the stack to userspace.
62  *
63  * Verifier errors (EFSBADCRC/EFSCORRUPTED) are recorded by setting
64  * OFLAG_CORRUPT in sm_flags and the *error is cleared.  In other words,
65  * we track verifier errors (and failed scrub checks) via OFLAG_CORRUPT,
66  * not via return codes.  We return false to tell the caller that
67  * something bad happened.  Since the error has been cleared, the caller
68  * will (presumably) return that zero and scrubbing will move on to
69  * whatever's next.
70  *
71  * ftrace can be used to record the precise metadata location and the
72  * approximate code location of the failed operation.
73  */
74 
75 /* Check for operational errors. */
76 static bool
77 __xchk_process_error(
78 	struct xfs_scrub	*sc,
79 	xfs_agnumber_t		agno,
80 	xfs_agblock_t		bno,
81 	int			*error,
82 	__u32			errflag,
83 	void			*ret_ip)
84 {
85 	switch (*error) {
86 	case 0:
87 		return true;
88 	case -EDEADLOCK:
89 	case -ECHRNG:
90 		/* Used to restart an op with deadlock avoidance. */
91 		trace_xchk_deadlock_retry(
92 				sc->ip ? sc->ip : XFS_I(file_inode(sc->file)),
93 				sc->sm, *error);
94 		break;
95 	case -ECANCELED:
96 		/*
97 		 * ECANCELED here means that the caller set one of the scrub
98 		 * outcome flags (corrupt, xfail, xcorrupt) and wants to exit
99 		 * quickly.  Set error to zero and do not continue.
100 		 */
101 		trace_xchk_op_error(sc, agno, bno, *error, ret_ip);
102 		*error = 0;
103 		break;
104 	case -EFSBADCRC:
105 	case -EFSCORRUPTED:
106 	case -EIO:
107 	case -ENODATA:
108 		/* Note the badness but don't abort. */
109 		sc->sm->sm_flags |= errflag;
110 		trace_xchk_op_error(sc, agno, bno, *error, ret_ip);
111 		*error = 0;
112 		break;
113 	default:
114 		trace_xchk_op_error(sc, agno, bno, *error, ret_ip);
115 		break;
116 	}
117 	return false;
118 }
119 
120 bool
121 xchk_process_error(
122 	struct xfs_scrub	*sc,
123 	xfs_agnumber_t		agno,
124 	xfs_agblock_t		bno,
125 	int			*error)
126 {
127 	return __xchk_process_error(sc, agno, bno, error,
128 			XFS_SCRUB_OFLAG_CORRUPT, __return_address);
129 }
130 
131 bool
132 xchk_process_rt_error(
133 	struct xfs_scrub	*sc,
134 	xfs_rgnumber_t		rgno,
135 	xfs_rgblock_t		rgbno,
136 	int			*error)
137 {
138 	return __xchk_process_error(sc, rgno, rgbno, error,
139 			XFS_SCRUB_OFLAG_CORRUPT, __return_address);
140 }
141 
142 bool
143 xchk_xref_process_error(
144 	struct xfs_scrub	*sc,
145 	xfs_agnumber_t		agno,
146 	xfs_agblock_t		bno,
147 	int			*error)
148 {
149 	return __xchk_process_error(sc, agno, bno, error,
150 			XFS_SCRUB_OFLAG_XFAIL, __return_address);
151 }
152 
153 /* Check for operational errors for a file offset. */
154 static bool
155 __xchk_fblock_process_error(
156 	struct xfs_scrub	*sc,
157 	int			whichfork,
158 	xfs_fileoff_t		offset,
159 	int			*error,
160 	__u32			errflag,
161 	void			*ret_ip)
162 {
163 	switch (*error) {
164 	case 0:
165 		return true;
166 	case -EDEADLOCK:
167 	case -ECHRNG:
168 		/* Used to restart an op with deadlock avoidance. */
169 		trace_xchk_deadlock_retry(sc->ip, sc->sm, *error);
170 		break;
171 	case -ECANCELED:
172 		/*
173 		 * ECANCELED here means that the caller set one of the scrub
174 		 * outcome flags (corrupt, xfail, xcorrupt) and wants to exit
175 		 * quickly.  Set error to zero and do not continue.
176 		 */
177 		trace_xchk_file_op_error(sc, whichfork, offset, *error,
178 				ret_ip);
179 		*error = 0;
180 		break;
181 	case -EFSBADCRC:
182 	case -EFSCORRUPTED:
183 	case -EIO:
184 	case -ENODATA:
185 		/* Note the badness but don't abort. */
186 		sc->sm->sm_flags |= errflag;
187 		trace_xchk_file_op_error(sc, whichfork, offset, *error,
188 				ret_ip);
189 		*error = 0;
190 		break;
191 	default:
192 		trace_xchk_file_op_error(sc, whichfork, offset, *error,
193 				ret_ip);
194 		break;
195 	}
196 	return false;
197 }
198 
199 bool
200 xchk_fblock_process_error(
201 	struct xfs_scrub	*sc,
202 	int			whichfork,
203 	xfs_fileoff_t		offset,
204 	int			*error)
205 {
206 	return __xchk_fblock_process_error(sc, whichfork, offset, error,
207 			XFS_SCRUB_OFLAG_CORRUPT, __return_address);
208 }
209 
210 bool
211 xchk_fblock_xref_process_error(
212 	struct xfs_scrub	*sc,
213 	int			whichfork,
214 	xfs_fileoff_t		offset,
215 	int			*error)
216 {
217 	return __xchk_fblock_process_error(sc, whichfork, offset, error,
218 			XFS_SCRUB_OFLAG_XFAIL, __return_address);
219 }
220 
221 /*
222  * Handling scrub corruption/optimization/warning checks.
223  *
224  * The *_set_{corrupt,preen,warning}() family of functions are used to
225  * record the presence of metadata that is incorrect (corrupt), could be
226  * optimized somehow (preen), or should be flagged for administrative
227  * review but is not incorrect (warn).
228  *
229  * ftrace can be used to record the precise metadata location and
230  * approximate code location of the failed check.
231  */
232 
233 /* Record a block which could be optimized. */
234 void
235 xchk_block_set_preen(
236 	struct xfs_scrub	*sc,
237 	struct xfs_buf		*bp)
238 {
239 	sc->sm->sm_flags |= XFS_SCRUB_OFLAG_PREEN;
240 	trace_xchk_block_preen(sc, xfs_buf_daddr(bp), __return_address);
241 }
242 
243 /*
244  * Record an inode which could be optimized.  The trace data will
245  * include the block given by bp if bp is given; otherwise it will use
246  * the block location of the inode record itself.
247  */
248 void
249 xchk_ino_set_preen(
250 	struct xfs_scrub	*sc,
251 	xfs_ino_t		ino)
252 {
253 	sc->sm->sm_flags |= XFS_SCRUB_OFLAG_PREEN;
254 	trace_xchk_ino_preen(sc, ino, __return_address);
255 }
256 
257 /* Record a block indexed by a file fork that could be optimized. */
258 void
259 xchk_fblock_set_preen(
260 	struct xfs_scrub        *sc,
261 	int                     whichfork,
262 	xfs_fileoff_t           offset)
263 {
264 	sc->sm->sm_flags |= XFS_SCRUB_OFLAG_PREEN;
265 	trace_xchk_fblock_preen(sc, whichfork, offset, __return_address);
266 }
267 
268 /* Record something being wrong with the filesystem primary superblock. */
269 void
270 xchk_set_corrupt(
271 	struct xfs_scrub	*sc)
272 {
273 	sc->sm->sm_flags |= XFS_SCRUB_OFLAG_CORRUPT;
274 	trace_xchk_fs_error(sc, 0, __return_address);
275 }
276 
277 /* Record a corrupt block. */
278 void
279 xchk_block_set_corrupt(
280 	struct xfs_scrub	*sc,
281 	struct xfs_buf		*bp)
282 {
283 	sc->sm->sm_flags |= XFS_SCRUB_OFLAG_CORRUPT;
284 	trace_xchk_block_error(sc, xfs_buf_daddr(bp), __return_address);
285 }
286 
287 #ifdef CONFIG_XFS_QUOTA
288 /* Record a corrupt quota counter. */
289 void
290 xchk_qcheck_set_corrupt(
291 	struct xfs_scrub	*sc,
292 	unsigned int		dqtype,
293 	xfs_dqid_t		id)
294 {
295 	sc->sm->sm_flags |= XFS_SCRUB_OFLAG_CORRUPT;
296 	trace_xchk_qcheck_error(sc, dqtype, id, __return_address);
297 }
298 #endif
299 
300 /* Record a corruption while cross-referencing. */
301 void
302 xchk_block_xref_set_corrupt(
303 	struct xfs_scrub	*sc,
304 	struct xfs_buf		*bp)
305 {
306 	sc->sm->sm_flags |= XFS_SCRUB_OFLAG_XCORRUPT;
307 	trace_xchk_block_error(sc, xfs_buf_daddr(bp), __return_address);
308 }
309 
310 /*
311  * Record a corrupt inode.  The trace data will include the block given
312  * by bp if bp is given; otherwise it will use the block location of the
313  * inode record itself.
314  */
315 void
316 xchk_ino_set_corrupt(
317 	struct xfs_scrub	*sc,
318 	xfs_ino_t		ino)
319 {
320 	sc->sm->sm_flags |= XFS_SCRUB_OFLAG_CORRUPT;
321 	trace_xchk_ino_error(sc, ino, __return_address);
322 }
323 
324 /* Record a corruption while cross-referencing with an inode. */
325 void
326 xchk_ip_xref_set_corrupt(
327 	struct xfs_scrub	*sc,
328 	struct xfs_inode	*ip)
329 {
330 	sc->sm->sm_flags |= XFS_SCRUB_OFLAG_XCORRUPT;
331 	trace_xchk_ino_error(sc, I_INO(ip), __return_address);
332 }
333 
334 /* Record corruption in a block indexed by a file fork. */
335 void
336 xchk_fblock_set_corrupt(
337 	struct xfs_scrub	*sc,
338 	int			whichfork,
339 	xfs_fileoff_t		offset)
340 {
341 	sc->sm->sm_flags |= XFS_SCRUB_OFLAG_CORRUPT;
342 	trace_xchk_fblock_error(sc, whichfork, offset, __return_address);
343 }
344 
345 /* Record a corruption while cross-referencing a fork block. */
346 void
347 xchk_fblock_xref_set_corrupt(
348 	struct xfs_scrub	*sc,
349 	int			whichfork,
350 	xfs_fileoff_t		offset)
351 {
352 	sc->sm->sm_flags |= XFS_SCRUB_OFLAG_XCORRUPT;
353 	trace_xchk_fblock_error(sc, whichfork, offset, __return_address);
354 }
355 
356 /*
357  * Warn about inodes that need administrative review but is not
358  * incorrect.
359  */
360 void
361 xchk_ino_set_warning(
362 	struct xfs_scrub	*sc,
363 	xfs_ino_t		ino)
364 {
365 	sc->sm->sm_flags |= XFS_SCRUB_OFLAG_WARNING;
366 	trace_xchk_ino_warning(sc, ino, __return_address);
367 }
368 
369 /* Warn about a block indexed by a file fork that needs review. */
370 void
371 xchk_fblock_set_warning(
372 	struct xfs_scrub	*sc,
373 	int			whichfork,
374 	xfs_fileoff_t		offset)
375 {
376 	sc->sm->sm_flags |= XFS_SCRUB_OFLAG_WARNING;
377 	trace_xchk_fblock_warning(sc, whichfork, offset, __return_address);
378 }
379 
380 /* Signal an incomplete scrub. */
381 void
382 xchk_set_incomplete(
383 	struct xfs_scrub	*sc)
384 {
385 	sc->sm->sm_flags |= XFS_SCRUB_OFLAG_INCOMPLETE;
386 	trace_xchk_incomplete(sc, __return_address);
387 }
388 
389 /*
390  * rmap scrubbing -- compute the number of blocks with a given owner,
391  * at least according to the reverse mapping data.
392  */
393 
394 struct xchk_rmap_ownedby_info {
395 	const struct xfs_owner_info	*oinfo;
396 	xfs_filblks_t			*blocks;
397 };
398 
399 STATIC int
400 xchk_count_rmap_ownedby_irec(
401 	struct xfs_btree_cur		*cur,
402 	const struct xfs_rmap_irec	*rec,
403 	void				*priv)
404 {
405 	struct xchk_rmap_ownedby_info	*sroi = priv;
406 	bool				irec_attr;
407 	bool				oinfo_attr;
408 
409 	irec_attr = rec->rm_flags & XFS_RMAP_ATTR_FORK;
410 	oinfo_attr = sroi->oinfo->oi_flags & XFS_OWNER_INFO_ATTR_FORK;
411 
412 	if (rec->rm_owner != sroi->oinfo->oi_owner)
413 		return 0;
414 
415 	if (XFS_RMAP_NON_INODE_OWNER(rec->rm_owner) || irec_attr == oinfo_attr)
416 		(*sroi->blocks) += rec->rm_blockcount;
417 
418 	return 0;
419 }
420 
421 /*
422  * Calculate the number of blocks the rmap thinks are owned by something.
423  * The caller should pass us an rmapbt cursor.
424  */
425 int
426 xchk_count_rmap_ownedby_ag(
427 	struct xfs_scrub		*sc,
428 	struct xfs_btree_cur		*cur,
429 	const struct xfs_owner_info	*oinfo,
430 	xfs_filblks_t			*blocks)
431 {
432 	struct xchk_rmap_ownedby_info	sroi = {
433 		.oinfo			= oinfo,
434 		.blocks			= blocks,
435 	};
436 
437 	*blocks = 0;
438 	return xfs_rmap_query_all(cur, xchk_count_rmap_ownedby_irec,
439 			&sroi);
440 }
441 
442 /*
443  * AG scrubbing
444  *
445  * These helpers facilitate locking an allocation group's header
446  * buffers, setting up cursors for all btrees that are present, and
447  * cleaning everything up once we're through.
448  */
449 
450 /* Decide if we want to return an AG header read failure. */
451 static inline bool
452 want_ag_read_header_failure(
453 	struct xfs_scrub	*sc,
454 	unsigned int		type)
455 {
456 	/* Return all AG header read failures when scanning btrees. */
457 	if (sc->sm->sm_type != XFS_SCRUB_TYPE_AGF &&
458 	    sc->sm->sm_type != XFS_SCRUB_TYPE_AGFL &&
459 	    sc->sm->sm_type != XFS_SCRUB_TYPE_AGI)
460 		return true;
461 	/*
462 	 * If we're scanning a given type of AG header, we only want to
463 	 * see read failures from that specific header.  We'd like the
464 	 * other headers to cross-check them, but this isn't required.
465 	 */
466 	if (sc->sm->sm_type == type)
467 		return true;
468 	return false;
469 }
470 
471 /*
472  * Grab the AG header buffers for the attached perag structure.
473  *
474  * The headers should be released by xchk_ag_free, but as a fail safe we attach
475  * all the buffers we grab to the scrub transaction so they'll all be freed
476  * when we cancel it.
477  */
478 static inline int
479 xchk_perag_read_headers(
480 	struct xfs_scrub	*sc,
481 	struct xchk_ag		*sa)
482 {
483 	int			error;
484 
485 	error = xfs_ialloc_read_agi(sa->pag, sc->tp, 0, &sa->agi_bp);
486 	if (error && want_ag_read_header_failure(sc, XFS_SCRUB_TYPE_AGI))
487 		return error;
488 
489 	error = xfs_alloc_read_agf(sa->pag, sc->tp, 0, &sa->agf_bp);
490 	if (error && want_ag_read_header_failure(sc, XFS_SCRUB_TYPE_AGF))
491 		return error;
492 
493 	return 0;
494 }
495 
496 /*
497  * Grab the AG headers for the attached perag structure and wait for pending
498  * intents to drain.
499  */
500 int
501 xchk_perag_drain_and_lock(
502 	struct xfs_scrub	*sc)
503 {
504 	struct xchk_ag		*sa = &sc->sa;
505 	int			error = 0;
506 
507 	ASSERT(sa->pag != NULL);
508 	ASSERT(sa->agi_bp == NULL);
509 	ASSERT(sa->agf_bp == NULL);
510 
511 	do {
512 		if (xchk_should_terminate(sc, &error))
513 			return error;
514 
515 		error = xchk_perag_read_headers(sc, sa);
516 		if (error)
517 			return error;
518 
519 		/*
520 		 * If we've grabbed an inode for scrubbing then we assume that
521 		 * holding its ILOCK will suffice to coordinate with any intent
522 		 * chains involving this inode.
523 		 */
524 		if (sc->ip)
525 			return 0;
526 
527 		/*
528 		 * Decide if this AG is quiet enough for all metadata to be
529 		 * consistent with each other.  XFS allows the AG header buffer
530 		 * locks to cycle across transaction rolls while processing
531 		 * chains of deferred ops, which means that there could be
532 		 * other threads in the middle of processing a chain of
533 		 * deferred ops.  For regular operations we are careful about
534 		 * ordering operations to prevent collisions between threads
535 		 * (which is why we don't need a per-AG lock), but scrub and
536 		 * repair have to serialize against chained operations.
537 		 *
538 		 * We just locked all the AG headers buffers; now take a look
539 		 * to see if there are any intents in progress.  If there are,
540 		 * drop the AG headers and wait for the intents to drain.
541 		 * Since we hold all the AG header locks for the duration of
542 		 * the scrub, this is the only time we have to sample the
543 		 * intents counter; any threads increasing it after this point
544 		 * can't possibly be in the middle of a chain of AG metadata
545 		 * updates.
546 		 *
547 		 * Obviously, this should be slanted against scrub and in favor
548 		 * of runtime threads.
549 		 */
550 		if (!xfs_group_intent_busy(pag_group(sa->pag)))
551 			return 0;
552 
553 		if (sa->agf_bp) {
554 			xfs_trans_brelse(sc->tp, sa->agf_bp);
555 			sa->agf_bp = NULL;
556 		}
557 
558 		if (sa->agi_bp) {
559 			xfs_trans_brelse(sc->tp, sa->agi_bp);
560 			sa->agi_bp = NULL;
561 		}
562 
563 		if (!(sc->flags & XCHK_FSGATES_DRAIN))
564 			return -ECHRNG;
565 		error = xfs_group_intent_drain(pag_group(sa->pag));
566 		if (error == -ERESTARTSYS)
567 			error = -EINTR;
568 	} while (!error);
569 
570 	return error;
571 }
572 
573 /*
574  * Grab the per-AG structure, grab all AG header buffers, and wait until there
575  * aren't any pending intents.  Returns -ENOENT if we can't grab the perag
576  * structure.
577  */
578 int
579 xchk_ag_read_headers(
580 	struct xfs_scrub	*sc,
581 	xfs_agnumber_t		agno)
582 {
583 	struct xfs_mount	*mp = sc->mp;
584 	struct xchk_ag		*sa = &sc->sa;
585 
586 	ASSERT(!sa->pag);
587 	sa->pag = xfs_perag_get(mp, agno);
588 	if (!sa->pag)
589 		return -ENOENT;
590 
591 	return xchk_perag_drain_and_lock(sc);
592 }
593 
594 /* Release all the AG btree cursors. */
595 void
596 xchk_ag_btcur_free(
597 	struct xfs_scrub	*sc)
598 {
599 	struct xchk_ag		*sa = &sc->sa;
600 
601 	if (sa->refc_cur)
602 		xfs_btree_del_cursor(sa->refc_cur, XFS_BTREE_ERROR);
603 	if (sa->rmap_cur)
604 		xfs_btree_del_cursor(sa->rmap_cur, XFS_BTREE_ERROR);
605 	if (sa->fino_cur)
606 		xfs_btree_del_cursor(sa->fino_cur, XFS_BTREE_ERROR);
607 	if (sa->ino_cur)
608 		xfs_btree_del_cursor(sa->ino_cur, XFS_BTREE_ERROR);
609 	if (sa->cnt_cur)
610 		xfs_btree_del_cursor(sa->cnt_cur, XFS_BTREE_ERROR);
611 	if (sa->bno_cur)
612 		xfs_btree_del_cursor(sa->bno_cur, XFS_BTREE_ERROR);
613 
614 	sa->refc_cur = NULL;
615 	sa->rmap_cur = NULL;
616 	sa->fino_cur = NULL;
617 	sa->ino_cur = NULL;
618 	sa->bno_cur = NULL;
619 	sa->cnt_cur = NULL;
620 }
621 
622 /* Initialize all the btree cursors for an AG. */
623 void
624 xchk_ag_btcur_init(
625 	struct xfs_scrub	*sc)
626 {
627 	struct xfs_mount	*mp = sc->mp;
628 	struct xchk_ag		*sa = &sc->sa;
629 
630 	if (sa->agf_bp) {
631 		/* Set up a bnobt cursor for cross-referencing. */
632 		sa->bno_cur = xfs_bnobt_init_cursor(mp, sc->tp, sa->agf_bp,
633 				sa->pag);
634 		xchk_ag_btree_del_cursor_if_sick(sc, &sa->bno_cur,
635 				XFS_SCRUB_TYPE_BNOBT);
636 
637 		/* Set up a cntbt cursor for cross-referencing. */
638 		sa->cnt_cur = xfs_cntbt_init_cursor(mp, sc->tp, sa->agf_bp,
639 				sa->pag);
640 		xchk_ag_btree_del_cursor_if_sick(sc, &sa->cnt_cur,
641 				XFS_SCRUB_TYPE_CNTBT);
642 
643 		/* Set up a rmapbt cursor for cross-referencing. */
644 		if (xfs_has_rmapbt(mp)) {
645 			sa->rmap_cur = xfs_rmapbt_init_cursor(mp, sc->tp,
646 					sa->agf_bp, sa->pag);
647 			xchk_ag_btree_del_cursor_if_sick(sc, &sa->rmap_cur,
648 					XFS_SCRUB_TYPE_RMAPBT);
649 		}
650 
651 		/* Set up a refcountbt cursor for cross-referencing. */
652 		if (xfs_has_reflink(mp)) {
653 			sa->refc_cur = xfs_refcountbt_init_cursor(mp, sc->tp,
654 					sa->agf_bp, sa->pag);
655 			xchk_ag_btree_del_cursor_if_sick(sc, &sa->refc_cur,
656 					XFS_SCRUB_TYPE_REFCNTBT);
657 		}
658 	}
659 
660 	if (sa->agi_bp) {
661 		/* Set up a inobt cursor for cross-referencing. */
662 		sa->ino_cur = xfs_inobt_init_cursor(sa->pag, sc->tp,
663 				sa->agi_bp);
664 		xchk_ag_btree_del_cursor_if_sick(sc, &sa->ino_cur,
665 				XFS_SCRUB_TYPE_INOBT);
666 
667 		/* Set up a finobt cursor for cross-referencing. */
668 		if (xfs_has_finobt(mp)) {
669 			sa->fino_cur = xfs_finobt_init_cursor(sa->pag, sc->tp,
670 					sa->agi_bp);
671 			xchk_ag_btree_del_cursor_if_sick(sc, &sa->fino_cur,
672 					XFS_SCRUB_TYPE_FINOBT);
673 		}
674 	}
675 }
676 
677 /* Release the AG header context and btree cursors. */
678 void
679 xchk_ag_free(
680 	struct xfs_scrub	*sc)
681 {
682 	struct xchk_ag		*sa = &sc->sa;
683 
684 	xchk_ag_btcur_free(sc);
685 	xrep_reset_perag_resv(sc);
686 	if (sa->agf_bp) {
687 		xfs_trans_brelse(sc->tp, sa->agf_bp);
688 		sa->agf_bp = NULL;
689 	}
690 	if (sa->agi_bp) {
691 		xfs_trans_brelse(sc->tp, sa->agi_bp);
692 		sa->agi_bp = NULL;
693 	}
694 	if (sa->pag) {
695 		xfs_perag_put(sa->pag);
696 		sa->pag = NULL;
697 	}
698 }
699 
700 /*
701  * For scrub, grab the perag structure, the AGI, and the AGF headers, in that
702  * order.  Locking order requires us to get the AGI before the AGF.  We use the
703  * transaction to avoid deadlocking on crosslinked metadata buffers; either the
704  * caller passes one in (bmap scrub) or we have to create a transaction
705  * ourselves.  Returns ENOENT if the perag struct cannot be grabbed.
706  */
707 int
708 xchk_ag_init(
709 	struct xfs_scrub	*sc,
710 	xfs_agnumber_t		agno)
711 {
712 	int			error;
713 
714 	error = xchk_ag_read_headers(sc, agno);
715 	if (error)
716 		return error;
717 
718 	xchk_ag_btcur_init(sc);
719 	return 0;
720 }
721 
722 #ifdef CONFIG_XFS_RT
723 /*
724  * For scrubbing a realtime group, grab all the in-core resources we'll need to
725  * check the metadata, which means taking the ILOCK of the realtime group's
726  * metadata inodes.  Callers must not join these inodes to the transaction with
727  * non-zero lockflags or concurrency problems will result.  The @rtglock_flags
728  * argument takes XFS_RTGLOCK_* flags.
729  */
730 int
731 xchk_rtgroup_init(
732 	struct xfs_scrub	*sc,
733 	xfs_rgnumber_t		rgno)
734 {
735 	struct xchk_rt		*sr = &sc->sr;
736 
737 	ASSERT(sr->rtg == NULL);
738 	ASSERT(sr->rtlock_flags == 0);
739 
740 	sr->rtg = xfs_rtgroup_get(sc->mp, rgno);
741 	if (!sr->rtg)
742 		return -ENOENT;
743 	return 0;
744 }
745 
746 /* Lock all the rt group metadata inode ILOCKs and wait for intents. */
747 int
748 xchk_rtgroup_lock(
749 	struct xfs_scrub	*sc,
750 	unsigned int		rtglock_flags)
751 {
752 	struct xchk_rt		*sr = &sc->sr;
753 	int			error = 0;
754 
755 	ASSERT(sr->rtg != NULL);
756 
757 	/*
758 	 * If we're /only/ locking the rtbitmap in shared mode, then we're
759 	 * obviously not trying to compare records in two metadata inodes.
760 	 * There's no need to drain intents here because the caller (most
761 	 * likely the rgsuper scanner) doesn't need that level of consistency.
762 	 */
763 	if (rtglock_flags == XFS_RTGLOCK_BITMAP_SHARED) {
764 		xfs_rtgroup_lock(sr->rtg, rtglock_flags);
765 		sr->rtlock_flags = rtglock_flags;
766 		return 0;
767 	}
768 
769 	do {
770 		if (xchk_should_terminate(sc, &error))
771 			return error;
772 
773 		xfs_rtgroup_lock(sr->rtg, rtglock_flags);
774 
775 		/*
776 		 * If we've grabbed a non-metadata file for scrubbing, we
777 		 * assume that holding its ILOCK will suffice to coordinate
778 		 * with any rt intent chains involving this inode.
779 		 */
780 		if (sc->ip && !xfs_is_internal_inode(sc->ip))
781 			break;
782 
783 		/*
784 		 * Decide if the rt group is quiet enough for all metadata to
785 		 * be consistent with each other.  Regular file IO doesn't get
786 		 * to lock all the rt inodes at the same time, which means that
787 		 * there could be other threads in the middle of processing a
788 		 * chain of deferred ops.
789 		 *
790 		 * We just locked all the metadata inodes for this rt group;
791 		 * now take a look to see if there are any intents in progress.
792 		 * If there are, drop the rt group inode locks and wait for the
793 		 * intents to drain.  Since we hold the rt group inode locks
794 		 * for the duration of the scrub, this is the only time we have
795 		 * to sample the intents counter; any threads increasing it
796 		 * after this point can't possibly be in the middle of a chain
797 		 * of rt metadata updates.
798 		 *
799 		 * Obviously, this should be slanted against scrub and in favor
800 		 * of runtime threads.
801 		 */
802 		if (!xfs_group_intent_busy(rtg_group(sr->rtg)))
803 			break;
804 
805 		xfs_rtgroup_unlock(sr->rtg, rtglock_flags);
806 
807 		if (!(sc->flags & XCHK_FSGATES_DRAIN))
808 			return -ECHRNG;
809 		error = xfs_group_intent_drain(rtg_group(sr->rtg));
810 		if (error) {
811 			if (error == -ERESTARTSYS)
812 				error = -EINTR;
813 			return error;
814 		}
815 	} while (1);
816 
817 	sr->rtlock_flags = rtglock_flags;
818 
819 	if (xfs_has_rtrmapbt(sc->mp) && (rtglock_flags & XFS_RTGLOCK_RMAP))
820 		sr->rmap_cur = xfs_rtrmapbt_init_cursor(sc->tp, sr->rtg);
821 
822 	if (xfs_has_rtreflink(sc->mp) && (rtglock_flags & XFS_RTGLOCK_REFCOUNT))
823 		sr->refc_cur = xfs_rtrefcountbt_init_cursor(sc->tp, sr->rtg);
824 
825 	return 0;
826 }
827 
828 /*
829  * Free all the btree cursors and other incore data relating to the realtime
830  * group.  This has to be done /before/ committing (or cancelling) the scrub
831  * transaction.
832  */
833 void
834 xchk_rtgroup_btcur_free(
835 	struct xfs_scrub	*sc)
836 {
837 	struct xchk_rt		*sr = &sc->sr;
838 
839 	if (sr->rmap_cur)
840 		xfs_btree_del_cursor(sr->rmap_cur, XFS_BTREE_ERROR);
841 	if (sr->refc_cur)
842 		xfs_btree_del_cursor(sr->refc_cur, XFS_BTREE_ERROR);
843 
844 	sr->refc_cur = NULL;
845 	sr->rmap_cur = NULL;
846 }
847 
848 /*
849  * Unlock the realtime group.  This must be done /after/ committing (or
850  * cancelling) the scrub transaction.
851  */
852 void
853 xchk_rtgroup_unlock(
854 	struct xfs_scrub	*sc)
855 {
856 	struct xchk_rt		*sr = &sc->sr;
857 
858 	ASSERT(sr->rtg != NULL);
859 
860 	if (sr->rtlock_flags) {
861 		xfs_rtgroup_unlock(sr->rtg, sr->rtlock_flags);
862 		sr->rtlock_flags = 0;
863 	}
864 }
865 
866 /*
867  * Unlock the realtime group and release its resources.  This must be done
868  * /after/ committing (or cancelling) the scrub transaction.
869  */
870 void
871 xchk_rtgroup_free(
872 	struct xfs_scrub	*sc)
873 {
874 	struct xchk_rt		*sr = &sc->sr;
875 
876 	ASSERT(sr->rtg != NULL);
877 
878 	xchk_rtgroup_unlock(sc);
879 
880 	xfs_rtgroup_put(sr->rtg);
881 	sr->rtg = NULL;
882 }
883 #endif /* CONFIG_XFS_RT */
884 
885 /* Per-scrubber setup functions */
886 
887 void
888 xchk_trans_cancel(
889 	struct xfs_scrub	*sc)
890 {
891 	xfs_trans_cancel(sc->tp);
892 	sc->tp = NULL;
893 }
894 
895 void
896 xchk_trans_alloc_empty(
897 	struct xfs_scrub	*sc)
898 {
899 	sc->tp = xfs_trans_alloc_empty(sc->mp);
900 }
901 
902 /*
903  * Grab an empty transaction so that we can re-grab locked buffers if
904  * one of our btrees turns out to be cyclic.
905  *
906  * If we're going to repair something, we need to ask for the largest possible
907  * log reservation so that we can handle the worst case scenario for metadata
908  * updates while rebuilding a metadata item.  We also need to reserve as many
909  * blocks in the head transaction as we think we're going to need to rebuild
910  * the metadata object.
911  */
912 int
913 xchk_trans_alloc(
914 	struct xfs_scrub	*sc,
915 	uint			resblks)
916 {
917 	if (sc->sm->sm_flags & XFS_SCRUB_IFLAG_REPAIR)
918 		return xfs_trans_alloc(sc->mp, &M_RES(sc->mp)->tr_itruncate,
919 				resblks, 0, 0, &sc->tp);
920 
921 	xchk_trans_alloc_empty(sc);
922 	return 0;
923 }
924 
925 /* Set us up with a transaction and an empty context. */
926 int
927 xchk_setup_fs(
928 	struct xfs_scrub	*sc)
929 {
930 	uint			resblks;
931 
932 	resblks = xrep_calc_ag_resblks(sc);
933 	return xchk_trans_alloc(sc, resblks);
934 }
935 
936 /* Set us up with a transaction and an empty context to repair rt metadata. */
937 int
938 xchk_setup_rt(
939 	struct xfs_scrub	*sc)
940 {
941 	return xchk_trans_alloc(sc, xrep_calc_rtgroup_resblks(sc));
942 }
943 
944 /* Set us up with AG headers and btree cursors. */
945 int
946 xchk_setup_ag_btree(
947 	struct xfs_scrub	*sc,
948 	bool			force_log)
949 {
950 	struct xfs_mount	*mp = sc->mp;
951 	int			error;
952 
953 	/*
954 	 * If the caller asks us to checkpont the log, do so.  This
955 	 * expensive operation should be performed infrequently and only
956 	 * as a last resort.  Any caller that sets force_log should
957 	 * document why they need to do so.
958 	 */
959 	if (force_log) {
960 		error = xchk_checkpoint_log(mp);
961 		if (error)
962 			return error;
963 	}
964 
965 	error = xchk_setup_fs(sc);
966 	if (error)
967 		return error;
968 
969 	return xchk_ag_init(sc, sc->sm->sm_agno);
970 }
971 
972 /* Push everything out of the log onto disk. */
973 int
974 xchk_checkpoint_log(
975 	struct xfs_mount	*mp)
976 {
977 	int			error;
978 
979 	error = xfs_log_force(mp, XFS_LOG_SYNC);
980 	if (error)
981 		return error;
982 	xfs_ail_push_all_sync(mp->m_ail);
983 	return 0;
984 }
985 
986 /* Verify that an inode is allocated ondisk, then return its cached inode. */
987 int
988 xchk_iget(
989 	struct xfs_scrub	*sc,
990 	xfs_ino_t		inum,
991 	struct xfs_inode	**ipp)
992 {
993 	ASSERT(sc->tp != NULL);
994 
995 	return xfs_iget(sc->mp, sc->tp, inum, XCHK_IGET_FLAGS, 0, ipp);
996 }
997 
998 /*
999  * Try to grab an inode in a manner that avoids races with physical inode
1000  * allocation.  If we can't, return the locked AGI buffer so that the caller
1001  * can single-step the loading process to see where things went wrong.
1002  * Callers must have a valid scrub transaction.
1003  *
1004  * If the iget succeeds, return 0, a NULL AGI, and the inode.
1005  *
1006  * If the iget fails, return the error, the locked AGI, and a NULL inode.  This
1007  * can include -EINVAL and -ENOENT for invalid inode numbers or inodes that are
1008  * no longer allocated; or any other corruption or runtime error.
1009  *
1010  * If the AGI read fails, return the error, a NULL AGI, and NULL inode.
1011  *
1012  * If a fatal signal is pending, return -EINTR, a NULL AGI, and a NULL inode.
1013  */
1014 int
1015 xchk_iget_agi(
1016 	struct xfs_scrub	*sc,
1017 	xfs_ino_t		inum,
1018 	struct xfs_buf		**agi_bpp,
1019 	struct xfs_inode	**ipp)
1020 {
1021 	struct xfs_mount	*mp = sc->mp;
1022 	struct xfs_trans	*tp = sc->tp;
1023 	struct xfs_perag	*pag;
1024 	int			error;
1025 
1026 	ASSERT(sc->tp != NULL);
1027 
1028 again:
1029 	*agi_bpp = NULL;
1030 	*ipp = NULL;
1031 	error = 0;
1032 
1033 	if (xchk_should_terminate(sc, &error))
1034 		return error;
1035 
1036 	/*
1037 	 * Attach the AGI buffer to the scrub transaction to avoid deadlocks
1038 	 * in the iget cache miss path.
1039 	 */
1040 	pag = xfs_perag_get(mp, XFS_INO_TO_AGNO(mp, inum));
1041 	error = xfs_ialloc_read_agi(pag, tp, 0, agi_bpp);
1042 	xfs_perag_put(pag);
1043 	if (error)
1044 		return error;
1045 
1046 	error = xfs_iget(mp, tp, inum, XFS_IGET_NORETRY | XCHK_IGET_FLAGS, 0,
1047 			ipp);
1048 	if (error == -EAGAIN) {
1049 		/*
1050 		 * The inode may be in core but temporarily unavailable and may
1051 		 * require the AGI buffer before it can be returned.  Drop the
1052 		 * AGI buffer and retry the lookup.
1053 		 *
1054 		 * Incore lookup will fail with EAGAIN on a cache hit if the
1055 		 * inode is queued to the inactivation list.  The inactivation
1056 		 * worker may remove the inode from the unlinked list and hence
1057 		 * needs the AGI.
1058 		 *
1059 		 * Hence xchk_iget_agi() needs to drop the AGI lock on EAGAIN
1060 		 * to allow inodegc to make progress and move the inode to
1061 		 * IRECLAIMABLE state where xfs_iget will be able to return it
1062 		 * again if it can lock the inode.
1063 		 */
1064 		xfs_trans_brelse(tp, *agi_bpp);
1065 		delay(1);
1066 		goto again;
1067 	}
1068 	if (error)
1069 		return error;
1070 
1071 	/* We got the inode, so we can release the AGI. */
1072 	ASSERT(*ipp != NULL);
1073 	xfs_trans_brelse(tp, *agi_bpp);
1074 	*agi_bpp = NULL;
1075 	return 0;
1076 }
1077 
1078 #ifdef CONFIG_XFS_QUOTA
1079 /*
1080  * Try to attach dquots to this inode if we think we might want to repair it.
1081  * Callers must not hold any ILOCKs.  If the dquots are broken and cannot be
1082  * attached, a quotacheck will be scheduled.
1083  */
1084 int
1085 xchk_ino_dqattach(
1086 	struct xfs_scrub	*sc)
1087 {
1088 	ASSERT(sc->tp != NULL);
1089 	ASSERT(sc->ip != NULL);
1090 
1091 	if (!xchk_could_repair(sc))
1092 		return 0;
1093 
1094 	return xrep_ino_dqattach(sc);
1095 }
1096 #endif
1097 
1098 /* Install an inode that we opened by handle for scrubbing. */
1099 int
1100 xchk_install_handle_inode(
1101 	struct xfs_scrub	*sc,
1102 	struct xfs_inode	*ip)
1103 {
1104 	if (VFS_I(ip)->i_generation != sc->sm->sm_gen) {
1105 		xchk_irele(sc, ip);
1106 		return -ENOENT;
1107 	}
1108 
1109 	sc->ip = ip;
1110 	return 0;
1111 }
1112 
1113 /*
1114  * Install an already-referenced inode for scrubbing.  Get our own reference to
1115  * the inode to make disposal simpler.  The inode must not be in I_FREEING or
1116  * I_WILL_FREE state!
1117  */
1118 int
1119 xchk_install_live_inode(
1120 	struct xfs_scrub	*sc,
1121 	struct xfs_inode	*ip)
1122 {
1123 	if (!igrab(VFS_I(ip))) {
1124 		xchk_ip_set_corrupt(sc, ip);
1125 		return -EFSCORRUPTED;
1126 	}
1127 
1128 	sc->ip = ip;
1129 	return 0;
1130 }
1131 
1132 /*
1133  * In preparation to scrub metadata structures that hang off of an inode,
1134  * grab either the inode referenced in the scrub control structure or the
1135  * inode passed in.  If the inumber does not reference an allocated inode
1136  * record, the function returns ENOENT to end the scrub early.  The inode
1137  * is not locked.
1138  */
1139 int
1140 xchk_iget_for_scrubbing(
1141 	struct xfs_scrub	*sc)
1142 {
1143 	struct xfs_imap		imap;
1144 	struct xfs_mount	*mp = sc->mp;
1145 	struct xfs_perag	*pag;
1146 	struct xfs_buf		*agi_bp;
1147 	struct xfs_inode	*ip_in = XFS_I(file_inode(sc->file));
1148 	struct xfs_inode	*ip = NULL;
1149 	xfs_agnumber_t		agno = XFS_INO_TO_AGNO(mp, sc->sm->sm_ino);
1150 	int			error;
1151 
1152 	ASSERT(sc->tp == NULL);
1153 
1154 	/* We want to scan the inode we already had opened. */
1155 	if (sc->sm->sm_ino == 0 || sc->sm->sm_ino == I_INO(ip_in))
1156 		return xchk_install_live_inode(sc, ip_in);
1157 
1158 	/*
1159 	 * On pre-metadir filesystems, reject internal metadata files.  For
1160 	 * metadir filesystems, limited scrubbing of any file in the metadata
1161 	 * directory tree by handle is allowed, because that is the only way to
1162 	 * validate the lack of parent pointers in the sb-root metadata inodes.
1163 	 */
1164 	if (!xfs_has_metadir(mp) && xfs_is_sb_inum(mp, sc->sm->sm_ino))
1165 		return -ENOENT;
1166 	/* Reject obviously bad inode numbers. */
1167 	if (!xfs_verify_ino(sc->mp, sc->sm->sm_ino))
1168 		return -ENOENT;
1169 
1170 	/* Try a safe untrusted iget. */
1171 	error = xchk_iget_safe(sc, sc->sm->sm_ino, &ip);
1172 	if (!error)
1173 		return xchk_install_handle_inode(sc, ip);
1174 	if (error == -ENOENT)
1175 		return error;
1176 	if (error != -EINVAL)
1177 		goto out_error;
1178 
1179 	/*
1180 	 * EINVAL with IGET_UNTRUSTED probably means one of several things:
1181 	 * userspace gave us an inode number that doesn't correspond to fs
1182 	 * space; the inode btree lacks a record for this inode; or there is a
1183 	 * record, and it says this inode is free.
1184 	 *
1185 	 * We want to look up this inode in the inobt to distinguish two
1186 	 * scenarios: (1) the inobt says the inode is free, in which case
1187 	 * there's nothing to do; and (2) the inobt says the inode is
1188 	 * allocated, but loading it failed due to corruption.
1189 	 *
1190 	 * Allocate a transaction and grab the AGI to prevent inobt activity
1191 	 * in this AG.  Retry the iget in case someone allocated a new inode
1192 	 * after the first iget failed.
1193 	 */
1194 	error = xchk_trans_alloc(sc, 0);
1195 	if (error)
1196 		goto out_error;
1197 
1198 	error = xchk_iget_agi(sc, sc->sm->sm_ino, &agi_bp, &ip);
1199 	if (error == 0) {
1200 		/* Actually got the inode, so install it. */
1201 		xchk_trans_cancel(sc);
1202 		return xchk_install_handle_inode(sc, ip);
1203 	}
1204 	if (error == -ENOENT)
1205 		goto out_gone;
1206 	if (error != -EINVAL)
1207 		goto out_cancel;
1208 
1209 	/* Ensure that we have protected against inode allocation/freeing. */
1210 	if (agi_bp == NULL) {
1211 		ASSERT(agi_bp != NULL);
1212 		error = -ECANCELED;
1213 		goto out_cancel;
1214 	}
1215 
1216 	/*
1217 	 * Untrusted iget failed a second time.  Let's try an inobt lookup.
1218 	 * If the inobt thinks this the inode neither can exist inside the
1219 	 * filesystem nor is allocated, return ENOENT to signal that the check
1220 	 * can be skipped.
1221 	 *
1222 	 * If the lookup returns corruption, we'll mark this inode corrupt and
1223 	 * exit to userspace.  There's little chance of fixing anything until
1224 	 * the inobt is straightened out, but there's nothing we can do here.
1225 	 *
1226 	 * If the lookup encounters any other error, exit to userspace.
1227 	 *
1228 	 * If the lookup succeeds, something else must be very wrong in the fs
1229 	 * such that setting up the incore inode failed in some strange way.
1230 	 * Treat those as corruptions.
1231 	 */
1232 	pag = xfs_perag_get(mp, XFS_INO_TO_AGNO(mp, sc->sm->sm_ino));
1233 	if (!pag) {
1234 		error = -EFSCORRUPTED;
1235 		goto out_cancel;
1236 	}
1237 
1238 	error = xfs_imap(pag, sc->tp, sc->sm->sm_ino, &imap,
1239 			XFS_IGET_UNTRUSTED);
1240 	xfs_perag_put(pag);
1241 	if (error == -EINVAL || error == -ENOENT)
1242 		goto out_gone;
1243 	if (!error)
1244 		error = -EFSCORRUPTED;
1245 
1246 out_cancel:
1247 	xchk_trans_cancel(sc);
1248 out_error:
1249 	trace_xchk_op_error(sc, agno, XFS_INO_TO_AGBNO(mp, sc->sm->sm_ino),
1250 			error, __return_address);
1251 	return error;
1252 out_gone:
1253 	/* The file is gone, so there's nothing to check. */
1254 	xchk_trans_cancel(sc);
1255 	return -ENOENT;
1256 }
1257 
1258 /* Release an inode, possibly dropping it in the process. */
1259 void
1260 xchk_irele(
1261 	struct xfs_scrub	*sc,
1262 	struct xfs_inode	*ip)
1263 {
1264 	if (sc->tp) {
1265 		/*
1266 		 * If we are in a transaction, we /cannot/ drop the inode
1267 		 * ourselves, because the VFS will trigger writeback, which
1268 		 * can require a transaction.  Clear DONTCACHE to force the
1269 		 * inode to the LRU, where someone else can take care of
1270 		 * dropping it.
1271 		 *
1272 		 * Note that when we grabbed our reference to the inode, it
1273 		 * could have had an active ref and DONTCACHE set if a sysadmin
1274 		 * is trying to coerce a change in file access mode.  icache
1275 		 * hits do not clear DONTCACHE, so we must do it here.
1276 		 */
1277 		spin_lock(&VFS_I(ip)->i_lock);
1278 		inode_state_clear(VFS_I(ip), I_DONTCACHE);
1279 		spin_unlock(&VFS_I(ip)->i_lock);
1280 	}
1281 
1282 	xfs_irele(ip);
1283 }
1284 
1285 /*
1286  * Set us up to scrub metadata mapped by a file's fork.  Callers must not use
1287  * this to operate on user-accessible regular file data because the MMAPLOCK is
1288  * not taken.
1289  */
1290 int
1291 xchk_setup_inode_contents(
1292 	struct xfs_scrub	*sc,
1293 	unsigned int		resblks)
1294 {
1295 	int			error;
1296 
1297 	error = xchk_iget_for_scrubbing(sc);
1298 	if (error)
1299 		return error;
1300 
1301 	error = xrep_tempfile_adjust_directory_tree(sc);
1302 	if (error)
1303 		return error;
1304 
1305 	/* Lock the inode so the VFS cannot touch this file. */
1306 	xchk_ilock(sc, XFS_IOLOCK_EXCL);
1307 
1308 	error = xchk_trans_alloc(sc, resblks);
1309 	if (error)
1310 		goto out;
1311 
1312 	error = xchk_ino_dqattach(sc);
1313 	if (error)
1314 		goto out;
1315 
1316 	xchk_ilock(sc, XFS_ILOCK_EXCL);
1317 out:
1318 	/* scrub teardown will unlock and release the inode for us */
1319 	return error;
1320 }
1321 
1322 void
1323 xchk_ilock(
1324 	struct xfs_scrub	*sc,
1325 	unsigned int		ilock_flags)
1326 {
1327 	xfs_ilock(sc->ip, ilock_flags);
1328 	sc->ilock_flags |= ilock_flags;
1329 }
1330 
1331 bool
1332 xchk_ilock_nowait(
1333 	struct xfs_scrub	*sc,
1334 	unsigned int		ilock_flags)
1335 {
1336 	if (xfs_ilock_nowait(sc->ip, ilock_flags)) {
1337 		sc->ilock_flags |= ilock_flags;
1338 		return true;
1339 	}
1340 
1341 	return false;
1342 }
1343 
1344 void
1345 xchk_iunlock(
1346 	struct xfs_scrub	*sc,
1347 	unsigned int		ilock_flags)
1348 {
1349 	sc->ilock_flags &= ~ilock_flags;
1350 	xfs_iunlock(sc->ip, ilock_flags);
1351 }
1352 
1353 /*
1354  * Predicate that decides if we need to evaluate the cross-reference check.
1355  * If there was an error accessing the cross-reference btree, just delete
1356  * the cursor and skip the check.
1357  */
1358 bool
1359 xchk_should_check_xref(
1360 	struct xfs_scrub	*sc,
1361 	int			*error,
1362 	struct xfs_btree_cur	**curpp)
1363 {
1364 	/* No point in xref if we already know we're corrupt. */
1365 	if (xchk_skip_xref(sc->sm))
1366 		return false;
1367 
1368 	if (*error == 0)
1369 		return true;
1370 
1371 	if (curpp) {
1372 		/* If we've already given up on xref, just bail out. */
1373 		if (!*curpp)
1374 			return false;
1375 
1376 		/* xref error, delete cursor and bail out. */
1377 		xfs_btree_del_cursor(*curpp, XFS_BTREE_ERROR);
1378 		*curpp = NULL;
1379 	}
1380 
1381 	sc->sm->sm_flags |= XFS_SCRUB_OFLAG_XFAIL;
1382 	trace_xchk_xref_error(sc, *error, __return_address);
1383 
1384 	/*
1385 	 * Errors encountered during cross-referencing with another
1386 	 * data structure should not cause this scrubber to abort.
1387 	 */
1388 	*error = 0;
1389 	return false;
1390 }
1391 
1392 /* Run the structure verifiers on in-memory buffers to detect bad memory. */
1393 void
1394 xchk_buffer_recheck(
1395 	struct xfs_scrub	*sc,
1396 	struct xfs_buf		*bp)
1397 {
1398 	xfs_failaddr_t		fa;
1399 
1400 	if (bp->b_ops == NULL) {
1401 		xchk_block_set_corrupt(sc, bp);
1402 		return;
1403 	}
1404 	if (bp->b_ops->verify_struct == NULL) {
1405 		xchk_set_incomplete(sc);
1406 		return;
1407 	}
1408 	fa = bp->b_ops->verify_struct(bp);
1409 	if (!fa)
1410 		return;
1411 	sc->sm->sm_flags |= XFS_SCRUB_OFLAG_CORRUPT;
1412 	trace_xchk_block_error(sc, xfs_buf_daddr(bp), fa);
1413 }
1414 
1415 static inline int
1416 xchk_metadata_inode_subtype(
1417 	struct xfs_scrub	*sc,
1418 	unsigned int		scrub_type)
1419 {
1420 	struct xfs_scrub_subord	*sub;
1421 	int			error;
1422 
1423 	sub = xchk_scrub_create_subord(sc, scrub_type);
1424 	if (!sub)
1425 		return -ENOMEM;
1426 
1427 	error = sub->sc.ops->scrub(&sub->sc);
1428 	xchk_scrub_free_subord(sub);
1429 	return error;
1430 }
1431 
1432 /*
1433  * Scrub the attr/data forks of a metadata inode.  The metadata inode must be
1434  * pointed to by sc->ip and the ILOCK must be held.
1435  */
1436 int
1437 xchk_metadata_inode_forks(
1438 	struct xfs_scrub	*sc)
1439 {
1440 	bool			shared;
1441 	int			error;
1442 
1443 	if (sc->sm->sm_flags & XFS_SCRUB_OFLAG_CORRUPT)
1444 		return 0;
1445 
1446 	/* Check the inode record. */
1447 	error = xchk_metadata_inode_subtype(sc, XFS_SCRUB_TYPE_INODE);
1448 	if (error || (sc->sm->sm_flags & XFS_SCRUB_OFLAG_CORRUPT))
1449 		return error;
1450 
1451 	/* Metadata inodes don't live on the rt device. */
1452 	if (sc->ip->i_diflags & XFS_DIFLAG_REALTIME) {
1453 		xchk_ip_set_corrupt(sc, sc->ip);
1454 		return 0;
1455 	}
1456 
1457 	/* They should never participate in reflink. */
1458 	if (xfs_is_reflink_inode(sc->ip)) {
1459 		xchk_ip_set_corrupt(sc, sc->ip);
1460 		return 0;
1461 	}
1462 
1463 	/* Invoke the data fork scrubber. */
1464 	error = xchk_metadata_inode_subtype(sc, XFS_SCRUB_TYPE_BMBTD);
1465 	if (error || (sc->sm->sm_flags & XFS_SCRUB_OFLAG_CORRUPT))
1466 		return error;
1467 
1468 	/* Look for incorrect shared blocks. */
1469 	if (xfs_has_reflink(sc->mp)) {
1470 		error = xfs_reflink_inode_has_shared_extents(sc->tp, sc->ip,
1471 				&shared);
1472 		if (!xchk_fblock_process_error(sc, XFS_DATA_FORK, 0,
1473 				&error))
1474 			return error;
1475 		if (shared)
1476 			xchk_ip_set_corrupt(sc, sc->ip);
1477 	}
1478 
1479 	/*
1480 	 * Metadata files can only have extended attributes on metadir
1481 	 * filesystems, either for parent pointers or for actual xattr data.
1482 	 */
1483 	if (xfs_inode_hasattr(sc->ip)) {
1484 		if (!xfs_has_metadir(sc->mp)) {
1485 			xchk_ip_set_corrupt(sc, sc->ip);
1486 			return 0;
1487 		}
1488 
1489 		error = xchk_metadata_inode_subtype(sc, XFS_SCRUB_TYPE_BMBTA);
1490 		if (error || (sc->sm->sm_flags & XFS_SCRUB_OFLAG_CORRUPT))
1491 			return error;
1492 	}
1493 
1494 	return 0;
1495 }
1496 
1497 /*
1498  * Enable filesystem hooks (i.e. runtime code patching) before starting a scrub
1499  * operation.  Callers must not hold any locks that intersect with the CPU
1500  * hotplug lock (e.g. writeback locks) because code patching must halt the CPUs
1501  * to change kernel code.
1502  */
1503 void
1504 xchk_fsgates_enable(
1505 	struct xfs_scrub	*sc,
1506 	unsigned int		scrub_fsgates)
1507 {
1508 	ASSERT(!(scrub_fsgates & ~XCHK_FSGATES_ALL));
1509 	ASSERT(!(sc->flags & scrub_fsgates));
1510 
1511 	trace_xchk_fsgates_enable(sc, scrub_fsgates);
1512 
1513 	if (scrub_fsgates & XCHK_FSGATES_DRAIN)
1514 		xfs_defer_drain_wait_enable();
1515 
1516 	if (scrub_fsgates & XCHK_FSGATES_QUOTA)
1517 		xfs_dqtrx_hook_enable();
1518 
1519 	if (scrub_fsgates & XCHK_FSGATES_DIRENTS)
1520 		xfs_dir_hook_enable();
1521 
1522 	if (scrub_fsgates & XCHK_FSGATES_RMAP)
1523 		xfs_rmap_hook_enable();
1524 
1525 	sc->flags |= scrub_fsgates;
1526 }
1527 
1528 /*
1529  * Decide if this is this a cached inode that's also allocated.  The caller
1530  * must hold a reference to an AG and the AGI buffer lock to prevent inodes
1531  * from being allocated or freed.
1532  *
1533  * Look up an inode by number in the given file system.  If the inode number
1534  * is invalid, return -EINVAL.  If the inode is not in cache, return -ENODATA.
1535  * If the inode is being reclaimed, return -ENODATA because we know the inode
1536  * cache cannot be updating the ondisk metadata.
1537  *
1538  * Otherwise, the incore inode is the one we want, and it is either live,
1539  * somewhere in the inactivation machinery, or reclaimable.  The inode is
1540  * allocated if i_mode is nonzero.  In all three cases, the cached inode will
1541  * be more up to date than the ondisk inode buffer, so we must use the incore
1542  * i_mode.
1543  */
1544 int
1545 xchk_inode_is_allocated(
1546 	struct xfs_scrub	*sc,
1547 	xfs_agino_t		agino,
1548 	bool			*inuse)
1549 {
1550 	struct xfs_mount	*mp = sc->mp;
1551 	struct xfs_perag	*pag = sc->sa.pag;
1552 	xfs_ino_t		ino;
1553 	struct xfs_inode	*ip;
1554 	int			error;
1555 
1556 	/* caller must hold perag reference */
1557 	if (pag == NULL) {
1558 		ASSERT(pag != NULL);
1559 		return -EINVAL;
1560 	}
1561 
1562 	/* caller must have AGI buffer */
1563 	if (sc->sa.agi_bp == NULL) {
1564 		ASSERT(sc->sa.agi_bp != NULL);
1565 		return -EINVAL;
1566 	}
1567 
1568 	/* reject inode numbers outside existing AGs */
1569 	ino = xfs_agino_to_ino(pag, agino);
1570 	if (!xfs_verify_ino(mp, ino))
1571 		return -EINVAL;
1572 
1573 	error = -ENODATA;
1574 	rcu_read_lock();
1575 	ip = radix_tree_lookup(&pag->pag_ici_root, agino);
1576 	if (!ip) {
1577 		/* cache miss */
1578 		goto out_rcu;
1579 	}
1580 
1581 	/*
1582 	 * If the inode number doesn't match, the incore inode got reused
1583 	 * during an RCU grace period and the radix tree hasn't been updated.
1584 	 * This isn't the inode we want.
1585 	 */
1586 	spin_lock(&ip->i_flags_lock);
1587 	if (I_INO(ip) != ino)
1588 		goto out_skip;
1589 
1590 	trace_xchk_inode_is_allocated(ip);
1591 
1592 	/*
1593 	 * We have an incore inode that matches the inode we want, and the
1594 	 * caller holds the perag structure and the AGI buffer.  Let's check
1595 	 * our assumptions below:
1596 	 */
1597 
1598 #ifdef DEBUG
1599 	/*
1600 	 * (1) If the incore inode is live (i.e. referenced from the dcache),
1601 	 * it will not be INEW, nor will it be in the inactivation or reclaim
1602 	 * machinery.  The ondisk inode had better be allocated.  This is the
1603 	 * most trivial case.
1604 	 */
1605 	if (!(ip->i_flags & (XFS_NEED_INACTIVE | XFS_INEW | XFS_IRECLAIMABLE |
1606 			     XFS_INACTIVATING))) {
1607 		/* live inode */
1608 		ASSERT(VFS_I(ip)->i_mode != 0);
1609 	}
1610 
1611 	/*
1612 	 * If the incore inode is INEW, there are several possibilities:
1613 	 *
1614 	 * (2) For a file that is being created, note that we allocate the
1615 	 * ondisk inode before allocating, initializing, and adding the incore
1616 	 * inode to the radix tree.
1617 	 *
1618 	 * (3) If the incore inode is being recycled, the inode has to be
1619 	 * allocated because we don't allow freed inodes to be recycled.
1620 	 * Recycling doesn't touch i_mode.
1621 	 */
1622 	if (ip->i_flags & XFS_INEW) {
1623 		/* created on disk already or recycling */
1624 		ASSERT(VFS_I(ip)->i_mode != 0);
1625 	}
1626 
1627 	/*
1628 	 * (4) If the inode is queued for inactivation (NEED_INACTIVE) but
1629 	 * inactivation has not started (!INACTIVATING), it is still allocated.
1630 	 */
1631 	if ((ip->i_flags & XFS_NEED_INACTIVE) &&
1632 	    !(ip->i_flags & XFS_INACTIVATING)) {
1633 		/* definitely before difree */
1634 		ASSERT(VFS_I(ip)->i_mode != 0);
1635 	}
1636 #endif
1637 
1638 	/*
1639 	 * If the incore inode is undergoing inactivation (INACTIVATING), there
1640 	 * are two possibilities:
1641 	 *
1642 	 * (5) It is before the point where it would get freed ondisk, in which
1643 	 * case i_mode is still nonzero.
1644 	 *
1645 	 * (6) It has already been freed, in which case i_mode is zero.
1646 	 *
1647 	 * We don't take the ILOCK here, but difree and dialloc update the AGI,
1648 	 * and we've taken the AGI buffer lock, which prevents that from
1649 	 * happening.
1650 	 */
1651 
1652 	/*
1653 	 * (7) Inodes undergoing inactivation (INACTIVATING) or queued for
1654 	 * reclaim (IRECLAIMABLE) could be allocated or free.  i_mode still
1655 	 * reflects the ondisk state.
1656 	 */
1657 
1658 	/*
1659 	 * (8) If the inode is in IFLUSHING, it's safe to query i_mode because
1660 	 * the flush code uses i_mode to format the ondisk inode.
1661 	 */
1662 
1663 	/*
1664 	 * (9) If the inode is in IRECLAIM and was reachable via the radix
1665 	 * tree, it still has the same i_mode as it did before it entered
1666 	 * reclaim.  The inode object is still alive because we hold the RCU
1667 	 * read lock.
1668 	 */
1669 
1670 	*inuse = VFS_I(ip)->i_mode != 0;
1671 	error = 0;
1672 
1673 out_skip:
1674 	spin_unlock(&ip->i_flags_lock);
1675 out_rcu:
1676 	rcu_read_unlock();
1677 	return error;
1678 }
1679 
1680 /* Is this inode a root directory for either tree? */
1681 bool
1682 xchk_inode_is_dirtree_root(const struct xfs_inode *ip)
1683 {
1684 	struct xfs_mount	*mp = ip->i_mount;
1685 
1686 	return ip == mp->m_rootip ||
1687 		(xfs_has_metadir(mp) && ip == mp->m_metadirip);
1688 }
1689 
1690 /* Does the superblock point down to this inode? */
1691 bool
1692 xchk_inode_is_sb_rooted(const struct xfs_inode *ip)
1693 {
1694 	return xchk_inode_is_dirtree_root(ip) ||
1695 	       xfs_is_sb_inum(ip->i_mount, I_INO(ip));
1696 }
1697 
1698 /* What is the root directory inumber for this inode? */
1699 xfs_ino_t
1700 xchk_inode_rootdir_inum(const struct xfs_inode *ip)
1701 {
1702 	struct xfs_mount	*mp = ip->i_mount;
1703 
1704 	if (xfs_is_metadir_inode(ip))
1705 		return I_INO(mp->m_metadirip);
1706 	return I_INO(mp->m_rootip);
1707 }
1708 
1709 static int
1710 xchk_meta_btree_count_blocks(
1711 	struct xfs_scrub	*sc,
1712 	xfs_extnum_t		*nextents,
1713 	xfs_filblks_t		*count)
1714 {
1715 	struct xfs_btree_cur	*cur;
1716 	int			error;
1717 
1718 	if (!sc->sr.rtg) {
1719 		ASSERT(0);
1720 		return -EFSCORRUPTED;
1721 	}
1722 
1723 	switch (sc->ip->i_metatype) {
1724 	case XFS_METAFILE_RTRMAP:
1725 		cur = xfs_rtrmapbt_init_cursor(sc->tp, sc->sr.rtg);
1726 		break;
1727 	case XFS_METAFILE_RTREFCOUNT:
1728 		cur = xfs_rtrefcountbt_init_cursor(sc->tp, sc->sr.rtg);
1729 		break;
1730 	default:
1731 		ASSERT(0);
1732 		return -EFSCORRUPTED;
1733 	}
1734 
1735 	error = xfs_btree_count_blocks(cur, count);
1736 	xfs_btree_del_cursor(cur, error);
1737 	if (!error) {
1738 		*nextents = 0;
1739 		(*count)--;	/* don't count the btree iroot */
1740 	}
1741 	return error;
1742 }
1743 
1744 /* Count the blocks used by a file, even if it's a metadata inode. */
1745 int
1746 xchk_inode_count_blocks(
1747 	struct xfs_scrub	*sc,
1748 	int			whichfork,
1749 	xfs_extnum_t		*nextents,
1750 	xfs_filblks_t		*count)
1751 {
1752 	struct xfs_ifork	*ifp = xfs_ifork_ptr(sc->ip, whichfork);
1753 
1754 	if (!ifp) {
1755 		*nextents = 0;
1756 		*count = 0;
1757 		return 0;
1758 	}
1759 
1760 	if (ifp->if_format == XFS_DINODE_FMT_META_BTREE) {
1761 		ASSERT(whichfork == XFS_DATA_FORK);
1762 		return xchk_meta_btree_count_blocks(sc, nextents, count);
1763 	}
1764 
1765 	return xfs_bmap_count_blocks(sc->tp, sc->ip, whichfork, nextents,
1766 			count);
1767 }
1768