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