unix.c revision 6dc64392c052839f373b7bbbb58efa3048bfb355
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#define _XOPEN_SOURCE 600 /* for inclusion of sa_handler in Solaris */
13
14#include <stdio.h>
15#ifdef HAVE_STDLIB_H
16#include <stdlib.h>
17#endif
18#include <string.h>
19#include <fcntl.h>
20#include <ctype.h>
21#include <time.h>
22#ifdef HAVE_SIGNAL_H
23#include <signal.h>
24#endif
25#ifdef HAVE_GETOPT_H
26#include <getopt.h>
27#else
28extern char *optarg;
29extern int optind;
30#endif
31#include <unistd.h>
32#ifdef HAVE_ERRNO_H
33#include <errno.h>
34#endif
35#ifdef HAVE_MNTENT_H
36#include <mntent.h>
37#endif
38#ifdef HAVE_SYS_IOCTL_H
39#include <sys/ioctl.h>
40#endif
41#ifdef HAVE_MALLOC_H
42#include <malloc.h>
43#endif
44#ifdef HAVE_SYS_TYPES_H
45#include <sys/types.h>
46#endif
47#ifdef HAVE_DIRENT_H
48#include <dirent.h>
49#endif
50
51#include "e2p/e2p.h"
52#include "et/com_err.h"
53#include "e2p/e2p.h"
54#include "e2fsck.h"
55#include "problem.h"
56#include "../version.h"
57
58/* Command line options */
59static int cflag;		/* check disk */
60static int show_version_only;
61static int verbose;
62
63static int replace_bad_blocks;
64static int keep_bad_blocks;
65static char *bad_blocks_file;
66
67e2fsck_t e2fsck_global_ctx;	/* Try your very best not to use this! */
68
69#ifdef CONFIG_JBD_DEBUG		/* Enabled by configure --enable-jfs-debug */
70int journal_enable_debug = -1;
71#endif
72
73static void usage(e2fsck_t ctx)
74{
75	fprintf(stderr,
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"),
80		ctx->program_name);
81
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"));
88	fprintf(stderr, _(""
89		" -v                   Be verbose\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"
95		));
96
97	exit(FSCK_USAGE);
98}
99
100static 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	int frag_percent_file, frag_percent_dir, frag_percent_total;
108	int i, j;
109
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));
119
120	frag_percent_file = (10000 * ctx->fs_fragmented) / inodes_used;
121	frag_percent_file = (frag_percent_file + 5) / 10;
122
123	frag_percent_dir = (10000 * ctx->fs_fragmented_dir) / inodes_used;
124	frag_percent_dir = (frag_percent_dir + 5) / 10;
125
126	frag_percent_total = ((10000 * (ctx->fs_fragmented +
127					ctx->fs_fragmented_dir))
128			      / inodes_used);
129	frag_percent_total = (frag_percent_total + 5) / 10;
130
131	if (!verbose) {
132		printf(_("%s: %u/%u files (%0d.%d%% non-contiguous), %llu/%llu blocks\n"),
133		       ctx->device_name, inodes_used, inodes,
134		       frag_percent_total / 10, frag_percent_total % 10,
135		       blocks_used, blocks);
136		return;
137	}
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",
142		   ctx->fs_fragmented),
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);
152
153	for (j=MAX_EXTENT_DEPTH_COUNT-1; j >=0; j--)
154		if (ctx->extent_depth_count[j])
155			break;
156	if (++j) {
157		printf (_("         Extent depth histogram: "));
158		for (i=0; i < j; i++) {
159			if (i)
160				fputc('/', stdout);
161			printf("%u", ctx->extent_depth_count[i]);
162		}
163		fputc('\n', stdout);
164	}
165
166	printf (P_("%8llu block used (%2.2f%%)\n",
167		   "%8llu blocks used (%2.2f%%)\n",
168		   blocks_used), blocks_used, 100.0 * blocks_used / blocks);
169	printf (P_("%8u bad block\n", "%8u bad blocks\n",
170		   ctx->fs_badblocks_count), ctx->fs_badblocks_count);
171	printf (P_("%8u large file\n", "%8u large files\n",
172		   ctx->large_files), ctx->large_files);
173	printf (P_("\n%8u regular file\n", "\n%8u regular files\n",
174		   ctx->fs_regular_count), ctx->fs_regular_count);
175	printf (P_("%8u directory\n", "%8u directories\n",
176		   ctx->fs_directory_count), ctx->fs_directory_count);
177	printf (P_("%8u character device file\n",
178		   "%8u character device files\n", ctx->fs_chardev_count),
179		ctx->fs_chardev_count);
180	printf (P_("%8u block device file\n", "%8u block device files\n",
181		   ctx->fs_blockdev_count), ctx->fs_blockdev_count);
182	printf (P_("%8u fifo\n", "%8u fifos\n", ctx->fs_fifo_count),
183		ctx->fs_fifo_count);
184	printf (P_("%8u link\n", "%8u links\n",
185		   ctx->fs_links_count - dir_links),
186		ctx->fs_links_count - dir_links);
187	printf (P_("%8u symbolic link", "%8u symbolic links",
188		   ctx->fs_symlinks_count), ctx->fs_symlinks_count);
189	printf (P_(" (%u fast symbolic link)\n", " (%u fast symbolic links)\n",
190		   ctx->fs_fast_symlinks_count), ctx->fs_fast_symlinks_count);
191	printf (P_("%8u socket\n", "%8u sockets\n", ctx->fs_sockets_count),
192		ctx->fs_sockets_count);
193	printf ("--------\n");
194	printf (P_("%8u file\n", "%8u files\n",
195		   ctx->fs_total_count - dir_links),
196		ctx->fs_total_count - dir_links);
197}
198
199static void check_mount(e2fsck_t ctx)
200{
201	errcode_t	retval;
202	int		cont;
203
204	retval = ext2fs_check_if_mounted(ctx->filesystem_name,
205					 &ctx->mount_flags);
206	if (retval) {
207		com_err("ext2fs_check_if_mount", retval,
208			_("while determining whether %s is mounted."),
209			ctx->filesystem_name);
210		return;
211	}
212
213	/*
214	 * If the filesystem isn't mounted, or it's the root
215	 * filesystem and it's mounted read-only, and we're not doing
216	 * a read/write check, then everything's fine.
217	 */
218	if ((!(ctx->mount_flags & EXT2_MF_MOUNTED)) ||
219	    ((ctx->mount_flags & EXT2_MF_ISROOT) &&
220	     (ctx->mount_flags & EXT2_MF_READONLY) &&
221	     !(ctx->options & E2F_OPT_WRITECHECK)))
222		return;
223
224	if ((ctx->options & E2F_OPT_READONLY) &&
225	    !(ctx->options & E2F_OPT_WRITECHECK)) {
226		printf(_("Warning!  %s is mounted.\n"), ctx->filesystem_name);
227		return;
228	}
229
230	printf(_("%s is mounted.  "), ctx->filesystem_name);
231	if (!ctx->interactive)
232		fatal_error(ctx, _("Cannot continue, aborting.\n\n"));
233	printf(_("\n\n\007\007\007\007WARNING!!!  "
234	       "The filesystem is mounted.   If you continue you ***WILL***\n"
235	       "cause ***SEVERE*** filesystem damage.\007\007\007\n\n"));
236	cont = ask_yn(_("Do you really want to continue"), -1);
237	if (!cont) {
238		printf (_("check aborted.\n"));
239		exit (0);
240	}
241	return;
242}
243
244static int is_on_batt(void)
245{
246	FILE	*f;
247	DIR	*d;
248	char	tmp[80], tmp2[80], fname[80];
249	unsigned int	acflag;
250	struct dirent*	de;
251
252	f = fopen("/proc/apm", "r");
253	if (f) {
254		if (fscanf(f, "%s %s %s %x", tmp, tmp, tmp, &acflag) != 4)
255			acflag = 1;
256		fclose(f);
257		return (acflag != 1);
258	}
259	d = opendir("/proc/acpi/ac_adapter");
260	if (d) {
261		while ((de=readdir(d)) != NULL) {
262			if (!strncmp(".", de->d_name, 1))
263				continue;
264			snprintf(fname, 80, "/proc/acpi/ac_adapter/%s/state",
265				 de->d_name);
266			f = fopen(fname, "r");
267			if (!f)
268				continue;
269			if (fscanf(f, "%s %s", tmp2, tmp) != 2)
270				tmp[0] = 0;
271			fclose(f);
272			if (strncmp(tmp, "off-line", 8) == 0) {
273				closedir(d);
274				return 1;
275			}
276		}
277		closedir(d);
278	}
279	return 0;
280}
281
282/*
283 * This routine checks to see if a filesystem can be skipped; if so,
284 * it will exit with E2FSCK_OK.  Under some conditions it will print a
285 * message explaining why a check is being forced.
286 */
287static void check_if_skip(e2fsck_t ctx)
288{
289	ext2_filsys fs = ctx->fs;
290	const char *reason = NULL;
291	unsigned int reason_arg = 0;
292	long next_check;
293	int batt = is_on_batt();
294	int defer_check_on_battery;
295	int broken_system_clock;
296	time_t lastcheck;
297
298	profile_get_boolean(ctx->profile, "options", "broken_system_clock",
299			    0, 0, &broken_system_clock);
300	if (ctx->flags & E2F_FLAG_TIME_INSANE)
301		broken_system_clock = 1;
302	profile_get_boolean(ctx->profile, "options",
303			    "defer_check_on_battery", 0, 1,
304			    &defer_check_on_battery);
305	if (!defer_check_on_battery)
306		batt = 0;
307
308	if ((ctx->options & E2F_OPT_FORCE) || bad_blocks_file || cflag)
309		return;
310
311	lastcheck = fs->super->s_lastcheck;
312	if (lastcheck > ctx->now)
313		lastcheck -= ctx->time_fudge;
314	if ((fs->super->s_state & EXT2_ERROR_FS) ||
315	    !ext2fs_test_valid(fs))
316		reason = _(" contains a file system with errors");
317	else if ((fs->super->s_state & EXT2_VALID_FS) == 0)
318		reason = _(" was not cleanly unmounted");
319	else if (check_backup_super_block(ctx))
320		reason = _(" primary superblock features different from backup");
321	else if ((fs->super->s_max_mnt_count > 0) &&
322		 (fs->super->s_mnt_count >=
323		  (unsigned) fs->super->s_max_mnt_count)) {
324		reason = _(" has been mounted %u times without being checked");
325		reason_arg = fs->super->s_mnt_count;
326		if (batt && (fs->super->s_mnt_count <
327			     (unsigned) fs->super->s_max_mnt_count*2))
328			reason = 0;
329	} else if (!broken_system_clock && fs->super->s_checkinterval &&
330		   (ctx->now < lastcheck)) {
331		reason = _(" has filesystem last checked time in the future");
332		if (batt)
333			reason = 0;
334	} else if (!broken_system_clock && fs->super->s_checkinterval &&
335		   ((ctx->now - lastcheck) >=
336		    ((time_t) fs->super->s_checkinterval))) {
337		reason = _(" has gone %u days without being checked");
338		reason_arg = (ctx->now - fs->super->s_lastcheck)/(3600*24);
339		if (batt && ((ctx->now - fs->super->s_lastcheck) <
340			     fs->super->s_checkinterval*2))
341			reason = 0;
342	}
343	if (reason) {
344		fputs(ctx->device_name, stdout);
345		printf(reason, reason_arg);
346		fputs(_(", check forced.\n"), stdout);
347		return;
348	}
349	printf(_("%s: clean, %u/%u files, %llu/%llu blocks"), ctx->device_name,
350	       fs->super->s_inodes_count - fs->super->s_free_inodes_count,
351	       fs->super->s_inodes_count,
352	       ext2fs_blocks_count(fs->super) -
353	       ext2fs_free_blocks_count(fs->super),
354	       ext2fs_blocks_count(fs->super));
355	next_check = 100000;
356	if (fs->super->s_max_mnt_count > 0) {
357		next_check = fs->super->s_max_mnt_count - fs->super->s_mnt_count;
358		if (next_check <= 0)
359			next_check = 1;
360	}
361	if (!broken_system_clock && fs->super->s_checkinterval &&
362	    ((ctx->now - fs->super->s_lastcheck) >= fs->super->s_checkinterval))
363		next_check = 1;
364	if (next_check <= 5) {
365		if (next_check == 1) {
366			if (batt)
367				fputs(_(" (check deferred; on battery)"),
368				      stdout);
369			else
370				fputs(_(" (check after next mount)"), stdout);
371		} else
372			printf(_(" (check in %ld mounts)"), next_check);
373	}
374	fputc('\n', stdout);
375	ext2fs_close(fs);
376	ctx->fs = NULL;
377	e2fsck_free_context(ctx);
378	exit(FSCK_OK);
379}
380
381/*
382 * For completion notice
383 */
384struct percent_tbl {
385	int	max_pass;
386	int	table[32];
387};
388struct percent_tbl e2fsck_tbl = {
389	5, { 0, 70, 90, 92,  95, 100 }
390};
391static char bar[128], spaces[128];
392
393static float calc_percent(struct percent_tbl *tbl, int pass, int curr,
394			  int max)
395{
396	float	percent;
397
398	if (pass <= 0)
399		return 0.0;
400	if (pass > tbl->max_pass || max == 0)
401		return 100.0;
402	percent = ((float) curr) / ((float) max);
403	return ((percent * (tbl->table[pass] - tbl->table[pass-1]))
404		+ tbl->table[pass-1]);
405}
406
407extern void e2fsck_clear_progbar(e2fsck_t ctx)
408{
409	if (!(ctx->flags & E2F_FLAG_PROG_BAR))
410		return;
411
412	printf("%s%s\r%s", ctx->start_meta, spaces + (sizeof(spaces) - 80),
413	       ctx->stop_meta);
414	fflush(stdout);
415	ctx->flags &= ~E2F_FLAG_PROG_BAR;
416}
417
418int e2fsck_simple_progress(e2fsck_t ctx, const char *label, float percent,
419			   unsigned int dpynum)
420{
421	static const char spinner[] = "\\|/-";
422	int	i;
423	unsigned int	tick;
424	struct timeval	tv;
425	int dpywidth;
426	int fixed_percent;
427
428	if (ctx->flags & E2F_FLAG_PROG_SUPPRESS)
429		return 0;
430
431	/*
432	 * Calculate the new progress position.  If the
433	 * percentage hasn't changed, then we skip out right
434	 * away.
435	 */
436	fixed_percent = (int) ((10 * percent) + 0.5);
437	if (ctx->progress_last_percent == fixed_percent)
438		return 0;
439	ctx->progress_last_percent = fixed_percent;
440
441	/*
442	 * If we've already updated the spinner once within
443	 * the last 1/8th of a second, no point doing it
444	 * again.
445	 */
446	gettimeofday(&tv, NULL);
447	tick = (tv.tv_sec << 3) + (tv.tv_usec / (1000000 / 8));
448	if ((tick == ctx->progress_last_time) &&
449	    (fixed_percent != 0) && (fixed_percent != 1000))
450		return 0;
451	ctx->progress_last_time = tick;
452
453	/*
454	 * Advance the spinner, and note that the progress bar
455	 * will be on the screen
456	 */
457	ctx->progress_pos = (ctx->progress_pos+1) & 3;
458	ctx->flags |= E2F_FLAG_PROG_BAR;
459
460	dpywidth = 66 - strlen(label);
461	dpywidth = 8 * (dpywidth / 8);
462	if (dpynum)
463		dpywidth -= 8;
464
465	i = ((percent * dpywidth) + 50) / 100;
466	printf("%s%s: |%s%s", ctx->start_meta, label,
467	       bar + (sizeof(bar) - (i+1)),
468	       spaces + (sizeof(spaces) - (dpywidth - i + 1)));
469	if (fixed_percent == 1000)
470		fputc('|', stdout);
471	else
472		fputc(spinner[ctx->progress_pos & 3], stdout);
473	printf(" %4.1f%%  ", percent);
474	if (dpynum)
475		printf("%u\r", dpynum);
476	else
477		fputs(" \r", stdout);
478	fputs(ctx->stop_meta, stdout);
479
480	if (fixed_percent == 1000)
481		e2fsck_clear_progbar(ctx);
482	fflush(stdout);
483
484	return 0;
485}
486
487static int e2fsck_update_progress(e2fsck_t ctx, int pass,
488				  unsigned long cur, unsigned long max)
489{
490	char buf[1024];
491	float percent;
492
493	if (pass == 0)
494		return 0;
495
496	if (ctx->progress_fd) {
497		snprintf(buf, sizeof(buf), "%d %lu %lu %s\n",
498			 pass, cur, max, ctx->device_name);
499		write_all(ctx->progress_fd, buf, strlen(buf));
500	} else {
501		percent = calc_percent(&e2fsck_tbl, pass, cur, max);
502		e2fsck_simple_progress(ctx, ctx->device_name,
503				       percent, 0);
504	}
505	return 0;
506}
507
508#define PATH_SET "PATH=/sbin"
509
510static void reserve_stdio_fds(void)
511{
512	int	fd;
513
514	while (1) {
515		fd = open("/dev/null", O_RDWR);
516		if (fd > 2)
517			break;
518		if (fd < 0) {
519			fprintf(stderr, _("ERROR: Couldn't open "
520				"/dev/null (%s)\n"),
521				strerror(errno));
522			break;
523		}
524	}
525	close(fd);
526}
527
528#ifdef HAVE_SIGNAL_H
529static void signal_progress_on(int sig EXT2FS_ATTR((unused)))
530{
531	e2fsck_t ctx = e2fsck_global_ctx;
532
533	if (!ctx)
534		return;
535
536	ctx->progress = e2fsck_update_progress;
537}
538
539static void signal_progress_off(int sig EXT2FS_ATTR((unused)))
540{
541	e2fsck_t ctx = e2fsck_global_ctx;
542
543	if (!ctx)
544		return;
545
546	e2fsck_clear_progbar(ctx);
547	ctx->progress = 0;
548}
549
550static void signal_cancel(int sig EXT2FS_ATTR((unused)))
551{
552	e2fsck_t ctx = e2fsck_global_ctx;
553
554	if (!ctx)
555		exit(FSCK_CANCELED);
556
557	ctx->flags |= E2F_FLAG_CANCEL;
558}
559#endif
560
561static void parse_extended_opts(e2fsck_t ctx, const char *opts)
562{
563	char	*buf, *token, *next, *p, *arg;
564	int	ea_ver;
565	int	extended_usage = 0;
566
567	buf = string_copy(ctx, opts, 0);
568	for (token = buf; token && *token; token = next) {
569		p = strchr(token, ',');
570		next = 0;
571		if (p) {
572			*p = 0;
573			next = p+1;
574		}
575		arg = strchr(token, '=');
576		if (arg) {
577			*arg = 0;
578			arg++;
579		}
580		if (strcmp(token, "ea_ver") == 0) {
581			if (!arg) {
582				extended_usage++;
583				continue;
584			}
585			ea_ver = strtoul(arg, &p, 0);
586			if (*p ||
587			    ((ea_ver != 1) && (ea_ver != 2))) {
588				fprintf(stderr,
589					_("Invalid EA version.\n"));
590				extended_usage++;
591				continue;
592			}
593			ctx->ext_attr_ver = ea_ver;
594		} else if (strcmp(token, "fragcheck") == 0) {
595			ctx->options |= E2F_OPT_FRAGCHECK;
596			continue;
597		} else {
598			fprintf(stderr, _("Unknown extended option: %s\n"),
599				token);
600			extended_usage++;
601		}
602	}
603	free(buf);
604
605	if (extended_usage) {
606		fputs(("\nExtended options are separated by commas, "
607		       "and may take an argument which\n"
608		       "is set off by an equals ('=') sign.  "
609		       "Valid extended options are:\n"), stderr);
610		fputs(("\tea_ver=<ea_version (1 or 2)>\n"), stderr);
611		fputs(("\tfragcheck\n"), stderr);
612		fputc('\n', stderr);
613		exit(1);
614	}
615}
616
617static void syntax_err_report(const char *filename, long err, int line_num)
618{
619	fprintf(stderr,
620		_("Syntax error in e2fsck config file (%s, line #%d)\n\t%s\n"),
621		filename, line_num, error_message(err));
622	exit(FSCK_ERROR);
623}
624
625static const char *config_fn[] = { ROOT_SYSCONFDIR "/e2fsck.conf", 0 };
626
627static errcode_t PRS(int argc, char *argv[], e2fsck_t *ret_ctx)
628{
629	int		flush = 0;
630	int		c, fd;
631#ifdef MTRACE
632	extern void	*mallwatch;
633#endif
634	e2fsck_t	ctx;
635	errcode_t	retval;
636#ifdef HAVE_SIGNAL_H
637	struct sigaction	sa;
638#endif
639	char		*extended_opts = 0;
640	char		*cp;
641	int 		res;		/* result of sscanf */
642#ifdef CONFIG_JBD_DEBUG
643	char 		*jbd_debug;
644#endif
645
646	retval = e2fsck_allocate_context(&ctx);
647	if (retval)
648		return retval;
649
650	*ret_ctx = ctx;
651
652	setvbuf(stdout, NULL, _IONBF, BUFSIZ);
653	setvbuf(stderr, NULL, _IONBF, BUFSIZ);
654	if (isatty(0) && isatty(1)) {
655		ctx->interactive = 1;
656	} else {
657		ctx->start_meta[0] = '\001';
658		ctx->stop_meta[0] = '\002';
659	}
660	memset(bar, '=', sizeof(bar)-1);
661	memset(spaces, ' ', sizeof(spaces)-1);
662	add_error_table(&et_ext2_error_table);
663	add_error_table(&et_prof_error_table);
664	blkid_get_cache(&ctx->blkid, NULL);
665
666	if (argc && *argv)
667		ctx->program_name = *argv;
668	else
669		ctx->program_name = "e2fsck";
670	while ((c = getopt (argc, argv, "panyrcC:B:dE:fvtFVM:b:I:j:P:l:L:N:SsDk")) != EOF)
671		switch (c) {
672		case 'C':
673			ctx->progress = e2fsck_update_progress;
674			res = sscanf(optarg, "%d", &ctx->progress_fd);
675			if (res != 1)
676				goto sscanf_err;
677
678			if (ctx->progress_fd < 0) {
679				ctx->progress = 0;
680				ctx->progress_fd = ctx->progress_fd * -1;
681			}
682			if (!ctx->progress_fd)
683				break;
684			/* Validate the file descriptor to avoid disasters */
685			fd = dup(ctx->progress_fd);
686			if (fd < 0) {
687				fprintf(stderr,
688				_("Error validating file descriptor %d: %s\n"),
689					ctx->progress_fd,
690					error_message(errno));
691				fatal_error(ctx,
692			_("Invalid completion information file descriptor"));
693			} else
694				close(fd);
695			break;
696		case 'D':
697			ctx->options |= E2F_OPT_COMPRESS_DIRS;
698			break;
699		case 'E':
700			extended_opts = optarg;
701			break;
702		case 'p':
703		case 'a':
704			if (ctx->options & (E2F_OPT_YES|E2F_OPT_NO)) {
705			conflict_opt:
706				fatal_error(ctx,
707	_("Only one of the options -p/-a, -n or -y may be specified."));
708			}
709			ctx->options |= E2F_OPT_PREEN;
710			break;
711		case 'n':
712			if (ctx->options & (E2F_OPT_YES|E2F_OPT_PREEN))
713				goto conflict_opt;
714			ctx->options |= E2F_OPT_NO;
715			break;
716		case 'y':
717			if (ctx->options & (E2F_OPT_PREEN|E2F_OPT_NO))
718				goto conflict_opt;
719			ctx->options |= E2F_OPT_YES;
720			break;
721		case 't':
722#ifdef RESOURCE_TRACK
723			if (ctx->options & E2F_OPT_TIME)
724				ctx->options |= E2F_OPT_TIME2;
725			else
726				ctx->options |= E2F_OPT_TIME;
727#else
728			fprintf(stderr, _("The -t option is not "
729				"supported on this version of e2fsck.\n"));
730#endif
731			break;
732		case 'c':
733			if (cflag++)
734				ctx->options |= E2F_OPT_WRITECHECK;
735			ctx->options |= E2F_OPT_CHECKBLOCKS;
736			break;
737		case 'r':
738			/* What we do by default, anyway! */
739			break;
740		case 'b':
741			res = sscanf(optarg, "%llu", &ctx->use_superblock);
742			if (res != 1)
743				goto sscanf_err;
744			ctx->flags |= E2F_FLAG_SB_SPECIFIED;
745			break;
746		case 'B':
747			ctx->blocksize = atoi(optarg);
748			break;
749		case 'I':
750			res = sscanf(optarg, "%d", &ctx->inode_buffer_blocks);
751			if (res != 1)
752				goto sscanf_err;
753			break;
754		case 'j':
755			ctx->journal_name = string_copy(ctx, optarg, 0);
756			break;
757		case 'P':
758			res = sscanf(optarg, "%d", &ctx->process_inode_size);
759			if (res != 1)
760				goto sscanf_err;
761			break;
762		case 'L':
763			replace_bad_blocks++;
764		case 'l':
765			bad_blocks_file = string_copy(ctx, optarg, 0);
766			break;
767		case 'd':
768			ctx->options |= E2F_OPT_DEBUG;
769			break;
770		case 'f':
771			ctx->options |= E2F_OPT_FORCE;
772			break;
773		case 'F':
774			flush = 1;
775			break;
776		case 'v':
777			verbose = 1;
778			break;
779		case 'V':
780			show_version_only = 1;
781			break;
782#ifdef MTRACE
783		case 'M':
784			mallwatch = (void *) strtol(optarg, NULL, 0);
785			break;
786#endif
787		case 'N':
788			ctx->device_name = string_copy(ctx, optarg, 0);
789			break;
790		case 'k':
791			keep_bad_blocks++;
792			break;
793		default:
794			usage(ctx);
795		}
796	if (show_version_only)
797		return 0;
798	if (optind != argc - 1)
799		usage(ctx);
800	if ((ctx->options & E2F_OPT_NO) &&
801	    (ctx->options & E2F_OPT_COMPRESS_DIRS)) {
802		com_err(ctx->program_name, 0,
803			_("The -n and -D options are incompatible."));
804		fatal_error(ctx, 0);
805	}
806	if ((ctx->options & E2F_OPT_NO) && cflag) {
807		com_err(ctx->program_name, 0,
808			_("The -n and -c options are incompatible."));
809		fatal_error(ctx, 0);
810	}
811	if ((ctx->options & E2F_OPT_NO) && bad_blocks_file) {
812		com_err(ctx->program_name, 0,
813			_("The -n and -l/-L options are incompatible."));
814		fatal_error(ctx, 0);
815	}
816	if (ctx->options & E2F_OPT_NO)
817		ctx->options |= E2F_OPT_READONLY;
818
819	ctx->io_options = strchr(argv[optind], '?');
820	if (ctx->io_options)
821		*ctx->io_options++ = 0;
822	ctx->filesystem_name = blkid_get_devname(ctx->blkid, argv[optind], 0);
823	if (!ctx->filesystem_name) {
824		com_err(ctx->program_name, 0, _("Unable to resolve '%s'"),
825			argv[optind]);
826		fatal_error(ctx, 0);
827	}
828	if (extended_opts)
829		parse_extended_opts(ctx, extended_opts);
830
831	if ((cp = getenv("E2FSCK_CONFIG")) != NULL)
832		config_fn[0] = cp;
833	profile_set_syntax_err_cb(syntax_err_report);
834	profile_init(config_fn, &ctx->profile);
835
836	if (flush) {
837		fd = open(ctx->filesystem_name, O_RDONLY, 0);
838		if (fd < 0) {
839			com_err("open", errno,
840				_("while opening %s for flushing"),
841				ctx->filesystem_name);
842			fatal_error(ctx, 0);
843		}
844		if ((retval = ext2fs_sync_device(fd, 1))) {
845			com_err("ext2fs_sync_device", retval,
846				_("while trying to flush %s"),
847				ctx->filesystem_name);
848			fatal_error(ctx, 0);
849		}
850		close(fd);
851	}
852	if (cflag && bad_blocks_file) {
853		fprintf(stderr, _("The -c and the -l/-L options may "
854				  "not be both used at the same time.\n"));
855		exit(FSCK_USAGE);
856	}
857#ifdef HAVE_SIGNAL_H
858	/*
859	 * Set up signal action
860	 */
861	memset(&sa, 0, sizeof(struct sigaction));
862	sa.sa_handler = signal_cancel;
863	sigaction(SIGINT, &sa, 0);
864	sigaction(SIGTERM, &sa, 0);
865#ifdef SA_RESTART
866	sa.sa_flags = SA_RESTART;
867#endif
868	e2fsck_global_ctx = ctx;
869	sa.sa_handler = signal_progress_on;
870	sigaction(SIGUSR1, &sa, 0);
871	sa.sa_handler = signal_progress_off;
872	sigaction(SIGUSR2, &sa, 0);
873#endif
874
875	/* Update our PATH to include /sbin if we need to run badblocks  */
876	if (cflag) {
877		char *oldpath = getenv("PATH");
878		char *newpath;
879		int len = sizeof(PATH_SET) + 1;
880
881		if (oldpath)
882			len += strlen(oldpath);
883
884		newpath = malloc(len);
885		if (!newpath)
886			fatal_error(ctx, "Couldn't malloc() newpath");
887		strcpy(newpath, PATH_SET);
888
889		if (oldpath) {
890			strcat(newpath, ":");
891			strcat(newpath, oldpath);
892		}
893		putenv(newpath);
894	}
895#ifdef CONFIG_JBD_DEBUG
896	jbd_debug = getenv("E2FSCK_JBD_DEBUG");
897	if (jbd_debug) {
898		res = sscanf(jbd_debug, "%d", &journal_enable_debug);
899		if (res != 1) {
900			fprintf(stderr,
901			        _("E2FSCK_JBD_DEBUG \"%s\" not an integer\n\n"),
902			        jbd_debug);
903			exit (1);
904		}
905	}
906#endif
907	return 0;
908
909sscanf_err:
910	fprintf(stderr, _("\nInvalid non-numeric argument to -%c (\"%s\")\n\n"),
911	        c, optarg);
912	exit (1);
913}
914
915static errcode_t try_open_fs(e2fsck_t ctx, int flags, io_manager io_ptr,
916			     ext2_filsys *ret_fs)
917{
918	errcode_t retval;
919
920	*ret_fs = NULL;
921	if (ctx->superblock && ctx->blocksize) {
922		retval = ext2fs_open2(ctx->filesystem_name, ctx->io_options,
923				      flags, ctx->superblock, ctx->blocksize,
924				      io_ptr, ret_fs);
925	} else if (ctx->superblock) {
926		int blocksize;
927		for (blocksize = EXT2_MIN_BLOCK_SIZE;
928		     blocksize <= EXT2_MAX_BLOCK_SIZE; blocksize *= 2) {
929			if (*ret_fs) {
930				ext2fs_free(*ret_fs);
931				*ret_fs = NULL;
932			}
933			retval = ext2fs_open2(ctx->filesystem_name,
934					      ctx->io_options, flags,
935					      ctx->superblock, blocksize,
936					      io_ptr, ret_fs);
937			if (!retval)
938				break;
939		}
940	} else
941		retval = ext2fs_open2(ctx->filesystem_name, ctx->io_options,
942				      flags, 0, 0, io_ptr, ret_fs);
943	return retval;
944}
945
946
947static const char *my_ver_string = E2FSPROGS_VERSION;
948static const char *my_ver_date = E2FSPROGS_DATE;
949
950int main (int argc, char *argv[])
951{
952	errcode_t	retval = 0, retval2 = 0, orig_retval = 0;
953	int		exit_value = FSCK_OK;
954	ext2_filsys	fs = 0;
955	io_manager	io_ptr;
956	struct ext2_super_block *sb;
957	const char	*lib_ver_date;
958	int		my_ver, lib_ver;
959	e2fsck_t	ctx;
960	blk_t		orig_superblock;
961	struct problem_context pctx;
962	int flags, run_result;
963	int journal_size;
964	int sysval, sys_page_size = 4096;
965	int old_bitmaps;
966	__u32 features[3];
967	char *cp;
968
969	clear_problem_context(&pctx);
970#ifdef MTRACE
971	mtrace();
972#endif
973#ifdef MCHECK
974	mcheck(0);
975#endif
976#ifdef ENABLE_NLS
977	setlocale(LC_MESSAGES, "");
978	setlocale(LC_CTYPE, "");
979	bindtextdomain(NLS_CAT_NAME, LOCALEDIR);
980	textdomain(NLS_CAT_NAME);
981#endif
982	my_ver = ext2fs_parse_version_string(my_ver_string);
983	lib_ver = ext2fs_get_library_version(0, &lib_ver_date);
984	if (my_ver > lib_ver) {
985		fprintf( stderr, _("Error: ext2fs library version "
986			"out of date!\n"));
987		show_version_only++;
988	}
989
990	retval = PRS(argc, argv, &ctx);
991	if (retval) {
992		com_err("e2fsck", retval,
993			_("while trying to initialize program"));
994		exit(FSCK_ERROR);
995	}
996	reserve_stdio_fds();
997
998	init_resource_track(&ctx->global_rtrack, NULL);
999	if (!(ctx->options & E2F_OPT_PREEN) || show_version_only)
1000		fprintf(stderr, "e2fsck %s (%s)\n", my_ver_string,
1001			 my_ver_date);
1002
1003	if (show_version_only) {
1004		fprintf(stderr, _("\tUsing %s, %s\n"),
1005			error_message(EXT2_ET_BASE), lib_ver_date);
1006		exit(FSCK_OK);
1007	}
1008
1009	check_mount(ctx);
1010
1011	if (!(ctx->options & E2F_OPT_PREEN) &&
1012	    !(ctx->options & E2F_OPT_NO) &&
1013	    !(ctx->options & E2F_OPT_YES)) {
1014		if (!ctx->interactive)
1015			fatal_error(ctx,
1016				    _("need terminal for interactive repairs"));
1017	}
1018	ctx->superblock = ctx->use_superblock;
1019restart:
1020#ifdef CONFIG_TESTIO_DEBUG
1021	if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_BLOCK")) {
1022		io_ptr = test_io_manager;
1023		test_io_backing_manager = unix_io_manager;
1024	} else
1025#endif
1026		io_ptr = unix_io_manager;
1027	flags = EXT2_FLAG_NOFREE_ON_ERROR;
1028	profile_get_boolean(ctx->profile, "options", "old_bitmaps", 0, 0,
1029			    &old_bitmaps);
1030	if (!old_bitmaps)
1031		flags |= EXT2_FLAG_64BITS;
1032	if ((ctx->options & E2F_OPT_READONLY) == 0)
1033		flags |= EXT2_FLAG_RW;
1034	if ((ctx->mount_flags & EXT2_MF_MOUNTED) == 0)
1035		flags |= EXT2_FLAG_EXCLUSIVE;
1036
1037	retval = try_open_fs(ctx, flags, io_ptr, &fs);
1038
1039	if (!ctx->superblock && !(ctx->options & E2F_OPT_PREEN) &&
1040	    !(ctx->flags & E2F_FLAG_SB_SPECIFIED) &&
1041	    ((retval == EXT2_ET_BAD_MAGIC) ||
1042	     (retval == EXT2_ET_CORRUPT_SUPERBLOCK) ||
1043	     ((retval == 0) && (retval2 = ext2fs_check_desc(fs))))) {
1044		if (retval2 == ENOMEM) {
1045			retval = retval2;
1046			goto failure;
1047		}
1048		if (fs->flags & EXT2_FLAG_NOFREE_ON_ERROR) {
1049			ext2fs_free(fs);
1050			fs = NULL;
1051		}
1052		if (!fs || (fs->group_desc_count > 1)) {
1053			printf(_("%s: %s trying backup blocks...\n"),
1054			       ctx->program_name,
1055			       retval ? _("Superblock invalid,") :
1056			       _("Group descriptors look bad..."));
1057			orig_superblock = ctx->superblock;
1058			get_backup_sb(ctx, fs, ctx->filesystem_name, io_ptr);
1059			if (fs)
1060				ext2fs_close(fs);
1061			orig_retval = retval;
1062			retval = try_open_fs(ctx, flags, io_ptr, &fs);
1063			if ((orig_retval == 0) && retval != 0) {
1064				com_err(ctx->program_name, retval,
1065					"when using the backup blocks");
1066				printf(_("%s: going back to original "
1067					 "superblock\n"), ctx->program_name);
1068				ctx->superblock = orig_superblock;
1069				retval = try_open_fs(ctx, flags, io_ptr, &fs);
1070			}
1071		}
1072	}
1073	if (((retval == EXT2_ET_UNSUPP_FEATURE) ||
1074	     (retval == EXT2_ET_RO_UNSUPP_FEATURE)) &&
1075	    fs && fs->super) {
1076		sb = fs->super;
1077		features[0] = (sb->s_feature_compat &
1078			       ~EXT2_LIB_FEATURE_COMPAT_SUPP);
1079		features[1] = (sb->s_feature_incompat &
1080			       ~EXT2_LIB_FEATURE_INCOMPAT_SUPP);
1081		features[2] = (sb->s_feature_ro_compat &
1082			       ~EXT2_LIB_FEATURE_RO_COMPAT_SUPP);
1083		if (features[0] || features[1] || features[2])
1084			goto print_unsupp_features;
1085	}
1086failure:
1087	if (retval) {
1088		if (orig_retval)
1089			retval = orig_retval;
1090		com_err(ctx->program_name, retval, _("while trying to open %s"),
1091			ctx->filesystem_name);
1092		if (retval == EXT2_ET_REV_TOO_HIGH) {
1093			printf(_("The filesystem revision is apparently "
1094			       "too high for this version of e2fsck.\n"
1095			       "(Or the filesystem superblock "
1096			       "is corrupt)\n\n"));
1097			fix_problem(ctx, PR_0_SB_CORRUPT, &pctx);
1098		} else if (retval == EXT2_ET_SHORT_READ)
1099			printf(_("Could this be a zero-length partition?\n"));
1100		else if ((retval == EPERM) || (retval == EACCES))
1101			printf(_("You must have %s access to the "
1102			       "filesystem or be root\n"),
1103			       (ctx->options & E2F_OPT_READONLY) ?
1104			       "r/o" : "r/w");
1105		else if (retval == ENXIO)
1106			printf(_("Possibly non-existent or swap device?\n"));
1107		else if (retval == EBUSY)
1108			printf(_("Filesystem mounted or opened exclusively "
1109				 "by another program?\n"));
1110#ifdef EROFS
1111		else if (retval == EROFS)
1112			printf(_("Disk write-protected; use the -n option "
1113			       "to do a read-only\n"
1114			       "check of the device.\n"));
1115#endif
1116		else
1117			fix_problem(ctx, PR_0_SB_CORRUPT, &pctx);
1118		fatal_error(ctx, 0);
1119	}
1120	/*
1121	 * We only update the master superblock because (a) paranoia;
1122	 * we don't want to corrupt the backup superblocks, and (b) we
1123	 * don't need to update the mount count and last checked
1124	 * fields in the backup superblock (the kernel doesn't update
1125	 * the backup superblocks anyway).  With newer versions of the
1126	 * library this flag is set by ext2fs_open2(), but we set this
1127	 * here just to be sure.  (No, we don't support e2fsck running
1128	 * with some other libext2fs than the one that it was shipped
1129	 * with, but just in case....)
1130	 */
1131	fs->flags |= EXT2_FLAG_MASTER_SB_ONLY;
1132
1133	if (!(ctx->flags & E2F_FLAG_GOT_DEVSIZE)) {
1134		__u32 blocksize = EXT2_BLOCK_SIZE(fs->super);
1135		int need_restart = 0;
1136
1137		pctx.errcode = ext2fs_get_device_size2(ctx->filesystem_name,
1138						       blocksize,
1139						       &ctx->num_blocks);
1140		/*
1141		 * The floppy driver refuses to allow anyone else to
1142		 * open the device if has been opened with O_EXCL;
1143		 * this is unlike other block device drivers in Linux.
1144		 * To handle this, we close the filesystem and then
1145		 * reopen the filesystem after we get the device size.
1146		 */
1147		if (pctx.errcode == EBUSY) {
1148			ext2fs_close(fs);
1149			need_restart++;
1150			pctx.errcode =
1151				ext2fs_get_device_size2(ctx->filesystem_name,
1152							blocksize,
1153							&ctx->num_blocks);
1154		}
1155		if (pctx.errcode == EXT2_ET_UNIMPLEMENTED)
1156			ctx->num_blocks = 0;
1157		else if (pctx.errcode) {
1158			fix_problem(ctx, PR_0_GETSIZE_ERROR, &pctx);
1159			ctx->flags |= E2F_FLAG_ABORT;
1160			fatal_error(ctx, 0);
1161		}
1162		ctx->flags |= E2F_FLAG_GOT_DEVSIZE;
1163		if (need_restart)
1164			goto restart;
1165	}
1166
1167	ctx->fs = fs;
1168	fs->priv_data = ctx;
1169	fs->now = ctx->now;
1170	sb = fs->super;
1171	if (sb->s_rev_level > E2FSCK_CURRENT_REV) {
1172		com_err(ctx->program_name, EXT2_ET_REV_TOO_HIGH,
1173			_("while trying to open %s"),
1174			ctx->filesystem_name);
1175	get_newer:
1176		fatal_error(ctx, _("Get a newer version of e2fsck!"));
1177	}
1178
1179	/*
1180	 * Set the device name, which is used whenever we print error
1181	 * or informational messages to the user.
1182	 */
1183	if (ctx->device_name == 0 &&
1184	    (sb->s_volume_name[0] != 0)) {
1185		ctx->device_name = string_copy(ctx, sb->s_volume_name,
1186					       sizeof(sb->s_volume_name));
1187	}
1188	if (ctx->device_name == 0)
1189		ctx->device_name = string_copy(ctx, ctx->filesystem_name, 0);
1190	for (cp = ctx->device_name; *cp; cp++)
1191		if (isspace(*cp) || *cp == ':')
1192			*cp = '_';
1193
1194	ehandler_init(fs->io);
1195
1196	if ((ctx->mount_flags & EXT2_MF_MOUNTED) &&
1197	    !(sb->s_feature_incompat & EXT3_FEATURE_INCOMPAT_RECOVER))
1198		goto skip_journal;
1199
1200	/*
1201	 * Make sure the ext3 superblock fields are consistent.
1202	 */
1203	retval = e2fsck_check_ext3_journal(ctx);
1204	if (retval) {
1205		com_err(ctx->program_name, retval,
1206			_("while checking ext3 journal for %s"),
1207			ctx->device_name);
1208		fatal_error(ctx, 0);
1209	}
1210
1211	/*
1212	 * Check to see if we need to do ext3-style recovery.  If so,
1213	 * do it, and then restart the fsck.
1214	 */
1215	if (sb->s_feature_incompat & EXT3_FEATURE_INCOMPAT_RECOVER) {
1216		if (ctx->options & E2F_OPT_READONLY) {
1217			printf(_("Warning: skipping journal recovery "
1218				 "because doing a read-only filesystem "
1219				 "check.\n"));
1220			io_channel_flush(ctx->fs->io);
1221		} else {
1222			if (ctx->flags & E2F_FLAG_RESTARTED) {
1223				/*
1224				 * Whoops, we attempted to run the
1225				 * journal twice.  This should never
1226				 * happen, unless the hardware or
1227				 * device driver is being bogus.
1228				 */
1229				com_err(ctx->program_name, 0,
1230					_("unable to set superblock flags on %s\n"), ctx->device_name);
1231				fatal_error(ctx, 0);
1232			}
1233			retval = e2fsck_run_ext3_journal(ctx);
1234			if (retval) {
1235				com_err(ctx->program_name, retval,
1236				_("while recovering ext3 journal of %s"),
1237					ctx->device_name);
1238				fatal_error(ctx, 0);
1239			}
1240			ext2fs_close(ctx->fs);
1241			ctx->fs = 0;
1242			ctx->flags |= E2F_FLAG_RESTARTED;
1243			goto restart;
1244		}
1245	}
1246
1247skip_journal:
1248	/*
1249	 * Check for compatibility with the feature sets.  We need to
1250	 * be more stringent than ext2fs_open().
1251	 */
1252	features[0] = sb->s_feature_compat & ~EXT2_LIB_FEATURE_COMPAT_SUPP;
1253	features[1] = sb->s_feature_incompat & ~EXT2_LIB_FEATURE_INCOMPAT_SUPP;
1254	features[2] = (sb->s_feature_ro_compat &
1255		       ~EXT2_LIB_FEATURE_RO_COMPAT_SUPP);
1256print_unsupp_features:
1257	if (features[0] || features[1] || features[2]) {
1258		int	i, j;
1259		__u32	*mask = features, m;
1260
1261		fprintf(stderr, _("%s has unsupported feature(s):"),
1262			ctx->filesystem_name);
1263
1264		for (i=0; i <3; i++,mask++) {
1265			for (j=0,m=1; j < 32; j++, m<<=1) {
1266				if (*mask & m)
1267					fprintf(stderr, " %s",
1268						e2p_feature2string(i, m));
1269			}
1270		}
1271		putc('\n', stderr);
1272		goto get_newer;
1273	}
1274#ifdef ENABLE_COMPRESSION
1275	if (sb->s_feature_incompat & EXT2_FEATURE_INCOMPAT_COMPRESSION)
1276		com_err(ctx->program_name, 0,
1277			_("Warning: compression support is experimental.\n"));
1278#endif
1279#ifndef ENABLE_HTREE
1280	if (sb->s_feature_compat & EXT2_FEATURE_COMPAT_DIR_INDEX) {
1281		com_err(ctx->program_name, 0,
1282			_("E2fsck not compiled with HTREE support,\n\t"
1283			  "but filesystem %s has HTREE directories.\n"),
1284			ctx->device_name);
1285		goto get_newer;
1286	}
1287#endif
1288
1289	/*
1290	 * If the user specified a specific superblock, presumably the
1291	 * master superblock has been trashed.  So we mark the
1292	 * superblock as dirty, so it can be written out.
1293	 */
1294	if (ctx->superblock &&
1295	    !(ctx->options & E2F_OPT_READONLY))
1296		ext2fs_mark_super_dirty(fs);
1297
1298	/*
1299	 * Calculate the number of filesystem blocks per pagesize.  If
1300	 * fs->blocksize > page_size, set the number of blocks per
1301	 * pagesize to 1 to avoid division by zero errors.
1302	 */
1303#ifdef _SC_PAGESIZE
1304	sysval = sysconf(_SC_PAGESIZE);
1305	if (sysval > 0)
1306		sys_page_size = sysval;
1307#endif /* _SC_PAGESIZE */
1308	ctx->blocks_per_page = sys_page_size / fs->blocksize;
1309	if (ctx->blocks_per_page == 0)
1310		ctx->blocks_per_page = 1;
1311
1312	if (ctx->superblock)
1313		set_latch_flags(PR_LATCH_RELOC, PRL_LATCHED, 0);
1314	ext2fs_mark_valid(fs);
1315	check_super_block(ctx);
1316	if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
1317		fatal_error(ctx, 0);
1318	check_if_skip(ctx);
1319	check_resize_inode(ctx);
1320	if (bad_blocks_file)
1321		read_bad_blocks_file(ctx, bad_blocks_file, replace_bad_blocks);
1322	else if (cflag)
1323		read_bad_blocks_file(ctx, 0, !keep_bad_blocks); /* Test disk */
1324	if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
1325		fatal_error(ctx, 0);
1326
1327	/*
1328	 * Mark the system as valid, 'til proven otherwise
1329	 */
1330	ext2fs_mark_valid(fs);
1331
1332	retval = ext2fs_read_bb_inode(fs, &fs->badblocks);
1333	if (retval) {
1334		com_err(ctx->program_name, retval,
1335			_("while reading bad blocks inode"));
1336		preenhalt(ctx);
1337		printf(_("This doesn't bode well,"
1338			 " but we'll try to go on...\n"));
1339	}
1340
1341	/*
1342	 * Save the journal size in megabytes.
1343	 * Try and use the journal size from the backup else let e2fsck
1344	 * find the default journal size.
1345	 */
1346	if (sb->s_jnl_backup_type == EXT3_JNL_BACKUP_BLOCKS)
1347		journal_size = sb->s_jnl_blocks[16] >> 20;
1348	else
1349		journal_size = -1;
1350
1351	run_result = e2fsck_run(ctx);
1352	e2fsck_clear_progbar(ctx);
1353
1354	if (ctx->flags & E2F_FLAG_JOURNAL_INODE) {
1355		if (fix_problem(ctx, PR_6_RECREATE_JOURNAL, &pctx)) {
1356			if (journal_size < 1024)
1357				journal_size = ext2fs_default_journal_size(ext2fs_blocks_count(fs->super));
1358			if (journal_size < 0) {
1359				fs->super->s_feature_compat &=
1360					~EXT3_FEATURE_COMPAT_HAS_JOURNAL;
1361				fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
1362				com_err(ctx->program_name, 0,
1363					_("Couldn't determine journal size"));
1364				goto no_journal;
1365			}
1366			printf(_("Creating journal (%d blocks): "),
1367			       journal_size);
1368			fflush(stdout);
1369			retval = ext2fs_add_journal_inode(fs,
1370							  journal_size, 0);
1371			if (retval) {
1372				com_err("Error ", retval,
1373					_("\n\twhile trying to create journal"));
1374				goto no_journal;
1375			}
1376			printf(_(" Done.\n"));
1377			printf(_("\n*** journal has been re-created - "
1378				       "filesystem is now ext3 again ***\n"));
1379		}
1380	}
1381no_journal:
1382
1383	if (run_result == E2F_FLAG_RESTART) {
1384		printf(_("Restarting e2fsck from the beginning...\n"));
1385		retval = e2fsck_reset_context(ctx);
1386		if (retval) {
1387			com_err(ctx->program_name, retval,
1388				_("while resetting context"));
1389			fatal_error(ctx, 0);
1390		}
1391		ext2fs_close(fs);
1392		goto restart;
1393	}
1394	if (run_result & E2F_FLAG_CANCEL) {
1395		printf(_("%s: e2fsck canceled.\n"), ctx->device_name ?
1396		       ctx->device_name : ctx->filesystem_name);
1397		exit_value |= FSCK_CANCELED;
1398	}
1399	if (run_result & E2F_FLAG_ABORT)
1400		fatal_error(ctx, _("aborted"));
1401	if (check_backup_super_block(ctx)) {
1402		fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
1403		ext2fs_mark_super_dirty(fs);
1404	}
1405
1406#ifdef MTRACE
1407	mtrace_print("Cleanup");
1408#endif
1409	if (ext2fs_test_changed(fs)) {
1410		exit_value |= FSCK_NONDESTRUCT;
1411		if (!(ctx->options & E2F_OPT_PREEN))
1412		    printf(_("\n%s: ***** FILE SYSTEM WAS MODIFIED *****\n"),
1413			       ctx->device_name);
1414		if (ctx->mount_flags & EXT2_MF_ISROOT) {
1415			printf(_("%s: ***** REBOOT LINUX *****\n"),
1416			       ctx->device_name);
1417			exit_value |= FSCK_REBOOT;
1418		}
1419	}
1420	if (!ext2fs_test_valid(fs) ||
1421	    ((exit_value & FSCK_CANCELED) &&
1422	     (sb->s_state & EXT2_ERROR_FS))) {
1423		printf(_("\n%s: ********** WARNING: Filesystem still has "
1424			 "errors **********\n\n"), ctx->device_name);
1425		exit_value |= FSCK_UNCORRECTED;
1426		exit_value &= ~FSCK_NONDESTRUCT;
1427	}
1428	if (exit_value & FSCK_CANCELED) {
1429		int	allow_cancellation;
1430
1431		profile_get_boolean(ctx->profile, "options",
1432				    "allow_cancellation", 0, 0,
1433				    &allow_cancellation);
1434		exit_value &= ~FSCK_NONDESTRUCT;
1435		if (allow_cancellation && ext2fs_test_valid(fs) &&
1436		    (sb->s_state & EXT2_VALID_FS) &&
1437		    !(sb->s_state & EXT2_ERROR_FS))
1438			exit_value = 0;
1439	} else {
1440		show_stats(ctx);
1441		if (!(ctx->options & E2F_OPT_READONLY)) {
1442			if (ext2fs_test_valid(fs)) {
1443				if (!(sb->s_state & EXT2_VALID_FS))
1444					exit_value |= FSCK_NONDESTRUCT;
1445				sb->s_state = EXT2_VALID_FS;
1446			} else
1447				sb->s_state &= ~EXT2_VALID_FS;
1448			sb->s_mnt_count = 0;
1449			if (!(ctx->flags & E2F_FLAG_TIME_INSANE))
1450				sb->s_lastcheck = ctx->now;
1451			ext2fs_mark_super_dirty(fs);
1452		}
1453	}
1454
1455	if ((run_result & E2F_FLAG_CANCEL) == 0 &&
1456	    sb->s_feature_ro_compat & EXT4_FEATURE_RO_COMPAT_GDT_CSUM &&
1457	    !(ctx->options & E2F_OPT_READONLY)) {
1458		retval = ext2fs_set_gdt_csum(ctx->fs);
1459		if (retval) {
1460			com_err(ctx->program_name, retval,
1461				_("while setting block group checksum info"));
1462			fatal_error(ctx, 0);
1463		}
1464	}
1465
1466	e2fsck_write_bitmaps(ctx);
1467	io_channel_flush(ctx->fs->io);
1468	print_resource_track(ctx, NULL, &ctx->global_rtrack, ctx->fs->io);
1469
1470	ext2fs_close(fs);
1471	ctx->fs = NULL;
1472	free(ctx->journal_name);
1473
1474	e2fsck_free_context(ctx);
1475	remove_error_table(&et_ext2_error_table);
1476	remove_error_table(&et_prof_error_table);
1477	return exit_value;
1478}
1479