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