xref: /linux/fs/xfs/scrub/nlinks.c (revision fab183d632628381b466a41479489541ac0e29a0)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) 2021-2024 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_log_format.h"
13 #include "xfs_trans.h"
14 #include "xfs_inode.h"
15 #include "xfs_icache.h"
16 #include "xfs_iwalk.h"
17 #include "xfs_ialloc.h"
18 #include "xfs_dir2.h"
19 #include "xfs_dir2_priv.h"
20 #include "xfs_ag.h"
21 #include "xfs_parent.h"
22 #include "scrub/scrub.h"
23 #include "scrub/common.h"
24 #include "scrub/repair.h"
25 #include "scrub/xfile.h"
26 #include "scrub/xfarray.h"
27 #include "scrub/iscan.h"
28 #include "scrub/orphanage.h"
29 #include "scrub/nlinks.h"
30 #include "scrub/trace.h"
31 #include "scrub/readdir.h"
32 #include "scrub/tempfile.h"
33 #include "scrub/listxattr.h"
34 
35 /*
36  * Live Inode Link Count Checking
37  * ==============================
38  *
39  * Inode link counts are "summary" metadata, in the sense that they are
40  * computed as the number of directory entries referencing each file on the
41  * filesystem.  Therefore, we compute the correct link counts by creating a
42  * shadow link count structure and walking every inode.
43  */
44 
45 /* Set us up to scrub inode link counts. */
46 int
xchk_setup_nlinks(struct xfs_scrub * sc)47 xchk_setup_nlinks(
48 	struct xfs_scrub	*sc)
49 {
50 	struct xchk_nlink_ctrs	*xnc;
51 	int			error;
52 
53 	xchk_fsgates_enable(sc, XCHK_FSGATES_DIRENTS);
54 
55 	if (xchk_could_repair(sc)) {
56 		error = xrep_setup_nlinks(sc);
57 		if (error)
58 			return error;
59 	}
60 
61 	xnc = kvzalloc_obj(struct xchk_nlink_ctrs, XCHK_GFP_FLAGS);
62 	if (!xnc)
63 		return -ENOMEM;
64 	xnc->xname.name = xnc->namebuf;
65 	xnc->sc = sc;
66 	sc->buf = xnc;
67 
68 	return xchk_setup_fs(sc);
69 }
70 
71 /*
72  * Part 1: Collecting file link counts.  For each file, we create a shadow link
73  * counting structure, then walk the entire directory tree, incrementing parent
74  * and child link counts for each directory entry seen.
75  *
76  * To avoid false corruption reports in part 2, any failure in this part must
77  * set the INCOMPLETE flag even when a negative errno is returned.  This care
78  * must be taken with certain errno values (i.e. EFSBADCRC, EFSCORRUPTED,
79  * ECANCELED) that are absorbed into a scrub state flag update by
80  * xchk_*_process_error.  Scrub and repair share the same incore data
81  * structures, so the INCOMPLETE flag is critical to prevent a repair based on
82  * insufficient information.
83  *
84  * Because we are scanning a live filesystem, it's possible that another thread
85  * will try to update the link counts for an inode that we've already scanned.
86  * This will cause our counts to be incorrect.  Therefore, we hook all
87  * directory entry updates because that is when link count updates occur.  By
88  * shadowing transaction updates in this manner, live nlink check can ensure by
89  * locking the inode and the shadow structure that its own copies are not out
90  * of date.  Because the hook code runs in a different process context from the
91  * scrub code and the scrub state flags are not accessed atomically, failures
92  * in the hook code must abort the iscan and the scrubber must notice the
93  * aborted scan and set the incomplete flag.
94  *
95  * Note that we use jump labels and srcu notifier hooks to minimize the
96  * overhead when live nlinks is /not/ running.  Locking order for nlink
97  * observations is inode ILOCK -> iscan_lock/xchk_nlink_ctrs lock.
98  */
99 
100 /*
101  * Add a delta to an nlink counter, clamping the value to U32_MAX.  Because
102  * XFS_MAXLINK < U32_MAX, the checking code will produce the correct results
103  * even if we lose some precision.
104  */
105 static inline void
careful_add(xfs_nlink_t * nlinkp,int delta)106 careful_add(
107 	xfs_nlink_t	*nlinkp,
108 	int		delta)
109 {
110 	uint64_t	new_value = (uint64_t)(*nlinkp) + delta;
111 
112 	BUILD_BUG_ON(XFS_MAXLINK > U32_MAX);
113 	*nlinkp = min_t(uint64_t, new_value, U32_MAX);
114 }
115 
116 /* Update incore link count information.  Caller must hold the nlinks lock. */
117 STATIC int
xchk_nlinks_update_incore(struct xchk_nlink_ctrs * xnc,xfs_ino_t ino,int parents_delta,int backrefs_delta,int children_delta)118 xchk_nlinks_update_incore(
119 	struct xchk_nlink_ctrs	*xnc,
120 	xfs_ino_t		ino,
121 	int			parents_delta,
122 	int			backrefs_delta,
123 	int			children_delta)
124 {
125 	struct xchk_nlink	nl;
126 	int			error;
127 
128 	if (!xnc->nlinks)
129 		return 0;
130 
131 	error = xfarray_load_sparse(xnc->nlinks, ino, &nl);
132 	if (error)
133 		return error;
134 
135 	trace_xchk_nlinks_update_incore(xnc->sc->mp, ino, &nl, parents_delta,
136 			backrefs_delta, children_delta);
137 
138 	careful_add(&nl.parents, parents_delta);
139 	careful_add(&nl.backrefs, backrefs_delta);
140 	careful_add(&nl.children, children_delta);
141 
142 	nl.flags |= XCHK_NLINK_WRITTEN;
143 	error = xfarray_store(xnc->nlinks, ino, &nl);
144 	if (error == -EFBIG) {
145 		/*
146 		 * EFBIG means we tried to store data at too high a byte offset
147 		 * in the sparse array.  IOWs, we cannot complete the check and
148 		 * must notify userspace that the check was incomplete.
149 		 */
150 		error = -ECANCELED;
151 	}
152 	return error;
153 }
154 
155 /*
156  * Apply a link count change from the regular filesystem into our shadow link
157  * count structure based on a directory update in progress.
158  */
159 STATIC int
xchk_nlinks_live_update(struct notifier_block * nb,unsigned long action,void * data)160 xchk_nlinks_live_update(
161 	struct notifier_block		*nb,
162 	unsigned long			action,
163 	void				*data)
164 {
165 	struct xfs_dir_update_params	*p = data;
166 	struct xchk_nlink_ctrs		*xnc;
167 	int				error;
168 
169 	xnc = container_of(nb, struct xchk_nlink_ctrs, dhook.dirent_hook.nb);
170 
171 	/*
172 	 * Ignore temporary directories being used to stage dir repairs, since
173 	 * we don't bump the link counts of the children.
174 	 */
175 	if (xrep_is_tempfile(p->dp))
176 		return NOTIFY_DONE;
177 
178 	trace_xchk_nlinks_live_update(xnc->sc->mp, p->dp, action, I_INO(p->ip),
179 			p->delta, p->name->name, p->name->len);
180 
181 	/*
182 	 * If we've already scanned @dp, update the number of parents that link
183 	 * to @ip.  If @ip is a subdirectory, update the number of child links
184 	 * going out of @dp.
185 	 */
186 	if (xchk_iscan_want_live_update(&xnc->collect_iscan, I_INO(p->dp))) {
187 		mutex_lock(&xnc->lock);
188 		error = xchk_nlinks_update_incore(xnc, I_INO(p->ip), p->delta,
189 				0, 0);
190 		if (!error && S_ISDIR(VFS_IC(p->ip)->i_mode))
191 			error = xchk_nlinks_update_incore(xnc, I_INO(p->dp), 0,
192 					0, p->delta);
193 		mutex_unlock(&xnc->lock);
194 		if (error)
195 			goto out_abort;
196 	}
197 
198 	/*
199 	 * If @ip is a subdirectory and we've already scanned it, update the
200 	 * number of backrefs pointing to @dp.
201 	 */
202 	if (S_ISDIR(VFS_IC(p->ip)->i_mode) &&
203 	    xchk_iscan_want_live_update(&xnc->collect_iscan, I_INO(p->ip))) {
204 		mutex_lock(&xnc->lock);
205 		error = xchk_nlinks_update_incore(xnc, I_INO(p->dp), 0,
206 				p->delta, 0);
207 		mutex_unlock(&xnc->lock);
208 		if (error)
209 			goto out_abort;
210 	}
211 
212 	return NOTIFY_DONE;
213 
214 out_abort:
215 	xchk_iscan_abort(&xnc->collect_iscan);
216 	return NOTIFY_DONE;
217 }
218 
219 /* Bump the observed link count for the inode referenced by this entry. */
220 STATIC int
xchk_nlinks_collect_dirent(struct xfs_scrub * sc,struct xfs_inode * dp,xfs_dir2_dataptr_t dapos,const struct xfs_name * name,xfs_ino_t ino,void * priv)221 xchk_nlinks_collect_dirent(
222 	struct xfs_scrub	*sc,
223 	struct xfs_inode	*dp,
224 	xfs_dir2_dataptr_t	dapos,
225 	const struct xfs_name	*name,
226 	xfs_ino_t		ino,
227 	void			*priv)
228 {
229 	struct xchk_nlink_ctrs	*xnc = priv;
230 	bool			dot = false, dotdot = false;
231 	int			error;
232 
233 	/* Does this name make sense? */
234 	if (name->len == 0 || !xfs_dir2_namecheck(name->name, name->len)) {
235 		error = -ECANCELED;
236 		goto out_abort;
237 	}
238 
239 	if (name->len == 1 && name->name[0] == '.')
240 		dot = true;
241 	else if (name->len == 2 && name->name[0] == '.' &&
242 				   name->name[1] == '.')
243 		dotdot = true;
244 
245 	/* Don't accept a '.' entry that points somewhere else. */
246 	if (dot && ino != I_INO(dp)) {
247 		error = -ECANCELED;
248 		goto out_abort;
249 	}
250 
251 	/* Don't accept an invalid inode number. */
252 	if (!xfs_verify_dir_ino(sc->mp, ino)) {
253 		error = -ECANCELED;
254 		goto out_abort;
255 	}
256 
257 	/* Update the shadow link counts if we haven't already failed. */
258 
259 	if (xchk_iscan_aborted(&xnc->collect_iscan)) {
260 		error = -ECANCELED;
261 		goto out_incomplete;
262 	}
263 
264 	trace_xchk_nlinks_collect_dirent(sc->mp, dp, ino, name);
265 
266 	mutex_lock(&xnc->lock);
267 
268 	/*
269 	 * If this is a dotdot entry, it is a back link from dp to ino.  How
270 	 * we handle this depends on whether or not dp is the root directory.
271 	 *
272 	 * The root directory is its own parent, so we pretend the dotdot entry
273 	 * establishes the "parent" of the root directory.  Increment the
274 	 * number of parents of the root directory.
275 	 *
276 	 * Otherwise, increment the number of backrefs pointing back to ino.
277 	 *
278 	 * If the filesystem has parent pointers, we walk the pptrs to
279 	 * determine the backref count.
280 	 */
281 	if (dotdot) {
282 		if (xchk_inode_is_dirtree_root(dp))
283 			error = xchk_nlinks_update_incore(xnc, ino, 1, 0, 0);
284 		else if (!xfs_has_parent(sc->mp))
285 			error = xchk_nlinks_update_incore(xnc, ino, 0, 1, 0);
286 		else
287 			error = 0;
288 		if (error)
289 			goto out_unlock;
290 	}
291 
292 	/*
293 	 * If this dirent is a forward link from dp to ino, increment the
294 	 * number of parents linking into ino.
295 	 */
296 	if (!dot && !dotdot) {
297 		error = xchk_nlinks_update_incore(xnc, ino, 1, 0, 0);
298 		if (error)
299 			goto out_unlock;
300 	}
301 
302 	/*
303 	 * If this dirent is a forward link to a subdirectory, increment the
304 	 * number of child links of dp.
305 	 */
306 	if (!dot && !dotdot && name->type == XFS_DIR3_FT_DIR) {
307 		error = xchk_nlinks_update_incore(xnc, I_INO(dp), 0, 0, 1);
308 		if (error)
309 			goto out_unlock;
310 	}
311 
312 	mutex_unlock(&xnc->lock);
313 	return 0;
314 
315 out_unlock:
316 	mutex_unlock(&xnc->lock);
317 out_abort:
318 	xchk_iscan_abort(&xnc->collect_iscan);
319 out_incomplete:
320 	xchk_set_incomplete(sc);
321 	return error;
322 }
323 
324 /* Bump the backref count for the inode referenced by this parent pointer. */
325 STATIC int
xchk_nlinks_collect_pptr(struct xfs_scrub * sc,struct xfs_inode * ip,unsigned int attr_flags,const unsigned char * name,unsigned int namelen,const void * value,unsigned int valuelen,void * priv)326 xchk_nlinks_collect_pptr(
327 	struct xfs_scrub		*sc,
328 	struct xfs_inode		*ip,
329 	unsigned int			attr_flags,
330 	const unsigned char		*name,
331 	unsigned int			namelen,
332 	const void			*value,
333 	unsigned int			valuelen,
334 	void				*priv)
335 {
336 	struct xfs_name			xname = {
337 		.name			= name,
338 		.len			= namelen,
339 	};
340 	struct xchk_nlink_ctrs		*xnc = priv;
341 	const struct xfs_parent_rec	*pptr_rec = value;
342 	xfs_ino_t			parent_ino;
343 	int				error;
344 
345 	/* Update the shadow link counts if we haven't already failed. */
346 
347 	if (xchk_iscan_aborted(&xnc->collect_iscan)) {
348 		error = -ECANCELED;
349 		goto out_incomplete;
350 	}
351 
352 	if (!(attr_flags & XFS_ATTR_PARENT))
353 		return 0;
354 
355 	error = xfs_parent_from_attr(sc->mp, attr_flags, name, namelen, value,
356 			valuelen, &parent_ino, NULL);
357 	if (error)
358 		return error;
359 
360 	trace_xchk_nlinks_collect_pptr(sc->mp, ip, &xname, pptr_rec);
361 
362 	mutex_lock(&xnc->lock);
363 
364 	error = xchk_nlinks_update_incore(xnc, parent_ino, 0, 1, 0);
365 	if (error)
366 		goto out_unlock;
367 
368 	mutex_unlock(&xnc->lock);
369 	return 0;
370 
371 out_unlock:
372 	mutex_unlock(&xnc->lock);
373 	xchk_iscan_abort(&xnc->collect_iscan);
374 out_incomplete:
375 	xchk_set_incomplete(sc);
376 	return error;
377 }
378 
379 static uint
xchk_nlinks_ilock_dir(struct xfs_inode * ip)380 xchk_nlinks_ilock_dir(
381 	struct xfs_inode	*ip)
382 {
383 	uint			lock_mode = XFS_ILOCK_SHARED;
384 
385 	/*
386 	 * Take the IOLOCK so that other threads cannot start a directory
387 	 * update while we're scanning.
388 	 */
389 	xfs_ilock(ip, XFS_IOLOCK_SHARED);
390 
391 	/*
392 	 * We're going to scan the directory entries, so we must be ready to
393 	 * pull the data fork mappings into memory if they aren't already.
394 	 */
395 	if (xfs_need_iread_extents(&ip->i_df))
396 		lock_mode = XFS_ILOCK_EXCL;
397 
398 	/*
399 	 * We're going to scan the parent pointers, so we must be ready to
400 	 * pull the attr fork mappings into memory if they aren't already.
401 	 */
402 	if (xfs_has_parent(ip->i_mount) && xfs_inode_has_attr_fork(ip) &&
403 	    xfs_need_iread_extents(&ip->i_af))
404 		lock_mode = XFS_ILOCK_EXCL;
405 
406 	xfs_ilock(ip, lock_mode);
407 	return lock_mode | XFS_IOLOCK_SHARED;
408 }
409 
410 /* Walk a directory to bump the observed link counts of the children. */
411 STATIC int
xchk_nlinks_collect_dir(struct xchk_nlink_ctrs * xnc,struct xfs_inode * dp)412 xchk_nlinks_collect_dir(
413 	struct xchk_nlink_ctrs	*xnc,
414 	struct xfs_inode	*dp)
415 {
416 	struct xfs_scrub	*sc = xnc->sc;
417 	unsigned int		lock_mode;
418 	int			error = 0;
419 
420 	/*
421 	 * Ignore temporary directories being used to stage dir repairs, since
422 	 * we don't bump the link counts of the children.
423 	 */
424 	if (xrep_is_tempfile(dp))
425 		return 0;
426 
427 	/* Prevent anyone from changing this directory while we walk it. */
428 	lock_mode = xchk_nlinks_ilock_dir(dp);
429 
430 	/*
431 	 * The dotdot entry of an unlinked directory still points to the last
432 	 * parent, but the parent no longer links to this directory.  Skip the
433 	 * directory to avoid overcounting.
434 	 */
435 	if (VFS_I(dp)->i_nlink == 0)
436 		goto out_unlock;
437 
438 	/*
439 	 * We cannot count file links if the directory looks as though it has
440 	 * been zapped by the inode record repair code.
441 	 */
442 	if (xchk_dir_looks_zapped(dp)) {
443 		error = -EBUSY;
444 		goto out_abort;
445 	}
446 
447 	error = xchk_dir_walk(sc, dp, xchk_nlinks_collect_dirent, xnc);
448 	if (error == -ECANCELED) {
449 		error = 0;
450 		goto out_unlock;
451 	}
452 	if (error)
453 		goto out_abort;
454 
455 	/* Walk the parent pointers to get real backref counts. */
456 	if (xfs_has_parent(sc->mp)) {
457 		/*
458 		 * If the extended attributes look as though they has been
459 		 * zapped by the inode record repair code, we cannot scan for
460 		 * parent pointers.
461 		 */
462 		if (xchk_pptr_looks_zapped(dp)) {
463 			error = -EBUSY;
464 			goto out_unlock;
465 		}
466 
467 		error = xchk_xattr_walk(sc, dp, xchk_nlinks_collect_pptr, NULL,
468 				xnc);
469 		if (error == -ECANCELED) {
470 			error = 0;
471 			goto out_unlock;
472 		}
473 		if (error)
474 			goto out_abort;
475 	}
476 
477 	xchk_iscan_mark_visited(&xnc->collect_iscan, dp);
478 	goto out_unlock;
479 
480 out_abort:
481 	xchk_set_incomplete(sc);
482 	xchk_iscan_abort(&xnc->collect_iscan);
483 out_unlock:
484 	xfs_iunlock(dp, lock_mode);
485 	return error;
486 }
487 
488 /* If this looks like a valid pointer, count it. */
489 static inline int
xchk_nlinks_collect_metafile(struct xchk_nlink_ctrs * xnc,xfs_ino_t ino)490 xchk_nlinks_collect_metafile(
491 	struct xchk_nlink_ctrs	*xnc,
492 	xfs_ino_t		ino)
493 {
494 	if (!xfs_verify_ino(xnc->sc->mp, ino))
495 		return 0;
496 
497 	trace_xchk_nlinks_collect_metafile(xnc->sc->mp, ino);
498 	return xchk_nlinks_update_incore(xnc, ino, 1, 0, 0);
499 }
500 
501 /* Bump the link counts of metadata files rooted in the superblock. */
502 STATIC int
xchk_nlinks_collect_metafiles(struct xchk_nlink_ctrs * xnc)503 xchk_nlinks_collect_metafiles(
504 	struct xchk_nlink_ctrs	*xnc)
505 {
506 	struct xfs_mount	*mp = xnc->sc->mp;
507 	int			error = -ECANCELED;
508 
509 
510 	if (xchk_iscan_aborted(&xnc->collect_iscan))
511 		goto out_incomplete;
512 
513 	mutex_lock(&xnc->lock);
514 	error = xchk_nlinks_collect_metafile(xnc, mp->m_sb.sb_rbmino);
515 	if (error)
516 		goto out_abort;
517 
518 	error = xchk_nlinks_collect_metafile(xnc, mp->m_sb.sb_rsumino);
519 	if (error)
520 		goto out_abort;
521 
522 	error = xchk_nlinks_collect_metafile(xnc, mp->m_sb.sb_uquotino);
523 	if (error)
524 		goto out_abort;
525 
526 	error = xchk_nlinks_collect_metafile(xnc, mp->m_sb.sb_gquotino);
527 	if (error)
528 		goto out_abort;
529 
530 	error = xchk_nlinks_collect_metafile(xnc, mp->m_sb.sb_pquotino);
531 	if (error)
532 		goto out_abort;
533 	mutex_unlock(&xnc->lock);
534 
535 	return 0;
536 
537 out_abort:
538 	mutex_unlock(&xnc->lock);
539 	xchk_iscan_abort(&xnc->collect_iscan);
540 out_incomplete:
541 	xchk_set_incomplete(xnc->sc);
542 	return error;
543 }
544 
545 /* Advance the collection scan cursor for this non-directory file. */
546 static inline int
xchk_nlinks_collect_file(struct xchk_nlink_ctrs * xnc,struct xfs_inode * ip)547 xchk_nlinks_collect_file(
548 	struct xchk_nlink_ctrs	*xnc,
549 	struct xfs_inode	*ip)
550 {
551 	xfs_ilock(ip, XFS_IOLOCK_SHARED);
552 	xchk_iscan_mark_visited(&xnc->collect_iscan, ip);
553 	xfs_iunlock(ip, XFS_IOLOCK_SHARED);
554 	return 0;
555 }
556 
557 /* Walk all directories and count inode links. */
558 STATIC int
xchk_nlinks_collect(struct xchk_nlink_ctrs * xnc)559 xchk_nlinks_collect(
560 	struct xchk_nlink_ctrs	*xnc)
561 {
562 	struct xfs_scrub	*sc = xnc->sc;
563 	struct xfs_inode	*ip;
564 	int			error;
565 
566 	/* Count the rt and quota files that are rooted in the superblock. */
567 	error = xchk_nlinks_collect_metafiles(xnc);
568 	if (error)
569 		return error;
570 
571 	/*
572 	 * Set up for a potentially lengthy filesystem scan by reducing our
573 	 * transaction resource usage for the duration.  Specifically:
574 	 *
575 	 * Cancel the transaction to release the log grant space while we scan
576 	 * the filesystem.
577 	 *
578 	 * Create a new empty transaction to eliminate the possibility of the
579 	 * inode scan deadlocking on cyclical metadata.
580 	 *
581 	 * We pass the empty transaction to the file scanning function to avoid
582 	 * repeatedly cycling empty transactions.  This can be done even though
583 	 * we take the IOLOCK to quiesce the file because empty transactions
584 	 * do not take sb_internal.
585 	 */
586 	xchk_trans_cancel(sc);
587 	xchk_trans_alloc_empty(sc);
588 
589 	while ((error = xchk_iscan_iter(&xnc->collect_iscan, &ip)) == 1) {
590 		if (S_ISDIR(VFS_I(ip)->i_mode))
591 			error = xchk_nlinks_collect_dir(xnc, ip);
592 		else
593 			error = xchk_nlinks_collect_file(xnc, ip);
594 		xchk_irele(sc, ip);
595 		if (error)
596 			break;
597 
598 		if (xchk_should_terminate(sc, &error))
599 			break;
600 	}
601 	xchk_iscan_iter_finish(&xnc->collect_iscan);
602 	if (error) {
603 		xchk_set_incomplete(sc);
604 		/*
605 		 * If we couldn't grab an inode that was busy with a state
606 		 * change, change the error code so that we exit to userspace
607 		 * as quickly as possible.
608 		 */
609 		if (error == -EBUSY)
610 			return -ECANCELED;
611 		return error;
612 	}
613 
614 	/*
615 	 * Switch out for a real transaction in preparation for building a new
616 	 * tree.
617 	 */
618 	xchk_trans_cancel(sc);
619 	return xchk_setup_fs(sc);
620 }
621 
622 /*
623  * Part 2: Comparing file link counters.  Walk each inode and compare the link
624  * counts against our shadow information; and then walk each shadow link count
625  * structure (that wasn't covered in the first part), comparing it against the
626  * file.
627  */
628 
629 /* Read the observed link count for comparison with the actual inode. */
630 STATIC int
xchk_nlinks_comparison_read(struct xchk_nlink_ctrs * xnc,xfs_ino_t ino,struct xchk_nlink * obs)631 xchk_nlinks_comparison_read(
632 	struct xchk_nlink_ctrs	*xnc,
633 	xfs_ino_t		ino,
634 	struct xchk_nlink	*obs)
635 {
636 	struct xchk_nlink	nl;
637 	int			error;
638 
639 	error = xfarray_load_sparse(xnc->nlinks, ino, &nl);
640 	if (error)
641 		return error;
642 
643 	nl.flags |= (XCHK_NLINK_COMPARE_SCANNED | XCHK_NLINK_WRITTEN);
644 
645 	error = xfarray_store(xnc->nlinks, ino, &nl);
646 	if (error == -EFBIG) {
647 		/*
648 		 * EFBIG means we tried to store data at too high a byte offset
649 		 * in the sparse array.  IOWs, we cannot complete the check and
650 		 * must notify userspace that the check was incomplete.  This
651 		 * shouldn't really happen outside of the collection phase.
652 		 */
653 		xchk_set_incomplete(xnc->sc);
654 		return -ECANCELED;
655 	}
656 	if (error)
657 		return error;
658 
659 	/* Copy the counters, but do not expose the internal state. */
660 	obs->parents = nl.parents;
661 	obs->backrefs = nl.backrefs;
662 	obs->children = nl.children;
663 	obs->flags = 0;
664 	return 0;
665 }
666 
667 /* Check our link count against an inode. */
668 STATIC int
xchk_nlinks_compare_inode(struct xchk_nlink_ctrs * xnc,struct xfs_inode * ip)669 xchk_nlinks_compare_inode(
670 	struct xchk_nlink_ctrs	*xnc,
671 	struct xfs_inode	*ip)
672 {
673 	struct xchk_nlink	obs;
674 	struct xfs_scrub	*sc = xnc->sc;
675 	uint64_t		total_links;
676 	unsigned int		actual_nlink;
677 	int			error;
678 
679 	/*
680 	 * Ignore temporary files being used to stage repairs, since we assume
681 	 * they're correct for non-directories, and the directory repair code
682 	 * doesn't bump the link counts for the children.
683 	 */
684 	if (xrep_is_tempfile(ip))
685 		return 0;
686 
687 	xfs_ilock(ip, XFS_ILOCK_SHARED);
688 	mutex_lock(&xnc->lock);
689 
690 	if (xchk_iscan_aborted(&xnc->collect_iscan)) {
691 		xchk_set_incomplete(xnc->sc);
692 		error = -ECANCELED;
693 		goto out_scanlock;
694 	}
695 
696 	error = xchk_nlinks_comparison_read(xnc, I_INO(ip), &obs);
697 	if (error)
698 		goto out_scanlock;
699 
700 	/*
701 	 * If we don't have ftype to get an accurate count of the subdirectory
702 	 * entries in this directory, take advantage of the fact that on a
703 	 * consistent ftype=0 filesystem, the number of subdirectory
704 	 * backreferences (dotdot entries) pointing towards this directory
705 	 * should be equal to the number of subdirectory entries in the
706 	 * directory.
707 	 */
708 	if (!xfs_has_ftype(sc->mp) && S_ISDIR(VFS_I(ip)->i_mode))
709 		obs.children = obs.backrefs;
710 
711 	total_links = xchk_nlink_total(ip, &obs);
712 	actual_nlink = VFS_I(ip)->i_nlink;
713 
714 	trace_xchk_nlinks_compare_inode(sc->mp, ip, &obs);
715 
716 	/*
717 	 * If we found so many parents that we'd overflow i_nlink, we must flag
718 	 * this as a corruption.  The VFS won't let users increase the link
719 	 * count, but it will let them decrease it.
720 	 */
721 	if (total_links > XFS_NLINK_PINNED) {
722 		xchk_ip_set_corrupt(sc, ip);
723 		goto out_corrupt;
724 	} else if (total_links > XFS_MAXLINK) {
725 		xchk_ino_set_warning(sc, I_INO(ip));
726 	}
727 
728 	/* Link counts should match. */
729 	if (total_links != actual_nlink) {
730 		xchk_ip_set_corrupt(sc, ip);
731 		goto out_corrupt;
732 	}
733 
734 	if (S_ISDIR(VFS_I(ip)->i_mode) && actual_nlink > 0) {
735 		/*
736 		 * The collection phase ignores directories with zero link
737 		 * count, so we ignore them here too.
738 		 *
739 		 * The number of subdirectory backreferences (dotdot entries)
740 		 * pointing towards this directory should be equal to the
741 		 * number of subdirectory entries in the directory.
742 		 */
743 		if (obs.children != obs.backrefs)
744 			xchk_ip_xref_set_corrupt(sc, ip);
745 	} else {
746 		/*
747 		 * Non-directories and unlinked directories should not have
748 		 * back references.
749 		 */
750 		if (obs.backrefs != 0) {
751 			xchk_ip_set_corrupt(sc, ip);
752 			goto out_corrupt;
753 		}
754 
755 		/*
756 		 * Non-directories and unlinked directories should not have
757 		 * children.
758 		 */
759 		if (obs.children != 0) {
760 			xchk_ip_set_corrupt(sc, ip);
761 			goto out_corrupt;
762 		}
763 	}
764 
765 	if (xchk_inode_is_dirtree_root(ip)) {
766 		/*
767 		 * For the root of a directory tree, both the '.' and '..'
768 		 * entries should point to the root directory.  The dotdot
769 		 * entry is counted as a parent of the root /and/ a backref of
770 		 * the root directory.
771 		 */
772 		if (obs.parents != 1) {
773 			xchk_ip_set_corrupt(sc, ip);
774 			goto out_corrupt;
775 		}
776 	} else if (actual_nlink > 0) {
777 		/*
778 		 * Linked files that are not the root directory should have at
779 		 * least one parent.
780 		 */
781 		if (obs.parents == 0) {
782 			xchk_ip_set_corrupt(sc, ip);
783 			goto out_corrupt;
784 		}
785 	}
786 
787 out_corrupt:
788 	if (sc->sm->sm_flags & XFS_SCRUB_OFLAG_CORRUPT)
789 		error = -ECANCELED;
790 out_scanlock:
791 	mutex_unlock(&xnc->lock);
792 	xfs_iunlock(ip, XFS_ILOCK_SHARED);
793 	return error;
794 }
795 
796 /*
797  * Check our link count against an inode that wasn't checked previously.  This
798  * is intended to catch directories with dangling links, though we could be
799  * racing with inode allocation in other threads.
800  */
801 STATIC int
xchk_nlinks_compare_inum(struct xchk_nlink_ctrs * xnc,xfs_ino_t ino)802 xchk_nlinks_compare_inum(
803 	struct xchk_nlink_ctrs	*xnc,
804 	xfs_ino_t		ino)
805 {
806 	struct xchk_nlink	obs;
807 	struct xfs_mount	*mp = xnc->sc->mp;
808 	struct xfs_trans	*tp = xnc->sc->tp;
809 	struct xfs_buf		*agi_bp;
810 	struct xfs_inode	*ip;
811 	int			error;
812 
813 	/*
814 	 * The first iget failed, so try again with the variant that returns
815 	 * either an incore inode or the AGI buffer.  If the function returns
816 	 * EINVAL/ENOENT, it should have passed us the AGI buffer so that we
817 	 * can guarantee that the inode won't be allocated while we check for
818 	 * a zero link count in the observed link count data.
819 	 */
820 	error = xchk_iget_agi(xnc->sc, ino, &agi_bp, &ip);
821 	if (!error) {
822 		/* Actually got an inode, so use the inode compare. */
823 		error = xchk_nlinks_compare_inode(xnc, ip);
824 		xchk_irele(xnc->sc, ip);
825 		return error;
826 	}
827 	if (error == -ENOENT || error == -EINVAL) {
828 		/* No inode was found.  Check for zero link count below. */
829 		error = 0;
830 	}
831 	if (error)
832 		goto out_agi;
833 
834 	/* Ensure that we have protected against inode allocation/freeing. */
835 	if (agi_bp == NULL) {
836 		ASSERT(agi_bp != NULL);
837 		xchk_set_incomplete(xnc->sc);
838 		return -ECANCELED;
839 	}
840 
841 	if (xchk_iscan_aborted(&xnc->collect_iscan)) {
842 		xchk_set_incomplete(xnc->sc);
843 		error = -ECANCELED;
844 		goto out_agi;
845 	}
846 
847 	mutex_lock(&xnc->lock);
848 	error = xchk_nlinks_comparison_read(xnc, ino, &obs);
849 	if (error)
850 		goto out_scanlock;
851 
852 	trace_xchk_nlinks_check_zero(mp, ino, &obs);
853 
854 	/*
855 	 * If we can't grab the inode, the link count had better be zero.  We
856 	 * still hold the AGI to prevent inode allocation/freeing.
857 	 */
858 	if (xchk_nlink_total(NULL, &obs) != 0) {
859 		xchk_ino_set_corrupt(xnc->sc, ino);
860 		error = -ECANCELED;
861 	}
862 
863 out_scanlock:
864 	mutex_unlock(&xnc->lock);
865 out_agi:
866 	if (agi_bp)
867 		xfs_trans_brelse(tp, agi_bp);
868 	return error;
869 }
870 
871 /*
872  * Try to visit every inode in the filesystem to compare the link count.  Move
873  * on if we can't grab an inode, since we'll revisit unchecked nlink records in
874  * the second part.
875  */
876 static int
xchk_nlinks_compare_iter(struct xchk_nlink_ctrs * xnc,struct xfs_inode ** ipp)877 xchk_nlinks_compare_iter(
878 	struct xchk_nlink_ctrs	*xnc,
879 	struct xfs_inode	**ipp)
880 {
881 	int			error;
882 
883 	do {
884 		error = xchk_iscan_iter(&xnc->compare_iscan, ipp);
885 	} while (error == -EBUSY);
886 
887 	return error;
888 }
889 
890 /* Compare the link counts we observed against the live information. */
891 STATIC int
xchk_nlinks_compare(struct xchk_nlink_ctrs * xnc)892 xchk_nlinks_compare(
893 	struct xchk_nlink_ctrs	*xnc)
894 {
895 	struct xchk_nlink	nl;
896 	struct xfs_scrub	*sc = xnc->sc;
897 	struct xfs_inode	*ip;
898 	xfarray_idx_t		cur = XFARRAY_CURSOR_INIT;
899 	int			error;
900 
901 	if (sc->sm->sm_flags & XFS_SCRUB_OFLAG_CORRUPT)
902 		return 0;
903 
904 	/*
905 	 * Create a new empty transaction so that we can advance the iscan
906 	 * cursor without deadlocking if the inobt has a cycle and push on the
907 	 * inactivation workqueue.
908 	 */
909 	xchk_trans_cancel(sc);
910 	xchk_trans_alloc_empty(sc);
911 
912 	/*
913 	 * Use the inobt to walk all allocated inodes to compare the link
914 	 * counts.  Inodes skipped by _compare_iter will be tried again in the
915 	 * next phase of the scan.
916 	 */
917 	xchk_iscan_start(sc, 0, 0, &xnc->compare_iscan);
918 	while ((error = xchk_nlinks_compare_iter(xnc, &ip)) == 1) {
919 		error = xchk_nlinks_compare_inode(xnc, ip);
920 		xchk_iscan_mark_visited(&xnc->compare_iscan, ip);
921 		xchk_irele(sc, ip);
922 		if (error)
923 			break;
924 
925 		if (xchk_should_terminate(sc, &error))
926 			break;
927 	}
928 	xchk_iscan_iter_finish(&xnc->compare_iscan);
929 	xchk_iscan_teardown(&xnc->compare_iscan);
930 	if (error)
931 		return error;
932 
933 	if (sc->sm->sm_flags & XFS_SCRUB_OFLAG_CORRUPT)
934 		return 0;
935 
936 	/*
937 	 * Walk all the non-null nlink observations that weren't checked in the
938 	 * previous step.
939 	 */
940 	mutex_lock(&xnc->lock);
941 	while ((error = xfarray_iter(xnc->nlinks, &cur, &nl)) == 1) {
942 		xfs_ino_t	ino = cur - 1;
943 
944 		if (nl.flags & XCHK_NLINK_COMPARE_SCANNED)
945 			continue;
946 
947 		mutex_unlock(&xnc->lock);
948 
949 		error = xchk_nlinks_compare_inum(xnc, ino);
950 		if (error)
951 			return error;
952 
953 		if (xchk_should_terminate(xnc->sc, &error))
954 			return error;
955 
956 		mutex_lock(&xnc->lock);
957 	}
958 	mutex_unlock(&xnc->lock);
959 
960 	return error;
961 }
962 
963 /* Tear down everything associated with a nlinks check. */
964 static void
xchk_nlinks_teardown_scan(void * priv)965 xchk_nlinks_teardown_scan(
966 	void			*priv)
967 {
968 	struct xchk_nlink_ctrs	*xnc = priv;
969 
970 	/* Discourage any hook functions that might be running. */
971 	xchk_iscan_abort(&xnc->collect_iscan);
972 
973 	xfs_dir_hook_del(xnc->sc->mp, &xnc->dhook);
974 
975 	if (xnc->nlinks)
976 		xfarray_destroy(xnc->nlinks);
977 	xnc->nlinks = NULL;
978 
979 	xchk_iscan_teardown(&xnc->collect_iscan);
980 	mutex_destroy(&xnc->lock);
981 	xnc->sc = NULL;
982 }
983 
984 /*
985  * Scan all inodes in the entire filesystem to generate link count data.  If
986  * the scan is successful, the counts will be left alive for a repair.  If any
987  * error occurs, we'll tear everything down.
988  */
989 STATIC int
xchk_nlinks_setup_scan(struct xfs_scrub * sc,struct xchk_nlink_ctrs * xnc)990 xchk_nlinks_setup_scan(
991 	struct xfs_scrub	*sc,
992 	struct xchk_nlink_ctrs	*xnc)
993 {
994 	struct xfs_mount	*mp = sc->mp;
995 	unsigned long long	max_inos;
996 	xfs_agnumber_t		last_agno = mp->m_sb.sb_agcount - 1;
997 	xfs_agino_t		first_agino, last_agino;
998 	int			error;
999 
1000 	mutex_init(&xnc->lock);
1001 
1002 	/* Retry iget every tenth of a second for up to 30 seconds. */
1003 	xchk_iscan_start(sc, 30000, 100, &xnc->collect_iscan);
1004 
1005 	/*
1006 	 * Set up enough space to store an nlink record for the highest
1007 	 * possible inode number in this system.
1008 	 */
1009 	xfs_agino_range(mp, last_agno, &first_agino, &last_agino);
1010 	max_inos = XFS_AGINO_TO_INO(mp, last_agno, last_agino) + 1;
1011 	error = xfarray_create("file link counts",
1012 			min(XFS_MAXINUMBER + 1, max_inos),
1013 			sizeof(struct xchk_nlink), &xnc->nlinks);
1014 	if (error)
1015 		goto out_teardown;
1016 
1017 	/*
1018 	 * Hook into the directory entry code so that we can capture updates to
1019 	 * file link counts.  The hook only triggers for inodes that were
1020 	 * already scanned, and the scanner thread takes each inode's ILOCK,
1021 	 * which means that any in-progress inode updates will finish before we
1022 	 * can scan the inode.
1023 	 */
1024 	ASSERT(sc->flags & XCHK_FSGATES_DIRENTS);
1025 	xfs_dir_hook_setup(&xnc->dhook, xchk_nlinks_live_update);
1026 	error = xfs_dir_hook_add(mp, &xnc->dhook);
1027 	if (error)
1028 		goto out_teardown;
1029 
1030 	/* Use deferred cleanup to pass the inode link count data to repair. */
1031 	sc->buf_cleanup = xchk_nlinks_teardown_scan;
1032 	return 0;
1033 
1034 out_teardown:
1035 	xchk_nlinks_teardown_scan(xnc);
1036 	return error;
1037 }
1038 
1039 /* Scrub the link count of all inodes on the filesystem. */
1040 int
xchk_nlinks(struct xfs_scrub * sc)1041 xchk_nlinks(
1042 	struct xfs_scrub	*sc)
1043 {
1044 	struct xchk_nlink_ctrs	*xnc = sc->buf;
1045 	int			error = 0;
1046 
1047 	/* Set ourselves up to check link counts on the live filesystem. */
1048 	error = xchk_nlinks_setup_scan(sc, xnc);
1049 	if (error)
1050 		return error;
1051 
1052 	/* Walk all inodes, picking up link count information. */
1053 	error = xchk_nlinks_collect(xnc);
1054 	if (!xchk_xref_process_error(sc, 0, 0, &error))
1055 		return error;
1056 
1057 	/* Fail fast if we're not playing with a full dataset. */
1058 	if (xchk_iscan_aborted(&xnc->collect_iscan))
1059 		xchk_set_incomplete(sc);
1060 	if (sc->sm->sm_flags & XFS_SCRUB_OFLAG_INCOMPLETE)
1061 		return 0;
1062 
1063 	/* Compare link counts. */
1064 	error = xchk_nlinks_compare(xnc);
1065 	if (!xchk_xref_process_error(sc, 0, 0, &error))
1066 		return error;
1067 
1068 	/* Check one last time for an incomplete dataset. */
1069 	if (xchk_iscan_aborted(&xnc->collect_iscan))
1070 		xchk_set_incomplete(sc);
1071 
1072 	return 0;
1073 }
1074