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