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
32static 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
38static 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/file.h>
46#include <sys/mount.h>
47#include <sys/resource.h>
48#include <sys/stat.h>
49#include <sys/sysctl.h>
50#include <sys/uio.h>
51#include <sys/disklabel.h>
52
53#include <ufs/ufs/dinode.h>
54#include <ufs/ffs/fs.h>
55
56#include <err.h>
57#include <errno.h>
58#include <fstab.h>
59#include <grp.h>
60#include <mntopts.h>
61#include <paths.h>
62#include <stdint.h>
63#include <string.h>
64#include <time.h>
65
66#include "fsck.h"
67
68int	restarts;
69
70static void usage(void) __dead2;
71static int argtoi(int flag, const char *req, const char *str, int base);
72static int checkfilesys(char *filesys);
73static int chkdoreload(struct statfs *mntp);
74static struct statfs *getmntpt(const char *);
75
76int
77main(int argc, char *argv[])
78{
79	int ch;
80	struct rlimit rlimit;
81	struct itimerval itimerval;
82	int ret = 0;
83
84	sync();
85	skipclean = 1;
86	inoopt = 0;
87	while ((ch = getopt(argc, argv, "b:Bc:CdEfFm:npRrSyZ")) != -1) {
88		switch (ch) {
89		case 'b':
90			skipclean = 0;
91			bflag = argtoi('b', "number", optarg, 10);
92			printf("Alternate super block location: %d\n", bflag);
93			break;
94
95		case 'B':
96			bkgrdflag = 1;
97			break;
98
99		case 'c':
100			skipclean = 0;
101			cvtlevel = argtoi('c', "conversion level", optarg, 10);
102			if (cvtlevel < 3)
103				errx(EEXIT, "cannot do level %d conversion",
104				    cvtlevel);
105			break;
106
107		case 'd':
108			debug++;
109			break;
110
111		case 'E':
112			Eflag++;
113			break;
114
115		case 'f':
116			skipclean = 0;
117			break;
118
119		case 'F':
120			bkgrdcheck = 1;
121			break;
122
123		case 'm':
124			lfmode = argtoi('m', "mode", optarg, 8);
125			if (lfmode &~ 07777)
126				errx(EEXIT, "bad mode to -m: %o", lfmode);
127			printf("** lost+found creation mode %o\n", lfmode);
128			break;
129
130		case 'n':
131			nflag++;
132			yflag = 0;
133			break;
134
135		case 'p':
136			preen++;
137			/*FALLTHROUGH*/
138
139		case 'C':
140			ckclean++;
141			break;
142
143		case 'R':
144			wantrestart = 1;
145			break;
146		case 'r':
147			inoopt++;
148			break;
149
150		case 'S':
151			surrender = 1;
152			break;
153
154		case 'y':
155			yflag++;
156			nflag = 0;
157			break;
158
159		case 'Z':
160			Zflag++;
161			break;
162
163		default:
164			usage();
165		}
166	}
167	argc -= optind;
168	argv += optind;
169
170	if (!argc)
171		usage();
172
173	if (signal(SIGINT, SIG_IGN) != SIG_IGN)
174		(void)signal(SIGINT, catch);
175	if (ckclean)
176		(void)signal(SIGQUIT, catchquit);
177	signal(SIGINFO, infohandler);
178	if (bkgrdflag) {
179		signal(SIGALRM, alarmhandler);
180		itimerval.it_interval.tv_sec = 5;
181		itimerval.it_interval.tv_usec = 0;
182		itimerval.it_value.tv_sec = 5;
183		itimerval.it_value.tv_usec = 0;
184		setitimer(ITIMER_REAL, &itimerval, NULL);
185	}
186	/*
187	 * Push up our allowed memory limit so we can cope
188	 * with huge file systems.
189	 */
190	if (getrlimit(RLIMIT_DATA, &rlimit) == 0) {
191		rlimit.rlim_cur = rlimit.rlim_max;
192		(void)setrlimit(RLIMIT_DATA, &rlimit);
193	}
194	while (argc > 0) {
195		if (checkfilesys(*argv) == ERESTART)
196			continue;
197		argc--;
198		argv++;
199	}
200
201	if (returntosingle)
202		ret = 2;
203	exit(ret);
204}
205
206static int
207argtoi(int flag, const char *req, const char *str, int base)
208{
209	char *cp;
210	int ret;
211
212	ret = (int)strtol(str, &cp, base);
213	if (cp == str || *cp)
214		errx(EEXIT, "-%c flag requires a %s", flag, req);
215	return (ret);
216}
217
218/*
219 * Check the specified file system.
220 */
221/* ARGSUSED */
222static int
223checkfilesys(char *filesys)
224{
225	ufs2_daddr_t n_ffree, n_bfree;
226	struct dups *dp;
227	struct statfs *mntp;
228	struct stat snapdir;
229	struct group *grp;
230	struct iovec *iov;
231	char errmsg[255];
232	int iovlen;
233	int cylno;
234	intmax_t blks, files;
235	size_t size;
236
237	iov = NULL;
238	iovlen = 0;
239	errmsg[0] = '\0';
240	fsutilinit();
241	fsckinit();
242
243	cdevname = filesys;
244	if (debug && ckclean)
245		pwarn("starting\n");
246	/*
247	 * Make best effort to get the disk name. Check first to see
248	 * if it is listed among the mounted file systems. Failing that
249	 * check to see if it is listed in /etc/fstab.
250	 */
251	mntp = getmntpt(filesys);
252	if (mntp != NULL)
253		filesys = mntp->f_mntfromname;
254	else
255		filesys = blockcheck(filesys);
256	/*
257	 * If -F flag specified, check to see whether a background check
258	 * is possible and needed. If possible and needed, exit with
259	 * status zero. Otherwise exit with status non-zero. A non-zero
260	 * exit status will cause a foreground check to be run.
261	 */
262	sblock_init();
263	if (bkgrdcheck) {
264		if ((fsreadfd = open(filesys, O_RDONLY)) < 0 || readsb(0) == 0)
265			exit(3);	/* Cannot read superblock */
266		close(fsreadfd);
267		/* Earlier background failed or journaled */
268		if (sblock.fs_flags & (FS_NEEDSFSCK | FS_SUJ))
269			exit(4);
270		if ((sblock.fs_flags & FS_DOSOFTDEP) == 0)
271			exit(5);	/* Not running soft updates */
272		size = MIBSIZE;
273		if (sysctlnametomib("vfs.ffs.adjrefcnt", adjrefcnt, &size) < 0)
274			exit(6);	/* Lacks kernel support */
275		if ((mntp == NULL && sblock.fs_clean == 1) ||
276		    (mntp != NULL && (sblock.fs_flags & FS_UNCLEAN) == 0))
277			exit(7);	/* Filesystem clean, report it now */
278		exit(0);
279	}
280	if (ckclean && skipclean) {
281		/*
282		 * If file system is gjournaled, check it here.
283		 */
284		if ((fsreadfd = open(filesys, O_RDONLY)) < 0 || readsb(0) == 0)
285			exit(3);	/* Cannot read superblock */
286		close(fsreadfd);
287		if ((sblock.fs_flags & FS_GJOURNAL) != 0) {
288			//printf("GJournaled file system detected on %s.\n",
289			//    filesys);
290			if (sblock.fs_clean == 1) {
291				pwarn("FILE SYSTEM CLEAN; SKIPPING CHECKS\n");
292				exit(0);
293			}
294			if ((sblock.fs_flags & (FS_UNCLEAN | FS_NEEDSFSCK)) == 0) {
295				gjournal_check(filesys);
296				if (chkdoreload(mntp) == 0)
297					exit(0);
298				exit(4);
299			} else {
300				pfatal(
301			    "UNEXPECTED INCONSISTENCY, CANNOT RUN FAST FSCK\n");
302			}
303		}
304	}
305	/*
306	 * If we are to do a background check:
307	 *	Get the mount point information of the file system
308	 *	create snapshot file
309	 *	return created snapshot file
310	 *	if not found, clear bkgrdflag and proceed with normal fsck
311	 */
312	if (bkgrdflag) {
313		if (mntp == NULL) {
314			bkgrdflag = 0;
315			pfatal("NOT MOUNTED, CANNOT RUN IN BACKGROUND\n");
316		} else if ((mntp->f_flags & MNT_SOFTDEP) == 0) {
317			bkgrdflag = 0;
318			pfatal(
319			  "NOT USING SOFT UPDATES, CANNOT RUN IN BACKGROUND\n");
320		} else if ((mntp->f_flags & MNT_RDONLY) != 0) {
321			bkgrdflag = 0;
322			pfatal("MOUNTED READ-ONLY, CANNOT RUN IN BACKGROUND\n");
323		} else if ((fsreadfd = open(filesys, O_RDONLY)) >= 0) {
324			if (readsb(0) != 0) {
325				if (sblock.fs_flags & (FS_NEEDSFSCK | FS_SUJ)) {
326					bkgrdflag = 0;
327					pfatal(
328			"UNEXPECTED INCONSISTENCY, CANNOT RUN IN BACKGROUND\n");
329				}
330				if ((sblock.fs_flags & FS_UNCLEAN) == 0 &&
331				    skipclean && ckclean) {
332					/*
333					 * file system is clean;
334					 * skip snapshot and report it clean
335					 */
336					pwarn(
337					"FILE SYSTEM CLEAN; SKIPPING CHECKS\n");
338					goto clean;
339				}
340			}
341			close(fsreadfd);
342		}
343		if (bkgrdflag) {
344			snprintf(snapname, sizeof snapname, "%s/.snap",
345			    mntp->f_mntonname);
346			if (stat(snapname, &snapdir) < 0) {
347				if (errno != ENOENT) {
348					bkgrdflag = 0;
349					pfatal(
350	"CANNOT FIND SNAPSHOT DIRECTORY %s: %s, CANNOT RUN IN BACKGROUND\n",
351					    snapname, strerror(errno));
352				} else if ((grp = getgrnam("operator")) == 0 ||
353				    mkdir(snapname, 0770) < 0 ||
354				    chown(snapname, -1, grp->gr_gid) < 0 ||
355				    chmod(snapname, 0770) < 0) {
356					bkgrdflag = 0;
357					pfatal(
358	"CANNOT CREATE SNAPSHOT DIRECTORY %s: %s, CANNOT RUN IN BACKGROUND\n",
359					    snapname, strerror(errno));
360				}
361			} else if (!S_ISDIR(snapdir.st_mode)) {
362				bkgrdflag = 0;
363				pfatal(
364			"%s IS NOT A DIRECTORY, CANNOT RUN IN BACKGROUND\n",
365				    snapname);
366			}
367		}
368		if (bkgrdflag) {
369			snprintf(snapname, sizeof snapname,
370			    "%s/.snap/fsck_snapshot", mntp->f_mntonname);
371			build_iovec(&iov, &iovlen, "fstype", "ffs", 4);
372			build_iovec(&iov, &iovlen, "from", snapname,
373			    (size_t)-1);
374			build_iovec(&iov, &iovlen, "fspath", mntp->f_mntonname,
375			    (size_t)-1);
376			build_iovec(&iov, &iovlen, "errmsg", errmsg,
377			    sizeof(errmsg));
378			build_iovec(&iov, &iovlen, "update", NULL, 0);
379			build_iovec(&iov, &iovlen, "snapshot", NULL, 0);
380
381			while (nmount(iov, iovlen, mntp->f_flags) < 0) {
382				if (errno == EEXIST && unlink(snapname) == 0)
383					continue;
384				bkgrdflag = 0;
385				pfatal("CANNOT CREATE SNAPSHOT %s: %s %s\n",
386				    snapname, strerror(errno), errmsg);
387				break;
388			}
389			if (bkgrdflag != 0)
390				filesys = snapname;
391		}
392	}
393
394	switch (setup(filesys)) {
395	case 0:
396		if (preen)
397			pfatal("CAN'T CHECK FILE SYSTEM.");
398		return (0);
399	case -1:
400	clean:
401		pwarn("clean, %ld free ", (long)(sblock.fs_cstotal.cs_nffree +
402		    sblock.fs_frag * sblock.fs_cstotal.cs_nbfree));
403		printf("(%jd frags, %jd blocks, %.1f%% fragmentation)\n",
404		    (intmax_t)sblock.fs_cstotal.cs_nffree,
405		    (intmax_t)sblock.fs_cstotal.cs_nbfree,
406		    sblock.fs_cstotal.cs_nffree * 100.0 / sblock.fs_dsize);
407		return (0);
408	}
409	/*
410	 * Determine if we can and should do journal recovery.
411	 */
412	if ((sblock.fs_flags & FS_SUJ) == FS_SUJ) {
413		if ((sblock.fs_flags & FS_NEEDSFSCK) != FS_NEEDSFSCK && skipclean) {
414			if (preen || reply("USE JOURNAL")) {
415				if (suj_check(filesys) == 0) {
416					printf("\n***** FILE SYSTEM MARKED CLEAN *****\n");
417					if (chkdoreload(mntp) == 0)
418						exit(0);
419					exit(4);
420				}
421			}
422			printf("** Skipping journal, falling through to full fsck\n\n");
423		}
424		/*
425		 * Write the superblock so we don't try to recover the
426		 * journal on another pass.
427		 */
428		sblock.fs_mtime = time(NULL);
429		sbdirty();
430	}
431
432	/*
433	 * Cleared if any questions answered no. Used to decide if
434	 * the superblock should be marked clean.
435	 */
436	resolved = 1;
437	/*
438	 * 1: scan inodes tallying blocks used
439	 */
440	if (preen == 0) {
441		printf("** Last Mounted on %s\n", sblock.fs_fsmnt);
442		if (mntp != NULL && mntp->f_flags & MNT_ROOTFS)
443			printf("** Root file system\n");
444		printf("** Phase 1 - Check Blocks and Sizes\n");
445	}
446	clock_gettime(CLOCK_REALTIME_PRECISE, &startprog);
447	pass1();
448	IOstats("Pass1");
449
450	/*
451	 * 1b: locate first references to duplicates, if any
452	 */
453	if (duplist) {
454		if (preen || usedsoftdep)
455			pfatal("INTERNAL ERROR: dups with %s%s%s",
456			    preen ? "-p" : "",
457			    (preen && usedsoftdep) ? " and " : "",
458			    usedsoftdep ? "softupdates" : "");
459		printf("** Phase 1b - Rescan For More DUPS\n");
460		pass1b();
461		IOstats("Pass1b");
462	}
463
464	/*
465	 * 2: traverse directories from root to mark all connected directories
466	 */
467	if (preen == 0)
468		printf("** Phase 2 - Check Pathnames\n");
469	pass2();
470	IOstats("Pass2");
471
472	/*
473	 * 3: scan inodes looking for disconnected directories
474	 */
475	if (preen == 0)
476		printf("** Phase 3 - Check Connectivity\n");
477	pass3();
478	IOstats("Pass3");
479
480	/*
481	 * 4: scan inodes looking for disconnected files; check reference counts
482	 */
483	if (preen == 0)
484		printf("** Phase 4 - Check Reference Counts\n");
485	pass4();
486	IOstats("Pass4");
487
488	/*
489	 * 5: check and repair resource counts in cylinder groups
490	 */
491	if (preen == 0)
492		printf("** Phase 5 - Check Cyl groups\n");
493	pass5();
494	IOstats("Pass5");
495
496	/*
497	 * print out summary statistics
498	 */
499	n_ffree = sblock.fs_cstotal.cs_nffree;
500	n_bfree = sblock.fs_cstotal.cs_nbfree;
501	files = maxino - ROOTINO - sblock.fs_cstotal.cs_nifree - n_files;
502	blks = n_blks +
503	    sblock.fs_ncg * (cgdmin(&sblock, 0) - cgsblock(&sblock, 0));
504	blks += cgsblock(&sblock, 0) - cgbase(&sblock, 0);
505	blks += howmany(sblock.fs_cssize, sblock.fs_fsize);
506	blks = maxfsblock - (n_ffree + sblock.fs_frag * n_bfree) - blks;
507	if (bkgrdflag && (files > 0 || blks > 0)) {
508		countdirs = sblock.fs_cstotal.cs_ndir - countdirs;
509		pwarn("Reclaimed: %ld directories, %jd files, %jd fragments\n",
510		    countdirs, files - countdirs, blks);
511	}
512	pwarn("%ld files, %jd used, %ju free ",
513	    (long)n_files, (intmax_t)n_blks,
514	    (uintmax_t)n_ffree + sblock.fs_frag * n_bfree);
515	printf("(%ju frags, %ju blocks, %.1f%% fragmentation)\n",
516	    (uintmax_t)n_ffree, (uintmax_t)n_bfree,
517	    n_ffree * 100.0 / sblock.fs_dsize);
518	if (debug) {
519		if (files < 0)
520			printf("%jd inodes missing\n", -files);
521		if (blks < 0)
522			printf("%jd blocks missing\n", -blks);
523		if (duplist != NULL) {
524			printf("The following duplicate blocks remain:");
525			for (dp = duplist; dp; dp = dp->next)
526				printf(" %jd,", (intmax_t)dp->dup);
527			printf("\n");
528		}
529	}
530	duplist = (struct dups *)0;
531	muldup = (struct dups *)0;
532	inocleanup();
533	if (fsmodified) {
534		sblock.fs_time = time(NULL);
535		sbdirty();
536	}
537	if (cvtlevel && sblk.b_dirty) {
538		/*
539		 * Write out the duplicate super blocks
540		 */
541		for (cylno = 0; cylno < sblock.fs_ncg; cylno++)
542			blwrite(fswritefd, (char *)&sblock,
543			    fsbtodb(&sblock, cgsblock(&sblock, cylno)),
544			    SBLOCKSIZE);
545	}
546	if (rerun)
547		resolved = 0;
548	finalIOstats();
549
550	/*
551	 * Check to see if the file system is mounted read-write.
552	 */
553	if (bkgrdflag == 0 && mntp != NULL && (mntp->f_flags & MNT_RDONLY) == 0)
554		resolved = 0;
555	ckfini(resolved);
556
557	for (cylno = 0; cylno < sblock.fs_ncg; cylno++)
558		if (inostathead[cylno].il_stat != NULL)
559			free((char *)inostathead[cylno].il_stat);
560	free((char *)inostathead);
561	inostathead = NULL;
562	if (fsmodified && !preen)
563		printf("\n***** FILE SYSTEM WAS MODIFIED *****\n");
564	if (rerun) {
565		if (wantrestart && (restarts++ < 10) &&
566		    (preen || reply("RESTART")))
567			return (ERESTART);
568		printf("\n***** PLEASE RERUN FSCK *****\n");
569	}
570	if (chkdoreload(mntp) != 0) {
571		if (!fsmodified)
572			return (0);
573		if (!preen)
574			printf("\n***** REBOOT NOW *****\n");
575		sync();
576		return (4);
577	}
578	return (0);
579}
580
581static int
582chkdoreload(struct statfs *mntp)
583{
584	struct iovec *iov;
585	int iovlen;
586	char errmsg[255];
587
588	if (mntp == NULL)
589		return (0);
590
591	iov = NULL;
592	iovlen = 0;
593	errmsg[0] = '\0';
594	/*
595	 * We modified a mounted file system.  Do a mount update on
596	 * it unless it is read-write, so we can continue using it
597	 * as safely as possible.
598	 */
599	if (mntp->f_flags & MNT_RDONLY) {
600		build_iovec(&iov, &iovlen, "fstype", "ffs", 4);
601		build_iovec(&iov, &iovlen, "from", mntp->f_mntfromname,
602		    (size_t)-1);
603		build_iovec(&iov, &iovlen, "fspath", mntp->f_mntonname,
604		    (size_t)-1);
605		build_iovec(&iov, &iovlen, "errmsg", errmsg,
606		    sizeof(errmsg));
607		build_iovec(&iov, &iovlen, "update", NULL, 0);
608		build_iovec(&iov, &iovlen, "reload", NULL, 0);
609		/*
610		 * XX: We need the following line until we clean up
611		 * nmount parsing of root mounts and NFS root mounts.
612		 */
613		build_iovec(&iov, &iovlen, "ro", NULL, 0);
614		if (nmount(iov, iovlen, mntp->f_flags) == 0) {
615			return (0);
616		}
617		pwarn("mount reload of '%s' failed: %s %s\n\n",
618		    mntp->f_mntonname, strerror(errno), errmsg);
619		return (1);
620	}
621	return (0);
622}
623
624/*
625 * Get the mount point information for name.
626 */
627static struct statfs *
628getmntpt(const char *name)
629{
630	struct stat devstat, mntdevstat;
631	char device[sizeof(_PATH_DEV) - 1 + MNAMELEN];
632	char *ddevname;
633	struct statfs *mntbuf, *statfsp;
634	int i, mntsize, isdev;
635
636	if (stat(name, &devstat) != 0)
637		return (NULL);
638	if (S_ISCHR(devstat.st_mode) || S_ISBLK(devstat.st_mode))
639		isdev = 1;
640	else
641		isdev = 0;
642	mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
643	for (i = 0; i < mntsize; i++) {
644		statfsp = &mntbuf[i];
645		ddevname = statfsp->f_mntfromname;
646		if (*ddevname != '/') {
647			strcpy(device, _PATH_DEV);
648			strcat(device, ddevname);
649			strcpy(statfsp->f_mntfromname, device);
650		}
651		if (isdev == 0) {
652			if (strcmp(name, statfsp->f_mntonname))
653				continue;
654			return (statfsp);
655		}
656		if (stat(ddevname, &mntdevstat) == 0 &&
657		    mntdevstat.st_rdev == devstat.st_rdev)
658			return (statfsp);
659	}
660	statfsp = NULL;
661	return (statfsp);
662}
663
664static void
665usage(void)
666{
667	(void) fprintf(stderr,
668"usage: %s [-BEFfnpry] [-b block] [-c level] [-m mode] filesystem ...\n",
669	    getprogname());
670	exit(1);
671}
672
673void
674infohandler(int sig __unused)
675{
676	got_siginfo = 1;
677}
678
679void
680alarmhandler(int sig __unused)
681{
682	got_sigalarm = 1;
683}
684