]> CyberLeo.Net >> Repos - FreeBSD/releng/7.2.git/blob - sbin/fsck_ffs/main.c
Add -C back.
[FreeBSD/releng/7.2.git] / sbin / fsck_ffs / main.c
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  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29
30 #if 0
31 #ifndef lint
32 static const char copyright[] =
33 "@(#) Copyright (c) 1980, 1986, 1993\n\
34         The Regents of the University of California.  All rights reserved.\n";
35 #endif /* not lint */
36
37 #ifndef lint
38 static char sccsid[] = "@(#)main.c      8.6 (Berkeley) 5/14/95";
39 #endif /* not lint */
40 #endif
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
43
44 #include <sys/param.h>
45 #include <sys/stat.h>
46 #include <sys/file.h>
47 #include <sys/time.h>
48 #include <sys/mount.h>
49 #include <sys/resource.h>
50 #include <sys/sysctl.h>
51 #include <sys/uio.h>
52 #include <sys/disklabel.h>
53
54 #include <ufs/ufs/dinode.h>
55 #include <ufs/ffs/fs.h>
56
57 #include <err.h>
58 #include <errno.h>
59 #include <fstab.h>
60 #include <grp.h>
61 #include <mntopts.h>
62 #include <paths.h>
63 #include <stdint.h>
64 #include <string.h>
65
66 #include "fsck.h"
67
68 static void usage(void) __dead2;
69 static int argtoi(int flag, const char *req, const char *str, int base);
70 static int checkfilesys(char *filesys);
71 static int chkdoreload(struct statfs *mntp);
72 static struct statfs *getmntpt(const char *);
73
74 int
75 main(int argc, char *argv[])
76 {
77         int ch;
78         struct rlimit rlimit;
79         struct itimerval itimerval;
80         int ret = 0;
81
82         sync();
83         skipclean = 1;
84         damagedflag = 0;
85         while ((ch = getopt(argc, argv, "b:Bc:CdDfFm: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 'D':
110                         damagedflag = 1;
111                         /* FALLTHROUGH */
112
113                 case 'f':
114                         skipclean = 0;
115                         break;
116
117                 case 'F':
118                         bkgrdcheck = 1;
119                         break;
120
121                 case 'm':
122                         lfmode = argtoi('m', "mode", optarg, 8);
123                         if (lfmode &~ 07777)
124                                 errx(EEXIT, "bad mode to -m: %o", lfmode);
125                         printf("** lost+found creation mode %o\n", lfmode);
126                         break;
127
128                 case 'n':
129                         nflag++;
130                         yflag = 0;
131                         break;
132
133                 case 'p':
134                         preen++;
135                         /*FALLTHROUGH*/
136
137                 case 'C':
138                         ckclean++;
139                         break;
140
141                 case 'y':
142                         yflag++;
143                         nflag = 0;
144                         break;
145
146                 default:
147                         usage();
148                 }
149         }
150         argc -= optind;
151         argv += optind;
152
153         if (!argc)
154                 usage();
155
156         if (signal(SIGINT, SIG_IGN) != SIG_IGN)
157                 (void)signal(SIGINT, catch);
158         if (ckclean)
159                 (void)signal(SIGQUIT, catchquit);
160         signal(SIGINFO, infohandler);
161         if (bkgrdflag) {
162                 signal(SIGALRM, alarmhandler);
163                 itimerval.it_interval.tv_sec = 5;
164                 itimerval.it_interval.tv_usec = 0;
165                 itimerval.it_value.tv_sec = 5;
166                 itimerval.it_value.tv_usec = 0;
167                 setitimer(ITIMER_REAL, &itimerval, NULL);
168         }
169         /*
170          * Push up our allowed memory limit so we can cope
171          * with huge file systems.
172          */
173         if (getrlimit(RLIMIT_DATA, &rlimit) == 0) {
174                 rlimit.rlim_cur = rlimit.rlim_max;
175                 (void)setrlimit(RLIMIT_DATA, &rlimit);
176         }
177         while (argc-- > 0)
178                 (void)checkfilesys(*argv++);
179
180         if (returntosingle)
181                 ret = 2;
182         exit(ret);
183 }
184
185 static int
186 argtoi(int flag, const char *req, const char *str, int base)
187 {
188         char *cp;
189         int ret;
190
191         ret = (int)strtol(str, &cp, base);
192         if (cp == str || *cp)
193                 errx(EEXIT, "-%c flag requires a %s", flag, req);
194         return (ret);
195 }
196
197 /*
198  * Check the specified file system.
199  */
200 /* ARGSUSED */
201 static int
202 checkfilesys(char *filesys)
203 {
204         ufs2_daddr_t n_ffree, n_bfree;
205         struct dups *dp;
206         struct statfs *mntp;
207         struct stat snapdir;
208         struct group *grp;
209         ufs2_daddr_t blks;
210         struct iovec *iov;
211         char errmsg[255];
212         int iovlen;
213         int fflags;
214         int cylno;
215         ino_t files;
216         size_t size;
217
218         iov = NULL;
219         iovlen = 0;
220         errmsg[0] = '\0';
221
222         cdevname = filesys;
223         if (debug && ckclean)
224                 pwarn("starting\n");
225         /*
226          * Make best effort to get the disk name. Check first to see
227          * if it is listed among the mounted file systems. Failing that
228          * check to see if it is listed in /etc/fstab.
229          */
230         mntp = getmntpt(filesys);
231         if (mntp != NULL)
232                 filesys = mntp->f_mntfromname;
233         else
234                 filesys = blockcheck(filesys);
235         /*
236          * If -F flag specified, check to see whether a background check
237          * is possible and needed. If possible and needed, exit with
238          * status zero. Otherwise exit with status non-zero. A non-zero
239          * exit status will cause a foreground check to be run.
240          */
241         sblock_init();
242         if (bkgrdcheck) {
243                 if ((fsreadfd = open(filesys, O_RDONLY)) < 0 || readsb(0) == 0)
244                         exit(3);        /* Cannot read superblock */
245                 close(fsreadfd);
246                 if (sblock.fs_flags & FS_NEEDSFSCK)
247                         exit(4);        /* Earlier background failed */
248                 if ((sblock.fs_flags & FS_DOSOFTDEP) == 0)
249                         exit(5);        /* Not running soft updates */
250                 size = MIBSIZE;
251                 if (sysctlnametomib("vfs.ffs.adjrefcnt", adjrefcnt, &size) < 0)
252                         exit(6);        /* Lacks kernel support */
253                 if ((mntp == NULL && sblock.fs_clean == 1) ||
254                     (mntp != NULL && (sblock.fs_flags & FS_UNCLEAN) == 0))
255                         exit(7);        /* Filesystem clean, report it now */
256                 exit(0);
257         }
258         if (ckclean && skipclean) {
259                 /*
260                  * If file system is gjournaled, check it here.
261                  */
262                 if ((fsreadfd = open(filesys, O_RDONLY)) < 0 || readsb(0) == 0)
263                         exit(3);        /* Cannot read superblock */
264                 close(fsreadfd);
265                 if ((sblock.fs_flags & FS_GJOURNAL) != 0) {
266                         //printf("GJournaled file system detected on %s.\n",
267                         //    filesys);
268                         if (sblock.fs_clean == 1) {
269                                 pwarn("FILE SYSTEM CLEAN; SKIPPING CHECKS\n");
270                                 exit(0);
271                         }
272                         if ((sblock.fs_flags & (FS_UNCLEAN | FS_NEEDSFSCK)) == 0) {
273                                 gjournal_check(filesys);
274                                 if (chkdoreload(mntp) == 0)
275                                         exit(0);
276                                 exit(4);
277                         } else {
278                                 pfatal("UNEXPECTED INCONSISTENCY, %s\n",
279                                     "CANNOT RUN FAST FSCK\n");
280                         }
281                 }
282         }
283         /*
284          * If we are to do a background check:
285          *      Get the mount point information of the file system
286          *      create snapshot file
287          *      return created snapshot file
288          *      if not found, clear bkgrdflag and proceed with normal fsck
289          */
290         if (bkgrdflag) {
291                 if (mntp == NULL) {
292                         bkgrdflag = 0;
293                         pfatal("NOT MOUNTED, CANNOT RUN IN BACKGROUND\n");
294                 } else if ((mntp->f_flags & MNT_SOFTDEP) == 0) {
295                         bkgrdflag = 0;
296                         pfatal("NOT USING SOFT UPDATES, %s\n",
297                             "CANNOT RUN IN BACKGROUND");
298                 } else if ((mntp->f_flags & MNT_RDONLY) != 0) {
299                         bkgrdflag = 0;
300                         pfatal("MOUNTED READ-ONLY, CANNOT RUN IN BACKGROUND\n");
301                 } else if ((fsreadfd = open(filesys, O_RDONLY)) >= 0) {
302                         if (readsb(0) != 0) {
303                                 if (sblock.fs_flags & FS_NEEDSFSCK) {
304                                         bkgrdflag = 0;
305                                         pfatal("UNEXPECTED INCONSISTENCY, %s\n",
306                                             "CANNOT RUN IN BACKGROUND\n");
307                                 }
308                                 if ((sblock.fs_flags & FS_UNCLEAN) == 0 &&
309                                     skipclean && ckclean) {
310                                         /*
311                                          * file system is clean;
312                                          * skip snapshot and report it clean
313                                          */
314                                         pwarn("FILE SYSTEM CLEAN; %s\n",
315                                             "SKIPPING CHECKS");
316                                         goto clean;
317                                 }
318                         }
319                         close(fsreadfd);
320                 }
321                 if (bkgrdflag) {
322                         snprintf(snapname, sizeof snapname, "%s/.snap",
323                             mntp->f_mntonname);
324                         if (stat(snapname, &snapdir) < 0) {
325                                 if (errno != ENOENT) {
326                                         bkgrdflag = 0;
327                                         pfatal("CANNOT FIND %s %s: %s, %s\n",
328                                             "SNAPSHOT DIRECTORY",
329                                             snapname, strerror(errno),
330                                             "CANNOT RUN IN BACKGROUND");
331                                 } else if ((grp = getgrnam("operator")) == 0 ||
332                                     mkdir(snapname, 0770) < 0 ||
333                                     chown(snapname, -1, grp->gr_gid) < 0 ||
334                                     chmod(snapname, 0770) < 0) {
335                                         bkgrdflag = 0;
336                                         pfatal("CANNOT CREATE %s %s: %s, %s\n",
337                                             "SNAPSHOT DIRECTORY",
338                                             snapname, strerror(errno),
339                                             "CANNOT RUN IN BACKGROUND");
340                                 }
341                         } else if (!S_ISDIR(snapdir.st_mode)) {
342                                 bkgrdflag = 0;
343                                 pfatal("%s IS NOT A DIRECTORY, %s\n", snapname,
344                                     "CANNOT RUN IN BACKGROUND");
345                         }
346                 }
347                 if (bkgrdflag) {
348                         snprintf(snapname, sizeof snapname,
349                             "%s/.snap/fsck_snapshot", mntp->f_mntonname);
350                         fflags = mntp->f_flags;
351                         /*
352                          * XXX: Need to kick out MNT_ROOTFS until we fix
353                          * nmount().
354                          */
355                         fflags &= ~MNT_ROOTFS;
356                         fflags = fflags | MNT_UPDATE | MNT_SNAPSHOT;
357                         build_iovec(&iov, &iovlen, "fstype", "ffs", 4);
358                         build_iovec(&iov, &iovlen, "from", snapname,
359                             (size_t)-1);
360                         build_iovec(&iov, &iovlen, "fspath", mntp->f_mntonname,
361                             (size_t)-1);
362                         build_iovec(&iov, &iovlen, "errmsg", errmsg,
363                             sizeof(errmsg));
364
365                         while (nmount(iov, iovlen, fflags) < 0) {
366                                 if (errno == EEXIST && unlink(snapname) == 0)
367                                         continue;
368                                 bkgrdflag = 0;
369                                 pfatal("CANNOT CREATE SNAPSHOT %s: %s %s\n",
370                                     snapname, strerror(errno), errmsg);
371                                 break;
372                         }
373                         if (bkgrdflag != 0)
374                                 filesys = snapname;
375                 }
376         }
377
378         switch (setup(filesys)) {
379         case 0:
380                 if (preen)
381                         pfatal("CAN'T CHECK FILE SYSTEM.");
382                 return (0);
383         case -1:
384         clean:
385                 pwarn("clean, %ld free ", (long)(sblock.fs_cstotal.cs_nffree +
386                     sblock.fs_frag * sblock.fs_cstotal.cs_nbfree));
387                 printf("(%lld frags, %lld blocks, %.1f%% fragmentation)\n",
388                     (long long)sblock.fs_cstotal.cs_nffree,
389                     (long long)sblock.fs_cstotal.cs_nbfree,
390                     sblock.fs_cstotal.cs_nffree * 100.0 / sblock.fs_dsize);
391                 return (0);
392         }
393         
394         /*
395          * Cleared if any questions answered no. Used to decide if
396          * the superblock should be marked clean.
397          */
398         resolved = 1;
399         /*
400          * 1: scan inodes tallying blocks used
401          */
402         if (preen == 0) {
403                 printf("** Last Mounted on %s\n", sblock.fs_fsmnt);
404                 if (mntp != NULL && mntp->f_flags & MNT_ROOTFS)
405                         printf("** Root file system\n");
406                 printf("** Phase 1 - Check Blocks and Sizes\n");
407         }
408         pass1();
409
410         /*
411          * 1b: locate first references to duplicates, if any
412          */
413         if (duplist) {
414                 if (preen || usedsoftdep)
415                         pfatal("INTERNAL ERROR: dups with -p");
416                 printf("** Phase 1b - Rescan For More DUPS\n");
417                 pass1b();
418         }
419
420         /*
421          * 2: traverse directories from root to mark all connected directories
422          */
423         if (preen == 0)
424                 printf("** Phase 2 - Check Pathnames\n");
425         pass2();
426
427         /*
428          * 3: scan inodes looking for disconnected directories
429          */
430         if (preen == 0)
431                 printf("** Phase 3 - Check Connectivity\n");
432         pass3();
433
434         /*
435          * 4: scan inodes looking for disconnected files; check reference counts
436          */
437         if (preen == 0)
438                 printf("** Phase 4 - Check Reference Counts\n");
439         pass4();
440
441         /*
442          * 5: check and repair resource counts in cylinder groups
443          */
444         if (preen == 0)
445                 printf("** Phase 5 - Check Cyl groups\n");
446         pass5();
447
448         /*
449          * print out summary statistics
450          */
451         n_ffree = sblock.fs_cstotal.cs_nffree;
452         n_bfree = sblock.fs_cstotal.cs_nbfree;
453         files = maxino - ROOTINO - sblock.fs_cstotal.cs_nifree - n_files;
454         blks = n_blks +
455             sblock.fs_ncg * (cgdmin(&sblock, 0) - cgsblock(&sblock, 0));
456         blks += cgsblock(&sblock, 0) - cgbase(&sblock, 0);
457         blks += howmany(sblock.fs_cssize, sblock.fs_fsize);
458         blks = maxfsblock - (n_ffree + sblock.fs_frag * n_bfree) - blks;
459         if (bkgrdflag && (files > 0 || blks > 0)) {
460                 countdirs = sblock.fs_cstotal.cs_ndir - countdirs;
461                 pwarn("Reclaimed: %ld directories, %ld files, %lld fragments\n",
462                     countdirs, (long)files - countdirs, (long long)blks);
463         }
464         pwarn("%ld files, %jd used, %ju free ",
465             (long)n_files, (intmax_t)n_blks,
466             (uintmax_t)n_ffree + sblock.fs_frag * n_bfree);
467         printf("(%ju frags, %ju blocks, %.1f%% fragmentation)\n",
468             (uintmax_t)n_ffree, (uintmax_t)n_bfree,
469             n_ffree * 100.0 / sblock.fs_dsize);
470         if (debug) {
471                 if (files < 0)
472                         printf("%d inodes missing\n", -files);
473                 if (blks < 0)
474                         printf("%lld blocks missing\n", -(long long)blks);
475                 if (duplist != NULL) {
476                         printf("The following duplicate blocks remain:");
477                         for (dp = duplist; dp; dp = dp->next)
478                                 printf(" %lld,", (long long)dp->dup);
479                         printf("\n");
480                 }
481         }
482         duplist = (struct dups *)0;
483         muldup = (struct dups *)0;
484         inocleanup();
485         if (fsmodified) {
486                 sblock.fs_time = time(NULL);
487                 sbdirty();
488         }
489         if (cvtlevel && sblk.b_dirty) {
490                 /*
491                  * Write out the duplicate super blocks
492                  */
493                 for (cylno = 0; cylno < sblock.fs_ncg; cylno++)
494                         blwrite(fswritefd, (char *)&sblock,
495                             fsbtodb(&sblock, cgsblock(&sblock, cylno)),
496                             SBLOCKSIZE);
497         }
498         if (rerun)
499                 resolved = 0;
500
501         /*
502          * Check to see if the file system is mounted read-write.
503          */
504         if (bkgrdflag == 0 && mntp != NULL && (mntp->f_flags & MNT_RDONLY) == 0)
505                 resolved = 0;
506         ckfini(resolved);
507
508         for (cylno = 0; cylno < sblock.fs_ncg; cylno++)
509                 if (inostathead[cylno].il_stat != NULL)
510                         free((char *)inostathead[cylno].il_stat);
511         free((char *)inostathead);
512         inostathead = NULL;
513         if (fsmodified && !preen)
514                 printf("\n***** FILE SYSTEM WAS MODIFIED *****\n");
515         if (rerun)
516                 printf("\n***** PLEASE RERUN FSCK *****\n");
517         if (chkdoreload(mntp) != 0) {
518                 if (!fsmodified)
519                         return (0);
520                 if (!preen)
521                         printf("\n***** REBOOT NOW *****\n");
522                 sync();
523                 return (4);
524         }
525         return (0);
526 }
527
528 static int
529 chkdoreload(struct statfs *mntp)
530 {
531         struct iovec *iov;
532         int iovlen;
533         int fflags;
534         char errmsg[255];
535
536         if (mntp == NULL)
537                 return (0);
538
539         iov = NULL;
540         iovlen = 0;
541         errmsg[0] = '\0';
542         fflags = mntp->f_flags;
543         /*
544          * We modified a mounted file system.  Do a mount update on
545          * it unless it is read-write, so we can continue using it
546          * as safely as possible.
547          */
548         if (mntp->f_flags & MNT_RDONLY) {
549                 /*
550                  * XXX: Need to kick out MNT_ROOTFS until we fix
551                  * nmount().
552                  */
553                 fflags &= ~MNT_ROOTFS;
554                 fflags = fflags | MNT_RELOAD;
555                 build_iovec(&iov, &iovlen, "fstype", "ffs", 4);
556                 build_iovec(&iov, &iovlen, "from", mntp->f_mntfromname,
557                     (size_t)-1);
558                 build_iovec(&iov, &iovlen, "fspath", mntp->f_mntonname,
559                     (size_t)-1);
560                 build_iovec(&iov, &iovlen, "errmsg", errmsg,
561                     sizeof(errmsg));
562                 build_iovec(&iov, &iovlen, "update", NULL, 0);
563                 /*
564                  * XX: We need the following line until we clean up
565                  * nmount parsing of root mounts and NFS root mounts.
566                  */ 
567                 build_iovec(&iov, &iovlen, "ro", NULL, 0);
568                 if (nmount(iov, iovlen, fflags) == 0) {
569                         return (0);
570                 }
571                 pwarn("mount reload of '%s' failed: %s %s\n\n",
572                     mntp->f_mntonname, strerror(errno), errmsg);
573                 return (1);
574         }
575         return (0);
576 }
577
578 /*
579  * Get the mount point information for name.
580  */
581 static struct statfs *
582 getmntpt(const char *name)
583 {
584         struct stat devstat, mntdevstat;
585         char device[sizeof(_PATH_DEV) - 1 + MNAMELEN];
586         char *ddevname;
587         struct statfs *mntbuf, *statfsp;
588         int i, mntsize, isdev;
589
590         if (stat(name, &devstat) != 0)
591                 return (NULL);
592         if (S_ISCHR(devstat.st_mode) || S_ISBLK(devstat.st_mode))
593                 isdev = 1;
594         else
595                 isdev = 0;
596         mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
597         for (i = 0; i < mntsize; i++) {
598                 statfsp = &mntbuf[i];
599                 ddevname = statfsp->f_mntfromname;
600                 if (*ddevname != '/') {
601                         strcpy(device, _PATH_DEV);
602                         strcat(device, ddevname);
603                         strcpy(statfsp->f_mntfromname, device);
604                 }
605                 if (isdev == 0) {
606                         if (strcmp(name, statfsp->f_mntonname))
607                                 continue;
608                         return (statfsp);
609                 }
610                 if (stat(ddevname, &mntdevstat) == 0 &&
611                     mntdevstat.st_rdev == devstat.st_rdev)
612                         return (statfsp);
613         }
614         statfsp = NULL;
615         return (statfsp);
616 }
617
618 static void
619 usage(void)
620 {
621         (void) fprintf(stderr,
622             "usage: %s [-BCFpfny] [-b block] [-c level] [-m mode] "
623                         "filesystem ...\n",
624             getprogname());
625         exit(1);
626 }