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