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