Home | History | Annotate | Download | only in misc
      1 /*
      2  * mke2fs.c - Make a ext2fs filesystem.
      3  *
      4  * Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
      5  * 	2003, 2004, 2005 by Theodore Ts'o.
      6  *
      7  * %Begin-Header%
      8  * This file may be redistributed under the terms of the GNU Public
      9  * License.
     10  * %End-Header%
     11  */
     12 
     13 /* Usage: mke2fs [options] device
     14  *
     15  * The device may be a block device or a image of one, but this isn't
     16  * enforced (but it's not much fun on a character device :-).
     17  */
     18 
     19 #define _XOPEN_SOURCE 600 /* for inclusion of PATH_MAX in Solaris */
     20 
     21 #include <stdio.h>
     22 #include <string.h>
     23 #include <strings.h>
     24 #include <fcntl.h>
     25 #include <ctype.h>
     26 #include <time.h>
     27 #ifdef __linux__
     28 #include <sys/utsname.h>
     29 #endif
     30 #ifdef HAVE_GETOPT_H
     31 #include <getopt.h>
     32 #else
     33 extern char *optarg;
     34 extern int optind;
     35 #endif
     36 #ifdef HAVE_UNISTD_H
     37 #include <unistd.h>
     38 #endif
     39 #ifdef HAVE_STDLIB_H
     40 #include <stdlib.h>
     41 #endif
     42 #ifdef HAVE_ERRNO_H
     43 #include <errno.h>
     44 #endif
     45 #ifdef HAVE_MNTENT_H
     46 #include <mntent.h>
     47 #endif
     48 #include <sys/ioctl.h>
     49 #include <sys/types.h>
     50 #include <sys/stat.h>
     51 #include <libgen.h>
     52 #include <limits.h>
     53 #include <blkid/blkid.h>
     54 
     55 #include "ext2fs/ext2_fs.h"
     56 #include "et/com_err.h"
     57 #include "uuid/uuid.h"
     58 #include "e2p/e2p.h"
     59 #include "ext2fs/ext2fs.h"
     60 #include "util.h"
     61 #include "profile.h"
     62 #include "prof_err.h"
     63 #include "../version.h"
     64 #include "nls-enable.h"
     65 
     66 #define STRIDE_LENGTH 8
     67 
     68 #ifndef __sparc__
     69 #define ZAP_BOOTBLOCK
     70 #endif
     71 
     72 #ifndef ROOT_SYSCONFDIR
     73 #define ROOT_SYSCONFDIR "/etc"
     74 #endif
     75 
     76 extern int isatty(int);
     77 extern FILE *fpopen(const char *cmd, const char *mode);
     78 
     79 const char * program_name = "mke2fs";
     80 const char * device_name /* = NULL */;
     81 
     82 /* Command line options */
     83 int	cflag;
     84 int	verbose;
     85 int	quiet;
     86 int	super_only;
     87 int	discard = 1;	/* attempt to discard device before fs creation */
     88 int	force;
     89 int	noaction;
     90 int	journal_size;
     91 int	journal_flags;
     92 int	lazy_itable_init;
     93 char	*bad_blocks_filename;
     94 __u32	fs_stride;
     95 
     96 struct ext2_super_block fs_param;
     97 char *fs_uuid = NULL;
     98 char *creator_os;
     99 char *volume_label;
    100 char *mount_dir;
    101 char *journal_device;
    102 int sync_kludge;	/* Set using the MKE2FS_SYNC env. option */
    103 char **fs_types;
    104 
    105 profile_t	profile;
    106 
    107 int sys_page_size = 4096;
    108 int linux_version_code = 0;
    109 
    110 static void usage(void)
    111 {
    112 	fprintf(stderr, _("Usage: %s [-c|-l filename] [-b block-size] "
    113 	"[-f fragment-size]\n\t[-i bytes-per-inode] [-I inode-size] "
    114 	"[-J journal-options]\n"
    115 	"\t[-G meta group size] [-N number-of-inodes]\n"
    116 	"\t[-m reserved-blocks-percentage] [-o creator-os]\n"
    117 	"\t[-g blocks-per-group] [-L volume-label] "
    118 	"[-M last-mounted-directory]\n\t[-O feature[,...]] "
    119 	"[-r fs-revision] [-E extended-option[,...]]\n"
    120 	"\t[-T fs-type] [-U UUID] [-jnqvFKSV] device [blocks-count]\n"),
    121 		program_name);
    122 	exit(1);
    123 }
    124 
    125 static int int_log2(int arg)
    126 {
    127 	int	l = 0;
    128 
    129 	arg >>= 1;
    130 	while (arg) {
    131 		l++;
    132 		arg >>= 1;
    133 	}
    134 	return l;
    135 }
    136 
    137 static int int_log10(unsigned int arg)
    138 {
    139 	int	l;
    140 
    141 	for (l=0; arg ; l++)
    142 		arg = arg / 10;
    143 	return l;
    144 }
    145 
    146 static int parse_version_number(const char *s)
    147 {
    148 	int	major, minor, rev;
    149 	char	*endptr;
    150 	const char *cp = s;
    151 
    152 	if (!s)
    153 		return 0;
    154 	major = strtol(cp, &endptr, 10);
    155 	if (cp == endptr || *endptr != '.')
    156 		return 0;
    157 	cp = endptr + 1;
    158 	minor = strtol(cp, &endptr, 10);
    159 	if (cp == endptr || *endptr != '.')
    160 		return 0;
    161 	cp = endptr + 1;
    162 	rev = strtol(cp, &endptr, 10);
    163 	if (cp == endptr)
    164 		return 0;
    165 	return ((((major * 256) + minor) * 256) + rev);
    166 }
    167 
    168 /*
    169  * Helper function for read_bb_file and test_disk
    170  */
    171 static void invalid_block(ext2_filsys fs EXT2FS_ATTR((unused)), blk_t blk)
    172 {
    173 	fprintf(stderr, _("Bad block %u out of range; ignored.\n"), blk);
    174 	return;
    175 }
    176 
    177 /*
    178  * Reads the bad blocks list from a file
    179  */
    180 static void read_bb_file(ext2_filsys fs, badblocks_list *bb_list,
    181 			 const char *bad_blocks_file)
    182 {
    183 	FILE		*f;
    184 	errcode_t	retval;
    185 
    186 	f = fopen(bad_blocks_file, "r");
    187 	if (!f) {
    188 		com_err("read_bad_blocks_file", errno,
    189 			_("while trying to open %s"), bad_blocks_file);
    190 		exit(1);
    191 	}
    192 	retval = ext2fs_read_bb_FILE(fs, f, bb_list, invalid_block);
    193 	fclose (f);
    194 	if (retval) {
    195 		com_err("ext2fs_read_bb_FILE", retval,
    196 			_("while reading in list of bad blocks from file"));
    197 		exit(1);
    198 	}
    199 }
    200 
    201 /*
    202  * Runs the badblocks program to test the disk
    203  */
    204 static void test_disk(ext2_filsys fs, badblocks_list *bb_list)
    205 {
    206 	FILE		*f;
    207 	errcode_t	retval;
    208 	char		buf[1024];
    209 
    210 	sprintf(buf, "badblocks -b %d -X %s%s%s %u", fs->blocksize,
    211 		quiet ? "" : "-s ", (cflag > 1) ? "-w " : "",
    212 		fs->device_name, fs->super->s_blocks_count-1);
    213 	if (verbose)
    214 		printf(_("Running command: %s\n"), buf);
    215 	f = popen(buf, "r");
    216 	if (!f) {
    217 		com_err("popen", errno,
    218 			_("while trying to run '%s'"), buf);
    219 		exit(1);
    220 	}
    221 	retval = ext2fs_read_bb_FILE(fs, f, bb_list, invalid_block);
    222 	pclose(f);
    223 	if (retval) {
    224 		com_err("ext2fs_read_bb_FILE", retval,
    225 			_("while processing list of bad blocks from program"));
    226 		exit(1);
    227 	}
    228 }
    229 
    230 static void handle_bad_blocks(ext2_filsys fs, badblocks_list bb_list)
    231 {
    232 	dgrp_t			i;
    233 	blk_t			j;
    234 	unsigned 		must_be_good;
    235 	blk_t			blk;
    236 	badblocks_iterate	bb_iter;
    237 	errcode_t		retval;
    238 	blk_t			group_block;
    239 	int			group;
    240 	int			group_bad;
    241 
    242 	if (!bb_list)
    243 		return;
    244 
    245 	/*
    246 	 * The primary superblock and group descriptors *must* be
    247 	 * good; if not, abort.
    248 	 */
    249 	must_be_good = fs->super->s_first_data_block + 1 + fs->desc_blocks;
    250 	for (i = fs->super->s_first_data_block; i <= must_be_good; i++) {
    251 		if (ext2fs_badblocks_list_test(bb_list, i)) {
    252 			fprintf(stderr, _("Block %d in primary "
    253 				"superblock/group descriptor area bad.\n"), i);
    254 			fprintf(stderr, _("Blocks %u through %u must be good "
    255 				"in order to build a filesystem.\n"),
    256 				fs->super->s_first_data_block, must_be_good);
    257 			fputs(_("Aborting....\n"), stderr);
    258 			exit(1);
    259 		}
    260 	}
    261 
    262 	/*
    263 	 * See if any of the bad blocks are showing up in the backup
    264 	 * superblocks and/or group descriptors.  If so, issue a
    265 	 * warning and adjust the block counts appropriately.
    266 	 */
    267 	group_block = fs->super->s_first_data_block +
    268 		fs->super->s_blocks_per_group;
    269 
    270 	for (i = 1; i < fs->group_desc_count; i++) {
    271 		group_bad = 0;
    272 		for (j=0; j < fs->desc_blocks+1; j++) {
    273 			if (ext2fs_badblocks_list_test(bb_list,
    274 						       group_block + j)) {
    275 				if (!group_bad)
    276 					fprintf(stderr,
    277 _("Warning: the backup superblock/group descriptors at block %u contain\n"
    278 "	bad blocks.\n\n"),
    279 						group_block);
    280 				group_bad++;
    281 				group = ext2fs_group_of_blk(fs, group_block+j);
    282 				fs->group_desc[group].bg_free_blocks_count++;
    283 				ext2fs_group_desc_csum_set(fs, group);
    284 				fs->super->s_free_blocks_count++;
    285 			}
    286 		}
    287 		group_block += fs->super->s_blocks_per_group;
    288 	}
    289 
    290 	/*
    291 	 * Mark all the bad blocks as used...
    292 	 */
    293 	retval = ext2fs_badblocks_list_iterate_begin(bb_list, &bb_iter);
    294 	if (retval) {
    295 		com_err("ext2fs_badblocks_list_iterate_begin", retval,
    296 			_("while marking bad blocks as used"));
    297 		exit(1);
    298 	}
    299 	while (ext2fs_badblocks_list_iterate(bb_iter, &blk))
    300 		ext2fs_mark_block_bitmap(fs->block_map, blk);
    301 	ext2fs_badblocks_list_iterate_end(bb_iter);
    302 }
    303 
    304 /*
    305  * These functions implement a generalized progress meter.
    306  */
    307 struct progress_struct {
    308 	char		format[20];
    309 	char		backup[80];
    310 	__u32		max;
    311 	int		skip_progress;
    312 };
    313 
    314 static void progress_init(struct progress_struct *progress,
    315 			  const char *label,__u32 max)
    316 {
    317 	int	i;
    318 
    319 	memset(progress, 0, sizeof(struct progress_struct));
    320 	if (quiet)
    321 		return;
    322 
    323 	/*
    324 	 * Figure out how many digits we need
    325 	 */
    326 	i = int_log10(max);
    327 	sprintf(progress->format, "%%%dd/%%%dld", i, i);
    328 	memset(progress->backup, '\b', sizeof(progress->backup)-1);
    329 	progress->backup[sizeof(progress->backup)-1] = 0;
    330 	if ((2*i)+1 < (int) sizeof(progress->backup))
    331 		progress->backup[(2*i)+1] = 0;
    332 	progress->max = max;
    333 
    334 	progress->skip_progress = 0;
    335 	if (getenv("MKE2FS_SKIP_PROGRESS"))
    336 		progress->skip_progress++;
    337 
    338 	fputs(label, stdout);
    339 	fflush(stdout);
    340 }
    341 
    342 static void progress_update(struct progress_struct *progress, __u32 val)
    343 {
    344 	if ((progress->format[0] == 0) || progress->skip_progress)
    345 		return;
    346 	printf(progress->format, val, progress->max);
    347 	fputs(progress->backup, stdout);
    348 }
    349 
    350 static void progress_close(struct progress_struct *progress)
    351 {
    352 	if (progress->format[0] == 0)
    353 		return;
    354 	fputs(_("done                            \n"), stdout);
    355 }
    356 
    357 static void write_inode_tables(ext2_filsys fs, int lazy_flag, int itable_zeroed)
    358 {
    359 	errcode_t	retval;
    360 	blk_t		blk;
    361 	dgrp_t		i;
    362 	int		num, ipb;
    363 	struct progress_struct progress;
    364 
    365 	if (quiet)
    366 		memset(&progress, 0, sizeof(progress));
    367 	else
    368 		progress_init(&progress, _("Writing inode tables: "),
    369 			      fs->group_desc_count);
    370 
    371 	for (i = 0; i < fs->group_desc_count; i++) {
    372 		progress_update(&progress, i);
    373 
    374 		blk = fs->group_desc[i].bg_inode_table;
    375 		num = fs->inode_blocks_per_group;
    376 
    377 		if (lazy_flag) {
    378 			ipb = fs->blocksize / EXT2_INODE_SIZE(fs->super);
    379 			num = ((((fs->super->s_inodes_per_group -
    380 				  fs->group_desc[i].bg_itable_unused) *
    381 				 EXT2_INODE_SIZE(fs->super)) +
    382 				EXT2_BLOCK_SIZE(fs->super) - 1) /
    383 			       EXT2_BLOCK_SIZE(fs->super));
    384 		}
    385 		if (!lazy_flag || itable_zeroed) {
    386 			/* The kernel doesn't need to zero the itable blocks */
    387 			fs->group_desc[i].bg_flags |= EXT2_BG_INODE_ZEROED;
    388 			ext2fs_group_desc_csum_set(fs, i);
    389 		}
    390 		retval = ext2fs_zero_blocks(fs, blk, num, &blk, &num);
    391 		if (retval) {
    392 			fprintf(stderr, _("\nCould not write %d "
    393 				  "blocks in inode table starting at %u: %s\n"),
    394 				num, blk, error_message(retval));
    395 			exit(1);
    396 		}
    397 		if (sync_kludge) {
    398 			if (sync_kludge == 1)
    399 				sync();
    400 			else if ((i % sync_kludge) == 0)
    401 				sync();
    402 		}
    403 	}
    404 	ext2fs_zero_blocks(0, 0, 0, 0, 0);
    405 	progress_close(&progress);
    406 }
    407 
    408 static void create_root_dir(ext2_filsys fs)
    409 {
    410 	errcode_t		retval;
    411 	struct ext2_inode	inode;
    412 	__u32			uid, gid;
    413 
    414 	retval = ext2fs_mkdir(fs, EXT2_ROOT_INO, EXT2_ROOT_INO, 0);
    415 	if (retval) {
    416 		com_err("ext2fs_mkdir", retval, _("while creating root dir"));
    417 		exit(1);
    418 	}
    419 	if (geteuid()) {
    420 		retval = ext2fs_read_inode(fs, EXT2_ROOT_INO, &inode);
    421 		if (retval) {
    422 			com_err("ext2fs_read_inode", retval,
    423 				_("while reading root inode"));
    424 			exit(1);
    425 		}
    426 		uid = getuid();
    427 		inode.i_uid = uid;
    428 		ext2fs_set_i_uid_high(inode, uid >> 16);
    429 		if (uid) {
    430 			gid = getgid();
    431 			inode.i_gid = gid;
    432 			ext2fs_set_i_gid_high(inode, gid >> 16);
    433 		}
    434 		retval = ext2fs_write_new_inode(fs, EXT2_ROOT_INO, &inode);
    435 		if (retval) {
    436 			com_err("ext2fs_write_inode", retval,
    437 				_("while setting root inode ownership"));
    438 			exit(1);
    439 		}
    440 	}
    441 }
    442 
    443 static void create_lost_and_found(ext2_filsys fs)
    444 {
    445 	unsigned int		lpf_size = 0;
    446 	errcode_t		retval;
    447 	ext2_ino_t		ino;
    448 	const char		*name = "lost+found";
    449 	int			i;
    450 
    451 	fs->umask = 077;
    452 	retval = ext2fs_mkdir(fs, EXT2_ROOT_INO, 0, name);
    453 	if (retval) {
    454 		com_err("ext2fs_mkdir", retval,
    455 			_("while creating /lost+found"));
    456 		exit(1);
    457 	}
    458 
    459 	retval = ext2fs_lookup(fs, EXT2_ROOT_INO, name, strlen(name), 0, &ino);
    460 	if (retval) {
    461 		com_err("ext2_lookup", retval,
    462 			_("while looking up /lost+found"));
    463 		exit(1);
    464 	}
    465 
    466 	for (i=1; i < EXT2_NDIR_BLOCKS; i++) {
    467 		/* Ensure that lost+found is at least 2 blocks, so we always
    468 		 * test large empty blocks for big-block filesystems.  */
    469 		if ((lpf_size += fs->blocksize) >= 16*1024 &&
    470 		    lpf_size >= 2 * fs->blocksize)
    471 			break;
    472 		retval = ext2fs_expand_dir(fs, ino);
    473 		if (retval) {
    474 			com_err("ext2fs_expand_dir", retval,
    475 				_("while expanding /lost+found"));
    476 			exit(1);
    477 		}
    478 	}
    479 }
    480 
    481 static void create_bad_block_inode(ext2_filsys fs, badblocks_list bb_list)
    482 {
    483 	errcode_t	retval;
    484 
    485 	ext2fs_mark_inode_bitmap(fs->inode_map, EXT2_BAD_INO);
    486 	ext2fs_inode_alloc_stats2(fs, EXT2_BAD_INO, +1, 0);
    487 	retval = ext2fs_update_bb_inode(fs, bb_list);
    488 	if (retval) {
    489 		com_err("ext2fs_update_bb_inode", retval,
    490 			_("while setting bad block inode"));
    491 		exit(1);
    492 	}
    493 
    494 }
    495 
    496 static void reserve_inodes(ext2_filsys fs)
    497 {
    498 	ext2_ino_t	i;
    499 
    500 	for (i = EXT2_ROOT_INO + 1; i < EXT2_FIRST_INODE(fs->super); i++)
    501 		ext2fs_inode_alloc_stats2(fs, i, +1, 0);
    502 	ext2fs_mark_ib_dirty(fs);
    503 }
    504 
    505 #define BSD_DISKMAGIC   (0x82564557UL)  /* The disk magic number */
    506 #define BSD_MAGICDISK   (0x57455682UL)  /* The disk magic number reversed */
    507 #define BSD_LABEL_OFFSET        64
    508 
    509 static void zap_sector(ext2_filsys fs, int sect, int nsect)
    510 {
    511 	char *buf;
    512 	int retval;
    513 	unsigned int *magic;
    514 
    515 	buf = malloc(512*nsect);
    516 	if (!buf) {
    517 		printf(_("Out of memory erasing sectors %d-%d\n"),
    518 		       sect, sect + nsect - 1);
    519 		exit(1);
    520 	}
    521 
    522 	if (sect == 0) {
    523 		/* Check for a BSD disklabel, and don't erase it if so */
    524 		retval = io_channel_read_blk(fs->io, 0, -512, buf);
    525 		if (retval)
    526 			fprintf(stderr,
    527 				_("Warning: could not read block 0: %s\n"),
    528 				error_message(retval));
    529 		else {
    530 			magic = (unsigned int *) (buf + BSD_LABEL_OFFSET);
    531 			if ((*magic == BSD_DISKMAGIC) ||
    532 			    (*magic == BSD_MAGICDISK))
    533 				return;
    534 		}
    535 	}
    536 
    537 	memset(buf, 0, 512*nsect);
    538 	io_channel_set_blksize(fs->io, 512);
    539 	retval = io_channel_write_blk(fs->io, sect, -512*nsect, buf);
    540 	io_channel_set_blksize(fs->io, fs->blocksize);
    541 	free(buf);
    542 	if (retval)
    543 		fprintf(stderr, _("Warning: could not erase sector %d: %s\n"),
    544 			sect, error_message(retval));
    545 }
    546 
    547 static void create_journal_dev(ext2_filsys fs)
    548 {
    549 	struct progress_struct progress;
    550 	errcode_t		retval;
    551 	char			*buf;
    552 	blk_t			blk, err_blk;
    553 	int			c, count, err_count;
    554 
    555 	retval = ext2fs_create_journal_superblock(fs,
    556 				  fs->super->s_blocks_count, 0, &buf);
    557 	if (retval) {
    558 		com_err("create_journal_dev", retval,
    559 			_("while initializing journal superblock"));
    560 		exit(1);
    561 	}
    562 	if (quiet)
    563 		memset(&progress, 0, sizeof(progress));
    564 	else
    565 		progress_init(&progress, _("Zeroing journal device: "),
    566 			      fs->super->s_blocks_count);
    567 
    568 	blk = 0;
    569 	count = fs->super->s_blocks_count;
    570 	while (count > 0) {
    571 		if (count > 1024)
    572 			c = 1024;
    573 		else
    574 			c = count;
    575 		retval = ext2fs_zero_blocks(fs, blk, c, &err_blk, &err_count);
    576 		if (retval) {
    577 			com_err("create_journal_dev", retval,
    578 				_("while zeroing journal device "
    579 				  "(block %u, count %d)"),
    580 				err_blk, err_count);
    581 			exit(1);
    582 		}
    583 		blk += c;
    584 		count -= c;
    585 		progress_update(&progress, blk);
    586 	}
    587 	ext2fs_zero_blocks(0, 0, 0, 0, 0);
    588 
    589 	retval = io_channel_write_blk(fs->io,
    590 				      fs->super->s_first_data_block+1,
    591 				      1, buf);
    592 	if (retval) {
    593 		com_err("create_journal_dev", retval,
    594 			_("while writing journal superblock"));
    595 		exit(1);
    596 	}
    597 	progress_close(&progress);
    598 }
    599 
    600 static void show_stats(ext2_filsys fs)
    601 {
    602 	struct ext2_super_block *s = fs->super;
    603 	char 			buf[80];
    604         char                    *os;
    605 	blk_t			group_block;
    606 	dgrp_t			i;
    607 	int			need, col_left;
    608 
    609 	if (fs_param.s_blocks_count != s->s_blocks_count)
    610 		fprintf(stderr, _("warning: %u blocks unused.\n\n"),
    611 		       fs_param.s_blocks_count - s->s_blocks_count);
    612 
    613 	memset(buf, 0, sizeof(buf));
    614 	strncpy(buf, s->s_volume_name, sizeof(s->s_volume_name));
    615 	printf(_("Filesystem label=%s\n"), buf);
    616 	fputs(_("OS type: "), stdout);
    617         os = e2p_os2string(fs->super->s_creator_os);
    618 	fputs(os, stdout);
    619 	free(os);
    620 	printf("\n");
    621 	printf(_("Block size=%u (log=%u)\n"), fs->blocksize,
    622 		s->s_log_block_size);
    623 	printf(_("Fragment size=%u (log=%u)\n"), fs->fragsize,
    624 		s->s_log_frag_size);
    625 	printf(_("Stride=%u blocks, Stripe width=%u blocks\n"),
    626 	       s->s_raid_stride, s->s_raid_stripe_width);
    627 	printf(_("%u inodes, %u blocks\n"), s->s_inodes_count,
    628 	       s->s_blocks_count);
    629 	printf(_("%u blocks (%2.2f%%) reserved for the super user\n"),
    630 		s->s_r_blocks_count,
    631 	       100.0 * s->s_r_blocks_count / s->s_blocks_count);
    632 	printf(_("First data block=%u\n"), s->s_first_data_block);
    633 	if (s->s_reserved_gdt_blocks)
    634 		printf(_("Maximum filesystem blocks=%lu\n"),
    635 		       (s->s_reserved_gdt_blocks + fs->desc_blocks) *
    636 		       EXT2_DESC_PER_BLOCK(s) * s->s_blocks_per_group);
    637 	if (fs->group_desc_count > 1)
    638 		printf(_("%u block groups\n"), fs->group_desc_count);
    639 	else
    640 		printf(_("%u block group\n"), fs->group_desc_count);
    641 	printf(_("%u blocks per group, %u fragments per group\n"),
    642 	       s->s_blocks_per_group, s->s_frags_per_group);
    643 	printf(_("%u inodes per group\n"), s->s_inodes_per_group);
    644 
    645 	if (fs->group_desc_count == 1) {
    646 		printf("\n");
    647 		return;
    648 	}
    649 
    650 	printf(_("Superblock backups stored on blocks: "));
    651 	group_block = s->s_first_data_block;
    652 	col_left = 0;
    653 	for (i = 1; i < fs->group_desc_count; i++) {
    654 		group_block += s->s_blocks_per_group;
    655 		if (!ext2fs_bg_has_super(fs, i))
    656 			continue;
    657 		if (i != 1)
    658 			printf(", ");
    659 		need = int_log10(group_block) + 2;
    660 		if (need > col_left) {
    661 			printf("\n\t");
    662 			col_left = 72;
    663 		}
    664 		col_left -= need;
    665 		printf("%u", group_block);
    666 	}
    667 	printf("\n\n");
    668 }
    669 
    670 /*
    671  * Set the S_CREATOR_OS field.  Return true if OS is known,
    672  * otherwise, 0.
    673  */
    674 static int set_os(struct ext2_super_block *sb, char *os)
    675 {
    676 	if (isdigit (*os))
    677 		sb->s_creator_os = atoi (os);
    678 	else if (strcasecmp(os, "linux") == 0)
    679 		sb->s_creator_os = EXT2_OS_LINUX;
    680 	else if (strcasecmp(os, "GNU") == 0 || strcasecmp(os, "hurd") == 0)
    681 		sb->s_creator_os = EXT2_OS_HURD;
    682 	else if (strcasecmp(os, "freebsd") == 0)
    683 		sb->s_creator_os = EXT2_OS_FREEBSD;
    684 	else if (strcasecmp(os, "lites") == 0)
    685 		sb->s_creator_os = EXT2_OS_LITES;
    686 	else
    687 		return 0;
    688 	return 1;
    689 }
    690 
    691 #define PATH_SET "PATH=/sbin"
    692 
    693 static void parse_extended_opts(struct ext2_super_block *param,
    694 				const char *opts)
    695 {
    696 	char	*buf, *token, *next, *p, *arg, *badopt = 0;
    697 	int	len;
    698 	int	r_usage = 0;
    699 
    700 	len = strlen(opts);
    701 	buf = malloc(len+1);
    702 	if (!buf) {
    703 		fprintf(stderr,
    704 			_("Couldn't allocate memory to parse options!\n"));
    705 		exit(1);
    706 	}
    707 	strcpy(buf, opts);
    708 	for (token = buf; token && *token; token = next) {
    709 		p = strchr(token, ',');
    710 		next = 0;
    711 		if (p) {
    712 			*p = 0;
    713 			next = p+1;
    714 		}
    715 		arg = strchr(token, '=');
    716 		if (arg) {
    717 			*arg = 0;
    718 			arg++;
    719 		}
    720 		if (strcmp(token, "stride") == 0) {
    721 			if (!arg) {
    722 				r_usage++;
    723 				badopt = token;
    724 				continue;
    725 			}
    726 			param->s_raid_stride = strtoul(arg, &p, 0);
    727 			if (*p || (param->s_raid_stride == 0)) {
    728 				fprintf(stderr,
    729 					_("Invalid stride parameter: %s\n"),
    730 					arg);
    731 				r_usage++;
    732 				continue;
    733 			}
    734 		} else if (strcmp(token, "stripe-width") == 0 ||
    735 			   strcmp(token, "stripe_width") == 0) {
    736 			if (!arg) {
    737 				r_usage++;
    738 				badopt = token;
    739 				continue;
    740 			}
    741 			param->s_raid_stripe_width = strtoul(arg, &p, 0);
    742 			if (*p || (param->s_raid_stripe_width == 0)) {
    743 				fprintf(stderr,
    744 					_("Invalid stripe-width parameter: %s\n"),
    745 					arg);
    746 				r_usage++;
    747 				continue;
    748 			}
    749 		} else if (!strcmp(token, "resize")) {
    750 			unsigned long resize, bpg, rsv_groups;
    751 			unsigned long group_desc_count, desc_blocks;
    752 			unsigned int gdpb, blocksize;
    753 			int rsv_gdb;
    754 
    755 			if (!arg) {
    756 				r_usage++;
    757 				badopt = token;
    758 				continue;
    759 			}
    760 
    761 			resize = parse_num_blocks(arg,
    762 						  param->s_log_block_size);
    763 
    764 			if (resize == 0) {
    765 				fprintf(stderr,
    766 					_("Invalid resize parameter: %s\n"),
    767 					arg);
    768 				r_usage++;
    769 				continue;
    770 			}
    771 			if (resize <= param->s_blocks_count) {
    772 				fprintf(stderr,
    773 					_("The resize maximum must be greater "
    774 					  "than the filesystem size.\n"));
    775 				r_usage++;
    776 				continue;
    777 			}
    778 
    779 			blocksize = EXT2_BLOCK_SIZE(param);
    780 			bpg = param->s_blocks_per_group;
    781 			if (!bpg)
    782 				bpg = blocksize * 8;
    783 			gdpb = EXT2_DESC_PER_BLOCK(param);
    784 			group_desc_count =
    785 				ext2fs_div_ceil(param->s_blocks_count, bpg);
    786 			desc_blocks = (group_desc_count +
    787 				       gdpb - 1) / gdpb;
    788 			rsv_groups = ext2fs_div_ceil(resize, bpg);
    789 			rsv_gdb = ext2fs_div_ceil(rsv_groups, gdpb) -
    790 				desc_blocks;
    791 			if (rsv_gdb > (int) EXT2_ADDR_PER_BLOCK(param))
    792 				rsv_gdb = EXT2_ADDR_PER_BLOCK(param);
    793 
    794 			if (rsv_gdb > 0) {
    795 				if (param->s_rev_level == EXT2_GOOD_OLD_REV) {
    796 					fprintf(stderr,
    797 	_("On-line resizing not supported with revision 0 filesystems\n"));
    798 					free(buf);
    799 					exit(1);
    800 				}
    801 				param->s_feature_compat |=
    802 					EXT2_FEATURE_COMPAT_RESIZE_INODE;
    803 
    804 				param->s_reserved_gdt_blocks = rsv_gdb;
    805 			}
    806 		} else if (!strcmp(token, "test_fs")) {
    807 			param->s_flags |= EXT2_FLAGS_TEST_FILESYS;
    808 		} else if (!strcmp(token, "lazy_itable_init")) {
    809 			if (arg)
    810 				lazy_itable_init = strtoul(arg, &p, 0);
    811 			else
    812 				lazy_itable_init = 1;
    813 		} else if (!strcmp(token, "discard")) {
    814 			discard = 1;
    815 		} else if (!strcmp(token, "nodiscard")) {
    816 			discard = 0;
    817 		} else {
    818 			r_usage++;
    819 			badopt = token;
    820 		}
    821 	}
    822 	if (r_usage) {
    823 		fprintf(stderr, _("\nBad option(s) specified: %s\n\n"
    824 			"Extended options are separated by commas, "
    825 			"and may take an argument which\n"
    826 			"\tis set off by an equals ('=') sign.\n\n"
    827 			"Valid extended options are:\n"
    828 			"\tstride=<RAID per-disk data chunk in blocks>\n"
    829 			"\tstripe-width=<RAID stride * data disks in blocks>\n"
    830 			"\tresize=<resize maximum size in blocks>\n"
    831 			"\tlazy_itable_init=<0 to disable, 1 to enable>\n"
    832 			"\ttest_fs\n"
    833 			"\tdiscard\n"
    834 			"\tnodiscard\n\n"),
    835 			badopt ? badopt : "");
    836 		free(buf);
    837 		exit(1);
    838 	}
    839 	if (param->s_raid_stride &&
    840 	    (param->s_raid_stripe_width % param->s_raid_stride) != 0)
    841 		fprintf(stderr, _("\nWarning: RAID stripe-width %u not an even "
    842 				  "multiple of stride %u.\n\n"),
    843 			param->s_raid_stripe_width, param->s_raid_stride);
    844 
    845 	free(buf);
    846 }
    847 
    848 static __u32 ok_features[3] = {
    849 	/* Compat */
    850 	EXT3_FEATURE_COMPAT_HAS_JOURNAL |
    851 		EXT2_FEATURE_COMPAT_RESIZE_INODE |
    852 		EXT2_FEATURE_COMPAT_DIR_INDEX |
    853 		EXT2_FEATURE_COMPAT_EXT_ATTR,
    854 	/* Incompat */
    855 	EXT2_FEATURE_INCOMPAT_FILETYPE|
    856 		EXT3_FEATURE_INCOMPAT_EXTENTS|
    857 		EXT3_FEATURE_INCOMPAT_JOURNAL_DEV|
    858 		EXT2_FEATURE_INCOMPAT_META_BG|
    859 		EXT4_FEATURE_INCOMPAT_FLEX_BG,
    860 	/* R/O compat */
    861 	EXT2_FEATURE_RO_COMPAT_LARGE_FILE|
    862 		EXT4_FEATURE_RO_COMPAT_HUGE_FILE|
    863 		EXT4_FEATURE_RO_COMPAT_DIR_NLINK|
    864 		EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE|
    865 		EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER|
    866 		EXT4_FEATURE_RO_COMPAT_GDT_CSUM
    867 };
    868 
    869 
    870 static void syntax_err_report(const char *filename, long err, int line_num)
    871 {
    872 	fprintf(stderr,
    873 		_("Syntax error in mke2fs config file (%s, line #%d)\n\t%s\n"),
    874 		filename, line_num, error_message(err));
    875 	exit(1);
    876 }
    877 
    878 static const char *config_fn[] = { ROOT_SYSCONFDIR "/mke2fs.conf", 0 };
    879 
    880 static void edit_feature(const char *str, __u32 *compat_array)
    881 {
    882 	if (!str)
    883 		return;
    884 
    885 	if (e2p_edit_feature(str, compat_array, ok_features)) {
    886 		fprintf(stderr, _("Invalid filesystem option set: %s\n"),
    887 			str);
    888 		exit(1);
    889 	}
    890 }
    891 
    892 struct str_list {
    893 	char **list;
    894 	int num;
    895 	int max;
    896 };
    897 
    898 static errcode_t init_list(struct str_list *sl)
    899 {
    900 	sl->num = 0;
    901 	sl->max = 0;
    902 	sl->list = malloc((sl->max+1) * sizeof(char *));
    903 	if (!sl->list)
    904 		return ENOMEM;
    905 	sl->list[0] = 0;
    906 	return 0;
    907 }
    908 
    909 static errcode_t push_string(struct str_list *sl, const char *str)
    910 {
    911 	char **new_list;
    912 
    913 	if (sl->num >= sl->max) {
    914 		sl->max += 2;
    915 		new_list = realloc(sl->list, (sl->max+1) * sizeof(char *));
    916 		if (!new_list)
    917 			return ENOMEM;
    918 		sl->list = new_list;
    919 	}
    920 	sl->list[sl->num] = malloc(strlen(str)+1);
    921 	if (sl->list[sl->num] == 0)
    922 		return ENOMEM;
    923 	strcpy(sl->list[sl->num], str);
    924 	sl->num++;
    925 	sl->list[sl->num] = 0;
    926 	return 0;
    927 }
    928 
    929 static void print_str_list(char **list)
    930 {
    931 	char **cpp;
    932 
    933 	for (cpp = list; *cpp; cpp++) {
    934 		printf("'%s'", *cpp);
    935 		if (cpp[1])
    936 			fputs(", ", stdout);
    937 	}
    938 	fputc('\n', stdout);
    939 }
    940 
    941 /*
    942  * Return TRUE if the profile has the given subsection
    943  */
    944 static int profile_has_subsection(profile_t profile, const char *section,
    945 				  const char *subsection)
    946 {
    947 	void			*state;
    948 	const char		*names[4];
    949 	char			*name;
    950 	int			ret = 0;
    951 
    952 	names[0] = section;
    953 	names[1] = subsection;
    954 	names[2] = 0;
    955 
    956 	if (profile_iterator_create(profile, names,
    957 				    PROFILE_ITER_LIST_SECTION |
    958 				    PROFILE_ITER_RELATIONS_ONLY, &state))
    959 		return 0;
    960 
    961 	if ((profile_iterator(&state, &name, 0) == 0) && name) {
    962 		free(name);
    963 		ret = 1;
    964 	}
    965 
    966 	profile_iterator_free(&state);
    967 	return ret;
    968 }
    969 
    970 static char **parse_fs_type(const char *fs_type,
    971 			    const char *usage_types,
    972 			    struct ext2_super_block *fs_param,
    973 			    char *progname)
    974 {
    975 	const char	*ext_type = 0;
    976 	char		*parse_str;
    977 	char		*profile_type = 0;
    978 	char		*cp, *t;
    979 	const char	*size_type;
    980 	struct str_list	list;
    981 	unsigned long	meg;
    982 	int		is_hurd = 0;
    983 
    984 	if (init_list(&list))
    985 		return 0;
    986 
    987 	if (creator_os && (!strcasecmp(creator_os, "GNU") ||
    988 			   !strcasecmp(creator_os, "hurd")))
    989 		is_hurd = 1;
    990 
    991 	if (fs_type)
    992 		ext_type = fs_type;
    993 	else if (is_hurd)
    994 		ext_type = "ext2";
    995 	else if (!strcmp(program_name, "mke3fs"))
    996 		ext_type = "ext3";
    997 	else if (progname) {
    998 		ext_type = strrchr(progname, '/');
    999 		if (ext_type)
   1000 			ext_type++;
   1001 		else
   1002 			ext_type = progname;
   1003 
   1004 		if (!strncmp(ext_type, "mkfs.", 5)) {
   1005 			ext_type += 5;
   1006 			if (ext_type[0] == 0)
   1007 				ext_type = 0;
   1008 		} else
   1009 			ext_type = 0;
   1010 	}
   1011 
   1012 	if (!ext_type) {
   1013 		profile_get_string(profile, "defaults", "fs_type", 0,
   1014 				   "ext2", &profile_type);
   1015 		ext_type = profile_type;
   1016 		if (!strcmp(ext_type, "ext2") && (journal_size != 0))
   1017 			ext_type = "ext3";
   1018 	}
   1019 
   1020 
   1021 	if (!profile_has_subsection(profile, "fs_types", ext_type) &&
   1022 	    strcmp(ext_type, "ext2")) {
   1023 		printf(_("\nYour mke2fs.conf file does not define the "
   1024 			 "%s filesystem type.\n"), ext_type);
   1025 		if (!strcmp(ext_type, "ext3") || !strcmp(ext_type, "ext4") ||
   1026 		    !strcmp(ext_type, "ext4dev")) {
   1027 			printf(_("You probably need to install an updated "
   1028 				 "mke2fs.conf file.\n\n"));
   1029 		}
   1030 		if (!force) {
   1031 			printf(_("Aborting...\n"));
   1032 			exit(1);
   1033 		}
   1034 	}
   1035 
   1036 	meg = (1024 * 1024) / EXT2_BLOCK_SIZE(fs_param);
   1037 	if (fs_param->s_blocks_count < 3 * meg)
   1038 		size_type = "floppy";
   1039 	else if (fs_param->s_blocks_count < 512 * meg)
   1040 		size_type = "small";
   1041 	else
   1042 		size_type = "default";
   1043 
   1044 	if (!usage_types)
   1045 		usage_types = size_type;
   1046 
   1047 	parse_str = malloc(usage_types ? strlen(usage_types)+1 : 1);
   1048 	if (!parse_str) {
   1049 		free(list.list);
   1050 		return 0;
   1051 	}
   1052 	if (usage_types)
   1053 		strcpy(parse_str, usage_types);
   1054 	else
   1055 		*parse_str = '\0';
   1056 
   1057 	if (ext_type)
   1058 		push_string(&list, ext_type);
   1059 	cp = parse_str;
   1060 	while (1) {
   1061 		t = strchr(cp, ',');
   1062 		if (t)
   1063 			*t = '\0';
   1064 
   1065 		if (*cp) {
   1066 			if (profile_has_subsection(profile, "fs_types", cp))
   1067 				push_string(&list, cp);
   1068 			else if (strcmp(cp, "default") != 0)
   1069 				fprintf(stderr,
   1070 					_("\nWarning: the fs_type %s is not "
   1071 					  "defined in mke2fs.conf\n\n"),
   1072 					cp);
   1073 		}
   1074 		if (t)
   1075 			cp = t+1;
   1076 		else {
   1077 			cp = "";
   1078 			break;
   1079 		}
   1080 	}
   1081 	free(parse_str);
   1082 	free(profile_type);
   1083 	if (is_hurd)
   1084 		push_string(&list, "hurd");
   1085 	return (list.list);
   1086 }
   1087 
   1088 static char *get_string_from_profile(char **fs_types, const char *opt,
   1089 				     const char *def_val)
   1090 {
   1091 	char *ret = 0;
   1092 	int i;
   1093 
   1094 	for (i=0; fs_types[i]; i++);
   1095 	for (i-=1; i >=0 ; i--) {
   1096 		profile_get_string(profile, "fs_types", fs_types[i],
   1097 				   opt, 0, &ret);
   1098 		if (ret)
   1099 			return ret;
   1100 	}
   1101 	profile_get_string(profile, "defaults", opt, 0, def_val, &ret);
   1102 	return (ret);
   1103 }
   1104 
   1105 static int get_int_from_profile(char **fs_types, const char *opt, int def_val)
   1106 {
   1107 	int ret;
   1108 	char **cpp;
   1109 
   1110 	profile_get_integer(profile, "defaults", opt, 0, def_val, &ret);
   1111 	for (cpp = fs_types; *cpp; cpp++)
   1112 		profile_get_integer(profile, "fs_types", *cpp, opt, ret, &ret);
   1113 	return ret;
   1114 }
   1115 
   1116 static int get_bool_from_profile(char **fs_types, const char *opt, int def_val)
   1117 {
   1118 	int ret;
   1119 	char **cpp;
   1120 
   1121 	profile_get_boolean(profile, "defaults", opt, 0, def_val, &ret);
   1122 	for (cpp = fs_types; *cpp; cpp++)
   1123 		profile_get_boolean(profile, "fs_types", *cpp, opt, ret, &ret);
   1124 	return ret;
   1125 }
   1126 
   1127 extern const char *mke2fs_default_profile;
   1128 static const char *default_files[] = { "<default>", 0 };
   1129 
   1130 #ifdef HAVE_BLKID_PROBE_GET_TOPOLOGY
   1131 /*
   1132  * Sets the geometry of a device (stripe/stride), and returns the
   1133  * device's alignment offset, if any, or a negative error.
   1134  */
   1135 static int get_device_geometry(const char *file,
   1136 			       struct ext2_super_block *fs_param,
   1137 			       int psector_size)
   1138 {
   1139 	int rc = -1;
   1140 	int blocksize;
   1141 	blkid_probe pr;
   1142 	blkid_topology tp;
   1143 	unsigned long min_io;
   1144 	unsigned long opt_io;
   1145 	struct stat statbuf;
   1146 
   1147 	/* Nothing to do for a regular file */
   1148 	if (!stat(file, &statbuf) && S_ISREG(statbuf.st_mode))
   1149 		return 0;
   1150 
   1151 	pr = blkid_new_probe_from_filename(file);
   1152 	if (!pr)
   1153 		goto out;
   1154 
   1155 	tp = blkid_probe_get_topology(pr);
   1156 	if (!tp)
   1157 		goto out;
   1158 
   1159 	min_io = blkid_topology_get_minimum_io_size(tp);
   1160 	opt_io = blkid_topology_get_optimal_io_size(tp);
   1161 	blocksize = EXT2_BLOCK_SIZE(fs_param);
   1162 	if ((min_io == 0) && (psector_size > blocksize))
   1163 		min_io = psector_size;
   1164 	if ((opt_io == 0) && min_io)
   1165 		opt_io = min_io;
   1166 	if ((opt_io == 0) && (psector_size > blocksize))
   1167 		opt_io = psector_size;
   1168 
   1169 	fs_param->s_raid_stride = min_io / blocksize;
   1170 	fs_param->s_raid_stripe_width = opt_io / blocksize;
   1171 
   1172 	rc = blkid_topology_get_alignment_offset(tp);
   1173 out:
   1174 	blkid_free_probe(pr);
   1175 	return rc;
   1176 }
   1177 #endif
   1178 
   1179 static void PRS(int argc, char *argv[])
   1180 {
   1181 	int		b, c;
   1182 	int		size;
   1183 	char 		*tmp, **cpp;
   1184 	int		blocksize = 0;
   1185 	int		inode_ratio = 0;
   1186 	int		inode_size = 0;
   1187 	unsigned long	flex_bg_size = 0;
   1188 	double		reserved_ratio = 5.0;
   1189 	int		lsector_size = 0, psector_size = 0;
   1190 	int		show_version_only = 0;
   1191 	unsigned long long num_inodes = 0; /* unsigned long long to catch too-large input */
   1192 	errcode_t	retval;
   1193 	char *		oldpath = getenv("PATH");
   1194 	char *		extended_opts = 0;
   1195 	const char *	fs_type = 0;
   1196 	const char *	usage_types = 0;
   1197 	blk_t		dev_size;
   1198 #ifdef __linux__
   1199 	struct 		utsname ut;
   1200 #endif
   1201 	long		sysval;
   1202 	int		s_opt = -1, r_opt = -1;
   1203 	char		*fs_features = 0;
   1204 	int		use_bsize;
   1205 	char		*newpath;
   1206 	int		pathlen = sizeof(PATH_SET) + 1;
   1207 
   1208 	if (oldpath)
   1209 		pathlen += strlen(oldpath);
   1210 	newpath = malloc(pathlen);
   1211 	strcpy(newpath, PATH_SET);
   1212 
   1213 	/* Update our PATH to include /sbin  */
   1214 	if (oldpath) {
   1215 		strcat (newpath, ":");
   1216 		strcat (newpath, oldpath);
   1217 	}
   1218 	putenv (newpath);
   1219 
   1220 	tmp = getenv("MKE2FS_SYNC");
   1221 	if (tmp)
   1222 		sync_kludge = atoi(tmp);
   1223 
   1224 	/* Determine the system page size if possible */
   1225 #ifdef HAVE_SYSCONF
   1226 #if (!defined(_SC_PAGESIZE) && defined(_SC_PAGE_SIZE))
   1227 #define _SC_PAGESIZE _SC_PAGE_SIZE
   1228 #endif
   1229 #ifdef _SC_PAGESIZE
   1230 	sysval = sysconf(_SC_PAGESIZE);
   1231 	if (sysval > 0)
   1232 		sys_page_size = sysval;
   1233 #endif /* _SC_PAGESIZE */
   1234 #endif /* HAVE_SYSCONF */
   1235 
   1236 	if ((tmp = getenv("MKE2FS_CONFIG")) != NULL)
   1237 		config_fn[0] = tmp;
   1238 	profile_set_syntax_err_cb(syntax_err_report);
   1239 	retval = profile_init(config_fn, &profile);
   1240 	if (retval == ENOENT) {
   1241 		profile_init(default_files, &profile);
   1242 		profile_set_default(profile, mke2fs_default_profile);
   1243 	}
   1244 
   1245 	setbuf(stdout, NULL);
   1246 	setbuf(stderr, NULL);
   1247 	add_error_table(&et_ext2_error_table);
   1248 	add_error_table(&et_prof_error_table);
   1249 	memset(&fs_param, 0, sizeof(struct ext2_super_block));
   1250 	fs_param.s_rev_level = 1;  /* Create revision 1 filesystems now */
   1251 
   1252 #ifdef __linux__
   1253 	if (uname(&ut)) {
   1254 		perror("uname");
   1255 		exit(1);
   1256 	}
   1257 	linux_version_code = parse_version_number(ut.release);
   1258 	if (linux_version_code && linux_version_code < (2*65536 + 2*256))
   1259 		fs_param.s_rev_level = 0;
   1260 #endif
   1261 
   1262 	if (argc && *argv) {
   1263 		program_name = get_progname(*argv);
   1264 
   1265 		/* If called as mkfs.ext3, create a journal inode */
   1266 		if (!strcmp(program_name, "mkfs.ext3") ||
   1267 		    !strcmp(program_name, "mke3fs"))
   1268 			journal_size = -1;
   1269 	}
   1270 
   1271 	while ((c = getopt (argc, argv,
   1272 		    "b:cf:g:G:i:jl:m:no:qr:s:t:vE:FI:J:KL:M:N:O:R:ST:U:V")) != EOF) {
   1273 		switch (c) {
   1274 		case 'b':
   1275 			blocksize = strtol(optarg, &tmp, 0);
   1276 			b = (blocksize > 0) ? blocksize : -blocksize;
   1277 			if (b < EXT2_MIN_BLOCK_SIZE ||
   1278 			    b > EXT2_MAX_BLOCK_SIZE || *tmp) {
   1279 				com_err(program_name, 0,
   1280 					_("invalid block size - %s"), optarg);
   1281 				exit(1);
   1282 			}
   1283 			if (blocksize > 4096)
   1284 				fprintf(stderr, _("Warning: blocksize %d not "
   1285 						  "usable on most systems.\n"),
   1286 					blocksize);
   1287 			if (blocksize > 0)
   1288 				fs_param.s_log_block_size =
   1289 					int_log2(blocksize >>
   1290 						 EXT2_MIN_BLOCK_LOG_SIZE);
   1291 			break;
   1292 		case 'c':	/* Check for bad blocks */
   1293 			cflag++;
   1294 			break;
   1295 		case 'f':
   1296 			size = strtoul(optarg, &tmp, 0);
   1297 			if (size < EXT2_MIN_BLOCK_SIZE ||
   1298 			    size > EXT2_MAX_BLOCK_SIZE || *tmp) {
   1299 				com_err(program_name, 0,
   1300 					_("invalid fragment size - %s"),
   1301 					optarg);
   1302 				exit(1);
   1303 			}
   1304 			fs_param.s_log_frag_size =
   1305 				int_log2(size >> EXT2_MIN_BLOCK_LOG_SIZE);
   1306 			fprintf(stderr, _("Warning: fragments not supported.  "
   1307 			       "Ignoring -f option\n"));
   1308 			break;
   1309 		case 'g':
   1310 			fs_param.s_blocks_per_group = strtoul(optarg, &tmp, 0);
   1311 			if (*tmp) {
   1312 				com_err(program_name, 0,
   1313 					_("Illegal number for blocks per group"));
   1314 				exit(1);
   1315 			}
   1316 			if ((fs_param.s_blocks_per_group % 8) != 0) {
   1317 				com_err(program_name, 0,
   1318 				_("blocks per group must be multiple of 8"));
   1319 				exit(1);
   1320 			}
   1321 			break;
   1322 		case 'G':
   1323 			flex_bg_size = strtoul(optarg, &tmp, 0);
   1324 			if (*tmp) {
   1325 				com_err(program_name, 0,
   1326 					_("Illegal number for flex_bg size"));
   1327 				exit(1);
   1328 			}
   1329 			if (flex_bg_size < 1 ||
   1330 			    (flex_bg_size & (flex_bg_size-1)) != 0) {
   1331 				com_err(program_name, 0,
   1332 					_("flex_bg size must be a power of 2"));
   1333 				exit(1);
   1334 			}
   1335 			break;
   1336 		case 'i':
   1337 			inode_ratio = strtoul(optarg, &tmp, 0);
   1338 			if (inode_ratio < EXT2_MIN_BLOCK_SIZE ||
   1339 			    inode_ratio > EXT2_MAX_BLOCK_SIZE * 1024 ||
   1340 			    *tmp) {
   1341 				com_err(program_name, 0,
   1342 					_("invalid inode ratio %s (min %d/max %d)"),
   1343 					optarg, EXT2_MIN_BLOCK_SIZE,
   1344 					EXT2_MAX_BLOCK_SIZE * 1024);
   1345 				exit(1);
   1346 			}
   1347 			break;
   1348 		case 'J':
   1349 			parse_journal_opts(optarg);
   1350 			break;
   1351 		case 'K':
   1352 			fprintf(stderr, _("Warning: -K option is deprecated and "
   1353 					  "should not be used anymore. Use "
   1354 					  "\'-E nodiscard\' extended option "
   1355 					  "instead!\n"));
   1356 			discard = 0;
   1357 			break;
   1358 		case 'j':
   1359 			if (!journal_size)
   1360 				journal_size = -1;
   1361 			break;
   1362 		case 'l':
   1363 			bad_blocks_filename = malloc(strlen(optarg)+1);
   1364 			if (!bad_blocks_filename) {
   1365 				com_err(program_name, ENOMEM,
   1366 					_("in malloc for bad_blocks_filename"));
   1367 				exit(1);
   1368 			}
   1369 			strcpy(bad_blocks_filename, optarg);
   1370 			break;
   1371 		case 'm':
   1372 			reserved_ratio = strtod(optarg, &tmp);
   1373 			if ( *tmp || reserved_ratio > 50 ||
   1374 			     reserved_ratio < 0) {
   1375 				com_err(program_name, 0,
   1376 					_("invalid reserved blocks percent - %s"),
   1377 					optarg);
   1378 				exit(1);
   1379 			}
   1380 			break;
   1381 		case 'n':
   1382 			noaction++;
   1383 			break;
   1384 		case 'o':
   1385 			creator_os = optarg;
   1386 			break;
   1387 		case 'q':
   1388 			quiet = 1;
   1389 			break;
   1390 		case 'r':
   1391 			r_opt = strtoul(optarg, &tmp, 0);
   1392 			if (*tmp) {
   1393 				com_err(program_name, 0,
   1394 					_("bad revision level - %s"), optarg);
   1395 				exit(1);
   1396 			}
   1397 			fs_param.s_rev_level = r_opt;
   1398 			break;
   1399 		case 's':	/* deprecated */
   1400 			s_opt = atoi(optarg);
   1401 			break;
   1402 		case 'I':
   1403 			inode_size = strtoul(optarg, &tmp, 0);
   1404 			if (*tmp) {
   1405 				com_err(program_name, 0,
   1406 					_("invalid inode size - %s"), optarg);
   1407 				exit(1);
   1408 			}
   1409 			break;
   1410 		case 'v':
   1411 			verbose = 1;
   1412 			break;
   1413 		case 'F':
   1414 			force++;
   1415 			break;
   1416 		case 'L':
   1417 			volume_label = optarg;
   1418 			break;
   1419 		case 'M':
   1420 			mount_dir = optarg;
   1421 			break;
   1422 		case 'N':
   1423 			num_inodes = strtoul(optarg, &tmp, 0);
   1424 			if (*tmp) {
   1425 				com_err(program_name, 0,
   1426 					_("bad num inodes - %s"), optarg);
   1427 					exit(1);
   1428 			}
   1429 			break;
   1430 		case 'O':
   1431 			fs_features = optarg;
   1432 			break;
   1433 		case 'E':
   1434 		case 'R':
   1435 			extended_opts = optarg;
   1436 			break;
   1437 		case 'S':
   1438 			super_only = 1;
   1439 			break;
   1440 		case 't':
   1441 			fs_type = optarg;
   1442 			break;
   1443 		case 'T':
   1444 			usage_types = optarg;
   1445 			break;
   1446 		case 'U':
   1447 			fs_uuid = optarg;
   1448 			break;
   1449 		case 'V':
   1450 			/* Print version number and exit */
   1451 			show_version_only++;
   1452 			break;
   1453 		default:
   1454 			usage();
   1455 		}
   1456 	}
   1457 	if ((optind == argc) && !show_version_only)
   1458 		usage();
   1459 	device_name = argv[optind++];
   1460 
   1461 	if (!quiet || show_version_only)
   1462 		fprintf (stderr, "mke2fs %s (%s)\n", E2FSPROGS_VERSION,
   1463 			 E2FSPROGS_DATE);
   1464 
   1465 	if (show_version_only) {
   1466 		fprintf(stderr, _("\tUsing %s\n"),
   1467 			error_message(EXT2_ET_BASE));
   1468 		exit(0);
   1469 	}
   1470 
   1471 	/*
   1472 	 * If there's no blocksize specified and there is a journal
   1473 	 * device, use it to figure out the blocksize
   1474 	 */
   1475 	if (blocksize <= 0 && journal_device) {
   1476 		ext2_filsys	jfs;
   1477 		io_manager	io_ptr;
   1478 
   1479 #ifdef CONFIG_TESTIO_DEBUG
   1480 		if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_BLOCK")) {
   1481 			io_ptr = test_io_manager;
   1482 			test_io_backing_manager = unix_io_manager;
   1483 		} else
   1484 #endif
   1485 			io_ptr = unix_io_manager;
   1486 		retval = ext2fs_open(journal_device,
   1487 				     EXT2_FLAG_JOURNAL_DEV_OK, 0,
   1488 				     0, io_ptr, &jfs);
   1489 		if (retval) {
   1490 			com_err(program_name, retval,
   1491 				_("while trying to open journal device %s\n"),
   1492 				journal_device);
   1493 			exit(1);
   1494 		}
   1495 		if ((blocksize < 0) && (jfs->blocksize < (unsigned) (-blocksize))) {
   1496 			com_err(program_name, 0,
   1497 				_("Journal dev blocksize (%d) smaller than "
   1498 				  "minimum blocksize %d\n"), jfs->blocksize,
   1499 				-blocksize);
   1500 			exit(1);
   1501 		}
   1502 		blocksize = jfs->blocksize;
   1503 		printf(_("Using journal device's blocksize: %d\n"), blocksize);
   1504 		fs_param.s_log_block_size =
   1505 			int_log2(blocksize >> EXT2_MIN_BLOCK_LOG_SIZE);
   1506 		ext2fs_close(jfs);
   1507 	}
   1508 
   1509 	if (blocksize > sys_page_size) {
   1510 		if (!force) {
   1511 			com_err(program_name, 0,
   1512 				_("%d-byte blocks too big for system (max %d)"),
   1513 				blocksize, sys_page_size);
   1514 			proceed_question();
   1515 		}
   1516 		fprintf(stderr, _("Warning: %d-byte blocks too big for system "
   1517 				  "(max %d), forced to continue\n"),
   1518 			blocksize, sys_page_size);
   1519 	}
   1520 	if (optind < argc) {
   1521 		fs_param.s_blocks_count = parse_num_blocks(argv[optind++],
   1522 				fs_param.s_log_block_size);
   1523 		if (!fs_param.s_blocks_count) {
   1524 			com_err(program_name, 0,
   1525 				_("invalid blocks count '%s' on device '%s'"),
   1526 				argv[optind - 1], device_name);
   1527 			exit(1);
   1528 		}
   1529 	}
   1530 	if (optind < argc)
   1531 		usage();
   1532 
   1533 	if (!force)
   1534 		check_plausibility(device_name);
   1535 	check_mount(device_name, force, _("filesystem"));
   1536 
   1537 	fs_param.s_log_frag_size = fs_param.s_log_block_size;
   1538 
   1539 	if (noaction && fs_param.s_blocks_count) {
   1540 		dev_size = fs_param.s_blocks_count;
   1541 		retval = 0;
   1542 	} else {
   1543 	retry:
   1544 		retval = ext2fs_get_device_size(device_name,
   1545 						EXT2_BLOCK_SIZE(&fs_param),
   1546 						&dev_size);
   1547 		if ((retval == EFBIG) &&
   1548 		    (blocksize == 0) &&
   1549 		    (fs_param.s_log_block_size == 0)) {
   1550 			fs_param.s_log_block_size = 2;
   1551 			blocksize = 4096;
   1552 			goto retry;
   1553 		}
   1554 	}
   1555 
   1556 	if (retval == EFBIG) {
   1557 		blk64_t	big_dev_size;
   1558 
   1559 		if (blocksize < 4096) {
   1560 			fs_param.s_log_block_size = 2;
   1561 			blocksize = 4096;
   1562 		}
   1563 		retval = ext2fs_get_device_size2(device_name,
   1564 				 EXT2_BLOCK_SIZE(&fs_param), &big_dev_size);
   1565 		if (retval)
   1566 			goto get_size_failure;
   1567 		if (big_dev_size == (1ULL << 32)) {
   1568 			dev_size = (blk_t) (big_dev_size - 1);
   1569 			goto got_size;
   1570 		}
   1571 		fprintf(stderr, _("%s: Size of device %s too big "
   1572 				  "to be expressed in 32 bits\n\t"
   1573 				  "using a blocksize of %d.\n"),
   1574 			program_name, device_name, EXT2_BLOCK_SIZE(&fs_param));
   1575 		exit(1);
   1576 	}
   1577 get_size_failure:
   1578 	if (retval && (retval != EXT2_ET_UNIMPLEMENTED)) {
   1579 		com_err(program_name, retval,
   1580 			_("while trying to determine filesystem size"));
   1581 		exit(1);
   1582 	}
   1583 got_size:
   1584 	if (!fs_param.s_blocks_count) {
   1585 		if (retval == EXT2_ET_UNIMPLEMENTED) {
   1586 			com_err(program_name, 0,
   1587 				_("Couldn't determine device size; you "
   1588 				"must specify\nthe size of the "
   1589 				"filesystem\n"));
   1590 			exit(1);
   1591 		} else {
   1592 			if (dev_size == 0) {
   1593 				com_err(program_name, 0,
   1594 				_("Device size reported to be zero.  "
   1595 				  "Invalid partition specified, or\n\t"
   1596 				  "partition table wasn't reread "
   1597 				  "after running fdisk, due to\n\t"
   1598 				  "a modified partition being busy "
   1599 				  "and in use.  You may need to reboot\n\t"
   1600 				  "to re-read your partition table.\n"
   1601 				  ));
   1602 				exit(1);
   1603 			}
   1604 			fs_param.s_blocks_count = dev_size;
   1605 			if (sys_page_size > EXT2_BLOCK_SIZE(&fs_param))
   1606 				fs_param.s_blocks_count &= ~((sys_page_size /
   1607 					   EXT2_BLOCK_SIZE(&fs_param))-1);
   1608 		}
   1609 
   1610 	} else if (!force && (fs_param.s_blocks_count > dev_size)) {
   1611 		com_err(program_name, 0,
   1612 			_("Filesystem larger than apparent device size."));
   1613 		proceed_question();
   1614 	}
   1615 
   1616 	fs_types = parse_fs_type(fs_type, usage_types, &fs_param, argv[0]);
   1617 	if (!fs_types) {
   1618 		fprintf(stderr, _("Failed to parse fs types list\n"));
   1619 		exit(1);
   1620 	}
   1621 
   1622 	/* Figure out what features should be enabled */
   1623 
   1624 	tmp = NULL;
   1625 	if (fs_param.s_rev_level != EXT2_GOOD_OLD_REV) {
   1626 		tmp = get_string_from_profile(fs_types, "base_features",
   1627 		      "sparse_super,filetype,resize_inode,dir_index");
   1628 		edit_feature(tmp, &fs_param.s_feature_compat);
   1629 		free(tmp);
   1630 
   1631 		for (cpp = fs_types; *cpp; cpp++) {
   1632 			tmp = NULL;
   1633 			profile_get_string(profile, "fs_types", *cpp,
   1634 					   "features", "", &tmp);
   1635 			if (tmp && *tmp)
   1636 				edit_feature(tmp, &fs_param.s_feature_compat);
   1637 			free(tmp);
   1638 		}
   1639 		tmp = get_string_from_profile(fs_types, "default_features",
   1640 					      "");
   1641 	}
   1642 	edit_feature(fs_features ? fs_features : tmp,
   1643 		     &fs_param.s_feature_compat);
   1644 	free(tmp);
   1645 
   1646 	if (fs_param.s_feature_incompat & EXT3_FEATURE_INCOMPAT_JOURNAL_DEV) {
   1647 		fs_types[0] = strdup("journal");
   1648 		fs_types[1] = 0;
   1649 	}
   1650 
   1651 	if (verbose) {
   1652 		fputs(_("fs_types for mke2fs.conf resolution: "), stdout);
   1653 		print_str_list(fs_types);
   1654 	}
   1655 
   1656 	if (r_opt == EXT2_GOOD_OLD_REV &&
   1657 	    (fs_param.s_feature_compat || fs_param.s_feature_incompat ||
   1658 	     fs_param.s_feature_ro_compat)) {
   1659 		fprintf(stderr, _("Filesystem features not supported "
   1660 				  "with revision 0 filesystems\n"));
   1661 		exit(1);
   1662 	}
   1663 
   1664 	if (s_opt > 0) {
   1665 		if (r_opt == EXT2_GOOD_OLD_REV) {
   1666 			fprintf(stderr, _("Sparse superblocks not supported "
   1667 				  "with revision 0 filesystems\n"));
   1668 			exit(1);
   1669 		}
   1670 		fs_param.s_feature_ro_compat |=
   1671 			EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER;
   1672 	} else if (s_opt == 0)
   1673 		fs_param.s_feature_ro_compat &=
   1674 			~EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER;
   1675 
   1676 	if (journal_size != 0) {
   1677 		if (r_opt == EXT2_GOOD_OLD_REV) {
   1678 			fprintf(stderr, _("Journals not supported "
   1679 				  "with revision 0 filesystems\n"));
   1680 			exit(1);
   1681 		}
   1682 		fs_param.s_feature_compat |=
   1683 			EXT3_FEATURE_COMPAT_HAS_JOURNAL;
   1684 	}
   1685 
   1686 	if (fs_param.s_feature_incompat &
   1687 	    EXT3_FEATURE_INCOMPAT_JOURNAL_DEV) {
   1688 		reserved_ratio = 0;
   1689 		fs_param.s_feature_incompat = EXT3_FEATURE_INCOMPAT_JOURNAL_DEV;
   1690 		fs_param.s_feature_compat = 0;
   1691 		fs_param.s_feature_ro_compat = 0;
   1692  	}
   1693 
   1694 	if ((fs_param.s_feature_incompat & EXT2_FEATURE_INCOMPAT_META_BG) &&
   1695 	    (fs_param.s_feature_compat & EXT2_FEATURE_COMPAT_RESIZE_INODE)) {
   1696 		fprintf(stderr, _("The resize_inode and meta_bg features "
   1697 				  "are not compatible.\n"
   1698 				  "They can not be both enabled "
   1699 				  "simultaneously.\n"));
   1700 		exit(1);
   1701 	}
   1702 
   1703 	/* Set first meta blockgroup via an environment variable */
   1704 	/* (this is mostly for debugging purposes) */
   1705 	if ((fs_param.s_feature_incompat & EXT2_FEATURE_INCOMPAT_META_BG) &&
   1706 	    ((tmp = getenv("MKE2FS_FIRST_META_BG"))))
   1707 		fs_param.s_first_meta_bg = atoi(tmp);
   1708 
   1709 	/* Get the hardware sector sizes, if available */
   1710 	retval = ext2fs_get_device_sectsize(device_name, &lsector_size);
   1711 	if (retval) {
   1712 		com_err(program_name, retval,
   1713 			_("while trying to determine hardware sector size"));
   1714 		exit(1);
   1715 	}
   1716 	retval = ext2fs_get_device_phys_sectsize(device_name, &psector_size);
   1717 	if (retval) {
   1718 		com_err(program_name, retval,
   1719 			_("while trying to determine physical sector size"));
   1720 		exit(1);
   1721 	}
   1722 
   1723 	if ((tmp = getenv("MKE2FS_DEVICE_SECTSIZE")) != NULL)
   1724 		lsector_size = atoi(tmp);
   1725 	if ((tmp = getenv("MKE2FS_DEVICE_PHYS_SECTSIZE")) != NULL)
   1726 		psector_size = atoi(tmp);
   1727 
   1728 	/* Older kernels may not have physical/logical distinction */
   1729 	if (!psector_size)
   1730 		psector_size = lsector_size;
   1731 
   1732 	if (blocksize <= 0) {
   1733 		use_bsize = get_int_from_profile(fs_types, "blocksize", 4096);
   1734 
   1735 		if (use_bsize == -1) {
   1736 			use_bsize = sys_page_size;
   1737 			if ((linux_version_code < (2*65536 + 6*256)) &&
   1738 			    (use_bsize > 4096))
   1739 				use_bsize = 4096;
   1740 		}
   1741 		if (lsector_size && use_bsize < lsector_size)
   1742 			use_bsize = lsector_size;
   1743 		if ((blocksize < 0) && (use_bsize < (-blocksize)))
   1744 			use_bsize = -blocksize;
   1745 		blocksize = use_bsize;
   1746 		fs_param.s_blocks_count /= blocksize / 1024;
   1747 	} else {
   1748 		if (blocksize < lsector_size) {			/* Impossible */
   1749 			com_err(program_name, EINVAL,
   1750 				_("while setting blocksize; too small "
   1751 				  "for device\n"));
   1752 			exit(1);
   1753 		} else if ((blocksize < psector_size) &&
   1754 			   (psector_size <= sys_page_size)) {	/* Suboptimal */
   1755 			fprintf(stderr, _("Warning: specified blocksize %d is "
   1756 				"less than device physical sectorsize %d\n"),
   1757 				blocksize, psector_size);
   1758 		}
   1759 	}
   1760 
   1761 	if (inode_ratio == 0) {
   1762 		inode_ratio = get_int_from_profile(fs_types, "inode_ratio",
   1763 						   8192);
   1764 		if (inode_ratio < blocksize)
   1765 			inode_ratio = blocksize;
   1766 	}
   1767 
   1768 	fs_param.s_log_frag_size = fs_param.s_log_block_size =
   1769 		int_log2(blocksize >> EXT2_MIN_BLOCK_LOG_SIZE);
   1770 
   1771 #ifdef HAVE_BLKID_PROBE_GET_TOPOLOGY
   1772 	retval = get_device_geometry(device_name, &fs_param, psector_size);
   1773 	if (retval < 0) {
   1774 		fprintf(stderr,
   1775 			_("warning: Unable to get device geometry for %s\n"),
   1776 			device_name);
   1777 	} else if (retval) {
   1778 		printf(_("%s alignment is offset by %lu bytes.\n"),
   1779 		       device_name, retval);
   1780 		printf(_("This may result in very poor performance, "
   1781 			  "(re)-partitioning suggested.\n"));
   1782 	}
   1783 #endif
   1784 
   1785 	blocksize = EXT2_BLOCK_SIZE(&fs_param);
   1786 
   1787 	lazy_itable_init = 0;
   1788 	if (access("/sys/fs/ext4/features/lazy_itable_init", R_OK) == 0)
   1789 		lazy_itable_init = 1;
   1790 
   1791 	lazy_itable_init = get_bool_from_profile(fs_types,
   1792 						 "lazy_itable_init",
   1793 						 lazy_itable_init);
   1794 	discard = get_bool_from_profile(fs_types, "discard" , discard);
   1795 
   1796 	/* Get options from profile */
   1797 	for (cpp = fs_types; *cpp; cpp++) {
   1798 		tmp = NULL;
   1799 		profile_get_string(profile, "fs_types", *cpp, "options", "", &tmp);
   1800 			if (tmp && *tmp)
   1801 				parse_extended_opts(&fs_param, tmp);
   1802 			free(tmp);
   1803 	}
   1804 
   1805 	if (extended_opts)
   1806 		parse_extended_opts(&fs_param, extended_opts);
   1807 
   1808 	/* Since sparse_super is the default, we would only have a problem
   1809 	 * here if it was explicitly disabled.
   1810 	 */
   1811 	if ((fs_param.s_feature_compat & EXT2_FEATURE_COMPAT_RESIZE_INODE) &&
   1812 	    !(fs_param.s_feature_ro_compat&EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER)) {
   1813 		com_err(program_name, 0,
   1814 			_("reserved online resize blocks not supported "
   1815 			  "on non-sparse filesystem"));
   1816 		exit(1);
   1817 	}
   1818 
   1819 	if (fs_param.s_blocks_per_group) {
   1820 		if (fs_param.s_blocks_per_group < 256 ||
   1821 		    fs_param.s_blocks_per_group > 8 * (unsigned) blocksize) {
   1822 			com_err(program_name, 0,
   1823 				_("blocks per group count out of range"));
   1824 			exit(1);
   1825 		}
   1826 	}
   1827 
   1828 	if (inode_size == 0)
   1829 		inode_size = get_int_from_profile(fs_types, "inode_size", 0);
   1830 	if (!flex_bg_size && (fs_param.s_feature_incompat &
   1831 			      EXT4_FEATURE_INCOMPAT_FLEX_BG))
   1832 		flex_bg_size = get_int_from_profile(fs_types,
   1833 						    "flex_bg_size", 16);
   1834 	if (flex_bg_size) {
   1835 		if (!(fs_param.s_feature_incompat &
   1836 		      EXT4_FEATURE_INCOMPAT_FLEX_BG)) {
   1837 			com_err(program_name, 0,
   1838 				_("Flex_bg feature not enabled, so "
   1839 				  "flex_bg size may not be specified"));
   1840 			exit(1);
   1841 		}
   1842 		fs_param.s_log_groups_per_flex = int_log2(flex_bg_size);
   1843 	}
   1844 
   1845 	if (inode_size && fs_param.s_rev_level >= EXT2_DYNAMIC_REV) {
   1846 		if (inode_size < EXT2_GOOD_OLD_INODE_SIZE ||
   1847 		    inode_size > EXT2_BLOCK_SIZE(&fs_param) ||
   1848 		    inode_size & (inode_size - 1)) {
   1849 			com_err(program_name, 0,
   1850 				_("invalid inode size %d (min %d/max %d)"),
   1851 				inode_size, EXT2_GOOD_OLD_INODE_SIZE,
   1852 				blocksize);
   1853 			exit(1);
   1854 		}
   1855 		fs_param.s_inode_size = inode_size;
   1856 	}
   1857 
   1858 	/* Make sure number of inodes specified will fit in 32 bits */
   1859 	if (num_inodes == 0) {
   1860 		unsigned long long n;
   1861 		n = (unsigned long long) fs_param.s_blocks_count * blocksize / inode_ratio;
   1862 		if (n > ~0U) {
   1863 			com_err(program_name, 0,
   1864 			    _("too many inodes (%llu), raise inode ratio?"), n);
   1865 			exit(1);
   1866 		}
   1867 	} else if (num_inodes > ~0U) {
   1868 		com_err(program_name, 0,
   1869 			_("too many inodes (%llu), specify < 2^32 inodes"),
   1870 			  num_inodes);
   1871 		exit(1);
   1872 	}
   1873 	/*
   1874 	 * Calculate number of inodes based on the inode ratio
   1875 	 */
   1876 	fs_param.s_inodes_count = num_inodes ? num_inodes :
   1877 		((__u64) fs_param.s_blocks_count * blocksize)
   1878 			/ inode_ratio;
   1879 
   1880 	if ((((long long)fs_param.s_inodes_count) *
   1881 	     (inode_size ? inode_size : EXT2_GOOD_OLD_INODE_SIZE)) >=
   1882 	    (((long long)fs_param.s_blocks_count) *
   1883 	     EXT2_BLOCK_SIZE(&fs_param))) {
   1884 		com_err(program_name, 0, _("inode_size (%u) * inodes_count "
   1885 					  "(%u) too big for a\n\t"
   1886 					  "filesystem with %lu blocks, "
   1887 					  "specify higher inode_ratio (-i)\n\t"
   1888 					  "or lower inode count (-N).\n"),
   1889 			inode_size ? inode_size : EXT2_GOOD_OLD_INODE_SIZE,
   1890 			fs_param.s_inodes_count,
   1891 			(unsigned long) fs_param.s_blocks_count);
   1892 		exit(1);
   1893 	}
   1894 
   1895 	/*
   1896 	 * Calculate number of blocks to reserve
   1897 	 */
   1898 	fs_param.s_r_blocks_count = (unsigned int) (reserved_ratio *
   1899 					fs_param.s_blocks_count / 100.0);
   1900 }
   1901 
   1902 static int should_do_undo(const char *name)
   1903 {
   1904 	errcode_t retval;
   1905 	io_channel channel;
   1906 	__u16	s_magic;
   1907 	struct ext2_super_block super;
   1908 	io_manager manager = unix_io_manager;
   1909 	int csum_flag, force_undo;
   1910 
   1911 	csum_flag = EXT2_HAS_RO_COMPAT_FEATURE(&fs_param,
   1912 					       EXT4_FEATURE_RO_COMPAT_GDT_CSUM);
   1913 	force_undo = get_int_from_profile(fs_types, "force_undo", 0);
   1914 	if (!force_undo && (!csum_flag || !lazy_itable_init))
   1915 		return 0;
   1916 
   1917 	retval = manager->open(name, IO_FLAG_EXCLUSIVE,  &channel);
   1918 	if (retval) {
   1919 		/*
   1920 		 * We don't handle error cases instead we
   1921 		 * declare that the file system doesn't exist
   1922 		 * and let the rest of mke2fs take care of
   1923 		 * error
   1924 		 */
   1925 		retval = 0;
   1926 		goto open_err_out;
   1927 	}
   1928 
   1929 	io_channel_set_blksize(channel, SUPERBLOCK_OFFSET);
   1930 	retval = io_channel_read_blk(channel, 1, -SUPERBLOCK_SIZE, &super);
   1931 	if (retval) {
   1932 		retval = 0;
   1933 		goto err_out;
   1934 	}
   1935 
   1936 #if defined(WORDS_BIGENDIAN)
   1937 	s_magic = ext2fs_swab16(super.s_magic);
   1938 #else
   1939 	s_magic = super.s_magic;
   1940 #endif
   1941 
   1942 	if (s_magic == EXT2_SUPER_MAGIC)
   1943 		retval = 1;
   1944 
   1945 err_out:
   1946 	io_channel_close(channel);
   1947 
   1948 open_err_out:
   1949 
   1950 	return retval;
   1951 }
   1952 
   1953 static int mke2fs_setup_tdb(const char *name, io_manager *io_ptr)
   1954 {
   1955 	errcode_t retval = 0;
   1956 	char *tdb_dir, *tdb_file;
   1957 	char *device_name, *tmp_name;
   1958 
   1959 	/*
   1960 	 * Configuration via a conf file would be
   1961 	 * nice
   1962 	 */
   1963 	tdb_dir = getenv("E2FSPROGS_UNDO_DIR");
   1964 	if (!tdb_dir)
   1965 		profile_get_string(profile, "defaults",
   1966 				   "undo_dir", 0, "/var/lib/e2fsprogs",
   1967 				   &tdb_dir);
   1968 
   1969 	if (!strcmp(tdb_dir, "none") || (tdb_dir[0] == 0) ||
   1970 	    access(tdb_dir, W_OK))
   1971 		return 0;
   1972 
   1973 	tmp_name = strdup(name);
   1974 	if (!tmp_name) {
   1975 	alloc_fn_fail:
   1976 		com_err(program_name, ENOMEM,
   1977 			_("Couldn't allocate memory for tdb filename\n"));
   1978 		return ENOMEM;
   1979 	}
   1980 	device_name = basename(tmp_name);
   1981 	tdb_file = malloc(strlen(tdb_dir) + 8 + strlen(device_name) + 7 + 1);
   1982 	if (!tdb_file)
   1983 		goto alloc_fn_fail;
   1984 	sprintf(tdb_file, "%s/mke2fs-%s.e2undo", tdb_dir, device_name);
   1985 
   1986 	if (!access(tdb_file, F_OK)) {
   1987 		if (unlink(tdb_file) < 0) {
   1988 			retval = errno;
   1989 			com_err(program_name, retval,
   1990 				_("while trying to delete %s"),
   1991 				tdb_file);
   1992 			free(tdb_file);
   1993 			return retval;
   1994 		}
   1995 	}
   1996 
   1997 	set_undo_io_backing_manager(*io_ptr);
   1998 	*io_ptr = undo_io_manager;
   1999 	set_undo_io_backup_file(tdb_file);
   2000 	printf(_("Overwriting existing filesystem; this can be undone "
   2001 		 "using the command:\n"
   2002 		 "    e2undo %s %s\n\n"), tdb_file, name);
   2003 
   2004 	free(tdb_file);
   2005 	free(tmp_name);
   2006 	return retval;
   2007 }
   2008 
   2009 #ifdef __linux__
   2010 
   2011 #ifndef BLKDISCARD
   2012 #define BLKDISCARD	_IO(0x12,119)
   2013 #endif
   2014 
   2015 #ifndef BLKDISCARDZEROES
   2016 #define BLKDISCARDZEROES _IO(0x12,124)
   2017 #endif
   2018 
   2019 /*
   2020  * Return zero if the discard succeeds, and -1 if the discard fails.
   2021  */
   2022 static int mke2fs_discard_blocks(ext2_filsys fs)
   2023 {
   2024 	int fd;
   2025 	int ret;
   2026 	int blocksize;
   2027 	__u64 blocks;
   2028 	__uint64_t range[2];
   2029 
   2030 	blocks = fs->super->s_blocks_count;
   2031 	blocksize = EXT2_BLOCK_SIZE(fs->super);
   2032 	range[0] = 0;
   2033 	range[1] = blocks * blocksize;
   2034 
   2035 #ifdef HAVE_OPEN64
   2036 	fd = open64(fs->device_name, O_RDWR);
   2037 #else
   2038 	fd = open(fs->device_name, O_RDWR);
   2039 #endif
   2040 	if (fd > 0) {
   2041 		ret = ioctl(fd, BLKDISCARD, &range);
   2042 		if (verbose) {
   2043 			printf(_("Calling BLKDISCARD from %llu to %llu "),
   2044 			       (unsigned long long) range[0],
   2045 			       (unsigned long long) range[1]);
   2046 			if (ret)
   2047 				printf(_("failed.\n"));
   2048 			else
   2049 				printf(_("succeeded.\n"));
   2050 		}
   2051 		close(fd);
   2052 	}
   2053 	return ret;
   2054 }
   2055 
   2056 static int mke2fs_discard_zeroes_data(ext2_filsys fs)
   2057 {
   2058 	int fd;
   2059 	int ret;
   2060 	int discard_zeroes_data = 0;
   2061 
   2062 #ifdef HAVE_OPEN64
   2063 	fd = open64(fs->device_name, O_RDWR);
   2064 #else
   2065 	fd = open(fs->device_name, O_RDWR);
   2066 #endif
   2067 	if (fd > 0) {
   2068 		ioctl(fd, BLKDISCARDZEROES, &discard_zeroes_data);
   2069 		close(fd);
   2070 	}
   2071 	return discard_zeroes_data;
   2072 }
   2073 #else
   2074 #define mke2fs_discard_blocks(fs)	1
   2075 #define mke2fs_discard_zeroes_data(fs)	0
   2076 #endif
   2077 
   2078 int main (int argc, char *argv[])
   2079 {
   2080 	errcode_t	retval = 0;
   2081 	ext2_filsys	fs;
   2082 	badblocks_list	bb_list = 0;
   2083 	unsigned int	journal_blocks;
   2084 	unsigned int	i;
   2085 	int		val, hash_alg;
   2086 	io_manager	io_ptr;
   2087 	char		tdb_string[40];
   2088 	char		*hash_alg_str;
   2089 	int		itable_zeroed = 0;
   2090 
   2091 #ifdef ENABLE_NLS
   2092 	setlocale(LC_MESSAGES, "");
   2093 	setlocale(LC_CTYPE, "");
   2094 	bindtextdomain(NLS_CAT_NAME, LOCALEDIR);
   2095 	textdomain(NLS_CAT_NAME);
   2096 #endif
   2097 	PRS(argc, argv);
   2098 
   2099 #ifdef CONFIG_TESTIO_DEBUG
   2100 	if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_BLOCK")) {
   2101 		io_ptr = test_io_manager;
   2102 		test_io_backing_manager = unix_io_manager;
   2103 	} else
   2104 #endif
   2105 		io_ptr = unix_io_manager;
   2106 
   2107 	if (should_do_undo(device_name)) {
   2108 		retval = mke2fs_setup_tdb(device_name, &io_ptr);
   2109 		if (retval)
   2110 			exit(1);
   2111 	}
   2112 
   2113 	/*
   2114 	 * Initialize the superblock....
   2115 	 */
   2116 	retval = ext2fs_initialize(device_name, EXT2_FLAG_EXCLUSIVE, &fs_param,
   2117 				   io_ptr, &fs);
   2118 	if (retval) {
   2119 		com_err(device_name, retval, _("while setting up superblock"));
   2120 		exit(1);
   2121 	}
   2122 
   2123 	/* Can't undo discard ... */
   2124 	if (discard && (io_ptr != undo_io_manager)) {
   2125 		retval = mke2fs_discard_blocks(fs);
   2126 
   2127 		if (!retval && mke2fs_discard_zeroes_data(fs)) {
   2128 			if (verbose)
   2129 				printf(_("Discard succeeded and will return 0s "
   2130 					 " - skipping inode table wipe\n"));
   2131 			lazy_itable_init = 1;
   2132 			itable_zeroed = 1;
   2133 		}
   2134 	}
   2135 
   2136 	sprintf(tdb_string, "tdb_data_size=%d", fs->blocksize <= 4096 ?
   2137 		32768 : fs->blocksize * 8);
   2138 	io_channel_set_options(fs->io, tdb_string);
   2139 
   2140 	if (fs_param.s_flags & EXT2_FLAGS_TEST_FILESYS)
   2141 		fs->super->s_flags |= EXT2_FLAGS_TEST_FILESYS;
   2142 
   2143 	if ((fs_param.s_feature_incompat &
   2144 	     (EXT3_FEATURE_INCOMPAT_EXTENTS|EXT4_FEATURE_INCOMPAT_FLEX_BG)) ||
   2145 	    (fs_param.s_feature_ro_compat &
   2146 	     (EXT4_FEATURE_RO_COMPAT_HUGE_FILE|EXT4_FEATURE_RO_COMPAT_GDT_CSUM|
   2147 	      EXT4_FEATURE_RO_COMPAT_DIR_NLINK|
   2148 	      EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE)))
   2149 		fs->super->s_kbytes_written = 1;
   2150 
   2151 	/*
   2152 	 * Wipe out the old on-disk superblock
   2153 	 */
   2154 	if (!noaction)
   2155 		zap_sector(fs, 2, 6);
   2156 
   2157 	/*
   2158 	 * Parse or generate a UUID for the filesystem
   2159 	 */
   2160 	if (fs_uuid) {
   2161 		if (uuid_parse(fs_uuid, fs->super->s_uuid) !=0) {
   2162 			com_err(device_name, 0, "could not parse UUID: %s\n",
   2163 				fs_uuid);
   2164 			exit(1);
   2165 		}
   2166 	} else
   2167 		uuid_generate(fs->super->s_uuid);
   2168 
   2169 	/*
   2170 	 * Initialize the directory index variables
   2171 	 */
   2172 	hash_alg_str = get_string_from_profile(fs_types, "hash_alg",
   2173 					       "half_md4");
   2174 	hash_alg = e2p_string2hash(hash_alg_str);
   2175 	free(hash_alg_str);
   2176 	fs->super->s_def_hash_version = (hash_alg >= 0) ? hash_alg :
   2177 		EXT2_HASH_HALF_MD4;
   2178 	uuid_generate((unsigned char *) fs->super->s_hash_seed);
   2179 
   2180 	/*
   2181 	 * Add "jitter" to the superblock's check interval so that we
   2182 	 * don't check all the filesystems at the same time.  We use a
   2183 	 * kludgy hack of using the UUID to derive a random jitter value.
   2184 	 */
   2185 	for (i = 0, val = 0 ; i < sizeof(fs->super->s_uuid); i++)
   2186 		val += fs->super->s_uuid[i];
   2187 	fs->super->s_max_mnt_count += val % EXT2_DFL_MAX_MNT_COUNT;
   2188 
   2189 	/*
   2190 	 * Override the creator OS, if applicable
   2191 	 */
   2192 	if (creator_os && !set_os(fs->super, creator_os)) {
   2193 		com_err (program_name, 0, _("unknown os - %s"), creator_os);
   2194 		exit(1);
   2195 	}
   2196 
   2197 	/*
   2198 	 * For the Hurd, we will turn off filetype since it doesn't
   2199 	 * support it.
   2200 	 */
   2201 	if (fs->super->s_creator_os == EXT2_OS_HURD)
   2202 		fs->super->s_feature_incompat &=
   2203 			~EXT2_FEATURE_INCOMPAT_FILETYPE;
   2204 
   2205 	/*
   2206 	 * Set the volume label...
   2207 	 */
   2208 	if (volume_label) {
   2209 		memset(fs->super->s_volume_name, 0,
   2210 		       sizeof(fs->super->s_volume_name));
   2211 		strncpy(fs->super->s_volume_name, volume_label,
   2212 			sizeof(fs->super->s_volume_name));
   2213 	}
   2214 
   2215 	/*
   2216 	 * Set the last mount directory
   2217 	 */
   2218 	if (mount_dir) {
   2219 		memset(fs->super->s_last_mounted, 0,
   2220 		       sizeof(fs->super->s_last_mounted));
   2221 		strncpy(fs->super->s_last_mounted, mount_dir,
   2222 			sizeof(fs->super->s_last_mounted));
   2223 	}
   2224 
   2225 	if (!quiet || noaction)
   2226 		show_stats(fs);
   2227 
   2228 	if (noaction)
   2229 		exit(0);
   2230 
   2231 	if (fs->super->s_feature_incompat &
   2232 	    EXT3_FEATURE_INCOMPAT_JOURNAL_DEV) {
   2233 		create_journal_dev(fs);
   2234 		exit(ext2fs_close(fs) ? 1 : 0);
   2235 	}
   2236 
   2237 	if (bad_blocks_filename)
   2238 		read_bb_file(fs, &bb_list, bad_blocks_filename);
   2239 	if (cflag)
   2240 		test_disk(fs, &bb_list);
   2241 
   2242 	handle_bad_blocks(fs, bb_list);
   2243 	fs->stride = fs_stride = fs->super->s_raid_stride;
   2244 	retval = ext2fs_allocate_tables(fs);
   2245 	if (retval) {
   2246 		com_err(program_name, retval,
   2247 			_("while trying to allocate filesystem tables"));
   2248 		exit(1);
   2249 	}
   2250 	if (super_only) {
   2251 		fs->super->s_state |= EXT2_ERROR_FS;
   2252 		fs->flags &= ~(EXT2_FLAG_IB_DIRTY|EXT2_FLAG_BB_DIRTY);
   2253 	} else {
   2254 		/* rsv must be a power of two (64kB is MD RAID sb alignment) */
   2255 		unsigned int rsv = 65536 / fs->blocksize;
   2256 		unsigned long blocks = fs->super->s_blocks_count;
   2257 		unsigned long start;
   2258 		blk_t ret_blk;
   2259 
   2260 #ifdef ZAP_BOOTBLOCK
   2261 		zap_sector(fs, 0, 2);
   2262 #endif
   2263 
   2264 		/*
   2265 		 * Wipe out any old MD RAID (or other) metadata at the end
   2266 		 * of the device.  This will also verify that the device is
   2267 		 * as large as we think.  Be careful with very small devices.
   2268 		 */
   2269 		start = (blocks & ~(rsv - 1));
   2270 		if (start > rsv)
   2271 			start -= rsv;
   2272 		if (start > 0)
   2273 			retval = ext2fs_zero_blocks(fs, start, blocks - start,
   2274 						    &ret_blk, NULL);
   2275 
   2276 		if (retval) {
   2277 			com_err(program_name, retval,
   2278 				_("while zeroing block %u at end of filesystem"),
   2279 				ret_blk);
   2280 		}
   2281 		write_inode_tables(fs, lazy_itable_init, itable_zeroed);
   2282 		create_root_dir(fs);
   2283 		create_lost_and_found(fs);
   2284 		reserve_inodes(fs);
   2285 		create_bad_block_inode(fs, bb_list);
   2286 		if (fs->super->s_feature_compat &
   2287 		    EXT2_FEATURE_COMPAT_RESIZE_INODE) {
   2288 			retval = ext2fs_create_resize_inode(fs);
   2289 			if (retval) {
   2290 				com_err("ext2fs_create_resize_inode", retval,
   2291 				_("while reserving blocks for online resize"));
   2292 				exit(1);
   2293 			}
   2294 		}
   2295 	}
   2296 
   2297 	if (journal_device) {
   2298 		ext2_filsys	jfs;
   2299 
   2300 		if (!force)
   2301 			check_plausibility(journal_device);
   2302 		check_mount(journal_device, force, _("journal"));
   2303 
   2304 		retval = ext2fs_open(journal_device, EXT2_FLAG_RW|
   2305 				     EXT2_FLAG_JOURNAL_DEV_OK, 0,
   2306 				     fs->blocksize, unix_io_manager, &jfs);
   2307 		if (retval) {
   2308 			com_err(program_name, retval,
   2309 				_("while trying to open journal device %s\n"),
   2310 				journal_device);
   2311 			exit(1);
   2312 		}
   2313 		if (!quiet) {
   2314 			printf(_("Adding journal to device %s: "),
   2315 			       journal_device);
   2316 			fflush(stdout);
   2317 		}
   2318 		retval = ext2fs_add_journal_device(fs, jfs);
   2319 		if(retval) {
   2320 			com_err (program_name, retval,
   2321 				 _("\n\twhile trying to add journal to device %s"),
   2322 				 journal_device);
   2323 			exit(1);
   2324 		}
   2325 		if (!quiet)
   2326 			printf(_("done\n"));
   2327 		ext2fs_close(jfs);
   2328 		free(journal_device);
   2329 	} else if ((journal_size) ||
   2330 		   (fs_param.s_feature_compat &
   2331 		    EXT3_FEATURE_COMPAT_HAS_JOURNAL)) {
   2332 		journal_blocks = figure_journal_size(journal_size, fs);
   2333 
   2334 		if (super_only) {
   2335 			printf(_("Skipping journal creation in super-only mode\n"));
   2336 			fs->super->s_journal_inum = EXT2_JOURNAL_INO;
   2337 			goto no_journal;
   2338 		}
   2339 
   2340 		if (!journal_blocks) {
   2341 			fs->super->s_feature_compat &=
   2342 				~EXT3_FEATURE_COMPAT_HAS_JOURNAL;
   2343 			goto no_journal;
   2344 		}
   2345 		if (!quiet) {
   2346 			printf(_("Creating journal (%u blocks): "),
   2347 			       journal_blocks);
   2348 			fflush(stdout);
   2349 		}
   2350 		retval = ext2fs_add_journal_inode(fs, journal_blocks,
   2351 						  journal_flags);
   2352 		if (retval) {
   2353 			com_err (program_name, retval,
   2354 				 _("\n\twhile trying to create journal"));
   2355 			exit(1);
   2356 		}
   2357 		if (!quiet)
   2358 			printf(_("done\n"));
   2359 	}
   2360 no_journal:
   2361 
   2362 	if (!quiet)
   2363 		printf(_("Writing superblocks and "
   2364 		       "filesystem accounting information: "));
   2365 	retval = ext2fs_flush(fs);
   2366 	if (retval) {
   2367 		fprintf(stderr,
   2368 			_("\nWarning, had trouble writing out superblocks."));
   2369 	}
   2370 	if (!quiet) {
   2371 		printf(_("done\n\n"));
   2372 		if (!getenv("MKE2FS_SKIP_CHECK_MSG"))
   2373 			print_check_message(fs);
   2374 	}
   2375 	val = ext2fs_close(fs);
   2376 	remove_error_table(&et_ext2_error_table);
   2377 	remove_error_table(&et_prof_error_table);
   2378 	profile_release(profile);
   2379 	for (i=0; fs_types[i]; i++)
   2380 		free(fs_types[i]);
   2381 	free(fs_types);
   2382 	return (retval || val) ? 1 : 0;
   2383 }
   2384