• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.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_log_format.h"
13 #include "xfs_trans.h"
14 #include "xfs_inode.h"
15 #include "xfs_quota.h"
16 #include "xfs_qm.h"
17 #include "xfs_scrub.h"
18 #include "xfs_buf_mem.h"
19 #include "xfs_rmap.h"
20 #include "xfs_exchrange.h"
21 #include "xfs_exchmaps.h"
22 #include "xfs_dir2.h"
23 #include "xfs_parent.h"
24 #include "xfs_icache.h"
25 #include "scrub/scrub.h"
26 #include "scrub/common.h"
27 #include "scrub/trace.h"
28 #include "scrub/repair.h"
29 #include "scrub/health.h"
30 #include "scrub/stats.h"
31 #include "scrub/xfile.h"
32 #include "scrub/tempfile.h"
33 #include "scrub/orphanage.h"
34 
35 /*
36  * Online Scrub and Repair
37  *
38  * Traditionally, XFS (the kernel driver) did not know how to check or
39  * repair on-disk data structures.  That task was left to the xfs_check
40  * and xfs_repair tools, both of which require taking the filesystem
41  * offline for a thorough but time consuming examination.  Online
42  * scrub & repair, on the other hand, enables us to check the metadata
43  * for obvious errors while carefully stepping around the filesystem's
44  * ongoing operations, locking rules, etc.
45  *
46  * Given that most XFS metadata consist of records stored in a btree,
47  * most of the checking functions iterate the btree blocks themselves
48  * looking for irregularities.  When a record block is encountered, each
49  * record can be checked for obviously bad values.  Record values can
50  * also be cross-referenced against other btrees to look for potential
51  * misunderstandings between pieces of metadata.
52  *
53  * It is expected that the checkers responsible for per-AG metadata
54  * structures will lock the AG headers (AGI, AGF, AGFL), iterate the
55  * metadata structure, and perform any relevant cross-referencing before
56  * unlocking the AG and returning the results to userspace.  These
57  * scrubbers must not keep an AG locked for too long to avoid tying up
58  * the block and inode allocators.
59  *
60  * Block maps and b-trees rooted in an inode present a special challenge
61  * because they can involve extents from any AG.  The general scrubber
62  * structure of lock -> check -> xref -> unlock still holds, but AG
63  * locking order rules /must/ be obeyed to avoid deadlocks.  The
64  * ordering rule, of course, is that we must lock in increasing AG
65  * order.  Helper functions are provided to track which AG headers we've
66  * already locked.  If we detect an imminent locking order violation, we
67  * can signal a potential deadlock, in which case the scrubber can jump
68  * out to the top level, lock all the AGs in order, and retry the scrub.
69  *
70  * For file data (directories, extended attributes, symlinks) scrub, we
71  * can simply lock the inode and walk the data.  For btree data
72  * (directories and attributes) we follow the same btree-scrubbing
73  * strategy outlined previously to check the records.
74  *
75  * We use a bit of trickery with transactions to avoid buffer deadlocks
76  * if there is a cycle in the metadata.  The basic problem is that
77  * travelling down a btree involves locking the current buffer at each
78  * tree level.  If a pointer should somehow point back to a buffer that
79  * we've already examined, we will deadlock due to the second buffer
80  * locking attempt.  Note however that grabbing a buffer in transaction
81  * context links the locked buffer to the transaction.  If we try to
82  * re-grab the buffer in the context of the same transaction, we avoid
83  * the second lock attempt and continue.  Between the verifier and the
84  * scrubber, something will notice that something is amiss and report
85  * the corruption.  Therefore, each scrubber will allocate an empty
86  * transaction, attach buffers to it, and cancel the transaction at the
87  * end of the scrub run.  Cancelling a non-dirty transaction simply
88  * unlocks the buffers.
89  *
90  * There are four pieces of data that scrub can communicate to
91  * userspace.  The first is the error code (errno), which can be used to
92  * communicate operational errors in performing the scrub.  There are
93  * also three flags that can be set in the scrub context.  If the data
94  * structure itself is corrupt, the CORRUPT flag will be set.  If
95  * the metadata is correct but otherwise suboptimal, the PREEN flag
96  * will be set.
97  *
98  * We perform secondary validation of filesystem metadata by
99  * cross-referencing every record with all other available metadata.
100  * For example, for block mapping extents, we verify that there are no
101  * records in the free space and inode btrees corresponding to that
102  * space extent and that there is a corresponding entry in the reverse
103  * mapping btree.  Inconsistent metadata is noted by setting the
104  * XCORRUPT flag; btree query function errors are noted by setting the
105  * XFAIL flag and deleting the cursor to prevent further attempts to
106  * cross-reference with a defective btree.
107  *
108  * If a piece of metadata proves corrupt or suboptimal, the userspace
109  * program can ask the kernel to apply some tender loving care (TLC) to
110  * the metadata object by setting the REPAIR flag and re-calling the
111  * scrub ioctl.  "Corruption" is defined by metadata violating the
112  * on-disk specification; operations cannot continue if the violation is
113  * left untreated.  It is possible for XFS to continue if an object is
114  * "suboptimal", however performance may be degraded.  Repairs are
115  * usually performed by rebuilding the metadata entirely out of
116  * redundant metadata.  Optimizing, on the other hand, can sometimes be
117  * done without rebuilding entire structures.
118  *
119  * Generally speaking, the repair code has the following code structure:
120  * Lock -> scrub -> repair -> commit -> re-lock -> re-scrub -> unlock.
121  * The first check helps us figure out if we need to rebuild or simply
122  * optimize the structure so that the rebuild knows what to do.  The
123  * second check evaluates the completeness of the repair; that is what
124  * is reported to userspace.
125  *
126  * A quick note on symbol prefixes:
127  * - "xfs_" are general XFS symbols.
128  * - "xchk_" are symbols related to metadata checking.
129  * - "xrep_" are symbols related to metadata repair.
130  * - "xfs_scrub_" are symbols that tie online fsck to the rest of XFS.
131  */
132 
133 /*
134  * Scrub probe -- userspace uses this to probe if we're willing to scrub
135  * or repair a given mountpoint.  This will be used by xfs_scrub to
136  * probe the kernel's abilities to scrub (and repair) the metadata.  We
137  * do this by validating the ioctl inputs from userspace, preparing the
138  * filesystem for a scrub (or a repair) operation, and immediately
139  * returning to userspace.  Userspace can use the returned errno and
140  * structure state to decide (in broad terms) if scrub/repair are
141  * supported by the running kernel.
142  */
143 static int
xchk_probe(struct xfs_scrub * sc)144 xchk_probe(
145 	struct xfs_scrub	*sc)
146 {
147 	int			error = 0;
148 
149 	if (xchk_should_terminate(sc, &error))
150 		return error;
151 
152 	/*
153 	 * If the caller is probing to see if repair works but repair isn't
154 	 * built into the kernel, return EOPNOTSUPP because that's the signal
155 	 * that userspace expects.  If online repair is built in, set the
156 	 * CORRUPT flag (without any of the usual tracing/logging) to force us
157 	 * into xrep_probe.
158 	 */
159 	if (xchk_could_repair(sc)) {
160 		if (!IS_ENABLED(CONFIG_XFS_ONLINE_REPAIR))
161 			return -EOPNOTSUPP;
162 		sc->sm->sm_flags |= XFS_SCRUB_OFLAG_CORRUPT;
163 	}
164 	return 0;
165 }
166 
167 /* Scrub setup and teardown */
168 
169 static inline void
xchk_fsgates_disable(struct xfs_scrub * sc)170 xchk_fsgates_disable(
171 	struct xfs_scrub	*sc)
172 {
173 	if (!(sc->flags & XCHK_FSGATES_ALL))
174 		return;
175 
176 	trace_xchk_fsgates_disable(sc, sc->flags & XCHK_FSGATES_ALL);
177 
178 	if (sc->flags & XCHK_FSGATES_DRAIN)
179 		xfs_drain_wait_disable();
180 
181 	if (sc->flags & XCHK_FSGATES_QUOTA)
182 		xfs_dqtrx_hook_disable();
183 
184 	if (sc->flags & XCHK_FSGATES_DIRENTS)
185 		xfs_dir_hook_disable();
186 
187 	if (sc->flags & XCHK_FSGATES_RMAP)
188 		xfs_rmap_hook_disable();
189 
190 	sc->flags &= ~XCHK_FSGATES_ALL;
191 }
192 
193 /* Free the resources associated with a scrub subtype. */
194 void
xchk_scrub_free_subord(struct xfs_scrub_subord * sub)195 xchk_scrub_free_subord(
196 	struct xfs_scrub_subord	*sub)
197 {
198 	struct xfs_scrub	*sc = sub->parent_sc;
199 
200 	ASSERT(sc->ip == sub->sc.ip);
201 	ASSERT(sc->orphanage == sub->sc.orphanage);
202 	ASSERT(sc->tempip == sub->sc.tempip);
203 
204 	sc->sm->sm_type = sub->old_smtype;
205 	sc->sm->sm_flags = sub->old_smflags |
206 				(sc->sm->sm_flags & XFS_SCRUB_FLAGS_OUT);
207 	sc->tp = sub->sc.tp;
208 
209 	if (sub->sc.buf) {
210 		if (sub->sc.buf_cleanup)
211 			sub->sc.buf_cleanup(sub->sc.buf);
212 		kvfree(sub->sc.buf);
213 	}
214 	if (sub->sc.xmbtp)
215 		xmbuf_free(sub->sc.xmbtp);
216 	if (sub->sc.xfile)
217 		xfile_destroy(sub->sc.xfile);
218 
219 	sc->ilock_flags = sub->sc.ilock_flags;
220 	sc->orphanage_ilock_flags = sub->sc.orphanage_ilock_flags;
221 	sc->temp_ilock_flags = sub->sc.temp_ilock_flags;
222 
223 	kfree(sub);
224 }
225 
226 /* Free all the resources and finish the transactions. */
227 STATIC int
xchk_teardown(struct xfs_scrub * sc,int error)228 xchk_teardown(
229 	struct xfs_scrub	*sc,
230 	int			error)
231 {
232 	xchk_ag_free(sc, &sc->sa);
233 	if (sc->tp) {
234 		if (error == 0 && (sc->sm->sm_flags & XFS_SCRUB_IFLAG_REPAIR))
235 			error = xfs_trans_commit(sc->tp);
236 		else
237 			xfs_trans_cancel(sc->tp);
238 		sc->tp = NULL;
239 	}
240 	if (sc->ip) {
241 		if (sc->ilock_flags)
242 			xchk_iunlock(sc, sc->ilock_flags);
243 		xchk_irele(sc, sc->ip);
244 		sc->ip = NULL;
245 	}
246 	if (sc->flags & XCHK_HAVE_FREEZE_PROT) {
247 		sc->flags &= ~XCHK_HAVE_FREEZE_PROT;
248 		mnt_drop_write_file(sc->file);
249 	}
250 	if (sc->xmbtp) {
251 		xmbuf_free(sc->xmbtp);
252 		sc->xmbtp = NULL;
253 	}
254 	if (sc->xfile) {
255 		xfile_destroy(sc->xfile);
256 		sc->xfile = NULL;
257 	}
258 	if (sc->buf) {
259 		if (sc->buf_cleanup)
260 			sc->buf_cleanup(sc->buf);
261 		kvfree(sc->buf);
262 		sc->buf_cleanup = NULL;
263 		sc->buf = NULL;
264 	}
265 
266 	xrep_tempfile_rele(sc);
267 	xrep_orphanage_rele(sc);
268 	xchk_fsgates_disable(sc);
269 	return error;
270 }
271 
272 /* Scrubbing dispatch. */
273 
274 static const struct xchk_meta_ops meta_scrub_ops[] = {
275 	[XFS_SCRUB_TYPE_PROBE] = {	/* ioctl presence test */
276 		.type	= ST_NONE,
277 		.setup	= xchk_setup_fs,
278 		.scrub	= xchk_probe,
279 		.repair = xrep_probe,
280 	},
281 	[XFS_SCRUB_TYPE_SB] = {		/* superblock */
282 		.type	= ST_PERAG,
283 		.setup	= xchk_setup_agheader,
284 		.scrub	= xchk_superblock,
285 		.repair	= xrep_superblock,
286 	},
287 	[XFS_SCRUB_TYPE_AGF] = {	/* agf */
288 		.type	= ST_PERAG,
289 		.setup	= xchk_setup_agheader,
290 		.scrub	= xchk_agf,
291 		.repair	= xrep_agf,
292 	},
293 	[XFS_SCRUB_TYPE_AGFL]= {	/* agfl */
294 		.type	= ST_PERAG,
295 		.setup	= xchk_setup_agheader,
296 		.scrub	= xchk_agfl,
297 		.repair	= xrep_agfl,
298 	},
299 	[XFS_SCRUB_TYPE_AGI] = {	/* agi */
300 		.type	= ST_PERAG,
301 		.setup	= xchk_setup_agheader,
302 		.scrub	= xchk_agi,
303 		.repair	= xrep_agi,
304 	},
305 	[XFS_SCRUB_TYPE_BNOBT] = {	/* bnobt */
306 		.type	= ST_PERAG,
307 		.setup	= xchk_setup_ag_allocbt,
308 		.scrub	= xchk_allocbt,
309 		.repair	= xrep_allocbt,
310 		.repair_eval = xrep_revalidate_allocbt,
311 	},
312 	[XFS_SCRUB_TYPE_CNTBT] = {	/* cntbt */
313 		.type	= ST_PERAG,
314 		.setup	= xchk_setup_ag_allocbt,
315 		.scrub	= xchk_allocbt,
316 		.repair	= xrep_allocbt,
317 		.repair_eval = xrep_revalidate_allocbt,
318 	},
319 	[XFS_SCRUB_TYPE_INOBT] = {	/* inobt */
320 		.type	= ST_PERAG,
321 		.setup	= xchk_setup_ag_iallocbt,
322 		.scrub	= xchk_iallocbt,
323 		.repair	= xrep_iallocbt,
324 		.repair_eval = xrep_revalidate_iallocbt,
325 	},
326 	[XFS_SCRUB_TYPE_FINOBT] = {	/* finobt */
327 		.type	= ST_PERAG,
328 		.setup	= xchk_setup_ag_iallocbt,
329 		.scrub	= xchk_iallocbt,
330 		.has	= xfs_has_finobt,
331 		.repair	= xrep_iallocbt,
332 		.repair_eval = xrep_revalidate_iallocbt,
333 	},
334 	[XFS_SCRUB_TYPE_RMAPBT] = {	/* rmapbt */
335 		.type	= ST_PERAG,
336 		.setup	= xchk_setup_ag_rmapbt,
337 		.scrub	= xchk_rmapbt,
338 		.has	= xfs_has_rmapbt,
339 		.repair	= xrep_rmapbt,
340 	},
341 	[XFS_SCRUB_TYPE_REFCNTBT] = {	/* refcountbt */
342 		.type	= ST_PERAG,
343 		.setup	= xchk_setup_ag_refcountbt,
344 		.scrub	= xchk_refcountbt,
345 		.has	= xfs_has_reflink,
346 		.repair	= xrep_refcountbt,
347 	},
348 	[XFS_SCRUB_TYPE_INODE] = {	/* inode record */
349 		.type	= ST_INODE,
350 		.setup	= xchk_setup_inode,
351 		.scrub	= xchk_inode,
352 		.repair	= xrep_inode,
353 	},
354 	[XFS_SCRUB_TYPE_BMBTD] = {	/* inode data fork */
355 		.type	= ST_INODE,
356 		.setup	= xchk_setup_inode_bmap,
357 		.scrub	= xchk_bmap_data,
358 		.repair	= xrep_bmap_data,
359 	},
360 	[XFS_SCRUB_TYPE_BMBTA] = {	/* inode attr fork */
361 		.type	= ST_INODE,
362 		.setup	= xchk_setup_inode_bmap,
363 		.scrub	= xchk_bmap_attr,
364 		.repair	= xrep_bmap_attr,
365 	},
366 	[XFS_SCRUB_TYPE_BMBTC] = {	/* inode CoW fork */
367 		.type	= ST_INODE,
368 		.setup	= xchk_setup_inode_bmap,
369 		.scrub	= xchk_bmap_cow,
370 		.repair	= xrep_bmap_cow,
371 	},
372 	[XFS_SCRUB_TYPE_DIR] = {	/* directory */
373 		.type	= ST_INODE,
374 		.setup	= xchk_setup_directory,
375 		.scrub	= xchk_directory,
376 		.repair	= xrep_directory,
377 	},
378 	[XFS_SCRUB_TYPE_XATTR] = {	/* extended attributes */
379 		.type	= ST_INODE,
380 		.setup	= xchk_setup_xattr,
381 		.scrub	= xchk_xattr,
382 		.repair	= xrep_xattr,
383 	},
384 	[XFS_SCRUB_TYPE_SYMLINK] = {	/* symbolic link */
385 		.type	= ST_INODE,
386 		.setup	= xchk_setup_symlink,
387 		.scrub	= xchk_symlink,
388 		.repair	= xrep_symlink,
389 	},
390 	[XFS_SCRUB_TYPE_PARENT] = {	/* parent pointers */
391 		.type	= ST_INODE,
392 		.setup	= xchk_setup_parent,
393 		.scrub	= xchk_parent,
394 		.repair	= xrep_parent,
395 	},
396 	[XFS_SCRUB_TYPE_RTBITMAP] = {	/* realtime bitmap */
397 		.type	= ST_FS,
398 		.setup	= xchk_setup_rtbitmap,
399 		.scrub	= xchk_rtbitmap,
400 		.repair	= xrep_rtbitmap,
401 	},
402 	[XFS_SCRUB_TYPE_RTSUM] = {	/* realtime summary */
403 		.type	= ST_FS,
404 		.setup	= xchk_setup_rtsummary,
405 		.scrub	= xchk_rtsummary,
406 		.repair	= xrep_rtsummary,
407 	},
408 	[XFS_SCRUB_TYPE_UQUOTA] = {	/* user quota */
409 		.type	= ST_FS,
410 		.setup	= xchk_setup_quota,
411 		.scrub	= xchk_quota,
412 		.repair	= xrep_quota,
413 	},
414 	[XFS_SCRUB_TYPE_GQUOTA] = {	/* group quota */
415 		.type	= ST_FS,
416 		.setup	= xchk_setup_quota,
417 		.scrub	= xchk_quota,
418 		.repair	= xrep_quota,
419 	},
420 	[XFS_SCRUB_TYPE_PQUOTA] = {	/* project quota */
421 		.type	= ST_FS,
422 		.setup	= xchk_setup_quota,
423 		.scrub	= xchk_quota,
424 		.repair	= xrep_quota,
425 	},
426 	[XFS_SCRUB_TYPE_FSCOUNTERS] = {	/* fs summary counters */
427 		.type	= ST_FS,
428 		.setup	= xchk_setup_fscounters,
429 		.scrub	= xchk_fscounters,
430 		.repair	= xrep_fscounters,
431 	},
432 	[XFS_SCRUB_TYPE_QUOTACHECK] = {	/* quota counters */
433 		.type	= ST_FS,
434 		.setup	= xchk_setup_quotacheck,
435 		.scrub	= xchk_quotacheck,
436 		.repair	= xrep_quotacheck,
437 	},
438 	[XFS_SCRUB_TYPE_NLINKS] = {	/* inode link counts */
439 		.type	= ST_FS,
440 		.setup	= xchk_setup_nlinks,
441 		.scrub	= xchk_nlinks,
442 		.repair	= xrep_nlinks,
443 	},
444 	[XFS_SCRUB_TYPE_HEALTHY] = {	/* fs healthy; clean all reminders */
445 		.type	= ST_FS,
446 		.setup	= xchk_setup_fs,
447 		.scrub	= xchk_health_record,
448 		.repair = xrep_notsupported,
449 	},
450 	[XFS_SCRUB_TYPE_DIRTREE] = {	/* directory tree structure */
451 		.type	= ST_INODE,
452 		.setup	= xchk_setup_dirtree,
453 		.scrub	= xchk_dirtree,
454 		.has	= xfs_has_parent,
455 		.repair	= xrep_dirtree,
456 	},
457 };
458 
459 static int
xchk_validate_inputs(struct xfs_mount * mp,struct xfs_scrub_metadata * sm)460 xchk_validate_inputs(
461 	struct xfs_mount		*mp,
462 	struct xfs_scrub_metadata	*sm)
463 {
464 	int				error;
465 	const struct xchk_meta_ops	*ops;
466 
467 	error = -EINVAL;
468 	/* Check our inputs. */
469 	sm->sm_flags &= ~XFS_SCRUB_FLAGS_OUT;
470 	if (sm->sm_flags & ~XFS_SCRUB_FLAGS_IN)
471 		goto out;
472 	/* sm_reserved[] must be zero */
473 	if (memchr_inv(sm->sm_reserved, 0, sizeof(sm->sm_reserved)))
474 		goto out;
475 
476 	error = -ENOENT;
477 	/* Do we know about this type of metadata? */
478 	if (sm->sm_type >= XFS_SCRUB_TYPE_NR)
479 		goto out;
480 	ops = &meta_scrub_ops[sm->sm_type];
481 	if (ops->setup == NULL || ops->scrub == NULL)
482 		goto out;
483 	/* Does this fs even support this type of metadata? */
484 	if (ops->has && !ops->has(mp))
485 		goto out;
486 
487 	error = -EINVAL;
488 	/* restricting fields must be appropriate for type */
489 	switch (ops->type) {
490 	case ST_NONE:
491 	case ST_FS:
492 		if (sm->sm_ino || sm->sm_gen || sm->sm_agno)
493 			goto out;
494 		break;
495 	case ST_PERAG:
496 		if (sm->sm_ino || sm->sm_gen ||
497 		    sm->sm_agno >= mp->m_sb.sb_agcount)
498 			goto out;
499 		break;
500 	case ST_INODE:
501 		if (sm->sm_agno || (sm->sm_gen && !sm->sm_ino))
502 			goto out;
503 		break;
504 	default:
505 		goto out;
506 	}
507 
508 	/* No rebuild without repair. */
509 	if ((sm->sm_flags & XFS_SCRUB_IFLAG_FORCE_REBUILD) &&
510 	    !(sm->sm_flags & XFS_SCRUB_IFLAG_REPAIR))
511 		return -EINVAL;
512 
513 	/*
514 	 * We only want to repair read-write v5+ filesystems.  Defer the check
515 	 * for ops->repair until after our scrub confirms that we need to
516 	 * perform repairs so that we avoid failing due to not supporting
517 	 * repairing an object that doesn't need repairs.
518 	 */
519 	if (sm->sm_flags & XFS_SCRUB_IFLAG_REPAIR) {
520 		error = -EOPNOTSUPP;
521 		if (!xfs_has_crc(mp))
522 			goto out;
523 
524 		error = -EROFS;
525 		if (xfs_is_readonly(mp))
526 			goto out;
527 	}
528 
529 	error = 0;
530 out:
531 	return error;
532 }
533 
534 #ifdef CONFIG_XFS_ONLINE_REPAIR
xchk_postmortem(struct xfs_scrub * sc)535 static inline void xchk_postmortem(struct xfs_scrub *sc)
536 {
537 	/*
538 	 * Userspace asked us to repair something, we repaired it, rescanned
539 	 * it, and the rescan says it's still broken.  Scream about this in
540 	 * the system logs.
541 	 */
542 	if ((sc->sm->sm_flags & XFS_SCRUB_IFLAG_REPAIR) &&
543 	    (sc->sm->sm_flags & (XFS_SCRUB_OFLAG_CORRUPT |
544 				 XFS_SCRUB_OFLAG_XCORRUPT)))
545 		xrep_failure(sc->mp);
546 }
547 #else
xchk_postmortem(struct xfs_scrub * sc)548 static inline void xchk_postmortem(struct xfs_scrub *sc)
549 {
550 	/*
551 	 * Userspace asked us to scrub something, it's broken, and we have no
552 	 * way of fixing it.  Scream in the logs.
553 	 */
554 	if (sc->sm->sm_flags & (XFS_SCRUB_OFLAG_CORRUPT |
555 				XFS_SCRUB_OFLAG_XCORRUPT))
556 		xfs_alert_ratelimited(sc->mp,
557 				"Corruption detected during scrub.");
558 }
559 #endif /* CONFIG_XFS_ONLINE_REPAIR */
560 
561 /*
562  * Create a new scrub context from an existing one, but with a different scrub
563  * type.
564  */
565 struct xfs_scrub_subord *
xchk_scrub_create_subord(struct xfs_scrub * sc,unsigned int subtype)566 xchk_scrub_create_subord(
567 	struct xfs_scrub	*sc,
568 	unsigned int		subtype)
569 {
570 	struct xfs_scrub_subord	*sub;
571 
572 	sub = kzalloc(sizeof(*sub), XCHK_GFP_FLAGS);
573 	if (!sub)
574 		return ERR_PTR(-ENOMEM);
575 
576 	sub->old_smtype = sc->sm->sm_type;
577 	sub->old_smflags = sc->sm->sm_flags;
578 	sub->parent_sc = sc;
579 	memcpy(&sub->sc, sc, sizeof(struct xfs_scrub));
580 	sub->sc.ops = &meta_scrub_ops[subtype];
581 	sub->sc.sm->sm_type = subtype;
582 	sub->sc.sm->sm_flags &= ~XFS_SCRUB_FLAGS_OUT;
583 	sub->sc.buf = NULL;
584 	sub->sc.buf_cleanup = NULL;
585 	sub->sc.xfile = NULL;
586 	sub->sc.xmbtp = NULL;
587 
588 	return sub;
589 }
590 
591 /* Dispatch metadata scrubbing. */
592 STATIC int
xfs_scrub_metadata(struct file * file,struct xfs_scrub_metadata * sm)593 xfs_scrub_metadata(
594 	struct file			*file,
595 	struct xfs_scrub_metadata	*sm)
596 {
597 	struct xchk_stats_run		run = { };
598 	struct xfs_scrub		*sc;
599 	struct xfs_mount		*mp = XFS_I(file_inode(file))->i_mount;
600 	u64				check_start;
601 	int				error = 0;
602 
603 	BUILD_BUG_ON(sizeof(meta_scrub_ops) !=
604 		(sizeof(struct xchk_meta_ops) * XFS_SCRUB_TYPE_NR));
605 
606 	trace_xchk_start(XFS_I(file_inode(file)), sm, error);
607 
608 	/* Forbidden if we are shut down or mounted norecovery. */
609 	error = -ESHUTDOWN;
610 	if (xfs_is_shutdown(mp))
611 		goto out;
612 	error = -ENOTRECOVERABLE;
613 	if (xfs_has_norecovery(mp))
614 		goto out;
615 
616 	error = xchk_validate_inputs(mp, sm);
617 	if (error)
618 		goto out;
619 
620 	xfs_warn_mount(mp, XFS_OPSTATE_WARNED_SCRUB,
621  "EXPERIMENTAL online scrub feature in use. Use at your own risk!");
622 
623 	sc = kzalloc(sizeof(struct xfs_scrub), XCHK_GFP_FLAGS);
624 	if (!sc) {
625 		error = -ENOMEM;
626 		goto out;
627 	}
628 
629 	sc->mp = mp;
630 	sc->file = file;
631 	sc->sm = sm;
632 	sc->ops = &meta_scrub_ops[sm->sm_type];
633 	sc->sick_mask = xchk_health_mask_for_scrub_type(sm->sm_type);
634 	sc->relax = INIT_XCHK_RELAX;
635 retry_op:
636 	/*
637 	 * When repairs are allowed, prevent freezing or readonly remount while
638 	 * scrub is running with a real transaction.
639 	 */
640 	if (sm->sm_flags & XFS_SCRUB_IFLAG_REPAIR) {
641 		error = mnt_want_write_file(sc->file);
642 		if (error)
643 			goto out_sc;
644 
645 		sc->flags |= XCHK_HAVE_FREEZE_PROT;
646 	}
647 
648 	/* Set up for the operation. */
649 	error = sc->ops->setup(sc);
650 	if (error == -EDEADLOCK && !(sc->flags & XCHK_TRY_HARDER))
651 		goto try_harder;
652 	if (error == -ECHRNG && !(sc->flags & XCHK_NEED_DRAIN))
653 		goto need_drain;
654 	if (error)
655 		goto out_teardown;
656 
657 	/* Scrub for errors. */
658 	check_start = xchk_stats_now();
659 	if ((sc->flags & XREP_ALREADY_FIXED) && sc->ops->repair_eval != NULL)
660 		error = sc->ops->repair_eval(sc);
661 	else
662 		error = sc->ops->scrub(sc);
663 	run.scrub_ns += xchk_stats_elapsed_ns(check_start);
664 	if (error == -EDEADLOCK && !(sc->flags & XCHK_TRY_HARDER))
665 		goto try_harder;
666 	if (error == -ECHRNG && !(sc->flags & XCHK_NEED_DRAIN))
667 		goto need_drain;
668 	if (error || (sm->sm_flags & XFS_SCRUB_OFLAG_INCOMPLETE))
669 		goto out_teardown;
670 
671 	xchk_update_health(sc);
672 
673 	if (xchk_could_repair(sc)) {
674 		/*
675 		 * If userspace asked for a repair but it wasn't necessary,
676 		 * report that back to userspace.
677 		 */
678 		if (!xrep_will_attempt(sc)) {
679 			sc->sm->sm_flags |= XFS_SCRUB_OFLAG_NO_REPAIR_NEEDED;
680 			goto out_nofix;
681 		}
682 
683 		/*
684 		 * If it's broken, userspace wants us to fix it, and we haven't
685 		 * already tried to fix it, then attempt a repair.
686 		 */
687 		error = xrep_attempt(sc, &run);
688 		if (error == -EAGAIN) {
689 			/*
690 			 * Either the repair function succeeded or it couldn't
691 			 * get all the resources it needs; either way, we go
692 			 * back to the beginning and call the scrub function.
693 			 */
694 			error = xchk_teardown(sc, 0);
695 			if (error) {
696 				xrep_failure(mp);
697 				goto out_sc;
698 			}
699 			goto retry_op;
700 		}
701 	}
702 
703 out_nofix:
704 	xchk_postmortem(sc);
705 out_teardown:
706 	error = xchk_teardown(sc, error);
707 out_sc:
708 	if (error != -ENOENT)
709 		xchk_stats_merge(mp, sm, &run);
710 	kfree(sc);
711 out:
712 	trace_xchk_done(XFS_I(file_inode(file)), sm, error);
713 	if (error == -EFSCORRUPTED || error == -EFSBADCRC) {
714 		sm->sm_flags |= XFS_SCRUB_OFLAG_CORRUPT;
715 		error = 0;
716 	}
717 	return error;
718 need_drain:
719 	error = xchk_teardown(sc, 0);
720 	if (error)
721 		goto out_sc;
722 	sc->flags |= XCHK_NEED_DRAIN;
723 	run.retries++;
724 	goto retry_op;
725 try_harder:
726 	/*
727 	 * Scrubbers return -EDEADLOCK to mean 'try harder'.  Tear down
728 	 * everything we hold, then set up again with preparation for
729 	 * worst-case scenarios.
730 	 */
731 	error = xchk_teardown(sc, 0);
732 	if (error)
733 		goto out_sc;
734 	sc->flags |= XCHK_TRY_HARDER;
735 	run.retries++;
736 	goto retry_op;
737 }
738 
739 /* Scrub one aspect of one piece of metadata. */
740 int
xfs_ioc_scrub_metadata(struct file * file,void __user * arg)741 xfs_ioc_scrub_metadata(
742 	struct file			*file,
743 	void				__user *arg)
744 {
745 	struct xfs_scrub_metadata	scrub;
746 	int				error;
747 
748 	if (!capable(CAP_SYS_ADMIN))
749 		return -EPERM;
750 
751 	if (copy_from_user(&scrub, arg, sizeof(scrub)))
752 		return -EFAULT;
753 
754 	error = xfs_scrub_metadata(file, &scrub);
755 	if (error)
756 		return error;
757 
758 	if (copy_to_user(arg, &scrub, sizeof(scrub)))
759 		return -EFAULT;
760 
761 	return 0;
762 }
763 
764 /* Decide if there have been any scrub failures up to this point. */
765 static inline int
xfs_scrubv_check_barrier(struct xfs_mount * mp,const struct xfs_scrub_vec * vectors,const struct xfs_scrub_vec * stop_vec)766 xfs_scrubv_check_barrier(
767 	struct xfs_mount		*mp,
768 	const struct xfs_scrub_vec	*vectors,
769 	const struct xfs_scrub_vec	*stop_vec)
770 {
771 	const struct xfs_scrub_vec	*v;
772 	__u32				failmask;
773 
774 	failmask = stop_vec->sv_flags & XFS_SCRUB_FLAGS_OUT;
775 
776 	for (v = vectors; v < stop_vec; v++) {
777 		if (v->sv_type == XFS_SCRUB_TYPE_BARRIER)
778 			continue;
779 
780 		/*
781 		 * Runtime errors count as a previous failure, except the ones
782 		 * used to ask userspace to retry.
783 		 */
784 		switch (v->sv_ret) {
785 		case -EBUSY:
786 		case -ENOENT:
787 		case -EUSERS:
788 		case 0:
789 			break;
790 		default:
791 			return -ECANCELED;
792 		}
793 
794 		/*
795 		 * If any of the out-flags on the scrub vector match the mask
796 		 * that was set on the barrier vector, that's a previous fail.
797 		 */
798 		if (v->sv_flags & failmask)
799 			return -ECANCELED;
800 	}
801 
802 	return 0;
803 }
804 
805 /*
806  * If the caller provided us with a nonzero inode number that isn't the ioctl
807  * file, try to grab a reference to it to eliminate all further untrusted inode
808  * lookups.  If we can't get the inode, let each scrub function try again.
809  */
810 STATIC struct xfs_inode *
xchk_scrubv_open_by_handle(struct xfs_mount * mp,const struct xfs_scrub_vec_head * head)811 xchk_scrubv_open_by_handle(
812 	struct xfs_mount		*mp,
813 	const struct xfs_scrub_vec_head	*head)
814 {
815 	struct xfs_trans		*tp;
816 	struct xfs_inode		*ip;
817 	int				error;
818 
819 	error = xfs_trans_alloc_empty(mp, &tp);
820 	if (error)
821 		return NULL;
822 
823 	error = xfs_iget(mp, tp, head->svh_ino, XCHK_IGET_FLAGS, 0, &ip);
824 	xfs_trans_cancel(tp);
825 	if (error)
826 		return NULL;
827 
828 	if (VFS_I(ip)->i_generation != head->svh_gen) {
829 		xfs_irele(ip);
830 		return NULL;
831 	}
832 
833 	return ip;
834 }
835 
836 /* Vectored scrub implementation to reduce ioctl calls. */
837 int
xfs_ioc_scrubv_metadata(struct file * file,void __user * arg)838 xfs_ioc_scrubv_metadata(
839 	struct file			*file,
840 	void				__user *arg)
841 {
842 	struct xfs_scrub_vec_head	head;
843 	struct xfs_scrub_vec_head	__user *uhead = arg;
844 	struct xfs_scrub_vec		*vectors;
845 	struct xfs_scrub_vec		__user *uvectors;
846 	struct xfs_inode		*ip_in = XFS_I(file_inode(file));
847 	struct xfs_mount		*mp = ip_in->i_mount;
848 	struct xfs_inode		*handle_ip = NULL;
849 	struct xfs_scrub_vec		*v;
850 	size_t				vec_bytes;
851 	unsigned int			i;
852 	int				error = 0;
853 
854 	if (!capable(CAP_SYS_ADMIN))
855 		return -EPERM;
856 
857 	if (copy_from_user(&head, uhead, sizeof(head)))
858 		return -EFAULT;
859 
860 	if (head.svh_reserved)
861 		return -EINVAL;
862 	if (head.svh_flags & ~XFS_SCRUB_VEC_FLAGS_ALL)
863 		return -EINVAL;
864 	if (head.svh_nr == 0)
865 		return 0;
866 
867 	vec_bytes = array_size(head.svh_nr, sizeof(struct xfs_scrub_vec));
868 	if (vec_bytes > PAGE_SIZE)
869 		return -ENOMEM;
870 
871 	uvectors = u64_to_user_ptr(head.svh_vectors);
872 	vectors = memdup_user(uvectors, vec_bytes);
873 	if (IS_ERR(vectors))
874 		return PTR_ERR(vectors);
875 
876 	trace_xchk_scrubv_start(ip_in, &head);
877 
878 	for (i = 0, v = vectors; i < head.svh_nr; i++, v++) {
879 		if (v->sv_reserved) {
880 			error = -EINVAL;
881 			goto out_free;
882 		}
883 
884 		if (v->sv_type == XFS_SCRUB_TYPE_BARRIER &&
885 		    (v->sv_flags & ~XFS_SCRUB_FLAGS_OUT)) {
886 			error = -EINVAL;
887 			goto out_free;
888 		}
889 
890 		trace_xchk_scrubv_item(mp, &head, i, v);
891 	}
892 
893 	/*
894 	 * If the caller wants us to do a scrub-by-handle and the file used to
895 	 * call the ioctl is not the same file, load the incore inode and pin
896 	 * it across all the scrubv actions to avoid repeated UNTRUSTED
897 	 * lookups.  The reference is not passed to deeper layers of scrub
898 	 * because each scrubber gets to decide its own strategy and return
899 	 * values for getting an inode.
900 	 */
901 	if (head.svh_ino && head.svh_ino != ip_in->i_ino)
902 		handle_ip = xchk_scrubv_open_by_handle(mp, &head);
903 
904 	/* Run all the scrubbers. */
905 	for (i = 0, v = vectors; i < head.svh_nr; i++, v++) {
906 		struct xfs_scrub_metadata	sm = {
907 			.sm_type		= v->sv_type,
908 			.sm_flags		= v->sv_flags,
909 			.sm_ino			= head.svh_ino,
910 			.sm_gen			= head.svh_gen,
911 			.sm_agno		= head.svh_agno,
912 		};
913 
914 		if (v->sv_type == XFS_SCRUB_TYPE_BARRIER) {
915 			v->sv_ret = xfs_scrubv_check_barrier(mp, vectors, v);
916 			if (v->sv_ret) {
917 				trace_xchk_scrubv_barrier_fail(mp, &head, i, v);
918 				break;
919 			}
920 
921 			continue;
922 		}
923 
924 		v->sv_ret = xfs_scrub_metadata(file, &sm);
925 		v->sv_flags = sm.sm_flags;
926 
927 		trace_xchk_scrubv_outcome(mp, &head, i, v);
928 
929 		if (head.svh_rest_us) {
930 			ktime_t		expires;
931 
932 			expires = ktime_add_ns(ktime_get(),
933 					head.svh_rest_us * 1000);
934 			set_current_state(TASK_KILLABLE);
935 			schedule_hrtimeout(&expires, HRTIMER_MODE_ABS);
936 		}
937 
938 		if (fatal_signal_pending(current)) {
939 			error = -EINTR;
940 			goto out_free;
941 		}
942 	}
943 
944 	if (copy_to_user(uvectors, vectors, vec_bytes) ||
945 	    copy_to_user(uhead, &head, sizeof(head))) {
946 		error = -EFAULT;
947 		goto out_free;
948 	}
949 
950 out_free:
951 	if (handle_ip)
952 		xfs_irele(handle_ip);
953 	kfree(vectors);
954 	return error;
955 }
956