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