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