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