2 * unix.c - The unix-specific code for e2fsck
4 * Copyright (C) 1993, 1994, 1995, 1996, 1997 Theodore Ts'o.
7 * This file may be redistributed under the terms of the GNU Public
12 #define _XOPEN_SOURCE 600 /* for inclusion of sa_handler in Solaris */
38 #ifdef HAVE_SYS_IOCTL_H
39 #include <sys/ioctl.h>
44 #ifdef HAVE_SYS_TYPES_H
45 #include <sys/types.h>
52 #include "et/com_err.h"
56 #include "../version.h"
58 /* Command line options */
59 static int cflag; /* check disk */
60 static int show_version_only;
63 static int replace_bad_blocks;
64 static int keep_bad_blocks;
65 static char *bad_blocks_file;
67 e2fsck_t e2fsck_global_ctx; /* Try your very best not to use this! */
69 #ifdef CONFIG_JBD_DEBUG /* Enabled by configure --enable-jfs-debug */
70 int journal_enable_debug = -1;
73 static void usage(e2fsck_t ctx)
76 _("Usage: %s [-panyrcdfvtDFV] [-b superblock] [-B blocksize]\n"
77 "\t\t[-I inode_buffer_blocks] [-P process_inode_size]\n"
78 "\t\t[-l|-L bad_blocks_file] [-C fd] [-j external_journal]\n"
79 "\t\t[-E extended-options] device\n"),
82 fprintf(stderr, _("\nEmergency help:\n"
83 " -p Automatic repair (no questions)\n"
84 " -n Make no changes to the filesystem\n"
85 " -y Assume \"yes\" to all questions\n"
86 " -c Check for bad blocks and add them to the badblock list\n"
87 " -f Force checking even if filesystem is marked clean\n"));
90 " -b superblock Use alternative superblock\n"
91 " -B blocksize Force blocksize when looking for superblock\n"
92 " -j external_journal Set location of the external journal\n"
93 " -l bad_blocks_file Add to badblocks list\n"
94 " -L bad_blocks_file Set badblocks list\n"
100 static void show_stats(e2fsck_t ctx)
102 ext2_filsys fs = ctx->fs;
103 ext2_ino_t inodes, inodes_used;
104 blk_t blocks, blocks_used;
106 int num_files, num_links;
107 int frag_percent_file, frag_percent_dir, frag_percent_total;
110 dir_links = 2 * ctx->fs_directory_count - 1;
111 num_files = ctx->fs_total_count - dir_links;
112 num_links = ctx->fs_links_count - dir_links;
113 inodes = fs->super->s_inodes_count;
114 inodes_used = (fs->super->s_inodes_count -
115 fs->super->s_free_inodes_count);
116 blocks = ext2fs_blocks_count(fs->super);
117 blocks_used = (ext2fs_blocks_count(fs->super) -
118 ext2fs_free_blocks_count(fs->super));
120 frag_percent_file = (10000 * ctx->fs_fragmented) / inodes_used;
121 frag_percent_file = (frag_percent_file + 5) / 10;
123 frag_percent_dir = (10000 * ctx->fs_fragmented_dir) / inodes_used;
124 frag_percent_dir = (frag_percent_dir + 5) / 10;
126 frag_percent_total = ((10000 * (ctx->fs_fragmented +
127 ctx->fs_fragmented_dir))
129 frag_percent_total = (frag_percent_total + 5) / 10;
132 printf(_("%s: %u/%u files (%0d.%d%% non-contiguous), %u/%u blocks\n"),
133 ctx->device_name, inodes_used, inodes,
134 frag_percent_total / 10, frag_percent_total % 10,
135 blocks_used, blocks);
138 printf (P_("\n%8u inode used (%2.2f%%)\n", "\n%8u inodes used (%2.2f%%)\n",
139 inodes_used), inodes_used, 100.0 * inodes_used / inodes);
140 printf (P_("%8u non-contiguous file (%0d.%d%%)\n",
141 "%8u non-contiguous files (%0d.%d%%)\n",
143 ctx->fs_fragmented, frag_percent_file / 10,
144 frag_percent_file % 10);
145 printf (P_("%8u non-contiguous directory (%0d.%d%%)\n",
146 "%8u non-contiguous directories (%0d.%d%%)\n",
147 ctx->fs_fragmented_dir),
148 ctx->fs_fragmented_dir, frag_percent_dir / 10,
149 frag_percent_dir % 10);
150 printf (_(" # of inodes with ind/dind/tind blocks: %u/%u/%u\n"),
151 ctx->fs_ind_count, ctx->fs_dind_count, ctx->fs_tind_count);
153 for (j=MAX_EXTENT_DEPTH_COUNT-1; j >=0; j--)
154 if (ctx->extent_depth_count[j])
157 printf (_(" Extent depth histogram: "));
158 for (i=0; i < j; i++) {
161 printf("%u", ctx->extent_depth_count[i]);
166 printf (P_("%8u block used (%2.2f%%)\n", "%8u blocks used (%2.2f%%)\n",
167 blocks_used), blocks_used, 100.0 * blocks_used / blocks);
168 printf (P_("%8u bad block\n", "%8u bad blocks\n",
169 ctx->fs_badblocks_count), ctx->fs_badblocks_count);
170 printf (P_("%8u large file\n", "%8u large files\n",
171 ctx->large_files), ctx->large_files);
172 printf (P_("\n%8u regular file\n", "\n%8u regular files\n",
173 ctx->fs_regular_count), ctx->fs_regular_count);
174 printf (P_("%8u directory\n", "%8u directories\n",
175 ctx->fs_directory_count), ctx->fs_directory_count);
176 printf (P_("%8u character device file\n",
177 "%8u character device files\n", ctx->fs_chardev_count),
178 ctx->fs_chardev_count);
179 printf (P_("%8u block device file\n", "%8u block device files\n",
180 ctx->fs_blockdev_count), ctx->fs_blockdev_count);
181 printf (P_("%8u fifo\n", "%8u fifos\n", ctx->fs_fifo_count),
183 printf (P_("%8u link\n", "%8u links\n",
184 ctx->fs_links_count - dir_links),
185 ctx->fs_links_count - dir_links);
186 printf (P_("%8u symbolic link", "%8u symbolic links",
187 ctx->fs_symlinks_count), ctx->fs_symlinks_count);
188 printf (P_(" (%u fast symbolic link)\n", " (%u fast symbolic links)\n",
189 ctx->fs_fast_symlinks_count), ctx->fs_fast_symlinks_count);
190 printf (P_("%8u socket\n", "%8u sockets\n", ctx->fs_sockets_count),
191 ctx->fs_sockets_count);
192 printf ("--------\n");
193 printf (P_("%8u file\n", "%8u files\n",
194 ctx->fs_total_count - dir_links),
195 ctx->fs_total_count - dir_links);
198 static void check_mount(e2fsck_t ctx)
203 retval = ext2fs_check_if_mounted(ctx->filesystem_name,
206 com_err("ext2fs_check_if_mount", retval,
207 _("while determining whether %s is mounted."),
208 ctx->filesystem_name);
213 * If the filesystem isn't mounted, or it's the root
214 * filesystem and it's mounted read-only, and we're not doing
215 * a read/write check, then everything's fine.
217 if ((!(ctx->mount_flags & EXT2_MF_MOUNTED)) ||
218 ((ctx->mount_flags & EXT2_MF_ISROOT) &&
219 (ctx->mount_flags & EXT2_MF_READONLY) &&
220 !(ctx->options & E2F_OPT_WRITECHECK)))
223 if ((ctx->options & E2F_OPT_READONLY) &&
224 !(ctx->options & E2F_OPT_WRITECHECK)) {
225 printf(_("Warning! %s is mounted.\n"), ctx->filesystem_name);
229 printf(_("%s is mounted. "), ctx->filesystem_name);
230 if (!ctx->interactive)
231 fatal_error(ctx, _("Cannot continue, aborting.\n\n"));
232 printf(_("\n\n\007\007\007\007WARNING!!! "
233 "The filesystem is mounted. If you continue you ***WILL***\n"
234 "cause ***SEVERE*** filesystem damage.\007\007\007\n\n"));
235 cont = ask_yn(_("Do you really want to continue"), -1);
237 printf (_("check aborted.\n"));
243 static int is_on_batt(void)
247 char tmp[80], tmp2[80], fname[80];
251 f = fopen("/proc/apm", "r");
253 if (fscanf(f, "%s %s %s %x", tmp, tmp, tmp, &acflag) != 4)
256 return (acflag != 1);
258 d = opendir("/proc/acpi/ac_adapter");
260 while ((de=readdir(d)) != NULL) {
261 if (!strncmp(".", de->d_name, 1))
263 snprintf(fname, 80, "/proc/acpi/ac_adapter/%s/state",
265 f = fopen(fname, "r");
268 if (fscanf(f, "%s %s", tmp2, tmp) != 2)
271 if (strncmp(tmp, "off-line", 8) == 0) {
282 * This routine checks to see if a filesystem can be skipped; if so,
283 * it will exit with E2FSCK_OK. Under some conditions it will print a
284 * message explaining why a check is being forced.
286 static void check_if_skip(e2fsck_t ctx)
288 ext2_filsys fs = ctx->fs;
289 const char *reason = NULL;
290 unsigned int reason_arg = 0;
292 int batt = is_on_batt();
293 int defer_check_on_battery;
296 profile_get_boolean(ctx->profile, "options",
297 "defer_check_on_battery", 0, 1,
298 &defer_check_on_battery);
299 if (!defer_check_on_battery)
302 if ((ctx->options & E2F_OPT_FORCE) || bad_blocks_file || cflag)
305 lastcheck = fs->super->s_lastcheck;
306 if (lastcheck > ctx->now)
307 lastcheck -= ctx->time_fudge;
308 if ((fs->super->s_state & EXT2_ERROR_FS) ||
309 !ext2fs_test_valid(fs))
310 reason = _(" contains a file system with errors");
311 else if ((fs->super->s_state & EXT2_VALID_FS) == 0)
312 reason = _(" was not cleanly unmounted");
313 else if (check_backup_super_block(ctx))
314 reason = _(" primary superblock features different from backup");
315 else if ((fs->super->s_max_mnt_count > 0) &&
316 (fs->super->s_mnt_count >=
317 (unsigned) fs->super->s_max_mnt_count)) {
318 reason = _(" has been mounted %u times without being checked");
319 reason_arg = fs->super->s_mnt_count;
320 if (batt && (fs->super->s_mnt_count <
321 (unsigned) fs->super->s_max_mnt_count*2))
323 } else if (fs->super->s_checkinterval && (ctx->now < lastcheck)) {
324 reason = _(" has filesystem last checked time in the future");
327 } else if (fs->super->s_checkinterval &&
328 ((ctx->now - lastcheck) >=
329 ((time_t) fs->super->s_checkinterval))) {
330 reason = _(" has gone %u days without being checked");
331 reason_arg = (ctx->now - fs->super->s_lastcheck)/(3600*24);
332 if (batt && ((ctx->now - fs->super->s_lastcheck) <
333 fs->super->s_checkinterval*2))
337 fputs(ctx->device_name, stdout);
338 printf(reason, reason_arg);
339 fputs(_(", check forced.\n"), stdout);
342 printf(_("%s: clean, %u/%u files, %llu/%llu blocks"), ctx->device_name,
343 fs->super->s_inodes_count - fs->super->s_free_inodes_count,
344 fs->super->s_inodes_count,
345 ext2fs_blocks_count(fs->super) -
346 ext2fs_free_blocks_count(fs->super),
347 ext2fs_blocks_count(fs->super));
349 if (fs->super->s_max_mnt_count > 0) {
350 next_check = fs->super->s_max_mnt_count - fs->super->s_mnt_count;
354 if (fs->super->s_checkinterval &&
355 ((ctx->now - fs->super->s_lastcheck) >= fs->super->s_checkinterval))
357 if (next_check <= 5) {
358 if (next_check == 1) {
360 fputs(_(" (check deferred; on battery)"),
363 fputs(_(" (check after next mount)"), stdout);
365 printf(_(" (check in %ld mounts)"), next_check);
370 e2fsck_free_context(ctx);
375 * For completion notice
381 struct percent_tbl e2fsck_tbl = {
382 5, { 0, 70, 90, 92, 95, 100 }
384 static char bar[128], spaces[128];
386 static float calc_percent(struct percent_tbl *tbl, int pass, int curr,
393 if (pass > tbl->max_pass || max == 0)
395 percent = ((float) curr) / ((float) max);
396 return ((percent * (tbl->table[pass] - tbl->table[pass-1]))
397 + tbl->table[pass-1]);
400 extern void e2fsck_clear_progbar(e2fsck_t ctx)
402 if (!(ctx->flags & E2F_FLAG_PROG_BAR))
405 printf("%s%s\r%s", ctx->start_meta, spaces + (sizeof(spaces) - 80),
408 ctx->flags &= ~E2F_FLAG_PROG_BAR;
411 int e2fsck_simple_progress(e2fsck_t ctx, const char *label, float percent,
414 static const char spinner[] = "\\|/-";
421 if (ctx->flags & E2F_FLAG_PROG_SUPPRESS)
425 * Calculate the new progress position. If the
426 * percentage hasn't changed, then we skip out right
429 fixed_percent = (int) ((10 * percent) + 0.5);
430 if (ctx->progress_last_percent == fixed_percent)
432 ctx->progress_last_percent = fixed_percent;
435 * If we've already updated the spinner once within
436 * the last 1/8th of a second, no point doing it
439 gettimeofday(&tv, NULL);
440 tick = (tv.tv_sec << 3) + (tv.tv_usec / (1000000 / 8));
441 if ((tick == ctx->progress_last_time) &&
442 (fixed_percent != 0) && (fixed_percent != 1000))
444 ctx->progress_last_time = tick;
447 * Advance the spinner, and note that the progress bar
448 * will be on the screen
450 ctx->progress_pos = (ctx->progress_pos+1) & 3;
451 ctx->flags |= E2F_FLAG_PROG_BAR;
453 dpywidth = 66 - strlen(label);
454 dpywidth = 8 * (dpywidth / 8);
458 i = ((percent * dpywidth) + 50) / 100;
459 printf("%s%s: |%s%s", ctx->start_meta, label,
460 bar + (sizeof(bar) - (i+1)),
461 spaces + (sizeof(spaces) - (dpywidth - i + 1)));
462 if (fixed_percent == 1000)
465 fputc(spinner[ctx->progress_pos & 3], stdout);
466 printf(" %4.1f%% ", percent);
468 printf("%u\r", dpynum);
470 fputs(" \r", stdout);
471 fputs(ctx->stop_meta, stdout);
473 if (fixed_percent == 1000)
474 e2fsck_clear_progbar(ctx);
480 static int e2fsck_update_progress(e2fsck_t ctx, int pass,
481 unsigned long cur, unsigned long max)
489 if (ctx->progress_fd) {
490 snprintf(buf, sizeof(buf), "%d %lu %lu %s\n",
491 pass, cur, max, ctx->device_name);
492 write_all(ctx->progress_fd, buf, strlen(buf));
494 percent = calc_percent(&e2fsck_tbl, pass, cur, max);
495 e2fsck_simple_progress(ctx, ctx->device_name,
501 #define PATH_SET "PATH=/sbin"
503 static void reserve_stdio_fds(void)
508 fd = open("/dev/null", O_RDWR);
512 fprintf(stderr, _("ERROR: Couldn't open "
522 static void signal_progress_on(int sig EXT2FS_ATTR((unused)))
524 e2fsck_t ctx = e2fsck_global_ctx;
529 ctx->progress = e2fsck_update_progress;
532 static void signal_progress_off(int sig EXT2FS_ATTR((unused)))
534 e2fsck_t ctx = e2fsck_global_ctx;
539 e2fsck_clear_progbar(ctx);
543 static void signal_cancel(int sig EXT2FS_ATTR((unused)))
545 e2fsck_t ctx = e2fsck_global_ctx;
550 ctx->flags |= E2F_FLAG_CANCEL;
554 static void parse_extended_opts(e2fsck_t ctx, const char *opts)
556 char *buf, *token, *next, *p, *arg;
558 int extended_usage = 0;
560 buf = string_copy(ctx, opts, 0);
561 for (token = buf; token && *token; token = next) {
562 p = strchr(token, ',');
568 arg = strchr(token, '=');
573 if (strcmp(token, "ea_ver") == 0) {
578 ea_ver = strtoul(arg, &p, 0);
580 ((ea_ver != 1) && (ea_ver != 2))) {
582 _("Invalid EA version.\n"));
586 ctx->ext_attr_ver = ea_ver;
587 } else if (strcmp(token, "fragcheck") == 0) {
588 ctx->options |= E2F_OPT_FRAGCHECK;
591 fprintf(stderr, _("Unknown extended option: %s\n"),
598 if (extended_usage) {
599 fputs(("\nExtended options are separated by commas, "
600 "and may take an argument which\n"
601 "is set off by an equals ('=') sign. "
602 "Valid extended options are:\n"), stderr);
603 fputs(("\tea_ver=<ea_version (1 or 2)>\n"), stderr);
604 fputs(("\tfragcheck\n"), stderr);
610 static void syntax_err_report(const char *filename, long err, int line_num)
613 _("Syntax error in e2fsck config file (%s, line #%d)\n\t%s\n"),
614 filename, line_num, error_message(err));
618 static const char *config_fn[] = { ROOT_SYSCONFDIR "/e2fsck.conf", 0 };
620 static errcode_t PRS(int argc, char *argv[], e2fsck_t *ret_ctx)
625 extern void *mallwatch;
632 char *extended_opts = 0;
634 int res; /* result of sscanf */
635 #ifdef CONFIG_JBD_DEBUG
639 retval = e2fsck_allocate_context(&ctx);
645 setvbuf(stdout, NULL, _IONBF, BUFSIZ);
646 setvbuf(stderr, NULL, _IONBF, BUFSIZ);
647 if (isatty(0) && isatty(1)) {
648 ctx->interactive = 1;
650 ctx->start_meta[0] = '\001';
651 ctx->stop_meta[0] = '\002';
653 memset(bar, '=', sizeof(bar)-1);
654 memset(spaces, ' ', sizeof(spaces)-1);
655 add_error_table(&et_ext2_error_table);
656 add_error_table(&et_prof_error_table);
657 blkid_get_cache(&ctx->blkid, NULL);
660 ctx->program_name = *argv;
662 ctx->program_name = "e2fsck";
663 while ((c = getopt (argc, argv, "panyrcC:B:dE:fvtFVM:b:I:j:P:l:L:N:SsDk")) != EOF)
666 ctx->progress = e2fsck_update_progress;
667 res = sscanf(optarg, "%d", &ctx->progress_fd);
671 if (ctx->progress_fd < 0) {
673 ctx->progress_fd = ctx->progress_fd * -1;
675 if (!ctx->progress_fd)
677 /* Validate the file descriptor to avoid disasters */
678 fd = dup(ctx->progress_fd);
681 _("Error validating file descriptor %d: %s\n"),
683 error_message(errno));
685 _("Invalid completion information file descriptor"));
690 ctx->options |= E2F_OPT_COMPRESS_DIRS;
693 extended_opts = optarg;
697 if (ctx->options & (E2F_OPT_YES|E2F_OPT_NO)) {
700 _("Only one of the options -p/-a, -n or -y may be specified."));
702 ctx->options |= E2F_OPT_PREEN;
705 if (ctx->options & (E2F_OPT_YES|E2F_OPT_PREEN))
707 ctx->options |= E2F_OPT_NO;
710 if (ctx->options & (E2F_OPT_PREEN|E2F_OPT_NO))
712 ctx->options |= E2F_OPT_YES;
715 #ifdef RESOURCE_TRACK
716 if (ctx->options & E2F_OPT_TIME)
717 ctx->options |= E2F_OPT_TIME2;
719 ctx->options |= E2F_OPT_TIME;
721 fprintf(stderr, _("The -t option is not "
722 "supported on this version of e2fsck.\n"));
727 ctx->options |= E2F_OPT_WRITECHECK;
728 ctx->options |= E2F_OPT_CHECKBLOCKS;
731 /* What we do by default, anyway! */
734 res = sscanf(optarg, "%u", &ctx->use_superblock);
737 ctx->flags |= E2F_FLAG_SB_SPECIFIED;
740 ctx->blocksize = atoi(optarg);
743 res = sscanf(optarg, "%d", &ctx->inode_buffer_blocks);
748 ctx->journal_name = string_copy(ctx, optarg, 0);
751 res = sscanf(optarg, "%d", &ctx->process_inode_size);
756 replace_bad_blocks++;
758 bad_blocks_file = string_copy(ctx, optarg, 0);
761 ctx->options |= E2F_OPT_DEBUG;
764 ctx->options |= E2F_OPT_FORCE;
773 show_version_only = 1;
777 mallwatch = (void *) strtol(optarg, NULL, 0);
781 ctx->device_name = string_copy(ctx, optarg, 0);
789 if (show_version_only)
791 if (optind != argc - 1)
793 if ((ctx->options & E2F_OPT_NO) &&
794 (ctx->options & E2F_OPT_COMPRESS_DIRS)) {
795 com_err(ctx->program_name, 0,
796 _("The -n and -D options are incompatible."));
799 if ((ctx->options & E2F_OPT_NO) && cflag) {
800 com_err(ctx->program_name, 0,
801 _("The -n and -c options are incompatible."));
804 if ((ctx->options & E2F_OPT_NO) && bad_blocks_file) {
805 com_err(ctx->program_name, 0,
806 _("The -n and -l/-L options are incompatible."));
809 if (ctx->options & E2F_OPT_NO)
810 ctx->options |= E2F_OPT_READONLY;
812 ctx->io_options = strchr(argv[optind], '?');
814 *ctx->io_options++ = 0;
815 ctx->filesystem_name = blkid_get_devname(ctx->blkid, argv[optind], 0);
816 if (!ctx->filesystem_name) {
817 com_err(ctx->program_name, 0, _("Unable to resolve '%s'"),
822 parse_extended_opts(ctx, extended_opts);
824 if ((cp = getenv("E2FSCK_CONFIG")) != NULL)
826 profile_set_syntax_err_cb(syntax_err_report);
827 profile_init(config_fn, &ctx->profile);
830 fd = open(ctx->filesystem_name, O_RDONLY, 0);
832 com_err("open", errno,
833 _("while opening %s for flushing"),
834 ctx->filesystem_name);
837 if ((retval = ext2fs_sync_device(fd, 1))) {
838 com_err("ext2fs_sync_device", retval,
839 _("while trying to flush %s"),
840 ctx->filesystem_name);
845 if (cflag && bad_blocks_file) {
846 fprintf(stderr, _("The -c and the -l/-L options may "
847 "not be both used at the same time.\n"));
852 * Set up signal action
854 memset(&sa, 0, sizeof(struct sigaction));
855 sa.sa_handler = signal_cancel;
856 sigaction(SIGINT, &sa, 0);
857 sigaction(SIGTERM, &sa, 0);
859 sa.sa_flags = SA_RESTART;
861 e2fsck_global_ctx = ctx;
862 sa.sa_handler = signal_progress_on;
863 sigaction(SIGUSR1, &sa, 0);
864 sa.sa_handler = signal_progress_off;
865 sigaction(SIGUSR2, &sa, 0);
868 /* Update our PATH to include /sbin if we need to run badblocks */
870 char *oldpath = getenv("PATH");
872 int len = sizeof(PATH_SET) + 1;
875 len += strlen(oldpath);
877 newpath = malloc(len);
879 fatal_error(ctx, "Couldn't malloc() newpath");
880 strcpy(newpath, PATH_SET);
883 strcat(newpath, ":");
884 strcat(newpath, oldpath);
888 #ifdef CONFIG_JBD_DEBUG
889 jbd_debug = getenv("E2FSCK_JBD_DEBUG");
891 res = sscanf(jbd_debug, "%d", &journal_enable_debug);
894 _("E2FSCK_JBD_DEBUG \"%s\" not an integer\n\n"),
903 fprintf(stderr, _("\nInvalid non-numeric argument to -%c (\"%s\")\n\n"),
908 static errcode_t try_open_fs(e2fsck_t ctx, int flags, io_manager io_ptr,
914 if (ctx->superblock && ctx->blocksize) {
915 retval = ext2fs_open2(ctx->filesystem_name, ctx->io_options,
916 flags, ctx->superblock, ctx->blocksize,
918 } else if (ctx->superblock) {
920 for (blocksize = EXT2_MIN_BLOCK_SIZE;
921 blocksize <= EXT2_MAX_BLOCK_SIZE; blocksize *= 2) {
923 ext2fs_free(*ret_fs);
926 retval = ext2fs_open2(ctx->filesystem_name,
927 ctx->io_options, flags,
928 ctx->superblock, blocksize,
934 retval = ext2fs_open2(ctx->filesystem_name, ctx->io_options,
935 flags, 0, 0, io_ptr, ret_fs);
940 static const char *my_ver_string = E2FSPROGS_VERSION;
941 static const char *my_ver_date = E2FSPROGS_DATE;
943 int main (int argc, char *argv[])
945 errcode_t retval = 0, retval2 = 0, orig_retval = 0;
946 int exit_value = FSCK_OK;
949 struct ext2_super_block *sb;
950 const char *lib_ver_date;
953 blk_t orig_superblock;
954 struct problem_context pctx;
955 int flags, run_result;
957 int sysval, sys_page_size = 4096;
962 clear_problem_context(&pctx);
970 setlocale(LC_MESSAGES, "");
971 setlocale(LC_CTYPE, "");
972 bindtextdomain(NLS_CAT_NAME, LOCALEDIR);
973 textdomain(NLS_CAT_NAME);
975 my_ver = ext2fs_parse_version_string(my_ver_string);
976 lib_ver = ext2fs_get_library_version(0, &lib_ver_date);
977 if (my_ver > lib_ver) {
978 fprintf( stderr, _("Error: ext2fs library version "
983 retval = PRS(argc, argv, &ctx);
985 com_err("e2fsck", retval,
986 _("while trying to initialize program"));
991 init_resource_track(&ctx->global_rtrack, NULL);
992 if (!(ctx->options & E2F_OPT_PREEN) || show_version_only)
993 fprintf(stderr, "e2fsck %s (%s)\n", my_ver_string,
996 if (show_version_only) {
997 fprintf(stderr, _("\tUsing %s, %s\n"),
998 error_message(EXT2_ET_BASE), lib_ver_date);
1004 if (!(ctx->options & E2F_OPT_PREEN) &&
1005 !(ctx->options & E2F_OPT_NO) &&
1006 !(ctx->options & E2F_OPT_YES)) {
1007 if (!ctx->interactive)
1009 _("need terminal for interactive repairs"));
1011 ctx->superblock = ctx->use_superblock;
1013 #ifdef CONFIG_TESTIO_DEBUG
1014 if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_BLOCK")) {
1015 io_ptr = test_io_manager;
1016 test_io_backing_manager = unix_io_manager;
1019 io_ptr = unix_io_manager;
1020 flags = EXT2_FLAG_NOFREE_ON_ERROR;
1021 profile_get_boolean(ctx->profile, "options", "old_bitmaps", 0, 0,
1024 flags |= EXT2_FLAG_64BITS;
1025 if ((ctx->options & E2F_OPT_READONLY) == 0)
1026 flags |= EXT2_FLAG_RW;
1027 if ((ctx->mount_flags & EXT2_MF_MOUNTED) == 0)
1028 flags |= EXT2_FLAG_EXCLUSIVE;
1030 retval = try_open_fs(ctx, flags, io_ptr, &fs);
1032 if (!ctx->superblock && !(ctx->options & E2F_OPT_PREEN) &&
1033 !(ctx->flags & E2F_FLAG_SB_SPECIFIED) &&
1034 ((retval == EXT2_ET_BAD_MAGIC) ||
1035 (retval == EXT2_ET_CORRUPT_SUPERBLOCK) ||
1036 ((retval == 0) && (retval2 = ext2fs_check_desc(fs))))) {
1037 if (retval2 == ENOMEM) {
1041 if (fs->flags & EXT2_FLAG_NOFREE_ON_ERROR) {
1045 if (!fs || (fs->group_desc_count > 1)) {
1046 printf(_("%s: %s trying backup blocks...\n"),
1048 retval ? _("Superblock invalid,") :
1049 _("Group descriptors look bad..."));
1050 orig_superblock = ctx->superblock;
1051 get_backup_sb(ctx, fs, ctx->filesystem_name, io_ptr);
1054 orig_retval = retval;
1055 retval = try_open_fs(ctx, flags, io_ptr, &fs);
1056 if ((orig_retval == 0) && retval != 0) {
1057 com_err(ctx->program_name, retval,
1058 "when using the backup blocks");
1059 printf(_("%s: going back to original "
1060 "superblock\n"), ctx->program_name);
1061 ctx->superblock = orig_superblock;
1062 retval = try_open_fs(ctx, flags, io_ptr, &fs);
1066 if (((retval == EXT2_ET_UNSUPP_FEATURE) ||
1067 (retval == EXT2_ET_RO_UNSUPP_FEATURE)) &&
1070 features[0] = (sb->s_feature_compat &
1071 ~EXT2_LIB_FEATURE_COMPAT_SUPP);
1072 features[1] = (sb->s_feature_incompat &
1073 ~EXT2_LIB_FEATURE_INCOMPAT_SUPP);
1074 features[2] = (sb->s_feature_ro_compat &
1075 ~EXT2_LIB_FEATURE_RO_COMPAT_SUPP);
1076 if (features[0] || features[1] || features[2])
1077 goto print_unsupp_features;
1082 retval = orig_retval;
1083 com_err(ctx->program_name, retval, _("while trying to open %s"),
1084 ctx->filesystem_name);
1085 if (retval == EXT2_ET_REV_TOO_HIGH) {
1086 printf(_("The filesystem revision is apparently "
1087 "too high for this version of e2fsck.\n"
1088 "(Or the filesystem superblock "
1089 "is corrupt)\n\n"));
1090 fix_problem(ctx, PR_0_SB_CORRUPT, &pctx);
1091 } else if (retval == EXT2_ET_SHORT_READ)
1092 printf(_("Could this be a zero-length partition?\n"));
1093 else if ((retval == EPERM) || (retval == EACCES))
1094 printf(_("You must have %s access to the "
1095 "filesystem or be root\n"),
1096 (ctx->options & E2F_OPT_READONLY) ?
1098 else if (retval == ENXIO)
1099 printf(_("Possibly non-existent or swap device?\n"));
1100 else if (retval == EBUSY)
1101 printf(_("Filesystem mounted or opened exclusively "
1102 "by another program?\n"));
1104 else if (retval == EROFS)
1105 printf(_("Disk write-protected; use the -n option "
1106 "to do a read-only\n"
1107 "check of the device.\n"));
1110 fix_problem(ctx, PR_0_SB_CORRUPT, &pctx);
1111 fatal_error(ctx, 0);
1114 * We only update the master superblock because (a) paranoia;
1115 * we don't want to corrupt the backup superblocks, and (b) we
1116 * don't need to update the mount count and last checked
1117 * fields in the backup superblock (the kernel doesn't update
1118 * the backup superblocks anyway). With newer versions of the
1119 * library this flag is set by ext2fs_open2(), but we set this
1120 * here just to be sure. (No, we don't support e2fsck running
1121 * with some other libext2fs than the one that it was shipped
1122 * with, but just in case....)
1124 fs->flags |= EXT2_FLAG_MASTER_SB_ONLY;
1126 if (!(ctx->flags & E2F_FLAG_GOT_DEVSIZE)) {
1127 __u32 blocksize = EXT2_BLOCK_SIZE(fs->super);
1128 int need_restart = 0;
1130 pctx.errcode = ext2fs_get_device_size2(ctx->filesystem_name,
1134 * The floppy driver refuses to allow anyone else to
1135 * open the device if has been opened with O_EXCL;
1136 * this is unlike other block device drivers in Linux.
1137 * To handle this, we close the filesystem and then
1138 * reopen the filesystem after we get the device size.
1140 if (pctx.errcode == EBUSY) {
1144 ext2fs_get_device_size2(ctx->filesystem_name,
1148 if (pctx.errcode == EXT2_ET_UNIMPLEMENTED)
1149 ctx->num_blocks = 0;
1150 else if (pctx.errcode) {
1151 fix_problem(ctx, PR_0_GETSIZE_ERROR, &pctx);
1152 ctx->flags |= E2F_FLAG_ABORT;
1153 fatal_error(ctx, 0);
1155 ctx->flags |= E2F_FLAG_GOT_DEVSIZE;
1161 fs->priv_data = ctx;
1164 if (sb->s_rev_level > E2FSCK_CURRENT_REV) {
1165 com_err(ctx->program_name, EXT2_ET_REV_TOO_HIGH,
1166 _("while trying to open %s"),
1167 ctx->filesystem_name);
1169 fatal_error(ctx, _("Get a newer version of e2fsck!"));
1173 * Set the device name, which is used whenever we print error
1174 * or informational messages to the user.
1176 if (ctx->device_name == 0 &&
1177 (sb->s_volume_name[0] != 0)) {
1178 ctx->device_name = string_copy(ctx, sb->s_volume_name,
1179 sizeof(sb->s_volume_name));
1181 if (ctx->device_name == 0)
1182 ctx->device_name = string_copy(ctx, ctx->filesystem_name, 0);
1183 for (cp = ctx->device_name; *cp; cp++)
1184 if (isspace(*cp) || *cp == ':')
1187 ehandler_init(fs->io);
1189 if ((ctx->mount_flags & EXT2_MF_MOUNTED) &&
1190 !(sb->s_feature_incompat & EXT3_FEATURE_INCOMPAT_RECOVER))
1194 * Make sure the ext3 superblock fields are consistent.
1196 retval = e2fsck_check_ext3_journal(ctx);
1198 com_err(ctx->program_name, retval,
1199 _("while checking ext3 journal for %s"),
1201 fatal_error(ctx, 0);
1205 * Check to see if we need to do ext3-style recovery. If so,
1206 * do it, and then restart the fsck.
1208 if (sb->s_feature_incompat & EXT3_FEATURE_INCOMPAT_RECOVER) {
1209 if (ctx->options & E2F_OPT_READONLY) {
1210 printf(_("Warning: skipping journal recovery "
1211 "because doing a read-only filesystem "
1213 io_channel_flush(ctx->fs->io);
1215 if (ctx->flags & E2F_FLAG_RESTARTED) {
1217 * Whoops, we attempted to run the
1218 * journal twice. This should never
1219 * happen, unless the hardware or
1220 * device driver is being bogus.
1222 com_err(ctx->program_name, 0,
1223 _("unable to set superblock flags on %s\n"), ctx->device_name);
1224 fatal_error(ctx, 0);
1226 retval = e2fsck_run_ext3_journal(ctx);
1228 com_err(ctx->program_name, retval,
1229 _("while recovering ext3 journal of %s"),
1231 fatal_error(ctx, 0);
1233 ext2fs_close(ctx->fs);
1235 ctx->flags |= E2F_FLAG_RESTARTED;
1242 * Check for compatibility with the feature sets. We need to
1243 * be more stringent than ext2fs_open().
1245 features[0] = sb->s_feature_compat & ~EXT2_LIB_FEATURE_COMPAT_SUPP;
1246 features[1] = sb->s_feature_incompat & ~EXT2_LIB_FEATURE_INCOMPAT_SUPP;
1247 features[2] = (sb->s_feature_ro_compat &
1248 ~EXT2_LIB_FEATURE_RO_COMPAT_SUPP);
1249 print_unsupp_features:
1250 if (features[0] || features[1] || features[2]) {
1252 __u32 *mask = features, m;
1254 fprintf(stderr, _("%s has unsupported feature(s):"),
1255 ctx->filesystem_name);
1257 for (i=0; i <3; i++,mask++) {
1258 for (j=0,m=1; j < 32; j++, m<<=1) {
1260 fprintf(stderr, " %s",
1261 e2p_feature2string(i, m));
1267 #ifdef ENABLE_COMPRESSION
1268 if (sb->s_feature_incompat & EXT2_FEATURE_INCOMPAT_COMPRESSION)
1269 com_err(ctx->program_name, 0,
1270 _("Warning: compression support is experimental.\n"));
1272 #ifndef ENABLE_HTREE
1273 if (sb->s_feature_compat & EXT2_FEATURE_COMPAT_DIR_INDEX) {
1274 com_err(ctx->program_name, 0,
1275 _("E2fsck not compiled with HTREE support,\n\t"
1276 "but filesystem %s has HTREE directories.\n"),
1283 * If the user specified a specific superblock, presumably the
1284 * master superblock has been trashed. So we mark the
1285 * superblock as dirty, so it can be written out.
1287 if (ctx->superblock &&
1288 !(ctx->options & E2F_OPT_READONLY))
1289 ext2fs_mark_super_dirty(fs);
1292 * Calculate the number of filesystem blocks per pagesize. If
1293 * fs->blocksize > page_size, set the number of blocks per
1294 * pagesize to 1 to avoid division by zero errors.
1297 sysval = sysconf(_SC_PAGESIZE);
1299 sys_page_size = sysval;
1300 #endif /* _SC_PAGESIZE */
1301 ctx->blocks_per_page = sys_page_size / fs->blocksize;
1302 if (ctx->blocks_per_page == 0)
1303 ctx->blocks_per_page = 1;
1305 if (ctx->superblock)
1306 set_latch_flags(PR_LATCH_RELOC, PRL_LATCHED, 0);
1307 ext2fs_mark_valid(fs);
1308 check_super_block(ctx);
1309 if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
1310 fatal_error(ctx, 0);
1312 check_resize_inode(ctx);
1313 if (bad_blocks_file)
1314 read_bad_blocks_file(ctx, bad_blocks_file, replace_bad_blocks);
1316 read_bad_blocks_file(ctx, 0, !keep_bad_blocks); /* Test disk */
1317 if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
1318 fatal_error(ctx, 0);
1321 * Mark the system as valid, 'til proven otherwise
1323 ext2fs_mark_valid(fs);
1325 retval = ext2fs_read_bb_inode(fs, &fs->badblocks);
1327 com_err(ctx->program_name, retval,
1328 _("while reading bad blocks inode"));
1330 printf(_("This doesn't bode well,"
1331 " but we'll try to go on...\n"));
1335 * Save the journal size in megabytes.
1336 * Try and use the journal size from the backup else let e2fsck
1337 * find the default journal size.
1339 if (sb->s_jnl_backup_type == EXT3_JNL_BACKUP_BLOCKS)
1340 journal_size = sb->s_jnl_blocks[16] >> 20;
1344 run_result = e2fsck_run(ctx);
1345 e2fsck_clear_progbar(ctx);
1347 if (ctx->flags & E2F_FLAG_JOURNAL_INODE) {
1348 if (fix_problem(ctx, PR_6_RECREATE_JOURNAL, &pctx)) {
1349 if (journal_size < 1024)
1350 journal_size = ext2fs_default_journal_size(ext2fs_blocks_count(fs->super));
1351 if (journal_size < 0) {
1352 fs->super->s_feature_compat &=
1353 ~EXT3_FEATURE_COMPAT_HAS_JOURNAL;
1354 fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
1355 com_err(ctx->program_name, 0,
1356 _("Couldn't determine journal size"));
1359 printf(_("Creating journal (%d blocks): "),
1362 retval = ext2fs_add_journal_inode(fs,
1365 com_err("Error ", retval,
1366 _("\n\twhile trying to create journal"));
1369 printf(_(" Done.\n"));
1370 printf(_("\n*** journal has been re-created - "
1371 "filesystem is now ext3 again ***\n"));
1376 if (run_result == E2F_FLAG_RESTART) {
1377 printf(_("Restarting e2fsck from the beginning...\n"));
1378 retval = e2fsck_reset_context(ctx);
1380 com_err(ctx->program_name, retval,
1381 _("while resetting context"));
1382 fatal_error(ctx, 0);
1387 if (run_result & E2F_FLAG_CANCEL) {
1388 printf(_("%s: e2fsck canceled.\n"), ctx->device_name ?
1389 ctx->device_name : ctx->filesystem_name);
1390 exit_value |= FSCK_CANCELED;
1392 if (run_result & E2F_FLAG_ABORT)
1393 fatal_error(ctx, _("aborted"));
1394 if (check_backup_super_block(ctx)) {
1395 fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
1396 ext2fs_mark_super_dirty(fs);
1400 mtrace_print("Cleanup");
1402 if (ext2fs_test_changed(fs)) {
1403 exit_value |= FSCK_NONDESTRUCT;
1404 if (!(ctx->options & E2F_OPT_PREEN))
1405 printf(_("\n%s: ***** FILE SYSTEM WAS MODIFIED *****\n"),
1407 if (ctx->mount_flags & EXT2_MF_ISROOT) {
1408 printf(_("%s: ***** REBOOT LINUX *****\n"),
1410 exit_value |= FSCK_REBOOT;
1413 if (!ext2fs_test_valid(fs) ||
1414 ((exit_value & FSCK_CANCELED) &&
1415 (sb->s_state & EXT2_ERROR_FS))) {
1416 printf(_("\n%s: ********** WARNING: Filesystem still has "
1417 "errors **********\n\n"), ctx->device_name);
1418 exit_value |= FSCK_UNCORRECTED;
1419 exit_value &= ~FSCK_NONDESTRUCT;
1421 if (exit_value & FSCK_CANCELED) {
1422 int allow_cancellation;
1424 profile_get_boolean(ctx->profile, "options",
1425 "allow_cancellation", 0, 0,
1426 &allow_cancellation);
1427 exit_value &= ~FSCK_NONDESTRUCT;
1428 if (allow_cancellation && ext2fs_test_valid(fs) &&
1429 (sb->s_state & EXT2_VALID_FS) &&
1430 !(sb->s_state & EXT2_ERROR_FS))
1434 if (!(ctx->options & E2F_OPT_READONLY)) {
1435 if (ext2fs_test_valid(fs)) {
1436 if (!(sb->s_state & EXT2_VALID_FS))
1437 exit_value |= FSCK_NONDESTRUCT;
1438 sb->s_state = EXT2_VALID_FS;
1440 sb->s_state &= ~EXT2_VALID_FS;
1441 sb->s_mnt_count = 0;
1442 sb->s_lastcheck = ctx->now;
1443 ext2fs_mark_super_dirty(fs);
1447 if (sb->s_feature_ro_compat & EXT4_FEATURE_RO_COMPAT_GDT_CSUM &&
1448 !(ctx->options & E2F_OPT_READONLY)) {
1449 retval = ext2fs_set_gdt_csum(ctx->fs);
1451 com_err(ctx->program_name, retval,
1452 _("while setting block group checksum info"));
1453 fatal_error(ctx, 0);
1457 e2fsck_write_bitmaps(ctx);
1458 io_channel_flush(ctx->fs->io);
1459 print_resource_track(ctx, NULL, &ctx->global_rtrack, ctx->fs->io);
1463 free(ctx->journal_name);
1465 e2fsck_free_context(ctx);
1466 remove_error_table(&et_ext2_error_table);
1467 remove_error_table(&et_prof_error_table);