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