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