main.c revision 86514
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 86514 2001-11-17 23:48:21Z iedowse $";
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#include <sys/sysctl.h>
55
56#include <ufs/ufs/dinode.h>
57#include <ufs/ufs/ufsmount.h>
58#include <ufs/ffs/fs.h>
59
60#include <err.h>
61#include <errno.h>
62#include <fstab.h>
63#include <paths.h>
64#include <string.h>
65
66#include "fsck.h"
67
68static void usage __P((void));
69static int argtoi __P((int flag, char *req, char *str, int base));
70static int checkfilesys __P((char *filesys));
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++);
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)
187	char *filesys;
188{
189	ufs_daddr_t n_ffree, n_bfree;
190	struct ufs_args args;
191	struct dups *dp;
192	struct statfs *mntp;
193	struct zlncnt *zlnp;
194	ufs_daddr_t blks;
195	ufs_daddr_t files;
196	int cylno, size;
197
198	cdevname = filesys;
199	if (debug && preen)
200		pwarn("starting\n");
201	/*
202	 * Make best effort to get the disk name. Check first to see
203	 * if it is listed among the mounted filesystems. Failing that
204	 * check to see if it is listed in /etc/fstab.
205	 */
206	mntp = getmntpt(filesys);
207	if (mntp != NULL)
208		filesys = mntp->f_mntfromname;
209	else
210		filesys = blockcheck(filesys);
211	/*
212	 * If -F flag specified, check to see whether a background check
213	 * is possible and needed. If possible and needed, exit with
214	 * status zero. Otherwise exit with status non-zero. A non-zero
215	 * exit status will cause a foreground check to be run.
216	 */
217	sblock_init();
218	if (bkgrdcheck) {
219		if ((fsreadfd = open(filesys, O_RDONLY)) < 0 || readsb(0) == 0)
220			exit(3);	/* Cannot read superblock */
221		close(fsreadfd);
222		if (sblock.fs_flags & FS_NEEDSFSCK)
223			exit(4);	/* Earlier background failed */
224		if ((sblock.fs_flags & FS_DOSOFTDEP) == 0)
225			exit(5);	/* Not running soft updates */
226		size = MIBSIZE;
227		if (sysctlnametomib("vfs.ffs.adjrefcnt", adjrefcnt, &size) < 0)
228			exit(6);	/* Lacks kernel support */
229		if ((mntp == NULL && sblock.fs_clean == 1) ||
230		    (mntp != NULL && (sblock.fs_flags & FS_UNCLEAN) == 0))
231			exit(7);	/* Filesystem clean, report it now */
232		exit(0);
233	}
234	/*
235	 * If we are to do a background check:
236	 *	Get the mount point information of the filesystem
237	 *	create snapshot file
238	 *	return created snapshot file
239	 *	if not found, clear bkgrdflag and proceed with normal fsck
240	 */
241	if (bkgrdflag) {
242		if (mntp == NULL) {
243			bkgrdflag = 0;
244			pfatal("NOT MOUNTED, CANNOT RUN IN BACKGROUND\n");
245		} else if ((mntp->f_flags & MNT_SOFTDEP) == 0) {
246			bkgrdflag = 0;
247			pfatal("NOT USING SOFT UPDATES, %s\n",
248			    "CANNOT RUN IN BACKGROUND");
249		} else if ((mntp->f_flags & MNT_RDONLY) != 0) {
250			bkgrdflag = 0;
251			pfatal("MOUNTED READ-ONLY, CANNOT RUN IN BACKGROUND\n");
252		} else if ((fsreadfd = open(filesys, O_RDONLY)) >= 0) {
253			if (readsb(0) != 0) {
254				if (sblock.fs_flags & FS_NEEDSFSCK) {
255					bkgrdflag = 0;
256					pfatal("UNEXPECTED INCONSISTENCY, %s\n",
257					    "CANNOT RUN IN BACKGROUND\n");
258				}
259				if ((sblock.fs_flags & FS_UNCLEAN) == 0 &&
260				    skipclean && preen) {
261					/*
262					 * filesystem is clean;
263					 * skip snapshot and report it clean
264					 */
265					pwarn("FILESYSTEM CLEAN; %s\n",
266					    "SKIPPING CHECKS");
267					goto clean;
268				}
269			}
270			close(fsreadfd);
271		}
272		if (bkgrdflag) {
273			snprintf(snapname, sizeof snapname, "%s/.fsck_snapshot",
274			    mntp->f_mntonname);
275			args.fspec = snapname;
276			while (mount("ffs", mntp->f_mntonname,
277			    mntp->f_flags | MNT_UPDATE | MNT_SNAPSHOT,
278			    &args) < 0) {
279				if (errno == EEXIST && unlink(snapname) == 0)
280					continue;
281				bkgrdflag = 0;
282				pfatal("CANNOT CREATE SNAPSHOT %s: %s\n",
283				    snapname, strerror(errno));
284				break;
285			}
286			if (bkgrdflag != 0)
287				filesys = snapname;
288		}
289	}
290
291	switch (setup(filesys)) {
292	case 0:
293		if (preen)
294			pfatal("CAN'T CHECK FILE SYSTEM.");
295		return (0);
296	case -1:
297	clean:
298		pwarn("clean, %ld free ", (long)(sblock.fs_cstotal.cs_nffree +
299		    sblock.fs_frag * sblock.fs_cstotal.cs_nbfree));
300		printf("(%d frags, %d blocks, %.1f%% fragmentation)\n",
301		    sblock.fs_cstotal.cs_nffree, sblock.fs_cstotal.cs_nbfree,
302		    sblock.fs_cstotal.cs_nffree * 100.0 / sblock.fs_dsize);
303		return (0);
304	}
305
306	/*
307	 * Cleared if any questions answered no. Used to decide if
308	 * the superblock should be marked clean.
309	 */
310	resolved = 1;
311	/*
312	 * 1: scan inodes tallying blocks used
313	 */
314	if (preen == 0) {
315		printf("** Last Mounted on %s\n", sblock.fs_fsmnt);
316		if (mntp != NULL && mntp->f_flags & MNT_ROOTFS)
317			printf("** Root file system\n");
318		printf("** Phase 1 - Check Blocks and Sizes\n");
319	}
320	pass1();
321
322	/*
323	 * 1b: locate first references to duplicates, if any
324	 */
325	if (duplist) {
326		if (preen || usedsoftdep)
327			pfatal("INTERNAL ERROR: dups with -p");
328		printf("** Phase 1b - Rescan For More DUPS\n");
329		pass1b();
330	}
331
332	/*
333	 * 2: traverse directories from root to mark all connected directories
334	 */
335	if (preen == 0)
336		printf("** Phase 2 - Check Pathnames\n");
337	pass2();
338
339	/*
340	 * 3: scan inodes looking for disconnected directories
341	 */
342	if (preen == 0)
343		printf("** Phase 3 - Check Connectivity\n");
344	pass3();
345
346	/*
347	 * 4: scan inodes looking for disconnected files; check reference counts
348	 */
349	if (preen == 0)
350		printf("** Phase 4 - Check Reference Counts\n");
351	pass4();
352
353	/*
354	 * 5: check and repair resource counts in cylinder groups
355	 */
356	if (preen == 0)
357		printf("** Phase 5 - Check Cyl groups\n");
358	pass5();
359
360	/*
361	 * print out summary statistics
362	 */
363	n_ffree = sblock.fs_cstotal.cs_nffree;
364	n_bfree = sblock.fs_cstotal.cs_nbfree;
365	files = maxino - ROOTINO - sblock.fs_cstotal.cs_nifree - n_files;
366	blks = n_blks +
367	    sblock.fs_ncg * (cgdmin(&sblock, 0) - cgsblock(&sblock, 0));
368	blks += cgsblock(&sblock, 0) - cgbase(&sblock, 0);
369	blks += howmany(sblock.fs_cssize, sblock.fs_fsize);
370	blks = maxfsblock - (n_ffree + sblock.fs_frag * n_bfree) - blks;
371	if (bkgrdflag && (files > 0 || blks > 0)) {
372		countdirs = sblock.fs_cstotal.cs_ndir - countdirs;
373		pwarn("Reclaimed: %ld directories, %ld files, %d fragments\n",
374		    countdirs, (long)files - countdirs, blks);
375	}
376	pwarn("%ld files, %ld used, %ld free ",
377	    (long)n_files, (long)n_blks, (long)(n_ffree +
378	    sblock.fs_frag * n_bfree));
379	printf("(%d frags, %d blocks, %.1f%% fragmentation)\n",
380	    n_ffree, n_bfree, n_ffree * 100.0 / sblock.fs_dsize);
381	if (debug) {
382		if (files < 0)
383			printf("%d inodes missing\n", -files);
384		if (blks < 0)
385			printf("%d blocks missing\n", -blks);
386		if (duplist != NULL) {
387			printf("The following duplicate blocks remain:");
388			for (dp = duplist; dp; dp = dp->next)
389				printf(" %d,", dp->dup);
390			printf("\n");
391		}
392		if (zlnhead != NULL) {
393			printf("The following zero link count inodes remain:");
394			for (zlnp = zlnhead; zlnp; zlnp = zlnp->next)
395				printf(" %u,", zlnp->zlncnt);
396			printf("\n");
397		}
398	}
399	zlnhead = (struct zlncnt *)0;
400	duplist = (struct dups *)0;
401	muldup = (struct dups *)0;
402	inocleanup();
403	if (fsmodified) {
404		sblock.fs_time = time(NULL);
405		sbdirty();
406	}
407	if (cvtlevel && sblk.b_dirty) {
408		/*
409		 * Write out the duplicate super blocks
410		 */
411		for (cylno = 0; cylno < sblock.fs_ncg; cylno++)
412			bwrite(fswritefd, (char *)&sblock,
413			    fsbtodb(&sblock, cgsblock(&sblock, cylno)), SBSIZE);
414	}
415	if (rerun)
416		resolved = 0;
417
418	/*
419	 * Check to see if the filesystem is mounted read-write.
420	 */
421	if (bkgrdflag == 0 && mntp != NULL && (mntp->f_flags & MNT_RDONLY) == 0)
422		resolved = 0;
423	ckfini(resolved);
424
425	for (cylno = 0; cylno < sblock.fs_ncg; cylno++)
426		if (inostathead[cylno].il_stat != NULL)
427			free((char *)inostathead[cylno].il_stat);
428	free((char *)inostathead);
429	inostathead = NULL;
430	if (fsmodified && !preen)
431		printf("\n***** FILE SYSTEM WAS MODIFIED *****\n");
432	if (rerun)
433		printf("\n***** PLEASE RERUN FSCK *****\n");
434	if (mntp != NULL) {
435		struct ufs_args args;
436		int ret;
437		/*
438		 * We modified a mounted filesystem.  Do a mount update on
439		 * it unless it is read-write, so we can continue using it
440		 * as safely as possible.
441		 */
442		if (mntp->f_flags & MNT_RDONLY) {
443			args.fspec = 0;
444			args.export.ex_flags = 0;
445			args.export.ex_root = 0;
446			ret = mount("ufs", mntp->f_mntonname,
447			    mntp->f_flags | MNT_UPDATE | MNT_RELOAD, &args);
448			if (ret == 0)
449				return (0);
450			pwarn("mount reload of '%s' failed: %s\n\n",
451			    mntp->f_mntonname, strerror(errno));
452		}
453		if (!fsmodified)
454			return (0);
455		if (!preen)
456			printf("\n***** REBOOT NOW *****\n");
457		sync();
458		return (4);
459	}
460	return (0);
461}
462
463/*
464 * Get the mount point information for name.
465 */
466static struct statfs *
467getmntpt(name)
468	const char *name;
469{
470	struct stat devstat, mntdevstat;
471	char device[sizeof(_PATH_DEV) - 1 + MNAMELEN];
472	char *devname;
473	struct statfs *mntbuf, *statfsp;
474	int i, mntsize, isdev;
475
476	if (stat(name, &devstat) != 0)
477		return (NULL);
478	if (S_ISCHR(devstat.st_mode) || S_ISBLK(devstat.st_mode))
479		isdev = 1;
480	else
481		isdev = 0;
482	mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
483	for (i = 0; i < mntsize; i++) {
484		statfsp = &mntbuf[i];
485		devname = statfsp->f_mntfromname;
486		if (*devname != '/') {
487			strcpy(device, _PATH_DEV);
488			strcat(device, devname);
489			strcpy(statfsp->f_mntfromname, device);
490		}
491		if (isdev == 0) {
492			if (strcmp(name, statfsp->f_mntonname))
493				continue;
494			return (statfsp);
495		}
496		if (stat(devname, &mntdevstat) == 0 &&
497		    mntdevstat.st_rdev == devstat.st_rdev)
498			return (statfsp);
499	}
500	statfsp = NULL;
501	return (statfsp);
502}
503
504static void
505usage()
506{
507        extern char *__progname;
508
509        (void) fprintf(stderr,
510            "Usage: %s [-BFpfny] [-b block] [-c level] [-m mode] "
511                        "filesystem ...\n",
512            __progname);
513        exit(1);
514}
515