main.c revision 114589
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 114589 2003-05-03 18:41:59Z obrien $");
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 <paths.h>
65#include <stdint.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 file systems.
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 file system.
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, ret;
194	ino_t files;
195	size_t size;
196
197	cdevname = filesys;
198	if (debug && preen)
199		pwarn("starting\n");
200	/*
201	 * Make best effort to get the disk name. Check first to see
202	 * if it is listed among the mounted file systems. Failing that
203	 * check to see if it is listed in /etc/fstab.
204	 */
205	mntp = getmntpt(filesys);
206	if (mntp != NULL)
207		filesys = mntp->f_mntfromname;
208	else
209		filesys = blockcheck(filesys);
210	/*
211	 * If -F flag specified, check to see whether a background check
212	 * is possible and needed. If possible and needed, exit with
213	 * status zero. Otherwise exit with status non-zero. A non-zero
214	 * exit status will cause a foreground check to be run.
215	 */
216	sblock_init();
217	if (bkgrdcheck) {
218		if ((fsreadfd = open(filesys, O_RDONLY)) < 0 || readsb(0) == 0)
219			exit(3);	/* Cannot read superblock */
220		close(fsreadfd);
221		if (sblock.fs_flags & FS_NEEDSFSCK)
222			exit(4);	/* Earlier background failed */
223		if ((sblock.fs_flags & FS_DOSOFTDEP) == 0)
224			exit(5);	/* Not running soft updates */
225		size = MIBSIZE;
226		if (sysctlnametomib("vfs.ffs.adjrefcnt", adjrefcnt, &size) < 0)
227			exit(6);	/* Lacks kernel support */
228		if ((mntp == NULL && sblock.fs_clean == 1) ||
229		    (mntp != NULL && (sblock.fs_flags & FS_UNCLEAN) == 0))
230			exit(7);	/* Filesystem clean, report it now */
231		exit(0);
232	}
233	/*
234	 * If we are to do a background check:
235	 *	Get the mount point information of the file system
236	 *	create snapshot file
237	 *	return created snapshot file
238	 *	if not found, clear bkgrdflag and proceed with normal fsck
239	 */
240	if (bkgrdflag) {
241		if (mntp == NULL) {
242			bkgrdflag = 0;
243			pfatal("NOT MOUNTED, CANNOT RUN IN BACKGROUND\n");
244		} else if ((mntp->f_flags & MNT_SOFTDEP) == 0) {
245			bkgrdflag = 0;
246			pfatal("NOT USING SOFT UPDATES, %s\n",
247			    "CANNOT RUN IN BACKGROUND");
248		} else if ((mntp->f_flags & MNT_RDONLY) != 0) {
249			bkgrdflag = 0;
250			pfatal("MOUNTED READ-ONLY, CANNOT RUN IN BACKGROUND\n");
251		} else if ((fsreadfd = open(filesys, O_RDONLY)) >= 0) {
252			if (readsb(0) != 0) {
253				if (sblock.fs_flags & FS_NEEDSFSCK) {
254					bkgrdflag = 0;
255					pfatal("UNEXPECTED INCONSISTENCY, %s\n",
256					    "CANNOT RUN IN BACKGROUND\n");
257				}
258				if ((sblock.fs_flags & FS_UNCLEAN) == 0 &&
259				    skipclean && preen) {
260					/*
261					 * file system is clean;
262					 * skip snapshot and report it clean
263					 */
264					pwarn("FILESYSTEM CLEAN; %s\n",
265					    "SKIPPING CHECKS");
266					goto clean;
267				}
268			}
269			close(fsreadfd);
270		}
271		if (bkgrdflag) {
272			snprintf(snapname, sizeof snapname, "%s/.fsck_snapshot",
273			    mntp->f_mntonname);
274			args.fspec = snapname;
275			while (mount("ffs", mntp->f_mntonname,
276			    mntp->f_flags | MNT_UPDATE | MNT_SNAPSHOT,
277			    &args) < 0) {
278				if (errno == EEXIST && unlink(snapname) == 0)
279					continue;
280				bkgrdflag = 0;
281				pfatal("CANNOT CREATE SNAPSHOT %s: %s\n",
282				    snapname, strerror(errno));
283				break;
284			}
285			if (bkgrdflag != 0)
286				filesys = snapname;
287		}
288	}
289
290	switch (setup(filesys)) {
291	case 0:
292		if (preen)
293			pfatal("CAN'T CHECK FILE SYSTEM.");
294		return (0);
295	case -1:
296	clean:
297		pwarn("clean, %ld free ", (long)(sblock.fs_cstotal.cs_nffree +
298		    sblock.fs_frag * sblock.fs_cstotal.cs_nbfree));
299		printf("(%lld frags, %lld blocks, %.1f%% fragmentation)\n",
300		    (long long)sblock.fs_cstotal.cs_nffree,
301		    (long long)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, %lld fragments\n",
374		    countdirs, (long)files - countdirs, (long long)blks);
375	}
376	pwarn("%ld files, %jd used, %ju free ",
377	    (long)n_files, (intmax_t)n_blks,
378	    (uintmax_t)n_ffree + sblock.fs_frag * n_bfree);
379	printf("(%ju frags, %ju blocks, %.1f%% fragmentation)\n",
380	    (uintmax_t)n_ffree, (uintmax_t)n_bfree,
381	    n_ffree * 100.0 / sblock.fs_dsize);
382	if (debug) {
383		if (files < 0)
384			printf("%d inodes missing\n", -files);
385		if (blks < 0)
386			printf("%lld blocks missing\n", -(long long)blks);
387		if (duplist != NULL) {
388			printf("The following duplicate blocks remain:");
389			for (dp = duplist; dp; dp = dp->next)
390				printf(" %lld,", (long long)dp->dup);
391			printf("\n");
392		}
393		if (zlnhead != NULL) {
394			printf("The following zero link count inodes remain:");
395			for (zlnp = zlnhead; zlnp; zlnp = zlnp->next)
396				printf(" %u,", zlnp->zlncnt);
397			printf("\n");
398		}
399	}
400	zlnhead = (struct zlncnt *)0;
401	duplist = (struct dups *)0;
402	muldup = (struct dups *)0;
403	inocleanup();
404	if (fsmodified) {
405		sblock.fs_time = time(NULL);
406		sbdirty();
407	}
408	if (cvtlevel && sblk.b_dirty) {
409		/*
410		 * Write out the duplicate super blocks
411		 */
412		for (cylno = 0; cylno < sblock.fs_ncg; cylno++)
413			bwrite(fswritefd, (char *)&sblock,
414			    fsbtodb(&sblock, cgsblock(&sblock, cylno)),
415			    SBLOCKSIZE);
416	}
417	if (rerun)
418		resolved = 0;
419
420	/*
421	 * Check to see if the file system is mounted read-write.
422	 */
423	if (bkgrdflag == 0 && mntp != NULL && (mntp->f_flags & MNT_RDONLY) == 0)
424		resolved = 0;
425	ckfini(resolved);
426
427	for (cylno = 0; cylno < sblock.fs_ncg; cylno++)
428		if (inostathead[cylno].il_stat != NULL)
429			free((char *)inostathead[cylno].il_stat);
430	free((char *)inostathead);
431	inostathead = NULL;
432	if (fsmodified && !preen)
433		printf("\n***** FILE SYSTEM WAS MODIFIED *****\n");
434	if (rerun)
435		printf("\n***** PLEASE RERUN FSCK *****\n");
436	if (mntp != NULL) {
437		/*
438		 * We modified a mounted file system.  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(const char *name)
468{
469	struct stat devstat, mntdevstat;
470	char device[sizeof(_PATH_DEV) - 1 + MNAMELEN];
471	char *ddevname;
472	struct statfs *mntbuf, *statfsp;
473	int i, mntsize, isdev;
474
475	if (stat(name, &devstat) != 0)
476		return (NULL);
477	if (S_ISCHR(devstat.st_mode) || S_ISBLK(devstat.st_mode))
478		isdev = 1;
479	else
480		isdev = 0;
481	mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
482	for (i = 0; i < mntsize; i++) {
483		statfsp = &mntbuf[i];
484		ddevname = statfsp->f_mntfromname;
485		if (*ddevname != '/') {
486			strcpy(device, _PATH_DEV);
487			strcat(device, ddevname);
488			strcpy(statfsp->f_mntfromname, device);
489		}
490		if (isdev == 0) {
491			if (strcmp(name, statfsp->f_mntonname))
492				continue;
493			return (statfsp);
494		}
495		if (stat(ddevname, &mntdevstat) == 0 &&
496		    mntdevstat.st_rdev == devstat.st_rdev)
497			return (statfsp);
498	}
499	statfsp = NULL;
500	return (statfsp);
501}
502
503static void
504usage(void)
505{
506        (void) fprintf(stderr,
507            "usage: %s [-BFpfny] [-b block] [-c level] [-m mode] "
508                        "file system ...\n",
509            getprogname());
510        exit(1);
511}
512