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