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