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