]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sbin/fsck_ffs/main.c
MFC r290326:
[FreeBSD/stable/8.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         inoopt = 0;
85         while ((ch = getopt(argc, argv, "b:Bc:CdEfFm:npry")) != -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 'E':
110                         Eflag++;
111                         break;
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 'r':
142                         inoopt++;
143                         break;
144
145                 case 'y':
146                         yflag++;
147                         nflag = 0;
148                         break;
149
150                 default:
151                         usage();
152                 }
153         }
154         argc -= optind;
155         argv += optind;
156
157         if (!argc)
158                 usage();
159
160         if (signal(SIGINT, SIG_IGN) != SIG_IGN)
161                 (void)signal(SIGINT, catch);
162         if (ckclean)
163                 (void)signal(SIGQUIT, catchquit);
164         signal(SIGINFO, infohandler);
165         if (bkgrdflag) {
166                 signal(SIGALRM, alarmhandler);
167                 itimerval.it_interval.tv_sec = 5;
168                 itimerval.it_interval.tv_usec = 0;
169                 itimerval.it_value.tv_sec = 5;
170                 itimerval.it_value.tv_usec = 0;
171                 setitimer(ITIMER_REAL, &itimerval, NULL);
172         }
173         /*
174          * Push up our allowed memory limit so we can cope
175          * with huge file systems.
176          */
177         if (getrlimit(RLIMIT_DATA, &rlimit) == 0) {
178                 rlimit.rlim_cur = rlimit.rlim_max;
179                 (void)setrlimit(RLIMIT_DATA, &rlimit);
180         }
181         while (argc-- > 0)
182                 (void)checkfilesys(*argv++);
183
184         if (returntosingle)
185                 ret = 2;
186         exit(ret);
187 }
188
189 static int
190 argtoi(int flag, const char *req, const char *str, int base)
191 {
192         char *cp;
193         int ret;
194
195         ret = (int)strtol(str, &cp, base);
196         if (cp == str || *cp)
197                 errx(EEXIT, "-%c flag requires a %s", flag, req);
198         return (ret);
199 }
200
201 /*
202  * Check the specified file system.
203  */
204 /* ARGSUSED */
205 static int
206 checkfilesys(char *filesys)
207 {
208         ufs2_daddr_t n_ffree, n_bfree;
209         struct dups *dp;
210         struct statfs *mntp;
211         struct stat snapdir;
212         struct group *grp;
213         ufs2_daddr_t blks;
214         struct iovec *iov;
215         char errmsg[255];
216         int iovlen;
217         int cylno;
218         ino_t files;
219         size_t size;
220
221         iov = NULL;
222         iovlen = 0;
223         errmsg[0] = '\0';
224
225         cdevname = filesys;
226         if (debug && ckclean)
227                 pwarn("starting\n");
228         /*
229          * Make best effort to get the disk name. Check first to see
230          * if it is listed among the mounted file systems. Failing that
231          * check to see if it is listed in /etc/fstab.
232          */
233         mntp = getmntpt(filesys);
234         if (mntp != NULL)
235                 filesys = mntp->f_mntfromname;
236         else
237                 filesys = blockcheck(filesys);
238         /*
239          * If -F flag specified, check to see whether a background check
240          * is possible and needed. If possible and needed, exit with
241          * status zero. Otherwise exit with status non-zero. A non-zero
242          * exit status will cause a foreground check to be run.
243          */
244         sblock_init();
245         if (bkgrdcheck) {
246                 if ((fsreadfd = open(filesys, O_RDONLY)) < 0 || readsb(0) == 0)
247                         exit(3);        /* Cannot read superblock */
248                 close(fsreadfd);
249                 if (sblock.fs_flags & FS_NEEDSFSCK)
250                         exit(4);        /* Earlier background failed */
251                 if ((sblock.fs_flags & FS_DOSOFTDEP) == 0)
252                         exit(5);        /* Not running soft updates */
253                 size = MIBSIZE;
254                 if (sysctlnametomib("vfs.ffs.adjrefcnt", adjrefcnt, &size) < 0)
255                         exit(6);        /* Lacks kernel support */
256                 if ((mntp == NULL && sblock.fs_clean == 1) ||
257                     (mntp != NULL && (sblock.fs_flags & FS_UNCLEAN) == 0))
258                         exit(7);        /* Filesystem clean, report it now */
259                 exit(0);
260         }
261         if (ckclean && skipclean) {
262                 /*
263                  * If file system is gjournaled, check it here.
264                  */
265                 if ((fsreadfd = open(filesys, O_RDONLY)) < 0 || readsb(0) == 0)
266                         exit(3);        /* Cannot read superblock */
267                 close(fsreadfd);
268                 if ((sblock.fs_flags & FS_GJOURNAL) != 0) {
269                         //printf("GJournaled file system detected on %s.\n",
270                         //    filesys);
271                         if (sblock.fs_clean == 1) {
272                                 pwarn("FILE SYSTEM CLEAN; SKIPPING CHECKS\n");
273                                 exit(0);
274                         }
275                         if ((sblock.fs_flags & (FS_UNCLEAN | FS_NEEDSFSCK)) == 0) {
276                                 gjournal_check(filesys);
277                                 if (chkdoreload(mntp) == 0)
278                                         exit(0);
279                                 exit(4);
280                         } else {
281                                 pfatal("UNEXPECTED INCONSISTENCY, %s\n",
282                                     "CANNOT RUN FAST FSCK\n");
283                         }
284                 }
285         }
286         /*
287          * If we are to do a background check:
288          *      Get the mount point information of the file system
289          *      create snapshot file
290          *      return created snapshot file
291          *      if not found, clear bkgrdflag and proceed with normal fsck
292          */
293         if (bkgrdflag) {
294                 if (mntp == NULL) {
295                         bkgrdflag = 0;
296                         pfatal("NOT MOUNTED, CANNOT RUN IN BACKGROUND\n");
297                 } else if ((mntp->f_flags & MNT_SOFTDEP) == 0) {
298                         bkgrdflag = 0;
299                         pfatal("NOT USING SOFT UPDATES, %s\n",
300                             "CANNOT RUN IN BACKGROUND");
301                 } else if ((mntp->f_flags & MNT_RDONLY) != 0) {
302                         bkgrdflag = 0;
303                         pfatal("MOUNTED READ-ONLY, CANNOT RUN IN BACKGROUND\n");
304                 } else if ((fsreadfd = open(filesys, O_RDONLY)) >= 0) {
305                         if (readsb(0) != 0) {
306                                 if (sblock.fs_flags & FS_NEEDSFSCK) {
307                                         bkgrdflag = 0;
308                                         pfatal("UNEXPECTED INCONSISTENCY, %s\n",
309                                             "CANNOT RUN IN BACKGROUND\n");
310                                 }
311                                 if ((sblock.fs_flags & FS_UNCLEAN) == 0 &&
312                                     skipclean && ckclean) {
313                                         /*
314                                          * file system is clean;
315                                          * skip snapshot and report it clean
316                                          */
317                                         pwarn("FILE SYSTEM CLEAN; %s\n",
318                                             "SKIPPING CHECKS");
319                                         goto clean;
320                                 }
321                         }
322                         close(fsreadfd);
323                 }
324                 if (bkgrdflag) {
325                         snprintf(snapname, sizeof snapname, "%s/.snap",
326                             mntp->f_mntonname);
327                         if (stat(snapname, &snapdir) < 0) {
328                                 if (errno != ENOENT) {
329                                         bkgrdflag = 0;
330                                         pfatal("CANNOT FIND %s %s: %s, %s\n",
331                                             "SNAPSHOT DIRECTORY",
332                                             snapname, strerror(errno),
333                                             "CANNOT RUN IN BACKGROUND");
334                                 } else if ((grp = getgrnam("operator")) == 0 ||
335                                     mkdir(snapname, 0770) < 0 ||
336                                     chown(snapname, -1, grp->gr_gid) < 0 ||
337                                     chmod(snapname, 0770) < 0) {
338                                         bkgrdflag = 0;
339                                         pfatal("CANNOT CREATE %s %s: %s, %s\n",
340                                             "SNAPSHOT DIRECTORY",
341                                             snapname, strerror(errno),
342                                             "CANNOT RUN IN BACKGROUND");
343                                 }
344                         } else if (!S_ISDIR(snapdir.st_mode)) {
345                                 bkgrdflag = 0;
346                                 pfatal("%s IS NOT A DIRECTORY, %s\n", snapname,
347                                     "CANNOT RUN IN BACKGROUND");
348                         }
349                 }
350                 if (bkgrdflag) {
351                         snprintf(snapname, sizeof snapname,
352                             "%s/.snap/fsck_snapshot", mntp->f_mntonname);
353                         build_iovec(&iov, &iovlen, "fstype", "ffs", 4);
354                         build_iovec(&iov, &iovlen, "from", snapname,
355                             (size_t)-1);
356                         build_iovec(&iov, &iovlen, "fspath", mntp->f_mntonname,
357                             (size_t)-1);
358                         build_iovec(&iov, &iovlen, "errmsg", errmsg,
359                             sizeof(errmsg));
360                         build_iovec(&iov, &iovlen, "update", NULL, 0);
361                         build_iovec(&iov, &iovlen, "snapshot", NULL, 0);
362
363                         while (nmount(iov, iovlen, mntp->f_flags) < 0) {
364                                 if (errno == EEXIST && unlink(snapname) == 0)
365                                         continue;
366                                 bkgrdflag = 0;
367                                 pfatal("CANNOT CREATE SNAPSHOT %s: %s %s\n",
368                                     snapname, strerror(errno), errmsg);
369                                 break;
370                         }
371                         if (bkgrdflag != 0)
372                                 filesys = snapname;
373                 }
374         }
375
376         switch (setup(filesys)) {
377         case 0:
378                 if (preen)
379                         pfatal("CAN'T CHECK FILE SYSTEM.");
380                 return (0);
381         case -1:
382         clean:
383                 pwarn("clean, %ld free ", (long)(sblock.fs_cstotal.cs_nffree +
384                     sblock.fs_frag * sblock.fs_cstotal.cs_nbfree));
385                 printf("(%lld frags, %lld blocks, %.1f%% fragmentation)\n",
386                     (long long)sblock.fs_cstotal.cs_nffree,
387                     (long long)sblock.fs_cstotal.cs_nbfree,
388                     sblock.fs_cstotal.cs_nffree * 100.0 / sblock.fs_dsize);
389                 return (0);
390         }
391         
392         /*
393          * Cleared if any questions answered no. Used to decide if
394          * the superblock should be marked clean.
395          */
396         resolved = 1;
397         /*
398          * 1: scan inodes tallying blocks used
399          */
400         if (preen == 0) {
401                 printf("** Last Mounted on %s\n", sblock.fs_fsmnt);
402                 if (mntp != NULL && mntp->f_flags & MNT_ROOTFS)
403                         printf("** Root file system\n");
404                 printf("** Phase 1 - Check Blocks and Sizes\n");
405         }
406         pass1();
407
408         /*
409          * 1b: locate first references to duplicates, if any
410          */
411         if (duplist) {
412                 if (preen || usedsoftdep)
413                         pfatal("INTERNAL ERROR: dups with -p");
414                 printf("** Phase 1b - Rescan For More DUPS\n");
415                 pass1b();
416         }
417
418         /*
419          * 2: traverse directories from root to mark all connected directories
420          */
421         if (preen == 0)
422                 printf("** Phase 2 - Check Pathnames\n");
423         pass2();
424
425         /*
426          * 3: scan inodes looking for disconnected directories
427          */
428         if (preen == 0)
429                 printf("** Phase 3 - Check Connectivity\n");
430         pass3();
431
432         /*
433          * 4: scan inodes looking for disconnected files; check reference counts
434          */
435         if (preen == 0)
436                 printf("** Phase 4 - Check Reference Counts\n");
437         pass4();
438
439         /*
440          * 5: check and repair resource counts in cylinder groups
441          */
442         if (preen == 0)
443                 printf("** Phase 5 - Check Cyl groups\n");
444         pass5();
445
446         /*
447          * print out summary statistics
448          */
449         n_ffree = sblock.fs_cstotal.cs_nffree;
450         n_bfree = sblock.fs_cstotal.cs_nbfree;
451         files = maxino - ROOTINO - sblock.fs_cstotal.cs_nifree - n_files;
452         blks = n_blks +
453             sblock.fs_ncg * (cgdmin(&sblock, 0) - cgsblock(&sblock, 0));
454         blks += cgsblock(&sblock, 0) - cgbase(&sblock, 0);
455         blks += howmany(sblock.fs_cssize, sblock.fs_fsize);
456         blks = maxfsblock - (n_ffree + sblock.fs_frag * n_bfree) - blks;
457         if (bkgrdflag && (files > 0 || blks > 0)) {
458                 countdirs = sblock.fs_cstotal.cs_ndir - countdirs;
459                 pwarn("Reclaimed: %ld directories, %ld files, %lld fragments\n",
460                     countdirs, (long)files - countdirs, (long long)blks);
461         }
462         pwarn("%ld files, %jd used, %ju free ",
463             (long)n_files, (intmax_t)n_blks,
464             (uintmax_t)n_ffree + sblock.fs_frag * n_bfree);
465         printf("(%ju frags, %ju blocks, %.1f%% fragmentation)\n",
466             (uintmax_t)n_ffree, (uintmax_t)n_bfree,
467             n_ffree * 100.0 / sblock.fs_dsize);
468         if (debug) {
469                 if (files < 0)
470                         printf("%d inodes missing\n", -files);
471                 if (blks < 0)
472                         printf("%lld blocks missing\n", -(long long)blks);
473                 if (duplist != NULL) {
474                         printf("The following duplicate blocks remain:");
475                         for (dp = duplist; dp; dp = dp->next)
476                                 printf(" %lld,", (long long)dp->dup);
477                         printf("\n");
478                 }
479         }
480         duplist = (struct dups *)0;
481         muldup = (struct dups *)0;
482         inocleanup();
483         if (fsmodified) {
484                 sblock.fs_time = time(NULL);
485                 sbdirty();
486         }
487         if (cvtlevel && sblk.b_dirty) {
488                 /*
489                  * Write out the duplicate super blocks
490                  */
491                 for (cylno = 0; cylno < sblock.fs_ncg; cylno++)
492                         blwrite(fswritefd, (char *)&sblock,
493                             fsbtodb(&sblock, cgsblock(&sblock, cylno)),
494                             SBLOCKSIZE);
495         }
496         if (rerun)
497                 resolved = 0;
498
499         /*
500          * Check to see if the file system is mounted read-write.
501          */
502         if (bkgrdflag == 0 && mntp != NULL && (mntp->f_flags & MNT_RDONLY) == 0)
503                 resolved = 0;
504         ckfini(resolved);
505
506         for (cylno = 0; cylno < sblock.fs_ncg; cylno++)
507                 if (inostathead[cylno].il_stat != NULL)
508                         free((char *)inostathead[cylno].il_stat);
509         free((char *)inostathead);
510         inostathead = NULL;
511         if (fsmodified && !preen)
512                 printf("\n***** FILE SYSTEM WAS MODIFIED *****\n");
513         if (rerun)
514                 printf("\n***** PLEASE RERUN FSCK *****\n");
515         if (chkdoreload(mntp) != 0) {
516                 if (!fsmodified)
517                         return (0);
518                 if (!preen)
519                         printf("\n***** REBOOT NOW *****\n");
520                 sync();
521                 return (4);
522         }
523         return (0);
524 }
525
526 static int
527 chkdoreload(struct statfs *mntp)
528 {
529         struct iovec *iov;
530         int iovlen;
531         char errmsg[255];
532
533         if (mntp == NULL)
534                 return (0);
535
536         iov = NULL;
537         iovlen = 0;
538         errmsg[0] = '\0';
539         /*
540          * We modified a mounted file system.  Do a mount update on
541          * it unless it is read-write, so we can continue using it
542          * as safely as possible.
543          */
544         if (mntp->f_flags & MNT_RDONLY) {
545                 build_iovec(&iov, &iovlen, "fstype", "ffs", 4);
546                 build_iovec(&iov, &iovlen, "from", mntp->f_mntfromname,
547                     (size_t)-1);
548                 build_iovec(&iov, &iovlen, "fspath", mntp->f_mntonname,
549                     (size_t)-1);
550                 build_iovec(&iov, &iovlen, "errmsg", errmsg,
551                     sizeof(errmsg));
552                 build_iovec(&iov, &iovlen, "update", NULL, 0);
553                 build_iovec(&iov, &iovlen, "reload", NULL, 0);
554                 /*
555                  * XX: We need the following line until we clean up
556                  * nmount parsing of root mounts and NFS root mounts.
557                  */ 
558                 build_iovec(&iov, &iovlen, "ro", NULL, 0);
559                 if (nmount(iov, iovlen, mntp->f_flags) == 0) {
560                         return (0);
561                 }
562                 pwarn("mount reload of '%s' failed: %s %s\n\n",
563                     mntp->f_mntonname, strerror(errno), errmsg);
564                 return (1);
565         }
566         return (0);
567 }
568
569 /*
570  * Get the mount point information for name.
571  */
572 static struct statfs *
573 getmntpt(const char *name)
574 {
575         struct stat devstat, mntdevstat;
576         char device[sizeof(_PATH_DEV) - 1 + MNAMELEN];
577         char *ddevname;
578         struct statfs *mntbuf, *statfsp;
579         int i, mntsize, isdev;
580
581         if (stat(name, &devstat) != 0)
582                 return (NULL);
583         if (S_ISCHR(devstat.st_mode) || S_ISBLK(devstat.st_mode))
584                 isdev = 1;
585         else
586                 isdev = 0;
587         mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
588         for (i = 0; i < mntsize; i++) {
589                 statfsp = &mntbuf[i];
590                 ddevname = statfsp->f_mntfromname;
591                 if (*ddevname != '/') {
592                         strcpy(device, _PATH_DEV);
593                         strcat(device, ddevname);
594                         strcpy(statfsp->f_mntfromname, device);
595                 }
596                 if (isdev == 0) {
597                         if (strcmp(name, statfsp->f_mntonname))
598                                 continue;
599                         return (statfsp);
600                 }
601                 if (stat(ddevname, &mntdevstat) == 0 &&
602                     mntdevstat.st_rdev == devstat.st_rdev)
603                         return (statfsp);
604         }
605         statfsp = NULL;
606         return (statfsp);
607 }
608
609 static void
610 usage(void)
611 {
612         (void) fprintf(stderr,
613             "usage: %s [-BEFfnpry] [-b block] [-c level] [-m mode] "
614                         "filesystem ...\n",
615             getprogname());
616         exit(1);
617 }