xref: /freebsd/sbin/fsck_ffs/main.c (revision 9162f64b58d01ec01481d60b6cdc06ffd8e8c7fc)
1 /*
2  * Copyright (c) 1980, 1986, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #if 0
31 #ifndef lint
32 static const char copyright[] =
33 "@(#) Copyright (c) 1980, 1986, 1993\n\
34 	The Regents of the University of California.  All rights reserved.\n";
35 #endif /* not lint */
36 
37 #ifndef lint
38 static char sccsid[] = "@(#)main.c	8.6 (Berkeley) 5/14/95";
39 #endif /* not lint */
40 #endif
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
43 
44 #include <sys/param.h>
45 #include <sys/stat.h>
46 #include <sys/file.h>
47 #include <sys/time.h>
48 #include <sys/mount.h>
49 #include <sys/resource.h>
50 #include <sys/sysctl.h>
51 #include <sys/uio.h>
52 #include <sys/disklabel.h>
53 
54 #include <ufs/ufs/dinode.h>
55 #include <ufs/ffs/fs.h>
56 
57 #include <err.h>
58 #include <errno.h>
59 #include <fstab.h>
60 #include <grp.h>
61 #include <mntopts.h>
62 #include <paths.h>
63 #include <stdint.h>
64 #include <string.h>
65 
66 #include "fsck.h"
67 
68 static void usage(void) __dead2;
69 static int argtoi(int flag, const char *req, const char *str, int base);
70 static int checkfilesys(char *filesys);
71 static int chkdoreload(struct statfs *mntp);
72 static struct statfs *getmntpt(const char *);
73 
74 int
75 main(int argc, char *argv[])
76 {
77 	int ch;
78 	struct rlimit rlimit;
79 	struct itimerval itimerval;
80 	int ret = 0;
81 
82 	sync();
83 	skipclean = 1;
84 	catastrophicflag = 0;
85 	while ((ch = getopt(argc, argv, "b:Bc:CdfFm:npy")) != -1) {
86 		switch (ch) {
87 		case 'b':
88 			skipclean = 0;
89 			bflag = argtoi('b', "number", optarg, 10);
90 			printf("Alternate super block location: %d\n", bflag);
91 			break;
92 
93 		case 'B':
94 			bkgrdflag = 1;
95 			break;
96 
97 		case 'c':
98 			skipclean = 0;
99 			cvtlevel = argtoi('c', "conversion level", optarg, 10);
100 			if (cvtlevel < 3)
101 				errx(EEXIT, "cannot do level %d conversion",
102 				    cvtlevel);
103 			break;
104 
105 		case 'd':
106 			debug++;
107 			break;
108 
109 		case 'C':
110 			catastrophicflag = 1;
111 			/* FALLTHROUGH */
112 
113 		case 'f':
114 			skipclean = 0;
115 			break;
116 
117 		case 'F':
118 			bkgrdcheck = 1;
119 			break;
120 
121 		case 'm':
122 			lfmode = argtoi('m', "mode", optarg, 8);
123 			if (lfmode &~ 07777)
124 				errx(EEXIT, "bad mode to -m: %o", lfmode);
125 			printf("** lost+found creation mode %o\n", lfmode);
126 			break;
127 
128 		case 'n':
129 			nflag++;
130 			yflag = 0;
131 			break;
132 
133 		case 'p':
134 			preen++;
135 			break;
136 
137 		case 'y':
138 			yflag++;
139 			nflag = 0;
140 			break;
141 
142 		default:
143 			usage();
144 		}
145 	}
146 	argc -= optind;
147 	argv += optind;
148 
149 	if (!argc)
150 		usage();
151 
152 	if (signal(SIGINT, SIG_IGN) != SIG_IGN)
153 		(void)signal(SIGINT, catch);
154 	if (preen)
155 		(void)signal(SIGQUIT, catchquit);
156 	signal(SIGINFO, infohandler);
157 	if (bkgrdflag) {
158 		signal(SIGALRM, alarmhandler);
159 		itimerval.it_interval.tv_sec = 5;
160 		itimerval.it_interval.tv_usec = 0;
161 		itimerval.it_value.tv_sec = 5;
162 		itimerval.it_value.tv_usec = 0;
163 		setitimer(ITIMER_REAL, &itimerval, NULL);
164 	}
165 	/*
166 	 * Push up our allowed memory limit so we can cope
167 	 * with huge file systems.
168 	 */
169 	if (getrlimit(RLIMIT_DATA, &rlimit) == 0) {
170 		rlimit.rlim_cur = rlimit.rlim_max;
171 		(void)setrlimit(RLIMIT_DATA, &rlimit);
172 	}
173 	while (argc-- > 0)
174 		(void)checkfilesys(*argv++);
175 
176 	if (returntosingle)
177 		ret = 2;
178 	exit(ret);
179 }
180 
181 static int
182 argtoi(int flag, const char *req, const char *str, int base)
183 {
184 	char *cp;
185 	int ret;
186 
187 	ret = (int)strtol(str, &cp, base);
188 	if (cp == str || *cp)
189 		errx(EEXIT, "-%c flag requires a %s", flag, req);
190 	return (ret);
191 }
192 
193 /*
194  * Check the specified file system.
195  */
196 /* ARGSUSED */
197 static int
198 checkfilesys(char *filesys)
199 {
200 	ufs2_daddr_t n_ffree, n_bfree;
201 	struct dups *dp;
202 	struct statfs *mntp;
203 	struct stat snapdir;
204 	struct group *grp;
205 	ufs2_daddr_t blks;
206 	struct iovec *iov;
207 	char errmsg[255];
208 	int iovlen;
209 	int cylno;
210 	ino_t files;
211 	size_t size;
212 
213 	iov = NULL;
214 	iovlen = 0;
215 	errmsg[0] = '\0';
216 
217 	cdevname = filesys;
218 	if (debug && preen)
219 		pwarn("starting\n");
220 	/*
221 	 * Make best effort to get the disk name. Check first to see
222 	 * if it is listed among the mounted file systems. Failing that
223 	 * check to see if it is listed in /etc/fstab.
224 	 */
225 	mntp = getmntpt(filesys);
226 	if (mntp != NULL)
227 		filesys = mntp->f_mntfromname;
228 	else
229 		filesys = blockcheck(filesys);
230 	/*
231 	 * If -F flag specified, check to see whether a background check
232 	 * is possible and needed. If possible and needed, exit with
233 	 * status zero. Otherwise exit with status non-zero. A non-zero
234 	 * exit status will cause a foreground check to be run.
235 	 */
236 	sblock_init();
237 	if (bkgrdcheck) {
238 		if ((fsreadfd = open(filesys, O_RDONLY)) < 0 || readsb(0) == 0)
239 			exit(3);	/* Cannot read superblock */
240 		close(fsreadfd);
241 		if (sblock.fs_flags & FS_NEEDSFSCK)
242 			exit(4);	/* Earlier background failed */
243 		if ((sblock.fs_flags & FS_DOSOFTDEP) == 0)
244 			exit(5);	/* Not running soft updates */
245 		size = MIBSIZE;
246 		if (sysctlnametomib("vfs.ffs.adjrefcnt", adjrefcnt, &size) < 0)
247 			exit(6);	/* Lacks kernel support */
248 		if ((mntp == NULL && sblock.fs_clean == 1) ||
249 		    (mntp != NULL && (sblock.fs_flags & FS_UNCLEAN) == 0))
250 			exit(7);	/* Filesystem clean, report it now */
251 		exit(0);
252 	}
253 	if (preen && skipclean) {
254 		/*
255 		 * If file system is gjournaled, check it here.
256 		 */
257 		if ((fsreadfd = open(filesys, O_RDONLY)) < 0 || readsb(0) == 0)
258 			exit(3);	/* Cannot read superblock */
259 		close(fsreadfd);
260 		if ((sblock.fs_flags & FS_GJOURNAL) != 0) {
261 			//printf("GJournaled file system detected on %s.\n",
262 			//    filesys);
263 			if (sblock.fs_clean == 1) {
264 				pwarn("FILE SYSTEM CLEAN; SKIPPING CHECKS\n");
265 				exit(0);
266 			}
267 			if ((sblock.fs_flags & (FS_UNCLEAN | FS_NEEDSFSCK)) == 0) {
268 				gjournal_check(filesys);
269 				if (chkdoreload(mntp) == 0)
270 					exit(0);
271 				exit(4);
272 			} else {
273 				pfatal("UNEXPECTED INCONSISTENCY, %s\n",
274 				    "CANNOT RUN FAST FSCK\n");
275 			}
276 		}
277 	}
278 	/*
279 	 * If we are to do a background check:
280 	 *	Get the mount point information of the file system
281 	 *	create snapshot file
282 	 *	return created snapshot file
283 	 *	if not found, clear bkgrdflag and proceed with normal fsck
284 	 */
285 	if (bkgrdflag) {
286 		if (mntp == NULL) {
287 			bkgrdflag = 0;
288 			pfatal("NOT MOUNTED, CANNOT RUN IN BACKGROUND\n");
289 		} else if ((mntp->f_flags & MNT_SOFTDEP) == 0) {
290 			bkgrdflag = 0;
291 			pfatal("NOT USING SOFT UPDATES, %s\n",
292 			    "CANNOT RUN IN BACKGROUND");
293 		} else if ((mntp->f_flags & MNT_RDONLY) != 0) {
294 			bkgrdflag = 0;
295 			pfatal("MOUNTED READ-ONLY, CANNOT RUN IN BACKGROUND\n");
296 		} else if ((fsreadfd = open(filesys, O_RDONLY)) >= 0) {
297 			if (readsb(0) != 0) {
298 				if (sblock.fs_flags & FS_NEEDSFSCK) {
299 					bkgrdflag = 0;
300 					pfatal("UNEXPECTED INCONSISTENCY, %s\n",
301 					    "CANNOT RUN IN BACKGROUND\n");
302 				}
303 				if ((sblock.fs_flags & FS_UNCLEAN) == 0 &&
304 				    skipclean && preen) {
305 					/*
306 					 * file system is clean;
307 					 * skip snapshot and report it clean
308 					 */
309 					pwarn("FILE SYSTEM CLEAN; %s\n",
310 					    "SKIPPING CHECKS");
311 					goto clean;
312 				}
313 			}
314 			close(fsreadfd);
315 		}
316 		if (bkgrdflag) {
317 			snprintf(snapname, sizeof snapname, "%s/.snap",
318 			    mntp->f_mntonname);
319 			if (stat(snapname, &snapdir) < 0) {
320 				if (errno != ENOENT) {
321 					bkgrdflag = 0;
322 					pfatal("CANNOT FIND %s %s: %s, %s\n",
323 					    "SNAPSHOT DIRECTORY",
324 					    snapname, strerror(errno),
325 					    "CANNOT RUN IN BACKGROUND");
326 				} else if ((grp = getgrnam("operator")) == 0 ||
327 				    mkdir(snapname, 0770) < 0 ||
328 				    chown(snapname, -1, grp->gr_gid) < 0 ||
329 				    chmod(snapname, 0770) < 0) {
330 					bkgrdflag = 0;
331 					pfatal("CANNOT CREATE %s %s: %s, %s\n",
332 					    "SNAPSHOT DIRECTORY",
333 					    snapname, strerror(errno),
334 					    "CANNOT RUN IN BACKGROUND");
335 				}
336 			} else if (!S_ISDIR(snapdir.st_mode)) {
337 				bkgrdflag = 0;
338 				pfatal("%s IS NOT A DIRECTORY, %s\n", snapname,
339 				    "CANNOT RUN IN BACKGROUND");
340 			}
341 		}
342 		if (bkgrdflag) {
343 			snprintf(snapname, sizeof snapname,
344 			    "%s/.snap/fsck_snapshot", mntp->f_mntonname);
345 			build_iovec(&iov, &iovlen, "fstype", "ffs", 4);
346 			build_iovec(&iov, &iovlen, "from", snapname,
347 			    (size_t)-1);
348 			build_iovec(&iov, &iovlen, "fspath", mntp->f_mntonname,
349 			    (size_t)-1);
350 			build_iovec(&iov, &iovlen, "errmsg", errmsg,
351 			    sizeof(errmsg));
352 			build_iovec(&iov, &iovlen, "update", NULL, 0);
353 			build_iovec(&iov, &iovlen, "snapshot", NULL, 0);
354 
355 			while (nmount(iov, iovlen, mntp->f_flags) < 0) {
356 				if (errno == EEXIST && unlink(snapname) == 0)
357 					continue;
358 				bkgrdflag = 0;
359 				pfatal("CANNOT CREATE SNAPSHOT %s: %s %s\n",
360 				    snapname, strerror(errno), errmsg);
361 				break;
362 			}
363 			if (bkgrdflag != 0)
364 				filesys = snapname;
365 		}
366 	}
367 
368 	switch (setup(filesys)) {
369 	case 0:
370 		if (preen)
371 			pfatal("CAN'T CHECK FILE SYSTEM.");
372 		return (0);
373 	case -1:
374 	clean:
375 		pwarn("clean, %ld free ", (long)(sblock.fs_cstotal.cs_nffree +
376 		    sblock.fs_frag * sblock.fs_cstotal.cs_nbfree));
377 		printf("(%lld frags, %lld blocks, %.1f%% fragmentation)\n",
378 		    (long long)sblock.fs_cstotal.cs_nffree,
379 		    (long long)sblock.fs_cstotal.cs_nbfree,
380 		    sblock.fs_cstotal.cs_nffree * 100.0 / sblock.fs_dsize);
381 		return (0);
382 	}
383 
384 	/*
385 	 * Cleared if any questions answered no. Used to decide if
386 	 * the superblock should be marked clean.
387 	 */
388 	resolved = 1;
389 	/*
390 	 * 1: scan inodes tallying blocks used
391 	 */
392 	if (preen == 0) {
393 		printf("** Last Mounted on %s\n", sblock.fs_fsmnt);
394 		if (mntp != NULL && mntp->f_flags & MNT_ROOTFS)
395 			printf("** Root file system\n");
396 		printf("** Phase 1 - Check Blocks and Sizes\n");
397 	}
398 	pass1();
399 
400 	/*
401 	 * 1b: locate first references to duplicates, if any
402 	 */
403 	if (duplist) {
404 		if (preen || usedsoftdep)
405 			pfatal("INTERNAL ERROR: dups with -p");
406 		printf("** Phase 1b - Rescan For More DUPS\n");
407 		pass1b();
408 	}
409 
410 	/*
411 	 * 2: traverse directories from root to mark all connected directories
412 	 */
413 	if (preen == 0)
414 		printf("** Phase 2 - Check Pathnames\n");
415 	pass2();
416 
417 	/*
418 	 * 3: scan inodes looking for disconnected directories
419 	 */
420 	if (preen == 0)
421 		printf("** Phase 3 - Check Connectivity\n");
422 	pass3();
423 
424 	/*
425 	 * 4: scan inodes looking for disconnected files; check reference counts
426 	 */
427 	if (preen == 0)
428 		printf("** Phase 4 - Check Reference Counts\n");
429 	pass4();
430 
431 	/*
432 	 * 5: check and repair resource counts in cylinder groups
433 	 */
434 	if (preen == 0)
435 		printf("** Phase 5 - Check Cyl groups\n");
436 	pass5();
437 
438 	/*
439 	 * print out summary statistics
440 	 */
441 	n_ffree = sblock.fs_cstotal.cs_nffree;
442 	n_bfree = sblock.fs_cstotal.cs_nbfree;
443 	files = maxino - ROOTINO - sblock.fs_cstotal.cs_nifree - n_files;
444 	blks = n_blks +
445 	    sblock.fs_ncg * (cgdmin(&sblock, 0) - cgsblock(&sblock, 0));
446 	blks += cgsblock(&sblock, 0) - cgbase(&sblock, 0);
447 	blks += howmany(sblock.fs_cssize, sblock.fs_fsize);
448 	blks = maxfsblock - (n_ffree + sblock.fs_frag * n_bfree) - blks;
449 	if (bkgrdflag && (files > 0 || blks > 0)) {
450 		countdirs = sblock.fs_cstotal.cs_ndir - countdirs;
451 		pwarn("Reclaimed: %ld directories, %ld files, %lld fragments\n",
452 		    countdirs, (long)files - countdirs, (long long)blks);
453 	}
454 	pwarn("%ld files, %jd used, %ju free ",
455 	    (long)n_files, (intmax_t)n_blks,
456 	    (uintmax_t)n_ffree + sblock.fs_frag * n_bfree);
457 	printf("(%ju frags, %ju blocks, %.1f%% fragmentation)\n",
458 	    (uintmax_t)n_ffree, (uintmax_t)n_bfree,
459 	    n_ffree * 100.0 / sblock.fs_dsize);
460 	if (debug) {
461 		if (files < 0)
462 			printf("%d inodes missing\n", -files);
463 		if (blks < 0)
464 			printf("%lld blocks missing\n", -(long long)blks);
465 		if (duplist != NULL) {
466 			printf("The following duplicate blocks remain:");
467 			for (dp = duplist; dp; dp = dp->next)
468 				printf(" %lld,", (long long)dp->dup);
469 			printf("\n");
470 		}
471 	}
472 	duplist = (struct dups *)0;
473 	muldup = (struct dups *)0;
474 	inocleanup();
475 	if (fsmodified) {
476 		sblock.fs_time = time(NULL);
477 		sbdirty();
478 	}
479 	if (cvtlevel && sblk.b_dirty) {
480 		/*
481 		 * Write out the duplicate super blocks
482 		 */
483 		for (cylno = 0; cylno < sblock.fs_ncg; cylno++)
484 			blwrite(fswritefd, (char *)&sblock,
485 			    fsbtodb(&sblock, cgsblock(&sblock, cylno)),
486 			    SBLOCKSIZE);
487 	}
488 	if (rerun)
489 		resolved = 0;
490 
491 	/*
492 	 * Check to see if the file system is mounted read-write.
493 	 */
494 	if (bkgrdflag == 0 && mntp != NULL && (mntp->f_flags & MNT_RDONLY) == 0)
495 		resolved = 0;
496 	ckfini(resolved);
497 
498 	for (cylno = 0; cylno < sblock.fs_ncg; cylno++)
499 		if (inostathead[cylno].il_stat != NULL)
500 			free((char *)inostathead[cylno].il_stat);
501 	free((char *)inostathead);
502 	inostathead = NULL;
503 	if (fsmodified && !preen)
504 		printf("\n***** FILE SYSTEM WAS MODIFIED *****\n");
505 	if (rerun)
506 		printf("\n***** PLEASE RERUN FSCK *****\n");
507 	if (chkdoreload(mntp) != 0) {
508 		if (!fsmodified)
509 			return (0);
510 		if (!preen)
511 			printf("\n***** REBOOT NOW *****\n");
512 		sync();
513 		return (4);
514 	}
515 	return (0);
516 }
517 
518 static int
519 chkdoreload(struct statfs *mntp)
520 {
521 	struct iovec *iov;
522 	int iovlen;
523 	char errmsg[255];
524 
525 	if (mntp == NULL)
526 		return (0);
527 
528 	iov = NULL;
529 	iovlen = 0;
530 	errmsg[0] = '\0';
531 	/*
532 	 * We modified a mounted file system.  Do a mount update on
533 	 * it unless it is read-write, so we can continue using it
534 	 * as safely as possible.
535 	 */
536 	if (mntp->f_flags & MNT_RDONLY) {
537 		build_iovec(&iov, &iovlen, "fstype", "ffs", 4);
538 		build_iovec(&iov, &iovlen, "from", mntp->f_mntfromname,
539 		    (size_t)-1);
540 		build_iovec(&iov, &iovlen, "fspath", mntp->f_mntonname,
541 		    (size_t)-1);
542 		build_iovec(&iov, &iovlen, "errmsg", errmsg,
543 		    sizeof(errmsg));
544 		build_iovec(&iov, &iovlen, "update", NULL, 0);
545 		build_iovec(&iov, &iovlen, "reload", NULL, 0);
546 		/*
547 		 * XX: We need the following line until we clean up
548 		 * nmount parsing of root mounts and NFS root mounts.
549 		 */
550 		build_iovec(&iov, &iovlen, "ro", NULL, 0);
551 		if (nmount(iov, iovlen, mntp->f_flags) == 0) {
552 			return (0);
553 		}
554 		pwarn("mount reload of '%s' failed: %s %s\n\n",
555 		    mntp->f_mntonname, strerror(errno), errmsg);
556 		return (1);
557 	}
558 	return (0);
559 }
560 
561 /*
562  * Get the mount point information for name.
563  */
564 static struct statfs *
565 getmntpt(const char *name)
566 {
567 	struct stat devstat, mntdevstat;
568 	char device[sizeof(_PATH_DEV) - 1 + MNAMELEN];
569 	char *ddevname;
570 	struct statfs *mntbuf, *statfsp;
571 	int i, mntsize, isdev;
572 
573 	if (stat(name, &devstat) != 0)
574 		return (NULL);
575 	if (S_ISCHR(devstat.st_mode) || S_ISBLK(devstat.st_mode))
576 		isdev = 1;
577 	else
578 		isdev = 0;
579 	mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
580 	for (i = 0; i < mntsize; i++) {
581 		statfsp = &mntbuf[i];
582 		ddevname = statfsp->f_mntfromname;
583 		if (*ddevname != '/') {
584 			strcpy(device, _PATH_DEV);
585 			strcat(device, ddevname);
586 			strcpy(statfsp->f_mntfromname, device);
587 		}
588 		if (isdev == 0) {
589 			if (strcmp(name, statfsp->f_mntonname))
590 				continue;
591 			return (statfsp);
592 		}
593 		if (stat(ddevname, &mntdevstat) == 0 &&
594 		    mntdevstat.st_rdev == devstat.st_rdev)
595 			return (statfsp);
596 	}
597 	statfsp = NULL;
598 	return (statfsp);
599 }
600 
601 static void
602 usage(void)
603 {
604         (void) fprintf(stderr,
605             "usage: %s [-BCFpfny] [-b block] [-c level] [-m mode] "
606                         "filesystem ...\n",
607             getprogname());
608         exit(1);
609 }
610