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