Whamcloud - gitweb
e2fsck: copy context when using multi-thread fsck
[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 "config.h"
15 #include <stdio.h>
16 #ifdef HAVE_STDLIB_H
17 #include <stdlib.h>
18 #endif
19 #include <string.h>
20 #include <fcntl.h>
21 #include <ctype.h>
22 #include <time.h>
23 #ifdef HAVE_SIGNAL_H
24 #include <signal.h>
25 #endif
26 #ifdef HAVE_GETOPT_H
27 #include <getopt.h>
28 #else
29 extern char *optarg;
30 extern int optind;
31 #endif
32 #include <unistd.h>
33 #ifdef HAVE_ERRNO_H
34 #include <errno.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 #ifdef HAVE_SYS_TYPES_H
43 #include <sys/types.h>
44 #endif
45 #ifdef HAVE_DIRENT_H
46 #include <dirent.h>
47 #endif
48 #include <libgen.h>
49
50 #include "e2p/e2p.h"
51 #include "et/com_err.h"
52 #include "e2p/e2p.h"
53 #include "uuid/uuid.h"
54 #include "support/plausible.h"
55 #include "support/devname.h"
56 #include "e2fsck.h"
57 #include "problem.h"
58 #include "jfs_user.h"
59 #include "../version.h"
60
61 /* Command line options */
62 static int cflag;               /* check disk */
63 static int show_version_only;
64 static int verbose;
65
66 static int replace_bad_blocks;
67 static int keep_bad_blocks;
68 static char *bad_blocks_file;
69
70 e2fsck_t e2fsck_global_ctx;     /* Try your very best not to use this! */
71
72 #ifdef CONFIG_JBD_DEBUG         /* Enabled by configure --enable-jbd-debug */
73 int journal_enable_debug = -1;
74 #endif
75
76 static void usage(e2fsck_t ctx)
77 {
78         fprintf(stderr,
79                 _("Usage: %s [-pamnyrcdfktvDFV] [-b superblock] [-B blocksize]\n"
80                 "\t\t[-l|-L bad_blocks_file] [-C fd] [-j external_journal]\n"
81                 "\t\t[-E extended-options] [-z undo_file] device\n"),
82                 ctx->program_name ? ctx->program_name : "e2fsck");
83
84         fprintf(stderr, "%s", _("\nEmergency help:\n"
85                 " -p                   Automatic repair (no questions)\n"
86                 " -m                   multiple threads to speedup fsck\n"
87                 " -n                   Make no changes to the filesystem\n"
88                 " -y                   Assume \"yes\" to all questions\n"
89                 " -c                   Check for bad blocks and add them to the badblock list\n"
90                 " -f                   Force checking even if filesystem is marked clean\n"));
91         fprintf(stderr, "%s", _(""
92                 " -v                   Be verbose\n"
93                 " -b superblock        Use alternative superblock\n"
94                 " -B blocksize         Force blocksize when looking for superblock\n"
95                 " -j external_journal  Set location of the external journal\n"
96                 " -l bad_blocks_file   Add to badblocks list\n"
97                 " -L bad_blocks_file   Set badblocks list\n"
98                 " -z undo_file         Create an undo file\n"
99                 ));
100
101         exit(FSCK_USAGE);
102 }
103
104 static void show_stats(e2fsck_t ctx)
105 {
106         ext2_filsys fs = ctx->fs;
107         ext2_ino_t inodes, inodes_used;
108         blk64_t blocks, blocks_used;
109         unsigned int dir_links;
110         unsigned int num_files, num_links;
111         __u32 *mask, m;
112         int frag_percent_file = 0, frag_percent_dir = 0, frag_percent_total = 0;
113         int i, j, printed = 0;
114
115         dir_links = 2 * ctx->fs_directory_count - 1;
116         num_files = ctx->fs_total_count - dir_links;
117         num_links = ctx->fs_links_count - dir_links;
118         inodes = fs->super->s_inodes_count;
119         inodes_used = (fs->super->s_inodes_count -
120                        fs->super->s_free_inodes_count);
121         blocks = ext2fs_blocks_count(fs->super);
122         blocks_used = (ext2fs_blocks_count(fs->super) -
123                        ext2fs_free_blocks_count(fs->super));
124
125         if (inodes_used > 0) {
126                 frag_percent_file = (10000 * ctx->fs_fragmented) / inodes_used;
127                 frag_percent_file = (frag_percent_file + 5) / 10;
128
129                 frag_percent_dir = (10000 * ctx->fs_fragmented_dir) / inodes_used;
130                 frag_percent_dir = (frag_percent_dir + 5) / 10;
131
132                 frag_percent_total = ((10000 * (ctx->fs_fragmented +
133                                                 ctx->fs_fragmented_dir))
134                                       / inodes_used);
135                 frag_percent_total = (frag_percent_total + 5) / 10;
136         }
137
138         if (!verbose) {
139                 log_out(ctx, _("%s: %u/%u files (%0d.%d%% non-contiguous), "
140                                "%llu/%llu blocks\n"),
141                         ctx->device_name, inodes_used, inodes,
142                         frag_percent_total / 10, frag_percent_total % 10,
143                         (unsigned long long) blocks_used,
144                         (unsigned long long) blocks);
145                 return;
146         }
147         profile_get_boolean(ctx->profile, "options", "report_features", 0, 0,
148                             &i);
149         if (verbose && i) {
150                 log_out(ctx, "\nFilesystem features:");
151                 mask = &ctx->fs->super->s_feature_compat;
152                 for (i = 0; i < 3; i++, mask++) {
153                         for (j = 0, m = 1; j < 32; j++, m <<= 1) {
154                                 if (*mask & m) {
155                                         log_out(ctx, " %s",
156                                                 e2p_feature2string(i, m));
157                                         printed++;
158                                 }
159                         }
160                 }
161                 if (printed == 0)
162                         log_out(ctx, " (none)");
163                 log_out(ctx, "\n");
164         }
165
166         log_out(ctx, P_("\n%12u inode used (%2.2f%%, out of %u)\n",
167                         "\n%12u inodes used (%2.2f%%, out of %u)\n",
168                         inodes_used), inodes_used,
169                 100.0 * inodes_used / inodes, inodes);
170         log_out(ctx, P_("%12u non-contiguous file (%0d.%d%%)\n",
171                         "%12u non-contiguous files (%0d.%d%%)\n",
172                         ctx->fs_fragmented),
173                 ctx->fs_fragmented, frag_percent_file / 10,
174                 frag_percent_file % 10);
175         log_out(ctx, P_("%12u non-contiguous directory (%0d.%d%%)\n",
176                         "%12u non-contiguous directories (%0d.%d%%)\n",
177                         ctx->fs_fragmented_dir),
178                 ctx->fs_fragmented_dir, frag_percent_dir / 10,
179                 frag_percent_dir % 10);
180         log_out(ctx, _("             # of inodes with ind/dind/tind blocks: "
181                        "%u/%u/%u\n"),
182                 ctx->fs_ind_count, ctx->fs_dind_count, ctx->fs_tind_count);
183
184         for (j=MAX_EXTENT_DEPTH_COUNT-1; j >=0; j--)
185                 if (ctx->extent_depth_count[j])
186                         break;
187         if (++j) {
188                 log_out(ctx, "%s", _("             Extent depth histogram: "));
189                 for (i=0; i < j; i++) {
190                         if (i)
191                                 fputc('/', stdout);
192                         log_out(ctx, "%u", ctx->extent_depth_count[i]);
193                 }
194                 log_out(ctx, "\n");
195         }
196
197         log_out(ctx, P_("%12llu block used (%2.2f%%, out of %llu)\n",
198                         "%12llu blocks used (%2.2f%%, out of %llu)\n",
199                    blocks_used),
200                 (unsigned long long) blocks_used, 100.0 * blocks_used / blocks,
201                 (unsigned long long) blocks);
202         log_out(ctx, P_("%12u bad block\n", "%12u bad blocks\n",
203                         ctx->fs_badblocks_count), ctx->fs_badblocks_count);
204         log_out(ctx, P_("%12u large file\n", "%12u large files\n",
205                         ctx->large_files), ctx->large_files);
206         log_out(ctx, P_("\n%12u regular file\n", "\n%12u regular files\n",
207                         ctx->fs_regular_count), ctx->fs_regular_count);
208         log_out(ctx, P_("%12u directory\n", "%12u directories\n",
209                         ctx->fs_directory_count), ctx->fs_directory_count);
210         log_out(ctx, P_("%12u character device file\n",
211                         "%12u character device files\n", ctx->fs_chardev_count),
212                 ctx->fs_chardev_count);
213         log_out(ctx, P_("%12u block device file\n", "%12u block device files\n",
214                         ctx->fs_blockdev_count), ctx->fs_blockdev_count);
215         log_out(ctx, P_("%12u fifo\n", "%12u fifos\n", ctx->fs_fifo_count),
216                 ctx->fs_fifo_count);
217         log_out(ctx, P_("%12u link\n", "%12u links\n", num_links),
218                 ctx->fs_links_count - dir_links);
219         log_out(ctx, P_("%12u symbolic link", "%12u symbolic links",
220                         ctx->fs_symlinks_count), ctx->fs_symlinks_count);
221         log_out(ctx, P_(" (%u fast symbolic link)\n",
222                         " (%u fast symbolic links)\n",
223                         ctx->fs_fast_symlinks_count),
224                 ctx->fs_fast_symlinks_count);
225         log_out(ctx, P_("%12u socket\n", "%12u sockets\n",
226                         ctx->fs_sockets_count),
227                 ctx->fs_sockets_count);
228         log_out(ctx, "------------\n");
229         log_out(ctx, P_("%12u file\n", "%12u files\n", num_files),
230                 num_files);
231 }
232
233 static void check_mount(e2fsck_t ctx)
234 {
235         errcode_t       retval;
236         int             cont;
237
238         retval = ext2fs_check_if_mounted(ctx->filesystem_name,
239                                          &ctx->mount_flags);
240         if (retval) {
241                 com_err("ext2fs_check_if_mount", retval,
242                         _("while determining whether %s is mounted."),
243                         ctx->filesystem_name);
244                 return;
245         }
246
247         /*
248          * If the filesystem isn't mounted, or it's the root
249          * filesystem and it's mounted read-only, and we're not doing
250          * a read/write check, then everything's fine.
251          */
252         if ((!(ctx->mount_flags & (EXT2_MF_MOUNTED | EXT2_MF_BUSY))) ||
253             ((ctx->mount_flags & EXT2_MF_ISROOT) &&
254              (ctx->mount_flags & EXT2_MF_READONLY) &&
255              !(ctx->options & E2F_OPT_WRITECHECK)))
256                 return;
257
258         if (((ctx->options & E2F_OPT_READONLY) ||
259              ((ctx->options & E2F_OPT_FORCE) &&
260               (ctx->mount_flags & EXT2_MF_READONLY))) &&
261             !(ctx->options & E2F_OPT_WRITECHECK)) {
262                 if (ctx->mount_flags & EXT2_MF_MOUNTED)
263                         log_out(ctx, _("Warning!  %s is mounted.\n"),
264                                         ctx->filesystem_name);
265                 else
266                         log_out(ctx, _("Warning!  %s is in use.\n"),
267                                         ctx->filesystem_name);
268                 return;
269         }
270
271         if (ctx->mount_flags & EXT2_MF_MOUNTED)
272                 log_out(ctx, _("%s is mounted.\n"), ctx->filesystem_name);
273         else
274                 log_out(ctx, _("%s is in use.\n"), ctx->filesystem_name);
275         if (!ctx->interactive || ctx->mount_flags & EXT2_MF_BUSY)
276                 fatal_error(ctx, _("Cannot continue, aborting.\n\n"));
277         puts("\007\007\007\007");
278         log_out(ctx, "%s", _("\n\nWARNING!!!  "
279                        "The filesystem is mounted.   "
280                        "If you continue you ***WILL***\n"
281                        "cause ***SEVERE*** filesystem damage.\n\n"));
282         puts("\007\007\007");
283         cont = ask_yn(ctx, _("Do you really want to continue"), 0);
284         if (!cont) {
285                 printf("%s", _("check aborted.\n"));
286                 exit (0);
287         }
288         return;
289 }
290
291 static int is_on_batt(void)
292 {
293         FILE    *f;
294         DIR     *d;
295         char    tmp[80], tmp2[80], fname[NAME_MAX+30];
296         unsigned int    acflag;
297         struct dirent*  de;
298
299         f = fopen("/sys/class/power_supply/AC/online", "r");
300         if (f) {
301                 if (fscanf(f, "%u\n", &acflag) == 1) {
302                         fclose(f);
303                         return (!acflag);
304                 }
305                 fclose(f);
306         }
307         f = fopen("/proc/apm", "r");
308         if (f) {
309                 if (fscanf(f, "%79s %79s %79s %x", tmp, tmp, tmp, &acflag) != 4)
310                         acflag = 1;
311                 fclose(f);
312                 return (acflag != 1);
313         }
314         d = opendir("/proc/acpi/ac_adapter");
315         if (d) {
316                 while ((de=readdir(d)) != NULL) {
317                         if (!strncmp(".", de->d_name, 1))
318                                 continue;
319                         snprintf(fname, sizeof(fname),
320                                  "/proc/acpi/ac_adapter/%s/state",
321                                  de->d_name);
322                         f = fopen(fname, "r");
323                         if (!f)
324                                 continue;
325                         if (fscanf(f, "%79s %79s", tmp2, tmp) != 2)
326                                 tmp[0] = 0;
327                         fclose(f);
328                         if (strncmp(tmp, "off-line", 8) == 0) {
329                                 closedir(d);
330                                 return 1;
331                         }
332                 }
333                 closedir(d);
334         }
335         return 0;
336 }
337
338 /*
339  * This routine checks to see if a filesystem can be skipped; if so,
340  * it will exit with E2FSCK_OK.  Under some conditions it will print a
341  * message explaining why a check is being forced.
342  */
343 static void check_if_skip(e2fsck_t ctx)
344 {
345         ext2_filsys fs = ctx->fs;
346         struct problem_context pctx;
347         const char *reason = NULL;
348         unsigned int reason_arg = 0;
349         long next_check;
350         int batt = is_on_batt();
351         int defer_check_on_battery;
352         int broken_system_clock;
353         time_t lastcheck;
354
355         if (ctx->flags & E2F_FLAG_PROBLEMS_FIXED)
356                 return;
357
358         profile_get_boolean(ctx->profile, "options", "broken_system_clock",
359                             0, 0, &broken_system_clock);
360         if (ctx->flags & E2F_FLAG_TIME_INSANE)
361                 broken_system_clock = 1;
362         profile_get_boolean(ctx->profile, "options",
363                             "defer_check_on_battery", 0, 1,
364                             &defer_check_on_battery);
365         if (!defer_check_on_battery)
366                 batt = 0;
367
368         if ((ctx->options & E2F_OPT_FORCE) || bad_blocks_file || cflag)
369                 return;
370
371         if (ctx->options & E2F_OPT_JOURNAL_ONLY)
372                 goto skip;
373
374         lastcheck = fs->super->s_lastcheck;
375         if (lastcheck > ctx->now)
376                 lastcheck -= ctx->time_fudge;
377         if ((fs->super->s_state & EXT2_ERROR_FS) ||
378             !ext2fs_test_valid(fs))
379                 reason = _(" contains a file system with errors");
380         else if ((fs->super->s_state & EXT2_VALID_FS) == 0)
381                 reason = _(" was not cleanly unmounted");
382         else if (check_backup_super_block(ctx))
383                 reason = _(" primary superblock features different from backup");
384         else if ((fs->super->s_max_mnt_count > 0) &&
385                  (fs->super->s_mnt_count >=
386                   (unsigned) fs->super->s_max_mnt_count)) {
387                 reason = _(" has been mounted %u times without being checked");
388                 reason_arg = fs->super->s_mnt_count;
389                 if (batt && (fs->super->s_mnt_count <
390                              (unsigned) fs->super->s_max_mnt_count*2))
391                         reason = 0;
392         } else if (!broken_system_clock && fs->super->s_checkinterval &&
393                    (ctx->now < lastcheck)) {
394                 reason = _(" has filesystem last checked time in the future");
395                 if (batt)
396                         reason = 0;
397         } else if (!broken_system_clock && fs->super->s_checkinterval &&
398                    ((ctx->now - lastcheck) >=
399                     ((time_t) fs->super->s_checkinterval))) {
400                 reason = _(" has gone %u days without being checked");
401                 reason_arg = (ctx->now - fs->super->s_lastcheck)/(3600*24);
402                 if (batt && ((ctx->now - fs->super->s_lastcheck) <
403                              fs->super->s_checkinterval*2))
404                         reason = 0;
405         } else if (broken_system_clock && fs->super->s_checkinterval) {
406                 log_out(ctx, "%s: ", ctx->device_name);
407                 log_out(ctx, "%s",
408                         _("ignoring check interval, broken_system_clock set\n"));
409         }
410
411         if (reason) {
412                 log_out(ctx, "%s", ctx->device_name);
413                 log_out(ctx, reason, reason_arg);
414                 log_out(ctx, "%s", _(", check forced.\n"));
415                 return;
416         }
417
418         /*
419          * Update the global counts from the block group counts.  This
420          * is needed since modern kernels don't update the global
421          * counts so as to avoid locking the entire file system.  So
422          * if the filesystem is not unmounted cleanly, the global
423          * counts may not be accurate.  Update them here if we can,
424          * for the benefit of users who might examine the file system
425          * using dumpe2fs.  (This is for cosmetic reasons only.)
426          */
427         clear_problem_context(&pctx);
428         pctx.ino = fs->super->s_free_inodes_count;
429         pctx.ino2 = ctx->free_inodes;
430         if ((pctx.ino != pctx.ino2) &&
431             !(ctx->options & E2F_OPT_READONLY) &&
432             fix_problem(ctx, PR_0_FREE_INODE_COUNT, &pctx)) {
433                 fs->super->s_free_inodes_count = ctx->free_inodes;
434                 ext2fs_mark_super_dirty(fs);
435         }
436         clear_problem_context(&pctx);
437         pctx.blk = ext2fs_free_blocks_count(fs->super);
438         pctx.blk2 = ctx->free_blocks;
439         if ((pctx.blk != pctx.blk2) &&
440             !(ctx->options & E2F_OPT_READONLY) &&
441             fix_problem(ctx, PR_0_FREE_BLOCK_COUNT, &pctx)) {
442                 ext2fs_free_blocks_count_set(fs->super, ctx->free_blocks);
443                 ext2fs_mark_super_dirty(fs);
444         }
445
446         /* Print the summary message when we're skipping a full check */
447         log_out(ctx, _("%s: clean, %u/%u files, %llu/%llu blocks"),
448                 ctx->device_name,
449                 fs->super->s_inodes_count - fs->super->s_free_inodes_count,
450                 fs->super->s_inodes_count,
451                 (unsigned long long) ext2fs_blocks_count(fs->super) -
452                 ext2fs_free_blocks_count(fs->super),
453                 (unsigned long long) ext2fs_blocks_count(fs->super));
454         next_check = 100000;
455         if (fs->super->s_max_mnt_count > 0) {
456                 next_check = fs->super->s_max_mnt_count - fs->super->s_mnt_count;
457                 if (next_check <= 0)
458                         next_check = 1;
459         }
460         if (!broken_system_clock && fs->super->s_checkinterval &&
461             ((ctx->now - fs->super->s_lastcheck) >= fs->super->s_checkinterval))
462                 next_check = 1;
463         if (next_check <= 5) {
464                 if (next_check == 1) {
465                         if (batt)
466                                 log_out(ctx, "%s",
467                                         _(" (check deferred; on battery)"));
468                         else
469                                 log_out(ctx, "%s",
470                                         _(" (check after next mount)"));
471                 } else
472                         log_out(ctx, _(" (check in %ld mounts)"),
473                                 next_check);
474         }
475         log_out(ctx, "\n");
476 skip:
477         ext2fs_close_free(&ctx->fs);
478         e2fsck_free_context(ctx);
479         exit(FSCK_OK);
480 }
481
482 /*
483  * For completion notice
484  */
485 struct percent_tbl {
486         int     max_pass;
487         int     table[32];
488 };
489 static struct percent_tbl e2fsck_tbl = {
490         5, { 0, 70, 90, 92,  95, 100 }
491 };
492 static char bar[128], spaces[128];
493
494 static float calc_percent(struct percent_tbl *tbl, int pass, int curr,
495                           int max)
496 {
497         float   percent;
498
499         if (pass <= 0)
500                 return 0.0;
501         if (pass > tbl->max_pass || max == 0)
502                 return 100.0;
503         percent = ((float) curr) / ((float) max);
504         return ((percent * (tbl->table[pass] - tbl->table[pass-1]))
505                 + tbl->table[pass-1]);
506 }
507
508 void e2fsck_clear_progbar(e2fsck_t ctx)
509 {
510         if (!(ctx->flags & E2F_FLAG_PROG_BAR))
511                 return;
512
513         printf("%s%s\r%s", ctx->start_meta, spaces + (sizeof(spaces) - 80),
514                ctx->stop_meta);
515         fflush(stdout);
516         ctx->flags &= ~E2F_FLAG_PROG_BAR;
517 }
518
519 int e2fsck_simple_progress(e2fsck_t ctx, const char *label, float percent,
520                            unsigned int dpynum)
521 {
522         static const char spinner[] = "\\|/-";
523         int     i;
524         unsigned int    tick;
525         struct timeval  tv;
526         int dpywidth;
527         int fixed_percent;
528
529         if (ctx->flags & E2F_FLAG_PROG_SUPPRESS)
530                 return 0;
531
532         /*
533          * Calculate the new progress position.  If the
534          * percentage hasn't changed, then we skip out right
535          * away.
536          */
537         fixed_percent = (int) ((10 * percent) + 0.5);
538         if (ctx->progress_last_percent == fixed_percent)
539                 return 0;
540         ctx->progress_last_percent = fixed_percent;
541
542         /*
543          * If we've already updated the spinner once within
544          * the last 1/8th of a second, no point doing it
545          * again.
546          */
547         gettimeofday(&tv, NULL);
548         tick = (tv.tv_sec << 3) + (tv.tv_usec / (1000000 / 8));
549         if ((tick == ctx->progress_last_time) &&
550             (fixed_percent != 0) && (fixed_percent != 1000))
551                 return 0;
552         ctx->progress_last_time = tick;
553
554         /*
555          * Advance the spinner, and note that the progress bar
556          * will be on the screen
557          */
558         ctx->progress_pos = (ctx->progress_pos+1) & 3;
559         ctx->flags |= E2F_FLAG_PROG_BAR;
560
561         dpywidth = 66 - strlen(label);
562         dpywidth = 8 * (dpywidth / 8);
563         if (dpynum)
564                 dpywidth -= 8;
565
566         i = ((percent * dpywidth) + 50) / 100;
567         printf("%s%s: |%s%s", ctx->start_meta, label,
568                bar + (sizeof(bar) - (i+1)),
569                spaces + (sizeof(spaces) - (dpywidth - i + 1)));
570         if (fixed_percent == 1000)
571                 fputc('|', stdout);
572         else
573                 fputc(spinner[ctx->progress_pos & 3], stdout);
574         printf(" %4.1f%%  ", percent);
575         if (dpynum)
576                 printf("%u\r", dpynum);
577         else
578                 fputs(" \r", stdout);
579         fputs(ctx->stop_meta, stdout);
580
581         if (fixed_percent == 1000)
582                 e2fsck_clear_progbar(ctx);
583         fflush(stdout);
584
585         return 0;
586 }
587
588 static int e2fsck_update_progress(e2fsck_t ctx, int pass,
589                                   unsigned long cur, unsigned long max)
590 {
591         char buf[1024];
592         float percent;
593
594         if (pass == 0)
595                 return 0;
596
597         if (ctx->progress_fd) {
598                 snprintf(buf, sizeof(buf), "%d %lu %lu %s\n",
599                          pass, cur, max, ctx->device_name);
600                 write_all(ctx->progress_fd, buf, strlen(buf));
601         } else {
602                 percent = calc_percent(&e2fsck_tbl, pass, cur, max);
603                 e2fsck_simple_progress(ctx, ctx->device_name,
604                                        percent, 0);
605         }
606         return 0;
607 }
608
609 #define PATH_SET "PATH=/sbin"
610
611 /*
612  * Make sure 0,1,2 file descriptors are open, so that we don't open
613  * the filesystem using the same file descriptor as stdout or stderr.
614  */
615 static void reserve_stdio_fds(void)
616 {
617         int     fd = 0;
618
619         while (fd <= 2) {
620                 fd = open("/dev/null", O_RDWR);
621                 if (fd < 0) {
622                         fprintf(stderr, _("ERROR: Couldn't open "
623                                 "/dev/null (%s)\n"),
624                                 strerror(errno));
625                         return;
626                 }
627         }
628         (void) close(fd);
629 }
630
631 #ifdef HAVE_SIGNAL_H
632 static void signal_progress_on(int sig EXT2FS_ATTR((unused)))
633 {
634         e2fsck_t ctx = e2fsck_global_ctx;
635
636         if (!ctx)
637                 return;
638
639         ctx->progress = e2fsck_update_progress;
640 }
641
642 static void signal_progress_off(int sig EXT2FS_ATTR((unused)))
643 {
644         e2fsck_t ctx = e2fsck_global_ctx;
645
646         if (!ctx)
647                 return;
648
649         e2fsck_clear_progbar(ctx);
650         ctx->progress = 0;
651 }
652
653 static void signal_cancel(int sig EXT2FS_ATTR((unused)))
654 {
655         e2fsck_t ctx = e2fsck_global_ctx;
656
657         if (!ctx)
658                 exit(FSCK_CANCELED);
659
660         ctx->flags |= E2F_FLAG_CANCEL;
661 }
662 #endif
663
664 static void parse_extended_opts(e2fsck_t ctx, const char *opts)
665 {
666         char    *buf, *token, *next, *p, *arg;
667         int     ea_ver;
668         int     extended_usage = 0;
669         unsigned long long reada_kb;
670
671         buf = string_copy(ctx, opts, 0);
672         for (token = buf; token && *token; token = next) {
673                 p = strchr(token, ',');
674                 next = 0;
675                 if (p) {
676                         *p = 0;
677                         next = p+1;
678                 }
679                 arg = strchr(token, '=');
680                 if (arg) {
681                         *arg = 0;
682                         arg++;
683                 }
684                 if (strcmp(token, "ea_ver") == 0) {
685                         if (!arg) {
686                                 extended_usage++;
687                                 continue;
688                         }
689                         ea_ver = strtoul(arg, &p, 0);
690                         if (*p ||
691                             ((ea_ver != 1) && (ea_ver != 2))) {
692                                 fprintf(stderr, "%s",
693                                         _("Invalid EA version.\n"));
694                                 extended_usage++;
695                                 continue;
696                         }
697                         ctx->ext_attr_ver = ea_ver;
698                 } else if (strcmp(token, "readahead_kb") == 0) {
699                         if (!arg) {
700                                 extended_usage++;
701                                 continue;
702                         }
703                         reada_kb = strtoull(arg, &p, 0);
704                         if (*p) {
705                                 fprintf(stderr, "%s",
706                                         _("Invalid readahead buffer size.\n"));
707                                 extended_usage++;
708                                 continue;
709                         }
710                         ctx->readahead_kb = reada_kb;
711                 } else if (strcmp(token, "fragcheck") == 0) {
712                         ctx->options |= E2F_OPT_FRAGCHECK;
713                         continue;
714                 } else if (strcmp(token, "journal_only") == 0) {
715                         if (arg) {
716                                 extended_usage++;
717                                 continue;
718                         }
719                         ctx->options |= E2F_OPT_JOURNAL_ONLY;
720                 } else if (strcmp(token, "discard") == 0) {
721                         ctx->options |= E2F_OPT_DISCARD;
722                         continue;
723                 } else if (strcmp(token, "nodiscard") == 0) {
724                         ctx->options &= ~E2F_OPT_DISCARD;
725                         continue;
726                 } else if (strcmp(token, "optimize_extents") == 0) {
727                         ctx->options &= ~E2F_OPT_NOOPT_EXTENTS;
728                         continue;
729                 } else if (strcmp(token, "no_optimize_extents") == 0) {
730                         ctx->options |= E2F_OPT_NOOPT_EXTENTS;
731                         continue;
732                 } else if (strcmp(token, "inode_count_fullmap") == 0) {
733                         ctx->options |= E2F_OPT_ICOUNT_FULLMAP;
734                         continue;
735                 } else if (strcmp(token, "no_inode_count_fullmap") == 0) {
736                         ctx->options &= ~E2F_OPT_ICOUNT_FULLMAP;
737                         continue;
738                 } else if (strcmp(token, "log_filename") == 0) {
739                         if (!arg)
740                                 extended_usage++;
741                         else
742                                 ctx->log_fn = string_copy(ctx, arg, 0);
743                         continue;
744                 } else if (strcmp(token, "problem_log") == 0) {
745                         if (!arg)
746                                 extended_usage++;
747                         else
748                                 ctx->problem_log_fn = string_copy(ctx, arg, 0);
749                         continue;
750                 } else if (strcmp(token, "bmap2extent") == 0) {
751                         ctx->options |= E2F_OPT_CONVERT_BMAP;
752                         continue;
753                 } else if (strcmp(token, "fixes_only") == 0) {
754                         ctx->options |= E2F_OPT_FIXES_ONLY;
755                         continue;
756                 } else if (strcmp(token, "unshare_blocks") == 0) {
757                         ctx->options |= E2F_OPT_UNSHARE_BLOCKS;
758                         ctx->options |= E2F_OPT_FORCE;
759                         continue;
760                 } else if (strcmp(token, "check_encoding") == 0) {
761                         ctx->options |= E2F_OPT_CHECK_ENCODING;
762                         continue;
763 #ifdef CONFIG_DEVELOPER_FEATURES
764                 } else if (strcmp(token, "clear_all_uninit_bits") == 0) {
765                         ctx->options |= E2F_OPT_CLEAR_UNINIT;
766                         continue;
767 #endif
768                 } else {
769                         fprintf(stderr, _("Unknown extended option: %s\n"),
770                                 token);
771                         extended_usage++;
772                 }
773         }
774         free(buf);
775
776         if (extended_usage) {
777                 fputs(_("\nExtended options are separated by commas, "
778                        "and may take an argument which\n"
779                        "is set off by an equals ('=') sign.  "
780                        "Valid extended options are:\n\n"), stderr);
781                 fputs(_("\tea_ver=<ea_version (1 or 2)>\n"), stderr);
782                 fputs("\tfragcheck\n", stderr);
783                 fputs("\tjournal_only\n", stderr);
784                 fputs("\tdiscard\n", stderr);
785                 fputs("\tnodiscard\n", stderr);
786                 fputs("\toptimize_extents\n", stderr);
787                 fputs("\tno_optimize_extents\n", stderr);
788                 fputs("\tinode_count_fullmap\n", stderr);
789                 fputs("\tno_inode_count_fullmap\n", stderr);
790                 fputs(_("\treadahead_kb=<buffer size>\n"), stderr);
791                 fputs("\tbmap2extent\n", stderr);
792                 fputs("\tunshare_blocks\n", stderr);
793                 fputs("\tfixes_only\n", stderr);
794                 fputs("\tcheck_encoding\n", stderr);
795                 fputc('\n', stderr);
796                 exit(1);
797         }
798 }
799
800 static void syntax_err_report(const char *filename, long err, int line_num)
801 {
802         fprintf(stderr,
803                 _("Syntax error in e2fsck config file (%s, line #%d)\n\t%s\n"),
804                 filename, line_num, error_message(err));
805         exit(FSCK_ERROR);
806 }
807
808 static const char *config_fn[] = { ROOT_SYSCONFDIR "/e2fsck.conf", 0 };
809
810 static errcode_t PRS(int argc, char *argv[], e2fsck_t *ret_ctx)
811 {
812         int             flush = 0;
813         int             c, fd;
814 #ifdef MTRACE
815         extern void     *mallwatch;
816 #endif
817         e2fsck_t        ctx;
818         errcode_t       retval;
819 #ifdef HAVE_SIGNAL_H
820         struct sigaction        sa;
821 #endif
822         char            *extended_opts = 0;
823         char            *cp;
824         int             res;            /* result of sscanf */
825 #ifdef CONFIG_JBD_DEBUG
826         char            *jbd_debug;
827 #endif
828         unsigned long long phys_mem_kb, blk;
829
830         retval = e2fsck_allocate_context(&ctx);
831         if (retval)
832                 return retval;
833
834         *ret_ctx = ctx;
835         e2fsck_global_ctx = ctx;
836
837         setvbuf(stdout, NULL, _IONBF, BUFSIZ);
838         setvbuf(stderr, NULL, _IONBF, BUFSIZ);
839         if (getenv("E2FSCK_FORCE_INTERACTIVE") || (isatty(0) && isatty(1))) {
840                 ctx->interactive = 1;
841         } else {
842                 ctx->start_meta[0] = '\001';
843                 ctx->stop_meta[0] = '\002';
844         }
845         memset(bar, '=', sizeof(bar)-1);
846         memset(spaces, ' ', sizeof(spaces)-1);
847         add_error_table(&et_ext2_error_table);
848         add_error_table(&et_prof_error_table);
849         blkid_get_cache(&ctx->blkid, NULL);
850
851         if (argc && *argv)
852                 ctx->program_name = *argv;
853         else
854                 usage(NULL);
855
856         phys_mem_kb = get_memory_size() / 1024;
857         ctx->readahead_kb = ~0ULL;
858
859         while ((c = getopt(argc, argv, "pamnyrcC:B:dE:fvtFVM:b:I:j:P:l:L:N:SsDkz:")) != EOF)
860                 switch (c) {
861                 case 'C':
862                         ctx->progress = e2fsck_update_progress;
863                         res = sscanf(optarg, "%d", &ctx->progress_fd);
864                         if (res != 1)
865                                 goto sscanf_err;
866
867                         if (ctx->progress_fd < 0) {
868                                 ctx->progress = 0;
869                                 ctx->progress_fd = ctx->progress_fd * -1;
870                         }
871                         if (!ctx->progress_fd)
872                                 break;
873                         /* Validate the file descriptor to avoid disasters */
874                         fd = dup(ctx->progress_fd);
875                         if (fd < 0) {
876                                 fprintf(stderr,
877                                 _("Error validating file descriptor %d: %s\n"),
878                                         ctx->progress_fd,
879                                         error_message(errno));
880                                 fatal_error(ctx,
881                         _("Invalid completion information file descriptor"));
882                         } else
883                                 close(fd);
884                         break;
885                 case 'D':
886                         ctx->options |= E2F_OPT_COMPRESS_DIRS;
887                         break;
888                 case 'E':
889                         extended_opts = optarg;
890                         break;
891                 case 'p':
892                 case 'a':
893                         if (ctx->options & (E2F_OPT_YES|E2F_OPT_NO)) {
894                         conflict_opt:
895                                 fatal_error(ctx,
896         _("Only one of the options -p/-a, -n or -y may be specified."));
897                         }
898                         ctx->options |= E2F_OPT_PREEN;
899                         break;
900                 case 'm':
901                         ctx->options |= E2F_OPT_MULTITHREAD;
902                         break;
903                 case 'n':
904                         if (ctx->options & (E2F_OPT_YES|E2F_OPT_PREEN))
905                                 goto conflict_opt;
906                         ctx->options |= E2F_OPT_NO;
907                         break;
908                 case 'y':
909                         if (ctx->options & (E2F_OPT_PREEN|E2F_OPT_NO))
910                                 goto conflict_opt;
911                         ctx->options |= E2F_OPT_YES;
912                         break;
913                 case 't':
914 #ifdef RESOURCE_TRACK
915                         if (ctx->options & E2F_OPT_TIME)
916                                 ctx->options |= E2F_OPT_TIME2;
917                         else
918                                 ctx->options |= E2F_OPT_TIME;
919 #else
920                         fprintf(stderr, _("The -t option is not "
921                                 "supported on this version of e2fsck.\n"));
922 #endif
923                         break;
924                 case 'c':
925                         if (cflag++)
926                                 ctx->options |= E2F_OPT_WRITECHECK;
927                         ctx->options |= E2F_OPT_CHECKBLOCKS;
928                         break;
929                 case 'r':
930                         /* What we do by default, anyway! */
931                         break;
932                 case 'b':
933                         res = sscanf(optarg, "%llu", &blk);
934                         ctx->use_superblock = blk;
935                         if (res != 1)
936                                 goto sscanf_err;
937                         ctx->flags |= E2F_FLAG_SB_SPECIFIED;
938                         break;
939                 case 'B':
940                         ctx->blocksize = atoi(optarg);
941                         break;
942                 case 'I':
943                         res = sscanf(optarg, "%d", &ctx->inode_buffer_blocks);
944                         if (res != 1)
945                                 goto sscanf_err;
946                         break;
947                 case 'j':
948                         ctx->journal_name = get_devname(ctx->blkid,
949                                                         optarg, NULL);
950                         if (!ctx->journal_name) {
951                                 com_err(ctx->program_name, 0,
952                                         _("Unable to resolve '%s'"),
953                                         optarg);
954                                 fatal_error(ctx, 0);
955                         }
956                         break;
957                 case 'P':
958                         res = sscanf(optarg, "%d", &ctx->process_inode_size);
959                         if (res != 1)
960                                 goto sscanf_err;
961                         break;
962                 case 'L':
963                         replace_bad_blocks++;
964                         /* fall through */
965                 case 'l':
966                         if (bad_blocks_file)
967                                 free(bad_blocks_file);
968                         bad_blocks_file = string_copy(ctx, optarg, 0);
969                         break;
970                 case 'd':
971                         ctx->options |= E2F_OPT_DEBUG;
972                         break;
973                 case 'f':
974                         ctx->options |= E2F_OPT_FORCE;
975                         break;
976                 case 'F':
977                         flush = 1;
978                         break;
979                 case 'v':
980                         verbose = 1;
981                         break;
982                 case 'V':
983                         show_version_only = 1;
984                         break;
985 #ifdef MTRACE
986                 case 'M':
987                         mallwatch = (void *) strtol(optarg, NULL, 0);
988                         break;
989 #endif
990                 case 'N':
991                         ctx->device_name = string_copy(ctx, optarg, 0);
992                         break;
993                 case 'k':
994                         keep_bad_blocks++;
995                         break;
996                 case 'z':
997                         ctx->undo_file = optarg;
998                         break;
999                 default:
1000                         usage(ctx);
1001                 }
1002         if (show_version_only)
1003                 return 0;
1004         if (optind != argc - 1)
1005                 usage(ctx);
1006         if ((ctx->options & E2F_OPT_NO) &&
1007             (ctx->options & E2F_OPT_COMPRESS_DIRS)) {
1008                 com_err(ctx->program_name, 0, "%s",
1009                         _("The -n and -D options are incompatible."));
1010                 fatal_error(ctx, 0);
1011         }
1012         if ((ctx->options & E2F_OPT_NO) && cflag) {
1013                 com_err(ctx->program_name, 0, "%s",
1014                         _("The -n and -c options are incompatible."));
1015                 fatal_error(ctx, 0);
1016         }
1017         if ((ctx->options & E2F_OPT_NO) && bad_blocks_file) {
1018                 com_err(ctx->program_name, 0, "%s",
1019                         _("The -n and -l/-L options are incompatible."));
1020                 fatal_error(ctx, 0);
1021         }
1022         if (ctx->options & E2F_OPT_MULTITHREAD) {
1023                 if ((ctx->options & (E2F_OPT_YES|E2F_OPT_NO|E2F_OPT_PREEN)) == 0) {
1024                         com_err(ctx->program_name, 0, "%s",
1025                                 _("The -m option should be used together with one of -p/-y/-n options."));
1026                         fatal_error(ctx, 0);
1027                 }
1028                 if (ctx->progress) {
1029                         com_err(ctx->program_name, 0, "%s",
1030                                 _("Only one of the options -C or -m may be specified."));
1031                         fatal_error(ctx, 0);
1032                 }
1033         }
1034         if (ctx->options & E2F_OPT_NO)
1035                 ctx->options |= E2F_OPT_READONLY;
1036
1037         ctx->io_options = strchr(argv[optind], '?');
1038         if (ctx->io_options)
1039                 *ctx->io_options++ = 0;
1040         ctx->filesystem_name = get_devname(ctx->blkid, argv[optind], 0);
1041         if (!ctx->filesystem_name) {
1042                 com_err(ctx->program_name, 0, _("Unable to resolve '%s'"),
1043                         argv[optind]);
1044                 fatal_error(ctx, 0);
1045         }
1046         if (extended_opts)
1047                 parse_extended_opts(ctx, extended_opts);
1048
1049         /* Complain about mutually exclusive rebuilding activities */
1050         if (getenv("E2FSCK_FIXES_ONLY"))
1051                 ctx->options |= E2F_OPT_FIXES_ONLY;
1052         if ((ctx->options & E2F_OPT_COMPRESS_DIRS) &&
1053             (ctx->options & E2F_OPT_FIXES_ONLY)) {
1054                 com_err(ctx->program_name, 0, "%s",
1055                         _("The -D and -E fixes_only options are incompatible."));
1056                 fatal_error(ctx, 0);
1057         }
1058         if ((ctx->options & E2F_OPT_CONVERT_BMAP) &&
1059             (ctx->options & E2F_OPT_FIXES_ONLY)) {
1060                 com_err(ctx->program_name, 0, "%s",
1061                         _("The -E bmap2extent and fixes_only options are incompatible."));
1062                 fatal_error(ctx, 0);
1063         }
1064
1065         if ((cp = getenv("E2FSCK_CONFIG")) != NULL)
1066                 config_fn[0] = cp;
1067         profile_set_syntax_err_cb(syntax_err_report);
1068         profile_init(config_fn, &ctx->profile);
1069
1070         profile_get_boolean(ctx->profile, "options", "report_time", 0, 0,
1071                             &c);
1072         if (c)
1073                 ctx->options |= E2F_OPT_TIME | E2F_OPT_TIME2;
1074         profile_get_boolean(ctx->profile, "options", "report_verbose", 0, 0,
1075                             &c);
1076         if (c)
1077                 verbose = 1;
1078
1079         profile_get_boolean(ctx->profile, "options", "no_optimize_extents",
1080                             0, 0, &c);
1081         if (c)
1082                 ctx->options |= E2F_OPT_NOOPT_EXTENTS;
1083
1084         profile_get_boolean(ctx->profile, "options", "inode_count_fullmap",
1085                             0, 0, &c);
1086         if (c)
1087                 ctx->options |= E2F_OPT_ICOUNT_FULLMAP;
1088
1089         if (ctx->readahead_kb == ~0ULL) {
1090                 profile_get_integer(ctx->profile, "options",
1091                                     "readahead_mem_pct", 0, -1, &c);
1092                 if (c >= 0 && c <= 100)
1093                         ctx->readahead_kb = phys_mem_kb * c / 100;
1094                 profile_get_integer(ctx->profile, "options",
1095                                     "readahead_kb", 0, -1, &c);
1096                 if (c >= 0)
1097                         ctx->readahead_kb = c;
1098                 if (ctx->readahead_kb != ~0ULL &&
1099                     ctx->readahead_kb > phys_mem_kb)
1100                         ctx->readahead_kb = phys_mem_kb;
1101         }
1102
1103         /* Turn off discard in read-only mode */
1104         if ((ctx->options & E2F_OPT_NO) &&
1105             (ctx->options & E2F_OPT_DISCARD))
1106                 ctx->options &= ~E2F_OPT_DISCARD;
1107
1108         if (flush) {
1109                 fd = open(ctx->filesystem_name, O_RDONLY, 0);
1110                 if (fd < 0) {
1111                         com_err("open", errno,
1112                                 _("while opening %s for flushing"),
1113                                 ctx->filesystem_name);
1114                         fatal_error(ctx, 0);
1115                 }
1116                 if ((retval = ext2fs_sync_device(fd, 1))) {
1117                         com_err("ext2fs_sync_device", retval,
1118                                 _("while trying to flush %s"),
1119                                 ctx->filesystem_name);
1120                         fatal_error(ctx, 0);
1121                 }
1122                 close(fd);
1123         }
1124         if (cflag && bad_blocks_file) {
1125                 fprintf(stderr, "%s", _("The -c and the -l/-L options may not "
1126                                         "be both used at the same time.\n"));
1127                 exit(FSCK_USAGE);
1128         }
1129 #ifdef HAVE_SIGNAL_H
1130         /*
1131          * Set up signal action
1132          */
1133         memset(&sa, 0, sizeof(struct sigaction));
1134         sa.sa_handler = signal_cancel;
1135         sigaction(SIGINT, &sa, 0);
1136         sigaction(SIGTERM, &sa, 0);
1137 #ifdef SA_RESTART
1138         sa.sa_flags = SA_RESTART;
1139 #endif
1140         if ((ctx->options & E2F_OPT_MULTITHREAD) == 0) {
1141                 sa.sa_handler = signal_progress_on;
1142                 sigaction(SIGUSR1, &sa, 0);
1143                 sa.sa_handler = signal_progress_off;
1144                 sigaction(SIGUSR2, &sa, 0);
1145         }
1146 #endif
1147
1148         /* Update our PATH to include /sbin if we need to run badblocks  */
1149         if (cflag) {
1150                 char *oldpath = getenv("PATH");
1151                 char *newpath;
1152                 int len = sizeof(PATH_SET) + 1;
1153
1154                 if (oldpath)
1155                         len += strlen(oldpath);
1156
1157                 newpath = malloc(len);
1158                 if (!newpath)
1159                         fatal_error(ctx, "Couldn't malloc() newpath");
1160                 strcpy(newpath, PATH_SET);
1161
1162                 if (oldpath) {
1163                         strcat(newpath, ":");
1164                         strcat(newpath, oldpath);
1165                 }
1166                 putenv(newpath);
1167         }
1168 #ifdef CONFIG_JBD_DEBUG
1169         jbd_debug = getenv("E2FSCK_JBD_DEBUG");
1170         if (jbd_debug) {
1171                 res = sscanf(jbd_debug, "%d", &journal_enable_debug);
1172                 if (res != 1) {
1173                         fprintf(stderr,
1174                                 _("E2FSCK_JBD_DEBUG \"%s\" not an integer\n\n"),
1175                                 jbd_debug);
1176                         exit (1);
1177                 }
1178         }
1179 #endif
1180         return 0;
1181
1182 sscanf_err:
1183         fprintf(stderr, _("\nInvalid non-numeric argument to -%c (\"%s\")\n\n"),
1184                 c, optarg);
1185         exit (1);
1186 }
1187
1188 static errcode_t try_open_fs(e2fsck_t ctx, int flags, io_manager io_ptr,
1189                              ext2_filsys *ret_fs)
1190 {
1191         errcode_t retval;
1192
1193         *ret_fs = NULL;
1194
1195         if (ctx->superblock) {
1196                 unsigned long blocksize = ctx->blocksize;
1197
1198                 if (!blocksize) {
1199                         for (blocksize = EXT2_MIN_BLOCK_SIZE;
1200                              blocksize <= EXT2_MAX_BLOCK_SIZE; blocksize *= 2) {
1201
1202                                 retval = ext2fs_open2(ctx->filesystem_name,
1203                                                       ctx->io_options, flags,
1204                                                       ctx->superblock, blocksize,
1205                                                       unix_io_manager, ret_fs);
1206                                 if (*ret_fs) {
1207                                         ext2fs_free(*ret_fs);
1208                                         *ret_fs = NULL;
1209                                 }
1210                                 if (!retval)
1211                                         break;
1212                         }
1213                         if (retval)
1214                                 return retval;
1215                 }
1216
1217                 retval = ext2fs_open2(ctx->filesystem_name, ctx->io_options,
1218                                       flags, ctx->superblock, blocksize,
1219                                       io_ptr, ret_fs);
1220         } else
1221                 retval = ext2fs_open2(ctx->filesystem_name, ctx->io_options,
1222                                       flags, 0, 0, io_ptr, ret_fs);
1223
1224         if (retval == 0) {
1225                 (*ret_fs)->priv_data = ctx;
1226                 e2fsck_set_bitmap_type(*ret_fs, EXT2FS_BMAP64_RBTREE,
1227                                        "default", NULL);
1228         }
1229         return retval;
1230 }
1231
1232 static const char *my_ver_string = E2FSPROGS_VERSION;
1233 static const char *my_ver_date = E2FSPROGS_DATE;
1234
1235 static errcode_t e2fsck_check_mmp(ext2_filsys fs, e2fsck_t ctx)
1236 {
1237         struct mmp_struct *mmp_s;
1238         unsigned int mmp_check_interval;
1239         errcode_t retval = 0;
1240         struct problem_context pctx;
1241         unsigned int wait_time = 0;
1242
1243         clear_problem_context(&pctx);
1244         if (fs->mmp_buf == NULL) {
1245                 retval = ext2fs_get_mem(fs->blocksize, &fs->mmp_buf);
1246                 if (retval)
1247                         goto check_error;
1248         }
1249
1250         retval = ext2fs_mmp_read(fs, fs->super->s_mmp_block, fs->mmp_buf);
1251         if (retval)
1252                 goto check_error;
1253
1254         mmp_s = fs->mmp_buf;
1255
1256         mmp_check_interval = fs->super->s_mmp_update_interval;
1257         if (mmp_check_interval < EXT4_MMP_MIN_CHECK_INTERVAL)
1258                 mmp_check_interval = EXT4_MMP_MIN_CHECK_INTERVAL;
1259
1260         /*
1261          * If check_interval in MMP block is larger, use that instead of
1262          * check_interval from the superblock.
1263          */
1264         if (mmp_s->mmp_check_interval > mmp_check_interval)
1265                 mmp_check_interval = mmp_s->mmp_check_interval;
1266
1267         wait_time = mmp_check_interval * 2 + 1;
1268
1269         if (mmp_s->mmp_seq == EXT4_MMP_SEQ_CLEAN)
1270                 retval = 0;
1271         else if (mmp_s->mmp_seq == EXT4_MMP_SEQ_FSCK)
1272                 retval = EXT2_ET_MMP_FSCK_ON;
1273         else if (mmp_s->mmp_seq > EXT4_MMP_SEQ_MAX)
1274                 retval = EXT2_ET_MMP_UNKNOWN_SEQ;
1275
1276         if (retval)
1277                 goto check_error;
1278
1279         /* Print warning if e2fsck will wait for more than 20 secs. */
1280         if (verbose || wait_time > EXT4_MMP_MIN_CHECK_INTERVAL * 4) {
1281                 log_out(ctx, _("MMP interval is %u seconds and total wait "
1282                                "time is %u seconds. Please wait...\n"),
1283                         mmp_check_interval, wait_time * 2);
1284         }
1285
1286         return 0;
1287
1288 check_error:
1289
1290         if (retval == EXT2_ET_MMP_BAD_BLOCK) {
1291                 if (fix_problem(ctx, PR_0_MMP_INVALID_BLK, &pctx)) {
1292                         fs->super->s_mmp_block = 0;
1293                         ext2fs_mark_super_dirty(fs);
1294                         retval = 0;
1295                 }
1296         } else if (retval == EXT2_ET_MMP_FAILED) {
1297                 com_err(ctx->program_name, retval, "%s",
1298                         _("while checking MMP block"));
1299                 dump_mmp_msg(fs->mmp_buf, NULL);
1300         } else if (retval == EXT2_ET_MMP_FSCK_ON ||
1301                    retval == EXT2_ET_MMP_UNKNOWN_SEQ) {
1302                 com_err(ctx->program_name, retval, "%s",
1303                         _("while checking MMP block"));
1304                 dump_mmp_msg(fs->mmp_buf,
1305                              _("If you are sure the filesystem is not "
1306                                "in use on any node, run:\n"
1307                                "'tune2fs -f -E clear_mmp %s'\n"),
1308                              ctx->device_name);
1309         } else if (retval == EXT2_ET_MMP_MAGIC_INVALID) {
1310                 if (fix_problem(ctx, PR_0_MMP_INVALID_MAGIC, &pctx)) {
1311                         ext2fs_mmp_clear(fs);
1312                         retval = 0;
1313                 }
1314         } else if (retval == EXT2_ET_MMP_CSUM_INVALID) {
1315                 if (fix_problem(ctx, PR_0_MMP_CSUM_INVALID, &pctx)) {
1316                         ext2fs_mmp_clear(fs);
1317                         retval = 0;
1318                 }
1319         } else
1320                 com_err(ctx->program_name, retval, "%s",
1321                         _("while reading MMP block"));
1322         return retval;
1323 }
1324
1325 static int e2fsck_setup_tdb(e2fsck_t ctx, io_manager *io_ptr)
1326 {
1327         errcode_t retval = ENOMEM;
1328         char *tdb_dir = NULL, *tdb_file = NULL;
1329         char *dev_name, *tmp_name;
1330         int free_tdb_dir = 0;
1331
1332         /* (re)open a specific undo file */
1333         if (ctx->undo_file && ctx->undo_file[0] != 0) {
1334                 retval = set_undo_io_backing_manager(*io_ptr);
1335                 if (retval)
1336                         goto err;
1337                 *io_ptr = undo_io_manager;
1338                 retval = set_undo_io_backup_file(ctx->undo_file);
1339                 if (retval)
1340                         goto err;
1341                 printf(_("Overwriting existing filesystem; this can be undone "
1342                          "using the command:\n"
1343                          "    e2undo %s %s\n\n"),
1344                         ctx->undo_file, ctx->filesystem_name);
1345                 return retval;
1346         }
1347
1348         /*
1349          * Configuration via a conf file would be
1350          * nice
1351          */
1352         tdb_dir = getenv("E2FSPROGS_UNDO_DIR");
1353         if (!tdb_dir) {
1354                 profile_get_string(ctx->profile, "defaults",
1355                                    "undo_dir", 0, "/var/lib/e2fsprogs",
1356                                    &tdb_dir);
1357                 free_tdb_dir = 1;
1358         }
1359
1360         if (!strcmp(tdb_dir, "none") || (tdb_dir[0] == 0) ||
1361             access(tdb_dir, W_OK)) {
1362                 if (free_tdb_dir)
1363                         free(tdb_dir);
1364                 return 0;
1365         }
1366
1367         tmp_name = strdup(ctx->filesystem_name);
1368         if (!tmp_name)
1369                 goto errout;
1370         dev_name = basename(tmp_name);
1371         tdb_file = malloc(strlen(tdb_dir) + 8 + strlen(dev_name) + 7 + 1);
1372         if (!tdb_file) {
1373                 free(tmp_name);
1374                 goto errout;
1375         }
1376         sprintf(tdb_file, "%s/e2fsck-%s.e2undo", tdb_dir, dev_name);
1377         free(tmp_name);
1378
1379         if ((unlink(tdb_file) < 0) && (errno != ENOENT)) {
1380                 retval = errno;
1381                 com_err(ctx->program_name, retval,
1382                         _("while trying to delete %s"), tdb_file);
1383                 goto errout;
1384         }
1385
1386         retval = set_undo_io_backing_manager(*io_ptr);
1387         if (retval)
1388                 goto errout;
1389         *io_ptr = undo_io_manager;
1390         retval = set_undo_io_backup_file(tdb_file);
1391         if (retval)
1392                 goto errout;
1393         printf(_("Overwriting existing filesystem; this can be undone "
1394                  "using the command:\n"
1395                  "    e2undo %s %s\n\n"), tdb_file, ctx->filesystem_name);
1396
1397         if (free_tdb_dir)
1398                 free(tdb_dir);
1399         free(tdb_file);
1400         return 0;
1401
1402 errout:
1403         if (free_tdb_dir)
1404                 free(tdb_dir);
1405         free(tdb_file);
1406 err:
1407         com_err(ctx->program_name, retval, "%s",
1408                 _("while trying to setup undo file\n"));
1409         return retval;
1410 }
1411
1412 int main (int argc, char *argv[])
1413 {
1414         errcode_t       retval = 0, retval2 = 0, orig_retval = 0;
1415         int             exit_value = FSCK_OK;
1416         ext2_filsys     fs = 0;
1417         io_manager      io_ptr;
1418         struct ext2_super_block *sb;
1419         const char      *lib_ver_date;
1420         int             my_ver, lib_ver;
1421         e2fsck_t        ctx;
1422         blk64_t         orig_superblock = ~(blk64_t)0;
1423         struct problem_context pctx;
1424         int flags, run_result, was_changed;
1425         int journal_size;
1426         int sysval, sys_page_size = 4096;
1427         int old_bitmaps;
1428         __u32 features[3];
1429         char *cp;
1430         enum quota_type qtype;
1431         struct ext2fs_journal_params jparams;
1432
1433         clear_problem_context(&pctx);
1434         sigcatcher_setup();
1435 #ifdef MTRACE
1436         mtrace();
1437 #endif
1438 #ifdef MCHECK
1439         mcheck(0);
1440 #endif
1441 #ifdef ENABLE_NLS
1442         setlocale(LC_MESSAGES, "");
1443         setlocale(LC_CTYPE, "");
1444         bindtextdomain(NLS_CAT_NAME, LOCALEDIR);
1445         textdomain(NLS_CAT_NAME);
1446         set_com_err_gettext(gettext);
1447 #endif
1448         my_ver = ext2fs_parse_version_string(my_ver_string);
1449         lib_ver = ext2fs_get_library_version(0, &lib_ver_date);
1450         if (my_ver > lib_ver) {
1451                 fprintf( stderr, "%s",
1452                          _("Error: ext2fs library version out of date!\n"));
1453                 show_version_only++;
1454         }
1455
1456         retval = PRS(argc, argv, &ctx);
1457         if (retval) {
1458                 com_err("e2fsck", retval, "%s",
1459                         _("while trying to initialize program"));
1460                 exit(FSCK_ERROR);
1461         }
1462         reserve_stdio_fds();
1463
1464         ctx->global_ctx = NULL;
1465         set_up_logging(ctx);
1466         if (ctx->logf) {
1467                 int i;
1468
1469                 fputs("E2fsck run: ", ctx->logf);
1470                 for (i = 0; i < argc; i++) {
1471                         if (i)
1472                                 fputc(' ', ctx->logf);
1473                         fputs(argv[i], ctx->logf);
1474                 }
1475                 fputc('\n', ctx->logf);
1476         }
1477         if (ctx->problem_logf) {
1478                 int i;
1479
1480                 fputs("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n",
1481                       ctx->problem_logf);
1482                 fprintf(ctx->problem_logf, "<problem_log time=\"%lu\">\n",
1483                         (unsigned long) ctx->now);
1484                 fprintf(ctx->problem_logf, "<invocation prog=\"%s\"",
1485                         argv[0]);
1486                 for (i = 1; i < argc; i++)
1487                         fprintf(ctx->problem_logf, " arg%d=\"%s\"", i, argv[i]);
1488                 fputs("/>\n", ctx->problem_logf);
1489         }
1490
1491         init_resource_track(&ctx->global_rtrack, NULL);
1492         if (!(ctx->options & E2F_OPT_PREEN) || show_version_only)
1493                 log_err(ctx, "e2fsck %s (%s)\n", my_ver_string,
1494                          my_ver_date);
1495
1496         if (show_version_only) {
1497                 log_err(ctx, _("\tUsing %s, %s\n"),
1498                         error_message(EXT2_ET_BASE), lib_ver_date);
1499                 exit(FSCK_OK);
1500         }
1501
1502         check_mount(ctx);
1503
1504         if (!(ctx->options & E2F_OPT_PREEN) &&
1505             !(ctx->options & E2F_OPT_NO) &&
1506             !(ctx->options & E2F_OPT_YES)) {
1507                 if (!ctx->interactive)
1508                         fatal_error(ctx,
1509                                     _("need terminal for interactive repairs"));
1510         }
1511         ctx->superblock = ctx->use_superblock;
1512
1513         flags = EXT2_FLAG_SKIP_MMP | EXT2_FLAG_THREADS;
1514 restart:
1515 #ifdef CONFIG_TESTIO_DEBUG
1516         if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_BLOCK")) {
1517                 io_ptr = test_io_manager;
1518                 test_io_backing_manager = unix_io_manager;
1519         } else
1520 #endif
1521                 io_ptr = unix_io_manager;
1522         flags |= EXT2_FLAG_NOFREE_ON_ERROR;
1523         profile_get_boolean(ctx->profile, "options", "old_bitmaps", 0, 0,
1524                             &old_bitmaps);
1525         if (!old_bitmaps)
1526                 flags |= EXT2_FLAG_64BITS;
1527         if ((ctx->options & E2F_OPT_READONLY) == 0) {
1528                 flags |= EXT2_FLAG_RW;
1529                 if (!(ctx->mount_flags & EXT2_MF_ISROOT &&
1530                       ctx->mount_flags & EXT2_MF_READONLY))
1531                         flags |= EXT2_FLAG_EXCLUSIVE;
1532                 if ((ctx->mount_flags & EXT2_MF_READONLY) &&
1533                     (ctx->options & E2F_OPT_FORCE))
1534                         flags &= ~EXT2_FLAG_EXCLUSIVE;
1535         }
1536
1537         if (ctx->undo_file) {
1538                 retval = e2fsck_setup_tdb(ctx, &io_ptr);
1539                 if (retval)
1540                         exit(FSCK_ERROR);
1541         }
1542
1543         ctx->openfs_flags = flags;
1544         retval = try_open_fs(ctx, flags, io_ptr, &fs);
1545
1546         if (!ctx->superblock && !(ctx->options & E2F_OPT_PREEN) &&
1547             !(ctx->flags & E2F_FLAG_SB_SPECIFIED) &&
1548             ((retval == EXT2_ET_BAD_MAGIC) ||
1549              (retval == EXT2_ET_SB_CSUM_INVALID) ||
1550              (retval == EXT2_ET_CORRUPT_SUPERBLOCK) ||
1551              ((retval == 0) && (retval2 = ext2fs_check_desc(fs))))) {
1552                 if (retval) {
1553                         pctx.errcode = retval;
1554                         fix_problem(ctx, PR_0_OPEN_FAILED, &pctx);
1555                 }
1556                 if (retval2) {
1557                         pctx.errcode = retval2;
1558                         fix_problem(ctx, PR_0_CHECK_DESC_FAILED, &pctx);
1559                 }
1560                 pctx.errcode = 0;
1561                 if (retval2 == ENOMEM || retval2 == EXT2_ET_NO_MEMORY) {
1562                         retval = retval2;
1563                         goto failure;
1564                 }
1565                 if (fs->flags & EXT2_FLAG_NOFREE_ON_ERROR) {
1566                         ext2fs_free(fs);
1567                         fs = NULL;
1568                 }
1569                 if (!fs || (fs->group_desc_count > 1)) {
1570                         log_out(ctx, _("%s: %s trying backup blocks...\n"),
1571                                 ctx->program_name,
1572                                 retval ? _("Superblock invalid,") :
1573                                 _("Group descriptors look bad..."));
1574                         orig_superblock = ctx->superblock;
1575                         get_backup_sb(ctx, fs, ctx->filesystem_name, io_ptr);
1576                         if (fs)
1577                                 ext2fs_close_free(&fs);
1578                         orig_retval = retval;
1579                         retval = try_open_fs(ctx, flags, io_ptr, &fs);
1580                         if ((orig_retval == 0) && retval != 0) {
1581                                 if (fs)
1582                                         ext2fs_close_free(&fs);
1583                                 log_out(ctx, _("%s: %s while using the "
1584                                                "backup blocks"),
1585                                         ctx->program_name,
1586                                         error_message(retval));
1587                                 log_out(ctx, _("%s: going back to original "
1588                                                "superblock\n"),
1589                                         ctx->program_name);
1590                                 ctx->superblock = orig_superblock;
1591                                 retval = try_open_fs(ctx, flags, io_ptr, &fs);
1592                         }
1593                 }
1594         }
1595         if (((retval == EXT2_ET_UNSUPP_FEATURE) ||
1596              (retval == EXT2_ET_RO_UNSUPP_FEATURE)) &&
1597             fs && fs->super) {
1598                 sb = fs->super;
1599                 features[0] = (sb->s_feature_compat &
1600                                ~EXT2_LIB_FEATURE_COMPAT_SUPP);
1601                 features[1] = (sb->s_feature_incompat &
1602                                ~EXT2_LIB_FEATURE_INCOMPAT_SUPP);
1603                 features[2] = (sb->s_feature_ro_compat &
1604                                ~EXT2_LIB_FEATURE_RO_COMPAT_SUPP);
1605                 if (features[0] || features[1] || features[2])
1606                         goto print_unsupp_features;
1607         }
1608 failure:
1609         if (retval) {
1610                 if (orig_retval)
1611                         retval = orig_retval;
1612                 com_err(ctx->program_name, retval, _("while trying to open %s"),
1613                         ctx->filesystem_name);
1614                 if (retval == EXT2_ET_REV_TOO_HIGH) {
1615                         log_out(ctx, "%s",
1616                                 _("The filesystem revision is apparently "
1617                                   "too high for this version of e2fsck.\n"
1618                                   "(Or the filesystem superblock "
1619                                   "is corrupt)\n\n"));
1620                         fix_problem(ctx, PR_0_SB_CORRUPT, &pctx);
1621                 } else if (retval == EXT2_ET_SHORT_READ)
1622                         log_out(ctx, "%s",
1623                                 _("Could this be a zero-length partition?\n"));
1624                 else if ((retval == EPERM) || (retval == EACCES))
1625                         log_out(ctx, _("You must have %s access to the "
1626                                        "filesystem or be root\n"),
1627                                (ctx->options & E2F_OPT_READONLY) ?
1628                                "r/o" : "r/w");
1629                 else if (retval == ENXIO)
1630                         log_out(ctx, "%s",
1631                                 _("Possibly non-existent or swap device?\n"));
1632                 else if (retval == EBUSY)
1633                         log_out(ctx, "%s", _("Filesystem mounted or opened "
1634                                          "exclusively by another program?\n"));
1635                 else if (retval == ENOENT)
1636                         log_out(ctx, "%s",
1637                                 _("Possibly non-existent device?\n"));
1638 #ifdef EROFS
1639                 else if (retval == EROFS)
1640                         log_out(ctx, "%s", _("Disk write-protected; use the "
1641                                              "-n option to do a read-only\n"
1642                                              "check of the device.\n"));
1643 #endif
1644                 else {
1645                         /*
1646                          * Let's try once more will less consistency checking
1647                          * so that we are able to recover from more errors
1648                          * (e.g. some tool messing up some value in the sb).
1649                          */
1650                         if (((retval == EXT2_ET_CORRUPT_SUPERBLOCK) ||
1651                              (retval == EXT2_ET_BAD_DESC_SIZE)) &&
1652                             !(flags & EXT2_FLAG_IGNORE_SB_ERRORS)) {
1653                                 if (fs)
1654                                         ext2fs_close_free(&fs);
1655                                 log_out(ctx, _("%s: Trying to load superblock "
1656                                         "despite errors...\n"),
1657                                         ctx->program_name);
1658                                 flags |= EXT2_FLAG_IGNORE_SB_ERRORS;
1659                                 /*
1660                                  * If we tried backup sb, revert to the
1661                                  * original one now.
1662                                  */
1663                                 if (orig_superblock != ~(blk64_t)0)
1664                                         ctx->superblock = orig_superblock;
1665                                 goto restart;
1666                         }
1667                         fix_problem(ctx, PR_0_SB_CORRUPT, &pctx);
1668                         if (retval == EXT2_ET_BAD_MAGIC)
1669                                 check_plausibility(ctx->filesystem_name,
1670                                                    CHECK_FS_EXIST, NULL);
1671                 }
1672                 fatal_error(ctx, 0);
1673         }
1674         /*
1675          * We only update the master superblock because (a) paranoia;
1676          * we don't want to corrupt the backup superblocks, and (b) we
1677          * don't need to update the mount count and last checked
1678          * fields in the backup superblock (the kernel doesn't update
1679          * the backup superblocks anyway).  With newer versions of the
1680          * library this flag is set by ext2fs_open2(), but we set this
1681          * here just to be sure.  (No, we don't support e2fsck running
1682          * with some other libext2fs than the one that it was shipped
1683          * with, but just in case....)
1684          */
1685         fs->flags |= EXT2_FLAG_MASTER_SB_ONLY;
1686
1687         if (!(ctx->flags & E2F_FLAG_GOT_DEVSIZE)) {
1688                 __u32 blocksize = EXT2_BLOCK_SIZE(fs->super);
1689                 int need_restart = 0;
1690
1691                 pctx.errcode = ext2fs_get_device_size2(ctx->filesystem_name,
1692                                                        blocksize,
1693                                                        &ctx->num_blocks);
1694                 /*
1695                  * The floppy driver refuses to allow anyone else to
1696                  * open the device if has been opened with O_EXCL;
1697                  * this is unlike other block device drivers in Linux.
1698                  * To handle this, we close the filesystem and then
1699                  * reopen the filesystem after we get the device size.
1700                  */
1701                 if (pctx.errcode == EBUSY) {
1702                         ext2fs_close_free(&fs);
1703                         need_restart++;
1704                         pctx.errcode =
1705                                 ext2fs_get_device_size2(ctx->filesystem_name,
1706                                                         blocksize,
1707                                                         &ctx->num_blocks);
1708                 }
1709                 if (pctx.errcode == EXT2_ET_UNIMPLEMENTED)
1710                         ctx->num_blocks = 0;
1711                 else if (pctx.errcode) {
1712                         fix_problem(ctx, PR_0_GETSIZE_ERROR, &pctx);
1713                         ctx->flags |= E2F_FLAG_ABORT;
1714                         fatal_error(ctx, 0);
1715                 }
1716                 ctx->flags |= E2F_FLAG_GOT_DEVSIZE;
1717                 if (need_restart)
1718                         goto restart;
1719         }
1720
1721         ctx->fs = fs;
1722         fs->now = ctx->now;
1723         sb = fs->super;
1724
1725         if (sb->s_rev_level > E2FSCK_CURRENT_REV) {
1726                 com_err(ctx->program_name, EXT2_ET_REV_TOO_HIGH,
1727                         _("while trying to open %s"),
1728                         ctx->filesystem_name);
1729         get_newer:
1730                 fatal_error(ctx, _("Get a newer version of e2fsck!"));
1731         }
1732
1733         /*
1734          * Set the device name, which is used whenever we print error
1735          * or informational messages to the user.
1736          */
1737         if (ctx->device_name == 0 && sb->s_volume_name[0])
1738                 ctx->device_name = string_copy(ctx, (char *) sb->s_volume_name,
1739                                                sizeof(sb->s_volume_name));
1740
1741         if (ctx->device_name == 0)
1742                 ctx->device_name = string_copy(ctx, ctx->filesystem_name, 0);
1743         for (cp = ctx->device_name; *cp; cp++)
1744                 if (isspace(*cp) || *cp == ':')
1745                         *cp = '_';
1746
1747         if (ctx->problem_logf) {
1748
1749                 fprintf(ctx->problem_logf, "<filesystem dev=\"%s\"",
1750                         ctx->filesystem_name);
1751                 if (!uuid_is_null(sb->s_uuid)) {
1752                         char buf[48];
1753
1754                         uuid_unparse(sb->s_uuid, buf);
1755                         fprintf(ctx->problem_logf, " uuid=\"%s\"", buf);
1756                 }
1757                 if (sb->s_volume_name[0])
1758                         fprintf(ctx->problem_logf, " label=\"%.*s\"",
1759                                 EXT2_LEN_STR(sb->s_volume_name));
1760
1761                 fputs("/>\n", ctx->problem_logf);
1762         }
1763
1764         ehandler_init(fs->io);
1765
1766         if (ext2fs_has_feature_mmp(fs->super) &&
1767             (flags & EXT2_FLAG_SKIP_MMP)) {
1768                 if (e2fsck_check_mmp(fs, ctx))
1769                         fatal_error(ctx, 0);
1770
1771                 /*
1772                  * Restart in order to reopen fs but this time start mmp.
1773                  */
1774                 ext2fs_close_free(&ctx->fs);
1775                 flags &= ~EXT2_FLAG_SKIP_MMP;
1776                 goto restart;
1777         }
1778
1779         if (ctx->logf)
1780                 fprintf(ctx->logf, "Filesystem UUID: %s\n",
1781                         e2p_uuid2str(sb->s_uuid));
1782
1783         /*
1784          * Make sure the ext3 superblock fields are consistent.
1785          */
1786         if ((ctx->mount_flags & (EXT2_MF_MOUNTED | EXT2_MF_BUSY)) == 0) {
1787                 retval = e2fsck_check_ext3_journal(ctx);
1788                 if (retval) {
1789                         com_err(ctx->program_name, retval,
1790                                 _("while checking journal for %s"),
1791                                 ctx->device_name);
1792                         fatal_error(ctx,
1793                                 _("Cannot proceed with file system check"));
1794                 }
1795         }
1796
1797         /*
1798          * Check to see if we need to do ext3-style recovery.  If so,
1799          * do it, and then restart the fsck.
1800          */
1801         if (ext2fs_has_feature_journal_needs_recovery(sb)) {
1802                 if (ctx->options & E2F_OPT_READONLY) {
1803                         log_out(ctx, "%s",
1804                                 _("Warning: skipping journal recovery because "
1805                                   "doing a read-only filesystem check.\n"));
1806                         io_channel_flush(ctx->fs->io);
1807                 } else {
1808                         if (ctx->flags & E2F_FLAG_RESTARTED) {
1809                                 /*
1810                                  * Whoops, we attempted to run the
1811                                  * journal twice.  This should never
1812                                  * happen, unless the hardware or
1813                                  * device driver is being bogus.
1814                                  */
1815                                 com_err(ctx->program_name, 0,
1816                                         _("unable to set superblock flags "
1817                                           "on %s\n"), ctx->device_name);
1818                                 fatal_error(ctx, 0);
1819                         }
1820                         retval = e2fsck_run_ext3_journal(ctx);
1821                         if (retval == EFSBADCRC) {
1822                                 log_out(ctx, _("Journal checksum error "
1823                                                "found in %s\n"),
1824                                         ctx->device_name);
1825                         } else if (retval == EFSCORRUPTED) {
1826                                 log_out(ctx, _("Journal corrupted in %s\n"),
1827                                         ctx->device_name);
1828                         } else if (retval) {
1829                                 com_err(ctx->program_name, retval,
1830                                 _("while recovering journal of %s"),
1831                                         ctx->device_name);
1832                         }
1833                         ext2fs_close_free(&ctx->fs);
1834                         ctx->flags |= E2F_FLAG_RESTARTED;
1835                         goto restart;
1836                 }
1837         }
1838
1839         /*
1840          * Check for compatibility with the feature sets.  We need to
1841          * be more stringent than ext2fs_open().
1842          */
1843         features[0] = sb->s_feature_compat & ~EXT2_LIB_FEATURE_COMPAT_SUPP;
1844         features[1] = sb->s_feature_incompat & ~EXT2_LIB_FEATURE_INCOMPAT_SUPP;
1845         features[2] = (sb->s_feature_ro_compat &
1846                        ~EXT2_LIB_FEATURE_RO_COMPAT_SUPP);
1847 print_unsupp_features:
1848         if (features[0] || features[1] || features[2]) {
1849                 int     i, j;
1850                 __u32   *mask = features, m;
1851
1852                 log_err(ctx, _("%s has unsupported feature(s):"),
1853                         ctx->filesystem_name);
1854
1855                 for (i=0; i <3; i++,mask++) {
1856                         for (j=0,m=1; j < 32; j++, m<<=1) {
1857                                 if (*mask & m)
1858                                         log_err(ctx, " %s",
1859                                                 e2p_feature2string(i, m));
1860                         }
1861                 }
1862                 log_err(ctx, "\n");
1863                 goto get_newer;
1864         }
1865
1866         if (ext2fs_has_feature_casefold(sb) && !fs->encoding) {
1867                 log_err(ctx, _("%s has unsupported encoding: %0x\n"),
1868                         ctx->filesystem_name, sb->s_encoding);
1869                 goto get_newer;
1870         }
1871
1872         /*
1873          * If the user specified a specific superblock, presumably the
1874          * master superblock has been trashed.  So we mark the
1875          * superblock as dirty, so it can be written out.
1876          */
1877         if (ctx->superblock &&
1878             !(ctx->options & E2F_OPT_READONLY))
1879                 ext2fs_mark_super_dirty(fs);
1880
1881         /*
1882          * Calculate the number of filesystem blocks per pagesize.  If
1883          * fs->blocksize > page_size, set the number of blocks per
1884          * pagesize to 1 to avoid division by zero errors.
1885          */
1886 #ifdef _SC_PAGESIZE
1887         sysval = sysconf(_SC_PAGESIZE);
1888         if (sysval > 0)
1889                 sys_page_size = sysval;
1890 #endif /* _SC_PAGESIZE */
1891         ctx->blocks_per_page = sys_page_size / fs->blocksize;
1892         if (ctx->blocks_per_page == 0)
1893                 ctx->blocks_per_page = 1;
1894
1895         if (ctx->superblock)
1896                 set_latch_flags(PR_LATCH_RELOC, PRL_LATCHED, 0);
1897         ext2fs_mark_valid(fs);
1898         check_super_block(ctx);
1899         if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
1900                 fatal_error(ctx, 0);
1901         check_if_skip(ctx);
1902         check_resize_inode(ctx);
1903         if (bad_blocks_file)
1904                 read_bad_blocks_file(ctx, bad_blocks_file, replace_bad_blocks);
1905         else if (cflag)
1906                 read_bad_blocks_file(ctx, 0, !keep_bad_blocks); /* Test disk */
1907         if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
1908                 fatal_error(ctx, 0);
1909
1910         /*
1911          * Mark the system as valid, 'til proven otherwise
1912          */
1913         ext2fs_mark_valid(fs);
1914
1915         retval = ext2fs_read_bb_inode(fs, &fs->badblocks);
1916         if (retval) {
1917                 log_out(ctx, _("%s: %s while reading bad blocks inode\n"),
1918                         ctx->program_name, error_message(retval));
1919                 preenhalt(ctx);
1920                 log_out(ctx, "%s", _("This doesn't bode well, "
1921                                      "but we'll try to go on...\n"));
1922         }
1923
1924         /*
1925          * Save the journal size in megabytes.
1926          * Try and use the journal size from the backup else let e2fsck
1927          * find the default journal size. If fast commit feature is enabled,
1928          * it is not clear how many of the journal blocks were fast commit
1929          * blocks. So, ignore the size of journal found in backup.
1930          *
1931          * TODO: Add a new backup type that captures fast commit info as
1932          * well.
1933          */
1934         if (sb->s_jnl_backup_type == EXT3_JNL_BACKUP_BLOCKS &&
1935                 !ext2fs_has_feature_fast_commit(sb))
1936                 journal_size = (sb->s_jnl_blocks[15] << (32 - 20)) |
1937                                (sb->s_jnl_blocks[16] >> 20);
1938         else
1939                 journal_size = -1;
1940
1941         if (ext2fs_has_feature_quota(sb)) {
1942                 /* Quotas were enabled. Do quota accounting during fsck. */
1943                 clear_problem_context(&pctx);
1944                 pctx.errcode = quota_init_context(&ctx->qctx, ctx->fs, 0);
1945                 if (pctx.errcode) {
1946                         fix_problem(ctx, PR_0_QUOTA_INIT_CTX, &pctx);
1947                         fatal_error(ctx, 0);
1948                 }
1949         }
1950
1951         run_result = e2fsck_run(ctx);
1952         e2fsck_clear_progbar(ctx);
1953
1954         if (!ctx->invalid_bitmaps &&
1955             (ctx->flags & E2F_FLAG_JOURNAL_INODE)) {
1956                 if (fix_problem(ctx, PR_6_RECREATE_JOURNAL, &pctx)) {
1957                         if (journal_size < 1024) {
1958                                 ext2fs_get_journal_params(&jparams, fs);
1959                         } else {
1960                                 jparams.num_journal_blocks = journal_size;
1961                                 jparams.num_fc_blocks = 0;
1962                         }
1963                         log_out(ctx, _("Creating journal (%d blocks): "),
1964                                jparams.num_journal_blocks);
1965                         fflush(stdout);
1966                         retval = ext2fs_add_journal_inode3(fs, &jparams, ~0ULL, 0);
1967                         if (retval) {
1968                                 log_out(ctx, "%s: while trying to create "
1969                                         "journal\n", error_message(retval));
1970                                 goto no_journal;
1971                         }
1972                         log_out(ctx, "%s", _(" Done.\n"));
1973                         log_out(ctx, "%s",
1974                                 _("\n*** journal has been regenerated ***\n"));
1975                 }
1976         }
1977 no_journal:
1978
1979         if (run_result & E2F_FLAG_ABORT) {
1980                 fatal_error(ctx, _("aborted"));
1981         } else if (run_result & E2F_FLAG_CANCEL) {
1982                 log_out(ctx, _("%s: e2fsck canceled.\n"), ctx->device_name ?
1983                         ctx->device_name : ctx->filesystem_name);
1984                 exit_value |= FSCK_CANCELED;
1985         } else if (ctx->qctx && !ctx->invalid_bitmaps) {
1986                 int needs_writeout;
1987
1988                 for (qtype = 0; qtype < MAXQUOTAS; qtype++) {
1989                         if (*quota_sb_inump(sb, qtype) == 0)
1990                                 continue;
1991                         needs_writeout = 0;
1992                         pctx.num = qtype;
1993                         retval = quota_compare_and_update(ctx->qctx, qtype,
1994                                                           &needs_writeout);
1995                         if ((retval || needs_writeout) &&
1996                             fix_problem(ctx, PR_6_UPDATE_QUOTAS, &pctx)) {
1997                                 pctx.errcode = quota_write_inode(ctx->qctx,
1998                                                                  1 << qtype);
1999                                 if (pctx.errcode)
2000                                         (void) fix_problem(ctx,
2001                                                 PR_6_WRITE_QUOTAS, &pctx);
2002                         }
2003                 }
2004                 quota_release_context(&ctx->qctx);
2005         }
2006
2007         if (run_result == E2F_FLAG_RESTART) {
2008                 log_out(ctx, "%s",
2009                         _("Restarting e2fsck from the beginning...\n"));
2010                 retval = e2fsck_reset_context(ctx);
2011                 if (retval) {
2012                         com_err(ctx->program_name, retval, "%s",
2013                                 _("while resetting context"));
2014                         fatal_error(ctx, 0);
2015                 }
2016                 ext2fs_close_free(&ctx->fs);
2017                 goto restart;
2018         }
2019
2020 #ifdef MTRACE
2021         mtrace_print("Cleanup");
2022 #endif
2023         was_changed = ext2fs_test_changed(fs);
2024         if (!(ctx->flags & E2F_FLAG_RUN_RETURN) &&
2025             !(ctx->options & E2F_OPT_READONLY)) {
2026                 if (ext2fs_test_valid(fs)) {
2027                         if (!(sb->s_state & EXT2_VALID_FS))
2028                                 exit_value |= FSCK_NONDESTRUCT;
2029                         sb->s_state = EXT2_VALID_FS;
2030                         if (check_backup_super_block(ctx))
2031                                 fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
2032                 } else
2033                         sb->s_state &= ~EXT2_VALID_FS;
2034                 if (!(ctx->flags & E2F_FLAG_TIME_INSANE))
2035                         sb->s_lastcheck = ctx->now;
2036                 sb->s_mnt_count = 0;
2037                 memset(((char *) sb) + EXT4_S_ERR_START, 0, EXT4_S_ERR_LEN);
2038                 pctx.errcode = ext2fs_set_gdt_csum(ctx->fs);
2039                 if (pctx.errcode)
2040                         fix_problem(ctx, PR_6_SET_BG_CHECKSUM, &pctx);
2041                 ext2fs_mark_super_dirty(fs);
2042         }
2043
2044         if (ext2fs_has_feature_shared_blocks(ctx->fs->super) &&
2045             (ctx->options & E2F_OPT_UNSHARE_BLOCKS) &&
2046             (ctx->options & E2F_OPT_NO))
2047                 /* Don't try to write or flush I/O, we just wanted to know whether or
2048                  * not there were enough free blocks to undo deduplication.
2049                  */
2050                 goto skip_write;
2051
2052         if (!(ctx->options & E2F_OPT_READONLY)) {
2053                 e2fsck_write_bitmaps(ctx);
2054                 if (fs->flags & EXT2_FLAG_DIRTY) {
2055                         pctx.errcode = ext2fs_flush(ctx->fs);
2056                         if (pctx.errcode)
2057                                 fix_problem(ctx, PR_6_FLUSH_FILESYSTEM, &pctx);
2058                 }
2059                 pctx.errcode = io_channel_flush(ctx->fs->io);
2060                 if (pctx.errcode)
2061                         fix_problem(ctx, PR_6_IO_FLUSH, &pctx);
2062         }
2063
2064         if (was_changed) {
2065                 int fs_fixed = (ctx->flags & E2F_FLAG_PROBLEMS_FIXED);
2066
2067                 if (fs_fixed)
2068                         exit_value |= FSCK_NONDESTRUCT;
2069                 if (!(ctx->options & E2F_OPT_PREEN)) {
2070 #if 0   /* Do this later; it breaks too many tests' golden outputs */
2071                         log_out(ctx, fs_fixed ?
2072                                 _("\n%s: ***** FILE SYSTEM ERRORS "
2073                                   "CORRECTED *****\n") :
2074                                 _("%s: File system was modified.\n"),
2075                                 ctx->device_name);
2076 #else
2077                         log_out(ctx,
2078                                 _("\n%s: ***** FILE SYSTEM WAS MODIFIED *****\n"),
2079                                 ctx->device_name);
2080 #endif
2081                 }
2082                 if (ctx->mount_flags & EXT2_MF_ISROOT) {
2083                         log_out(ctx, _("%s: ***** REBOOT SYSTEM *****\n"),
2084                                 ctx->device_name);
2085                         exit_value |= FSCK_REBOOT;
2086                 }
2087         }
2088
2089 skip_write:
2090         if (!ext2fs_test_valid(fs) ||
2091             ((exit_value & FSCK_CANCELED) &&
2092              (sb->s_state & EXT2_ERROR_FS))) {
2093                 log_out(ctx, _("\n%s: ********** WARNING: Filesystem still has "
2094                                "errors **********\n\n"), ctx->device_name);
2095                 exit_value |= FSCK_UNCORRECTED;
2096                 exit_value &= ~FSCK_NONDESTRUCT;
2097         }
2098         if (exit_value & FSCK_CANCELED) {
2099                 int     allow_cancellation;
2100
2101                 profile_get_boolean(ctx->profile, "options",
2102                                     "allow_cancellation", 0, 0,
2103                                     &allow_cancellation);
2104                 exit_value &= ~FSCK_NONDESTRUCT;
2105                 if (allow_cancellation && ext2fs_test_valid(fs) &&
2106                     (sb->s_state & EXT2_VALID_FS) &&
2107                     !(sb->s_state & EXT2_ERROR_FS))
2108                         exit_value = 0;
2109         } else
2110                 show_stats(ctx);
2111
2112         print_resource_track(ctx, NULL, &ctx->global_rtrack, ctx->fs->io);
2113
2114         ext2fs_close_free(&ctx->fs);
2115         free(ctx->journal_name);
2116
2117         if (ctx->logf)
2118                 fprintf(ctx->logf, "Exit status: %d\n", exit_value);
2119         e2fsck_free_context(ctx);
2120         remove_error_table(&et_ext2_error_table);
2121         remove_error_table(&et_prof_error_table);
2122         return exit_value;
2123 }