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