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