Whamcloud - gitweb
c6c088f9440abc1da96d7087af20fcaf16ed9bf5
[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         int inodes, inodes_used, blocks, blocks_used;
102         int dir_links;
103         int num_files, num_links;
104         int frag_percent;
105
106         dir_links = 2 * ctx->fs_directory_count - 1;
107         num_files = ctx->fs_total_count - dir_links;
108         num_links = ctx->fs_links_count - dir_links;
109         inodes = fs->super->s_inodes_count;
110         inodes_used = (fs->super->s_inodes_count -
111                        fs->super->s_free_inodes_count);
112         blocks = fs->super->s_blocks_count;
113         blocks_used = (fs->super->s_blocks_count -
114                        fs->super->s_free_blocks_count);
115
116         frag_percent = (10000 * ctx->fs_fragmented) / inodes_used;
117         frag_percent = (frag_percent + 5) / 10;
118         
119         if (!verbose) {
120                 printf(_("%s: %d/%d files (%0d.%d%% non-contiguous), %d/%d blocks\n"),
121                        ctx->device_name, inodes_used, inodes,
122                        frag_percent / 10, frag_percent % 10,
123                        blocks_used, blocks);
124                 return;
125         }
126         printf (P_("\n%8d inode used (%d%%)\n", "\n%8d inodes used (%d%%)\n",
127                    inodes_used), inodes_used, 100 * inodes_used / inodes);
128         printf (P_("%8d non-contiguous inode (%0d.%d%%)\n",
129                    "%8d non-contiguous inodes (%0d.%d%%)\n",
130                    ctx->fs_fragmented),
131                 ctx->fs_fragmented, frag_percent / 10, frag_percent % 10);
132         printf (_("         # of inodes with ind/dind/tind blocks: %d/%d/%d\n"),
133                 ctx->fs_ind_count, ctx->fs_dind_count, ctx->fs_tind_count);
134         printf (P_("%8d block used (%d%%)\n", "%8d blocks used (%d%%)\n",
135                    blocks_used),
136                 blocks_used, (int) ((long long) 100 * blocks_used / blocks));
137         printf (P_("%8d bad block\n", "%8d bad blocks\n",
138                    ctx->fs_badblocks_count), ctx->fs_badblocks_count);
139         printf (P_("%8d large file\n", "%8d large files\n",
140                    ctx->large_files), ctx->large_files);
141         printf (P_("\n%8d regular file\n", "\n%8d regular files\n",
142                    ctx->fs_regular_count), ctx->fs_regular_count);
143         printf (P_("%8d directory\n", "%8d directories\n",
144                    ctx->fs_directory_count), ctx->fs_directory_count);
145         printf (P_("%8d character device file\n",
146                    "%8d character device files\n", ctx->fs_chardev_count),
147                 ctx->fs_chardev_count);
148         printf (P_("%8d block device file\n", "%8d block device files\n",
149                    ctx->fs_blockdev_count), ctx->fs_blockdev_count);
150         printf (P_("%8d fifo\n", "%8d fifos\n", ctx->fs_fifo_count),
151                 ctx->fs_fifo_count);
152         printf (P_("%8d link\n", "%8d links\n",
153                    ctx->fs_links_count - dir_links),
154                 ctx->fs_links_count - dir_links);
155         printf (P_("%8d symbolic link", "%8d symbolic links",
156                    ctx->fs_symlinks_count), ctx->fs_symlinks_count);
157         printf (P_(" (%d fast symbolic link)\n", " (%d fast symbolic links)\n",
158                    ctx->fs_fast_symlinks_count), ctx->fs_fast_symlinks_count);
159         printf (P_("%8d socket\n", "%8d sockets\n", ctx->fs_sockets_count),
160                 ctx->fs_sockets_count);
161         printf ("--------\n");
162         printf (P_("%8d file\n", "%8d 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         
263         if ((ctx->options & E2F_OPT_FORCE) || bad_blocks_file ||
264             cflag || swapfs)
265                 return;
266         
267         if ((fs->super->s_state & EXT2_ERROR_FS) ||
268             !ext2fs_test_valid(fs))
269                 reason = _(" contains a file system with errors");
270         else if ((fs->super->s_state & EXT2_VALID_FS) == 0)
271                 reason = _(" was not cleanly unmounted");
272         else if ((fs->super->s_max_mnt_count > 0) &&
273                  (fs->super->s_mnt_count >=
274                   (unsigned) fs->super->s_max_mnt_count)) {
275                 reason = _(" has been mounted %u times without being checked");
276                 reason_arg = fs->super->s_mnt_count;
277                 if (batt && (fs->super->s_mnt_count < 
278                              (unsigned) fs->super->s_max_mnt_count*2))
279                         reason = 0;
280         } else if (fs->super->s_checkinterval &&
281                    ((ctx->now - fs->super->s_lastcheck) >= 
282                     fs->super->s_checkinterval)) {
283                 reason = _(" has gone %u days without being checked");
284                 reason_arg = (ctx->now - fs->super->s_lastcheck)/(3600*24);
285                 if (batt && ((ctx->now - fs->super->s_lastcheck) < 
286                              fs->super->s_checkinterval*2))
287                         reason = 0;
288         }
289         if (reason) {
290                 fputs(ctx->device_name, stdout);
291                 printf(reason, reason_arg);
292                 fputs(_(", check forced.\n"), stdout);
293                 return;
294         }
295         printf(_("%s: clean, %d/%d files, %d/%d blocks"), ctx->device_name,
296                fs->super->s_inodes_count - fs->super->s_free_inodes_count,
297                fs->super->s_inodes_count,
298                fs->super->s_blocks_count - fs->super->s_free_blocks_count,
299                fs->super->s_blocks_count);
300         next_check = 100000;
301         if (fs->super->s_max_mnt_count > 0) {
302                 next_check = fs->super->s_max_mnt_count - fs->super->s_mnt_count;
303                 if (next_check <= 0) 
304                         next_check = 1;
305         }
306         if (fs->super->s_checkinterval &&
307             ((ctx->now - fs->super->s_lastcheck) >= fs->super->s_checkinterval))
308                 next_check = 1;
309         if (next_check <= 5) {
310                 if (next_check == 1)
311                         fputs(_(" (check after next mount)"), stdout);
312                 else
313                         printf(_(" (check in %ld mounts)"), next_check);
314         }
315         fputc('\n', stdout);
316         ext2fs_close(fs);
317         ctx->fs = NULL;
318         e2fsck_free_context(ctx);
319         exit(FSCK_OK);
320 }
321
322 /*
323  * For completion notice
324  */
325 struct percent_tbl {
326         int     max_pass;
327         int     table[32];
328 };
329 struct percent_tbl e2fsck_tbl = {
330         5, { 0, 70, 90, 92,  95, 100 }
331 };
332 static char bar[128], spaces[128];
333
334 static float calc_percent(struct percent_tbl *tbl, int pass, int curr,
335                           int max)
336 {
337         float   percent;
338         
339         if (pass <= 0)
340                 return 0.0;
341         if (pass > tbl->max_pass || max == 0)
342                 return 100.0;
343         percent = ((float) curr) / ((float) max);
344         return ((percent * (tbl->table[pass] - tbl->table[pass-1]))
345                 + tbl->table[pass-1]);
346 }
347
348 extern void e2fsck_clear_progbar(e2fsck_t ctx)
349 {
350         if (!(ctx->flags & E2F_FLAG_PROG_BAR))
351                 return;
352         
353         printf("%s%s\r%s", ctx->start_meta, spaces + (sizeof(spaces) - 80),
354                ctx->stop_meta);
355         fflush(stdout);
356         ctx->flags &= ~E2F_FLAG_PROG_BAR;
357 }
358
359 int e2fsck_simple_progress(e2fsck_t ctx, const char *label, float percent,
360                            unsigned int dpynum)
361 {
362         static const char spinner[] = "\\|/-";
363         int     i;
364         unsigned int    tick;
365         struct timeval  tv;
366         int dpywidth;
367         int fixed_percent;
368
369         if (ctx->flags & E2F_FLAG_PROG_SUPPRESS)
370                 return 0;
371
372         /*
373          * Calculate the new progress position.  If the
374          * percentage hasn't changed, then we skip out right
375          * away. 
376          */
377         fixed_percent = (int) ((10 * percent) + 0.5);
378         if (ctx->progress_last_percent == fixed_percent)
379                 return 0;
380         ctx->progress_last_percent = fixed_percent;
381
382         /*
383          * If we've already updated the spinner once within
384          * the last 1/8th of a second, no point doing it
385          * again.
386          */
387         gettimeofday(&tv, NULL);
388         tick = (tv.tv_sec << 3) + (tv.tv_usec / (1000000 / 8));
389         if ((tick == ctx->progress_last_time) &&
390             (fixed_percent != 0) && (fixed_percent != 1000))
391                 return 0;
392         ctx->progress_last_time = tick;
393
394         /*
395          * Advance the spinner, and note that the progress bar
396          * will be on the screen
397          */
398         ctx->progress_pos = (ctx->progress_pos+1) & 3;
399         ctx->flags |= E2F_FLAG_PROG_BAR;
400
401         dpywidth = 66 - strlen(label);
402         dpywidth = 8 * (dpywidth / 8);
403         if (dpynum)
404                 dpywidth -= 8;
405
406         i = ((percent * dpywidth) + 50) / 100;
407         printf("%s%s: |%s%s", ctx->start_meta, label,
408                bar + (sizeof(bar) - (i+1)),
409                spaces + (sizeof(spaces) - (dpywidth - i + 1)));
410         if (fixed_percent == 1000)
411                 fputc('|', stdout);
412         else
413                 fputc(spinner[ctx->progress_pos & 3], stdout);
414         printf(" %4.1f%%  ", percent);
415         if (dpynum)
416                 printf("%u\r", dpynum);
417         else
418                 fputs(" \r", stdout);
419         fputs(ctx->stop_meta, stdout);
420         
421         if (fixed_percent == 1000)
422                 e2fsck_clear_progbar(ctx);
423         fflush(stdout);
424
425         return 0;
426 }
427
428 static int e2fsck_update_progress(e2fsck_t ctx, int pass,
429                                   unsigned long cur, unsigned long max)
430 {
431         char buf[80];
432         float percent;
433
434         if (pass == 0)
435                 return 0;
436         
437         if (ctx->progress_fd) {
438                 sprintf(buf, "%d %lu %lu\n", pass, cur, max);
439                 write(ctx->progress_fd, buf, strlen(buf));
440         } else {
441                 percent = calc_percent(&e2fsck_tbl, pass, cur, max);
442                 e2fsck_simple_progress(ctx, ctx->device_name,
443                                        percent, 0);
444         }
445         return 0;
446 }
447
448 #define PATH_SET "PATH=/sbin"
449
450 static void reserve_stdio_fds(void)
451 {
452         int     fd;
453
454         while (1) {
455                 fd = open("/dev/null", O_RDWR);
456                 if (fd > 2)
457                         break;
458                 if (fd < 0) {
459                         fprintf(stderr, _("ERROR: Couldn't open "
460                                 "/dev/null (%s)\n"),
461                                 strerror(errno));
462                         break;
463                 }
464         }
465         close(fd);
466 }
467
468 #ifdef HAVE_SIGNAL_H
469 static void signal_progress_on(int sig EXT2FS_ATTR((unused)))
470 {
471         e2fsck_t ctx = e2fsck_global_ctx;
472
473         if (!ctx)
474                 return;
475
476         ctx->progress = e2fsck_update_progress;
477         ctx->progress_fd = 0;
478 }
479
480 static void signal_progress_off(int sig EXT2FS_ATTR((unused)))
481 {
482         e2fsck_t ctx = e2fsck_global_ctx;
483
484         if (!ctx)
485                 return;
486
487         e2fsck_clear_progbar(ctx);
488         ctx->progress = 0;
489 }
490
491 static void signal_cancel(int sig EXT2FS_ATTR((unused)))
492 {
493         e2fsck_t ctx = e2fsck_global_ctx;
494
495         if (!ctx)
496                 exit(FSCK_CANCELED);
497
498         ctx->flags |= E2F_FLAG_CANCEL;
499 }
500 #endif
501
502 static void parse_extended_opts(e2fsck_t ctx, const char *opts)
503 {
504         char    *buf, *token, *next, *p, *arg;
505         int     ea_ver;
506         int     extended_usage = 0;
507
508         buf = string_copy(ctx, opts, 0);
509         for (token = buf; token && *token; token = next) {
510                 p = strchr(token, ',');
511                 next = 0;
512                 if (p) {
513                         *p = 0;
514                         next = p+1;
515                 } 
516                 arg = strchr(token, '=');
517                 if (arg) {
518                         *arg = 0;
519                         arg++;
520                 }
521                 if (strcmp(token, "ea_ver") == 0) {
522                         if (!arg) {
523                                 extended_usage++;
524                                 continue;
525                         }
526                         ea_ver = strtoul(arg, &p, 0);
527                         if (*p ||
528                             ((ea_ver != 1) && (ea_ver != 2))) {
529                                 fprintf(stderr,
530                                         _("Invalid EA version.\n"));
531                                 extended_usage++;
532                                 continue;
533                         }
534                         ctx->ext_attr_ver = ea_ver;
535                 } else {
536                         fprintf(stderr, _("Unknown extended option: %s\n"),
537                                 token);
538                         extended_usage++;
539                 }
540         }
541         if (extended_usage) {
542                 fputs(("\nExtended options are separated by commas, "
543                        "and may take an argument which\n"
544                        "is set off by an equals ('=') sign.  "
545                         "Valid extended options are:\n"
546                        "\tea_ver=<ea_version (1 or 2)>\n\n"), stderr);
547                 exit(1);
548         }
549 }       
550
551 static void syntax_err_report(const char *filename, long err, int line_num)
552 {
553         fprintf(stderr, 
554                 _("Syntax error in e2fsck config file (%s, line #%d)\n\t%s\n"),
555                 filename, line_num, error_message(err));
556         exit(FSCK_ERROR);
557 }
558
559 static const char *config_fn[] = { "/etc/e2fsck.conf", 0 };
560
561 static errcode_t PRS(int argc, char *argv[], e2fsck_t *ret_ctx)
562 {
563         int             flush = 0;
564         int             c, fd;
565 #ifdef MTRACE
566         extern void     *mallwatch;
567 #endif
568         e2fsck_t        ctx;
569         errcode_t       retval;
570 #ifdef HAVE_SIGNAL_H
571         struct sigaction        sa;
572 #endif
573         char            *extended_opts = 0;
574         char            *cp;
575
576         retval = e2fsck_allocate_context(&ctx);
577         if (retval)
578                 return retval;
579
580         *ret_ctx = ctx;
581
582         setvbuf(stdout, NULL, _IONBF, BUFSIZ);
583         setvbuf(stderr, NULL, _IONBF, BUFSIZ);
584         if (isatty(0) && isatty(1)) {
585                 ctx->interactive = 1;
586         } else {
587                 ctx->start_meta[0] = '\001';
588                 ctx->stop_meta[0] = '\002';
589         }
590         memset(bar, '=', sizeof(bar)-1);
591         memset(spaces, ' ', sizeof(spaces)-1);
592         initialize_ext2_error_table();
593         initialize_prof_error_table();
594         blkid_get_cache(&ctx->blkid, NULL);
595         
596         if (argc && *argv)
597                 ctx->program_name = *argv;
598         else
599                 ctx->program_name = "e2fsck";
600         while ((c = getopt (argc, argv, "panyrcC:B:dE:fvtFVM:b:I:j:P:l:L:N:SsDk")) != EOF)
601                 switch (c) {
602                 case 'C':
603                         ctx->progress = e2fsck_update_progress;
604                         ctx->progress_fd = atoi(optarg);
605                         if (!ctx->progress_fd)
606                                 break;
607                         /* Validate the file descriptor to avoid disasters */
608                         fd = dup(ctx->progress_fd);
609                         if (fd < 0) {
610                                 fprintf(stderr,
611                                 _("Error validating file descriptor %d: %s\n"),
612                                         ctx->progress_fd,
613                                         error_message(errno));
614                                 fatal_error(ctx,
615                         _("Invalid completion information file descriptor"));
616                         } else
617                                 close(fd);
618                         break;
619                 case 'D':
620                         ctx->options |= E2F_OPT_COMPRESS_DIRS;
621                         break;
622                 case 'E':
623                         extended_opts = optarg;
624                         break;
625                 case 'p':
626                 case 'a':
627                         if (ctx->options & (E2F_OPT_YES|E2F_OPT_NO)) {
628                         conflict_opt:
629                                 fatal_error(ctx, 
630         _("Only one of the options -p/-a, -n or -y may be specified."));
631                         }
632                         ctx->options |= E2F_OPT_PREEN;
633                         break;
634                 case 'n':
635                         if (ctx->options & (E2F_OPT_YES|E2F_OPT_PREEN))
636                                 goto conflict_opt;
637                         ctx->options |= E2F_OPT_NO;
638                         break;
639                 case 'y':
640                         if (ctx->options & (E2F_OPT_PREEN|E2F_OPT_NO))
641                                 goto conflict_opt;
642                         ctx->options |= E2F_OPT_YES;
643                         break;
644                 case 't':
645 #ifdef RESOURCE_TRACK
646                         if (ctx->options & E2F_OPT_TIME)
647                                 ctx->options |= E2F_OPT_TIME2;
648                         else
649                                 ctx->options |= E2F_OPT_TIME;
650 #else
651                         fprintf(stderr, _("The -t option is not "
652                                 "supported on this version of e2fsck.\n"));
653 #endif
654                         break;
655                 case 'c':
656                         if (cflag++)
657                                 ctx->options |= E2F_OPT_WRITECHECK;
658                         ctx->options |= E2F_OPT_CHECKBLOCKS;
659                         break;
660                 case 'r':
661                         /* What we do by default, anyway! */
662                         break;
663                 case 'b':
664                         ctx->use_superblock = atoi(optarg);
665                         ctx->flags |= E2F_FLAG_SB_SPECIFIED;
666                         break;
667                 case 'B':
668                         ctx->blocksize = atoi(optarg);
669                         break;
670                 case 'I':
671                         ctx->inode_buffer_blocks = atoi(optarg);
672                         break;
673                 case 'j':
674                         ctx->journal_name = string_copy(ctx, optarg, 0);
675                         break;
676                 case 'P':
677                         ctx->process_inode_size = atoi(optarg);
678                         break;
679                 case 'L':
680                         replace_bad_blocks++;
681                 case 'l':
682                         bad_blocks_file = string_copy(ctx, optarg, 0);
683                         break;
684                 case 'd':
685                         ctx->options |= E2F_OPT_DEBUG;
686                         break;
687                 case 'f':
688                         ctx->options |= E2F_OPT_FORCE;
689                         break;
690                 case 'F':
691                         flush = 1;
692                         break;
693                 case 'v':
694                         verbose = 1;
695                         break;
696                 case 'V':
697                         show_version_only = 1;
698                         break;
699 #ifdef MTRACE
700                 case 'M':
701                         mallwatch = (void *) strtol(optarg, NULL, 0);
702                         break;
703 #endif
704                 case 'N':
705                         ctx->device_name = optarg;
706                         break;
707 #ifdef ENABLE_SWAPFS
708                 case 's':
709                         normalize_swapfs = 1;
710                 case 'S':
711                         swapfs = 1;
712                         break;
713 #else
714                 case 's':
715                 case 'S':
716                         fprintf(stderr, _("Byte-swapping filesystems "
717                                           "not compiled in this version "
718                                           "of e2fsck\n"));
719                         exit(1);
720 #endif
721                 case 'k':
722                         keep_bad_blocks++;
723                         break;
724                 default:
725                         usage(ctx);
726                 }
727         if (show_version_only)
728                 return 0;
729         if (optind != argc - 1)
730                 usage(ctx);
731         if ((ctx->options & E2F_OPT_NO) && !bad_blocks_file &&
732             !cflag && !swapfs && !(ctx->options & E2F_OPT_COMPRESS_DIRS))
733                 ctx->options |= E2F_OPT_READONLY;
734         ctx->io_options = strchr(argv[optind], '?');
735         if (ctx->io_options) 
736                 *ctx->io_options++ = 0;
737         ctx->filesystem_name = blkid_get_devname(ctx->blkid, argv[optind], 0);
738         if (!ctx->filesystem_name) {
739                 com_err(ctx->program_name, 0, _("Unable to resolve '%s'"), 
740                         argv[optind]);
741                 fatal_error(ctx, 0);
742         }
743         if (extended_opts)
744                 parse_extended_opts(ctx, extended_opts);
745
746         if ((cp = getenv("E2FSCK_CONFIG")) != NULL)
747                 config_fn[0] = cp;
748         profile_set_syntax_err_cb(syntax_err_report);
749         profile_init(config_fn, &ctx->profile);
750
751         if (flush) {
752                 fd = open(ctx->filesystem_name, O_RDONLY, 0);
753                 if (fd < 0) {
754                         com_err("open", errno,
755                                 _("while opening %s for flushing"),
756                                 ctx->filesystem_name);
757                         fatal_error(ctx, 0);
758                 }
759                 if ((retval = ext2fs_sync_device(fd, 1))) {
760                         com_err("ext2fs_sync_device", retval,
761                                 _("while trying to flush %s"),
762                                 ctx->filesystem_name);
763                         fatal_error(ctx, 0);
764                 }
765                 close(fd);
766         }
767 #ifdef ENABLE_SWAPFS
768         if (swapfs) {
769                 if (cflag || bad_blocks_file) {
770                         fprintf(stderr, _("Incompatible options not "
771                                           "allowed when byte-swapping.\n"));
772                         exit(FSCK_USAGE);
773                 }
774         }
775 #endif
776         if (cflag && bad_blocks_file) {
777                 fprintf(stderr, _("The -c and the -l/-L options may "
778                                   "not be both used at the same time.\n"));
779                 exit(FSCK_USAGE);
780         }
781 #ifdef HAVE_SIGNAL_H
782         /*
783          * Set up signal action
784          */
785         memset(&sa, 0, sizeof(struct sigaction));
786         sa.sa_handler = signal_cancel;
787         sigaction(SIGINT, &sa, 0);
788         sigaction(SIGTERM, &sa, 0);
789 #ifdef SA_RESTART
790         sa.sa_flags = SA_RESTART;
791 #endif
792         e2fsck_global_ctx = ctx;
793         sa.sa_handler = signal_progress_on;
794         sigaction(SIGUSR1, &sa, 0);
795         sa.sa_handler = signal_progress_off;
796         sigaction(SIGUSR2, &sa, 0);
797 #endif
798
799         /* Update our PATH to include /sbin if we need to run badblocks  */
800         if (cflag) {
801                 char *oldpath = getenv("PATH");
802                 if (oldpath) {
803                         char *newpath;
804
805                         newpath = (char *) malloc(sizeof (PATH_SET) + 1 +
806                                                   strlen (oldpath));
807                         if (!newpath)
808                                 fatal_error(ctx, "Couldn't malloc() newpath");
809                         strcpy (newpath, PATH_SET);
810                         strcat (newpath, ":");
811                         strcat (newpath, oldpath);
812                         putenv (newpath);
813                 } else
814                         putenv (PATH_SET);
815         }
816 #ifdef CONFIG_JBD_DEBUG
817         if (getenv("E2FSCK_JBD_DEBUG"))
818                 journal_enable_debug = atoi(getenv("E2FSCK_JBD_DEBUG"));
819 #endif
820         return 0;
821 }
822
823 static const char *my_ver_string = E2FSPROGS_VERSION;
824 static const char *my_ver_date = E2FSPROGS_DATE;
825                                         
826 int main (int argc, char *argv[])
827 {
828         errcode_t       retval = 0;
829         int             exit_value = FSCK_OK;
830         ext2_filsys     fs = 0;
831         io_manager      io_ptr;
832         struct ext2_super_block *sb;
833         const char      *lib_ver_date;
834         int             my_ver, lib_ver;
835         e2fsck_t        ctx;
836         struct problem_context pctx;
837         int flags, run_result;
838         
839         clear_problem_context(&pctx);
840 #ifdef MTRACE
841         mtrace();
842 #endif
843 #ifdef MCHECK
844         mcheck(0);
845 #endif
846 #ifdef ENABLE_NLS
847         setlocale(LC_MESSAGES, "");
848         setlocale(LC_CTYPE, "");
849         bindtextdomain(NLS_CAT_NAME, LOCALEDIR);
850         textdomain(NLS_CAT_NAME);
851 #endif
852         my_ver = ext2fs_parse_version_string(my_ver_string);
853         lib_ver = ext2fs_get_library_version(0, &lib_ver_date);
854         if (my_ver > lib_ver) {
855                 fprintf( stderr, _("Error: ext2fs library version "
856                         "out of date!\n"));
857                 show_version_only++;
858         }
859         
860         retval = PRS(argc, argv, &ctx);
861         if (retval) {
862                 com_err("e2fsck", retval,
863                         _("while trying to initialize program"));
864                 exit(FSCK_ERROR);
865         }
866         reserve_stdio_fds();
867         
868 #ifdef RESOURCE_TRACK
869         init_resource_track(&ctx->global_rtrack);
870 #endif
871
872         if (!(ctx->options & E2F_OPT_PREEN) || show_version_only)
873                 fprintf(stderr, "e2fsck %s (%s)\n", my_ver_string,
874                          my_ver_date);
875
876         if (show_version_only) {
877                 fprintf(stderr, _("\tUsing %s, %s\n"),
878                         error_message(EXT2_ET_BASE), lib_ver_date);
879                 exit(FSCK_OK);
880         }
881         
882         check_mount(ctx);
883         
884         if (!(ctx->options & E2F_OPT_PREEN) &&
885             !(ctx->options & E2F_OPT_NO) &&
886             !(ctx->options & E2F_OPT_YES)) {
887                 if (!ctx->interactive)
888                         fatal_error(ctx,
889                                     _("need terminal for interactive repairs"));
890         }
891         ctx->superblock = ctx->use_superblock;
892 restart:
893 #ifdef CONFIG_TESTIO_DEBUG
894         io_ptr = test_io_manager;
895         test_io_backing_manager = unix_io_manager;
896 #else
897         io_ptr = unix_io_manager;
898 #endif
899         flags = 0;
900         if ((ctx->options & E2F_OPT_READONLY) == 0)
901                 flags |= EXT2_FLAG_RW;
902
903         if (ctx->superblock && ctx->blocksize) {
904                 retval = ext2fs_open2(ctx->filesystem_name, ctx->io_options, 
905                                       flags, ctx->superblock, ctx->blocksize,
906                                       io_ptr, &fs);
907         } else if (ctx->superblock) {
908                 int blocksize;
909                 for (blocksize = EXT2_MIN_BLOCK_SIZE;
910                      blocksize <= EXT2_MAX_BLOCK_SIZE; blocksize *= 2) {
911                         retval = ext2fs_open2(ctx->filesystem_name, 
912                                               ctx->io_options, flags,
913                                               ctx->superblock, blocksize,
914                                               io_ptr, &fs);
915                         if (!retval)
916                                 break;
917                 }
918         } else 
919                 retval = ext2fs_open2(ctx->filesystem_name, ctx->io_options, 
920                                       flags, 0, 0, io_ptr, &fs);
921         if (!ctx->superblock && !(ctx->options & E2F_OPT_PREEN) &&
922             !(ctx->flags & E2F_FLAG_SB_SPECIFIED) &&
923             ((retval == EXT2_ET_BAD_MAGIC) ||
924              ((retval == 0) && ext2fs_check_desc(fs)))) {
925                 if (!fs || (fs->group_desc_count > 1)) {
926                         printf(_("%s trying backup blocks...\n"),
927                                retval ? _("Couldn't find ext2 superblock,") :
928                                _("Group descriptors look bad..."));
929                         get_backup_sb(ctx, fs, ctx->filesystem_name, io_ptr);
930                         if (fs)
931                                 ext2fs_close(fs);
932                         goto restart;
933                 }
934         }
935         if (retval) {
936                 com_err(ctx->program_name, retval, _("while trying to open %s"),
937                         ctx->filesystem_name);
938                 if (retval == EXT2_ET_REV_TOO_HIGH) {
939                         printf(_("The filesystem revision is apparently "
940                                "too high for this version of e2fsck.\n"
941                                "(Or the filesystem superblock "
942                                "is corrupt)\n\n"));
943                         fix_problem(ctx, PR_0_SB_CORRUPT, &pctx);
944                 } else if (retval == EXT2_ET_SHORT_READ)
945                         printf(_("Could this be a zero-length partition?\n"));
946                 else if ((retval == EPERM) || (retval == EACCES))
947                         printf(_("You must have %s access to the "
948                                "filesystem or be root\n"),
949                                (ctx->options & E2F_OPT_READONLY) ?
950                                "r/o" : "r/w");
951                 else if (retval == ENXIO)
952                         printf(_("Possibly non-existent or swap device?\n"));
953 #ifdef EROFS
954                 else if (retval == EROFS)
955                         printf(_("Disk write-protected; use the -n option "
956                                "to do a read-only\n"
957                                "check of the device.\n"));
958 #endif
959                 else
960                         fix_problem(ctx, PR_0_SB_CORRUPT, &pctx);
961                 fatal_error(ctx, 0);
962         }
963         ctx->fs = fs;
964         fs->priv_data = ctx;
965         fs->now = ctx->now;
966         sb = fs->super;
967         if (sb->s_rev_level > E2FSCK_CURRENT_REV) {
968                 com_err(ctx->program_name, EXT2_ET_REV_TOO_HIGH,
969                         _("while trying to open %s"),
970                         ctx->filesystem_name);
971         get_newer:
972                 fatal_error(ctx, _("Get a newer version of e2fsck!"));
973         }
974
975         /*
976          * Set the device name, which is used whenever we print error
977          * or informational messages to the user.
978          */
979         if (ctx->device_name == 0 &&
980             (sb->s_volume_name[0] != 0)) {
981                 ctx->device_name = string_copy(ctx, sb->s_volume_name,
982                                                sizeof(sb->s_volume_name));
983         }
984         if (ctx->device_name == 0)
985                 ctx->device_name = ctx->filesystem_name;
986
987         /*
988          * Make sure the ext3 superblock fields are consistent.
989          */
990         retval = e2fsck_check_ext3_journal(ctx);
991         if (retval) {
992                 com_err(ctx->program_name, retval,
993                         _("while checking ext3 journal for %s"),
994                         ctx->device_name);
995                 fatal_error(ctx, 0);
996         }
997
998         /*
999          * Check to see if we need to do ext3-style recovery.  If so,
1000          * do it, and then restart the fsck.
1001          */
1002         if (sb->s_feature_incompat & EXT3_FEATURE_INCOMPAT_RECOVER) {
1003                 if (ctx->options & E2F_OPT_READONLY) {
1004                         printf(_("Warning: skipping journal recovery "
1005                                  "because doing a read-only filesystem "
1006                                  "check.\n"));
1007                         io_channel_flush(ctx->fs->io);
1008                 } else {
1009                         if (ctx->flags & E2F_FLAG_RESTARTED) {
1010                                 /*
1011                                  * Whoops, we attempted to run the
1012                                  * journal twice.  This should never
1013                                  * happen, unless the hardware or
1014                                  * device driver is being bogus.
1015                                  */
1016                                 com_err(ctx->program_name, 0,
1017                                         _("unable to set superblock flags on %s\n"), ctx->device_name);
1018                                 fatal_error(ctx, 0);
1019                         }
1020                         retval = e2fsck_run_ext3_journal(ctx);
1021                         if (retval) {
1022                                 com_err(ctx->program_name, retval,
1023                                 _("while recovering ext3 journal of %s"),
1024                                         ctx->device_name);
1025                                 fatal_error(ctx, 0);
1026                         }
1027                         ext2fs_close(ctx->fs);
1028                         ctx->fs = 0;
1029                         ctx->flags |= E2F_FLAG_RESTARTED;
1030                         goto restart;
1031                 }
1032         }
1033
1034         /*
1035          * Check for compatibility with the feature sets.  We need to
1036          * be more stringent than ext2fs_open().
1037          */
1038         if ((sb->s_feature_compat & ~EXT2_LIB_FEATURE_COMPAT_SUPP) ||
1039             (sb->s_feature_incompat & ~EXT2_LIB_FEATURE_INCOMPAT_SUPP)) {
1040                 com_err(ctx->program_name, EXT2_ET_UNSUPP_FEATURE,
1041                         "(%s)", ctx->device_name);
1042                 goto get_newer;
1043         }
1044         if (sb->s_feature_ro_compat & ~EXT2_LIB_FEATURE_RO_COMPAT_SUPP) {
1045                 com_err(ctx->program_name, EXT2_ET_RO_UNSUPP_FEATURE,
1046                         "(%s)", ctx->device_name);
1047                 goto get_newer;
1048         }
1049 #ifdef ENABLE_COMPRESSION
1050         if (sb->s_feature_incompat & EXT2_FEATURE_INCOMPAT_COMPRESSION)
1051                 com_err(ctx->program_name, 0,
1052                         _("Warning: compression support is experimental.\n"));
1053 #endif
1054 #ifndef ENABLE_HTREE
1055         if (sb->s_feature_compat & EXT2_FEATURE_COMPAT_DIR_INDEX) {
1056                 com_err(ctx->program_name, 0,
1057                         _("E2fsck not compiled with HTREE support,\n\t"
1058                           "but filesystem %s has HTREE directories.\n"),
1059                         ctx->device_name);
1060                 goto get_newer;
1061         }
1062 #endif
1063
1064         /*
1065          * If the user specified a specific superblock, presumably the
1066          * master superblock has been trashed.  So we mark the
1067          * superblock as dirty, so it can be written out.
1068          */
1069         if (ctx->superblock &&
1070             !(ctx->options & E2F_OPT_READONLY))
1071                 ext2fs_mark_super_dirty(fs);
1072
1073         /*
1074          * We only update the master superblock because (a) paranoia;
1075          * we don't want to corrupt the backup superblocks, and (b) we
1076          * don't need to update the mount count and last checked
1077          * fields in the backup superblock (the kernel doesn't
1078          * update the backup superblocks anyway).
1079          */
1080         fs->flags |= EXT2_FLAG_MASTER_SB_ONLY;
1081
1082         ehandler_init(fs->io);
1083
1084         if (ctx->superblock)
1085                 set_latch_flags(PR_LATCH_RELOC, PRL_LATCHED, 0);
1086         ext2fs_mark_valid(fs);
1087         check_super_block(ctx);
1088         if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
1089                 fatal_error(ctx, 0);
1090         check_if_skip(ctx);
1091         if (bad_blocks_file)
1092                 read_bad_blocks_file(ctx, bad_blocks_file, replace_bad_blocks);
1093         else if (cflag)
1094                 read_bad_blocks_file(ctx, 0, !keep_bad_blocks); /* Test disk */
1095         if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
1096                 fatal_error(ctx, 0);
1097 #ifdef ENABLE_SWAPFS
1098         if (normalize_swapfs) {
1099                 if ((fs->flags & EXT2_FLAG_SWAP_BYTES) ==
1100                     ext2fs_native_flag()) {
1101                         fprintf(stderr, _("%s: Filesystem byte order "
1102                                 "already normalized.\n"), ctx->device_name);
1103                         fatal_error(ctx, 0);
1104                 }
1105         }
1106         if (swapfs) {
1107                 swap_filesys(ctx);
1108                 if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
1109                         fatal_error(ctx, 0);
1110         }
1111 #endif
1112
1113         /*
1114          * Mark the system as valid, 'til proven otherwise
1115          */
1116         ext2fs_mark_valid(fs);
1117
1118         retval = ext2fs_read_bb_inode(fs, &fs->badblocks);
1119         if (retval) {
1120                 com_err(ctx->program_name, retval,
1121                         _("while reading bad blocks inode"));
1122                 preenhalt(ctx);
1123                 printf(_("This doesn't bode well,"
1124                          " but we'll try to go on...\n"));
1125         }
1126
1127         run_result = e2fsck_run(ctx);
1128         e2fsck_clear_progbar(ctx);
1129         if (run_result == E2F_FLAG_RESTART) {
1130                 printf(_("Restarting e2fsck from the beginning...\n"));
1131                 retval = e2fsck_reset_context(ctx);
1132                 if (retval) {
1133                         com_err(ctx->program_name, retval,
1134                                 _("while resetting context"));
1135                         fatal_error(ctx, 0);
1136                 }
1137                 ext2fs_close(fs);
1138                 goto restart;
1139         }
1140         if (run_result & E2F_FLAG_CANCEL) {
1141                 printf(_("%s: e2fsck canceled.\n"), ctx->device_name ?
1142                        ctx->device_name : ctx->filesystem_name);
1143                 exit_value |= FSCK_CANCELED;
1144         }
1145         if (run_result & E2F_FLAG_ABORT)
1146                 fatal_error(ctx, _("aborted"));
1147
1148 #ifdef MTRACE
1149         mtrace_print("Cleanup");
1150 #endif
1151         if (ext2fs_test_changed(fs)) {
1152                 exit_value |= FSCK_NONDESTRUCT;
1153                 if (!(ctx->options & E2F_OPT_PREEN))
1154                     printf(_("\n%s: ***** FILE SYSTEM WAS MODIFIED *****\n"),
1155                                ctx->device_name);
1156                 if (ctx->mount_flags & EXT2_MF_ISROOT) {
1157                         printf(_("%s: ***** REBOOT LINUX *****\n"),
1158                                ctx->device_name);
1159                         exit_value |= FSCK_REBOOT;
1160                 }
1161         }
1162         if (!ext2fs_test_valid(fs) ||
1163             ((exit_value & FSCK_CANCELED) && 
1164              (sb->s_state & EXT2_ERROR_FS))) {
1165                 printf(_("\n%s: ********** WARNING: Filesystem still has "
1166                          "errors **********\n\n"), ctx->device_name);
1167                 exit_value |= FSCK_UNCORRECTED;
1168                 exit_value &= ~FSCK_NONDESTRUCT;
1169         }
1170         if (exit_value & FSCK_CANCELED) {
1171                 int     allow_cancellation;
1172
1173                 profile_get_boolean(ctx->profile, "options",
1174                                     "allow_cancellation", 0, 0, 
1175                                     &allow_cancellation);
1176                 exit_value &= ~FSCK_NONDESTRUCT;
1177                 if (allow_cancellation && ext2fs_test_valid(fs) &&
1178                     (sb->s_state & EXT2_VALID_FS) && 
1179                     !(sb->s_state & EXT2_ERROR_FS))
1180                         exit_value = 0;
1181         } else {
1182                 show_stats(ctx);
1183                 if (!(ctx->options & E2F_OPT_READONLY)) {
1184                         if (ext2fs_test_valid(fs)) {
1185                                 if (!(sb->s_state & EXT2_VALID_FS))
1186                                         exit_value |= FSCK_NONDESTRUCT;
1187                                 sb->s_state = EXT2_VALID_FS;
1188                         } else
1189                                 sb->s_state &= ~EXT2_VALID_FS;
1190                         sb->s_mnt_count = 0;
1191                         sb->s_lastcheck = ctx->now;
1192                         ext2fs_mark_super_dirty(fs);
1193                 }
1194         }
1195
1196         e2fsck_write_bitmaps(ctx);
1197         
1198         ext2fs_close(fs);
1199         ctx->fs = NULL;
1200         free(ctx->filesystem_name);
1201         free(ctx->journal_name);
1202
1203 #ifdef RESOURCE_TRACK
1204         if (ctx->options & E2F_OPT_TIME)
1205                 print_resource_track(NULL, &ctx->global_rtrack);
1206 #endif
1207         e2fsck_free_context(ctx);
1208         return exit_value;
1209 }