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