b4257a2add34f0ef94234bd1904647a314b53b43
[platform/upstream/busybox.git] / e2fsprogs / fsck.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * fsck --- A generic, parallelizing front-end for the fsck program.
4  * It will automatically try to run fsck programs in parallel if the
5  * devices are on separate spindles.  It is based on the same ideas as
6  * the generic front end for fsck by David Engel and Fred van Kempen,
7  * but it has been completely rewritten from scratch to support
8  * parallel execution.
9  *
10  * Written by Theodore Ts'o, <tytso@mit.edu>
11  *
12  * Miquel van Smoorenburg (miquels@drinkel.ow.org) 20-Oct-1994:
13  *   o Changed -t fstype to behave like with mount when -A (all file
14  *     systems) or -M (like mount) is specified.
15  *   o fsck looks if it can find the fsck.type program to decide
16  *     if it should ignore the fs type. This way more fsck programs
17  *     can be added without changing this front-end.
18  *   o -R flag skip root file system.
19  *
20  * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
21  *      2001, 2002, 2003, 2004, 2005 by  Theodore Ts'o.
22  *
23  * Licensed under GPLv2, see file LICENSE in this source tree.
24  */
25
26 /* All filesystem specific hooks have been removed.
27  * If filesystem cannot be determined, we will execute
28  * "fsck.auto". Currently this also happens if you specify
29  * UUID=xxx or LABEL=xxx as an object to check.
30  * Detection code for that is also probably has to be in fsck.auto.
31  *
32  * In other words, this is _really_ is just a driver program which
33  * spawns actual fsck.something for each filesystem to check.
34  * It doesn't guess filesystem types from on-disk format.
35  */
36
37 //usage:#define fsck_trivial_usage
38 //usage:       "[-ANPRTV] [-C FD] [-t FSTYPE] [FS_OPTS] [BLOCKDEV]..."
39 //usage:#define fsck_full_usage "\n\n"
40 //usage:       "Check and repair filesystems\n"
41 //usage:     "\nOptions:"
42 //usage:     "\n        -A      Walk /etc/fstab and check all filesystems"
43 //usage:     "\n        -N      Don't execute, just show what would be done"
44 //usage:     "\n        -P      With -A, check filesystems in parallel"
45 //usage:     "\n        -R      With -A, skip the root filesystem"
46 //usage:     "\n        -T      Don't show title on startup"
47 //usage:     "\n        -V      Verbose"
48 //usage:     "\n        -C n    Write status information to specified filedescriptor"
49 //usage:     "\n        -t TYPE List of filesystem types to check"
50
51 #include "libbb.h"
52
53 /* "progress indicator" code is somewhat buggy and ext[23] specific.
54  * We should be filesystem agnostic. IOW: there should be a well-defined
55  * API for fsck.something, NOT ad-hoc hacks in generic fsck. */
56 #define DO_PROGRESS_INDICATOR 0
57
58 /* fsck 1.41.4 (27-Jan-2009) manpage says:
59  * 0   - No errors
60  * 1   - File system errors corrected
61  * 2   - System should be rebooted
62  * 4   - File system errors left uncorrected
63  * 8   - Operational error
64  * 16  - Usage or syntax error
65  * 32  - Fsck canceled by user request
66  * 128 - Shared library error
67  */
68 #define EXIT_OK          0
69 #define EXIT_NONDESTRUCT 1
70 #define EXIT_DESTRUCT    2
71 #define EXIT_UNCORRECTED 4
72 #define EXIT_ERROR       8
73 #define EXIT_USAGE       16
74 #define FSCK_CANCELED    32     /* Aborted with a signal or ^C */
75
76 /*
77  * Internal structure for mount table entries.
78  */
79 struct fs_info {
80         struct fs_info *next;
81         char    *device;
82         char    *mountpt;
83         char    *type;
84         char    *opts;
85         int     passno;
86         int     flags;
87 };
88
89 #define FLAG_DONE 1
90 #define FLAG_PROGRESS 2
91 /*
92  * Structure to allow exit codes to be stored
93  */
94 struct fsck_instance {
95         struct fsck_instance *next;
96         int     pid;
97         int     flags;
98 #if DO_PROGRESS_INDICATOR
99         time_t  start_time;
100 #endif
101         char    *prog;
102         char    *device;
103         char    *base_device; /* /dev/hda for /dev/hdaN etc */
104 };
105
106 static const char ignored_types[] ALIGN1 =
107         "ignore\0"
108         "iso9660\0"
109         "nfs\0"
110         "proc\0"
111         "sw\0"
112         "swap\0"
113         "tmpfs\0"
114         "devpts\0";
115
116 #if 0
117 static const char really_wanted[] ALIGN1 =
118         "minix\0"
119         "ext2\0"
120         "ext3\0"
121         "jfs\0"
122         "reiserfs\0"
123         "xiafs\0"
124         "xfs\0";
125 #endif
126
127 #define BASE_MD "/dev/md"
128
129 static char **args;
130 static int num_args;
131 static int verbose;
132
133 #define FS_TYPE_FLAG_NORMAL 0
134 #define FS_TYPE_FLAG_OPT    1
135 #define FS_TYPE_FLAG_NEGOPT 2
136 static char **fs_type_list;
137 static uint8_t *fs_type_flag;
138 static smallint fs_type_negated;
139
140 static smallint noexecute;
141 static smallint serialize;
142 static smallint skip_root;
143 /* static smallint like_mount; */
144 static smallint parallel_root;
145 static smallint force_all_parallel;
146
147 #if DO_PROGRESS_INDICATOR
148 static smallint progress;
149 static int progress_fd;
150 #endif
151
152 static int num_running;
153 static int max_running;
154 static char *fstype;
155 static struct fs_info *filesys_info;
156 static struct fs_info *filesys_last;
157 static struct fsck_instance *instance_list;
158
159 /*
160  * Return the "base device" given a particular device; this is used to
161  * assure that we only fsck one partition on a particular drive at any
162  * one time.  Otherwise, the disk heads will be seeking all over the
163  * place.  If the base device cannot be determined, return NULL.
164  *
165  * The base_device() function returns an allocated string which must
166  * be freed.
167  */
168 #if ENABLE_FEATURE_DEVFS
169 /*
170  * Required for the uber-silly devfs /dev/ide/host1/bus2/target3/lun3
171  * pathames.
172  */
173 static const char *const devfs_hier[] = {
174         "host", "bus", "target", "lun", NULL
175 };
176 #endif
177
178 static char *base_device(const char *device)
179 {
180         char *str, *cp;
181 #if ENABLE_FEATURE_DEVFS
182         const char *const *hier;
183         const char *disk;
184         int len;
185 #endif
186         str = xstrdup(device);
187
188         /* Skip over "/dev/"; if it's not present, give up */
189         cp = skip_dev_pfx(str);
190         if (cp == str)
191                 goto errout;
192
193         /*
194          * For md devices, we treat them all as if they were all
195          * on one disk, since we don't know how to parallelize them.
196          */
197         if (cp[0] == 'm' && cp[1] == 'd') {
198                 cp[2] = 0;
199                 return str;
200         }
201
202         /* Handle DAC 960 devices */
203         if (strncmp(cp, "rd/", 3) == 0) {
204                 cp += 3;
205                 if (cp[0] != 'c' || !isdigit(cp[1])
206                  || cp[2] != 'd' || !isdigit(cp[3]))
207                         goto errout;
208                 cp[4] = 0;
209                 return str;
210         }
211
212         /* Now let's handle /dev/hd* and /dev/sd* devices.... */
213         if ((cp[0] == 'h' || cp[0] == 's') && cp[1] == 'd') {
214                 cp += 2;
215                 /* If there's a single number after /dev/hd, skip it */
216                 if (isdigit(*cp))
217                         cp++;
218                 /* What follows must be an alpha char, or give up */
219                 if (!isalpha(*cp))
220                         goto errout;
221                 cp[1] = 0;
222                 return str;
223         }
224
225 #if ENABLE_FEATURE_DEVFS
226         /* Now let's handle devfs (ugh) names */
227         len = 0;
228         if (strncmp(cp, "ide/", 4) == 0)
229                 len = 4;
230         if (strncmp(cp, "scsi/", 5) == 0)
231                 len = 5;
232         if (len) {
233                 cp += len;
234                 /*
235                  * Now we proceed down the expected devfs hierarchy.
236                  * i.e., .../host1/bus2/target3/lun4/...
237                  * If we don't find the expected token, followed by
238                  * some number of digits at each level, abort.
239                  */
240                 for (hier = devfs_hier; *hier; hier++) {
241                         len = strlen(*hier);
242                         if (strncmp(cp, *hier, len) != 0)
243                                 goto errout;
244                         cp += len;
245                         while (*cp != '/' && *cp != 0) {
246                                 if (!isdigit(*cp))
247                                         goto errout;
248                                 cp++;
249                         }
250                         cp++;
251                 }
252                 cp[-1] = 0;
253                 return str;
254         }
255
256         /* Now handle devfs /dev/disc or /dev/disk names */
257         disk = 0;
258         if (strncmp(cp, "discs/", 6) == 0)
259                 disk = "disc";
260         else if (strncmp(cp, "disks/", 6) == 0)
261                 disk = "disk";
262         if (disk) {
263                 cp += 6;
264                 if (strncmp(cp, disk, 4) != 0)
265                         goto errout;
266                 cp += 4;
267                 while (*cp != '/' && *cp != 0) {
268                         if (!isdigit(*cp))
269                                 goto errout;
270                         cp++;
271                 }
272                 *cp = 0;
273                 return str;
274         }
275 #endif
276  errout:
277         free(str);
278         return NULL;
279 }
280
281 static void free_instance(struct fsck_instance *p)
282 {
283         free(p->prog);
284         free(p->device);
285         free(p->base_device);
286         free(p);
287 }
288
289 static struct fs_info *create_fs_device(const char *device, const char *mntpnt,
290                                         const char *type, const char *opts,
291                                         int passno)
292 {
293         struct fs_info *fs;
294
295         fs = xzalloc(sizeof(*fs));
296         fs->device = xstrdup(device);
297         fs->mountpt = xstrdup(mntpnt);
298         if (strchr(type, ','))
299                 type = (char *)"auto";
300         fs->type = xstrdup(type);
301         fs->opts = xstrdup(opts ? opts : "");
302         fs->passno = passno < 0 ? 1 : passno;
303         /*fs->flags = 0; */
304         /*fs->next = NULL; */
305
306         if (!filesys_info)
307                 filesys_info = fs;
308         else
309                 filesys_last->next = fs;
310         filesys_last = fs;
311
312         return fs;
313 }
314
315 /* Load the filesystem database from /etc/fstab */
316 static void load_fs_info(const char *filename)
317 {
318         FILE *fstab;
319         struct mntent mte;
320         struct fs_info *fs;
321
322         fstab = setmntent(filename, "r");
323         if (!fstab) {
324                 bb_perror_msg("can't read '%s'", filename);
325                 return;
326         }
327
328         // Loop through entries
329         while (getmntent_r(fstab, &mte, bb_common_bufsiz1, COMMON_BUFSIZE)) {
330                 //bb_info_msg("CREATE[%s][%s][%s][%s][%d]", mte.mnt_fsname, mte.mnt_dir,
331                 //      mte.mnt_type, mte.mnt_opts,
332                 //      mte.mnt_passno);
333                 fs = create_fs_device(mte.mnt_fsname, mte.mnt_dir,
334                         mte.mnt_type, mte.mnt_opts,
335                         mte.mnt_passno);
336         }
337         endmntent(fstab);
338 }
339
340 /* Lookup filesys in /etc/fstab and return the corresponding entry. */
341 static struct fs_info *lookup(char *filesys)
342 {
343         struct fs_info *fs;
344
345         for (fs = filesys_info; fs; fs = fs->next) {
346                 if (strcmp(filesys, fs->device) == 0
347                  || (fs->mountpt && strcmp(filesys, fs->mountpt) == 0)
348                 )
349                         break;
350         }
351
352         return fs;
353 }
354
355 #if DO_PROGRESS_INDICATOR
356 static int progress_active(void)
357 {
358         struct fsck_instance *inst;
359
360         for (inst = instance_list; inst; inst = inst->next) {
361                 if (inst->flags & FLAG_DONE)
362                         continue;
363                 if (inst->flags & FLAG_PROGRESS)
364                         return 1;
365         }
366         return 0;
367 }
368 #endif
369
370
371 /*
372  * Send a signal to all outstanding fsck child processes
373  */
374 static void kill_all_if_got_signal(void)
375 {
376         static smallint kill_sent;
377
378         struct fsck_instance *inst;
379
380         if (!bb_got_signal || kill_sent)
381                 return;
382
383         for (inst = instance_list; inst; inst = inst->next) {
384                 if (inst->flags & FLAG_DONE)
385                         continue;
386                 kill(inst->pid, SIGTERM);
387         }
388         kill_sent = 1;
389 }
390
391 /*
392  * Wait for one child process to exit; when it does, unlink it from
393  * the list of executing child processes, free, and return its exit status.
394  * If there is no exited child, return -1.
395  */
396 static int wait_one(int flags)
397 {
398         int status;
399         int sig;
400         struct fsck_instance *inst, *prev;
401         pid_t pid;
402
403         if (!instance_list)
404                 return -1;
405         /* if (noexecute) { already returned -1; } */
406
407         while (1) {
408                 pid = waitpid(-1, &status, flags);
409                 kill_all_if_got_signal();
410                 if (pid == 0) /* flags == WNOHANG and no children exited */
411                         return -1;
412                 if (pid < 0) {
413                         if (errno == EINTR)
414                                 continue;
415                         if (errno == ECHILD) { /* paranoia */
416                                 bb_error_msg("wait: no more children");
417                                 return -1;
418                         }
419                         bb_perror_msg("wait");
420                         continue;
421                 }
422                 prev = NULL;
423                 inst = instance_list;
424                 do {
425                         if (inst->pid == pid)
426                                 goto child_died;
427                         prev = inst;
428                         inst = inst->next;
429                 } while (inst);
430         }
431  child_died:
432
433         if (WIFEXITED(status))
434                 status = WEXITSTATUS(status);
435         else if (WIFSIGNALED(status)) {
436                 sig = WTERMSIG(status);
437                 status = EXIT_UNCORRECTED;
438                 if (sig != SIGINT) {
439                         printf("Warning: %s %s terminated "
440                                 "by signal %d\n",
441                                 inst->prog, inst->device, sig);
442                         status = EXIT_ERROR;
443                 }
444         } else {
445                 printf("%s %s: status is %x, should never happen\n",
446                         inst->prog, inst->device, status);
447                 status = EXIT_ERROR;
448         }
449
450 #if DO_PROGRESS_INDICATOR
451         if (progress && (inst->flags & FLAG_PROGRESS) && !progress_active()) {
452                 struct fsck_instance *inst2;
453                 for (inst2 = instance_list; inst2; inst2 = inst2->next) {
454                         if (inst2->flags & FLAG_DONE)
455                                 continue;
456                         if (strcmp(inst2->type, "ext2") != 0
457                          && strcmp(inst2->type, "ext3") != 0
458                         ) {
459                                 continue;
460                         }
461                         /* ext[23], we will send USR1
462                          * (request to start displaying progress bar)
463                          *
464                          * If we've just started the fsck, wait a tiny
465                          * bit before sending the kill, to give it
466                          * time to set up the signal handler
467                          */
468                         if (inst2->start_time >= time(NULL) - 1)
469                                 sleep(1);
470                         kill(inst2->pid, SIGUSR1);
471                         inst2->flags |= FLAG_PROGRESS;
472                         break;
473                 }
474         }
475 #endif
476
477         if (prev)
478                 prev->next = inst->next;
479         else
480                 instance_list = inst->next;
481         if (verbose > 1)
482                 printf("Finished with %s (exit status %d)\n",
483                        inst->device, status);
484         num_running--;
485         free_instance(inst);
486
487         return status;
488 }
489
490 /*
491  * Wait until all executing child processes have exited; return the
492  * logical OR of all of their exit code values.
493  */
494 #define FLAG_WAIT_ALL           0
495 #define FLAG_WAIT_ATLEAST_ONE   WNOHANG
496 static int wait_many(int flags)
497 {
498         int exit_status;
499         int global_status = 0;
500         int wait_flags = 0;
501
502         while ((exit_status = wait_one(wait_flags)) != -1) {
503                 global_status |= exit_status;
504                 wait_flags |= flags;
505         }
506         return global_status;
507 }
508
509 /*
510  * Execute a particular fsck program, and link it into the list of
511  * child processes we are waiting for.
512  */
513 static void execute(const char *type, const char *device,
514                 const char *mntpt /*, int interactive */)
515 {
516         int i;
517         struct fsck_instance *inst;
518         pid_t pid;
519
520         args[0] = xasprintf("fsck.%s", type);
521
522 #if DO_PROGRESS_INDICATOR
523         if (progress && !progress_active()) {
524                 if (strcmp(type, "ext2") == 0
525                  || strcmp(type, "ext3") == 0
526                 ) {
527                         args[XXX] = xasprintf("-C%d", progress_fd); /* 1 */
528                         inst->flags |= FLAG_PROGRESS;
529                 }
530         }
531 #endif
532
533         args[num_args - 2] = (char*)device;
534         /* args[num_args - 1] = NULL; - already is */
535
536         if (verbose || noexecute) {
537                 printf("[%s (%d) -- %s]", args[0], num_running,
538                                         mntpt ? mntpt : device);
539                 for (i = 0; args[i]; i++)
540                         printf(" %s", args[i]);
541                 bb_putchar('\n');
542         }
543
544         /* Fork and execute the correct program. */
545         pid = -1;
546         if (!noexecute) {
547                 pid = spawn(args);
548                 if (pid < 0)
549                         bb_simple_perror_msg(args[0]);
550         }
551
552 #if DO_PROGRESS_INDICATOR
553         free(args[XXX]);
554 #endif
555
556         /* No child, so don't record an instance */
557         if (pid <= 0) {
558                 free(args[0]);
559                 return;
560         }
561
562         inst = xzalloc(sizeof(*inst));
563         inst->pid = pid;
564         inst->prog = args[0];
565         inst->device = xstrdup(device);
566         inst->base_device = base_device(device);
567 #if DO_PROGRESS_INDICATOR
568         inst->start_time = time(NULL);
569 #endif
570
571         /* Add to the list of running fsck's.
572          * (was adding to the end, but adding to the front is simpler...) */
573         inst->next = instance_list;
574         instance_list = inst;
575 }
576
577 /*
578  * Run the fsck program on a particular device
579  *
580  * If the type is specified using -t, and it isn't prefixed with "no"
581  * (as in "noext2") and only one filesystem type is specified, then
582  * use that type regardless of what is specified in /etc/fstab.
583  *
584  * If the type isn't specified by the user, then use either the type
585  * specified in /etc/fstab, or "auto".
586  */
587 static void fsck_device(struct fs_info *fs /*, int interactive */)
588 {
589         const char *type;
590
591         if (strcmp(fs->type, "auto") != 0) {
592                 type = fs->type;
593                 if (verbose > 2)
594                         bb_info_msg("using filesystem type '%s' %s",
595                                         type, "from fstab");
596         } else if (fstype
597          && (fstype[0] != 'n' || fstype[1] != 'o') /* != "no" */
598          && strncmp(fstype, "opts=", 5) != 0
599          && strncmp(fstype, "loop", 4) != 0
600          && !strchr(fstype, ',')
601         ) {
602                 type = fstype;
603                 if (verbose > 2)
604                         bb_info_msg("using filesystem type '%s' %s",
605                                         type, "from -t");
606         } else {
607                 type = "auto";
608                 if (verbose > 2)
609                         bb_info_msg("using filesystem type '%s' %s",
610                                         type, "(default)");
611         }
612
613         num_running++;
614         execute(type, fs->device, fs->mountpt /*, interactive */);
615 }
616
617 /*
618  * Returns TRUE if a partition on the same disk is already being
619  * checked.
620  */
621 static int device_already_active(char *device)
622 {
623         struct fsck_instance *inst;
624         char *base;
625
626         if (force_all_parallel)
627                 return 0;
628
629 #ifdef BASE_MD
630         /* Don't check a soft raid disk with any other disk */
631         if (instance_list
632          && (!strncmp(instance_list->device, BASE_MD, sizeof(BASE_MD)-1)
633              || !strncmp(device, BASE_MD, sizeof(BASE_MD)-1))
634         ) {
635                 return 1;
636         }
637 #endif
638
639         base = base_device(device);
640         /*
641          * If we don't know the base device, assume that the device is
642          * already active if there are any fsck instances running.
643          */
644         if (!base)
645                 return (instance_list != NULL);
646
647         for (inst = instance_list; inst; inst = inst->next) {
648                 if (!inst->base_device || !strcmp(base, inst->base_device)) {
649                         free(base);
650                         return 1;
651                 }
652         }
653
654         free(base);
655         return 0;
656 }
657
658 /*
659  * This function returns true if a particular option appears in a
660  * comma-delimited options list
661  */
662 static int opt_in_list(char *opt, char *optlist)
663 {
664         char *s;
665         int len;
666
667         if (!optlist)
668                 return 0;
669
670         len = strlen(opt);
671         s = optlist - 1;
672         while (1) {
673                 s = strstr(s + 1, opt);
674                 if (!s)
675                         return 0;
676                 /* neither "opt.." nor "xxx,opt.."? */
677                 if (s != optlist && s[-1] != ',')
678                         continue;
679                 /* neither "..opt" nor "..opt,xxx"? */
680                 if (s[len] != '\0' && s[len] != ',')
681                         continue;
682                 return 1;
683         }
684 }
685
686 /* See if the filesystem matches the criteria given by the -t option */
687 static int fs_match(struct fs_info *fs)
688 {
689         int n, ret, checked_type;
690         char *cp;
691
692         if (!fs_type_list)
693                 return 1;
694
695         ret = 0;
696         checked_type = 0;
697         n = 0;
698         while (1) {
699                 cp = fs_type_list[n];
700                 if (!cp)
701                         break;
702                 switch (fs_type_flag[n]) {
703                 case FS_TYPE_FLAG_NORMAL:
704                         checked_type++;
705                         if (strcmp(cp, fs->type) == 0)
706                                 ret = 1;
707                         break;
708                 case FS_TYPE_FLAG_NEGOPT:
709                         if (opt_in_list(cp, fs->opts))
710                                 return 0;
711                         break;
712                 case FS_TYPE_FLAG_OPT:
713                         if (!opt_in_list(cp, fs->opts))
714                                 return 0;
715                         break;
716                 }
717                 n++;
718         }
719         if (checked_type == 0)
720                 return 1;
721
722         return (fs_type_negated ? !ret : ret);
723 }
724
725 /* Check if we should ignore this filesystem. */
726 static int ignore(struct fs_info *fs)
727 {
728         /*
729          * If the pass number is 0, ignore it.
730          */
731         if (fs->passno == 0)
732                 return 1;
733
734         /*
735          * If a specific fstype is specified, and it doesn't match,
736          * ignore it.
737          */
738         if (!fs_match(fs))
739                 return 1;
740
741         /* Are we ignoring this type? */
742         if (index_in_strings(ignored_types, fs->type) >= 0)
743                 return 1;
744
745         /* We can and want to check this file system type. */
746         return 0;
747 }
748
749 /* Check all file systems, using the /etc/fstab table. */
750 static int check_all(void)
751 {
752         struct fs_info *fs;
753         int status = EXIT_OK;
754         smallint not_done_yet;
755         smallint pass_done;
756         int passno;
757
758         if (verbose)
759                 puts("Checking all filesystems");
760
761         /*
762          * Do an initial scan over the filesystem; mark filesystems
763          * which should be ignored as done, and resolve any "auto"
764          * filesystem types (done as a side-effect of calling ignore()).
765          */
766         for (fs = filesys_info; fs; fs = fs->next)
767                 if (ignore(fs))
768                         fs->flags |= FLAG_DONE;
769
770         /*
771          * Find and check the root filesystem.
772          */
773         if (!parallel_root) {
774                 for (fs = filesys_info; fs; fs = fs->next) {
775                         if (LONE_CHAR(fs->mountpt, '/')) {
776                                 if (!skip_root && !ignore(fs)) {
777                                         fsck_device(fs /*, 1*/);
778                                         status |= wait_many(FLAG_WAIT_ALL);
779                                         if (status > EXIT_NONDESTRUCT)
780                                                 return status;
781                                 }
782                                 fs->flags |= FLAG_DONE;
783                                 break;
784                         }
785                 }
786         }
787         /*
788          * This is for the bone-headed user who has root
789          * filesystem listed twice.
790          * "Skip root" will skip _all_ root entries.
791          */
792         if (skip_root)
793                 for (fs = filesys_info; fs; fs = fs->next)
794                         if (LONE_CHAR(fs->mountpt, '/'))
795                                 fs->flags |= FLAG_DONE;
796
797         not_done_yet = 1;
798         passno = 1;
799         while (not_done_yet) {
800                 not_done_yet = 0;
801                 pass_done = 1;
802
803                 for (fs = filesys_info; fs; fs = fs->next) {
804                         if (bb_got_signal)
805                                 break;
806                         if (fs->flags & FLAG_DONE)
807                                 continue;
808                         /*
809                          * If the filesystem's pass number is higher
810                          * than the current pass number, then we didn't
811                          * do it yet.
812                          */
813                         if (fs->passno > passno) {
814                                 not_done_yet = 1;
815                                 continue;
816                         }
817                         /*
818                          * If a filesystem on a particular device has
819                          * already been spawned, then we need to defer
820                          * this to another pass.
821                          */
822                         if (device_already_active(fs->device)) {
823                                 pass_done = 0;
824                                 continue;
825                         }
826                         /*
827                          * Spawn off the fsck process
828                          */
829                         fsck_device(fs /*, serialize*/);
830                         fs->flags |= FLAG_DONE;
831
832                         /*
833                          * Only do one filesystem at a time, or if we
834                          * have a limit on the number of fsck's extant
835                          * at one time, apply that limit.
836                          */
837                         if (serialize
838                          || (max_running && (num_running >= max_running))
839                         ) {
840                                 pass_done = 0;
841                                 break;
842                         }
843                 }
844                 if (bb_got_signal)
845                         break;
846                 if (verbose > 1)
847                         printf("--waiting-- (pass %d)\n", passno);
848                 status |= wait_many(pass_done ? FLAG_WAIT_ALL :
849                                     FLAG_WAIT_ATLEAST_ONE);
850                 if (pass_done) {
851                         if (verbose > 1)
852                                 puts("----------------------------------");
853                         passno++;
854                 } else
855                         not_done_yet = 1;
856         }
857         kill_all_if_got_signal();
858         status |= wait_many(FLAG_WAIT_ATLEAST_ONE);
859         return status;
860 }
861
862 /*
863  * Deal with the fsck -t argument.
864  * Huh, for mount "-t novfat,nfs" means "neither vfat nor nfs"!
865  * Why here we require "-t novfat,nonfs" ??
866  */
867 static void compile_fs_type(char *fs_type)
868 {
869         char *s;
870         int num = 2;
871         smallint negate;
872
873         s = fs_type;
874         while ((s = strchr(s, ','))) {
875                 num++;
876                 s++;
877         }
878
879         fs_type_list = xzalloc(num * sizeof(fs_type_list[0]));
880         fs_type_flag = xzalloc(num * sizeof(fs_type_flag[0]));
881         fs_type_negated = -1; /* not yet known is it negated or not */
882
883         num = 0;
884         s = fs_type;
885         while (1) {
886                 char *comma;
887
888                 negate = 0;
889                 if (s[0] == 'n' && s[1] == 'o') { /* "no.." */
890                         s += 2;
891                         negate = 1;
892                 } else if (s[0] == '!') {
893                         s++;
894                         negate = 1;
895                 }
896
897                 if (strcmp(s, "loop") == 0)
898                         /* loop is really short-hand for opts=loop */
899                         goto loop_special_case;
900                 if (strncmp(s, "opts=", 5) == 0) {
901                         s += 5;
902  loop_special_case:
903                         fs_type_flag[num] = negate ? FS_TYPE_FLAG_NEGOPT : FS_TYPE_FLAG_OPT;
904                 } else {
905                         if (fs_type_negated == -1)
906                                 fs_type_negated = negate;
907                         if (fs_type_negated != negate)
908                                 bb_error_msg_and_die(
909 "either all or none of the filesystem types passed to -t must be prefixed "
910 "with 'no' or '!'");
911                 }
912                 comma = strchr(s, ',');
913                 fs_type_list[num++] = comma ? xstrndup(s, comma-s) : xstrdup(s);
914                 if (!comma)
915                         break;
916                 s = comma + 1;
917         }
918 }
919
920 static char **new_args(void)
921 {
922         args = xrealloc_vector(args, 2, num_args);
923         return &args[num_args++];
924 }
925
926 int fsck_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
927 int fsck_main(int argc UNUSED_PARAM, char **argv)
928 {
929         int i, status;
930         /*int interactive;*/
931         struct fs_info *fs;
932         const char *fstab;
933         char *tmp;
934         char **devices;
935         int num_devices;
936         smallint opts_for_fsck;
937         smallint doall;
938         smallint notitle;
939
940         /* we want wait() to be interruptible */
941         signal_no_SA_RESTART_empty_mask(SIGINT, record_signo);
942         signal_no_SA_RESTART_empty_mask(SIGTERM, record_signo);
943
944         setbuf(stdout, NULL);
945
946         opts_for_fsck = doall = notitle = 0;
947         devices = NULL;
948         num_devices = 0;
949         new_args(); /* args[0] = NULL, will be replaced by fsck.<type> */
950         /* instance_list = NULL; - in bss, so already zeroed */
951
952         while (*++argv) {
953                 int j;
954                 int optpos;
955                 char *options;
956                 char *arg = *argv;
957
958                 /* "/dev/blk" or "/path" or "UUID=xxx" or "LABEL=xxx" */
959                 if ((arg[0] == '/' && !opts_for_fsck) || strchr(arg, '=')) {
960 // FIXME: must check that arg is a blkdev, or resolve
961 // "/path", "UUID=xxx" or "LABEL=xxx" into block device name
962 // ("UUID=xxx"/"LABEL=xxx" can probably shifted to fsck.auto duties)
963                         devices = xrealloc_vector(devices, 2, num_devices);
964                         devices[num_devices++] = arg;
965                         continue;
966                 }
967
968                 if (arg[0] != '-' || opts_for_fsck) {
969                         *new_args() = arg;
970                         continue;
971                 }
972
973                 if (LONE_CHAR(arg + 1, '-')) { /* "--" ? */
974                         opts_for_fsck = 1;
975                         continue;
976                 }
977
978                 optpos = 0;
979                 options = NULL;
980                 for (j = 1; arg[j]; j++) {
981                         switch (arg[j]) {
982                         case 'A':
983                                 doall = 1;
984                                 break;
985 #if DO_PROGRESS_INDICATOR
986                         case 'C':
987                                 progress = 1;
988                                 if (arg[++j]) { /* -Cn */
989                                         progress_fd = xatoi_positive(&arg[j]);
990                                         goto next_arg;
991                                 }
992                                 /* -C n */
993                                 if (!*++argv)
994                                         bb_show_usage();
995                                 progress_fd = xatoi_positive(*argv);
996                                 goto next_arg;
997 #endif
998                         case 'V':
999                                 verbose++;
1000                                 break;
1001                         case 'N':
1002                                 noexecute = 1;
1003                                 break;
1004                         case 'R':
1005                                 skip_root = 1;
1006                                 break;
1007                         case 'T':
1008                                 notitle = 1;
1009                                 break;
1010 /*                      case 'M':
1011                                 like_mount = 1;
1012                                 break; */
1013                         case 'P':
1014                                 parallel_root = 1;
1015                                 break;
1016                         case 's':
1017                                 serialize = 1;
1018                                 break;
1019                         case 't':
1020                                 if (fstype)
1021                                         bb_show_usage();
1022                                 if (arg[++j])
1023                                         tmp = &arg[j];
1024                                 else if (*++argv)
1025                                         tmp = *argv;
1026                                 else
1027                                         bb_show_usage();
1028                                 fstype = xstrdup(tmp);
1029                                 compile_fs_type(fstype);
1030                                 goto next_arg;
1031                         case '?':
1032                                 bb_show_usage();
1033                                 break;
1034                         default:
1035                                 optpos++;
1036                                 /* one extra for '\0' */
1037                                 options = xrealloc(options, optpos + 2);
1038                                 options[optpos] = arg[j];
1039                                 break;
1040                         }
1041                 }
1042  next_arg:
1043                 if (optpos) {
1044                         options[0] = '-';
1045                         options[optpos + 1] = '\0';
1046                         *new_args() = options;
1047                 }
1048         }
1049         if (getenv("FSCK_FORCE_ALL_PARALLEL"))
1050                 force_all_parallel = 1;
1051         tmp = getenv("FSCK_MAX_INST");
1052         if (tmp)
1053                 max_running = xatoi(tmp);
1054         new_args(); /* args[num_args - 2] will be replaced by <device> */
1055         new_args(); /* args[num_args - 1] is the last, NULL element */
1056
1057         if (!notitle)
1058                 puts("fsck (busybox "BB_VER", "BB_BT")");
1059
1060         /* Even plain "fsck /dev/hda1" needs fstab to get fs type,
1061          * so we are scanning it anyway */
1062         fstab = getenv("FSTAB_FILE");
1063         if (!fstab)
1064                 fstab = "/etc/fstab";
1065         load_fs_info(fstab);
1066
1067         /*interactive = (num_devices == 1) | serialize;*/
1068
1069         if (num_devices == 0)
1070                 /*interactive =*/ serialize = doall = 1;
1071         if (doall)
1072                 return check_all();
1073
1074         status = 0;
1075         for (i = 0; i < num_devices; i++) {
1076                 if (bb_got_signal) {
1077                         kill_all_if_got_signal();
1078                         break;
1079                 }
1080
1081                 fs = lookup(devices[i]);
1082                 if (!fs)
1083                         fs = create_fs_device(devices[i], "", "auto", NULL, -1);
1084                 fsck_device(fs /*, interactive */);
1085
1086                 if (serialize
1087                  || (max_running && (num_running >= max_running))
1088                 ) {
1089                         int exit_status = wait_one(0);
1090                         if (exit_status >= 0)
1091                                 status |= exit_status;
1092                         if (verbose > 1)
1093                                 puts("----------------------------------");
1094                 }
1095         }
1096         status |= wait_many(FLAG_WAIT_ALL);
1097         return status;
1098 }