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