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