main.c revision 75927
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 * 3. All advertising materials mentioning features or use of this software
14 *    must display the following acknowledgement:
15 *	This product includes software developed by the University of
16 *	California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34#ifndef lint
35static const char copyright[] =
36"@(#) Copyright (c) 1980, 1986, 1993\n\
37	The Regents of the University of California.  All rights reserved.\n";
38#endif /* not lint */
39
40#ifndef lint
41#if 0
42static char sccsid[] = "@(#)main.c	8.6 (Berkeley) 5/14/95";
43#endif
44static const char rcsid[] =
45  "$FreeBSD: head/sbin/fsck_ffs/main.c 75927 2001-04-24 22:38:08Z mckusick $";
46#endif /* not lint */
47
48#include <sys/param.h>
49#include <sys/stat.h>
50#include <sys/file.h>
51#include <sys/time.h>
52#include <sys/mount.h>
53#include <sys/resource.h>
54
55#include <ufs/ufs/dinode.h>
56#include <ufs/ufs/ufsmount.h>
57#include <ufs/ffs/fs.h>
58
59#include <err.h>
60#include <errno.h>
61#include <fstab.h>
62#include <paths.h>
63
64#include "fsck.h"
65
66static void usage __P((void));
67static int argtoi __P((int flag, char *req, char *str, int base));
68static int docheck __P((struct fstab *fsp));
69static int checkfilesys __P((char *filesys, char *mntpt, long auxdata,
70		int child));
71static struct statfs *getmntpt __P((const char *));
72int main __P((int argc, char *argv[]));
73
74int
75main(argc, argv)
76	int	argc;
77	char	*argv[];
78{
79	int ch;
80	struct rlimit rlimit;
81	int ret = 0;
82
83	sync();
84	skipclean = 1;
85	while ((ch = getopt(argc, argv, "b:Bc:dfFm: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			break;
101
102		case 'd':
103			debug++;
104			break;
105
106		case 'f':
107			skipclean = 0;
108			break;
109
110		case 'F':
111			bkgrdcheck = 1;
112			break;
113
114		case 'm':
115			lfmode = argtoi('m', "mode", optarg, 8);
116			if (lfmode &~ 07777)
117				errx(EEXIT, "bad mode to -m: %o", lfmode);
118			printf("** lost+found creation mode %o\n", lfmode);
119			break;
120
121		case 'n':
122			nflag++;
123			yflag = 0;
124			break;
125
126		case 'p':
127			preen++;
128			break;
129
130		case 'y':
131			yflag++;
132			nflag = 0;
133			break;
134
135		default:
136			usage();
137		}
138	}
139	argc -= optind;
140	argv += optind;
141
142	if (!argc)
143		usage();
144
145	if (signal(SIGINT, SIG_IGN) != SIG_IGN)
146		(void)signal(SIGINT, catch);
147	if (preen)
148		(void)signal(SIGQUIT, catchquit);
149	signal(SIGINFO, infohandler);
150	/*
151	 * Push up our allowed memory limit so we can cope
152	 * with huge filesystems.
153	 */
154	if (getrlimit(RLIMIT_DATA, &rlimit) == 0) {
155		rlimit.rlim_cur = rlimit.rlim_max;
156		(void)setrlimit(RLIMIT_DATA, &rlimit);
157	}
158	while (argc-- > 0)
159		(void)checkfilesys(*argv++, 0, 0L, 0);
160
161	if (returntosingle)
162		ret = 2;
163	exit(ret);
164}
165
166static int
167argtoi(flag, req, str, base)
168	int flag;
169	char *req, *str;
170	int base;
171{
172	char *cp;
173	int ret;
174
175	ret = (int)strtol(str, &cp, base);
176	if (cp == str || *cp)
177		errx(EEXIT, "-%c flag requires a %s", flag, req);
178	return (ret);
179}
180
181/*
182 * Check the specified filesystem.
183 */
184/* ARGSUSED */
185static int
186checkfilesys(filesys, mntpt, auxdata, child)
187	char *filesys, *mntpt;
188	long auxdata;
189	int child;
190{
191	ufs_daddr_t n_ffree, n_bfree;
192	struct ufs_args args;
193	struct dups *dp;
194	struct statfs *mntp;
195	struct zlncnt *zlnp;
196	ufs_daddr_t blks;
197	ufs_daddr_t files;
198	int cylno, size;
199
200	if (preen && child)
201		(void)signal(SIGQUIT, voidquit);
202	cdevname = filesys;
203	if (debug && preen)
204		pwarn("starting\n");
205	/*
206	 * Make best effort to get the disk name. Check first to see
207	 * if it is listed among the mounted filesystems. Failing that
208	 * check to see if it is listed in /etc/fstab.
209	 */
210	mntp = getmntpt(filesys);
211	if (mntp != NULL)
212		filesys = mntp->f_mntfromname;
213	else
214		filesys = blockcheck(filesys);
215	/*
216	 * If -F flag specified, check to see whether a background check
217	 * is possible and needed. If possible and needed, exit with
218	 * status zero. Otherwise exit with status non-zero. A non-zero
219	 * exit status will cause a foreground check to be run.
220	 */
221	sblock_init();
222	if (bkgrdcheck) {
223		if ((fsreadfd = open(filesys, O_RDONLY)) < 0 || readsb(0) == 0)
224			exit(3);	/* Cannot read superblock */
225		close(fsreadfd);
226		if (sblock.fs_flags & FS_NEEDSFSCK)
227			exit(4);	/* Earlier background failed */
228		if ((sblock.fs_flags & FS_DOSOFTDEP) == 0)
229			exit(5);	/* Not running soft updates */
230		size = MIBSIZE;
231		if (sysctlnametomib("vfs.ffs.adjrefcnt", adjrefcnt, &size) < 0)
232			exit(6);	/* Lacks kernel support */
233		if ((mntp == NULL && sblock.fs_clean == 1) ||
234		    (mntp != NULL && (sblock.fs_flags & FS_UNCLEAN) == 0))
235			exit(7);	/* Filesystem clean, report it now */
236		exit(0);
237	}
238	/*
239	 * If we are to do a background check:
240	 *	Get the mount point information of the filesystem
241	 *	create snapshot file
242	 *	return created snapshot file
243	 *	if not found, clear bkgrdflag and proceed with normal fsck
244	 */
245	if (bkgrdflag) {
246		if (mntp == NULL) {
247			bkgrdflag = 0;
248			pfatal("NOT MOUNTED, CANNOT RUN IN BACKGROUND\n");
249		} else if ((mntp->f_flags & MNT_SOFTDEP) == 0) {
250			bkgrdflag = 0;
251			pfatal("NOT USING SOFT UPDATES, %s\n",
252			    "CANNOT RUN IN BACKGROUND");
253		} else if ((mntp->f_flags & MNT_RDONLY) != 0) {
254			bkgrdflag = 0;
255			pfatal("MOUNTED READ-ONLY, CANNOT RUN IN BACKGROUND\n");
256		} else if ((fsreadfd = open(filesys, O_RDONLY)) >= 0) {
257			if (readsb(0) != 0) {
258				if (sblock.fs_flags & FS_NEEDSFSCK) {
259					bkgrdflag = 0;
260					pfatal("UNEXPECTED INCONSISTENCY, %s\n",
261					    "CANNOT RUN IN BACKGROUND\n");
262				}
263				if ((sblock.fs_flags & FS_UNCLEAN) == 0 &&
264				    skipclean && preen) {
265					/*
266					 * filesystem is clean;
267					 * skip snapshot and report it clean
268					 */
269					pwarn("FILESYSTEM CLEAN; %s\n",
270					    "SKIPPING CHECKS");
271					goto clean;
272				}
273			}
274			close(fsreadfd);
275		}
276		if (bkgrdflag) {
277			snprintf(snapname, sizeof snapname, "%s/.fsck_snapshot",
278			    mntp->f_mntonname);
279			args.fspec = snapname;
280			while (mount("ffs", mntp->f_mntonname,
281			    mntp->f_flags | MNT_UPDATE | MNT_SNAPSHOT,
282			    &args) < 0) {
283				if (errno == EEXIST && unlink(snapname) == 0)
284					continue;
285				bkgrdflag = 0;
286				pfatal("CANNOT CREATE SNAPSHOT %s: %s\n",
287				    snapname, strerror(errno));
288				break;
289			}
290			if (bkgrdflag != 0)
291				filesys = snapname;
292		}
293	}
294
295	switch (setup(filesys)) {
296	case 0:
297		if (preen)
298			pfatal("CAN'T CHECK FILE SYSTEM.");
299		return (0);
300	case -1:
301	clean:
302		pwarn("clean, %ld free ", sblock.fs_cstotal.cs_nffree +
303		    sblock.fs_frag * sblock.fs_cstotal.cs_nbfree);
304		printf("(%d frags, %d blocks, %.1f%% fragmentation)\n",
305		    sblock.fs_cstotal.cs_nffree, sblock.fs_cstotal.cs_nbfree,
306		    sblock.fs_cstotal.cs_nffree * 100.0 / sblock.fs_dsize);
307		return (0);
308	}
309
310	/*
311	 * Cleared if any questions answered no. Used to decide if
312	 * the superblock should be marked clean.
313	 */
314	resolved = 1;
315	/*
316	 * 1: scan inodes tallying blocks used
317	 */
318	if (preen == 0) {
319		printf("** Last Mounted on %s\n", sblock.fs_fsmnt);
320		if (mntp != NULL && mntp->f_flags & MNT_ROOTFS)
321			printf("** Root file system\n");
322		printf("** Phase 1 - Check Blocks and Sizes\n");
323	}
324	pass1();
325
326	/*
327	 * 1b: locate first references to duplicates, if any
328	 */
329	if (duplist) {
330		if (preen || usedsoftdep)
331			pfatal("INTERNAL ERROR: dups with -p");
332		printf("** Phase 1b - Rescan For More DUPS\n");
333		pass1b();
334	}
335
336	/*
337	 * 2: traverse directories from root to mark all connected directories
338	 */
339	if (preen == 0)
340		printf("** Phase 2 - Check Pathnames\n");
341	pass2();
342
343	/*
344	 * 3: scan inodes looking for disconnected directories
345	 */
346	if (preen == 0)
347		printf("** Phase 3 - Check Connectivity\n");
348	pass3();
349
350	/*
351	 * 4: scan inodes looking for disconnected files; check reference counts
352	 */
353	if (preen == 0)
354		printf("** Phase 4 - Check Reference Counts\n");
355	pass4();
356
357	/*
358	 * 5: check and repair resource counts in cylinder groups
359	 */
360	if (preen == 0)
361		printf("** Phase 5 - Check Cyl groups\n");
362	pass5();
363
364	/*
365	 * print out summary statistics
366	 */
367	n_ffree = sblock.fs_cstotal.cs_nffree;
368	n_bfree = sblock.fs_cstotal.cs_nbfree;
369	files = maxino - ROOTINO - sblock.fs_cstotal.cs_nifree - n_files;
370	blks = n_blks +
371	    sblock.fs_ncg * (cgdmin(&sblock, 0) - cgsblock(&sblock, 0));
372	blks += cgsblock(&sblock, 0) - cgbase(&sblock, 0);
373	blks += howmany(sblock.fs_cssize, sblock.fs_fsize);
374	blks = maxfsblock - (n_ffree + sblock.fs_frag * n_bfree) - blks;
375	if (bkgrdflag && (files > 0 || blks > 0)) {
376		countdirs = sblock.fs_cstotal.cs_ndir - countdirs;
377		pwarn("Reclaimed: %d directories, %d files, %d fragments\n",
378		    countdirs, files - countdirs, blks);
379	}
380	pwarn("%ld files, %ld used, %ld free ",
381	    n_files, n_blks, n_ffree + sblock.fs_frag * n_bfree);
382	printf("(%d frags, %d blocks, %.1f%% fragmentation)\n",
383	    n_ffree, n_bfree, n_ffree * 100.0 / sblock.fs_dsize);
384	if (debug) {
385		if (files < 0)
386			printf("%d inodes missing\n", -files);
387		if (blks < 0)
388			printf("%d blocks missing\n", -blks);
389		if (duplist != NULL) {
390			printf("The following duplicate blocks remain:");
391			for (dp = duplist; dp; dp = dp->next)
392				printf(" %d,", dp->dup);
393			printf("\n");
394		}
395		if (zlnhead != NULL) {
396			printf("The following zero link count inodes remain:");
397			for (zlnp = zlnhead; zlnp; zlnp = zlnp->next)
398				printf(" %u,", zlnp->zlncnt);
399			printf("\n");
400		}
401	}
402	zlnhead = (struct zlncnt *)0;
403	duplist = (struct dups *)0;
404	muldup = (struct dups *)0;
405	inocleanup();
406	if (fsmodified) {
407		sblock.fs_time = time(NULL);
408		sbdirty();
409	}
410	if (cvtlevel && sblk.b_dirty) {
411		/*
412		 * Write out the duplicate super blocks
413		 */
414		for (cylno = 0; cylno < sblock.fs_ncg; cylno++)
415			bwrite(fswritefd, (char *)&sblock,
416			    fsbtodb(&sblock, cgsblock(&sblock, cylno)), SBSIZE);
417	}
418	if (rerun)
419		resolved = 0;
420
421	/*
422	 * Check to see if the filesystem is mounted read-write.
423	 */
424	if (bkgrdflag == 0 && mntp != NULL && (mntp->f_flags & MNT_RDONLY) == 0)
425		resolved = 0;
426	ckfini(resolved);
427
428	for (cylno = 0; cylno < sblock.fs_ncg; cylno++)
429		if (inostathead[cylno].il_stat != NULL)
430			free((char *)inostathead[cylno].il_stat);
431	free((char *)inostathead);
432	inostathead = NULL;
433	if (fsmodified && !preen)
434		printf("\n***** FILE SYSTEM WAS MODIFIED *****\n");
435	if (rerun)
436		printf("\n***** PLEASE RERUN FSCK *****\n");
437	if (mntp != NULL) {
438		struct ufs_args args;
439		int ret;
440		/*
441		 * We modified a mounted filesystem.  Do a mount update on
442		 * it unless it is read-write, so we can continue using it
443		 * as safely as possible.
444		 */
445		if (mntp->f_flags & MNT_RDONLY) {
446			args.fspec = 0;
447			args.export.ex_flags = 0;
448			args.export.ex_root = 0;
449			ret = mount("ufs", mntp->f_mntonname,
450			    mntp->f_flags | MNT_UPDATE | MNT_RELOAD, &args);
451			if (ret == 0)
452				return (0);
453			pwarn("mount reload of '%s' failed: %s\n\n",
454			    mntp->f_mntonname, strerror(errno));
455		}
456		if (!fsmodified)
457			return (0);
458		if (!preen)
459			printf("\n***** REBOOT NOW *****\n");
460		sync();
461		return (4);
462	}
463	return (0);
464}
465
466/*
467 * Get the mount point information for name.
468 */
469static struct statfs *
470getmntpt(name)
471	const char *name;
472{
473	struct stat devstat, mntdevstat;
474	char device[sizeof(_PATH_DEV) - 1 + MNAMELEN];
475	char *devname;
476	struct statfs *mntbuf, *statfsp;
477	int i, mntsize, isdev;
478
479	if (stat(name, &devstat) != 0)
480		return (NULL);
481	if (S_ISCHR(devstat.st_mode) || S_ISBLK(devstat.st_mode))
482		isdev = 1;
483	else
484		isdev = 0;
485	mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
486	for (i = 0; i < mntsize; i++) {
487		statfsp = &mntbuf[i];
488		devname = statfsp->f_mntfromname;
489		if (*devname != '/') {
490			strcpy(device, _PATH_DEV);
491			strcat(device, devname);
492			strcpy(statfsp->f_mntfromname, device);
493		}
494		if (isdev == 0) {
495			if (strcmp(name, statfsp->f_mntonname))
496				continue;
497			return (statfsp);
498		}
499		if (stat(devname, &mntdevstat) == 0 &&
500		    mntdevstat.st_rdev == devstat.st_rdev)
501			return (statfsp);
502	}
503	statfsp = NULL;
504	return (statfsp);
505}
506
507static void
508usage()
509{
510        extern char *__progname;
511
512        (void) fprintf(stderr,
513            "Usage: %s [-dfnpy] [-B be|le] [-b block] [-c level] [-m mode] "
514                        "filesystem ...\n",
515            __progname);
516        exit(1);
517}
518