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 "config.h"
13 #include <stdio.h>
14 #ifdef HAVE_STDLIB_H
15 #include <stdlib.h>
16 #endif
17 #include <string.h>
18 #include <fcntl.h>
19 #include <ctype.h>
20 #include <time.h>
21 #ifdef HAVE_SIGNAL_H
22 #include <signal.h>
23 #endif
24 #ifdef HAVE_GETOPT_H
25 #include <getopt.h>
26 #else
27 extern char *optarg;
28 extern int optind;
29 #endif
30 #include <unistd.h>
31 #ifdef HAVE_ERRNO_H
32 #include <errno.h>
33 #endif
34 #ifdef HAVE_SYS_IOCTL_H
35 #include <sys/ioctl.h>
36 #endif
37 #ifdef HAVE_MALLOC_H
38 #include <stdlib.h>
39 #endif
40 #ifdef HAVE_SYS_TYPES_H
41 #include <sys/types.h>
42 #endif
43 #ifdef HAVE_DIRENT_H
44 #include <dirent.h>
45 #endif
46 #include <libgen.h>
47 
48 #include "e2p/e2p.h"
49 #include "et/com_err.h"
50 #include "e2p/e2p.h"
51 #include "uuid/uuid.h"
52 #include "support/plausible.h"
53 #include "e2fsck.h"
54 #include "problem.h"
55 #include "jfs_user.h"
56 #include "../version.h"
57 
58 /* Command line options */
59 static int cflag;		/* check disk */
60 static int show_version_only;
61 static int verbose;
62 
63 static int replace_bad_blocks;
64 static int keep_bad_blocks;
65 static char *bad_blocks_file;
66 
67 e2fsck_t e2fsck_global_ctx;	/* Try your very best not to use this! */
68 
69 #ifdef CONFIG_JBD_DEBUG		/* Enabled by configure --enable-jbd-debug */
70 int journal_enable_debug = -1;
71 #endif
72 
73 static void usage(e2fsck_t ctx)
74 {
75 	fprintf(stderr,
76 		_("Usage: %s [-panyrcdfktvDFV] [-b superblock] [-B blocksize]\n"
77 		"\t\t[-l|-L bad_blocks_file] [-C fd] [-j external_journal]\n"
78 		"\t\t[-E extended-options] [-z undo_file] device\n"),
79 		ctx->program_name);
80 
81 	fprintf(stderr, "%s", _("\nEmergency help:\n"
82 		" -p                   Automatic repair (no questions)\n"
83 		" -n                   Make no changes to the filesystem\n"
84 		" -y                   Assume \"yes\" to all questions\n"
85 		" -c                   Check for bad blocks and add them to the badblock list\n"
86 		" -f                   Force checking even if filesystem is marked clean\n"));
87 	fprintf(stderr, "%s", _(""
88 		" -v                   Be verbose\n"
89 		" -b superblock        Use alternative superblock\n"
90 		" -B blocksize         Force blocksize when looking for superblock\n"
91 		" -j external_journal  Set location of the external journal\n"
92 		" -l bad_blocks_file   Add to badblocks list\n"
93 		" -L bad_blocks_file   Set badblocks list\n"
94 		" -z undo_file         Create an undo file\n"
95 		));
96 
97 	exit(FSCK_USAGE);
98 }
99 
100 static void show_stats(e2fsck_t	ctx)
101 {
102 	ext2_filsys fs = ctx->fs;
103 	ext2_ino_t inodes, inodes_used;
104 	blk64_t blocks, blocks_used;
105 	unsigned int dir_links;
106 	unsigned int num_files, num_links;
107 	__u32 *mask, m;
108 	int frag_percent_file = 0, frag_percent_dir = 0, frag_percent_total = 0;
109 	int i, j, printed = 0;
110 
111 	dir_links = 2 * ctx->fs_directory_count - 1;
112 	num_files = ctx->fs_total_count - dir_links;
113 	num_links = ctx->fs_links_count - dir_links;
114 	inodes = fs->super->s_inodes_count;
115 	inodes_used = (fs->super->s_inodes_count -
116 		       fs->super->s_free_inodes_count);
117 	blocks = ext2fs_blocks_count(fs->super);
118 	blocks_used = (ext2fs_blocks_count(fs->super) -
119 		       ext2fs_free_blocks_count(fs->super));
120 
121 	if (inodes_used > 0) {
122 		frag_percent_file = (10000 * ctx->fs_fragmented) / inodes_used;
123 		frag_percent_file = (frag_percent_file + 5) / 10;
124 
125 		frag_percent_dir = (10000 * ctx->fs_fragmented_dir) / inodes_used;
126 		frag_percent_dir = (frag_percent_dir + 5) / 10;
127 
128 		frag_percent_total = ((10000 * (ctx->fs_fragmented +
129 						ctx->fs_fragmented_dir))
130 				      / inodes_used);
131 		frag_percent_total = (frag_percent_total + 5) / 10;
132 	}
133 
134 	if (!verbose) {
135 		log_out(ctx, _("%s: %u/%u files (%0d.%d%% non-contiguous), "
136 			       "%llu/%llu blocks\n"),
137 			ctx->device_name, inodes_used, inodes,
138 			frag_percent_total / 10, frag_percent_total % 10,
139 			(unsigned long long) blocks_used,
140 			(unsigned long long) blocks);
141 		return;
142 	}
143 	profile_get_boolean(ctx->profile, "options", "report_features", 0, 0,
144 			    &i);
145 	if (verbose && i) {
146 		log_out(ctx, "\nFilesystem features:");
147 		mask = &ctx->fs->super->s_feature_compat;
148 		for (i = 0; i < 3; i++, mask++) {
149 			for (j = 0, m = 1; j < 32; j++, m <<= 1) {
150 				if (*mask & m) {
151 					log_out(ctx, " %s",
152 						e2p_feature2string(i, m));
153 					printed++;
154 				}
155 			}
156 		}
157 		if (printed == 0)
158 			log_out(ctx, " (none)");
159 		log_out(ctx, "\n");
160 	}
161 
162 	log_out(ctx, P_("\n%12u inode used (%2.2f%%, out of %u)\n",
163 			"\n%12u inodes used (%2.2f%%, out of %u)\n",
164 			inodes_used), inodes_used,
165 		100.0 * inodes_used / inodes, inodes);
166 	log_out(ctx, P_("%12u non-contiguous file (%0d.%d%%)\n",
167 			"%12u non-contiguous files (%0d.%d%%)\n",
168 			ctx->fs_fragmented),
169 		ctx->fs_fragmented, frag_percent_file / 10,
170 		frag_percent_file % 10);
171 	log_out(ctx, P_("%12u non-contiguous directory (%0d.%d%%)\n",
172 			"%12u non-contiguous directories (%0d.%d%%)\n",
173 			ctx->fs_fragmented_dir),
174 		ctx->fs_fragmented_dir, frag_percent_dir / 10,
175 		frag_percent_dir % 10);
176 	log_out(ctx, _("             # of inodes with ind/dind/tind blocks: "
177 		       "%u/%u/%u\n"),
178 		ctx->fs_ind_count, ctx->fs_dind_count, ctx->fs_tind_count);
179 
180 	for (j=MAX_EXTENT_DEPTH_COUNT-1; j >=0; j--)
181 		if (ctx->extent_depth_count[j])
182 			break;
183 	if (++j) {
184 		log_out(ctx, "%s", _("             Extent depth histogram: "));
185 		for (i=0; i < j; i++) {
186 			if (i)
187 				fputc('/', stdout);
188 			log_out(ctx, "%u", ctx->extent_depth_count[i]);
189 		}
190 		log_out(ctx, "\n");
191 	}
192 
193 	log_out(ctx, P_("%12llu block used (%2.2f%%, out of %llu)\n",
194 			"%12llu blocks used (%2.2f%%, out of %llu)\n",
195 		   blocks_used),
196 		(unsigned long long) blocks_used, 100.0 * blocks_used / blocks,
197 		(unsigned long long) blocks);
198 	log_out(ctx, P_("%12u bad block\n", "%12u bad blocks\n",
199 			ctx->fs_badblocks_count), ctx->fs_badblocks_count);
200 	log_out(ctx, P_("%12u large file\n", "%12u large files\n",
201 			ctx->large_files), ctx->large_files);
202 	log_out(ctx, P_("\n%12u regular file\n", "\n%12u regular files\n",
203 			ctx->fs_regular_count), ctx->fs_regular_count);
204 	log_out(ctx, P_("%12u directory\n", "%12u directories\n",
205 			ctx->fs_directory_count), ctx->fs_directory_count);
206 	log_out(ctx, P_("%12u character device file\n",
207 			"%12u character device files\n", ctx->fs_chardev_count),
208 		ctx->fs_chardev_count);
209 	log_out(ctx, P_("%12u block device file\n", "%12u block device files\n",
210 			ctx->fs_blockdev_count), ctx->fs_blockdev_count);
211 	log_out(ctx, P_("%12u fifo\n", "%12u fifos\n", ctx->fs_fifo_count),
212 		ctx->fs_fifo_count);
213 	log_out(ctx, P_("%12u link\n", "%12u links\n", num_links),
214 		ctx->fs_links_count - dir_links);
215 	log_out(ctx, P_("%12u symbolic link", "%12u symbolic links",
216 			ctx->fs_symlinks_count), ctx->fs_symlinks_count);
217 	log_out(ctx, P_(" (%u fast symbolic link)\n",
218 			" (%u fast symbolic links)\n",
219 			ctx->fs_fast_symlinks_count),
220 		ctx->fs_fast_symlinks_count);
221 	log_out(ctx, P_("%12u socket\n", "%12u sockets\n",
222 			ctx->fs_sockets_count),
223 		ctx->fs_sockets_count);
224 	log_out(ctx, "------------\n");
225 	log_out(ctx, P_("%12u file\n", "%12u files\n", num_files),
226 		num_files);
227 }
228 
229 static void check_mount(e2fsck_t ctx)
230 {
231 	errcode_t	retval;
232 	int		cont;
233 
234 	retval = ext2fs_check_if_mounted(ctx->filesystem_name,
235 					 &ctx->mount_flags);
236 	if (retval) {
237 		com_err("ext2fs_check_if_mount", retval,
238 			_("while determining whether %s is mounted."),
239 			ctx->filesystem_name);
240 		return;
241 	}
242 
243 	/*
244 	 * If the filesystem isn't mounted, or it's the root
245 	 * filesystem and it's mounted read-only, and we're not doing
246 	 * a read/write check, then everything's fine.
247 	 */
248 	if ((!(ctx->mount_flags & (EXT2_MF_MOUNTED | EXT2_MF_BUSY))) ||
249 	    ((ctx->mount_flags & EXT2_MF_ISROOT) &&
250 	     (ctx->mount_flags & EXT2_MF_READONLY) &&
251 	     !(ctx->options & E2F_OPT_WRITECHECK)))
252 		return;
253 
254 	if (((ctx->options & E2F_OPT_READONLY) ||
255 	     ((ctx->options & E2F_OPT_FORCE) &&
256 	      (ctx->mount_flags & EXT2_MF_READONLY))) &&
257 	    !(ctx->options & E2F_OPT_WRITECHECK)) {
258 		if (ctx->mount_flags & EXT2_MF_MOUNTED)
259 			log_out(ctx, _("Warning!  %s is mounted.\n"),
260 					ctx->filesystem_name);
261 		else
262 			log_out(ctx, _("Warning!  %s is in use.\n"),
263 					ctx->filesystem_name);
264 		return;
265 	}
266 
267 	if (ctx->mount_flags & EXT2_MF_MOUNTED)
268 		log_out(ctx, _("%s is mounted.\n"), ctx->filesystem_name);
269 	else
270 		log_out(ctx, _("%s is in use.\n"), ctx->filesystem_name);
271 	if (!ctx->interactive || ctx->mount_flags & EXT2_MF_BUSY)
272 		fatal_error(ctx, _("Cannot continue, aborting.\n\n"));
273 	puts("\007\007\007\007");
274 	log_out(ctx, "%s", _("\n\nWARNING!!!  "
275 		       "The filesystem is mounted.   "
276 		       "If you continue you ***WILL***\n"
277 		       "cause ***SEVERE*** filesystem damage.\n\n"));
278 	puts("\007\007\007");
279 	cont = ask_yn(ctx, _("Do you really want to continue"), 0);
280 	if (!cont) {
281 		printf("%s", _("check aborted.\n"));
282 		exit (0);
283 	}
284 	return;
285 }
286 
287 static int is_on_batt(void)
288 {
289 	FILE	*f;
290 	DIR	*d;
291 	char	tmp[80], tmp2[80], fname[NAME_MAX+30];
292 	unsigned int	acflag;
293 	struct dirent*	de;
294 
295 	f = fopen("/sys/class/power_supply/AC/online", "r");
296 	if (f) {
297 		if (fscanf(f, "%u\n", &acflag) == 1) {
298 			fclose(f);
299 			return (!acflag);
300 		}
301 		fclose(f);
302 	}
303 	f = fopen("/proc/apm", "r");
304 	if (f) {
305 		if (fscanf(f, "%79s %79s %79s %x", tmp, tmp, tmp, &acflag) != 4)
306 			acflag = 1;
307 		fclose(f);
308 		return (acflag != 1);
309 	}
310 	d = opendir("/proc/acpi/ac_adapter");
311 	if (d) {
312 		while ((de=readdir(d)) != NULL) {
313 			if (!strncmp(".", de->d_name, 1))
314 				continue;
315 			snprintf(fname, sizeof(fname),
316 				 "/proc/acpi/ac_adapter/%s/state",
317 				 de->d_name);
318 			f = fopen(fname, "r");
319 			if (!f)
320 				continue;
321 			if (fscanf(f, "%79s %79s", tmp2, tmp) != 2)
322 				tmp[0] = 0;
323 			fclose(f);
324 			if (strncmp(tmp, "off-line", 8) == 0) {
325 				closedir(d);
326 				return 1;
327 			}
328 		}
329 		closedir(d);
330 	}
331 	return 0;
332 }
333 
334 /*
335  * This routine checks to see if a filesystem can be skipped; if so,
336  * it will exit with E2FSCK_OK.  Under some conditions it will print a
337  * message explaining why a check is being forced.
338  */
339 static void check_if_skip(e2fsck_t ctx)
340 {
341 	ext2_filsys fs = ctx->fs;
342 	struct problem_context pctx;
343 	const char *reason = NULL;
344 	unsigned int reason_arg = 0;
345 	long next_check;
346 	int batt = is_on_batt();
347 	int defer_check_on_battery;
348 	int broken_system_clock;
349 	time_t lastcheck;
350 
351 	if (ctx->flags & E2F_FLAG_PROBLEMS_FIXED)
352 		return;
353 
354 	profile_get_boolean(ctx->profile, "options", "broken_system_clock",
355 			    0, 0, &broken_system_clock);
356 	if (ctx->flags & E2F_FLAG_TIME_INSANE)
357 		broken_system_clock = 1;
358 	profile_get_boolean(ctx->profile, "options",
359 			    "defer_check_on_battery", 0, 1,
360 			    &defer_check_on_battery);
361 	if (!defer_check_on_battery)
362 		batt = 0;
363 
364 	if ((ctx->options & E2F_OPT_FORCE) || bad_blocks_file || cflag)
365 		return;
366 
367 	if (ctx->options & E2F_OPT_JOURNAL_ONLY)
368 		goto skip;
369 
370 	lastcheck = fs->super->s_lastcheck;
371 	if (lastcheck > ctx->now)
372 		lastcheck -= ctx->time_fudge;
373 	if ((fs->super->s_state & EXT2_ERROR_FS) ||
374 	    !ext2fs_test_valid(fs))
375 		reason = _(" contains a file system with errors");
376 	else if ((fs->super->s_state & EXT2_VALID_FS) == 0)
377 		reason = _(" was not cleanly unmounted");
378 	else if (check_backup_super_block(ctx))
379 		reason = _(" primary superblock features different from backup");
380 	else if ((fs->super->s_max_mnt_count > 0) &&
381 		 (fs->super->s_mnt_count >=
382 		  (unsigned) fs->super->s_max_mnt_count)) {
383 		reason = _(" has been mounted %u times without being checked");
384 		reason_arg = fs->super->s_mnt_count;
385 		if (batt && (fs->super->s_mnt_count <
386 			     (unsigned) fs->super->s_max_mnt_count*2))
387 			reason = 0;
388 	} else if (!broken_system_clock && fs->super->s_checkinterval &&
389 		   (ctx->now < lastcheck)) {
390 		reason = _(" has filesystem last checked time in the future");
391 		if (batt)
392 			reason = 0;
393 	} else if (!broken_system_clock && fs->super->s_checkinterval &&
394 		   ((ctx->now - lastcheck) >=
395 		    ((time_t) fs->super->s_checkinterval))) {
396 		reason = _(" has gone %u days without being checked");
397 		reason_arg = (ctx->now - fs->super->s_lastcheck)/(3600*24);
398 		if (batt && ((ctx->now - fs->super->s_lastcheck) <
399 			     fs->super->s_checkinterval*2))
400 			reason = 0;
401 	} else if (broken_system_clock && fs->super->s_checkinterval) {
402 		log_out(ctx, "%s: ", ctx->device_name);
403 		log_out(ctx, "%s",
404 			_("ignoring check interval, broken_system_clock set\n"));
405 	}
406 
407 	if (reason) {
408 		log_out(ctx, "%s", ctx->device_name);
409 		log_out(ctx, reason, reason_arg);
410 		log_out(ctx, "%s", _(", check forced.\n"));
411 		return;
412 	}
413 
414 	/*
415 	 * Update the global counts from the block group counts.  This
416 	 * is needed since modern kernels don't update the global
417 	 * counts so as to avoid locking the entire file system.  So
418 	 * if the filesystem is not unmounted cleanly, the global
419 	 * counts may not be accurate.  Update them here if we can,
420 	 * for the benefit of users who might examine the file system
421 	 * using dumpe2fs.  (This is for cosmetic reasons only.)
422 	 */
423 	clear_problem_context(&pctx);
424 	pctx.ino = fs->super->s_free_inodes_count;
425 	pctx.ino2 = ctx->free_inodes;
426 	if ((pctx.ino != pctx.ino2) &&
427 	    !(ctx->options & E2F_OPT_READONLY) &&
428 	    fix_problem(ctx, PR_0_FREE_INODE_COUNT, &pctx)) {
429 		fs->super->s_free_inodes_count = ctx->free_inodes;
430 		ext2fs_mark_super_dirty(fs);
431 	}
432 	clear_problem_context(&pctx);
433 	pctx.blk = ext2fs_free_blocks_count(fs->super);
434 	pctx.blk2 = ctx->free_blocks;
435 	if ((pctx.blk != pctx.blk2) &&
436 	    !(ctx->options & E2F_OPT_READONLY) &&
437 	    fix_problem(ctx, PR_0_FREE_BLOCK_COUNT, &pctx)) {
438 		ext2fs_free_blocks_count_set(fs->super, ctx->free_blocks);
439 		ext2fs_mark_super_dirty(fs);
440 	}
441 
442 	/* Print the summary message when we're skipping a full check */
443 	log_out(ctx, _("%s: clean, %u/%u files, %llu/%llu blocks"),
444 		ctx->device_name,
445 		fs->super->s_inodes_count - fs->super->s_free_inodes_count,
446 		fs->super->s_inodes_count,
447 		(unsigned long long) ext2fs_blocks_count(fs->super) -
448 		ext2fs_free_blocks_count(fs->super),
449 		(unsigned long long) ext2fs_blocks_count(fs->super));
450 	next_check = 100000;
451 	if (fs->super->s_max_mnt_count > 0) {
452 		next_check = fs->super->s_max_mnt_count - fs->super->s_mnt_count;
453 		if (next_check <= 0)
454 			next_check = 1;
455 	}
456 	if (!broken_system_clock && fs->super->s_checkinterval &&
457 	    ((ctx->now - fs->super->s_lastcheck) >= fs->super->s_checkinterval))
458 		next_check = 1;
459 	if (next_check <= 5) {
460 		if (next_check == 1) {
461 			if (batt)
462 				log_out(ctx, "%s",
463 					_(" (check deferred; on battery)"));
464 			else
465 				log_out(ctx, "%s",
466 					_(" (check after next mount)"));
467 		} else
468 			log_out(ctx, _(" (check in %ld mounts)"),
469 				next_check);
470 	}
471 	log_out(ctx, "\n");
472 skip:
473 	ext2fs_close_free(&ctx->fs);
474 	e2fsck_free_context(ctx);
475 	exit(FSCK_OK);
476 }
477 
478 /*
479  * For completion notice
480  */
481 struct percent_tbl {
482 	int	max_pass;
483 	int	table[32];
484 };
485 static struct percent_tbl e2fsck_tbl = {
486 	5, { 0, 70, 90, 92,  95, 100 }
487 };
488 static char bar[128], spaces[128];
489 
490 static float calc_percent(struct percent_tbl *tbl, int pass, int curr,
491 			  int max)
492 {
493 	float	percent;
494 
495 	if (pass <= 0)
496 		return 0.0;
497 	if (pass > tbl->max_pass || max == 0)
498 		return 100.0;
499 	percent = ((float) curr) / ((float) max);
500 	return ((percent * (tbl->table[pass] - tbl->table[pass-1]))
501 		+ tbl->table[pass-1]);
502 }
503 
504 void e2fsck_clear_progbar(e2fsck_t ctx)
505 {
506 	if (!(ctx->flags & E2F_FLAG_PROG_BAR))
507 		return;
508 
509 	printf("%s%s\r%s", ctx->start_meta, spaces + (sizeof(spaces) - 80),
510 	       ctx->stop_meta);
511 	fflush(stdout);
512 	ctx->flags &= ~E2F_FLAG_PROG_BAR;
513 }
514 
515 int e2fsck_simple_progress(e2fsck_t ctx, const char *label, float percent,
516 			   unsigned int dpynum)
517 {
518 	static const char spinner[] = "\\|/-";
519 	int	i;
520 	unsigned int	tick;
521 	struct timeval	tv;
522 	int dpywidth;
523 	int fixed_percent;
524 
525 	if (ctx->flags & E2F_FLAG_PROG_SUPPRESS)
526 		return 0;
527 
528 	/*
529 	 * Calculate the new progress position.  If the
530 	 * percentage hasn't changed, then we skip out right
531 	 * away.
532 	 */
533 	fixed_percent = (int) ((10 * percent) + 0.5);
534 	if (ctx->progress_last_percent == fixed_percent)
535 		return 0;
536 	ctx->progress_last_percent = fixed_percent;
537 
538 	/*
539 	 * If we've already updated the spinner once within
540 	 * the last 1/8th of a second, no point doing it
541 	 * again.
542 	 */
543 	gettimeofday(&tv, NULL);
544 	tick = (tv.tv_sec << 3) + (tv.tv_usec / (1000000 / 8));
545 	if ((tick == ctx->progress_last_time) &&
546 	    (fixed_percent != 0) && (fixed_percent != 1000))
547 		return 0;
548 	ctx->progress_last_time = tick;
549 
550 	/*
551 	 * Advance the spinner, and note that the progress bar
552 	 * will be on the screen
553 	 */
554 	ctx->progress_pos = (ctx->progress_pos+1) & 3;
555 	ctx->flags |= E2F_FLAG_PROG_BAR;
556 
557 	dpywidth = 66 - strlen(label);
558 	dpywidth = 8 * (dpywidth / 8);
559 	if (dpynum)
560 		dpywidth -= 8;
561 
562 	i = ((percent * dpywidth) + 50) / 100;
563 	printf("%s%s: |%s%s", ctx->start_meta, label,
564 	       bar + (sizeof(bar) - (i+1)),
565 	       spaces + (sizeof(spaces) - (dpywidth - i + 1)));
566 	if (fixed_percent == 1000)
567 		fputc('|', stdout);
568 	else
569 		fputc(spinner[ctx->progress_pos & 3], stdout);
570 	printf(" %4.1f%%  ", percent);
571 	if (dpynum)
572 		printf("%u\r", dpynum);
573 	else
574 		fputs(" \r", stdout);
575 	fputs(ctx->stop_meta, stdout);
576 
577 	if (fixed_percent == 1000)
578 		e2fsck_clear_progbar(ctx);
579 	fflush(stdout);
580 
581 	return 0;
582 }
583 
584 static int e2fsck_update_progress(e2fsck_t ctx, int pass,
585 				  unsigned long cur, unsigned long max)
586 {
587 	char buf[1024];
588 	float percent;
589 
590 	if (pass == 0)
591 		return 0;
592 
593 	if (ctx->progress_fd) {
594 		snprintf(buf, sizeof(buf), "%d %lu %lu %s\n",
595 			 pass, cur, max, ctx->device_name);
596 		write_all(ctx->progress_fd, buf, strlen(buf));
597 	} else {
598 		percent = calc_percent(&e2fsck_tbl, pass, cur, max);
599 		e2fsck_simple_progress(ctx, ctx->device_name,
600 				       percent, 0);
601 	}
602 	return 0;
603 }
604 
605 static int e2fsck_progress_once(e2fsck_t ctx, int pass, unsigned long cur, unsigned long max)
606 {
607 	char buf[80];
608 	float percent;
609 
610 	if (pass == 0)
611 		return 0;
612 
613 	percent = calc_percent(&e2fsck_tbl, pass, cur, max);
614 	e2fsck_simple_progress(ctx, ctx->device_name,
615 			percent, 0);
616 
617 	printf("\n");
618 	ctx->progress = 0;
619 	return 0;
620 }
621 
622 
623 #define PATH_SET "PATH=/sbin"
624 
625 /*
626  * Make sure 0,1,2 file descriptors are open, so that we don't open
627  * the filesystem using the same file descriptor as stdout or stderr.
628  */
629 static void reserve_stdio_fds(void)
630 {
631 	int	fd = 0;
632 
633 	while (fd <= 2) {
634 		fd = open("/dev/null", O_RDWR);
635 		if (fd < 0) {
636 			fprintf(stderr, _("ERROR: Couldn't open "
637 				"/dev/null (%s)\n"),
638 				strerror(errno));
639 			return;
640 		}
641 	}
642 	(void) close(fd);
643 }
644 
645 #ifdef HAVE_SIGNAL_H
646 static void signal_progress_on(int sig EXT2FS_ATTR((unused)))
647 {
648 	e2fsck_t ctx = e2fsck_global_ctx;
649 
650 	if (!ctx)
651 		return;
652 
653 	ctx->progress = e2fsck_update_progress;
654 }
655 
656 static void signal_progress_now(int sig EXT2FS_ATTR((unused)))
657 {
658 	e2fsck_t ctx = e2fsck_global_ctx;
659 
660 	if (!ctx)
661 		return;
662 
663 	ctx->progress = e2fsck_progress_once;
664 	ctx->progress_fd = 0;
665 }
666 
667 static void signal_progress_off(int sig EXT2FS_ATTR((unused)))
668 {
669 	e2fsck_t ctx = e2fsck_global_ctx;
670 
671 	if (!ctx)
672 		return;
673 
674 	e2fsck_clear_progbar(ctx);
675 	ctx->progress = 0;
676 }
677 
678 static void signal_cancel(int sig EXT2FS_ATTR((unused)))
679 {
680 	e2fsck_t ctx = e2fsck_global_ctx;
681 
682 	if (!ctx)
683 		exit(FSCK_CANCELED);
684 
685 	ctx->flags |= E2F_FLAG_CANCEL;
686 }
687 #endif
688 
689 static void parse_extended_opts(e2fsck_t ctx, const char *opts)
690 {
691 	char	*buf, *token, *next, *p, *arg;
692 	int	ea_ver;
693 	int	extended_usage = 0;
694 	unsigned long long reada_kb;
695 
696 	buf = string_copy(ctx, opts, 0);
697 	for (token = buf; token && *token; token = next) {
698 		p = strchr(token, ',');
699 		next = 0;
700 		if (p) {
701 			*p = 0;
702 			next = p+1;
703 		}
704 		arg = strchr(token, '=');
705 		if (arg) {
706 			*arg = 0;
707 			arg++;
708 		}
709 		if (strcmp(token, "ea_ver") == 0) {
710 			if (!arg) {
711 				extended_usage++;
712 				continue;
713 			}
714 			ea_ver = strtoul(arg, &p, 0);
715 			if (*p ||
716 			    ((ea_ver != 1) && (ea_ver != 2))) {
717 				fprintf(stderr, "%s",
718 					_("Invalid EA version.\n"));
719 				extended_usage++;
720 				continue;
721 			}
722 			ctx->ext_attr_ver = ea_ver;
723 		} else if (strcmp(token, "readahead_kb") == 0) {
724 			if (!arg) {
725 				extended_usage++;
726 				continue;
727 			}
728 			reada_kb = strtoull(arg, &p, 0);
729 			if (*p) {
730 				fprintf(stderr, "%s",
731 					_("Invalid readahead buffer size.\n"));
732 				extended_usage++;
733 				continue;
734 			}
735 			ctx->readahead_kb = reada_kb;
736 		} else if (strcmp(token, "fragcheck") == 0) {
737 			ctx->options |= E2F_OPT_FRAGCHECK;
738 			continue;
739 		} else if (strcmp(token, "journal_only") == 0) {
740 			if (arg) {
741 				extended_usage++;
742 				continue;
743 			}
744 			ctx->options |= E2F_OPT_JOURNAL_ONLY;
745 		} else if (strcmp(token, "discard") == 0) {
746 			ctx->options |= E2F_OPT_DISCARD;
747 			continue;
748 		} else if (strcmp(token, "nodiscard") == 0) {
749 			ctx->options &= ~E2F_OPT_DISCARD;
750 			continue;
751 		} else if (strcmp(token, "optimize_extents") == 0) {
752 			ctx->options &= ~E2F_OPT_NOOPT_EXTENTS;
753 			continue;
754 		} else if (strcmp(token, "no_optimize_extents") == 0) {
755 			ctx->options |= E2F_OPT_NOOPT_EXTENTS;
756 			continue;
757 		} else if (strcmp(token, "inode_count_fullmap") == 0) {
758 			ctx->options |= E2F_OPT_ICOUNT_FULLMAP;
759 			continue;
760 		} else if (strcmp(token, "no_inode_count_fullmap") == 0) {
761 			ctx->options &= ~E2F_OPT_ICOUNT_FULLMAP;
762 			continue;
763 		} else if (strcmp(token, "log_filename") == 0) {
764 			if (!arg)
765 				extended_usage++;
766 			else
767 				ctx->log_fn = string_copy(ctx, arg, 0);
768 			continue;
769 		} else if (strcmp(token, "problem_log") == 0) {
770 			if (!arg)
771 				extended_usage++;
772 			else
773 				ctx->problem_log_fn = string_copy(ctx, arg, 0);
774 			continue;
775 		} else if (strcmp(token, "bmap2extent") == 0) {
776 			ctx->options |= E2F_OPT_CONVERT_BMAP;
777 			continue;
778 		} else if (strcmp(token, "fixes_only") == 0) {
779 			ctx->options |= E2F_OPT_FIXES_ONLY;
780 			continue;
781 		} else if (strcmp(token, "unshare_blocks") == 0) {
782 			ctx->options |= E2F_OPT_UNSHARE_BLOCKS;
783 			ctx->options |= E2F_OPT_FORCE;
784 			continue;
785 		} else if (strcmp(token, "check_encoding") == 0) {
786 			ctx->options |= E2F_OPT_CHECK_ENCODING;
787 			continue;
788 #ifdef CONFIG_DEVELOPER_FEATURES
789 		} else if (strcmp(token, "clear_all_uninit_bits") == 0) {
790 			ctx->options |= E2F_OPT_CLEAR_UNINIT;
791 			continue;
792 #endif
793 		} else {
794 			fprintf(stderr, _("Unknown extended option: %s\n"),
795 				token);
796 			extended_usage++;
797 		}
798 	}
799 	free(buf);
800 
801 	if (extended_usage) {
802 		fputs(_("\nExtended options are separated by commas, "
803 		       "and may take an argument which\n"
804 		       "is set off by an equals ('=') sign.  "
805 		       "Valid extended options are:\n\n"), stderr);
806 		fputs(_("\tea_ver=<ea_version (1 or 2)>\n"), stderr);
807 		fputs("\tfragcheck\n", stderr);
808 		fputs("\tjournal_only\n", stderr);
809 		fputs("\tdiscard\n", stderr);
810 		fputs("\tnodiscard\n", stderr);
811 		fputs("\toptimize_extents\n", stderr);
812 		fputs("\tno_optimize_extents\n", stderr);
813 		fputs("\tinode_count_fullmap\n", stderr);
814 		fputs("\tno_inode_count_fullmap\n", stderr);
815 		fputs(_("\treadahead_kb=<buffer size>\n"), stderr);
816 		fputs("\tbmap2extent\n", stderr);
817 		fputs("\tunshare_blocks\n", stderr);
818 		fputs("\tfixes_only\n", stderr);
819 		fputs("\tcheck_encoding\n", stderr);
820 		fputc('\n', stderr);
821 		exit(1);
822 	}
823 }
824 
825 static void syntax_err_report(const char *filename, long err, int line_num)
826 {
827 	fprintf(stderr,
828 		_("Syntax error in e2fsck config file (%s, line #%d)\n\t%s\n"),
829 		filename, line_num, error_message(err));
830 	exit(FSCK_ERROR);
831 }
832 
833 static const char *config_fn[] = { ROOT_SYSCONFDIR "/e2fsck.conf", 0 };
834 
835 static errcode_t PRS(int argc, char *argv[], e2fsck_t *ret_ctx)
836 {
837 	int		flush = 0;
838 	int		c, fd;
839 #ifdef MTRACE
840 	extern void	*mallwatch;
841 #endif
842 	e2fsck_t	ctx;
843 	errcode_t	retval;
844 #ifdef HAVE_SIGNAL_H
845 	struct sigaction	sa;
846 #endif
847 	char		*extended_opts = 0;
848 	char		*cp;
849 	int 		res;		/* result of sscanf */
850 #ifdef CONFIG_JBD_DEBUG
851 	char 		*jbd_debug;
852 #endif
853 	unsigned long long phys_mem_kb, blk;
854 
855 	retval = e2fsck_allocate_context(&ctx);
856 	if (retval)
857 		return retval;
858 
859 	*ret_ctx = ctx;
860 	e2fsck_global_ctx = ctx;
861 
862 	setvbuf(stdout, NULL, _IONBF, BUFSIZ);
863 	setvbuf(stderr, NULL, _IONBF, BUFSIZ);
864 	if (getenv("E2FSCK_FORCE_INTERACTIVE") || (isatty(0) && isatty(1))) {
865 		ctx->interactive = 1;
866 	} else {
867 		ctx->start_meta[0] = '\001';
868 		ctx->stop_meta[0] = '\002';
869 	}
870 	memset(bar, '=', sizeof(bar)-1);
871 	memset(spaces, ' ', sizeof(spaces)-1);
872 	add_error_table(&et_ext2_error_table);
873 	add_error_table(&et_prof_error_table);
874 	blkid_get_cache(&ctx->blkid, NULL);
875 
876 	if (argc && *argv)
877 		ctx->program_name = *argv;
878 	else
879 		ctx->program_name = "e2fsck";
880 
881 	phys_mem_kb = get_memory_size() / 1024;
882 	ctx->readahead_kb = ~0ULL;
883 	while ((c = getopt(argc, argv, "panyrcC:B:dE:fvtFVM:b:I:j:P:l:L:N:SsDkz:")) != EOF)
884 		switch (c) {
885 		case 'C':
886 			ctx->progress = e2fsck_update_progress;
887 			res = sscanf(optarg, "%d", &ctx->progress_fd);
888 			if (res != 1)
889 				goto sscanf_err;
890 
891 			if (ctx->progress_fd < 0) {
892 				ctx->progress = 0;
893 				ctx->progress_fd = ctx->progress_fd * -1;
894 			}
895 			if (!ctx->progress_fd)
896 				break;
897 			/* Validate the file descriptor to avoid disasters */
898 			fd = dup(ctx->progress_fd);
899 			if (fd < 0) {
900 				fprintf(stderr,
901 				_("Error validating file descriptor %d: %s\n"),
902 					ctx->progress_fd,
903 					error_message(errno));
904 				fatal_error(ctx,
905 			_("Invalid completion information file descriptor"));
906 			} else
907 				close(fd);
908 			break;
909 		case 'D':
910 			ctx->options |= E2F_OPT_COMPRESS_DIRS;
911 			break;
912 		case 'E':
913 			extended_opts = optarg;
914 			break;
915 		case 'p':
916 		case 'a':
917 			if (ctx->options & (E2F_OPT_YES|E2F_OPT_NO)) {
918 			conflict_opt:
919 				fatal_error(ctx,
920 	_("Only one of the options -p/-a, -n or -y may be specified."));
921 			}
922 			ctx->options |= E2F_OPT_PREEN;
923 			break;
924 		case 'n':
925 			if (ctx->options & (E2F_OPT_YES|E2F_OPT_PREEN))
926 				goto conflict_opt;
927 			ctx->options |= E2F_OPT_NO;
928 			break;
929 		case 'y':
930 			if (ctx->options & (E2F_OPT_PREEN|E2F_OPT_NO))
931 				goto conflict_opt;
932 			ctx->options |= E2F_OPT_YES;
933 			break;
934 		case 't':
935 #ifdef RESOURCE_TRACK
936 			if (ctx->options & E2F_OPT_TIME)
937 				ctx->options |= E2F_OPT_TIME2;
938 			else
939 				ctx->options |= E2F_OPT_TIME;
940 #else
941 			fprintf(stderr, _("The -t option is not "
942 				"supported on this version of e2fsck.\n"));
943 #endif
944 			break;
945 		case 'c':
946 			if (cflag++)
947 				ctx->options |= E2F_OPT_WRITECHECK;
948 			ctx->options |= E2F_OPT_CHECKBLOCKS;
949 			break;
950 		case 'r':
951 			/* What we do by default, anyway! */
952 			break;
953 		case 'b':
954 			res = sscanf(optarg, "%llu", &blk);
955 			ctx->use_superblock = blk;
956 			if (res != 1)
957 				goto sscanf_err;
958 			ctx->flags |= E2F_FLAG_SB_SPECIFIED;
959 			break;
960 		case 'B':
961 			ctx->blocksize = atoi(optarg);
962 			break;
963 		case 'I':
964 			res = sscanf(optarg, "%d", &ctx->inode_buffer_blocks);
965 			if (res != 1)
966 				goto sscanf_err;
967 			break;
968 		case 'j':
969 			ctx->journal_name = blkid_get_devname(ctx->blkid,
970 							      optarg, NULL);
971 			if (!ctx->journal_name) {
972 				com_err(ctx->program_name, 0,
973 					_("Unable to resolve '%s'"),
974 					optarg);
975 				fatal_error(ctx, 0);
976 			}
977 			break;
978 		case 'P':
979 			res = sscanf(optarg, "%d", &ctx->process_inode_size);
980 			if (res != 1)
981 				goto sscanf_err;
982 			break;
983 		case 'L':
984 			replace_bad_blocks++;
985 			/* fall through */
986 		case 'l':
987 			if (bad_blocks_file)
988 				free(bad_blocks_file);
989 			bad_blocks_file = string_copy(ctx, optarg, 0);
990 			break;
991 		case 'd':
992 			ctx->options |= E2F_OPT_DEBUG;
993 			break;
994 		case 'f':
995 			ctx->options |= E2F_OPT_FORCE;
996 			break;
997 		case 'F':
998 			flush = 1;
999 			break;
1000 		case 'v':
1001 			verbose = 1;
1002 			break;
1003 		case 'V':
1004 			show_version_only = 1;
1005 			break;
1006 #ifdef MTRACE
1007 		case 'M':
1008 			mallwatch = (void *) strtol(optarg, NULL, 0);
1009 			break;
1010 #endif
1011 		case 'N':
1012 			ctx->device_name = string_copy(ctx, optarg, 0);
1013 			break;
1014 		case 'k':
1015 			keep_bad_blocks++;
1016 			break;
1017 		case 'z':
1018 			ctx->undo_file = optarg;
1019 			break;
1020 		default:
1021 			usage(ctx);
1022 		}
1023 	if (show_version_only)
1024 		return 0;
1025 	if (optind != argc - 1)
1026 		usage(ctx);
1027 	if ((ctx->options & E2F_OPT_NO) &&
1028 	    (ctx->options & E2F_OPT_COMPRESS_DIRS)) {
1029 		com_err(ctx->program_name, 0, "%s",
1030 			_("The -n and -D options are incompatible."));
1031 		fatal_error(ctx, 0);
1032 	}
1033 	if ((ctx->options & E2F_OPT_NO) && cflag) {
1034 		com_err(ctx->program_name, 0, "%s",
1035 			_("The -n and -c options are incompatible."));
1036 		fatal_error(ctx, 0);
1037 	}
1038 	if ((ctx->options & E2F_OPT_NO) && bad_blocks_file) {
1039 		com_err(ctx->program_name, 0, "%s",
1040 			_("The -n and -l/-L options are incompatible."));
1041 		fatal_error(ctx, 0);
1042 	}
1043 	if (ctx->options & E2F_OPT_NO)
1044 		ctx->options |= E2F_OPT_READONLY;
1045 
1046 	ctx->io_options = strchr(argv[optind], '?');
1047 	if (ctx->io_options)
1048 		*ctx->io_options++ = 0;
1049 	ctx->filesystem_name = blkid_get_devname(ctx->blkid, argv[optind], 0);
1050 	if (!ctx->filesystem_name) {
1051 		com_err(ctx->program_name, 0, _("Unable to resolve '%s'"),
1052 			argv[optind]);
1053 		fatal_error(ctx, 0);
1054 	}
1055 	if (extended_opts)
1056 		parse_extended_opts(ctx, extended_opts);
1057 
1058 	/* Complain about mutually exclusive rebuilding activities */
1059 	if (getenv("E2FSCK_FIXES_ONLY"))
1060 		ctx->options |= E2F_OPT_FIXES_ONLY;
1061 	if ((ctx->options & E2F_OPT_COMPRESS_DIRS) &&
1062 	    (ctx->options & E2F_OPT_FIXES_ONLY)) {
1063 		com_err(ctx->program_name, 0, "%s",
1064 			_("The -D and -E fixes_only options are incompatible."));
1065 		fatal_error(ctx, 0);
1066 	}
1067 	if ((ctx->options & E2F_OPT_CONVERT_BMAP) &&
1068 	    (ctx->options & E2F_OPT_FIXES_ONLY)) {
1069 		com_err(ctx->program_name, 0, "%s",
1070 			_("The -E bmap2extent and fixes_only options are incompatible."));
1071 		fatal_error(ctx, 0);
1072 	}
1073 
1074 	if ((cp = getenv("E2FSCK_CONFIG")) != NULL)
1075 		config_fn[0] = cp;
1076 	profile_set_syntax_err_cb(syntax_err_report);
1077 	profile_init(config_fn, &ctx->profile);
1078 
1079 	profile_get_boolean(ctx->profile, "options", "report_time", 0, 0,
1080 			    &c);
1081 	if (c)
1082 		ctx->options |= E2F_OPT_TIME | E2F_OPT_TIME2;
1083 	profile_get_boolean(ctx->profile, "options", "report_verbose", 0, 0,
1084 			    &c);
1085 	if (c)
1086 		verbose = 1;
1087 
1088 	profile_get_boolean(ctx->profile, "options", "no_optimize_extents",
1089 			    0, 0, &c);
1090 	if (c)
1091 		ctx->options |= E2F_OPT_NOOPT_EXTENTS;
1092 
1093 	profile_get_boolean(ctx->profile, "options", "inode_count_fullmap",
1094 			    0, 0, &c);
1095 	if (c)
1096 		ctx->options |= E2F_OPT_ICOUNT_FULLMAP;
1097 
1098 	if (ctx->readahead_kb == ~0ULL) {
1099 		profile_get_integer(ctx->profile, "options",
1100 				    "readahead_mem_pct", 0, -1, &c);
1101 		if (c >= 0 && c <= 100)
1102 			ctx->readahead_kb = phys_mem_kb * c / 100;
1103 		profile_get_integer(ctx->profile, "options",
1104 				    "readahead_kb", 0, -1, &c);
1105 		if (c >= 0)
1106 			ctx->readahead_kb = c;
1107 		if (ctx->readahead_kb != ~0ULL &&
1108 		    ctx->readahead_kb > phys_mem_kb)
1109 			ctx->readahead_kb = phys_mem_kb;
1110 	}
1111 
1112 	/* Turn off discard in read-only mode */
1113 	if ((ctx->options & E2F_OPT_NO) &&
1114 	    (ctx->options & E2F_OPT_DISCARD))
1115 		ctx->options &= ~E2F_OPT_DISCARD;
1116 
1117 	if (flush) {
1118 		fd = open(ctx->filesystem_name, O_RDONLY, 0);
1119 		if (fd < 0) {
1120 			com_err("open", errno,
1121 				_("while opening %s for flushing"),
1122 				ctx->filesystem_name);
1123 			fatal_error(ctx, 0);
1124 		}
1125 		if ((retval = ext2fs_sync_device(fd, 1))) {
1126 			com_err("ext2fs_sync_device", retval,
1127 				_("while trying to flush %s"),
1128 				ctx->filesystem_name);
1129 			fatal_error(ctx, 0);
1130 		}
1131 		close(fd);
1132 	}
1133 	if (cflag && bad_blocks_file) {
1134 		fprintf(stderr, "%s", _("The -c and the -l/-L options may not "
1135 					"be both used at the same time.\n"));
1136 		exit(FSCK_USAGE);
1137 	}
1138 #ifdef HAVE_SIGNAL_H
1139 	/*
1140 	 * Set up signal action
1141 	 */
1142 	memset(&sa, 0, sizeof(struct sigaction));
1143 	sa.sa_handler = signal_cancel;
1144 	sigaction(SIGINT, &sa, 0);
1145 	sigaction(SIGTERM, &sa, 0);
1146 #ifdef SA_RESTART
1147 	sa.sa_flags = SA_RESTART;
1148 #endif
1149 	sa.sa_handler = signal_progress_on;
1150 	sigaction(SIGUSR1, &sa, 0);
1151 	sa.sa_handler = signal_progress_off;
1152 	sigaction(SIGUSR2, &sa, 0);
1153 	sa.sa_handler = signal_progress_now;
1154 	if (!getenv("e2fsprogs_inhibit_SIGINFO")) {
1155 		sigaction(SIGINFO, &sa, 0);
1156 	}
1157 #endif
1158 
1159 	/* Update our PATH to include /sbin if we need to run badblocks  */
1160 	if (cflag) {
1161 		char *oldpath = getenv("PATH");
1162 		char *newpath;
1163 		int len = sizeof(PATH_SET) + 1;
1164 
1165 		if (oldpath)
1166 			len += strlen(oldpath);
1167 
1168 		newpath = malloc(len);
1169 		if (!newpath)
1170 			fatal_error(ctx, "Couldn't malloc() newpath");
1171 		strcpy(newpath, PATH_SET);
1172 
1173 		if (oldpath) {
1174 			strcat(newpath, ":");
1175 			strcat(newpath, oldpath);
1176 		}
1177 		putenv(newpath);
1178 	}
1179 #ifdef CONFIG_JBD_DEBUG
1180 	jbd_debug = getenv("E2FSCK_JBD_DEBUG");
1181 	if (jbd_debug) {
1182 		res = sscanf(jbd_debug, "%d", &journal_enable_debug);
1183 		if (res != 1) {
1184 			fprintf(stderr,
1185 			        _("E2FSCK_JBD_DEBUG \"%s\" not an integer\n\n"),
1186 			        jbd_debug);
1187 			exit (1);
1188 		}
1189 	}
1190 #endif
1191 	return 0;
1192 
1193 sscanf_err:
1194 	fprintf(stderr, _("\nInvalid non-numeric argument to -%c (\"%s\")\n\n"),
1195 	        c, optarg);
1196 	exit (1);
1197 }
1198 
1199 static errcode_t try_open_fs(e2fsck_t ctx, int flags, io_manager io_ptr,
1200 			     ext2_filsys *ret_fs)
1201 {
1202 	errcode_t retval;
1203 
1204 	*ret_fs = NULL;
1205 	if (ctx->superblock && ctx->blocksize) {
1206 		retval = ext2fs_open2(ctx->filesystem_name, ctx->io_options,
1207 				      flags, ctx->superblock, ctx->blocksize,
1208 				      io_ptr, ret_fs);
1209 	} else if (ctx->superblock) {
1210 		int blocksize;
1211 		for (blocksize = EXT2_MIN_BLOCK_SIZE;
1212 		     blocksize <= EXT2_MAX_BLOCK_SIZE; blocksize *= 2) {
1213 			if (*ret_fs) {
1214 				ext2fs_free(*ret_fs);
1215 				*ret_fs = NULL;
1216 			}
1217 			retval = ext2fs_open2(ctx->filesystem_name,
1218 					      ctx->io_options, flags,
1219 					      ctx->superblock, blocksize,
1220 					      io_ptr, ret_fs);
1221 			if (!retval)
1222 				break;
1223 		}
1224 	} else
1225 		retval = ext2fs_open2(ctx->filesystem_name, ctx->io_options,
1226 				      flags, 0, 0, io_ptr, ret_fs);
1227 
1228 	if (retval == 0) {
1229 		(*ret_fs)->priv_data = ctx;
1230 		e2fsck_set_bitmap_type(*ret_fs, EXT2FS_BMAP64_RBTREE,
1231 				       "default", NULL);
1232 	}
1233 	return retval;
1234 }
1235 
1236 static const char *my_ver_string = E2FSPROGS_VERSION;
1237 static const char *my_ver_date = E2FSPROGS_DATE;
1238 
1239 static errcode_t e2fsck_check_mmp(ext2_filsys fs, e2fsck_t ctx)
1240 {
1241 	struct mmp_struct *mmp_s;
1242 	unsigned int mmp_check_interval;
1243 	errcode_t retval = 0;
1244 	struct problem_context pctx;
1245 	unsigned int wait_time = 0;
1246 
1247 	clear_problem_context(&pctx);
1248 	if (fs->mmp_buf == NULL) {
1249 		retval = ext2fs_get_mem(fs->blocksize, &fs->mmp_buf);
1250 		if (retval)
1251 			goto check_error;
1252 	}
1253 
1254 	retval = ext2fs_mmp_read(fs, fs->super->s_mmp_block, fs->mmp_buf);
1255 	if (retval)
1256 		goto check_error;
1257 
1258 	mmp_s = fs->mmp_buf;
1259 
1260 	mmp_check_interval = fs->super->s_mmp_update_interval;
1261 	if (mmp_check_interval < EXT4_MMP_MIN_CHECK_INTERVAL)
1262 		mmp_check_interval = EXT4_MMP_MIN_CHECK_INTERVAL;
1263 
1264 	/*
1265 	 * If check_interval in MMP block is larger, use that instead of
1266 	 * check_interval from the superblock.
1267 	 */
1268 	if (mmp_s->mmp_check_interval > mmp_check_interval)
1269 		mmp_check_interval = mmp_s->mmp_check_interval;
1270 
1271 	wait_time = mmp_check_interval * 2 + 1;
1272 
1273 	if (mmp_s->mmp_seq == EXT4_MMP_SEQ_CLEAN)
1274 		retval = 0;
1275 	else if (mmp_s->mmp_seq == EXT4_MMP_SEQ_FSCK)
1276 		retval = EXT2_ET_MMP_FSCK_ON;
1277 	else if (mmp_s->mmp_seq > EXT4_MMP_SEQ_MAX)
1278 		retval = EXT2_ET_MMP_UNKNOWN_SEQ;
1279 
1280 	if (retval)
1281 		goto check_error;
1282 
1283 	/* Print warning if e2fsck will wait for more than 20 secs. */
1284 	if (verbose || wait_time > EXT4_MMP_MIN_CHECK_INTERVAL * 4) {
1285 		log_out(ctx, _("MMP interval is %u seconds and total wait "
1286 			       "time is %u seconds. Please wait...\n"),
1287 			mmp_check_interval, wait_time * 2);
1288 	}
1289 
1290 	return 0;
1291 
1292 check_error:
1293 
1294 	if (retval == EXT2_ET_MMP_BAD_BLOCK) {
1295 		if (fix_problem(ctx, PR_0_MMP_INVALID_BLK, &pctx)) {
1296 			fs->super->s_mmp_block = 0;
1297 			ext2fs_mark_super_dirty(fs);
1298 			retval = 0;
1299 		}
1300 	} else if (retval == EXT2_ET_MMP_FAILED) {
1301 		com_err(ctx->program_name, retval, "%s",
1302 			_("while checking MMP block"));
1303 		dump_mmp_msg(fs->mmp_buf, NULL);
1304 	} else if (retval == EXT2_ET_MMP_FSCK_ON ||
1305 		   retval == EXT2_ET_MMP_UNKNOWN_SEQ) {
1306 		com_err(ctx->program_name, retval, "%s",
1307 			_("while checking MMP block"));
1308 		dump_mmp_msg(fs->mmp_buf,
1309 			     _("If you are sure the filesystem is not "
1310 			       "in use on any node, run:\n"
1311 			       "'tune2fs -f -E clear_mmp %s'\n"),
1312 			     ctx->device_name);
1313 	} else if (retval == EXT2_ET_MMP_MAGIC_INVALID) {
1314 		if (fix_problem(ctx, PR_0_MMP_INVALID_MAGIC, &pctx)) {
1315 			ext2fs_mmp_clear(fs);
1316 			retval = 0;
1317 		}
1318 	} else if (retval == EXT2_ET_MMP_CSUM_INVALID) {
1319 		if (fix_problem(ctx, PR_0_MMP_CSUM_INVALID, &pctx)) {
1320 			ext2fs_mmp_clear(fs);
1321 			retval = 0;
1322 		}
1323 	} else
1324 		com_err(ctx->program_name, retval, "%s",
1325 			_("while reading MMP block"));
1326 	return retval;
1327 }
1328 
1329 static int e2fsck_setup_tdb(e2fsck_t ctx, io_manager *io_ptr)
1330 {
1331 	errcode_t retval = ENOMEM;
1332 	char *tdb_dir = NULL, *tdb_file = NULL;
1333 	char *dev_name, *tmp_name;
1334 	int free_tdb_dir = 0;
1335 
1336 	/* (re)open a specific undo file */
1337 	if (ctx->undo_file && ctx->undo_file[0] != 0) {
1338 		retval = set_undo_io_backing_manager(*io_ptr);
1339 		if (retval)
1340 			goto err;
1341 		*io_ptr = undo_io_manager;
1342 		retval = set_undo_io_backup_file(ctx->undo_file);
1343 		if (retval)
1344 			goto err;
1345 		printf(_("Overwriting existing filesystem; this can be undone "
1346 			 "using the command:\n"
1347 			 "    e2undo %s %s\n\n"),
1348 			ctx->undo_file, ctx->filesystem_name);
1349 		return retval;
1350 	}
1351 
1352 	/*
1353 	 * Configuration via a conf file would be
1354 	 * nice
1355 	 */
1356 	tdb_dir = getenv("E2FSPROGS_UNDO_DIR");
1357 	if (!tdb_dir) {
1358 		profile_get_string(ctx->profile, "defaults",
1359 				   "undo_dir", 0, "/var/lib/e2fsprogs",
1360 				   &tdb_dir);
1361 		free_tdb_dir = 1;
1362 	}
1363 
1364 	if (!strcmp(tdb_dir, "none") || (tdb_dir[0] == 0) ||
1365 	    access(tdb_dir, W_OK)) {
1366 		if (free_tdb_dir)
1367 			free(tdb_dir);
1368 		return 0;
1369 	}
1370 
1371 	tmp_name = strdup(ctx->filesystem_name);
1372 	if (!tmp_name)
1373 		goto errout;
1374 	dev_name = basename(tmp_name);
1375 	tdb_file = malloc(strlen(tdb_dir) + 8 + strlen(dev_name) + 7 + 1);
1376 	if (!tdb_file) {
1377 		free(tmp_name);
1378 		goto errout;
1379 	}
1380 	sprintf(tdb_file, "%s/e2fsck-%s.e2undo", tdb_dir, dev_name);
1381 	free(tmp_name);
1382 
1383 	if ((unlink(tdb_file) < 0) && (errno != ENOENT)) {
1384 		retval = errno;
1385 		com_err(ctx->program_name, retval,
1386 			_("while trying to delete %s"), tdb_file);
1387 		goto errout;
1388 	}
1389 
1390 	retval = set_undo_io_backing_manager(*io_ptr);
1391 	if (retval)
1392 		goto errout;
1393 	*io_ptr = undo_io_manager;
1394 	retval = set_undo_io_backup_file(tdb_file);
1395 	if (retval)
1396 		goto errout;
1397 	printf(_("Overwriting existing filesystem; this can be undone "
1398 		 "using the command:\n"
1399 		 "    e2undo %s %s\n\n"), tdb_file, ctx->filesystem_name);
1400 
1401 	if (free_tdb_dir)
1402 		free(tdb_dir);
1403 	free(tdb_file);
1404 	return 0;
1405 
1406 errout:
1407 	if (free_tdb_dir)
1408 		free(tdb_dir);
1409 	free(tdb_file);
1410 err:
1411 	com_err(ctx->program_name, retval, "%s",
1412 		_("while trying to setup undo file\n"));
1413 	return retval;
1414 }
1415 
1416 int main (int argc, char *argv[])
1417 {
1418 	errcode_t	retval = 0, retval2 = 0, orig_retval = 0;
1419 	int		exit_value = FSCK_OK;
1420 	ext2_filsys	fs = 0;
1421 	io_manager	io_ptr;
1422 	struct ext2_super_block *sb;
1423 	const char	*lib_ver_date;
1424 	int		my_ver, lib_ver;
1425 	e2fsck_t	ctx;
1426 	blk64_t		orig_superblock = ~(blk64_t)0;
1427 	struct problem_context pctx;
1428 	int flags, run_result, was_changed;
1429 	int journal_size;
1430 	int sysval, sys_page_size = 4096;
1431 	int old_bitmaps;
1432 	__u32 features[3];
1433 	char *cp;
1434 	enum quota_type qtype;
1435 	struct ext2fs_journal_params jparams;
1436 
1437 	clear_problem_context(&pctx);
1438 	sigcatcher_setup();
1439 #ifdef MTRACE
1440 	mtrace();
1441 #endif
1442 #ifdef MCHECK
1443 	mcheck(0);
1444 #endif
1445 #ifdef ENABLE_NLS
1446 	setlocale(LC_MESSAGES, "");
1447 	setlocale(LC_CTYPE, "");
1448 	bindtextdomain(NLS_CAT_NAME, LOCALEDIR);
1449 	textdomain(NLS_CAT_NAME);
1450 	set_com_err_gettext(gettext);
1451 #endif
1452 	my_ver = ext2fs_parse_version_string(my_ver_string);
1453 	lib_ver = ext2fs_get_library_version(0, &lib_ver_date);
1454 	if (my_ver > lib_ver) {
1455 		fprintf( stderr, "%s",
1456 			 _("Error: ext2fs library version out of date!\n"));
1457 		show_version_only++;
1458 	}
1459 
1460 	retval = PRS(argc, argv, &ctx);
1461 	if (retval) {
1462 		com_err("e2fsck", retval, "%s",
1463 			_("while trying to initialize program"));
1464 		exit(FSCK_ERROR);
1465 	}
1466 	reserve_stdio_fds();
1467 
1468 	set_up_logging(ctx);
1469 	if (ctx->logf) {
1470 		int i;
1471 
1472 		fputs("E2fsck run: ", ctx->logf);
1473 		for (i = 0; i < argc; i++) {
1474 			if (i)
1475 				fputc(' ', ctx->logf);
1476 			fputs(argv[i], ctx->logf);
1477 		}
1478 		fputc('\n', ctx->logf);
1479 	}
1480 	if (ctx->problem_logf) {
1481 		int i;
1482 
1483 		fputs("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n",
1484 		      ctx->problem_logf);
1485 		fprintf(ctx->problem_logf, "<problem_log time=\"%lu\">\n",
1486 			(unsigned long) ctx->now);
1487 		fprintf(ctx->problem_logf, "<invocation prog=\"%s\"",
1488 			argv[0]);
1489 		for (i = 1; i < argc; i++)
1490 			fprintf(ctx->problem_logf, " arg%d=\"%s\"", i, argv[i]);
1491 		fputs("/>\n", ctx->problem_logf);
1492 	}
1493 
1494 	init_resource_track(&ctx->global_rtrack, NULL);
1495 	if (!(ctx->options & E2F_OPT_PREEN) || show_version_only)
1496 		log_err(ctx, "e2fsck %s (%s)\n", my_ver_string,
1497 			 my_ver_date);
1498 
1499 	if (show_version_only) {
1500 		log_err(ctx, _("\tUsing %s, %s\n"),
1501 			error_message(EXT2_ET_BASE), lib_ver_date);
1502 		exit(FSCK_OK);
1503 	}
1504 
1505 	check_mount(ctx);
1506 
1507 	if (!(ctx->options & E2F_OPT_PREEN) &&
1508 	    !(ctx->options & E2F_OPT_NO) &&
1509 	    !(ctx->options & E2F_OPT_YES)) {
1510 		if (!ctx->interactive)
1511 			fatal_error(ctx,
1512 				    _("need terminal for interactive repairs"));
1513 	}
1514 	ctx->superblock = ctx->use_superblock;
1515 
1516 	flags = EXT2_FLAG_SKIP_MMP | EXT2_FLAG_THREADS;
1517 restart:
1518 #ifdef CONFIG_TESTIO_DEBUG
1519 	if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_BLOCK")) {
1520 		io_ptr = test_io_manager;
1521 		test_io_backing_manager = unix_io_manager;
1522 	} else
1523 #endif
1524 		io_ptr = unix_io_manager;
1525 	flags |= EXT2_FLAG_NOFREE_ON_ERROR;
1526 	profile_get_boolean(ctx->profile, "options", "old_bitmaps", 0, 0,
1527 			    &old_bitmaps);
1528 	if (!old_bitmaps)
1529 		flags |= EXT2_FLAG_64BITS;
1530 	if ((ctx->options & E2F_OPT_READONLY) == 0) {
1531 		flags |= EXT2_FLAG_RW;
1532 		if (!(ctx->mount_flags & EXT2_MF_ISROOT &&
1533 		      ctx->mount_flags & EXT2_MF_READONLY))
1534 			flags |= EXT2_FLAG_EXCLUSIVE;
1535 		if ((ctx->mount_flags & EXT2_MF_READONLY) &&
1536 		    (ctx->options & E2F_OPT_FORCE))
1537 			flags &= ~EXT2_FLAG_EXCLUSIVE;
1538 	}
1539 
1540 	if (ctx->undo_file) {
1541 		retval = e2fsck_setup_tdb(ctx, &io_ptr);
1542 		if (retval)
1543 			exit(FSCK_ERROR);
1544 	}
1545 
1546 	ctx->openfs_flags = flags;
1547 	retval = try_open_fs(ctx, flags, io_ptr, &fs);
1548 
1549 	if (!ctx->superblock && !(ctx->options & E2F_OPT_PREEN) &&
1550 	    !(ctx->flags & E2F_FLAG_SB_SPECIFIED) &&
1551 	    ((retval == EXT2_ET_BAD_MAGIC) ||
1552 	     (retval == EXT2_ET_SB_CSUM_INVALID) ||
1553 	     (retval == EXT2_ET_CORRUPT_SUPERBLOCK) ||
1554 	     ((retval == 0) && (retval2 = ext2fs_check_desc(fs))))) {
1555 		if (retval) {
1556 			pctx.errcode = retval;
1557 			fix_problem(ctx, PR_0_OPEN_FAILED, &pctx);
1558 		}
1559 		if (retval2) {
1560 			pctx.errcode = retval2;
1561 			fix_problem(ctx, PR_0_CHECK_DESC_FAILED, &pctx);
1562 		}
1563 		pctx.errcode = 0;
1564 		if (retval2 == ENOMEM || retval2 == EXT2_ET_NO_MEMORY) {
1565 			retval = retval2;
1566 			goto failure;
1567 		}
1568 		if (fs->flags & EXT2_FLAG_NOFREE_ON_ERROR) {
1569 			ext2fs_free(fs);
1570 			fs = NULL;
1571 		}
1572 		if (!fs || (fs->group_desc_count > 1)) {
1573 			log_out(ctx, _("%s: %s trying backup blocks...\n"),
1574 				ctx->program_name,
1575 				retval ? _("Superblock invalid,") :
1576 				_("Group descriptors look bad..."));
1577 			orig_superblock = ctx->superblock;
1578 			get_backup_sb(ctx, fs, ctx->filesystem_name, io_ptr);
1579 			if (fs)
1580 				ext2fs_close_free(&fs);
1581 			orig_retval = retval;
1582 			retval = try_open_fs(ctx, flags, io_ptr, &fs);
1583 			if ((orig_retval == 0) && retval != 0) {
1584 				if (fs)
1585 					ext2fs_close_free(&fs);
1586 				log_out(ctx, _("%s: %s while using the "
1587 					       "backup blocks"),
1588 					ctx->program_name,
1589 					error_message(retval));
1590 				log_out(ctx, _("%s: going back to original "
1591 					       "superblock\n"),
1592 					ctx->program_name);
1593 				ctx->superblock = orig_superblock;
1594 				retval = try_open_fs(ctx, flags, io_ptr, &fs);
1595 			}
1596 		}
1597 	}
1598 	if (((retval == EXT2_ET_UNSUPP_FEATURE) ||
1599 	     (retval == EXT2_ET_RO_UNSUPP_FEATURE)) &&
1600 	    fs && fs->super) {
1601 		sb = fs->super;
1602 		features[0] = (sb->s_feature_compat &
1603 			       ~EXT2_LIB_FEATURE_COMPAT_SUPP);
1604 		features[1] = (sb->s_feature_incompat &
1605 			       ~EXT2_LIB_FEATURE_INCOMPAT_SUPP);
1606 		features[2] = (sb->s_feature_ro_compat &
1607 			       ~EXT2_LIB_FEATURE_RO_COMPAT_SUPP);
1608 		if (features[0] || features[1] || features[2])
1609 			goto print_unsupp_features;
1610 	}
1611 failure:
1612 	if (retval) {
1613 		if (orig_retval)
1614 			retval = orig_retval;
1615 		com_err(ctx->program_name, retval, _("while trying to open %s"),
1616 			ctx->filesystem_name);
1617 		if (retval == EXT2_ET_REV_TOO_HIGH) {
1618 			log_out(ctx, "%s",
1619 				_("The filesystem revision is apparently "
1620 				  "too high for this version of e2fsck.\n"
1621 				  "(Or the filesystem superblock "
1622 				  "is corrupt)\n\n"));
1623 			fix_problem(ctx, PR_0_SB_CORRUPT, &pctx);
1624 		} else if (retval == EXT2_ET_SHORT_READ)
1625 			log_out(ctx, "%s",
1626 				_("Could this be a zero-length partition?\n"));
1627 		else if ((retval == EPERM) || (retval == EACCES))
1628 			log_out(ctx, _("You must have %s access to the "
1629 				       "filesystem or be root\n"),
1630 			       (ctx->options & E2F_OPT_READONLY) ?
1631 			       "r/o" : "r/w");
1632 		else if (retval == ENXIO)
1633 			log_out(ctx, "%s",
1634 				_("Possibly non-existent or swap device?\n"));
1635 		else if (retval == EBUSY)
1636 			log_out(ctx, "%s", _("Filesystem mounted or opened "
1637 					 "exclusively by another program?\n"));
1638 		else if (retval == ENOENT)
1639 			log_out(ctx, "%s",
1640 				_("Possibly non-existent device?\n"));
1641 #ifdef EROFS
1642 		else if (retval == EROFS)
1643 			log_out(ctx, "%s", _("Disk write-protected; use the "
1644 					     "-n option to do a read-only\n"
1645 					     "check of the device.\n"));
1646 #endif
1647 		else {
1648 			/*
1649 			 * Let's try once more will less consistency checking
1650 			 * so that we are able to recover from more errors
1651 			 * (e.g. some tool messing up some value in the sb).
1652 			 */
1653 			if ((retval == EXT2_ET_CORRUPT_SUPERBLOCK) &&
1654 			    !(flags & EXT2_FLAG_IGNORE_SB_ERRORS)) {
1655 				if (fs)
1656 					ext2fs_close_free(&fs);
1657 				log_out(ctx, _("%s: Trying to load superblock "
1658 					"despite errors...\n"),
1659 					ctx->program_name);
1660 				flags |= EXT2_FLAG_IGNORE_SB_ERRORS;
1661 				/*
1662 				 * If we tried backup sb, revert to the
1663 				 * original one now.
1664 				 */
1665 				if (orig_superblock != ~(blk64_t)0)
1666 					ctx->superblock = orig_superblock;
1667 				goto restart;
1668 			}
1669 			fix_problem(ctx, PR_0_SB_CORRUPT, &pctx);
1670 			if (retval == EXT2_ET_BAD_MAGIC)
1671 				check_plausibility(ctx->filesystem_name,
1672 						   CHECK_FS_EXIST, NULL);
1673 		}
1674 		fatal_error(ctx, 0);
1675 	}
1676 	/*
1677 	 * We only update the master superblock because (a) paranoia;
1678 	 * we don't want to corrupt the backup superblocks, and (b) we
1679 	 * don't need to update the mount count and last checked
1680 	 * fields in the backup superblock (the kernel doesn't update
1681 	 * the backup superblocks anyway).  With newer versions of the
1682 	 * library this flag is set by ext2fs_open2(), but we set this
1683 	 * here just to be sure.  (No, we don't support e2fsck running
1684 	 * with some other libext2fs than the one that it was shipped
1685 	 * with, but just in case....)
1686 	 */
1687 	fs->flags |= EXT2_FLAG_MASTER_SB_ONLY;
1688 
1689 	if (!(ctx->flags & E2F_FLAG_GOT_DEVSIZE)) {
1690 		__u32 blocksize = EXT2_BLOCK_SIZE(fs->super);
1691 		int need_restart = 0;
1692 
1693 		pctx.errcode = ext2fs_get_device_size2(ctx->filesystem_name,
1694 						       blocksize,
1695 						       &ctx->num_blocks);
1696 		/*
1697 		 * The floppy driver refuses to allow anyone else to
1698 		 * open the device if has been opened with O_EXCL;
1699 		 * this is unlike other block device drivers in Linux.
1700 		 * To handle this, we close the filesystem and then
1701 		 * reopen the filesystem after we get the device size.
1702 		 */
1703 		if (pctx.errcode == EBUSY) {
1704 			ext2fs_close_free(&fs);
1705 			need_restart++;
1706 			pctx.errcode =
1707 				ext2fs_get_device_size2(ctx->filesystem_name,
1708 							blocksize,
1709 							&ctx->num_blocks);
1710 		}
1711 		if (pctx.errcode == EXT2_ET_UNIMPLEMENTED)
1712 			ctx->num_blocks = 0;
1713 		else if (pctx.errcode) {
1714 			fix_problem(ctx, PR_0_GETSIZE_ERROR, &pctx);
1715 			ctx->flags |= E2F_FLAG_ABORT;
1716 			fatal_error(ctx, 0);
1717 		}
1718 		ctx->flags |= E2F_FLAG_GOT_DEVSIZE;
1719 		if (need_restart)
1720 			goto restart;
1721 	}
1722 
1723 	ctx->fs = fs;
1724 	fs->now = ctx->now;
1725 	sb = fs->super;
1726 
1727 	if (sb->s_rev_level > E2FSCK_CURRENT_REV) {
1728 		com_err(ctx->program_name, EXT2_ET_REV_TOO_HIGH,
1729 			_("while trying to open %s"),
1730 			ctx->filesystem_name);
1731 	get_newer:
1732 		fatal_error(ctx, _("Get a newer version of e2fsck!"));
1733 	}
1734 
1735 	/*
1736 	 * Set the device name, which is used whenever we print error
1737 	 * or informational messages to the user.
1738 	 */
1739 	if (ctx->device_name == 0 && sb->s_volume_name[0])
1740 		ctx->device_name = string_copy(ctx, (char *) sb->s_volume_name,
1741 					       sizeof(sb->s_volume_name));
1742 
1743 	if (ctx->device_name == 0)
1744 		ctx->device_name = string_copy(ctx, ctx->filesystem_name, 0);
1745 	for (cp = ctx->device_name; *cp; cp++)
1746 		if (isspace(*cp) || *cp == ':')
1747 			*cp = '_';
1748 
1749 	if (ctx->problem_logf) {
1750 
1751 		fprintf(ctx->problem_logf, "<filesystem dev=\"%s\"",
1752 			ctx->filesystem_name);
1753 		if (!uuid_is_null(sb->s_uuid)) {
1754 			char buf[48];
1755 
1756 			uuid_unparse(sb->s_uuid, buf);
1757 			fprintf(ctx->problem_logf, " uuid=\"%s\"", buf);
1758 		}
1759 		if (sb->s_volume_name[0])
1760 			fprintf(ctx->problem_logf, " label=\"%.*s\"",
1761 				EXT2_LEN_STR(sb->s_volume_name));
1762 
1763 		fputs("/>\n", ctx->problem_logf);
1764 	}
1765 
1766 	ehandler_init(fs->io);
1767 
1768 	if (ext2fs_has_feature_mmp(fs->super) &&
1769 	    (flags & EXT2_FLAG_SKIP_MMP)) {
1770 		if (e2fsck_check_mmp(fs, ctx))
1771 			fatal_error(ctx, 0);
1772 
1773 		/*
1774 		 * Restart in order to reopen fs but this time start mmp.
1775 		 */
1776 		ext2fs_close_free(&ctx->fs);
1777 		flags &= ~EXT2_FLAG_SKIP_MMP;
1778 		goto restart;
1779 	}
1780 
1781 	if (ctx->logf)
1782 		fprintf(ctx->logf, "Filesystem UUID: %s\n",
1783 			e2p_uuid2str(sb->s_uuid));
1784 
1785 	/*
1786 	 * Make sure the ext3 superblock fields are consistent.
1787 	 */
1788 	if ((ctx->mount_flags & (EXT2_MF_MOUNTED | EXT2_MF_BUSY)) == 0) {
1789 		retval = e2fsck_check_ext3_journal(ctx);
1790 		if (retval) {
1791 			com_err(ctx->program_name, retval,
1792 				_("while checking journal for %s"),
1793 				ctx->device_name);
1794 			fatal_error(ctx,
1795 				_("Cannot proceed with file system check"));
1796 		}
1797 	}
1798 
1799 	/*
1800 	 * Check to see if we need to do ext3-style recovery.  If so,
1801 	 * do it, and then restart the fsck.
1802 	 */
1803 	if (ext2fs_has_feature_journal_needs_recovery(sb)) {
1804 		if (ctx->options & E2F_OPT_READONLY) {
1805 			log_out(ctx, "%s",
1806 				_("Warning: skipping journal recovery because "
1807 				  "doing a read-only filesystem check.\n"));
1808 			io_channel_flush(ctx->fs->io);
1809 		} else {
1810 			if (ctx->flags & E2F_FLAG_RESTARTED) {
1811 				/*
1812 				 * Whoops, we attempted to run the
1813 				 * journal twice.  This should never
1814 				 * happen, unless the hardware or
1815 				 * device driver is being bogus.
1816 				 */
1817 				com_err(ctx->program_name, 0,
1818 					_("unable to set superblock flags "
1819 					  "on %s\n"), ctx->device_name);
1820 				fatal_error(ctx, 0);
1821 			}
1822 			retval = e2fsck_run_ext3_journal(ctx);
1823 			if (retval == EFSBADCRC) {
1824 				log_out(ctx, _("Journal checksum error "
1825 					       "found in %s\n"),
1826 					ctx->device_name);
1827 			} else if (retval == EFSCORRUPTED) {
1828 				log_out(ctx, _("Journal corrupted in %s\n"),
1829 					ctx->device_name);
1830 			} else if (retval) {
1831 				com_err(ctx->program_name, retval,
1832 				_("while recovering journal of %s"),
1833 					ctx->device_name);
1834 			}
1835 			ext2fs_close_free(&ctx->fs);
1836 			ctx->flags |= E2F_FLAG_RESTARTED;
1837 			goto restart;
1838 		}
1839 	}
1840 
1841 	/*
1842 	 * Check for compatibility with the feature sets.  We need to
1843 	 * be more stringent than ext2fs_open().
1844 	 */
1845 	features[0] = sb->s_feature_compat & ~EXT2_LIB_FEATURE_COMPAT_SUPP;
1846 	features[1] = sb->s_feature_incompat & ~EXT2_LIB_FEATURE_INCOMPAT_SUPP;
1847 	features[2] = (sb->s_feature_ro_compat &
1848 		       ~EXT2_LIB_FEATURE_RO_COMPAT_SUPP);
1849 print_unsupp_features:
1850 	if (features[0] || features[1] || features[2]) {
1851 		int	i, j;
1852 		__u32	*mask = features, m;
1853 
1854 		log_err(ctx, _("%s has unsupported feature(s):"),
1855 			ctx->filesystem_name);
1856 
1857 		for (i=0; i <3; i++,mask++) {
1858 			for (j=0,m=1; j < 32; j++, m<<=1) {
1859 				if (*mask & m)
1860 					log_err(ctx, " %s",
1861 						e2p_feature2string(i, m));
1862 			}
1863 		}
1864 		log_err(ctx, "\n");
1865 		goto get_newer;
1866 	}
1867 
1868 	if (ext2fs_has_feature_casefold(sb) && !fs->encoding) {
1869 		log_err(ctx, _("%s has unsupported encoding: %0x\n"),
1870 			ctx->filesystem_name, sb->s_encoding);
1871 		goto get_newer;
1872 	}
1873 
1874 	/*
1875 	 * If the user specified a specific superblock, presumably the
1876 	 * master superblock has been trashed.  So we mark the
1877 	 * superblock as dirty, so it can be written out.
1878 	 */
1879 	if (ctx->superblock &&
1880 	    !(ctx->options & E2F_OPT_READONLY))
1881 		ext2fs_mark_super_dirty(fs);
1882 
1883 	/*
1884 	 * Calculate the number of filesystem blocks per pagesize.  If
1885 	 * fs->blocksize > page_size, set the number of blocks per
1886 	 * pagesize to 1 to avoid division by zero errors.
1887 	 */
1888 #ifdef _SC_PAGESIZE
1889 	sysval = sysconf(_SC_PAGESIZE);
1890 	if (sysval > 0)
1891 		sys_page_size = sysval;
1892 #endif /* _SC_PAGESIZE */
1893 	ctx->blocks_per_page = sys_page_size / fs->blocksize;
1894 	if (ctx->blocks_per_page == 0)
1895 		ctx->blocks_per_page = 1;
1896 
1897 	if (ctx->superblock)
1898 		set_latch_flags(PR_LATCH_RELOC, PRL_LATCHED, 0);
1899 	ext2fs_mark_valid(fs);
1900 	check_super_block(ctx);
1901 	if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
1902 		fatal_error(ctx, 0);
1903 	check_if_skip(ctx);
1904 	check_resize_inode(ctx);
1905 	if (bad_blocks_file)
1906 		read_bad_blocks_file(ctx, bad_blocks_file, replace_bad_blocks);
1907 	else if (cflag)
1908 		read_bad_blocks_file(ctx, 0, !keep_bad_blocks); /* Test disk */
1909 	if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
1910 		fatal_error(ctx, 0);
1911 
1912 	/*
1913 	 * Mark the system as valid, 'til proven otherwise
1914 	 */
1915 	ext2fs_mark_valid(fs);
1916 
1917 	retval = ext2fs_read_bb_inode(fs, &fs->badblocks);
1918 	if (retval) {
1919 		log_out(ctx, _("%s: %s while reading bad blocks inode\n"),
1920 			ctx->program_name, error_message(retval));
1921 		preenhalt(ctx);
1922 		log_out(ctx, "%s", _("This doesn't bode well, "
1923 				     "but we'll try to go on...\n"));
1924 	}
1925 
1926 	/*
1927 	 * Save the journal size in megabytes.
1928 	 * Try and use the journal size from the backup else let e2fsck
1929 	 * find the default journal size. If fast commit feature is enabled,
1930 	 * it is not clear how many of the journal blocks were fast commit
1931 	 * blocks. So, ignore the size of journal found in backup.
1932 	 *
1933 	 * TODO: Add a new backup type that captures fast commit info as
1934 	 * well.
1935 	 */
1936 	if (sb->s_jnl_backup_type == EXT3_JNL_BACKUP_BLOCKS &&
1937 		!ext2fs_has_feature_fast_commit(sb))
1938 		journal_size = (sb->s_jnl_blocks[15] << (32 - 20)) |
1939 			       (sb->s_jnl_blocks[16] >> 20);
1940 	else
1941 		journal_size = -1;
1942 
1943 	if (ext2fs_has_feature_quota(sb)) {
1944 		/* Quotas were enabled. Do quota accounting during fsck. */
1945 		clear_problem_context(&pctx);
1946 		pctx.errcode = quota_init_context(&ctx->qctx, ctx->fs, 0);
1947 		if (pctx.errcode) {
1948 			fix_problem(ctx, PR_0_QUOTA_INIT_CTX, &pctx);
1949 			fatal_error(ctx, 0);
1950 		}
1951 	}
1952 
1953 	run_result = e2fsck_run(ctx);
1954 	e2fsck_clear_progbar(ctx);
1955 
1956 	if (!ctx->invalid_bitmaps &&
1957 	    (ctx->flags & E2F_FLAG_JOURNAL_INODE)) {
1958 		if (fix_problem(ctx, PR_6_RECREATE_JOURNAL, &pctx)) {
1959 			if (journal_size < 1024) {
1960 				ext2fs_get_journal_params(&jparams, fs);
1961 			} else {
1962 				jparams.num_journal_blocks = journal_size;
1963 				jparams.num_fc_blocks = 0;
1964 			}
1965 			log_out(ctx, _("Creating journal (%d blocks): "),
1966 			       jparams.num_journal_blocks);
1967 			fflush(stdout);
1968 			retval = ext2fs_add_journal_inode3(fs, &jparams, ~0ULL, 0);
1969 			if (retval) {
1970 				log_out(ctx, "%s: while trying to create "
1971 					"journal\n", error_message(retval));
1972 				goto no_journal;
1973 			}
1974 			log_out(ctx, "%s", _(" Done.\n"));
1975 			log_out(ctx, "%s",
1976 				_("\n*** journal has been regenerated ***\n"));
1977 		}
1978 	}
1979 no_journal:
1980 
1981 	if (run_result & E2F_FLAG_ABORT) {
1982 		fatal_error(ctx, _("aborted"));
1983 	} else if (run_result & E2F_FLAG_CANCEL) {
1984 		log_out(ctx, _("%s: e2fsck canceled.\n"), ctx->device_name ?
1985 			ctx->device_name : ctx->filesystem_name);
1986 		exit_value |= FSCK_CANCELED;
1987 	} else if (ctx->qctx && !ctx->invalid_bitmaps) {
1988 		int needs_writeout;
1989 
1990 		for (qtype = 0; qtype < MAXQUOTAS; qtype++) {
1991 			if (*quota_sb_inump(sb, qtype) == 0)
1992 				continue;
1993 			needs_writeout = 0;
1994 			pctx.num = qtype;
1995 			retval = quota_compare_and_update(ctx->qctx, qtype,
1996 							  &needs_writeout);
1997 			if ((retval || needs_writeout) &&
1998 			    fix_problem(ctx, PR_6_UPDATE_QUOTAS, &pctx)) {
1999 				pctx.errcode = quota_write_inode(ctx->qctx,
2000 								 1 << qtype);
2001 				if (pctx.errcode)
2002 					(void) fix_problem(ctx,
2003 						PR_6_WRITE_QUOTAS, &pctx);
2004 			}
2005 		}
2006 		quota_release_context(&ctx->qctx);
2007 	}
2008 
2009 	if (run_result == E2F_FLAG_RESTART) {
2010 		log_out(ctx, "%s",
2011 			_("Restarting e2fsck from the beginning...\n"));
2012 		retval = e2fsck_reset_context(ctx);
2013 		if (retval) {
2014 			com_err(ctx->program_name, retval, "%s",
2015 				_("while resetting context"));
2016 			fatal_error(ctx, 0);
2017 		}
2018 		ext2fs_close_free(&ctx->fs);
2019 		goto restart;
2020 	}
2021 
2022 #ifdef MTRACE
2023 	mtrace_print("Cleanup");
2024 #endif
2025 	was_changed = ext2fs_test_changed(fs);
2026 	if (!(ctx->flags & E2F_FLAG_RUN_RETURN) &&
2027 	    !(ctx->options & E2F_OPT_READONLY)) {
2028 		if (ext2fs_test_valid(fs)) {
2029 			if (!(sb->s_state & EXT2_VALID_FS))
2030 				exit_value |= FSCK_NONDESTRUCT;
2031 			sb->s_state = EXT2_VALID_FS;
2032 			if (check_backup_super_block(ctx))
2033 				fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
2034 		} else
2035 			sb->s_state &= ~EXT2_VALID_FS;
2036 		if (!(ctx->flags & E2F_FLAG_TIME_INSANE))
2037 			sb->s_lastcheck = ctx->now;
2038 		sb->s_mnt_count = 0;
2039 		memset(((char *) sb) + EXT4_S_ERR_START, 0, EXT4_S_ERR_LEN);
2040 		pctx.errcode = ext2fs_set_gdt_csum(ctx->fs);
2041 		if (pctx.errcode)
2042 			fix_problem(ctx, PR_6_SET_BG_CHECKSUM, &pctx);
2043 		ext2fs_mark_super_dirty(fs);
2044 	}
2045 
2046 	if (ext2fs_has_feature_shared_blocks(ctx->fs->super) &&
2047 	    (ctx->options & E2F_OPT_UNSHARE_BLOCKS) &&
2048 	    (ctx->options & E2F_OPT_NO))
2049 		/* Don't try to write or flush I/O, we just wanted to know whether or
2050 		 * not there were enough free blocks to undo deduplication.
2051 		 */
2052 		goto skip_write;
2053 
2054 	if (!(ctx->options & E2F_OPT_READONLY)) {
2055 		e2fsck_write_bitmaps(ctx);
2056 		if (fs->flags & EXT2_FLAG_DIRTY) {
2057 			pctx.errcode = ext2fs_flush(ctx->fs);
2058 			if (pctx.errcode)
2059 				fix_problem(ctx, PR_6_FLUSH_FILESYSTEM, &pctx);
2060 		}
2061 		pctx.errcode = io_channel_flush(ctx->fs->io);
2062 		if (pctx.errcode)
2063 			fix_problem(ctx, PR_6_IO_FLUSH, &pctx);
2064 	}
2065 
2066 	if (was_changed) {
2067 		int fs_fixed = (ctx->flags & E2F_FLAG_PROBLEMS_FIXED);
2068 
2069 		if (fs_fixed)
2070 			exit_value |= FSCK_NONDESTRUCT;
2071 		if (!(ctx->options & E2F_OPT_PREEN)) {
2072 #if 0	/* Do this later; it breaks too many tests' golden outputs */
2073 			log_out(ctx, fs_fixed ?
2074 				_("\n%s: ***** FILE SYSTEM ERRORS "
2075 				  "CORRECTED *****\n") :
2076 				_("%s: File system was modified.\n"),
2077 				ctx->device_name);
2078 #else
2079 			log_out(ctx,
2080 				_("\n%s: ***** FILE SYSTEM WAS MODIFIED *****\n"),
2081 				ctx->device_name);
2082 #endif
2083 		}
2084 		if (ctx->mount_flags & EXT2_MF_ISROOT) {
2085 			log_out(ctx, _("%s: ***** REBOOT SYSTEM *****\n"),
2086 				ctx->device_name);
2087 			exit_value |= FSCK_REBOOT;
2088 		}
2089 	}
2090 
2091 skip_write:
2092 	if (!ext2fs_test_valid(fs) ||
2093 	    ((exit_value & FSCK_CANCELED) &&
2094 	     (sb->s_state & EXT2_ERROR_FS))) {
2095 		log_out(ctx, _("\n%s: ********** WARNING: Filesystem still has "
2096 			       "errors **********\n\n"), ctx->device_name);
2097 		exit_value |= FSCK_UNCORRECTED;
2098 		exit_value &= ~FSCK_NONDESTRUCT;
2099 	}
2100 	if (exit_value & FSCK_CANCELED) {
2101 		int	allow_cancellation;
2102 
2103 		profile_get_boolean(ctx->profile, "options",
2104 				    "allow_cancellation", 0, 0,
2105 				    &allow_cancellation);
2106 		exit_value &= ~FSCK_NONDESTRUCT;
2107 		if (allow_cancellation && ext2fs_test_valid(fs) &&
2108 		    (sb->s_state & EXT2_VALID_FS) &&
2109 		    !(sb->s_state & EXT2_ERROR_FS))
2110 			exit_value = 0;
2111 	} else
2112 		show_stats(ctx);
2113 
2114 	print_resource_track(ctx, NULL, &ctx->global_rtrack, ctx->fs->io);
2115 
2116 	ext2fs_close_free(&ctx->fs);
2117 	free(ctx->journal_name);
2118 
2119 	if (ctx->logf)
2120 		fprintf(ctx->logf, "Exit status: %d\n", exit_value);
2121 	e2fsck_free_context(ctx);
2122 	remove_error_table(&et_ext2_error_table);
2123 	remove_error_table(&et_prof_error_table);
2124 	return exit_value;
2125 }
2126