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