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