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