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