Whamcloud - gitweb
352d6b7f2aa3c7744aa6b37a2b93c9982f59f68a
[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         set_up_logging(ctx);
1465         if (ctx->logf) {
1466                 int i;
1467
1468                 fputs("E2fsck run: ", ctx->logf);
1469                 for (i = 0; i < argc; i++) {
1470                         if (i)
1471                                 fputc(' ', ctx->logf);
1472                         fputs(argv[i], ctx->logf);
1473                 }
1474                 fputc('\n', ctx->logf);
1475         }
1476         if (ctx->problem_logf) {
1477                 int i;
1478
1479                 fputs("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n",
1480                       ctx->problem_logf);
1481                 fprintf(ctx->problem_logf, "<problem_log time=\"%lu\">\n",
1482                         (unsigned long) ctx->now);
1483                 fprintf(ctx->problem_logf, "<invocation prog=\"%s\"",
1484                         argv[0]);
1485                 for (i = 1; i < argc; i++)
1486                         fprintf(ctx->problem_logf, " arg%d=\"%s\"", i, argv[i]);
1487                 fputs("/>\n", ctx->problem_logf);
1488         }
1489
1490         init_resource_track(&ctx->global_rtrack, NULL);
1491         if (!(ctx->options & E2F_OPT_PREEN) || show_version_only)
1492                 log_err(ctx, "e2fsck %s (%s)\n", my_ver_string,
1493                          my_ver_date);
1494
1495         if (show_version_only) {
1496                 log_err(ctx, _("\tUsing %s, %s\n"),
1497                         error_message(EXT2_ET_BASE), lib_ver_date);
1498                 exit(FSCK_OK);
1499         }
1500
1501         check_mount(ctx);
1502
1503         if (!(ctx->options & E2F_OPT_PREEN) &&
1504             !(ctx->options & E2F_OPT_NO) &&
1505             !(ctx->options & E2F_OPT_YES)) {
1506                 if (!ctx->interactive)
1507                         fatal_error(ctx,
1508                                     _("need terminal for interactive repairs"));
1509         }
1510         ctx->superblock = ctx->use_superblock;
1511
1512         flags = EXT2_FLAG_SKIP_MMP | EXT2_FLAG_THREADS;
1513 restart:
1514 #ifdef CONFIG_TESTIO_DEBUG
1515         if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_BLOCK")) {
1516                 io_ptr = test_io_manager;
1517                 test_io_backing_manager = unix_io_manager;
1518         } else
1519 #endif
1520                 io_ptr = unix_io_manager;
1521         flags |= EXT2_FLAG_NOFREE_ON_ERROR;
1522         profile_get_boolean(ctx->profile, "options", "old_bitmaps", 0, 0,
1523                             &old_bitmaps);
1524         if (!old_bitmaps)
1525                 flags |= EXT2_FLAG_64BITS;
1526         if ((ctx->options & E2F_OPT_READONLY) == 0) {
1527                 flags |= EXT2_FLAG_RW;
1528                 if (!(ctx->mount_flags & EXT2_MF_ISROOT &&
1529                       ctx->mount_flags & EXT2_MF_READONLY))
1530                         flags |= EXT2_FLAG_EXCLUSIVE;
1531                 if ((ctx->mount_flags & EXT2_MF_READONLY) &&
1532                     (ctx->options & E2F_OPT_FORCE))
1533                         flags &= ~EXT2_FLAG_EXCLUSIVE;
1534         }
1535
1536         if (ctx->undo_file) {
1537                 retval = e2fsck_setup_tdb(ctx, &io_ptr);
1538                 if (retval)
1539                         exit(FSCK_ERROR);
1540         }
1541
1542         ctx->openfs_flags = flags;
1543         retval = try_open_fs(ctx, flags, io_ptr, &fs);
1544
1545         if (!ctx->superblock && !(ctx->options & E2F_OPT_PREEN) &&
1546             !(ctx->flags & E2F_FLAG_SB_SPECIFIED) &&
1547             ((retval == EXT2_ET_BAD_MAGIC) ||
1548              (retval == EXT2_ET_SB_CSUM_INVALID) ||
1549              (retval == EXT2_ET_CORRUPT_SUPERBLOCK) ||
1550              ((retval == 0) && (retval2 = ext2fs_check_desc(fs))))) {
1551                 if (retval) {
1552                         pctx.errcode = retval;
1553                         fix_problem(ctx, PR_0_OPEN_FAILED, &pctx);
1554                 }
1555                 if (retval2) {
1556                         pctx.errcode = retval2;
1557                         fix_problem(ctx, PR_0_CHECK_DESC_FAILED, &pctx);
1558                 }
1559                 pctx.errcode = 0;
1560                 if (retval2 == ENOMEM || retval2 == EXT2_ET_NO_MEMORY) {
1561                         retval = retval2;
1562                         goto failure;
1563                 }
1564                 if (fs->flags & EXT2_FLAG_NOFREE_ON_ERROR) {
1565                         ext2fs_free(fs);
1566                         fs = NULL;
1567                 }
1568                 if (!fs || (fs->group_desc_count > 1)) {
1569                         log_out(ctx, _("%s: %s trying backup blocks...\n"),
1570                                 ctx->program_name,
1571                                 retval ? _("Superblock invalid,") :
1572                                 _("Group descriptors look bad..."));
1573                         orig_superblock = ctx->superblock;
1574                         get_backup_sb(ctx, fs, ctx->filesystem_name, io_ptr);
1575                         if (fs)
1576                                 ext2fs_close_free(&fs);
1577                         orig_retval = retval;
1578                         retval = try_open_fs(ctx, flags, io_ptr, &fs);
1579                         if ((orig_retval == 0) && retval != 0) {
1580                                 if (fs)
1581                                         ext2fs_close_free(&fs);
1582                                 log_out(ctx, _("%s: %s while using the "
1583                                                "backup blocks"),
1584                                         ctx->program_name,
1585                                         error_message(retval));
1586                                 log_out(ctx, _("%s: going back to original "
1587                                                "superblock\n"),
1588                                         ctx->program_name);
1589                                 ctx->superblock = orig_superblock;
1590                                 retval = try_open_fs(ctx, flags, io_ptr, &fs);
1591                         }
1592                 }
1593         }
1594         if (((retval == EXT2_ET_UNSUPP_FEATURE) ||
1595              (retval == EXT2_ET_RO_UNSUPP_FEATURE)) &&
1596             fs && fs->super) {
1597                 sb = fs->super;
1598                 features[0] = (sb->s_feature_compat &
1599                                ~EXT2_LIB_FEATURE_COMPAT_SUPP);
1600                 features[1] = (sb->s_feature_incompat &
1601                                ~EXT2_LIB_FEATURE_INCOMPAT_SUPP);
1602                 features[2] = (sb->s_feature_ro_compat &
1603                                ~EXT2_LIB_FEATURE_RO_COMPAT_SUPP);
1604                 if (features[0] || features[1] || features[2])
1605                         goto print_unsupp_features;
1606         }
1607 failure:
1608         if (retval) {
1609                 if (orig_retval)
1610                         retval = orig_retval;
1611                 com_err(ctx->program_name, retval, _("while trying to open %s"),
1612                         ctx->filesystem_name);
1613                 if (retval == EXT2_ET_REV_TOO_HIGH) {
1614                         log_out(ctx, "%s",
1615                                 _("The filesystem revision is apparently "
1616                                   "too high for this version of e2fsck.\n"
1617                                   "(Or the filesystem superblock "
1618                                   "is corrupt)\n\n"));
1619                         fix_problem(ctx, PR_0_SB_CORRUPT, &pctx);
1620                 } else if (retval == EXT2_ET_SHORT_READ)
1621                         log_out(ctx, "%s",
1622                                 _("Could this be a zero-length partition?\n"));
1623                 else if ((retval == EPERM) || (retval == EACCES))
1624                         log_out(ctx, _("You must have %s access to the "
1625                                        "filesystem or be root\n"),
1626                                (ctx->options & E2F_OPT_READONLY) ?
1627                                "r/o" : "r/w");
1628                 else if (retval == ENXIO)
1629                         log_out(ctx, "%s",
1630                                 _("Possibly non-existent or swap device?\n"));
1631                 else if (retval == EBUSY)
1632                         log_out(ctx, "%s", _("Filesystem mounted or opened "
1633                                          "exclusively by another program?\n"));
1634                 else if (retval == ENOENT)
1635                         log_out(ctx, "%s",
1636                                 _("Possibly non-existent device?\n"));
1637 #ifdef EROFS
1638                 else if (retval == EROFS)
1639                         log_out(ctx, "%s", _("Disk write-protected; use the "
1640                                              "-n option to do a read-only\n"
1641                                              "check of the device.\n"));
1642 #endif
1643                 else {
1644                         /*
1645                          * Let's try once more will less consistency checking
1646                          * so that we are able to recover from more errors
1647                          * (e.g. some tool messing up some value in the sb).
1648                          */
1649                         if (((retval == EXT2_ET_CORRUPT_SUPERBLOCK) ||
1650                              (retval == EXT2_ET_BAD_DESC_SIZE)) &&
1651                             !(flags & EXT2_FLAG_IGNORE_SB_ERRORS)) {
1652                                 if (fs)
1653                                         ext2fs_close_free(&fs);
1654                                 log_out(ctx, _("%s: Trying to load superblock "
1655                                         "despite errors...\n"),
1656                                         ctx->program_name);
1657                                 flags |= EXT2_FLAG_IGNORE_SB_ERRORS;
1658                                 /*
1659                                  * If we tried backup sb, revert to the
1660                                  * original one now.
1661                                  */
1662                                 if (orig_superblock != ~(blk64_t)0)
1663                                         ctx->superblock = orig_superblock;
1664                                 goto restart;
1665                         }
1666                         fix_problem(ctx, PR_0_SB_CORRUPT, &pctx);
1667                         if (retval == EXT2_ET_BAD_MAGIC)
1668                                 check_plausibility(ctx->filesystem_name,
1669                                                    CHECK_FS_EXIST, NULL);
1670                 }
1671                 fatal_error(ctx, 0);
1672         }
1673         /*
1674          * We only update the master superblock because (a) paranoia;
1675          * we don't want to corrupt the backup superblocks, and (b) we
1676          * don't need to update the mount count and last checked
1677          * fields in the backup superblock (the kernel doesn't update
1678          * the backup superblocks anyway).  With newer versions of the
1679          * library this flag is set by ext2fs_open2(), but we set this
1680          * here just to be sure.  (No, we don't support e2fsck running
1681          * with some other libext2fs than the one that it was shipped
1682          * with, but just in case....)
1683          */
1684         fs->flags |= EXT2_FLAG_MASTER_SB_ONLY;
1685
1686         if (!(ctx->flags & E2F_FLAG_GOT_DEVSIZE)) {
1687                 __u32 blocksize = EXT2_BLOCK_SIZE(fs->super);
1688                 int need_restart = 0;
1689
1690                 pctx.errcode = ext2fs_get_device_size2(ctx->filesystem_name,
1691                                                        blocksize,
1692                                                        &ctx->num_blocks);
1693                 /*
1694                  * The floppy driver refuses to allow anyone else to
1695                  * open the device if has been opened with O_EXCL;
1696                  * this is unlike other block device drivers in Linux.
1697                  * To handle this, we close the filesystem and then
1698                  * reopen the filesystem after we get the device size.
1699                  */
1700                 if (pctx.errcode == EBUSY) {
1701                         ext2fs_close_free(&fs);
1702                         need_restart++;
1703                         pctx.errcode =
1704                                 ext2fs_get_device_size2(ctx->filesystem_name,
1705                                                         blocksize,
1706                                                         &ctx->num_blocks);
1707                 }
1708                 if (pctx.errcode == EXT2_ET_UNIMPLEMENTED)
1709                         ctx->num_blocks = 0;
1710                 else if (pctx.errcode) {
1711                         fix_problem(ctx, PR_0_GETSIZE_ERROR, &pctx);
1712                         ctx->flags |= E2F_FLAG_ABORT;
1713                         fatal_error(ctx, 0);
1714                 }
1715                 ctx->flags |= E2F_FLAG_GOT_DEVSIZE;
1716                 if (need_restart)
1717                         goto restart;
1718         }
1719
1720         ctx->fs = fs;
1721         fs->now = ctx->now;
1722         sb = fs->super;
1723
1724         if (sb->s_rev_level > E2FSCK_CURRENT_REV) {
1725                 com_err(ctx->program_name, EXT2_ET_REV_TOO_HIGH,
1726                         _("while trying to open %s"),
1727                         ctx->filesystem_name);
1728         get_newer:
1729                 fatal_error(ctx, _("Get a newer version of e2fsck!"));
1730         }
1731
1732         /*
1733          * Set the device name, which is used whenever we print error
1734          * or informational messages to the user.
1735          */
1736         if (ctx->device_name == 0 && sb->s_volume_name[0])
1737                 ctx->device_name = string_copy(ctx, (char *) sb->s_volume_name,
1738                                                sizeof(sb->s_volume_name));
1739
1740         if (ctx->device_name == 0)
1741                 ctx->device_name = string_copy(ctx, ctx->filesystem_name, 0);
1742         for (cp = ctx->device_name; *cp; cp++)
1743                 if (isspace(*cp) || *cp == ':')
1744                         *cp = '_';
1745
1746         if (ctx->problem_logf) {
1747
1748                 fprintf(ctx->problem_logf, "<filesystem dev=\"%s\"",
1749                         ctx->filesystem_name);
1750                 if (!uuid_is_null(sb->s_uuid)) {
1751                         char buf[48];
1752
1753                         uuid_unparse(sb->s_uuid, buf);
1754                         fprintf(ctx->problem_logf, " uuid=\"%s\"", buf);
1755                 }
1756                 if (sb->s_volume_name[0])
1757                         fprintf(ctx->problem_logf, " label=\"%.*s\"",
1758                                 EXT2_LEN_STR(sb->s_volume_name));
1759
1760                 fputs("/>\n", ctx->problem_logf);
1761         }
1762
1763         ehandler_init(fs->io);
1764
1765         if (ext2fs_has_feature_mmp(fs->super) &&
1766             (flags & EXT2_FLAG_SKIP_MMP)) {
1767                 if (e2fsck_check_mmp(fs, ctx))
1768                         fatal_error(ctx, 0);
1769
1770                 /*
1771                  * Restart in order to reopen fs but this time start mmp.
1772                  */
1773                 ext2fs_close_free(&ctx->fs);
1774                 flags &= ~EXT2_FLAG_SKIP_MMP;
1775                 goto restart;
1776         }
1777
1778         if (ctx->logf)
1779                 fprintf(ctx->logf, "Filesystem UUID: %s\n",
1780                         e2p_uuid2str(sb->s_uuid));
1781
1782         /*
1783          * Make sure the ext3 superblock fields are consistent.
1784          */
1785         if ((ctx->mount_flags & (EXT2_MF_MOUNTED | EXT2_MF_BUSY)) == 0) {
1786                 retval = e2fsck_check_ext3_journal(ctx);
1787                 if (retval) {
1788                         com_err(ctx->program_name, retval,
1789                                 _("while checking journal for %s"),
1790                                 ctx->device_name);
1791                         fatal_error(ctx,
1792                                 _("Cannot proceed with file system check"));
1793                 }
1794         }
1795
1796         /*
1797          * Check to see if we need to do ext3-style recovery.  If so,
1798          * do it, and then restart the fsck.
1799          */
1800         if (ext2fs_has_feature_journal_needs_recovery(sb)) {
1801                 if (ctx->options & E2F_OPT_READONLY) {
1802                         log_out(ctx, "%s",
1803                                 _("Warning: skipping journal recovery because "
1804                                   "doing a read-only filesystem check.\n"));
1805                         io_channel_flush(ctx->fs->io);
1806                 } else {
1807                         if (ctx->flags & E2F_FLAG_RESTARTED) {
1808                                 /*
1809                                  * Whoops, we attempted to run the
1810                                  * journal twice.  This should never
1811                                  * happen, unless the hardware or
1812                                  * device driver is being bogus.
1813                                  */
1814                                 com_err(ctx->program_name, 0,
1815                                         _("unable to set superblock flags "
1816                                           "on %s\n"), ctx->device_name);
1817                                 fatal_error(ctx, 0);
1818                         }
1819                         retval = e2fsck_run_ext3_journal(ctx);
1820                         if (retval == EFSBADCRC) {
1821                                 log_out(ctx, _("Journal checksum error "
1822                                                "found in %s\n"),
1823                                         ctx->device_name);
1824                         } else if (retval == EFSCORRUPTED) {
1825                                 log_out(ctx, _("Journal corrupted in %s\n"),
1826                                         ctx->device_name);
1827                         } else if (retval) {
1828                                 com_err(ctx->program_name, retval,
1829                                 _("while recovering journal of %s"),
1830                                         ctx->device_name);
1831                         }
1832                         ext2fs_close_free(&ctx->fs);
1833                         ctx->flags |= E2F_FLAG_RESTARTED;
1834                         goto restart;
1835                 }
1836         }
1837
1838         /*
1839          * Check for compatibility with the feature sets.  We need to
1840          * be more stringent than ext2fs_open().
1841          */
1842         features[0] = sb->s_feature_compat & ~EXT2_LIB_FEATURE_COMPAT_SUPP;
1843         features[1] = sb->s_feature_incompat & ~EXT2_LIB_FEATURE_INCOMPAT_SUPP;
1844         features[2] = (sb->s_feature_ro_compat &
1845                        ~EXT2_LIB_FEATURE_RO_COMPAT_SUPP);
1846 print_unsupp_features:
1847         if (features[0] || features[1] || features[2]) {
1848                 int     i, j;
1849                 __u32   *mask = features, m;
1850
1851                 log_err(ctx, _("%s has unsupported feature(s):"),
1852                         ctx->filesystem_name);
1853
1854                 for (i=0; i <3; i++,mask++) {
1855                         for (j=0,m=1; j < 32; j++, m<<=1) {
1856                                 if (*mask & m)
1857                                         log_err(ctx, " %s",
1858                                                 e2p_feature2string(i, m));
1859                         }
1860                 }
1861                 log_err(ctx, "\n");
1862                 goto get_newer;
1863         }
1864
1865         if (ext2fs_has_feature_casefold(sb) && !fs->encoding) {
1866                 log_err(ctx, _("%s has unsupported encoding: %0x\n"),
1867                         ctx->filesystem_name, sb->s_encoding);
1868                 goto get_newer;
1869         }
1870
1871         /*
1872          * If the user specified a specific superblock, presumably the
1873          * master superblock has been trashed.  So we mark the
1874          * superblock as dirty, so it can be written out.
1875          */
1876         if (ctx->superblock &&
1877             !(ctx->options & E2F_OPT_READONLY))
1878                 ext2fs_mark_super_dirty(fs);
1879
1880         /*
1881          * Calculate the number of filesystem blocks per pagesize.  If
1882          * fs->blocksize > page_size, set the number of blocks per
1883          * pagesize to 1 to avoid division by zero errors.
1884          */
1885 #ifdef _SC_PAGESIZE
1886         sysval = sysconf(_SC_PAGESIZE);
1887         if (sysval > 0)
1888                 sys_page_size = sysval;
1889 #endif /* _SC_PAGESIZE */
1890         ctx->blocks_per_page = sys_page_size / fs->blocksize;
1891         if (ctx->blocks_per_page == 0)
1892                 ctx->blocks_per_page = 1;
1893
1894         if (ctx->superblock)
1895                 set_latch_flags(PR_LATCH_RELOC, PRL_LATCHED, 0);
1896         ext2fs_mark_valid(fs);
1897         check_super_block(ctx);
1898         if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
1899                 fatal_error(ctx, 0);
1900         check_if_skip(ctx);
1901         check_resize_inode(ctx);
1902         if (bad_blocks_file)
1903                 read_bad_blocks_file(ctx, bad_blocks_file, replace_bad_blocks);
1904         else if (cflag)
1905                 read_bad_blocks_file(ctx, 0, !keep_bad_blocks); /* Test disk */
1906         if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
1907                 fatal_error(ctx, 0);
1908
1909         /*
1910          * Mark the system as valid, 'til proven otherwise
1911          */
1912         ext2fs_mark_valid(fs);
1913
1914         retval = ext2fs_read_bb_inode(fs, &fs->badblocks);
1915         if (retval) {
1916                 log_out(ctx, _("%s: %s while reading bad blocks inode\n"),
1917                         ctx->program_name, error_message(retval));
1918                 preenhalt(ctx);
1919                 log_out(ctx, "%s", _("This doesn't bode well, "
1920                                      "but we'll try to go on...\n"));
1921         }
1922
1923         /*
1924          * Save the journal size in megabytes.
1925          * Try and use the journal size from the backup else let e2fsck
1926          * find the default journal size. If fast commit feature is enabled,
1927          * it is not clear how many of the journal blocks were fast commit
1928          * blocks. So, ignore the size of journal found in backup.
1929          *
1930          * TODO: Add a new backup type that captures fast commit info as
1931          * well.
1932          */
1933         if (sb->s_jnl_backup_type == EXT3_JNL_BACKUP_BLOCKS &&
1934                 !ext2fs_has_feature_fast_commit(sb))
1935                 journal_size = (sb->s_jnl_blocks[15] << (32 - 20)) |
1936                                (sb->s_jnl_blocks[16] >> 20);
1937         else
1938                 journal_size = -1;
1939
1940         if (ext2fs_has_feature_quota(sb)) {
1941                 /* Quotas were enabled. Do quota accounting during fsck. */
1942                 clear_problem_context(&pctx);
1943                 pctx.errcode = quota_init_context(&ctx->qctx, ctx->fs, 0);
1944                 if (pctx.errcode) {
1945                         fix_problem(ctx, PR_0_QUOTA_INIT_CTX, &pctx);
1946                         fatal_error(ctx, 0);
1947                 }
1948         }
1949
1950         run_result = e2fsck_run(ctx);
1951         e2fsck_clear_progbar(ctx);
1952
1953         if (!ctx->invalid_bitmaps &&
1954             (ctx->flags & E2F_FLAG_JOURNAL_INODE)) {
1955                 if (fix_problem(ctx, PR_6_RECREATE_JOURNAL, &pctx)) {
1956                         if (journal_size < 1024) {
1957                                 ext2fs_get_journal_params(&jparams, fs);
1958                         } else {
1959                                 jparams.num_journal_blocks = journal_size;
1960                                 jparams.num_fc_blocks = 0;
1961                         }
1962                         log_out(ctx, _("Creating journal (%d blocks): "),
1963                                jparams.num_journal_blocks);
1964                         fflush(stdout);
1965                         retval = ext2fs_add_journal_inode3(fs, &jparams, ~0ULL, 0);
1966                         if (retval) {
1967                                 log_out(ctx, "%s: while trying to create "
1968                                         "journal\n", error_message(retval));
1969                                 goto no_journal;
1970                         }
1971                         log_out(ctx, "%s", _(" Done.\n"));
1972                         log_out(ctx, "%s",
1973                                 _("\n*** journal has been regenerated ***\n"));
1974                 }
1975         }
1976 no_journal:
1977
1978         if (run_result & E2F_FLAG_ABORT) {
1979                 fatal_error(ctx, _("aborted"));
1980         } else if (run_result & E2F_FLAG_CANCEL) {
1981                 log_out(ctx, _("%s: e2fsck canceled.\n"), ctx->device_name ?
1982                         ctx->device_name : ctx->filesystem_name);
1983                 exit_value |= FSCK_CANCELED;
1984         } else if (ctx->qctx && !ctx->invalid_bitmaps) {
1985                 int needs_writeout;
1986
1987                 for (qtype = 0; qtype < MAXQUOTAS; qtype++) {
1988                         if (*quota_sb_inump(sb, qtype) == 0)
1989                                 continue;
1990                         needs_writeout = 0;
1991                         pctx.num = qtype;
1992                         retval = quota_compare_and_update(ctx->qctx, qtype,
1993                                                           &needs_writeout);
1994                         if ((retval || needs_writeout) &&
1995                             fix_problem(ctx, PR_6_UPDATE_QUOTAS, &pctx)) {
1996                                 pctx.errcode = quota_write_inode(ctx->qctx,
1997                                                                  1 << qtype);
1998                                 if (pctx.errcode)
1999                                         (void) fix_problem(ctx,
2000                                                 PR_6_WRITE_QUOTAS, &pctx);
2001                         }
2002                 }
2003                 quota_release_context(&ctx->qctx);
2004         }
2005
2006         if (run_result == E2F_FLAG_RESTART) {
2007                 log_out(ctx, "%s",
2008                         _("Restarting e2fsck from the beginning...\n"));
2009                 retval = e2fsck_reset_context(ctx);
2010                 if (retval) {
2011                         com_err(ctx->program_name, retval, "%s",
2012                                 _("while resetting context"));
2013                         fatal_error(ctx, 0);
2014                 }
2015                 ext2fs_close_free(&ctx->fs);
2016                 goto restart;
2017         }
2018
2019 #ifdef MTRACE
2020         mtrace_print("Cleanup");
2021 #endif
2022         was_changed = ext2fs_test_changed(fs);
2023         if (!(ctx->flags & E2F_FLAG_RUN_RETURN) &&
2024             !(ctx->options & E2F_OPT_READONLY)) {
2025                 if (ext2fs_test_valid(fs)) {
2026                         if (!(sb->s_state & EXT2_VALID_FS))
2027                                 exit_value |= FSCK_NONDESTRUCT;
2028                         sb->s_state = EXT2_VALID_FS;
2029                         if (check_backup_super_block(ctx))
2030                                 fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
2031                 } else
2032                         sb->s_state &= ~EXT2_VALID_FS;
2033                 if (!(ctx->flags & E2F_FLAG_TIME_INSANE))
2034                         sb->s_lastcheck = ctx->now;
2035                 sb->s_mnt_count = 0;
2036                 memset(((char *) sb) + EXT4_S_ERR_START, 0, EXT4_S_ERR_LEN);
2037                 pctx.errcode = ext2fs_set_gdt_csum(ctx->fs);
2038                 if (pctx.errcode)
2039                         fix_problem(ctx, PR_6_SET_BG_CHECKSUM, &pctx);
2040                 ext2fs_mark_super_dirty(fs);
2041         }
2042
2043         if (ext2fs_has_feature_shared_blocks(ctx->fs->super) &&
2044             (ctx->options & E2F_OPT_UNSHARE_BLOCKS) &&
2045             (ctx->options & E2F_OPT_NO))
2046                 /* Don't try to write or flush I/O, we just wanted to know whether or
2047                  * not there were enough free blocks to undo deduplication.
2048                  */
2049                 goto skip_write;
2050
2051         if (!(ctx->options & E2F_OPT_READONLY)) {
2052                 e2fsck_write_bitmaps(ctx);
2053                 if (fs->flags & EXT2_FLAG_DIRTY) {
2054                         pctx.errcode = ext2fs_flush(ctx->fs);
2055                         if (pctx.errcode)
2056                                 fix_problem(ctx, PR_6_FLUSH_FILESYSTEM, &pctx);
2057                 }
2058                 pctx.errcode = io_channel_flush(ctx->fs->io);
2059                 if (pctx.errcode)
2060                         fix_problem(ctx, PR_6_IO_FLUSH, &pctx);
2061         }
2062
2063         if (was_changed) {
2064                 int fs_fixed = (ctx->flags & E2F_FLAG_PROBLEMS_FIXED);
2065
2066                 if (fs_fixed)
2067                         exit_value |= FSCK_NONDESTRUCT;
2068                 if (!(ctx->options & E2F_OPT_PREEN)) {
2069 #if 0   /* Do this later; it breaks too many tests' golden outputs */
2070                         log_out(ctx, fs_fixed ?
2071                                 _("\n%s: ***** FILE SYSTEM ERRORS "
2072                                   "CORRECTED *****\n") :
2073                                 _("%s: File system was modified.\n"),
2074                                 ctx->device_name);
2075 #else
2076                         log_out(ctx,
2077                                 _("\n%s: ***** FILE SYSTEM WAS MODIFIED *****\n"),
2078                                 ctx->device_name);
2079 #endif
2080                 }
2081                 if (ctx->mount_flags & EXT2_MF_ISROOT) {
2082                         log_out(ctx, _("%s: ***** REBOOT SYSTEM *****\n"),
2083                                 ctx->device_name);
2084                         exit_value |= FSCK_REBOOT;
2085                 }
2086         }
2087
2088 skip_write:
2089         if (!ext2fs_test_valid(fs) ||
2090             ((exit_value & FSCK_CANCELED) &&
2091              (sb->s_state & EXT2_ERROR_FS))) {
2092                 log_out(ctx, _("\n%s: ********** WARNING: Filesystem still has "
2093                                "errors **********\n\n"), ctx->device_name);
2094                 exit_value |= FSCK_UNCORRECTED;
2095                 exit_value &= ~FSCK_NONDESTRUCT;
2096         }
2097         if (exit_value & FSCK_CANCELED) {
2098                 int     allow_cancellation;
2099
2100                 profile_get_boolean(ctx->profile, "options",
2101                                     "allow_cancellation", 0, 0,
2102                                     &allow_cancellation);
2103                 exit_value &= ~FSCK_NONDESTRUCT;
2104                 if (allow_cancellation && ext2fs_test_valid(fs) &&
2105                     (sb->s_state & EXT2_VALID_FS) &&
2106                     !(sb->s_state & EXT2_ERROR_FS))
2107                         exit_value = 0;
2108         } else
2109                 show_stats(ctx);
2110
2111         print_resource_track(ctx, NULL, &ctx->global_rtrack, ctx->fs->io);
2112
2113         ext2fs_close_free(&ctx->fs);
2114         free(ctx->journal_name);
2115
2116         if (ctx->logf)
2117                 fprintf(ctx->logf, "Exit status: %d\n", exit_value);
2118         e2fsck_free_context(ctx);
2119         remove_error_table(&et_ext2_error_table);
2120         remove_error_table(&et_prof_error_table);
2121         return exit_value;
2122 }