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