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