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