Import device-tree files from Linux 5.15
[freebsd.git] / sbin / fsck / fsck.c
1 /*      $NetBSD: fsck.c,v 1.30 2003/08/07 10:04:15 agc Exp $    */
2
3 /*-
4  * SPDX-License-Identifier: BSD-3-Clause
5  *
6  * Copyright (c) 1996 Christos Zoulas. All rights reserved.
7  * Copyright (c) 1980, 1989, 1993, 1994
8  *      The Regents of the University of California.  All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  * From: @(#)mount.c    8.19 (Berkeley) 4/19/94
35  * From: $NetBSD: mount.c,v 1.24 1995/11/18 03:34:29 cgd Exp 
36  * $NetBSD: fsck.c,v 1.30 2003/08/07 10:04:15 agc Exp $
37  */
38
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
41
42 #include <sys/param.h>
43 #include <sys/mount.h>
44 #include <sys/queue.h>
45 #include <sys/wait.h>
46 #include <sys/disk.h>
47 #include <sys/ioctl.h>
48
49 #include <ctype.h>
50 #include <err.h>
51 #include <fstab.h>
52 #include <fcntl.h>
53 #include <paths.h>
54 #include <signal.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <unistd.h>
59
60 #include "fsutil.h"
61
62 static enum { IN_LIST, NOT_IN_LIST } which = NOT_IN_LIST;
63
64 static TAILQ_HEAD(fstypelist, entry) opthead, selhead;
65
66 struct entry {
67         char *type;
68         char *options;
69         TAILQ_ENTRY(entry) entries;
70 };
71
72 static char *options = NULL;
73 static int flags = 0;
74 static int forceflag = 0;
75
76 static int checkfs(const char *, const char *, const char *, const char *, pid_t *);
77 static int selected(const char *);
78 static void addoption(char *);
79 static const char *getoptions(const char *);
80 static void addentry(struct fstypelist *, const char *, const char *);
81 static void maketypelist(char *);
82 static void catopt(char **, const char *);
83 static void mangle(char *, int *, const char ** volatile *, int *);
84 static const char *getfstype(const char *);
85 static void usage(void) __dead2;
86 static int isok(struct fstab *);
87
88 static struct {
89         const char *ptype;
90         const char *name;
91 } ptype_map[] = {
92         { "ufs",        "ffs" },
93         { "ffs",        "ffs" },
94         { "fat",        "msdosfs" },
95         { "efi",        "msdosfs" },
96         { NULL,         NULL },
97 };
98
99 int
100 main(int argc, char *argv[])
101 {
102         struct fstab *fs;
103         int i, rval = 0;
104         const char *vfstype = NULL;
105         char globopt[3];
106         const char *etc_fstab;
107
108         globopt[0] = '-';
109         globopt[2] = '\0';
110
111         TAILQ_INIT(&selhead);
112         TAILQ_INIT(&opthead);
113
114         etc_fstab = NULL;
115         while ((i = getopt(argc, argv, "BCdvpfFnyl:t:T:c:")) != -1)
116                 switch (i) {
117                 case 'B':
118                         if (flags & CHECK_BACKGRD)
119                                 errx(1, "Cannot specify -B and -F.");
120                         flags |= DO_BACKGRD;
121                         break;
122
123                 case 'd':
124                         flags |= CHECK_DEBUG;
125                         break;
126
127                 case 'v':
128                         flags |= CHECK_VERBOSE;
129                         break;
130
131                 case 'F':
132                         if (flags & DO_BACKGRD)
133                                 errx(1, "Cannot specify -B and -F.");
134                         flags |= CHECK_BACKGRD;
135                         break;
136
137                 case 'p':
138                         flags |= CHECK_PREEN;
139                         /*FALLTHROUGH*/
140                 case 'C':
141                         flags |= CHECK_CLEAN;
142                         /*FALLTHROUGH*/
143                 case 'n':
144                 case 'y':
145                         globopt[1] = i;
146                         catopt(&options, globopt);
147                         break;
148
149                 case 'f':
150                         forceflag = 1;
151                         globopt[1] = i;
152                         catopt(&options, globopt);
153                         break;
154
155                 case 'l':
156                         warnx("Ignoring obsolete -l option\n");
157                         break;
158
159                 case 'T':
160                         if (*optarg)
161                                 addoption(optarg);
162                         break;
163
164                 case 't':
165                         if (!TAILQ_EMPTY(&selhead))
166                                 errx(1, "only one -t option may be specified.");
167
168                         maketypelist(optarg);
169                         vfstype = optarg;
170                         break;
171
172                 case 'c':
173                         etc_fstab = optarg;
174                         break;
175
176                 case '?':
177                 default:
178                         usage();
179                         /* NOTREACHED */
180                 }
181
182         argc -= optind;
183         argv += optind;
184
185         if (etc_fstab != NULL)
186                 setfstab(etc_fstab);
187
188         if (argc == 0)
189                 return checkfstab(flags, isok, checkfs);
190
191 #define BADTYPE(type)                                                   \
192         (strcmp(type, FSTAB_RO) &&                                      \
193             strcmp(type, FSTAB_RW) && strcmp(type, FSTAB_RQ))
194
195
196         for (; argc--; argv++) {
197                 const char *spec, *mntpt, *type, *cp;
198                 char device[MAXPATHLEN];
199                 struct statfs *mntp;
200
201                 mntpt = NULL;
202                 spec = *argv;
203                 cp = strrchr(spec, '/');
204                 if (cp == NULL) {
205                         (void)snprintf(device, sizeof(device), "%s%s",
206                                 _PATH_DEV, spec);
207                         spec = device;
208                 }
209                 mntp = getmntpt(spec);
210                 if (mntp != NULL) {
211                         spec = mntp->f_mntfromname;
212                         mntpt = mntp->f_mntonname;
213                 }
214                 if ((fs = getfsfile(spec)) == NULL &&
215                     (fs = getfsspec(spec)) == NULL) {
216                         if (vfstype == NULL)
217                                 vfstype = getfstype(spec);
218                         if (vfstype == NULL)
219                                 vfstype = "ufs";
220                         type = vfstype;
221                         devcheck(spec);
222                 } else {
223                         spec = fs->fs_spec;
224                         type = fs->fs_vfstype;
225                         mntpt = fs->fs_file;
226                         if (BADTYPE(fs->fs_type))
227                                 errx(1, "%s has unknown file system type.",
228                                     spec);
229                 }
230                 if ((flags & CHECK_BACKGRD) &&
231                     checkfs(type, spec, mntpt, "-F", NULL) == 0) {
232                         printf("%s: DEFER FOR BACKGROUND CHECKING\n", *argv);
233                         continue;
234                 }
235                 if ((flags & DO_BACKGRD) && forceflag == 0 &&
236                     checkfs(type, spec, mntpt, "-F", NULL) != 0)
237                         continue;
238
239                 rval |= checkfs(type, spec, mntpt, NULL, NULL);
240         }
241
242         return rval;
243 }
244
245
246 static int
247 isok(struct fstab *fs)
248 {
249         int i;
250
251         if (fs->fs_passno == 0)
252                 return (0);
253         if (BADTYPE(fs->fs_type))
254                 return (0);
255         if (!selected(fs->fs_vfstype))
256                 return (0);
257         /* If failok, always check now */
258         if (getfsopt(fs, "failok"))
259                 return (1);
260         /*
261          * If the -B flag has been given, then process the needed
262          * background checks. Background checks cannot be run on
263          * file systems that will be mounted read-only or that were
264          * not mounted at boot time (typically those marked `noauto').
265          * If these basic tests are passed, check with the file system
266          * itself to see if it is willing to do background checking
267          * by invoking its check program with the -F flag.
268          */
269         if (flags & DO_BACKGRD) {
270                 if (!strcmp(fs->fs_type, FSTAB_RO))
271                         return (0);
272                 if (getmntpt(fs->fs_spec) == NULL)
273                         return (0);
274                 if (checkfs(fs->fs_vfstype, fs->fs_spec, fs->fs_file, "-F", 0))
275                         return (0);
276                 return (1);
277         }
278         /*
279          * If the -F flag has been given, then consider deferring the
280          * check to background. Background checks cannot be run on
281          * file systems that will be mounted read-only or that will
282          * not be mounted at boot time (e.g., marked `noauto'). If
283          * these basic tests are passed, check with the file system
284          * itself to see if it is willing to defer to background
285          * checking by invoking its check program with the -F flag.
286          */
287         if ((flags & CHECK_BACKGRD) == 0 || !strcmp(fs->fs_type, FSTAB_RO))
288                 return (1);
289         for (i = strlen(fs->fs_mntops) - 6; i >= 0; i--)
290                 if (!strncmp(&fs->fs_mntops[i], "noauto", 6))
291                         break;
292         if (i >= 0)
293                 return (1);
294         if (checkfs(fs->fs_vfstype, fs->fs_spec, fs->fs_file, "-F", NULL) != 0)
295                 return (1);
296         printf("%s: DEFER FOR BACKGROUND CHECKING\n", fs->fs_spec);
297         return (0);
298 }
299
300
301 static int
302 checkfs(const char *pvfstype, const char *spec, const char *mntpt,
303     const char *auxopt, pid_t *pidp)
304 {
305         const char ** volatile argv;
306         pid_t pid;
307         int argc, i, status, maxargc;
308         char *optbuf, execbase[MAXPATHLEN];
309         char *vfstype = NULL;
310         const char *extra = NULL;
311
312 #ifdef __GNUC__
313         /* Avoid vfork clobbering */
314         (void) &optbuf;
315         (void) &vfstype;
316 #endif
317         /*
318          * We convert the vfstype to lowercase and any spaces to underscores
319          * to not confuse the issue
320          *
321          * XXX This is a kludge to make automatic filesystem type guessing
322          * from the disklabel work for "4.2BSD" filesystems.  It does a
323          * very limited subset of transliteration to a normalised form of
324          * filesystem name, and we do not seem to enforce a filesystem
325          * name character set.
326          */
327         vfstype = strdup(pvfstype);
328         if (vfstype == NULL)
329                 perr("strdup(pvfstype)");
330         for (i = 0; i < (int)strlen(vfstype); i++) {
331                 vfstype[i] = tolower(vfstype[i]);
332                 if (vfstype[i] == ' ')
333                         vfstype[i] = '_';
334         }
335
336         extra = getoptions(vfstype);
337         optbuf = NULL;
338         if (options)
339                 catopt(&optbuf, options);
340         if (extra)
341                 catopt(&optbuf, extra);
342         if (auxopt)
343                 catopt(&optbuf, auxopt);
344         else if (flags & DO_BACKGRD)
345                 catopt(&optbuf, "-B");
346
347         maxargc = 64;
348         argv = emalloc(sizeof(char *) * maxargc);
349
350         (void) snprintf(execbase, sizeof(execbase), "fsck_%s", vfstype);
351         argc = 0;
352         argv[argc++] = execbase;
353         if (optbuf)
354                 mangle(optbuf, &argc, &argv, &maxargc);
355         argv[argc++] = spec;
356         argv[argc] = NULL;
357
358         if (flags & (CHECK_DEBUG|CHECK_VERBOSE)) {
359                 (void)printf("start %s %swait", mntpt, 
360                         pidp ? "no" : "");
361                 for (i = 0; i < argc; i++)
362                         (void)printf(" %s", argv[i]);
363                 (void)printf("\n");
364         }
365
366         switch (pid = vfork()) {
367         case -1:                                /* Error. */
368                 warn("vfork");
369                 if (optbuf)
370                         free(optbuf);
371                 free(vfstype);
372                 return (1);
373
374         case 0:                                 /* Child. */
375                 if ((flags & CHECK_DEBUG) && auxopt == NULL)
376                         _exit(0);
377
378                 /* Go find an executable. */
379                 execvP(execbase, _PATH_SYSPATH, __DECONST(char * const *, argv));
380                 if (spec)
381                         warn("exec %s for %s in %s", execbase, spec, _PATH_SYSPATH);
382                 else
383                         warn("exec %s in %s", execbase, _PATH_SYSPATH);
384                 _exit(1);
385                 /* NOTREACHED */
386
387         default:                                /* Parent. */
388                 if (optbuf)
389                         free(optbuf);
390
391                 free(vfstype);
392
393                 if (pidp) {
394                         *pidp = pid;
395                         return 0;
396                 }
397
398                 if (waitpid(pid, &status, 0) < 0) {
399                         warn("waitpid");
400                         return (1);
401                 }
402
403                 if (WIFEXITED(status)) {
404                         if (WEXITSTATUS(status) != 0)
405                                 return (WEXITSTATUS(status));
406                 }
407                 else if (WIFSIGNALED(status)) {
408                         warnx("%s: %s", spec, strsignal(WTERMSIG(status)));
409                         return (1);
410                 }
411                 break;
412         }
413
414         return (0);
415 }
416
417
418 static int
419 selected(const char *type)
420 {
421         struct entry *e;
422
423         /* If no type specified, it's always selected. */
424         TAILQ_FOREACH(e, &selhead, entries)
425                 if (!strncmp(e->type, type, MFSNAMELEN))
426                         return which == IN_LIST ? 1 : 0;
427
428         return which == IN_LIST ? 0 : 1;
429 }
430
431
432 static const char *
433 getoptions(const char *type)
434 {
435         struct entry *e;
436
437         TAILQ_FOREACH(e, &opthead, entries)
438                 if (!strncmp(e->type, type, MFSNAMELEN))
439                         return e->options;
440         return "";
441 }
442
443
444 static void
445 addoption(char *optstr)
446 {
447         char *newoptions;
448         struct entry *e;
449
450         if ((newoptions = strchr(optstr, ':')) == NULL)
451                 errx(1, "Invalid option string");
452
453         *newoptions++ = '\0';
454
455         TAILQ_FOREACH(e, &opthead, entries)
456                 if (!strncmp(e->type, optstr, MFSNAMELEN)) {
457                         catopt(&e->options, newoptions);
458                         return;
459                 }
460         addentry(&opthead, optstr, newoptions);
461 }
462
463
464 static void
465 addentry(struct fstypelist *list, const char *type, const char *opts)
466 {
467         struct entry *e;
468
469         e = emalloc(sizeof(struct entry));
470         e->type = estrdup(type);
471         e->options = estrdup(opts);
472         TAILQ_INSERT_TAIL(list, e, entries);
473 }
474
475
476 static void
477 maketypelist(char *fslist)
478 {
479         char *ptr;
480
481         if ((fslist == NULL) || (fslist[0] == '\0'))
482                 errx(1, "empty type list");
483
484         if (fslist[0] == 'n' && fslist[1] == 'o') {
485                 fslist += 2;
486                 which = NOT_IN_LIST;
487         }
488         else
489                 which = IN_LIST;
490
491         while ((ptr = strsep(&fslist, ",")) != NULL)
492                 addentry(&selhead, ptr, "");
493
494 }
495
496
497 static void
498 catopt(char **sp, const char *o)
499 {
500         char *s;
501         size_t i, j;
502
503         s = *sp;
504         if (s) {
505                 i = strlen(s);
506                 j = i + 1 + strlen(o) + 1;
507                 s = erealloc(s, j);
508                 (void)snprintf(s + i, j, ",%s", o);
509         } else
510                 s = estrdup(o);
511         *sp = s;
512 }
513
514
515 static void
516 mangle(char *opts, int *argcp, const char ** volatile *argvp, int *maxargcp)
517 {
518         char *p, *s;
519         int argc, maxargc;
520         const char **argv;
521
522         argc = *argcp;
523         argv = *argvp;
524         maxargc = *maxargcp;
525
526         for (s = opts; (p = strsep(&s, ",")) != NULL;) {
527                 /* Always leave space for one more argument and the NULL. */
528                 if (argc >= maxargc - 3) {
529                         maxargc <<= 1;
530                         argv = erealloc(argv, maxargc * sizeof(char *));
531                 }
532                 if (*p != '\0')  {
533                         if (*p == '-') {
534                                 argv[argc++] = p;
535                                 p = strchr(p, '=');
536                                 if (p) {
537                                         *p = '\0';
538                                         argv[argc++] = p+1;
539                                 }
540                         } else {
541                                 argv[argc++] = "-o";
542                                 argv[argc++] = p;
543                         }
544                 }
545         }
546
547         *argcp = argc;
548         *argvp = argv;
549         *maxargcp = maxargc;
550 }
551
552 static const char *
553 getfstype(const char *str)
554 {
555         struct diocgattr_arg attr;
556         int fd, i;
557
558         if ((fd = open(str, O_RDONLY)) == -1)
559                 err(1, "cannot open `%s'", str);
560
561         strncpy(attr.name, "PART::type", sizeof(attr.name));
562         memset(&attr.value, 0, sizeof(attr.value));
563         attr.len = sizeof(attr.value);
564         if (ioctl(fd, DIOCGATTR, &attr) == -1) {
565                 (void) close(fd);
566                 return(NULL);
567         }
568         (void) close(fd);
569         for (i = 0; ptype_map[i].ptype != NULL; i++)
570                 if (strstr(attr.value.str, ptype_map[i].ptype) != NULL)
571                         return (ptype_map[i].name);
572         return (NULL);
573 }
574
575
576 static void
577 usage(void)
578 {
579         static const char common[] =
580             "[-Cdfnpvy] [-B | -F] [-T fstype:fsoptions] [-t fstype] [-c fstab]";
581
582         (void)fprintf(stderr, "usage: %s %s [special | node] ...\n",
583             getprogname(), common);
584         exit(1);
585 }