Whamcloud - gitweb
When testing a disk using e2fsck -c, use the list
[tools/e2fsprogs.git] / e2fsck / unix.c
1 /*
2  * unix.c - The unix-specific code for e2fsck
3  * 
4  * Copyright (C) 1993, 1994, 1995, 1996, 1997 Theodore Ts'o.
5  *
6  * %Begin-Header%
7  * This file may be redistributed under the terms of the GNU Public
8  * License.
9  * %End-Header%
10  */
11
12 #include <stdio.h>
13 #ifdef HAVE_STDLIB_H
14 #include <stdlib.h>
15 #endif
16 #include <string.h>
17 #include <fcntl.h>
18 #include <ctype.h>
19 #include <time.h>
20 #ifdef HAVE_SIGNAL_H
21 #include <signal.h>
22 #endif
23 #ifdef HAVE_GETOPT_H
24 #include <getopt.h>
25 #else
26 extern char *optarg;
27 extern int optind;
28 #endif
29 #include <unistd.h>
30 #ifdef HAVE_ERRNO_H
31 #include <errno.h>
32 #endif
33 #ifdef HAVE_MNTENT_H
34 #include <mntent.h>
35 #endif
36 #ifdef HAVE_SYS_IOCTL_H
37 #include <sys/ioctl.h>
38 #endif
39 #ifdef HAVE_MALLOC_H
40 #include <malloc.h>
41 #endif
42
43 #include "et/com_err.h"
44 #include "e2fsck.h"
45 #include "problem.h"
46 #include "../version.h"
47
48 /* Command line options */
49 static int swapfs;
50 static int normalize_swapfs;
51 static int cflag;               /* check disk */
52 static int show_version_only;
53 static int verbose;
54
55 static int replace_bad_blocks;
56 static char *bad_blocks_file;
57
58 e2fsck_t e2fsck_global_ctx;     /* Try your very best not to use this! */
59
60 #ifdef CONFIG_JBD_DEBUG         /* Enabled by configure --enable-jfs-debug */
61 int journal_enable_debug = -1;
62 #endif
63
64 static void usage(e2fsck_t ctx)
65 {
66         fprintf(stderr,
67                 _("Usage: %s [-panyrcdfvstDFSV] [-b superblock] [-B blocksize]\n"
68                 "\t\t[-I inode_buffer_blocks] [-P process_inode_size]\n"
69                 "\t\t[-l|-L bad_blocks_file] [-C fd] [-j ext-journal]\n"
70                 "\t\t[-E extended-options] device\n"),
71                 ctx->program_name);
72
73         fprintf(stderr, _("\nEmergency help:\n"
74                 " -p                   Automatic repair (no questions)\n"
75                 " -n                   Make no changes to the filesystem\n"
76                 " -y                   Assume \"yes\" to all questions\n"
77                 " -c                   Check for bad blocks and add them to the badblock list\n"
78                 " -f                   Force checking even if filesystem is marked clean\n"));
79         fprintf(stderr, _(""
80                 " -v                   Be verbose\n"
81                 " -b superblock        Use alternative superblock\n"
82                 " -B blocksize         Force blocksize when looking for superblock\n"
83                 " -j external-journal  Set location of the external journal\n"
84                 " -l bad_blocks_file   Add to badblocks list\n"
85                 " -L bad_blocks_file   Set badblocks list\n"
86                 ));
87
88         exit(FSCK_USAGE);
89 }
90
91 static void show_stats(e2fsck_t ctx)
92 {
93         ext2_filsys fs = ctx->fs;
94         int inodes, inodes_used, blocks, blocks_used;
95         int dir_links;
96         int num_files, num_links;
97         int frag_percent;
98
99         dir_links = 2 * ctx->fs_directory_count - 1;
100         num_files = ctx->fs_total_count - dir_links;
101         num_links = ctx->fs_links_count - dir_links;
102         inodes = fs->super->s_inodes_count;
103         inodes_used = (fs->super->s_inodes_count -
104                        fs->super->s_free_inodes_count);
105         blocks = fs->super->s_blocks_count;
106         blocks_used = (fs->super->s_blocks_count -
107                        fs->super->s_free_blocks_count);
108
109         frag_percent = (10000 * ctx->fs_fragmented) / inodes_used;
110         frag_percent = (frag_percent + 5) / 10;
111         
112         if (!verbose) {
113                 printf(_("%s: %d/%d files (%0d.%d%% non-contiguous), %d/%d blocks\n"),
114                        ctx->device_name, inodes_used, inodes,
115                        frag_percent / 10, frag_percent % 10,
116                        blocks_used, blocks);
117                 return;
118         }
119         printf (P_("\n%8d inode used (%d%%)\n", "\n%8d inodes used (%d%%)\n",
120                    inodes_used), inodes_used, 100 * inodes_used / inodes);
121         printf (P_("%8d non-contiguous inode (%0d.%d%%)\n",
122                    "%8d non-contiguous inodes (%0d.%d%%)\n",
123                    ctx->fs_fragmented),
124                 ctx->fs_fragmented, frag_percent / 10, frag_percent % 10);
125         printf (_("         # of inodes with ind/dind/tind blocks: %d/%d/%d\n"),
126                 ctx->fs_ind_count, ctx->fs_dind_count, ctx->fs_tind_count);
127         printf (P_("%8d block used (%d%%)\n", "%8d blocks used (%d%%)\n",
128                    blocks_used),
129                 blocks_used, (int) ((long long) 100 * blocks_used / blocks));
130         printf (P_("%8d bad block\n", "%8d bad blocks\n",
131                    ctx->fs_badblocks_count), ctx->fs_badblocks_count);
132         printf (P_("%8d large file\n", "%8d large files\n",
133                    ctx->large_files), ctx->large_files);
134         printf (P_("\n%8d regular file\n", "\n%8d regular files\n",
135                    ctx->fs_regular_count), ctx->fs_regular_count);
136         printf (P_("%8d directory\n", "%8d directories\n",
137                    ctx->fs_directory_count), ctx->fs_directory_count);
138         printf (P_("%8d character device file\n",
139                    "%8d character device files\n", ctx->fs_chardev_count),
140                 ctx->fs_chardev_count);
141         printf (P_("%8d block device file\n", "%8d block device files\n",
142                    ctx->fs_blockdev_count), ctx->fs_blockdev_count);
143         printf (P_("%8d fifo\n", "%8d fifos\n", ctx->fs_fifo_count),
144                 ctx->fs_fifo_count);
145         printf (P_("%8d link\n", "%8d links\n",
146                    ctx->fs_links_count - dir_links),
147                 ctx->fs_links_count - dir_links);
148         printf (P_("%8d symbolic link", "%8d symbolic links",
149                    ctx->fs_symlinks_count), ctx->fs_symlinks_count);
150         printf (P_(" (%d fast symbolic link)\n", " (%d fast symbolic links)\n",
151                    ctx->fs_fast_symlinks_count), ctx->fs_fast_symlinks_count);
152         printf (P_("%8d socket\n", "%8d sockets\n", ctx->fs_sockets_count),
153                 ctx->fs_sockets_count);
154         printf ("--------\n");
155         printf (P_("%8d file\n", "%8d files\n",
156                    ctx->fs_total_count - dir_links),
157                 ctx->fs_total_count - dir_links);
158 }
159
160 static void check_mount(e2fsck_t ctx)
161 {
162         errcode_t       retval;
163         int             cont;
164
165         retval = ext2fs_check_if_mounted(ctx->filesystem_name,
166                                          &ctx->mount_flags);
167         if (retval) {
168                 com_err("ext2fs_check_if_mount", retval,
169                         _("while determining whether %s is mounted."),
170                         ctx->filesystem_name);
171                 return;
172         }
173
174         /*
175          * If the filesystem isn't mounted, or it's the root filesystem
176          * and it's mounted read-only, then everything's fine.
177          */
178         if ((!(ctx->mount_flags & EXT2_MF_MOUNTED)) ||
179             ((ctx->mount_flags & EXT2_MF_ISROOT) &&
180              (ctx->mount_flags & EXT2_MF_READONLY)))
181                 return;
182
183         if (ctx->options & E2F_OPT_READONLY) {
184                 printf(_("Warning!  %s is mounted.\n"), ctx->filesystem_name);
185                 return;
186         }
187
188         printf(_("%s is mounted.  "), ctx->filesystem_name);
189         if (!ctx->interactive)
190                 fatal_error(ctx, _("Cannot continue, aborting.\n\n"));
191         printf(_("\n\n\007\007\007\007WARNING!!!  "
192                "Running e2fsck on a mounted filesystem may cause\n"
193                "SEVERE filesystem damage.\007\007\007\n\n"));
194         cont = ask_yn(_("Do you really want to continue"), -1);
195         if (!cont) {
196                 printf (_("check aborted.\n"));
197                 exit (0);
198         }
199         return;
200 }
201
202 static int is_on_batt()
203 {
204         FILE    *f;
205         char    tmp[80], tmp2[80];
206         unsigned int    acflag;
207
208         f = fopen("/proc/apm", "r");
209         if (f) {
210                 if (fscanf(f, "%s %s %s %x", tmp, tmp, tmp, &acflag) != 4) 
211                         acflag = 1;
212                 fclose(f);
213                 return (acflag != 1);
214         }
215         f = fopen("/proc/acpi/ac_adapter/AC/state", "r");
216         if (f) {
217                 if (fscanf(f, "%s %s", tmp2, tmp) != 2)
218                         tmp[0] = 0;
219                 fclose(f);
220                 if (strncmp(tmp, "off-line", 8) == 0)
221                         return 1;
222         }
223         return 0;
224 }
225
226 /*
227  * This routine checks to see if a filesystem can be skipped; if so,
228  * it will exit with E2FSCK_OK.  Under some conditions it will print a
229  * message explaining why a check is being forced.
230  */
231 static void check_if_skip(e2fsck_t ctx)
232 {
233         ext2_filsys fs = ctx->fs;
234         const char *reason = NULL;
235         unsigned int reason_arg = 0;
236         long next_check;
237         int batt = is_on_batt();
238         time_t now = time(0);
239         
240         if ((ctx->options & E2F_OPT_FORCE) || bad_blocks_file ||
241             cflag || swapfs)
242                 return;
243         
244         if (fs->super->s_state & EXT2_ERROR_FS)
245                 reason = _(" contains a file system with errors");
246         else if ((fs->super->s_state & EXT2_VALID_FS) == 0)
247                 reason = _(" was not cleanly unmounted");
248         else if ((fs->super->s_max_mnt_count > 0) &&
249                  (fs->super->s_mnt_count >=
250                   (unsigned) fs->super->s_max_mnt_count)) {
251                 reason = _(" has been mounted %u times without being checked");
252                 reason_arg = fs->super->s_mnt_count;
253                 if (batt && (fs->super->s_mnt_count < 
254                              (unsigned) fs->super->s_max_mnt_count*2))
255                         reason = 0;
256         } else if (fs->super->s_checkinterval &&
257                  now >= (fs->super->s_lastcheck +
258                              fs->super->s_checkinterval)) {
259                 reason = _(" has gone %u days without being checked");
260                 reason_arg = (now - fs->super->s_lastcheck)/(3600*24);
261                 if (batt && (now < (fs->super->s_lastcheck +
262                                     fs->super->s_checkinterval*2)))
263                         reason = 0;
264         }
265         if (reason) {
266                 fputs(ctx->device_name, stdout);
267                 printf(reason, reason_arg);
268                 fputs(_(", check forced.\n"), stdout);
269                 return;
270         }
271         printf(_("%s: clean, %d/%d files, %d/%d blocks"), ctx->device_name,
272                fs->super->s_inodes_count - fs->super->s_free_inodes_count,
273                fs->super->s_inodes_count,
274                fs->super->s_blocks_count - fs->super->s_free_blocks_count,
275                fs->super->s_blocks_count);
276         next_check = 100000;
277         if (fs->super->s_max_mnt_count > 0) {
278                 next_check = fs->super->s_max_mnt_count - fs->super->s_mnt_count;
279                 if (next_check <= 0) 
280                         next_check = 1;
281         }
282         if (now >= (fs->super->s_lastcheck + fs->super->s_checkinterval))
283                 next_check = 1;
284         if (next_check <= 5) {
285                 if (next_check == 1)
286                         fputs(_(" (check after next mount)"), stdout);
287                 else
288                         printf(_(" (check in %d mounts)"), next_check);
289         }
290         fputc('\n', stdout);
291         ext2fs_close(fs);
292         ctx->fs = NULL;
293         e2fsck_free_context(ctx);
294         exit(FSCK_OK);
295 }
296
297 /*
298  * For completion notice
299  */
300 struct percent_tbl {
301         int     max_pass;
302         int     table[32];
303 };
304 struct percent_tbl e2fsck_tbl = {
305         5, { 0, 70, 90, 92,  95, 100 }
306 };
307 static char bar[128], spaces[128];
308
309 static float calc_percent(struct percent_tbl *tbl, int pass, int curr,
310                           int max)
311 {
312         float   percent;
313         
314         if (pass <= 0)
315                 return 0.0;
316         if (pass > tbl->max_pass || max == 0)
317                 return 100.0;
318         percent = ((float) curr) / ((float) max);
319         return ((percent * (tbl->table[pass] - tbl->table[pass-1]))
320                 + tbl->table[pass-1]);
321 }
322
323 extern void e2fsck_clear_progbar(e2fsck_t ctx)
324 {
325         if (!(ctx->flags & E2F_FLAG_PROG_BAR))
326                 return;
327         
328         printf("%s%s\r%s", ctx->start_meta, spaces + (sizeof(spaces) - 80),
329                ctx->stop_meta);
330         fflush(stdout);
331         ctx->flags &= ~E2F_FLAG_PROG_BAR;
332 }
333
334 int e2fsck_simple_progress(e2fsck_t ctx, const char *label, float percent,
335                            unsigned int dpynum)
336 {
337         static const char spinner[] = "\\|/-";
338         int     i;
339         int     tick;
340         struct timeval  tv;
341         int dpywidth;
342
343         if (ctx->flags & E2F_FLAG_PROG_SUPPRESS)
344                 return 0;
345
346         /*
347          * Calculate the new progress position.  If the
348          * percentage hasn't changed, then we skip out right
349          * away. 
350          */
351         if (ctx->progress_last_percent == (int) 10 * percent)
352                 return 0;
353         ctx->progress_last_percent = (int) 10 * percent;
354
355         /*
356          * If we've already updated the spinner once within
357          * the last 1/8th of a second, no point doing it
358          * again.
359          */
360         gettimeofday(&tv, NULL);
361         tick = (tv.tv_sec << 3) + (tv.tv_usec / (1000000 / 8));
362         if ((tick == ctx->progress_last_time) &&
363             (percent != 0.0) && (percent != 100.0))
364                 return 0;
365         ctx->progress_last_time = tick;
366
367         /*
368          * Advance the spinner, and note that the progress bar
369          * will be on the screen
370          */
371         ctx->progress_pos = (ctx->progress_pos+1) & 3;
372         ctx->flags |= E2F_FLAG_PROG_BAR;
373
374         dpywidth = 66 - strlen(label);
375         dpywidth = 8 * (dpywidth / 8);
376         if (dpynum)
377                 dpywidth -= 8;
378
379         i = ((percent * dpywidth) + 50) / 100;
380         printf("%s%s: |%s%s", ctx->start_meta, label,
381                bar + (sizeof(bar) - (i+1)),
382                spaces + (sizeof(spaces) - (dpywidth - i + 1)));
383         if (percent == 100.0)
384                 fputc('|', stdout);
385         else
386                 fputc(spinner[ctx->progress_pos & 3], stdout);
387         if (dpynum)
388                 printf(" %4.1f%%  %u\r%s", percent, dpynum, ctx->stop_meta);
389         else
390                 printf(" %4.1f%%   \r%s", percent, ctx->stop_meta);
391         
392         if (percent == 100.0)
393                 e2fsck_clear_progbar(ctx);
394         fflush(stdout);
395
396         return 0;
397 }
398
399 static int e2fsck_update_progress(e2fsck_t ctx, int pass,
400                                   unsigned long cur, unsigned long max)
401 {
402         char buf[80];
403         float percent;
404
405         if (pass == 0)
406                 return 0;
407         
408         if (ctx->progress_fd) {
409                 sprintf(buf, "%d %lu %lu\n", pass, cur, max);
410                 write(ctx->progress_fd, buf, strlen(buf));
411         } else {
412                 percent = calc_percent(&e2fsck_tbl, pass, cur, max);
413                 e2fsck_simple_progress(ctx, ctx->device_name,
414                                        percent, 0);
415         }
416         return 0;
417 }
418
419 #define PATH_SET "PATH=/sbin"
420
421 static void reserve_stdio_fds(void)
422 {
423         int     fd;
424
425         while (1) {
426                 fd = open("/dev/null", O_RDWR);
427                 if (fd > 2)
428                         break;
429                 if (fd < 0) {
430                         fprintf(stderr, _("ERROR: Couldn't open "
431                                 "/dev/null (%s)\n"),
432                                 strerror(errno));
433                         break;
434                 }
435         }
436         close(fd);
437 }
438
439 #ifdef HAVE_SIGNAL_H
440 static void signal_progress_on(int sig)
441 {
442         e2fsck_t ctx = e2fsck_global_ctx;
443
444         if (!ctx)
445                 return;
446
447         ctx->progress = e2fsck_update_progress;
448         ctx->progress_fd = 0;
449 }
450
451 static void signal_progress_off(int sig)
452 {
453         e2fsck_t ctx = e2fsck_global_ctx;
454
455         if (!ctx)
456                 return;
457
458         e2fsck_clear_progbar(ctx);
459         ctx->progress = 0;
460 }
461
462 static void signal_cancel(int sig)
463 {
464         e2fsck_t ctx = e2fsck_global_ctx;
465
466         if (!ctx)
467                 exit(FSCK_CANCELED);
468
469         ctx->flags |= E2F_FLAG_CANCEL;
470 }
471 #endif
472
473 static void parse_extended_opts(e2fsck_t ctx, const char *opts)
474 {
475         char    *buf, *token, *next, *p, *arg;
476         int     ea_ver;
477         int     extended_usage = 0;
478
479         buf = string_copy(ctx, opts, 0);
480         for (token = buf; token && *token; token = next) {
481                 p = strchr(token, ',');
482                 next = 0;
483                 if (p) {
484                         *p = 0;
485                         next = p+1;
486                 } 
487                 arg = strchr(token, '=');
488                 if (arg) {
489                         *arg = 0;
490                         arg++;
491                 }
492                 if (strcmp(token, "ea_ver") == 0) {
493                         if (!arg) {
494                                 extended_usage++;
495                                 continue;
496                         }
497                         ea_ver = strtoul(arg, &p, 0);
498                         if (*p ||
499                             ((ea_ver != 1) && (ea_ver != 2))) {
500                                 fprintf(stderr,
501                                         _("Invalid EA version.\n"));
502                                 extended_usage++;
503                                 continue;
504                         }
505                         ctx->ext_attr_ver = ea_ver;
506                 } else
507                         extended_usage++;
508         }
509         if (extended_usage) {
510                 fprintf(stderr, _("Extended options are separated by commas, "
511                         "and may take an argument which\n"
512                         "is set off by an equals ('=') sign.  "
513                         "Valid raid options are:\n"
514                         "\tea_ver=<ea_version (1 or 2)\n\n"));
515                 exit(1);
516         }
517 }       
518
519
520 static errcode_t PRS(int argc, char *argv[], e2fsck_t *ret_ctx)
521 {
522         int             flush = 0;
523         int             c, fd;
524 #ifdef MTRACE
525         extern void     *mallwatch;
526 #endif
527         e2fsck_t        ctx;
528         errcode_t       retval;
529 #ifdef HAVE_SIGNAL_H
530         struct sigaction        sa;
531 #endif
532         char            *extended_opts = 0;
533
534         retval = e2fsck_allocate_context(&ctx);
535         if (retval)
536                 return retval;
537
538         *ret_ctx = ctx;
539
540         setvbuf(stdout, NULL, _IONBF, BUFSIZ);
541         setvbuf(stderr, NULL, _IONBF, BUFSIZ);
542         if (isatty(0) && isatty(1)) {
543                 ctx->interactive = 1;
544         } else {
545                 ctx->start_meta[0] = '\001';
546                 ctx->stop_meta[0] = '\002';
547         }
548         memset(bar, '=', sizeof(bar)-1);
549         memset(spaces, ' ', sizeof(spaces)-1);
550         initialize_ext2_error_table();
551         blkid_get_cache(&ctx->blkid, NULL);
552         
553         if (argc && *argv)
554                 ctx->program_name = *argv;
555         else
556                 ctx->program_name = "e2fsck";
557         while ((c = getopt (argc, argv, "panyrcC:B:dE:fvtFVM:b:I:j:P:l:L:N:SsD")) != EOF)
558                 switch (c) {
559                 case 'C':
560                         ctx->progress = e2fsck_update_progress;
561                         ctx->progress_fd = atoi(optarg);
562                         if (!ctx->progress_fd)
563                                 break;
564                         /* Validate the file descriptor to avoid disasters */
565                         fd = dup(ctx->progress_fd);
566                         if (fd < 0) {
567                                 fprintf(stderr,
568                                 _("Error validating file descriptor %d: %s\n"),
569                                         ctx->progress_fd,
570                                         error_message(errno));
571                                 fatal_error(ctx,
572                         _("Invalid completion information file descriptor"));
573                         } else
574                                 close(fd);
575                         break;
576                 case 'D':
577                         ctx->options |= E2F_OPT_COMPRESS_DIRS;
578                         break;
579                 case 'E':
580                         extended_opts = optarg;
581                         break;
582                 case 'p':
583                 case 'a':
584                         if (ctx->options & (E2F_OPT_YES|E2F_OPT_NO)) {
585                         conflict_opt:
586                                 fatal_error(ctx, 
587         _("Only one the options -p/-a, -n or -y may be specified."));
588                         }
589                         ctx->options |= E2F_OPT_PREEN;
590                         break;
591                 case 'n':
592                         if (ctx->options & (E2F_OPT_YES|E2F_OPT_PREEN))
593                                 goto conflict_opt;
594                         ctx->options |= E2F_OPT_NO;
595                         break;
596                 case 'y':
597                         if (ctx->options & (E2F_OPT_PREEN|E2F_OPT_NO))
598                                 goto conflict_opt;
599                         ctx->options |= E2F_OPT_YES;
600                         break;
601                 case 't':
602 #ifdef RESOURCE_TRACK
603                         if (ctx->options & E2F_OPT_TIME)
604                                 ctx->options |= E2F_OPT_TIME2;
605                         else
606                                 ctx->options |= E2F_OPT_TIME;
607 #else
608                         fprintf(stderr, _("The -t option is not "
609                                 "supported on this version of e2fsck.\n"));
610 #endif
611                         break;
612                 case 'c':
613                         if (cflag++)
614                                 ctx->options |= E2F_OPT_WRITECHECK;
615                         ctx->options |= E2F_OPT_CHECKBLOCKS;
616                         break;
617                 case 'r':
618                         /* What we do by default, anyway! */
619                         break;
620                 case 'b':
621                         ctx->use_superblock = atoi(optarg);
622                         ctx->flags |= E2F_FLAG_SB_SPECIFIED;
623                         break;
624                 case 'B':
625                         ctx->blocksize = atoi(optarg);
626                         break;
627                 case 'I':
628                         ctx->inode_buffer_blocks = atoi(optarg);
629                         break;
630                 case 'j':
631                         ctx->journal_name = string_copy(ctx, optarg, 0);
632                         break;
633                 case 'P':
634                         ctx->process_inode_size = atoi(optarg);
635                         break;
636                 case 'L':
637                         replace_bad_blocks++;
638                 case 'l':
639                         bad_blocks_file = string_copy(ctx, optarg, 0);
640                         break;
641                 case 'd':
642                         ctx->options |= E2F_OPT_DEBUG;
643                         break;
644                 case 'f':
645                         ctx->options |= E2F_OPT_FORCE;
646                         break;
647                 case 'F':
648                         flush = 1;
649                         break;
650                 case 'v':
651                         verbose = 1;
652                         break;
653                 case 'V':
654                         show_version_only = 1;
655                         break;
656 #ifdef MTRACE
657                 case 'M':
658                         mallwatch = (void *) strtol(optarg, NULL, 0);
659                         break;
660 #endif
661                 case 'N':
662                         ctx->device_name = optarg;
663                         break;
664 #ifdef ENABLE_SWAPFS
665                 case 's':
666                         normalize_swapfs = 1;
667                 case 'S':
668                         swapfs = 1;
669                         break;
670 #else
671                 case 's':
672                 case 'S':
673                         fprintf(stderr, _("Byte-swapping filesystems "
674                                           "not compiled in this version "
675                                           "of e2fsck\n"));
676                         exit(1);
677 #endif
678                 default:
679                         usage(ctx);
680                 }
681         if (show_version_only)
682                 return 0;
683         if (optind != argc - 1)
684                 usage(ctx);
685         if ((ctx->options & E2F_OPT_NO) && !bad_blocks_file &&
686             !cflag && !swapfs && !(ctx->options & E2F_OPT_COMPRESS_DIRS))
687                 ctx->options |= E2F_OPT_READONLY;
688         ctx->filesystem_name = blkid_get_devname(ctx->blkid, argv[optind], 0);
689         if (!ctx->filesystem_name) {
690                 com_err(ctx->program_name, 0, _("Unable to resolve '%s'"), 
691                         argv[optind]);
692                 fatal_error(ctx, 0);
693         }
694         if (extended_opts)
695                 parse_extended_opts(ctx, extended_opts);
696         
697         if (flush) {
698                 fd = open(ctx->filesystem_name, O_RDONLY, 0);
699                 if (fd < 0) {
700                         com_err("open", errno,
701                                 _("while opening %s for flushing"),
702                                 ctx->filesystem_name);
703                         fatal_error(ctx, 0);
704                 }
705                 if ((retval = ext2fs_sync_device(fd, 1))) {
706                         com_err("ext2fs_sync_device", retval,
707                                 _("while trying to flush %s"),
708                                 ctx->filesystem_name);
709                         fatal_error(ctx, 0);
710                 }
711                 close(fd);
712         }
713 #ifdef ENABLE_SWAPFS
714         if (swapfs) {
715                 if (cflag || bad_blocks_file) {
716                         fprintf(stderr, _("Incompatible options not "
717                                           "allowed when byte-swapping.\n"));
718                         exit(FSCK_USAGE);
719                 }
720         }
721 #endif
722         if (cflag && bad_blocks_file) {
723                 fprintf(stderr, _("The -c and the -l/-L options may "
724                                   "not be both used at the same time.\n"));
725                 exit(FSCK_USAGE);
726         }
727 #ifdef HAVE_SIGNAL_H
728         /*
729          * Set up signal action
730          */
731         memset(&sa, 0, sizeof(struct sigaction));
732         sa.sa_handler = signal_cancel;
733         sigaction(SIGINT, &sa, 0);
734         sigaction(SIGTERM, &sa, 0);
735 #ifdef SA_RESTART
736         sa.sa_flags = SA_RESTART;
737 #endif
738         e2fsck_global_ctx = ctx;
739         sa.sa_handler = signal_progress_on;
740         sigaction(SIGUSR1, &sa, 0);
741         sa.sa_handler = signal_progress_off;
742         sigaction(SIGUSR2, &sa, 0);
743 #endif
744
745         /* Update our PATH to include /sbin if we need to run badblocks  */
746         if (cflag) {
747                 char *oldpath = getenv("PATH");
748                 if (oldpath) {
749                         char *newpath;
750
751                         newpath = (char *) malloc(sizeof (PATH_SET) + 1 +
752                                                   strlen (oldpath));
753                         if (!newpath)
754                                 fatal_error(ctx, "Couldn't malloc() newpath");
755                         strcpy (newpath, PATH_SET);
756                         strcat (newpath, ":");
757                         strcat (newpath, oldpath);
758                         putenv (newpath);
759                 } else
760                         putenv (PATH_SET);
761         }
762 #ifdef CONFIG_JBD_DEBUG
763         if (getenv("E2FSCK_JBD_DEBUG"))
764                 journal_enable_debug = atoi(getenv("E2FSCK_JBD_DEBUG"));
765 #endif
766         return 0;
767 }
768
769 static const char *my_ver_string = E2FSPROGS_VERSION;
770 static const char *my_ver_date = E2FSPROGS_DATE;
771                                         
772 int main (int argc, char *argv[])
773 {
774         errcode_t       retval = 0;
775         int             exit_value = FSCK_OK;
776         ext2_filsys     fs = 0;
777         io_manager      io_ptr;
778         struct ext2_super_block *sb;
779         const char      *lib_ver_date;
780         int             my_ver, lib_ver;
781         e2fsck_t        ctx;
782         struct problem_context pctx;
783         int flags, run_result;
784         
785         clear_problem_context(&pctx);
786 #ifdef MTRACE
787         mtrace();
788 #endif
789 #ifdef MCHECK
790         mcheck(0);
791 #endif
792 #ifdef ENABLE_NLS
793         setlocale(LC_MESSAGES, "");
794         setlocale(LC_CTYPE, "");
795         bindtextdomain(NLS_CAT_NAME, LOCALEDIR);
796         textdomain(NLS_CAT_NAME);
797 #endif
798         my_ver = ext2fs_parse_version_string(my_ver_string);
799         lib_ver = ext2fs_get_library_version(0, &lib_ver_date);
800         if (my_ver > lib_ver) {
801                 fprintf( stderr, _("Error: ext2fs library version "
802                         "out of date!\n"));
803                 show_version_only++;
804         }
805         
806         retval = PRS(argc, argv, &ctx);
807         if (retval) {
808                 com_err("e2fsck", retval,
809                         _("while trying to initialize program"));
810                 exit(FSCK_ERROR);
811         }
812         reserve_stdio_fds();
813         
814 #ifdef RESOURCE_TRACK
815         init_resource_track(&ctx->global_rtrack);
816 #endif
817
818         if (!(ctx->options & E2F_OPT_PREEN) || show_version_only)
819                 fprintf(stderr, "e2fsck %s (%s)\n", my_ver_string,
820                          my_ver_date);
821
822         if (show_version_only) {
823                 fprintf(stderr, _("\tUsing %s, %s\n"),
824                         error_message(EXT2_ET_BASE), lib_ver_date);
825                 exit(FSCK_OK);
826         }
827         
828         check_mount(ctx);
829         
830         if (!(ctx->options & E2F_OPT_PREEN) &&
831             !(ctx->options & E2F_OPT_NO) &&
832             !(ctx->options & E2F_OPT_YES)) {
833                 if (!ctx->interactive)
834                         fatal_error(ctx,
835                                     _("need terminal for interactive repairs"));
836         }
837         ctx->superblock = ctx->use_superblock;
838 restart:
839 #ifdef CONFIG_TESTIO_DEBUG
840         io_ptr = test_io_manager;
841         test_io_backing_manager = unix_io_manager;
842 #else
843         io_ptr = unix_io_manager;
844 #endif
845         flags = 0;
846         if ((ctx->options & E2F_OPT_READONLY) == 0)
847                 flags |= EXT2_FLAG_RW;
848
849         if (ctx->superblock && ctx->blocksize) {
850                 retval = ext2fs_open(ctx->filesystem_name, flags,
851                                      ctx->superblock, ctx->blocksize,
852                                      io_ptr, &fs);
853         } else if (ctx->superblock) {
854                 int blocksize;
855                 for (blocksize = EXT2_MIN_BLOCK_SIZE;
856                      blocksize <= EXT2_MAX_BLOCK_SIZE; blocksize *= 2) {
857                         retval = ext2fs_open(ctx->filesystem_name, flags,
858                                              ctx->superblock, blocksize,
859                                              io_ptr, &fs);
860                         if (!retval)
861                                 break;
862                 }
863         } else 
864                 retval = ext2fs_open(ctx->filesystem_name, flags, 
865                                      0, 0, io_ptr, &fs);
866         if (!ctx->superblock && !(ctx->options & E2F_OPT_PREEN) &&
867             !(ctx->flags & E2F_FLAG_SB_SPECIFIED) &&
868             ((retval == EXT2_ET_BAD_MAGIC) ||
869              ((retval == 0) && ext2fs_check_desc(fs)))) {
870                 if (!fs || (fs->group_desc_count > 1)) {
871                         printf(_("%s trying backup blocks...\n"),
872                                retval ? _("Couldn't find ext2 superblock,") :
873                                _("Group descriptors look bad..."));
874                         get_backup_sb(ctx, fs, ctx->filesystem_name, io_ptr);
875                         if (fs)
876                                 ext2fs_close(fs);
877                         goto restart;
878                 }
879         }
880         if (retval) {
881                 com_err(ctx->program_name, retval, _("while trying to open %s"),
882                         ctx->filesystem_name);
883                 if (retval == EXT2_ET_REV_TOO_HIGH) {
884                         printf(_("The filesystem revision is apparently "
885                                "too high for this version of e2fsck.\n"
886                                "(Or the filesystem superblock "
887                                "is corrupt)\n\n"));
888                         fix_problem(ctx, PR_0_SB_CORRUPT, &pctx);
889                 } else if (retval == EXT2_ET_SHORT_READ)
890                         printf(_("Could this be a zero-length partition?\n"));
891                 else if ((retval == EPERM) || (retval == EACCES))
892                         printf(_("You must have %s access to the "
893                                "filesystem or be root\n"),
894                                (ctx->options & E2F_OPT_READONLY) ?
895                                "r/o" : "r/w");
896                 else if (retval == ENXIO)
897                         printf(_("Possibly non-existent or swap device?\n"));
898 #ifdef EROFS
899                 else if (retval == EROFS)
900                         printf(_("Disk write-protected; use the -n option "
901                                "to do a read-only\n"
902                                "check of the device.\n"));
903 #endif
904                 else
905                         fix_problem(ctx, PR_0_SB_CORRUPT, &pctx);
906                 fatal_error(ctx, 0);
907         }
908         ctx->fs = fs;
909         fs->priv_data = ctx;
910         sb = fs->super;
911         if (sb->s_rev_level > E2FSCK_CURRENT_REV) {
912                 com_err(ctx->program_name, EXT2_ET_REV_TOO_HIGH,
913                         _("while trying to open %s"),
914                         ctx->filesystem_name);
915         get_newer:
916                 fatal_error(ctx, _("Get a newer version of e2fsck!"));
917         }
918
919         /*
920          * Set the device name, which is used whenever we print error
921          * or informational messages to the user.
922          */
923         if (ctx->device_name == 0 &&
924             (sb->s_volume_name[0] != 0)) {
925                 ctx->device_name = string_copy(ctx, sb->s_volume_name,
926                                                sizeof(sb->s_volume_name));
927         }
928         if (ctx->device_name == 0)
929                 ctx->device_name = ctx->filesystem_name;
930
931         /*
932          * Make sure the ext3 superblock fields are consistent.
933          */
934         retval = e2fsck_check_ext3_journal(ctx);
935         if (retval) {
936                 com_err(ctx->program_name, retval,
937                         _("while checking ext3 journal for %s"),
938                         ctx->device_name);
939                 fatal_error(ctx, 0);
940         }
941
942         /*
943          * Check to see if we need to do ext3-style recovery.  If so,
944          * do it, and then restart the fsck.
945          */
946         if (sb->s_feature_incompat & EXT3_FEATURE_INCOMPAT_RECOVER) {
947                 if (ctx->options & E2F_OPT_READONLY) {
948                         printf(_("Warning: skipping journal recovery "
949                                  "because doing a read-only filesystem "
950                                  "check.\n"));
951                         io_channel_flush(ctx->fs->io);
952                 } else {
953                         if (ctx->flags & E2F_FLAG_RESTARTED) {
954                                 /*
955                                  * Whoops, we attempted to run the
956                                  * journal twice.  This should never
957                                  * happen, unless the hardware or
958                                  * device driver is being bogus.
959                                  */
960                                 com_err(ctx->program_name, 0,
961                                         _("unable to set superblock flags on %s\n"), ctx->device_name);
962                                 fatal_error(ctx, 0);
963                         }
964                         retval = e2fsck_run_ext3_journal(ctx);
965                         if (retval) {
966                                 com_err(ctx->program_name, retval,
967                                 _("while recovering ext3 journal of %s"),
968                                         ctx->device_name);
969                                 fatal_error(ctx, 0);
970                         }
971                         ext2fs_close(ctx->fs);
972                         ctx->fs = 0;
973                         ctx->flags |= E2F_FLAG_RESTARTED;
974                         goto restart;
975                 }
976         }
977
978         /*
979          * Check for compatibility with the feature sets.  We need to
980          * be more stringent than ext2fs_open().
981          */
982         if ((sb->s_feature_compat & ~EXT2_LIB_FEATURE_COMPAT_SUPP) ||
983             (sb->s_feature_incompat & ~EXT2_LIB_FEATURE_INCOMPAT_SUPP)) {
984                 com_err(ctx->program_name, EXT2_ET_UNSUPP_FEATURE,
985                         "(%s)", ctx->device_name);
986                 goto get_newer;
987         }
988         if (sb->s_feature_ro_compat & ~EXT2_LIB_FEATURE_RO_COMPAT_SUPP) {
989                 com_err(ctx->program_name, EXT2_ET_RO_UNSUPP_FEATURE,
990                         "(%s)", ctx->device_name);
991                 goto get_newer;
992         }
993 #ifdef ENABLE_COMPRESSION
994         if (sb->s_feature_incompat & EXT2_FEATURE_INCOMPAT_COMPRESSION)
995                 com_err(ctx->program_name, 0,
996                         _("Warning: compression support is experimental.\n"));
997 #endif
998 #ifndef ENABLE_HTREE
999         if (sb->s_feature_compat & EXT2_FEATURE_COMPAT_DIR_INDEX) {
1000                 com_err(ctx->program_name, 0,
1001                         _("E2fsck not compiled with HTREE support,\n\t"
1002                           "but filesystem %s has HTREE directories.\n"),
1003                         ctx->device_name);
1004                 goto get_newer;
1005         }
1006 #endif
1007
1008         /*
1009          * If the user specified a specific superblock, presumably the
1010          * master superblock has been trashed.  So we mark the
1011          * superblock as dirty, so it can be written out.
1012          */
1013         if (ctx->superblock &&
1014             !(ctx->options & E2F_OPT_READONLY))
1015                 ext2fs_mark_super_dirty(fs);
1016
1017         /*
1018          * We only update the master superblock because (a) paranoia;
1019          * we don't want to corrupt the backup superblocks, and (b) we
1020          * don't need to update the mount count and last checked
1021          * fields in the backup superblock (the kernel doesn't
1022          * update the backup superblocks anyway).
1023          */
1024         fs->flags |= EXT2_FLAG_MASTER_SB_ONLY;
1025
1026         ehandler_init(fs->io);
1027
1028         if (ctx->superblock)
1029                 set_latch_flags(PR_LATCH_RELOC, PRL_LATCHED, 0);
1030         check_super_block(ctx);
1031         if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
1032                 fatal_error(ctx, 0);
1033         check_if_skip(ctx);
1034         if (bad_blocks_file)
1035                 read_bad_blocks_file(ctx, bad_blocks_file, replace_bad_blocks);
1036         else if (cflag)
1037                 read_bad_blocks_file(ctx, 0, 1); /* Test disk */
1038         if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
1039                 fatal_error(ctx, 0);
1040 #ifdef ENABLE_SWAPFS
1041         if (normalize_swapfs) {
1042                 if ((fs->flags & EXT2_FLAG_SWAP_BYTES) ==
1043                     ext2fs_native_flag()) {
1044                         fprintf(stderr, _("%s: Filesystem byte order "
1045                                 "already normalized.\n"), ctx->device_name);
1046                         fatal_error(ctx, 0);
1047                 }
1048         }
1049         if (swapfs) {
1050                 swap_filesys(ctx);
1051                 if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
1052                         fatal_error(ctx, 0);
1053         }
1054 #endif
1055
1056         /*
1057          * Mark the system as valid, 'til proven otherwise
1058          */
1059         ext2fs_mark_valid(fs);
1060
1061         retval = ext2fs_read_bb_inode(fs, &fs->badblocks);
1062         if (retval) {
1063                 com_err(ctx->program_name, retval,
1064                         _("while reading bad blocks inode"));
1065                 preenhalt(ctx);
1066                 printf(_("This doesn't bode well,"
1067                          " but we'll try to go on...\n"));
1068         }
1069
1070         run_result = e2fsck_run(ctx);
1071         e2fsck_clear_progbar(ctx);
1072         if (run_result == E2F_FLAG_RESTART) {
1073                 printf(_("Restarting e2fsck from the beginning...\n"));
1074                 retval = e2fsck_reset_context(ctx);
1075                 if (retval) {
1076                         com_err(ctx->program_name, retval,
1077                                 _("while resetting context"));
1078                         fatal_error(ctx, 0);
1079                 }
1080                 ext2fs_close(fs);
1081                 goto restart;
1082         }
1083         if (run_result & E2F_FLAG_CANCEL) {
1084                 printf(_("%s: e2fsck canceled.\n"), ctx->device_name ?
1085                        ctx->device_name : ctx->filesystem_name);
1086                 exit_value |= FSCK_CANCELED;
1087         }
1088         if (run_result & E2F_FLAG_ABORT)
1089                 fatal_error(ctx, _("aborted"));
1090
1091 #ifdef MTRACE
1092         mtrace_print("Cleanup");
1093 #endif
1094         if (ext2fs_test_changed(fs)) {
1095                 exit_value |= FSCK_NONDESTRUCT;
1096                 if (!(ctx->options & E2F_OPT_PREEN))
1097                     printf(_("\n%s: ***** FILE SYSTEM WAS MODIFIED *****\n"),
1098                                ctx->device_name);
1099                 if (ctx->mount_flags & EXT2_MF_ISROOT) {
1100                         printf(_("%s: ***** REBOOT LINUX *****\n"),
1101                                ctx->device_name);
1102                         exit_value |= FSCK_REBOOT;
1103                 }
1104         }
1105         if (!ext2fs_test_valid(fs)) {
1106                 printf(_("\n%s: ********** WARNING: Filesystem still has "
1107                          "errors **********\n\n"), ctx->device_name);
1108                 exit_value |= FSCK_UNCORRECTED;
1109                 exit_value &= ~FSCK_NONDESTRUCT;
1110         }
1111         if (exit_value & FSCK_CANCELED)
1112                 exit_value &= ~FSCK_NONDESTRUCT;
1113         else {
1114                 show_stats(ctx);
1115                 if (!(ctx->options & E2F_OPT_READONLY)) {
1116                         if (ext2fs_test_valid(fs)) {
1117                                 if (!(sb->s_state & EXT2_VALID_FS))
1118                                         exit_value |= FSCK_NONDESTRUCT;
1119                                 sb->s_state = EXT2_VALID_FS;
1120                         } else
1121                                 sb->s_state &= ~EXT2_VALID_FS;
1122                         sb->s_mnt_count = 0;
1123                         sb->s_lastcheck = time(NULL);
1124                         ext2fs_mark_super_dirty(fs);
1125                 }
1126         }
1127
1128         e2fsck_write_bitmaps(ctx);
1129         
1130         ext2fs_close(fs);
1131         ctx->fs = NULL;
1132         free(ctx->filesystem_name);
1133         free(ctx->journal_name);
1134         e2fsck_free_context(ctx);
1135         
1136 #ifdef RESOURCE_TRACK
1137         if (ctx->options & E2F_OPT_TIME)
1138                 print_resource_track(NULL, &ctx->global_rtrack);
1139 #endif
1140
1141         return exit_value;
1142 }