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