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