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