Whamcloud - gitweb
7e95ca8897ee4a4fb69445f1216a3e7642d8dcb6
[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 #define _XOPEN_SOURCE 600 /* for inclusion of sa_handler in Solaris */
13
14 #include <stdio.h>
15 #ifdef HAVE_STDLIB_H
16 #include <stdlib.h>
17 #endif
18 #include <string.h>
19 #include <fcntl.h>
20 #include <ctype.h>
21 #include <time.h>
22 #ifdef HAVE_SIGNAL_H
23 #include <signal.h>
24 #endif
25 #ifdef HAVE_GETOPT_H
26 #include <getopt.h>
27 #else
28 extern char *optarg;
29 extern int optind;
30 #endif
31 #include <unistd.h>
32 #ifdef HAVE_ERRNO_H
33 #include <errno.h>
34 #endif
35 #ifdef HAVE_MNTENT_H
36 #include <mntent.h>
37 #endif
38 #ifdef HAVE_SYS_IOCTL_H
39 #include <sys/ioctl.h>
40 #endif
41 #ifdef HAVE_MALLOC_H
42 #include <malloc.h>
43 #endif
44 #ifdef HAVE_SYS_TYPES_H
45 #include <sys/types.h>
46 #endif
47 #ifdef HAVE_DIRENT_H
48 #include <dirent.h>
49 #endif
50
51 #include "e2p/e2p.h"
52 #include "et/com_err.h"
53 #include "e2p/e2p.h"
54 #include "e2fsck.h"
55 #include "problem.h"
56 #include "../version.h"
57
58 /* Command line options */
59 static int cflag;               /* check disk */
60 static int show_version_only;
61 static int verbose;
62
63 static int replace_bad_blocks;
64 static int keep_bad_blocks;
65 static char *bad_blocks_file;
66
67 e2fsck_t e2fsck_global_ctx;     /* Try your very best not to use this! */
68
69 #ifdef CONFIG_JBD_DEBUG         /* Enabled by configure --enable-jfs-debug */
70 int journal_enable_debug = -1;
71 #endif
72
73 static void usage(e2fsck_t ctx)
74 {
75         fprintf(stderr,
76                 _("Usage: %s [-panyrcdfvtDFV] [-b superblock] [-B blocksize]\n"
77                 "\t\t[-I inode_buffer_blocks] [-P process_inode_size]\n"
78                 "\t\t[-l|-L bad_blocks_file] [-C fd] [-j external_journal]\n"
79                 "\t\t[-E extended-options] device\n"),
80                 ctx->program_name);
81
82         fprintf(stderr, _("\nEmergency help:\n"
83                 " -p                   Automatic repair (no questions)\n"
84                 " -n                   Make no changes to the filesystem\n"
85                 " -y                   Assume \"yes\" to all questions\n"
86                 " -c                   Check for bad blocks and add them to the badblock list\n"
87                 " -f                   Force checking even if filesystem is marked clean\n"));
88         fprintf(stderr, _(""
89                 " -v                   Be verbose\n"
90                 " -b superblock        Use alternative superblock\n"
91                 " -B blocksize         Force blocksize when looking for superblock\n"
92                 " -j external_journal  Set location of the external journal\n"
93                 " -l bad_blocks_file   Add to badblocks list\n"
94                 " -L bad_blocks_file   Set badblocks list\n"
95                 ));
96
97         exit(FSCK_USAGE);
98 }
99
100 static void show_stats(e2fsck_t ctx)
101 {
102         ext2_filsys fs = ctx->fs;
103         ext2_ino_t inodes, inodes_used;
104         blk64_t blocks, blocks_used;
105         unsigned int dir_links;
106         unsigned int num_files, num_links;
107         int frag_percent_file, frag_percent_dir, frag_percent_total;
108         int i, j;
109
110         dir_links = 2 * ctx->fs_directory_count - 1;
111         num_files = ctx->fs_total_count - dir_links;
112         num_links = ctx->fs_links_count - dir_links;
113         inodes = fs->super->s_inodes_count;
114         inodes_used = (fs->super->s_inodes_count -
115                        fs->super->s_free_inodes_count);
116         blocks = ext2fs_blocks_count(fs->super);
117         blocks_used = (ext2fs_blocks_count(fs->super) -
118                        ext2fs_free_blocks_count(fs->super));
119
120         frag_percent_file = (10000 * ctx->fs_fragmented) / inodes_used;
121         frag_percent_file = (frag_percent_file + 5) / 10;
122
123         frag_percent_dir = (10000 * ctx->fs_fragmented_dir) / inodes_used;
124         frag_percent_dir = (frag_percent_dir + 5) / 10;
125
126         frag_percent_total = ((10000 * (ctx->fs_fragmented +
127                                         ctx->fs_fragmented_dir))
128                               / inodes_used);
129         frag_percent_total = (frag_percent_total + 5) / 10;
130
131         if (!verbose) {
132                 printf(_("%s: %u/%u files (%0d.%d%% non-contiguous), %llu/%llu blocks\n"),
133                        ctx->device_name, inodes_used, inodes,
134                        frag_percent_total / 10, frag_percent_total % 10,
135                        blocks_used, blocks);
136                 return;
137         }
138         printf (P_("\n%8u inode used (%2.2f%%)\n", "\n%8u inodes used (%2.2f%%)\n",
139                    inodes_used), inodes_used, 100.0 * inodes_used / inodes);
140         printf (P_("%8u non-contiguous file (%0d.%d%%)\n",
141                    "%8u non-contiguous files (%0d.%d%%)\n",
142                    ctx->fs_fragmented),
143                 ctx->fs_fragmented, frag_percent_file / 10,
144                 frag_percent_file % 10);
145         printf (P_("%8u non-contiguous directory (%0d.%d%%)\n",
146                    "%8u non-contiguous directories (%0d.%d%%)\n",
147                    ctx->fs_fragmented_dir),
148                 ctx->fs_fragmented_dir, frag_percent_dir / 10,
149                 frag_percent_dir % 10);
150         printf (_("         # of inodes with ind/dind/tind blocks: %u/%u/%u\n"),
151                 ctx->fs_ind_count, ctx->fs_dind_count, ctx->fs_tind_count);
152
153         for (j=MAX_EXTENT_DEPTH_COUNT-1; j >=0; j--)
154                 if (ctx->extent_depth_count[j])
155                         break;
156         if (++j) {
157                 printf (_("         Extent depth histogram: "));
158                 for (i=0; i < j; i++) {
159                         if (i)
160                                 fputc('/', stdout);
161                         printf("%u", ctx->extent_depth_count[i]);
162                 }
163                 fputc('\n', stdout);
164         }
165
166         printf (P_("%8llu block used (%2.2f%%)\n",
167                    "%8llu blocks used (%2.2f%%)\n",
168                    blocks_used), blocks_used, 100.0 * blocks_used / blocks);
169         printf (P_("%8u bad block\n", "%8u bad blocks\n",
170                    ctx->fs_badblocks_count), ctx->fs_badblocks_count);
171         printf (P_("%8u large file\n", "%8u large files\n",
172                    ctx->large_files), ctx->large_files);
173         printf (P_("\n%8u regular file\n", "\n%8u regular files\n",
174                    ctx->fs_regular_count), ctx->fs_regular_count);
175         printf (P_("%8u directory\n", "%8u directories\n",
176                    ctx->fs_directory_count), ctx->fs_directory_count);
177         printf (P_("%8u character device file\n",
178                    "%8u character device files\n", ctx->fs_chardev_count),
179                 ctx->fs_chardev_count);
180         printf (P_("%8u block device file\n", "%8u block device files\n",
181                    ctx->fs_blockdev_count), ctx->fs_blockdev_count);
182         printf (P_("%8u fifo\n", "%8u fifos\n", ctx->fs_fifo_count),
183                 ctx->fs_fifo_count);
184         printf (P_("%8u link\n", "%8u links\n",
185                    ctx->fs_links_count - dir_links),
186                 ctx->fs_links_count - dir_links);
187         printf (P_("%8u symbolic link", "%8u symbolic links",
188                    ctx->fs_symlinks_count), ctx->fs_symlinks_count);
189         printf (P_(" (%u fast symbolic link)\n", " (%u fast symbolic links)\n",
190                    ctx->fs_fast_symlinks_count), ctx->fs_fast_symlinks_count);
191         printf (P_("%8u socket\n", "%8u sockets\n", ctx->fs_sockets_count),
192                 ctx->fs_sockets_count);
193         printf ("--------\n");
194         printf (P_("%8u file\n", "%8u files\n",
195                    ctx->fs_total_count - dir_links),
196                 ctx->fs_total_count - dir_links);
197 }
198
199 static void check_mount(e2fsck_t ctx)
200 {
201         errcode_t       retval;
202         int             cont;
203
204         retval = ext2fs_check_if_mounted(ctx->filesystem_name,
205                                          &ctx->mount_flags);
206         if (retval) {
207                 com_err("ext2fs_check_if_mount", retval,
208                         _("while determining whether %s is mounted."),
209                         ctx->filesystem_name);
210                 return;
211         }
212
213         /*
214          * If the filesystem isn't mounted, or it's the root
215          * filesystem and it's mounted read-only, and we're not doing
216          * a read/write check, then everything's fine.
217          */
218         if ((!(ctx->mount_flags & EXT2_MF_MOUNTED)) ||
219             ((ctx->mount_flags & EXT2_MF_ISROOT) &&
220              (ctx->mount_flags & EXT2_MF_READONLY) &&
221              !(ctx->options & E2F_OPT_WRITECHECK)))
222                 return;
223
224         if ((ctx->options & E2F_OPT_READONLY) &&
225             !(ctx->options & E2F_OPT_WRITECHECK)) {
226                 printf(_("Warning!  %s is mounted.\n"), ctx->filesystem_name);
227                 return;
228         }
229
230         printf(_("%s is mounted.  "), ctx->filesystem_name);
231         if (!ctx->interactive)
232                 fatal_error(ctx, _("Cannot continue, aborting.\n\n"));
233         printf(_("\n\n\007\007\007\007WARNING!!!  "
234                "The filesystem is mounted.   If you continue you ***WILL***\n"
235                "cause ***SEVERE*** filesystem damage.\007\007\007\n\n"));
236         cont = ask_yn(_("Do you really want to continue"), 0);
237         if (!cont) {
238                 printf (_("check aborted.\n"));
239                 exit (0);
240         }
241         return;
242 }
243
244 static int is_on_batt(void)
245 {
246         FILE    *f;
247         DIR     *d;
248         char    tmp[80], tmp2[80], fname[80];
249         unsigned int    acflag;
250         struct dirent*  de;
251
252         f = fopen("/proc/apm", "r");
253         if (f) {
254                 if (fscanf(f, "%s %s %s %x", tmp, tmp, tmp, &acflag) != 4)
255                         acflag = 1;
256                 fclose(f);
257                 return (acflag != 1);
258         }
259         d = opendir("/proc/acpi/ac_adapter");
260         if (d) {
261                 while ((de=readdir(d)) != NULL) {
262                         if (!strncmp(".", de->d_name, 1))
263                                 continue;
264                         snprintf(fname, 80, "/proc/acpi/ac_adapter/%s/state",
265                                  de->d_name);
266                         f = fopen(fname, "r");
267                         if (!f)
268                                 continue;
269                         if (fscanf(f, "%s %s", tmp2, tmp) != 2)
270                                 tmp[0] = 0;
271                         fclose(f);
272                         if (strncmp(tmp, "off-line", 8) == 0) {
273                                 closedir(d);
274                                 return 1;
275                         }
276                 }
277                 closedir(d);
278         }
279         return 0;
280 }
281
282 /*
283  * This routine checks to see if a filesystem can be skipped; if so,
284  * it will exit with E2FSCK_OK.  Under some conditions it will print a
285  * message explaining why a check is being forced.
286  */
287 static void check_if_skip(e2fsck_t ctx)
288 {
289         ext2_filsys fs = ctx->fs;
290         struct problem_context pctx;
291         const char *reason = NULL;
292         unsigned int reason_arg = 0;
293         long next_check;
294         int batt = is_on_batt();
295         int defer_check_on_battery;
296         int broken_system_clock;
297         time_t lastcheck;
298
299         profile_get_boolean(ctx->profile, "options", "broken_system_clock",
300                             0, 0, &broken_system_clock);
301         if (ctx->flags & E2F_FLAG_TIME_INSANE)
302                 broken_system_clock = 1;
303         profile_get_boolean(ctx->profile, "options",
304                             "defer_check_on_battery", 0, 1,
305                             &defer_check_on_battery);
306         if (!defer_check_on_battery)
307                 batt = 0;
308
309         if ((ctx->options & E2F_OPT_FORCE) || bad_blocks_file || cflag)
310                 return;
311
312         if (ctx->options & E2F_OPT_JOURNAL_ONLY)
313                 goto skip;
314
315         lastcheck = fs->super->s_lastcheck;
316         if (lastcheck > ctx->now)
317                 lastcheck -= ctx->time_fudge;
318         if ((fs->super->s_state & EXT2_ERROR_FS) ||
319             !ext2fs_test_valid(fs))
320                 reason = _(" contains a file system with errors");
321         else if ((fs->super->s_state & EXT2_VALID_FS) == 0)
322                 reason = _(" was not cleanly unmounted");
323         else if (check_backup_super_block(ctx))
324                 reason = _(" primary superblock features different from backup");
325         else if ((fs->super->s_max_mnt_count > 0) &&
326                  (fs->super->s_mnt_count >=
327                   (unsigned) fs->super->s_max_mnt_count)) {
328                 reason = _(" has been mounted %u times without being checked");
329                 reason_arg = fs->super->s_mnt_count;
330                 if (batt && (fs->super->s_mnt_count <
331                              (unsigned) fs->super->s_max_mnt_count*2))
332                         reason = 0;
333         } else if (!broken_system_clock && fs->super->s_checkinterval &&
334                    (ctx->now < lastcheck)) {
335                 reason = _(" has filesystem last checked time in the future");
336                 if (batt)
337                         reason = 0;
338         } else if (!broken_system_clock && fs->super->s_checkinterval &&
339                    ((ctx->now - lastcheck) >=
340                     ((time_t) fs->super->s_checkinterval))) {
341                 reason = _(" has gone %u days without being checked");
342                 reason_arg = (ctx->now - fs->super->s_lastcheck)/(3600*24);
343                 if (batt && ((ctx->now - fs->super->s_lastcheck) <
344                              fs->super->s_checkinterval*2))
345                         reason = 0;
346         }
347         if (reason) {
348                 fputs(ctx->device_name, stdout);
349                 printf(reason, reason_arg);
350                 fputs(_(", check forced.\n"), stdout);
351                 return;
352         }
353
354         /*
355          * Update the global counts from the block group counts.  This
356          * is needed since modern kernels don't update the global
357          * counts so as to avoid locking the entire file system.  So
358          * if the filesystem is not unmounted cleanly, the global
359          * counts may not be accurate.  Update them here if we can,
360          * for the benefit of users who might examine the file system
361          * using dumpe2fs.  (This is for cosmetic reasons only.)
362          */
363         clear_problem_context(&pctx);
364         pctx.ino = fs->super->s_free_inodes_count;
365         pctx.ino2 = ctx->free_inodes;
366         if ((pctx.ino != pctx.ino2) &&
367             !(ctx->options & E2F_OPT_READONLY) &&
368             fix_problem(ctx, PR_0_FREE_INODE_COUNT, &pctx)) {
369                 fs->super->s_free_inodes_count = ctx->free_inodes;
370                 ext2fs_mark_super_dirty(fs);
371         }
372         clear_problem_context(&pctx);
373         pctx.blk = ext2fs_free_blocks_count(fs->super);
374         pctx.blk2 = ctx->free_blocks;
375         if ((pctx.blk != pctx.blk2) &&
376             !(ctx->options & E2F_OPT_READONLY) &&
377             fix_problem(ctx, PR_0_FREE_BLOCK_COUNT, &pctx)) {
378                 ext2fs_free_blocks_count_set(fs->super, ctx->free_blocks);
379                 ext2fs_mark_super_dirty(fs);
380         }
381
382         /* Print the summary message when we're skipping a full check */
383         printf(_("%s: clean, %u/%u files, %llu/%llu blocks"), ctx->device_name,
384                fs->super->s_inodes_count - fs->super->s_free_inodes_count,
385                fs->super->s_inodes_count,
386                ext2fs_blocks_count(fs->super) -
387                ext2fs_free_blocks_count(fs->super),
388                ext2fs_blocks_count(fs->super));
389         next_check = 100000;
390         if (fs->super->s_max_mnt_count > 0) {
391                 next_check = fs->super->s_max_mnt_count - fs->super->s_mnt_count;
392                 if (next_check <= 0)
393                         next_check = 1;
394         }
395         if (!broken_system_clock && fs->super->s_checkinterval &&
396             ((ctx->now - fs->super->s_lastcheck) >= fs->super->s_checkinterval))
397                 next_check = 1;
398         if (next_check <= 5) {
399                 if (next_check == 1) {
400                         if (batt)
401                                 fputs(_(" (check deferred; on battery)"),
402                                       stdout);
403                         else
404                                 fputs(_(" (check after next mount)"), stdout);
405                 } else
406                         printf(_(" (check in %ld mounts)"), next_check);
407         }
408         fputc('\n', stdout);
409 skip:
410         ext2fs_close(fs);
411         ctx->fs = NULL;
412         e2fsck_free_context(ctx);
413         exit(FSCK_OK);
414 }
415
416 /*
417  * For completion notice
418  */
419 struct percent_tbl {
420         int     max_pass;
421         int     table[32];
422 };
423 struct percent_tbl e2fsck_tbl = {
424         5, { 0, 70, 90, 92,  95, 100 }
425 };
426 static char bar[128], spaces[128];
427
428 static float calc_percent(struct percent_tbl *tbl, int pass, int curr,
429                           int max)
430 {
431         float   percent;
432
433         if (pass <= 0)
434                 return 0.0;
435         if (pass > tbl->max_pass || max == 0)
436                 return 100.0;
437         percent = ((float) curr) / ((float) max);
438         return ((percent * (tbl->table[pass] - tbl->table[pass-1]))
439                 + tbl->table[pass-1]);
440 }
441
442 extern void e2fsck_clear_progbar(e2fsck_t ctx)
443 {
444         if (!(ctx->flags & E2F_FLAG_PROG_BAR))
445                 return;
446
447         printf("%s%s\r%s", ctx->start_meta, spaces + (sizeof(spaces) - 80),
448                ctx->stop_meta);
449         fflush(stdout);
450         ctx->flags &= ~E2F_FLAG_PROG_BAR;
451 }
452
453 int e2fsck_simple_progress(e2fsck_t ctx, const char *label, float percent,
454                            unsigned int dpynum)
455 {
456         static const char spinner[] = "\\|/-";
457         int     i;
458         unsigned int    tick;
459         struct timeval  tv;
460         int dpywidth;
461         int fixed_percent;
462
463         if (ctx->flags & E2F_FLAG_PROG_SUPPRESS)
464                 return 0;
465
466         /*
467          * Calculate the new progress position.  If the
468          * percentage hasn't changed, then we skip out right
469          * away.
470          */
471         fixed_percent = (int) ((10 * percent) + 0.5);
472         if (ctx->progress_last_percent == fixed_percent)
473                 return 0;
474         ctx->progress_last_percent = fixed_percent;
475
476         /*
477          * If we've already updated the spinner once within
478          * the last 1/8th of a second, no point doing it
479          * again.
480          */
481         gettimeofday(&tv, NULL);
482         tick = (tv.tv_sec << 3) + (tv.tv_usec / (1000000 / 8));
483         if ((tick == ctx->progress_last_time) &&
484             (fixed_percent != 0) && (fixed_percent != 1000))
485                 return 0;
486         ctx->progress_last_time = tick;
487
488         /*
489          * Advance the spinner, and note that the progress bar
490          * will be on the screen
491          */
492         ctx->progress_pos = (ctx->progress_pos+1) & 3;
493         ctx->flags |= E2F_FLAG_PROG_BAR;
494
495         dpywidth = 66 - strlen(label);
496         dpywidth = 8 * (dpywidth / 8);
497         if (dpynum)
498                 dpywidth -= 8;
499
500         i = ((percent * dpywidth) + 50) / 100;
501         printf("%s%s: |%s%s", ctx->start_meta, label,
502                bar + (sizeof(bar) - (i+1)),
503                spaces + (sizeof(spaces) - (dpywidth - i + 1)));
504         if (fixed_percent == 1000)
505                 fputc('|', stdout);
506         else
507                 fputc(spinner[ctx->progress_pos & 3], stdout);
508         printf(" %4.1f%%  ", percent);
509         if (dpynum)
510                 printf("%u\r", dpynum);
511         else
512                 fputs(" \r", stdout);
513         fputs(ctx->stop_meta, stdout);
514
515         if (fixed_percent == 1000)
516                 e2fsck_clear_progbar(ctx);
517         fflush(stdout);
518
519         return 0;
520 }
521
522 static int e2fsck_update_progress(e2fsck_t ctx, int pass,
523                                   unsigned long cur, unsigned long max)
524 {
525         char buf[1024];
526         float percent;
527
528         if (pass == 0)
529                 return 0;
530
531         if (ctx->progress_fd) {
532                 snprintf(buf, sizeof(buf), "%d %lu %lu %s\n",
533                          pass, cur, max, ctx->device_name);
534                 write_all(ctx->progress_fd, buf, strlen(buf));
535         } else {
536                 percent = calc_percent(&e2fsck_tbl, pass, cur, max);
537                 e2fsck_simple_progress(ctx, ctx->device_name,
538                                        percent, 0);
539         }
540         return 0;
541 }
542
543 #define PATH_SET "PATH=/sbin"
544
545 static void reserve_stdio_fds(void)
546 {
547         int     fd;
548
549         while (1) {
550                 fd = open("/dev/null", O_RDWR);
551                 if (fd > 2)
552                         break;
553                 if (fd < 0) {
554                         fprintf(stderr, _("ERROR: Couldn't open "
555                                 "/dev/null (%s)\n"),
556                                 strerror(errno));
557                         break;
558                 }
559         }
560         close(fd);
561 }
562
563 #ifdef HAVE_SIGNAL_H
564 static void signal_progress_on(int sig EXT2FS_ATTR((unused)))
565 {
566         e2fsck_t ctx = e2fsck_global_ctx;
567
568         if (!ctx)
569                 return;
570
571         ctx->progress = e2fsck_update_progress;
572 }
573
574 static void signal_progress_off(int sig EXT2FS_ATTR((unused)))
575 {
576         e2fsck_t ctx = e2fsck_global_ctx;
577
578         if (!ctx)
579                 return;
580
581         e2fsck_clear_progbar(ctx);
582         ctx->progress = 0;
583 }
584
585 static void signal_cancel(int sig EXT2FS_ATTR((unused)))
586 {
587         e2fsck_t ctx = e2fsck_global_ctx;
588
589         if (!ctx)
590                 exit(FSCK_CANCELED);
591
592         ctx->flags |= E2F_FLAG_CANCEL;
593 }
594 #endif
595
596 static void parse_extended_opts(e2fsck_t ctx, const char *opts)
597 {
598         char    *buf, *token, *next, *p, *arg;
599         int     ea_ver;
600         int     extended_usage = 0;
601
602         buf = string_copy(ctx, opts, 0);
603         for (token = buf; token && *token; token = next) {
604                 p = strchr(token, ',');
605                 next = 0;
606                 if (p) {
607                         *p = 0;
608                         next = p+1;
609                 }
610                 arg = strchr(token, '=');
611                 if (arg) {
612                         *arg = 0;
613                         arg++;
614                 }
615                 if (strcmp(token, "ea_ver") == 0) {
616                         if (!arg) {
617                                 extended_usage++;
618                                 continue;
619                         }
620                         ea_ver = strtoul(arg, &p, 0);
621                         if (*p ||
622                             ((ea_ver != 1) && (ea_ver != 2))) {
623                                 fprintf(stderr,
624                                         _("Invalid EA version.\n"));
625                                 extended_usage++;
626                                 continue;
627                         }
628                         ctx->ext_attr_ver = ea_ver;
629                 } else if (strcmp(token, "fragcheck") == 0) {
630                         ctx->options |= E2F_OPT_FRAGCHECK;
631                         continue;
632                 } else if (strcmp(token, "journal_only") == 0) {
633                         if (arg) {
634                                 extended_usage++;
635                                 continue;
636                         }
637                         ctx->options |= E2F_OPT_JOURNAL_ONLY;
638                 } else if (strcmp(token, "discard") == 0) {
639                         ctx->options |= E2F_OPT_DISCARD;
640                         continue;
641                 } else if (strcmp(token, "nodiscard") == 0) {
642                         ctx->options &= ~E2F_OPT_DISCARD;
643                         continue;
644                 } else {
645                         fprintf(stderr, _("Unknown extended option: %s\n"),
646                                 token);
647                         extended_usage++;
648                 }
649         }
650         free(buf);
651
652         if (extended_usage) {
653                 fputs(("\nExtended options are separated by commas, "
654                        "and may take an argument which\n"
655                        "is set off by an equals ('=') sign.  "
656                        "Valid extended options are:\n"), stderr);
657                 fputs(("\tea_ver=<ea_version (1 or 2)>\n"), stderr);
658                 fputs(("\tfragcheck\n"), stderr);
659                 fputs(("\tjournal_only\n"), stderr);
660                 fputs(("\tdiscard\n"), stderr);
661                 fputs(("\tnodiscard\n"), stderr);
662                 fputc('\n', stderr);
663                 exit(1);
664         }
665 }
666
667 static void syntax_err_report(const char *filename, long err, int line_num)
668 {
669         fprintf(stderr,
670                 _("Syntax error in e2fsck config file (%s, line #%d)\n\t%s\n"),
671                 filename, line_num, error_message(err));
672         exit(FSCK_ERROR);
673 }
674
675 static const char *config_fn[] = { ROOT_SYSCONFDIR "/e2fsck.conf", 0 };
676
677 static errcode_t PRS(int argc, char *argv[], e2fsck_t *ret_ctx)
678 {
679         int             flush = 0;
680         int             c, fd;
681 #ifdef MTRACE
682         extern void     *mallwatch;
683 #endif
684         e2fsck_t        ctx;
685         errcode_t       retval;
686 #ifdef HAVE_SIGNAL_H
687         struct sigaction        sa;
688 #endif
689         char            *extended_opts = 0;
690         char            *cp;
691         int             res;            /* result of sscanf */
692 #ifdef CONFIG_JBD_DEBUG
693         char            *jbd_debug;
694 #endif
695
696         retval = e2fsck_allocate_context(&ctx);
697         if (retval)
698                 return retval;
699
700         *ret_ctx = ctx;
701
702         setvbuf(stdout, NULL, _IONBF, BUFSIZ);
703         setvbuf(stderr, NULL, _IONBF, BUFSIZ);
704         if (isatty(0) && isatty(1)) {
705                 ctx->interactive = 1;
706         } else {
707                 ctx->start_meta[0] = '\001';
708                 ctx->stop_meta[0] = '\002';
709         }
710         memset(bar, '=', sizeof(bar)-1);
711         memset(spaces, ' ', sizeof(spaces)-1);
712         add_error_table(&et_ext2_error_table);
713         add_error_table(&et_prof_error_table);
714         blkid_get_cache(&ctx->blkid, NULL);
715
716         if (argc && *argv)
717                 ctx->program_name = *argv;
718         else
719                 ctx->program_name = "e2fsck";
720
721         while ((c = getopt (argc, argv, "panyrcC:B:dE:fvtFVM:b:I:j:P:l:L:N:SsDk")) != EOF)
722                 switch (c) {
723                 case 'C':
724                         ctx->progress = e2fsck_update_progress;
725                         res = sscanf(optarg, "%d", &ctx->progress_fd);
726                         if (res != 1)
727                                 goto sscanf_err;
728
729                         if (ctx->progress_fd < 0) {
730                                 ctx->progress = 0;
731                                 ctx->progress_fd = ctx->progress_fd * -1;
732                         }
733                         if (!ctx->progress_fd)
734                                 break;
735                         /* Validate the file descriptor to avoid disasters */
736                         fd = dup(ctx->progress_fd);
737                         if (fd < 0) {
738                                 fprintf(stderr,
739                                 _("Error validating file descriptor %d: %s\n"),
740                                         ctx->progress_fd,
741                                         error_message(errno));
742                                 fatal_error(ctx,
743                         _("Invalid completion information file descriptor"));
744                         } else
745                                 close(fd);
746                         break;
747                 case 'D':
748                         ctx->options |= E2F_OPT_COMPRESS_DIRS;
749                         break;
750                 case 'E':
751                         extended_opts = optarg;
752                         break;
753                 case 'p':
754                 case 'a':
755                         if (ctx->options & (E2F_OPT_YES|E2F_OPT_NO)) {
756                         conflict_opt:
757                                 fatal_error(ctx,
758         _("Only one of the options -p/-a, -n or -y may be specified."));
759                         }
760                         ctx->options |= E2F_OPT_PREEN;
761                         break;
762                 case 'n':
763                         if (ctx->options & (E2F_OPT_YES|E2F_OPT_PREEN))
764                                 goto conflict_opt;
765                         ctx->options |= E2F_OPT_NO;
766                         break;
767                 case 'y':
768                         if (ctx->options & (E2F_OPT_PREEN|E2F_OPT_NO))
769                                 goto conflict_opt;
770                         ctx->options |= E2F_OPT_YES;
771                         break;
772                 case 't':
773 #ifdef RESOURCE_TRACK
774                         if (ctx->options & E2F_OPT_TIME)
775                                 ctx->options |= E2F_OPT_TIME2;
776                         else
777                                 ctx->options |= E2F_OPT_TIME;
778 #else
779                         fprintf(stderr, _("The -t option is not "
780                                 "supported on this version of e2fsck.\n"));
781 #endif
782                         break;
783                 case 'c':
784                         if (cflag++)
785                                 ctx->options |= E2F_OPT_WRITECHECK;
786                         ctx->options |= E2F_OPT_CHECKBLOCKS;
787                         break;
788                 case 'r':
789                         /* What we do by default, anyway! */
790                         break;
791                 case 'b':
792                         res = sscanf(optarg, "%llu", &ctx->use_superblock);
793                         if (res != 1)
794                                 goto sscanf_err;
795                         ctx->flags |= E2F_FLAG_SB_SPECIFIED;
796                         break;
797                 case 'B':
798                         ctx->blocksize = atoi(optarg);
799                         break;
800                 case 'I':
801                         res = sscanf(optarg, "%d", &ctx->inode_buffer_blocks);
802                         if (res != 1)
803                                 goto sscanf_err;
804                         break;
805                 case 'j':
806                         ctx->journal_name = blkid_get_devname(ctx->blkid,
807                                                               optarg, NULL);
808                         if (!ctx->journal_name) {
809                                 com_err(ctx->program_name, 0,
810                                         _("Unable to resolve '%s'"),
811                                         optarg);
812                                 fatal_error(ctx, 0);
813                         }
814                         break;
815                 case 'P':
816                         res = sscanf(optarg, "%d", &ctx->process_inode_size);
817                         if (res != 1)
818                                 goto sscanf_err;
819                         break;
820                 case 'L':
821                         replace_bad_blocks++;
822                 case 'l':
823                         bad_blocks_file = string_copy(ctx, optarg, 0);
824                         break;
825                 case 'd':
826                         ctx->options |= E2F_OPT_DEBUG;
827                         break;
828                 case 'f':
829                         ctx->options |= E2F_OPT_FORCE;
830                         break;
831                 case 'F':
832                         flush = 1;
833                         break;
834                 case 'v':
835                         verbose = 1;
836                         break;
837                 case 'V':
838                         show_version_only = 1;
839                         break;
840 #ifdef MTRACE
841                 case 'M':
842                         mallwatch = (void *) strtol(optarg, NULL, 0);
843                         break;
844 #endif
845                 case 'N':
846                         ctx->device_name = string_copy(ctx, optarg, 0);
847                         break;
848                 case 'k':
849                         keep_bad_blocks++;
850                         break;
851                 default:
852                         usage(ctx);
853                 }
854         if (show_version_only)
855                 return 0;
856         if (optind != argc - 1)
857                 usage(ctx);
858         if ((ctx->options & E2F_OPT_NO) &&
859             (ctx->options & E2F_OPT_COMPRESS_DIRS)) {
860                 com_err(ctx->program_name, 0,
861                         _("The -n and -D options are incompatible."));
862                 fatal_error(ctx, 0);
863         }
864         if ((ctx->options & E2F_OPT_NO) && cflag) {
865                 com_err(ctx->program_name, 0,
866                         _("The -n and -c options are incompatible."));
867                 fatal_error(ctx, 0);
868         }
869         if ((ctx->options & E2F_OPT_NO) && bad_blocks_file) {
870                 com_err(ctx->program_name, 0,
871                         _("The -n and -l/-L options are incompatible."));
872                 fatal_error(ctx, 0);
873         }
874         if (ctx->options & E2F_OPT_NO)
875                 ctx->options |= E2F_OPT_READONLY;
876
877         ctx->io_options = strchr(argv[optind], '?');
878         if (ctx->io_options)
879                 *ctx->io_options++ = 0;
880         ctx->filesystem_name = blkid_get_devname(ctx->blkid, argv[optind], 0);
881         if (!ctx->filesystem_name) {
882                 com_err(ctx->program_name, 0, _("Unable to resolve '%s'"),
883                         argv[optind]);
884                 fatal_error(ctx, 0);
885         }
886         if (extended_opts)
887                 parse_extended_opts(ctx, extended_opts);
888
889         if ((cp = getenv("E2FSCK_CONFIG")) != NULL)
890                 config_fn[0] = cp;
891         profile_set_syntax_err_cb(syntax_err_report);
892         profile_init(config_fn, &ctx->profile);
893
894         if (flush) {
895                 fd = open(ctx->filesystem_name, O_RDONLY, 0);
896                 if (fd < 0) {
897                         com_err("open", errno,
898                                 _("while opening %s for flushing"),
899                                 ctx->filesystem_name);
900                         fatal_error(ctx, 0);
901                 }
902                 if ((retval = ext2fs_sync_device(fd, 1))) {
903                         com_err("ext2fs_sync_device", retval,
904                                 _("while trying to flush %s"),
905                                 ctx->filesystem_name);
906                         fatal_error(ctx, 0);
907                 }
908                 close(fd);
909         }
910         if (cflag && bad_blocks_file) {
911                 fprintf(stderr, _("The -c and the -l/-L options may "
912                                   "not be both used at the same time.\n"));
913                 exit(FSCK_USAGE);
914         }
915 #ifdef HAVE_SIGNAL_H
916         /*
917          * Set up signal action
918          */
919         memset(&sa, 0, sizeof(struct sigaction));
920         sa.sa_handler = signal_cancel;
921         sigaction(SIGINT, &sa, 0);
922         sigaction(SIGTERM, &sa, 0);
923 #ifdef SA_RESTART
924         sa.sa_flags = SA_RESTART;
925 #endif
926         e2fsck_global_ctx = ctx;
927         sa.sa_handler = signal_progress_on;
928         sigaction(SIGUSR1, &sa, 0);
929         sa.sa_handler = signal_progress_off;
930         sigaction(SIGUSR2, &sa, 0);
931 #endif
932
933         /* Update our PATH to include /sbin if we need to run badblocks  */
934         if (cflag) {
935                 char *oldpath = getenv("PATH");
936                 char *newpath;
937                 int len = sizeof(PATH_SET) + 1;
938
939                 if (oldpath)
940                         len += strlen(oldpath);
941
942                 newpath = malloc(len);
943                 if (!newpath)
944                         fatal_error(ctx, "Couldn't malloc() newpath");
945                 strcpy(newpath, PATH_SET);
946
947                 if (oldpath) {
948                         strcat(newpath, ":");
949                         strcat(newpath, oldpath);
950                 }
951                 putenv(newpath);
952         }
953 #ifdef CONFIG_JBD_DEBUG
954         jbd_debug = getenv("E2FSCK_JBD_DEBUG");
955         if (jbd_debug) {
956                 res = sscanf(jbd_debug, "%d", &journal_enable_debug);
957                 if (res != 1) {
958                         fprintf(stderr,
959                                 _("E2FSCK_JBD_DEBUG \"%s\" not an integer\n\n"),
960                                 jbd_debug);
961                         exit (1);
962                 }
963         }
964 #endif
965         return 0;
966
967 sscanf_err:
968         fprintf(stderr, _("\nInvalid non-numeric argument to -%c (\"%s\")\n\n"),
969                 c, optarg);
970         exit (1);
971 }
972
973 static errcode_t try_open_fs(e2fsck_t ctx, int flags, io_manager io_ptr,
974                              ext2_filsys *ret_fs)
975 {
976         errcode_t retval;
977
978         *ret_fs = NULL;
979         if (ctx->superblock && ctx->blocksize) {
980                 retval = ext2fs_open2(ctx->filesystem_name, ctx->io_options,
981                                       flags, ctx->superblock, ctx->blocksize,
982                                       io_ptr, ret_fs);
983         } else if (ctx->superblock) {
984                 int blocksize;
985                 for (blocksize = EXT2_MIN_BLOCK_SIZE;
986                      blocksize <= EXT2_MAX_BLOCK_SIZE; blocksize *= 2) {
987                         if (*ret_fs) {
988                                 ext2fs_free(*ret_fs);
989                                 *ret_fs = NULL;
990                         }
991                         retval = ext2fs_open2(ctx->filesystem_name,
992                                               ctx->io_options, flags,
993                                               ctx->superblock, blocksize,
994                                               io_ptr, ret_fs);
995                         if (!retval)
996                                 break;
997                 }
998         } else
999                 retval = ext2fs_open2(ctx->filesystem_name, ctx->io_options,
1000                                       flags, 0, 0, io_ptr, ret_fs);
1001         return retval;
1002 }
1003
1004 static const char *my_ver_string = E2FSPROGS_VERSION;
1005 static const char *my_ver_date = E2FSPROGS_DATE;
1006
1007 int main (int argc, char *argv[])
1008 {
1009         errcode_t       retval = 0, retval2 = 0, orig_retval = 0;
1010         int             exit_value = FSCK_OK;
1011         ext2_filsys     fs = 0;
1012         io_manager      io_ptr;
1013         struct ext2_super_block *sb;
1014         const char      *lib_ver_date;
1015         int             my_ver, lib_ver;
1016         e2fsck_t        ctx;
1017         blk_t           orig_superblock;
1018         struct problem_context pctx;
1019         int flags, run_result;
1020         int journal_size;
1021         int sysval, sys_page_size = 4096;
1022         int old_bitmaps;
1023         __u32 features[3];
1024         char *cp;
1025
1026         clear_problem_context(&pctx);
1027 #ifdef MTRACE
1028         mtrace();
1029 #endif
1030 #ifdef MCHECK
1031         mcheck(0);
1032 #endif
1033 #ifdef ENABLE_NLS
1034         setlocale(LC_MESSAGES, "");
1035         setlocale(LC_CTYPE, "");
1036         bindtextdomain(NLS_CAT_NAME, LOCALEDIR);
1037         textdomain(NLS_CAT_NAME);
1038 #endif
1039         my_ver = ext2fs_parse_version_string(my_ver_string);
1040         lib_ver = ext2fs_get_library_version(0, &lib_ver_date);
1041         if (my_ver > lib_ver) {
1042                 fprintf( stderr, _("Error: ext2fs library version "
1043                         "out of date!\n"));
1044                 show_version_only++;
1045         }
1046
1047         retval = PRS(argc, argv, &ctx);
1048         if (retval) {
1049                 com_err("e2fsck", retval,
1050                         _("while trying to initialize program"));
1051                 exit(FSCK_ERROR);
1052         }
1053         reserve_stdio_fds();
1054
1055         init_resource_track(&ctx->global_rtrack, NULL);
1056         if (!(ctx->options & E2F_OPT_PREEN) || show_version_only)
1057                 fprintf(stderr, "e2fsck %s (%s)\n", my_ver_string,
1058                          my_ver_date);
1059
1060         if (show_version_only) {
1061                 fprintf(stderr, _("\tUsing %s, %s\n"),
1062                         error_message(EXT2_ET_BASE), lib_ver_date);
1063                 exit(FSCK_OK);
1064         }
1065
1066         check_mount(ctx);
1067
1068         if (!(ctx->options & E2F_OPT_PREEN) &&
1069             !(ctx->options & E2F_OPT_NO) &&
1070             !(ctx->options & E2F_OPT_YES)) {
1071                 if (!ctx->interactive)
1072                         fatal_error(ctx,
1073                                     _("need terminal for interactive repairs"));
1074         }
1075         ctx->superblock = ctx->use_superblock;
1076 restart:
1077 #ifdef CONFIG_TESTIO_DEBUG
1078         if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_BLOCK")) {
1079                 io_ptr = test_io_manager;
1080                 test_io_backing_manager = unix_io_manager;
1081         } else
1082 #endif
1083                 io_ptr = unix_io_manager;
1084         flags = EXT2_FLAG_NOFREE_ON_ERROR;
1085         profile_get_boolean(ctx->profile, "options", "old_bitmaps", 0, 0,
1086                             &old_bitmaps);
1087         if (!old_bitmaps)
1088                 flags |= EXT2_FLAG_64BITS;
1089         if ((ctx->options & E2F_OPT_READONLY) == 0)
1090                 flags |= EXT2_FLAG_RW;
1091         if ((ctx->mount_flags & EXT2_MF_MOUNTED) == 0)
1092                 flags |= EXT2_FLAG_EXCLUSIVE;
1093
1094         retval = try_open_fs(ctx, flags, io_ptr, &fs);
1095
1096         if (!ctx->superblock && !(ctx->options & E2F_OPT_PREEN) &&
1097             !(ctx->flags & E2F_FLAG_SB_SPECIFIED) &&
1098             ((retval == EXT2_ET_BAD_MAGIC) ||
1099              (retval == EXT2_ET_CORRUPT_SUPERBLOCK) ||
1100              ((retval == 0) && (retval2 = ext2fs_check_desc(fs))))) {
1101                 if (retval2 == ENOMEM) {
1102                         retval = retval2;
1103                         goto failure;
1104                 }
1105                 if (fs->flags & EXT2_FLAG_NOFREE_ON_ERROR) {
1106                         ext2fs_free(fs);
1107                         fs = NULL;
1108                 }
1109                 if (!fs || (fs->group_desc_count > 1)) {
1110                         printf(_("%s: %s trying backup blocks...\n"),
1111                                ctx->program_name,
1112                                retval ? _("Superblock invalid,") :
1113                                _("Group descriptors look bad..."));
1114                         orig_superblock = ctx->superblock;
1115                         get_backup_sb(ctx, fs, ctx->filesystem_name, io_ptr);
1116                         if (fs)
1117                                 ext2fs_close(fs);
1118                         orig_retval = retval;
1119                         retval = try_open_fs(ctx, flags, io_ptr, &fs);
1120                         if ((orig_retval == 0) && retval != 0) {
1121                                 if (fs)
1122                                         ext2fs_close(fs);
1123                                 com_err(ctx->program_name, retval,
1124                                         "when using the backup blocks");
1125                                 printf(_("%s: going back to original "
1126                                          "superblock\n"), ctx->program_name);
1127                                 ctx->superblock = orig_superblock;
1128                                 retval = try_open_fs(ctx, flags, io_ptr, &fs);
1129                         }
1130                 }
1131         }
1132         if (((retval == EXT2_ET_UNSUPP_FEATURE) ||
1133              (retval == EXT2_ET_RO_UNSUPP_FEATURE)) &&
1134             fs && fs->super) {
1135                 sb = fs->super;
1136                 features[0] = (sb->s_feature_compat &
1137                                ~EXT2_LIB_FEATURE_COMPAT_SUPP);
1138                 features[1] = (sb->s_feature_incompat &
1139                                ~EXT2_LIB_FEATURE_INCOMPAT_SUPP);
1140                 features[2] = (sb->s_feature_ro_compat &
1141                                ~EXT2_LIB_FEATURE_RO_COMPAT_SUPP);
1142                 if (features[0] || features[1] || features[2])
1143                         goto print_unsupp_features;
1144         }
1145 failure:
1146         if (retval) {
1147                 if (orig_retval)
1148                         retval = orig_retval;
1149                 com_err(ctx->program_name, retval, _("while trying to open %s"),
1150                         ctx->filesystem_name);
1151                 if (retval == EXT2_ET_REV_TOO_HIGH) {
1152                         printf(_("The filesystem revision is apparently "
1153                                "too high for this version of e2fsck.\n"
1154                                "(Or the filesystem superblock "
1155                                "is corrupt)\n\n"));
1156                         fix_problem(ctx, PR_0_SB_CORRUPT, &pctx);
1157                 } else if (retval == EXT2_ET_SHORT_READ)
1158                         printf(_("Could this be a zero-length partition?\n"));
1159                 else if ((retval == EPERM) || (retval == EACCES))
1160                         printf(_("You must have %s access to the "
1161                                "filesystem or be root\n"),
1162                                (ctx->options & E2F_OPT_READONLY) ?
1163                                "r/o" : "r/w");
1164                 else if (retval == ENXIO)
1165                         printf(_("Possibly non-existent or swap device?\n"));
1166                 else if (retval == EBUSY)
1167                         printf(_("Filesystem mounted or opened exclusively "
1168                                  "by another program?\n"));
1169                 else if (retval == ENOENT)
1170                         printf(_("Possibly non-existent device?\n"));
1171 #ifdef EROFS
1172                 else if (retval == EROFS)
1173                         printf(_("Disk write-protected; use the -n option "
1174                                "to do a read-only\n"
1175                                "check of the device.\n"));
1176 #endif
1177                 else
1178                         fix_problem(ctx, PR_0_SB_CORRUPT, &pctx);
1179                 fatal_error(ctx, 0);
1180         }
1181         /*
1182          * We only update the master superblock because (a) paranoia;
1183          * we don't want to corrupt the backup superblocks, and (b) we
1184          * don't need to update the mount count and last checked
1185          * fields in the backup superblock (the kernel doesn't update
1186          * the backup superblocks anyway).  With newer versions of the
1187          * library this flag is set by ext2fs_open2(), but we set this
1188          * here just to be sure.  (No, we don't support e2fsck running
1189          * with some other libext2fs than the one that it was shipped
1190          * with, but just in case....)
1191          */
1192         fs->flags |= EXT2_FLAG_MASTER_SB_ONLY;
1193
1194         if (!(ctx->flags & E2F_FLAG_GOT_DEVSIZE)) {
1195                 __u32 blocksize = EXT2_BLOCK_SIZE(fs->super);
1196                 int need_restart = 0;
1197
1198                 pctx.errcode = ext2fs_get_device_size2(ctx->filesystem_name,
1199                                                        blocksize,
1200                                                        &ctx->num_blocks);
1201                 /*
1202                  * The floppy driver refuses to allow anyone else to
1203                  * open the device if has been opened with O_EXCL;
1204                  * this is unlike other block device drivers in Linux.
1205                  * To handle this, we close the filesystem and then
1206                  * reopen the filesystem after we get the device size.
1207                  */
1208                 if (pctx.errcode == EBUSY) {
1209                         ext2fs_close(fs);
1210                         need_restart++;
1211                         pctx.errcode =
1212                                 ext2fs_get_device_size2(ctx->filesystem_name,
1213                                                         blocksize,
1214                                                         &ctx->num_blocks);
1215                 }
1216                 if (pctx.errcode == EXT2_ET_UNIMPLEMENTED)
1217                         ctx->num_blocks = 0;
1218                 else if (pctx.errcode) {
1219                         fix_problem(ctx, PR_0_GETSIZE_ERROR, &pctx);
1220                         ctx->flags |= E2F_FLAG_ABORT;
1221                         fatal_error(ctx, 0);
1222                 }
1223                 ctx->flags |= E2F_FLAG_GOT_DEVSIZE;
1224                 if (need_restart)
1225                         goto restart;
1226         }
1227
1228         ctx->fs = fs;
1229         fs->priv_data = ctx;
1230         fs->now = ctx->now;
1231         sb = fs->super;
1232         if (sb->s_rev_level > E2FSCK_CURRENT_REV) {
1233                 com_err(ctx->program_name, EXT2_ET_REV_TOO_HIGH,
1234                         _("while trying to open %s"),
1235                         ctx->filesystem_name);
1236         get_newer:
1237                 fatal_error(ctx, _("Get a newer version of e2fsck!"));
1238         }
1239
1240         /*
1241          * Set the device name, which is used whenever we print error
1242          * or informational messages to the user.
1243          */
1244         if (ctx->device_name == 0 &&
1245             (sb->s_volume_name[0] != 0)) {
1246                 ctx->device_name = string_copy(ctx, sb->s_volume_name,
1247                                                sizeof(sb->s_volume_name));
1248         }
1249         if (ctx->device_name == 0)
1250                 ctx->device_name = string_copy(ctx, ctx->filesystem_name, 0);
1251         for (cp = ctx->device_name; *cp; cp++)
1252                 if (isspace(*cp) || *cp == ':')
1253                         *cp = '_';
1254
1255         ehandler_init(fs->io);
1256
1257         if ((ctx->mount_flags & EXT2_MF_MOUNTED) &&
1258             !(sb->s_feature_incompat & EXT3_FEATURE_INCOMPAT_RECOVER))
1259                 goto skip_journal;
1260
1261         /*
1262          * Make sure the ext3 superblock fields are consistent.
1263          */
1264         retval = e2fsck_check_ext3_journal(ctx);
1265         if (retval) {
1266                 com_err(ctx->program_name, retval,
1267                         _("while checking ext3 journal for %s"),
1268                         ctx->device_name);
1269                 fatal_error(ctx, 0);
1270         }
1271
1272         /*
1273          * Check to see if we need to do ext3-style recovery.  If so,
1274          * do it, and then restart the fsck.
1275          */
1276         if (sb->s_feature_incompat & EXT3_FEATURE_INCOMPAT_RECOVER) {
1277                 if (ctx->options & E2F_OPT_READONLY) {
1278                         printf(_("Warning: skipping journal recovery "
1279                                  "because doing a read-only filesystem "
1280                                  "check.\n"));
1281                         io_channel_flush(ctx->fs->io);
1282                 } else {
1283                         if (ctx->flags & E2F_FLAG_RESTARTED) {
1284                                 /*
1285                                  * Whoops, we attempted to run the
1286                                  * journal twice.  This should never
1287                                  * happen, unless the hardware or
1288                                  * device driver is being bogus.
1289                                  */
1290                                 com_err(ctx->program_name, 0,
1291                                         _("unable to set superblock flags on %s\n"), ctx->device_name);
1292                                 fatal_error(ctx, 0);
1293                         }
1294                         retval = e2fsck_run_ext3_journal(ctx);
1295                         if (retval) {
1296                                 com_err(ctx->program_name, retval,
1297                                 _("while recovering ext3 journal of %s"),
1298                                         ctx->device_name);
1299                                 fatal_error(ctx, 0);
1300                         }
1301                         ext2fs_close(ctx->fs);
1302                         ctx->fs = 0;
1303                         ctx->flags |= E2F_FLAG_RESTARTED;
1304                         goto restart;
1305                 }
1306         }
1307
1308 skip_journal:
1309         /*
1310          * Check for compatibility with the feature sets.  We need to
1311          * be more stringent than ext2fs_open().
1312          */
1313         features[0] = sb->s_feature_compat & ~EXT2_LIB_FEATURE_COMPAT_SUPP;
1314         features[1] = sb->s_feature_incompat & ~EXT2_LIB_FEATURE_INCOMPAT_SUPP;
1315         features[2] = (sb->s_feature_ro_compat &
1316                        ~EXT2_LIB_FEATURE_RO_COMPAT_SUPP);
1317 print_unsupp_features:
1318         if (features[0] || features[1] || features[2]) {
1319                 int     i, j;
1320                 __u32   *mask = features, m;
1321
1322                 fprintf(stderr, _("%s has unsupported feature(s):"),
1323                         ctx->filesystem_name);
1324
1325                 for (i=0; i <3; i++,mask++) {
1326                         for (j=0,m=1; j < 32; j++, m<<=1) {
1327                                 if (*mask & m)
1328                                         fprintf(stderr, " %s",
1329                                                 e2p_feature2string(i, m));
1330                         }
1331                 }
1332                 putc('\n', stderr);
1333                 goto get_newer;
1334         }
1335 #ifdef ENABLE_COMPRESSION
1336         if (sb->s_feature_incompat & EXT2_FEATURE_INCOMPAT_COMPRESSION)
1337                 com_err(ctx->program_name, 0,
1338                         _("Warning: compression support is experimental.\n"));
1339 #endif
1340 #ifndef ENABLE_HTREE
1341         if (sb->s_feature_compat & EXT2_FEATURE_COMPAT_DIR_INDEX) {
1342                 com_err(ctx->program_name, 0,
1343                         _("E2fsck not compiled with HTREE support,\n\t"
1344                           "but filesystem %s has HTREE directories.\n"),
1345                         ctx->device_name);
1346                 goto get_newer;
1347         }
1348 #endif
1349
1350         /*
1351          * If the user specified a specific superblock, presumably the
1352          * master superblock has been trashed.  So we mark the
1353          * superblock as dirty, so it can be written out.
1354          */
1355         if (ctx->superblock &&
1356             !(ctx->options & E2F_OPT_READONLY))
1357                 ext2fs_mark_super_dirty(fs);
1358
1359         /*
1360          * Calculate the number of filesystem blocks per pagesize.  If
1361          * fs->blocksize > page_size, set the number of blocks per
1362          * pagesize to 1 to avoid division by zero errors.
1363          */
1364 #ifdef _SC_PAGESIZE
1365         sysval = sysconf(_SC_PAGESIZE);
1366         if (sysval > 0)
1367                 sys_page_size = sysval;
1368 #endif /* _SC_PAGESIZE */
1369         ctx->blocks_per_page = sys_page_size / fs->blocksize;
1370         if (ctx->blocks_per_page == 0)
1371                 ctx->blocks_per_page = 1;
1372
1373         if (ctx->superblock)
1374                 set_latch_flags(PR_LATCH_RELOC, PRL_LATCHED, 0);
1375         ext2fs_mark_valid(fs);
1376         check_super_block(ctx);
1377         if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
1378                 fatal_error(ctx, 0);
1379         check_if_skip(ctx);
1380         check_resize_inode(ctx);
1381         if (bad_blocks_file)
1382                 read_bad_blocks_file(ctx, bad_blocks_file, replace_bad_blocks);
1383         else if (cflag)
1384                 read_bad_blocks_file(ctx, 0, !keep_bad_blocks); /* Test disk */
1385         if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
1386                 fatal_error(ctx, 0);
1387
1388         /*
1389          * Mark the system as valid, 'til proven otherwise
1390          */
1391         ext2fs_mark_valid(fs);
1392
1393         retval = ext2fs_read_bb_inode(fs, &fs->badblocks);
1394         if (retval) {
1395                 com_err(ctx->program_name, retval,
1396                         _("while reading bad blocks inode"));
1397                 preenhalt(ctx);
1398                 printf(_("This doesn't bode well,"
1399                          " but we'll try to go on...\n"));
1400         }
1401
1402         /*
1403          * Save the journal size in megabytes.
1404          * Try and use the journal size from the backup else let e2fsck
1405          * find the default journal size.
1406          */
1407         if (sb->s_jnl_backup_type == EXT3_JNL_BACKUP_BLOCKS)
1408                 journal_size = (sb->s_jnl_blocks[15] << (32 - 20)) |
1409                                (sb->s_jnl_blocks[16] >> 20);
1410         else
1411                 journal_size = -1;
1412
1413         run_result = e2fsck_run(ctx);
1414         e2fsck_clear_progbar(ctx);
1415
1416         if (ctx->flags & E2F_FLAG_JOURNAL_INODE) {
1417                 if (fix_problem(ctx, PR_6_RECREATE_JOURNAL, &pctx)) {
1418                         if (journal_size < 1024)
1419                                 journal_size = ext2fs_default_journal_size(ext2fs_blocks_count(fs->super));
1420                         if (journal_size < 0) {
1421                                 fs->super->s_feature_compat &=
1422                                         ~EXT3_FEATURE_COMPAT_HAS_JOURNAL;
1423                                 fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
1424                                 com_err(ctx->program_name, 0,
1425                                         _("Couldn't determine journal size"));
1426                                 goto no_journal;
1427                         }
1428                         printf(_("Creating journal (%d blocks): "),
1429                                journal_size);
1430                         fflush(stdout);
1431                         retval = ext2fs_add_journal_inode(fs,
1432                                                           journal_size, 0);
1433                         if (retval) {
1434                                 com_err("Error ", retval,
1435                                         _("\n\twhile trying to create journal"));
1436                                 goto no_journal;
1437                         }
1438                         printf(_(" Done.\n"));
1439                         printf(_("\n*** journal has been re-created - "
1440                                        "filesystem is now ext3 again ***\n"));
1441                 }
1442         }
1443 no_journal:
1444
1445         if (run_result == E2F_FLAG_RESTART) {
1446                 printf(_("Restarting e2fsck from the beginning...\n"));
1447                 retval = e2fsck_reset_context(ctx);
1448                 if (retval) {
1449                         com_err(ctx->program_name, retval,
1450                                 _("while resetting context"));
1451                         fatal_error(ctx, 0);
1452                 }
1453                 ext2fs_close(fs);
1454                 goto restart;
1455         }
1456         if (run_result & E2F_FLAG_CANCEL) {
1457                 printf(_("%s: e2fsck canceled.\n"), ctx->device_name ?
1458                        ctx->device_name : ctx->filesystem_name);
1459                 exit_value |= FSCK_CANCELED;
1460         }
1461         if (run_result & E2F_FLAG_ABORT)
1462                 fatal_error(ctx, _("aborted"));
1463         if (check_backup_super_block(ctx)) {
1464                 fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
1465                 ext2fs_mark_super_dirty(fs);
1466         }
1467
1468 #ifdef MTRACE
1469         mtrace_print("Cleanup");
1470 #endif
1471         if (ext2fs_test_changed(fs)) {
1472                 exit_value |= FSCK_NONDESTRUCT;
1473                 if (!(ctx->options & E2F_OPT_PREEN))
1474                     printf(_("\n%s: ***** FILE SYSTEM WAS MODIFIED *****\n"),
1475                                ctx->device_name);
1476                 if (ctx->mount_flags & EXT2_MF_ISROOT) {
1477                         printf(_("%s: ***** REBOOT LINUX *****\n"),
1478                                ctx->device_name);
1479                         exit_value |= FSCK_REBOOT;
1480                 }
1481         }
1482         if (!ext2fs_test_valid(fs) ||
1483             ((exit_value & FSCK_CANCELED) &&
1484              (sb->s_state & EXT2_ERROR_FS))) {
1485                 printf(_("\n%s: ********** WARNING: Filesystem still has "
1486                          "errors **********\n\n"), ctx->device_name);
1487                 exit_value |= FSCK_UNCORRECTED;
1488                 exit_value &= ~FSCK_NONDESTRUCT;
1489         }
1490         if (exit_value & FSCK_CANCELED) {
1491                 int     allow_cancellation;
1492
1493                 profile_get_boolean(ctx->profile, "options",
1494                                     "allow_cancellation", 0, 0,
1495                                     &allow_cancellation);
1496                 exit_value &= ~FSCK_NONDESTRUCT;
1497                 if (allow_cancellation && ext2fs_test_valid(fs) &&
1498                     (sb->s_state & EXT2_VALID_FS) &&
1499                     !(sb->s_state & EXT2_ERROR_FS))
1500                         exit_value = 0;
1501         } else {
1502                 show_stats(ctx);
1503                 if (!(ctx->options & E2F_OPT_READONLY)) {
1504                         if (ext2fs_test_valid(fs)) {
1505                                 if (!(sb->s_state & EXT2_VALID_FS))
1506                                         exit_value |= FSCK_NONDESTRUCT;
1507                                 sb->s_state = EXT2_VALID_FS;
1508                         } else
1509                                 sb->s_state &= ~EXT2_VALID_FS;
1510                         sb->s_mnt_count = 0;
1511                         if (!(ctx->flags & E2F_FLAG_TIME_INSANE))
1512                                 sb->s_lastcheck = ctx->now;
1513                         memset(((char *) sb) + EXT4_S_ERR_START, 0,
1514                                EXT4_S_ERR_LEN);
1515                         ext2fs_mark_super_dirty(fs);
1516                 }
1517         }
1518
1519         if ((run_result & E2F_FLAG_CANCEL) == 0 &&
1520             sb->s_feature_ro_compat & EXT4_FEATURE_RO_COMPAT_GDT_CSUM &&
1521             !(ctx->options & E2F_OPT_READONLY)) {
1522                 retval = ext2fs_set_gdt_csum(ctx->fs);
1523                 if (retval) {
1524                         com_err(ctx->program_name, retval,
1525                                 _("while setting block group checksum info"));
1526                         fatal_error(ctx, 0);
1527                 }
1528         }
1529
1530         e2fsck_write_bitmaps(ctx);
1531         io_channel_flush(ctx->fs->io);
1532         print_resource_track(ctx, NULL, &ctx->global_rtrack, ctx->fs->io);
1533
1534         ext2fs_close(fs);
1535         ctx->fs = NULL;
1536         free(ctx->journal_name);
1537
1538         e2fsck_free_context(ctx);
1539         remove_error_table(&et_ext2_error_table);
1540         remove_error_table(&et_prof_error_table);
1541         return exit_value;
1542 }