Whamcloud - gitweb
LU-9501 mke2fs: avoid inode number error with large FS
[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
20
21 #include "config.h"
22 #include <stdio.h>
23 #include <string.h>
24 #include <strings.h>
25 #include <ctype.h>
26 #include <time.h>
27 #ifdef HAVE_GETOPT_H
28 #include <getopt.h>
29 #else
30 extern char *optarg;
31 extern int optind;
32 #endif
33 #ifdef HAVE_UNISTD_H
34 #include <unistd.h>
35 #endif
36 #ifdef HAVE_STDLIB_H
37 #include <stdlib.h>
38 #endif
39 #ifdef HAVE_ERRNO_H
40 #include <errno.h>
41 #endif
42 #ifdef HAVE_SYS_IOCTL_H
43 #include <sys/ioctl.h>
44 #endif
45 #include <libgen.h>
46 #include <limits.h>
47 #include <blkid/blkid.h>
48
49 #include "ext2fs/ext2_fs.h"
50 #include "ext2fs/ext2fsP.h"
51 #include "uuid/uuid.h"
52 #include "util.h"
53 #include "support/nls-enable.h"
54 #include "support/plausible.h"
55 #include "support/profile.h"
56 #include "support/prof_err.h"
57 #include "../version.h"
58 #include "support/quotaio.h"
59 #include "mke2fs.h"
60 #include "create_inode.h"
61
62 #define STRIDE_LENGTH 8
63
64 #define MAX_32_NUM ((((unsigned long long) 1) << 32) - 1)
65
66 #ifndef __sparc__
67 #define ZAP_BOOTBLOCK
68 #endif
69
70 #define DISCARD_STEP_MB         (2048)
71
72 extern int isatty(int);
73 extern FILE *fpopen(const char *cmd, const char *mode);
74
75 const char * program_name = "mke2fs";
76 static const char * device_name /* = NULL */;
77
78 /* Command line options */
79 static int      cflag;
80 int     verbose;
81 int     quiet;
82 static int      super_only;
83 static int      discard = 1;    /* attempt to discard device before fs creation */
84 static int      direct_io;
85 static int      force;
86 static int      noaction;
87 static int      num_backups = 2; /* number of backup bg's for sparse_super2 */
88 static uid_t    root_uid;
89 static gid_t    root_gid;
90 int     journal_size;
91 int     journal_flags;
92 int     journal_fc_size;
93 static int      lazy_itable_init;
94 static int      packed_meta_blocks;
95 int             no_copy_xattrs;
96 static char     *bad_blocks_filename = NULL;
97 static __u32    fs_stride;
98 /* Initialize usr/grp quotas by default */
99 static unsigned int quotatype_bits = (QUOTA_USR_BIT | QUOTA_GRP_BIT);
100 static __u64    offset;
101 static blk64_t journal_location = ~0LL;
102 static int      proceed_delay = -1;
103 static blk64_t  dev_size;
104
105 static struct ext2_super_block fs_param;
106 static __u32 zero_buf[4];
107 static char *fs_uuid = NULL;
108 static char *creator_os;
109 static char *volume_label;
110 static char *mount_dir;
111 char *journal_device;
112 static int sync_kludge; /* Set using the MKE2FS_SYNC env. option */
113 char **fs_types;
114 const char *src_root_dir;  /* Copy files from the specified directory */
115 static char *undo_file;
116
117 static int android_sparse_file; /* -E android_sparse */
118
119 static profile_t        profile;
120
121 static int sys_page_size = 4096;
122
123 static int errors_behavior = 0;
124
125 static void usage(void)
126 {
127         fprintf(stderr, _("Usage: %s [-c|-l filename] [-b block-size] "
128         "[-C cluster-size]\n\t[-i bytes-per-inode] [-I inode-size] "
129         "[-J journal-options]\n"
130         "\t[-G flex-group-size] [-N number-of-inodes] "
131         "[-d root-directory]\n"
132         "\t[-m reserved-blocks-percentage] [-o creator-os]\n"
133         "\t[-g blocks-per-group] [-L volume-label] "
134         "[-M last-mounted-directory]\n\t[-O feature[,...]] "
135         "[-r fs-revision] [-E extended-option[,...]]\n"
136         "\t[-t fs-type] [-T usage-type ] [-U UUID] [-e errors_behavior]"
137         "[-z undo_file]\n"
138         "\t[-jnqvDFSV] device [blocks-count]\n"),
139                 program_name);
140         exit(1);
141 }
142
143 static int int_log2(unsigned long long arg)
144 {
145         int     l = 0;
146
147         arg >>= 1;
148         while (arg) {
149                 l++;
150                 arg >>= 1;
151         }
152         return l;
153 }
154
155 int int_log10(unsigned long long arg)
156 {
157         int     l;
158
159         for (l=0; arg ; l++)
160                 arg = arg / 10;
161         return l;
162 }
163
164 /*
165  * Helper function for read_bb_file and test_disk
166  */
167 static void invalid_block(ext2_filsys fs EXT2FS_ATTR((unused)), blk_t blk)
168 {
169         fprintf(stderr, _("Bad block %u out of range; ignored.\n"), blk);
170         return;
171 }
172
173 /*
174  * Reads the bad blocks list from a file
175  */
176 static void read_bb_file(ext2_filsys fs, badblocks_list *bb_list,
177                          const char *bad_blocks_file)
178 {
179         FILE            *f;
180         errcode_t       retval;
181
182         f = fopen(bad_blocks_file, "r");
183         if (!f) {
184                 com_err("read_bad_blocks_file", errno,
185                         _("while trying to open %s"), bad_blocks_file);
186                 exit(1);
187         }
188         retval = ext2fs_read_bb_FILE(fs, f, bb_list, invalid_block);
189         fclose (f);
190         if (retval) {
191                 com_err("ext2fs_read_bb_FILE", retval, "%s",
192                         _("while reading in list of bad blocks from file"));
193                 exit(1);
194         }
195 }
196
197 /*
198  * Runs the badblocks program to test the disk
199  */
200 static void test_disk(ext2_filsys fs, badblocks_list *bb_list)
201 {
202         FILE            *f;
203         errcode_t       retval;
204         char            buf[1024];
205
206         sprintf(buf, "badblocks -b %d -X %s%s%s %llu", fs->blocksize,
207                 quiet ? "" : "-s ", (cflag > 1) ? "-w " : "",
208                 fs->device_name,
209                 (unsigned long long) ext2fs_blocks_count(fs->super)-1);
210         if (verbose)
211                 printf(_("Running command: %s\n"), buf);
212         f = popen(buf, "r");
213         if (!f) {
214                 com_err("popen", errno,
215                         _("while trying to run '%s'"), buf);
216                 exit(1);
217         }
218         retval = ext2fs_read_bb_FILE(fs, f, bb_list, invalid_block);
219         pclose(f);
220         if (retval) {
221                 com_err("ext2fs_read_bb_FILE", retval, "%s",
222                         _("while processing list of bad blocks from program"));
223                 exit(1);
224         }
225 }
226
227 static void handle_bad_blocks(ext2_filsys fs, badblocks_list bb_list)
228 {
229         dgrp_t                  i;
230         blk_t                   j;
231         unsigned                must_be_good;
232         blk_t                   blk;
233         badblocks_iterate       bb_iter;
234         errcode_t               retval;
235         blk_t                   group_block;
236         int                     group;
237         int                     group_bad;
238
239         if (!bb_list)
240                 return;
241
242         /*
243          * The primary superblock and group descriptors *must* be
244          * good; if not, abort.
245          */
246         must_be_good = fs->super->s_first_data_block + 1 + fs->desc_blocks;
247         for (i = fs->super->s_first_data_block; i <= must_be_good; i++) {
248                 if (ext2fs_badblocks_list_test(bb_list, i)) {
249                         fprintf(stderr, _("Block %d in primary "
250                                 "superblock/group descriptor area bad.\n"), i);
251                         fprintf(stderr, _("Blocks %u through %u must be good "
252                                 "in order to build a filesystem.\n"),
253                                 fs->super->s_first_data_block, must_be_good);
254                         fputs(_("Aborting....\n"), stderr);
255                         exit(1);
256                 }
257         }
258
259         /*
260          * See if any of the bad blocks are showing up in the backup
261          * superblocks and/or group descriptors.  If so, issue a
262          * warning and adjust the block counts appropriately.
263          */
264         group_block = fs->super->s_first_data_block +
265                 fs->super->s_blocks_per_group;
266
267         for (i = 1; i < fs->group_desc_count; i++) {
268                 group_bad = 0;
269                 for (j=0; j < fs->desc_blocks+1; j++) {
270                         if (ext2fs_badblocks_list_test(bb_list,
271                                                        group_block + j)) {
272                                 if (!group_bad)
273                                         fprintf(stderr,
274 _("Warning: the backup superblock/group descriptors at block %u contain\n"
275 "       bad blocks.\n\n"),
276                                                 group_block);
277                                 group_bad++;
278                                 group = ext2fs_group_of_blk2(fs, group_block+j);
279                                 ext2fs_bg_free_blocks_count_set(fs, group, ext2fs_bg_free_blocks_count(fs, group) + 1);
280                                 ext2fs_group_desc_csum_set(fs, group);
281                                 ext2fs_free_blocks_count_add(fs->super, 1);
282                         }
283                 }
284                 group_block += fs->super->s_blocks_per_group;
285         }
286
287         /*
288          * Mark all the bad blocks as used...
289          */
290         retval = ext2fs_badblocks_list_iterate_begin(bb_list, &bb_iter);
291         if (retval) {
292                 com_err("ext2fs_badblocks_list_iterate_begin", retval, "%s",
293                         _("while marking bad blocks as used"));
294                 exit(1);
295         }
296         while (ext2fs_badblocks_list_iterate(bb_iter, &blk))
297                 ext2fs_mark_block_bitmap2(fs->block_map, blk);
298         ext2fs_badblocks_list_iterate_end(bb_iter);
299 }
300
301 static void write_reserved_inodes(ext2_filsys fs)
302 {
303         errcode_t       retval;
304         ext2_ino_t      ino;
305         struct ext2_inode *inode;
306
307         retval = ext2fs_get_memzero(EXT2_INODE_SIZE(fs->super), &inode);
308         if (retval) {
309                 com_err("inode_init", retval, _("while allocating memory"));
310                 exit(1);
311         }
312
313         for (ino = 1; ino < EXT2_FIRST_INO(fs->super); ino++) {
314                 retval = ext2fs_write_inode_full(fs, ino, inode,
315                                                  EXT2_INODE_SIZE(fs->super));
316                 if (retval) {
317                         com_err("ext2fs_write_inode_full", retval,
318                                 _("while writing reserved inodes"));
319                         exit(1);
320                 }
321         }
322
323         ext2fs_free_mem(&inode);
324 }
325
326 static errcode_t packed_allocate_tables(ext2_filsys fs)
327 {
328         errcode_t       retval;
329         dgrp_t          i;
330         blk64_t         goal = 0;
331
332         for (i = 0; i < fs->group_desc_count; i++) {
333                 retval = ext2fs_new_block2(fs, goal, NULL, &goal);
334                 if (retval)
335                         return retval;
336                 ext2fs_block_alloc_stats2(fs, goal, +1);
337                 ext2fs_block_bitmap_loc_set(fs, i, goal);
338         }
339         for (i = 0; i < fs->group_desc_count; i++) {
340                 retval = ext2fs_new_block2(fs, goal, NULL, &goal);
341                 if (retval)
342                         return retval;
343                 ext2fs_block_alloc_stats2(fs, goal, +1);
344                 ext2fs_inode_bitmap_loc_set(fs, i, goal);
345         }
346         for (i = 0; i < fs->group_desc_count; i++) {
347                 blk64_t end = ext2fs_blocks_count(fs->super) - 1;
348                 retval = ext2fs_get_free_blocks2(fs, goal, end,
349                                                  fs->inode_blocks_per_group,
350                                                  fs->block_map, &goal);
351                 if (retval)
352                         return retval;
353                 ext2fs_block_alloc_stats_range(fs, goal,
354                                                fs->inode_blocks_per_group, +1);
355                 ext2fs_inode_table_loc_set(fs, i, goal);
356                 ext2fs_group_desc_csum_set(fs, i);
357         }
358         return 0;
359 }
360
361 static void write_inode_tables(ext2_filsys fs, int lazy_flag, int itable_zeroed)
362 {
363         errcode_t       retval;
364         blk64_t         blk;
365         dgrp_t          i;
366         int             num;
367         struct ext2fs_numeric_progress_struct progress;
368
369         ext2fs_numeric_progress_init(fs, &progress,
370                                      _("Writing inode tables: "),
371                                      fs->group_desc_count);
372
373         for (i = 0; i < fs->group_desc_count; i++) {
374                 ext2fs_numeric_progress_update(fs, &progress, i);
375
376                 blk = ext2fs_inode_table_loc(fs, i);
377                 num = fs->inode_blocks_per_group;
378
379                 if (lazy_flag)
380                         num = ext2fs_div_ceil((fs->super->s_inodes_per_group -
381                                                ext2fs_bg_itable_unused(fs, i)) *
382                                               EXT2_INODE_SIZE(fs->super),
383                                               EXT2_BLOCK_SIZE(fs->super));
384                 if (!lazy_flag || itable_zeroed) {
385                         /* The kernel doesn't need to zero the itable blocks */
386                         ext2fs_bg_flags_set(fs, i, EXT2_BG_INODE_ZEROED);
387                         ext2fs_group_desc_csum_set(fs, i);
388                 }
389                 if (!itable_zeroed) {
390                         retval = ext2fs_zero_blocks2(fs, blk, num, &blk, &num);
391                         if (retval) {
392                                 fprintf(stderr, _("\nCould not write %d "
393                                           "blocks in inode table starting at %llu: %s\n"),
394                                         num, (unsigned long long) blk,
395                                         error_message(retval));
396                                 exit(1);
397                         }
398                 }
399                 if (sync_kludge) {
400                         if (sync_kludge == 1)
401                                 io_channel_flush(fs->io);
402                         else if ((i % sync_kludge) == 0)
403                                 io_channel_flush(fs->io);
404                 }
405         }
406         ext2fs_numeric_progress_close(fs, &progress,
407                                       _("done                            \n"));
408
409         /* Reserved inodes must always have correct checksums */
410         if (ext2fs_has_feature_metadata_csum(fs->super))
411                 write_reserved_inodes(fs);
412 }
413
414 static void create_root_dir(ext2_filsys fs)
415 {
416         errcode_t               retval;
417         struct ext2_inode       inode;
418
419         retval = ext2fs_mkdir(fs, EXT2_ROOT_INO, EXT2_ROOT_INO, 0);
420         if (retval) {
421                 com_err("ext2fs_mkdir", retval, "%s",
422                         _("while creating root dir"));
423                 exit(1);
424         }
425         if (root_uid != 0 || root_gid != 0) {
426                 retval = ext2fs_read_inode(fs, EXT2_ROOT_INO, &inode);
427                 if (retval) {
428                         com_err("ext2fs_read_inode", retval, "%s",
429                                 _("while reading root inode"));
430                         exit(1);
431                 }
432
433                 inode.i_uid = root_uid;
434                 ext2fs_set_i_uid_high(inode, root_uid >> 16);
435                 inode.i_gid = root_gid;
436                 ext2fs_set_i_gid_high(inode, root_gid >> 16);
437
438                 retval = ext2fs_write_new_inode(fs, EXT2_ROOT_INO, &inode);
439                 if (retval) {
440                         com_err("ext2fs_write_inode", retval, "%s",
441                                 _("while setting root inode ownership"));
442                         exit(1);
443                 }
444         }
445 }
446
447 static void create_lost_and_found(ext2_filsys fs)
448 {
449         unsigned int            lpf_size = 0;
450         errcode_t               retval;
451         ext2_ino_t              ino;
452         const char              *name = "lost+found";
453         int                     i;
454
455         fs->umask = 077;
456         retval = ext2fs_mkdir(fs, EXT2_ROOT_INO, 0, name);
457         if (retval) {
458                 com_err("ext2fs_mkdir", retval, "%s",
459                         _("while creating /lost+found"));
460                 exit(1);
461         }
462
463         retval = ext2fs_lookup(fs, EXT2_ROOT_INO, name, strlen(name), 0, &ino);
464         if (retval) {
465                 com_err("ext2_lookup", retval, "%s",
466                         _("while looking up /lost+found"));
467                 exit(1);
468         }
469
470         for (i=1; i < EXT2_NDIR_BLOCKS; i++) {
471                 /* Ensure that lost+found is at least 2 blocks, so we always
472                  * test large empty blocks for big-block filesystems.  */
473                 if ((lpf_size += fs->blocksize) >= 16*1024 &&
474                     lpf_size >= 2 * fs->blocksize)
475                         break;
476                 retval = ext2fs_expand_dir(fs, ino);
477                 if (retval) {
478                         com_err("ext2fs_expand_dir", retval, "%s",
479                                 _("while expanding /lost+found"));
480                         exit(1);
481                 }
482         }
483 }
484
485 static void create_bad_block_inode(ext2_filsys fs, badblocks_list bb_list)
486 {
487         errcode_t       retval;
488
489         ext2fs_mark_inode_bitmap2(fs->inode_map, EXT2_BAD_INO);
490         ext2fs_inode_alloc_stats2(fs, EXT2_BAD_INO, +1, 0);
491         retval = ext2fs_update_bb_inode(fs, bb_list);
492         if (retval) {
493                 com_err("ext2fs_update_bb_inode", retval, "%s",
494                         _("while setting bad block inode"));
495                 exit(1);
496         }
497
498 }
499
500 static void reserve_inodes(ext2_filsys fs)
501 {
502         ext2_ino_t      i;
503
504         for (i = EXT2_ROOT_INO + 1; i < EXT2_FIRST_INODE(fs->super); i++)
505                 ext2fs_inode_alloc_stats2(fs, i, +1, 0);
506         ext2fs_mark_ib_dirty(fs);
507 }
508
509 #define BSD_DISKMAGIC   (0x82564557UL)  /* The disk magic number */
510 #define BSD_MAGICDISK   (0x57455682UL)  /* The disk magic number reversed */
511 #define BSD_LABEL_OFFSET        64
512
513 static void zap_sector(ext2_filsys fs, int sect, int nsect)
514 {
515         char *buf;
516         int retval;
517         unsigned int *magic;
518
519         buf = calloc(512, nsect);
520         if (!buf) {
521                 printf(_("Out of memory erasing sectors %d-%d\n"),
522                        sect, sect + nsect - 1);
523                 exit(1);
524         }
525
526         if (sect == 0) {
527                 /* Check for a BSD disklabel, and don't erase it if so */
528                 retval = io_channel_read_blk64(fs->io, 0, -512, buf);
529                 if (retval)
530                         fprintf(stderr,
531                                 _("Warning: could not read block 0: %s\n"),
532                                 error_message(retval));
533                 else {
534                         magic = (unsigned int *) (buf + BSD_LABEL_OFFSET);
535                         if ((*magic == BSD_DISKMAGIC) ||
536                             (*magic == BSD_MAGICDISK))
537                                 return;
538                 }
539         }
540
541         memset(buf, 0, 512*nsect);
542         io_channel_set_blksize(fs->io, 512);
543         retval = io_channel_write_blk64(fs->io, sect, -512*nsect, buf);
544         io_channel_set_blksize(fs->io, fs->blocksize);
545         free(buf);
546         if (retval)
547                 fprintf(stderr, _("Warning: could not erase sector %d: %s\n"),
548                         sect, error_message(retval));
549 }
550
551 static void create_journal_dev(ext2_filsys fs)
552 {
553         struct ext2fs_numeric_progress_struct progress;
554         errcode_t               retval;
555         char                    *buf;
556         blk64_t                 blk, err_blk;
557         int                     c, count, err_count;
558         struct ext2fs_journal_params    jparams;
559
560         retval = ext2fs_get_journal_params(&jparams, fs);
561         if (retval) {
562                 com_err("create_journal_dev", retval, "%s",
563                         _("while splitting the journal size"));
564                 exit(1);
565         }
566
567         retval = ext2fs_create_journal_superblock2(fs, &jparams, 0, &buf);
568         if (retval) {
569                 com_err("create_journal_dev", retval, "%s",
570                         _("while initializing journal superblock"));
571                 exit(1);
572         }
573
574         if (journal_flags & EXT2_MKJOURNAL_LAZYINIT)
575                 goto write_superblock;
576
577         ext2fs_numeric_progress_init(fs, &progress,
578                                      _("Zeroing journal device: "),
579                                      ext2fs_blocks_count(fs->super));
580         blk = 0;
581         count = ext2fs_blocks_count(fs->super);
582         while (count > 0) {
583                 if (count > 1024)
584                         c = 1024;
585                 else
586                         c = count;
587                 retval = ext2fs_zero_blocks2(fs, blk, c, &err_blk, &err_count);
588                 if (retval) {
589                         com_err("create_journal_dev", retval,
590                                 _("while zeroing journal device "
591                                   "(block %llu, count %d)"),
592                                 (unsigned long long) err_blk, err_count);
593                         exit(1);
594                 }
595                 blk += c;
596                 count -= c;
597                 ext2fs_numeric_progress_update(fs, &progress, blk);
598         }
599
600         ext2fs_numeric_progress_close(fs, &progress, NULL);
601 write_superblock:
602         retval = io_channel_write_blk64(fs->io,
603                                         fs->super->s_first_data_block+1,
604                                         1, buf);
605         (void) ext2fs_free_mem(&buf);
606         if (retval) {
607                 com_err("create_journal_dev", retval, "%s",
608                         _("while writing journal superblock"));
609                 exit(1);
610         }
611 }
612
613 static void show_stats(ext2_filsys fs)
614 {
615         struct ext2_super_block *s = fs->super;
616         char                    *os;
617         blk64_t                 group_block;
618         dgrp_t                  i;
619         int                     need, col_left;
620
621         if (!verbose) {
622                 printf(_("Creating filesystem with %llu %dk blocks and "
623                          "%u inodes\n"),
624                        (unsigned long long) ext2fs_blocks_count(s),
625                        fs->blocksize >> 10, s->s_inodes_count);
626                 goto skip_details;
627         }
628
629         if (ext2fs_blocks_count(&fs_param) != ext2fs_blocks_count(s))
630                 fprintf(stderr, _("warning: %llu blocks unused.\n\n"),
631                         (unsigned long long) (ext2fs_blocks_count(&fs_param) -
632                                               ext2fs_blocks_count(s)));
633
634         printf(_("Filesystem label=%.*s\n"), EXT2_LEN_STR(s->s_volume_name));
635
636         os = e2p_os2string(fs->super->s_creator_os);
637         if (os)
638                 printf(_("OS type: %s\n"), os);
639         free(os);
640         printf(_("Block size=%u (log=%u)\n"), fs->blocksize,
641                 s->s_log_block_size);
642         if (ext2fs_has_feature_bigalloc(fs->super))
643                 printf(_("Cluster size=%u (log=%u)\n"),
644                        fs->blocksize << fs->cluster_ratio_bits,
645                        s->s_log_cluster_size);
646         else
647                 printf(_("Fragment size=%u (log=%u)\n"), EXT2_CLUSTER_SIZE(s),
648                        s->s_log_cluster_size);
649         printf(_("Stride=%u blocks, Stripe width=%u blocks\n"),
650                s->s_raid_stride, s->s_raid_stripe_width);
651         printf(_("%u inodes, %llu blocks\n"), s->s_inodes_count,
652                (unsigned long long) ext2fs_blocks_count(s));
653         printf(_("%llu blocks (%2.2f%%) reserved for the super user\n"),
654                (unsigned long long) ext2fs_r_blocks_count(s),
655                100.0 *  ext2fs_r_blocks_count(s) / ext2fs_blocks_count(s));
656         printf(_("First data block=%u\n"), s->s_first_data_block);
657         if (root_uid != 0 || root_gid != 0)
658                 printf(_("Root directory owner=%u:%u\n"), root_uid, root_gid);
659         if (s->s_reserved_gdt_blocks)
660                 printf(_("Maximum filesystem blocks=%lu\n"),
661                        (s->s_reserved_gdt_blocks + fs->desc_blocks) *
662                        EXT2_DESC_PER_BLOCK(s) * s->s_blocks_per_group);
663         if (fs->group_desc_count > 1)
664                 printf(_("%u block groups\n"), fs->group_desc_count);
665         else
666                 printf(_("%u block group\n"), fs->group_desc_count);
667         if (ext2fs_has_feature_bigalloc(fs->super))
668                 printf(_("%u blocks per group, %u clusters per group\n"),
669                        s->s_blocks_per_group, s->s_clusters_per_group);
670         else
671                 printf(_("%u blocks per group, %u fragments per group\n"),
672                        s->s_blocks_per_group, s->s_clusters_per_group);
673         printf(_("%u inodes per group\n"), s->s_inodes_per_group);
674
675 skip_details:
676         if (fs->group_desc_count == 1) {
677                 printf("\n");
678                 return;
679         }
680
681         if (!e2p_is_null_uuid(s->s_uuid))
682                 printf(_("Filesystem UUID: %s\n"), e2p_uuid2str(s->s_uuid));
683         printf("%s", _("Superblock backups stored on blocks: "));
684         group_block = s->s_first_data_block;
685         col_left = 0;
686         for (i = 1; i < fs->group_desc_count; i++) {
687                 group_block += s->s_blocks_per_group;
688                 if (!ext2fs_bg_has_super(fs, i))
689                         continue;
690                 if (i != 1)
691                         printf(", ");
692                 need = int_log10(group_block) + 2;
693                 if (need > col_left) {
694                         printf("\n\t");
695                         col_left = 72;
696                 }
697                 col_left -= need;
698                 printf("%llu", (unsigned long long) group_block);
699         }
700         printf("\n\n");
701 }
702
703 /*
704  * Returns true if making a file system for the Hurd, else 0
705  */
706 static int for_hurd(const char *os)
707 {
708         if (!os) {
709 #ifdef __GNU__
710                 return 1;
711 #else
712                 return 0;
713 #endif
714         }
715         if (isdigit(*os))
716                 return (atoi(os) == EXT2_OS_HURD);
717         return (strcasecmp(os, "GNU") == 0 || strcasecmp(os, "hurd") == 0);
718 }
719
720 /*
721  * Set the S_CREATOR_OS field.  Return true if OS is known,
722  * otherwise, 0.
723  */
724 static int set_os(struct ext2_super_block *sb, char *os)
725 {
726         if (isdigit (*os))
727                 sb->s_creator_os = atoi (os);
728         else if (strcasecmp(os, "linux") == 0)
729                 sb->s_creator_os = EXT2_OS_LINUX;
730         else if (strcasecmp(os, "GNU") == 0 || strcasecmp(os, "hurd") == 0)
731                 sb->s_creator_os = EXT2_OS_HURD;
732         else if (strcasecmp(os, "freebsd") == 0)
733                 sb->s_creator_os = EXT2_OS_FREEBSD;
734         else if (strcasecmp(os, "lites") == 0)
735                 sb->s_creator_os = EXT2_OS_LITES;
736         else
737                 return 0;
738         return 1;
739 }
740
741 #define PATH_SET "PATH=/sbin"
742
743 static void parse_extended_opts(struct ext2_super_block *param,
744                                 const char *opts)
745 {
746         char    *buf, *token, *next, *p, *arg, *badopt = 0;
747         int     len;
748         int     r_usage = 0;
749         int     ret;
750         int     encoding = -1;
751         char    *encoding_flags = NULL;
752
753         len = strlen(opts);
754         buf = malloc(len+1);
755         if (!buf) {
756                 fprintf(stderr, "%s",
757                         _("Couldn't allocate memory to parse options!\n"));
758                 exit(1);
759         }
760         strcpy(buf, opts);
761         for (token = buf; token && *token; token = next) {
762                 p = strchr(token, ',');
763                 next = 0;
764                 if (p) {
765                         *p = 0;
766                         next = p+1;
767                 }
768                 arg = strchr(token, '=');
769                 if (arg) {
770                         *arg = 0;
771                         arg++;
772                 }
773                 if (strcmp(token, "desc-size") == 0 ||
774                     strcmp(token, "desc_size") == 0) {
775                         int desc_size;
776
777                         if (!ext2fs_has_feature_64bit(&fs_param)) {
778                                 fprintf(stderr,
779                                         _("%s requires '-O 64bit'\n"), token);
780                                 r_usage++;
781                                 continue;
782                         }
783                         if (param->s_reserved_gdt_blocks != 0) {
784                                 fprintf(stderr,
785                                         _("'%s' must be before 'resize=%u'\n"),
786                                         token, param->s_reserved_gdt_blocks);
787                                 r_usage++;
788                                 continue;
789                         }
790                         if (!arg) {
791                                 r_usage++;
792                                 badopt = token;
793                                 continue;
794                         }
795                         desc_size = strtoul(arg, &p, 0);
796                         if (*p || (desc_size & (desc_size - 1))) {
797                                 fprintf(stderr,
798                                         _("Invalid desc_size: '%s'\n"), arg);
799                                 r_usage++;
800                                 continue;
801                         }
802                         param->s_desc_size = desc_size;
803                 } else if (strcmp(token, "hash_seed") == 0) {
804                         if (!arg) {
805                                 r_usage++;
806                                 badopt = token;
807                                 continue;
808                         }
809                         if (uuid_parse(arg,
810                                 (unsigned char *)param->s_hash_seed) != 0) {
811                                 fprintf(stderr,
812                                         _("Invalid hash seed: %s\n"), arg);
813                                 r_usage++;
814                                 continue;
815                         }
816                 } else if (strcmp(token, "offset") == 0) {
817                         if (!arg) {
818                                 r_usage++;
819                                 badopt = token;
820                                 continue;
821                         }
822                         offset = strtoull(arg, &p, 0);
823                         if (*p) {
824                                 fprintf(stderr, _("Invalid offset: %s\n"),
825                                         arg);
826                                 r_usage++;
827                                 continue;
828                         }
829                 } else if (strcmp(token, "mmp_update_interval") == 0) {
830                         if (!arg) {
831                                 r_usage++;
832                                 badopt = token;
833                                 continue;
834                         }
835                         param->s_mmp_update_interval = strtoul(arg, &p, 0);
836                         if (*p) {
837                                 fprintf(stderr,
838                                         _("Invalid mmp_update_interval: %s\n"),
839                                         arg);
840                                 r_usage++;
841                                 continue;
842                         }
843                 } else if (strcmp(token, "no_copy_xattrs") == 0) {
844                         no_copy_xattrs = 1;
845                         continue;
846                 } else if (strcmp(token, "num_backup_sb") == 0) {
847                         if (!arg) {
848                                 r_usage++;
849                                 badopt = token;
850                                 continue;
851                         }
852                         num_backups = strtoul(arg, &p, 0);
853                         if (*p || num_backups > 2) {
854                                 fprintf(stderr,
855                                         _("Invalid # of backup "
856                                           "superblocks: %s\n"),
857                                         arg);
858                                 r_usage++;
859                                 continue;
860                         }
861                 } else if (strcmp(token, "packed_meta_blocks") == 0) {
862                         if (arg)
863                                 packed_meta_blocks = strtoul(arg, &p, 0);
864                         else
865                                 packed_meta_blocks = 1;
866                         if (packed_meta_blocks)
867                                 journal_location = 0;
868                 } else if (strcmp(token, "stride") == 0) {
869                         if (!arg) {
870                                 r_usage++;
871                                 badopt = token;
872                                 continue;
873                         }
874                         param->s_raid_stride = strtoul(arg, &p, 0);
875                         if (*p) {
876                                 fprintf(stderr,
877                                         _("Invalid stride parameter: %s\n"),
878                                         arg);
879                                 r_usage++;
880                                 continue;
881                         }
882                 } else if (strcmp(token, "stripe-width") == 0 ||
883                            strcmp(token, "stripe_width") == 0) {
884                         if (!arg) {
885                                 r_usage++;
886                                 badopt = token;
887                                 continue;
888                         }
889                         param->s_raid_stripe_width = strtoul(arg, &p, 0);
890                         if (*p) {
891                                 fprintf(stderr,
892                                         _("Invalid stripe-width parameter: %s\n"),
893                                         arg);
894                                 r_usage++;
895                                 continue;
896                         }
897                 } else if (!strcmp(token, "resize")) {
898                         blk64_t resize;
899                         unsigned long bpg, rsv_groups;
900                         unsigned long group_desc_count, desc_blocks;
901                         unsigned int gdpb, blocksize;
902                         int rsv_gdb;
903
904                         if (!arg) {
905                                 r_usage++;
906                                 badopt = token;
907                                 continue;
908                         }
909
910                         resize = parse_num_blocks2(arg,
911                                                    param->s_log_block_size);
912
913                         if (resize == 0) {
914                                 fprintf(stderr,
915                                         _("Invalid resize parameter: %s\n"),
916                                         arg);
917                                 r_usage++;
918                                 continue;
919                         }
920                         if (resize <= ext2fs_blocks_count(param)) {
921                                 fprintf(stderr, "%s",
922                                         _("The resize maximum must be greater "
923                                           "than the filesystem size.\n"));
924                                 r_usage++;
925                                 continue;
926                         }
927
928                         blocksize = EXT2_BLOCK_SIZE(param);
929                         bpg = param->s_blocks_per_group;
930                         if (!bpg)
931                                 bpg = blocksize * 8;
932                         gdpb = EXT2_DESC_PER_BLOCK(param);
933                         group_desc_count = (__u32) ext2fs_div64_ceil(
934                                 ext2fs_blocks_count(param), bpg);
935                         desc_blocks = (group_desc_count +
936                                        gdpb - 1) / gdpb;
937                         rsv_groups = ext2fs_div64_ceil(resize, bpg);
938                         rsv_gdb = ext2fs_div_ceil(rsv_groups, gdpb) -
939                                 desc_blocks;
940                         if (rsv_gdb > (int) EXT2_ADDR_PER_BLOCK(param))
941                                 rsv_gdb = EXT2_ADDR_PER_BLOCK(param);
942
943                         if (rsv_gdb > 0) {
944                                 if (param->s_rev_level == EXT2_GOOD_OLD_REV) {
945                                         fprintf(stderr, "%s",
946         _("On-line resizing not supported with revision 0 filesystems\n"));
947                                         free(buf);
948                                         exit(1);
949                                 }
950                                 ext2fs_set_feature_resize_inode(param);
951
952                                 param->s_reserved_gdt_blocks = rsv_gdb;
953                         }
954                 } else if (!strcmp(token, "test_fs")) {
955                         param->s_flags |= EXT2_FLAGS_TEST_FILESYS;
956                 } else if (!strcmp(token, "lazy_itable_init")) {
957                         if (arg)
958                                 lazy_itable_init = strtoul(arg, &p, 0);
959                         else
960                                 lazy_itable_init = 1;
961                 } else if (!strcmp(token, "lazy_journal_init")) {
962                         if (arg)
963                                 journal_flags |= strtoul(arg, &p, 0) ?
964                                                 EXT2_MKJOURNAL_LAZYINIT : 0;
965                         else
966                                 journal_flags |= EXT2_MKJOURNAL_LAZYINIT;
967                 } else if (!strcmp(token, "root_owner")) {
968                         if (arg) {
969                                 root_uid = strtoul(arg, &p, 0);
970                                 if (*p != ':') {
971                                         fprintf(stderr,
972                                                 _("Invalid root_owner: '%s'\n"),
973                                                 arg);
974                                         r_usage++;
975                                         continue;
976                                 }
977                                 p++;
978                                 root_gid = strtoul(p, &p, 0);
979                                 if (*p) {
980                                         fprintf(stderr,
981                                                 _("Invalid root_owner: '%s'\n"),
982                                                 arg);
983                                         r_usage++;
984                                         continue;
985                                 }
986                         } else {
987                                 root_uid = getuid();
988                                 root_gid = getgid();
989                         }
990                 } else if (!strcmp(token, "discard")) {
991                         discard = 1;
992                 } else if (!strcmp(token, "nodiscard")) {
993                         discard = 0;
994                 } else if (!strcmp(token, "quotatype")) {
995                         char *errtok = NULL;
996
997                         if (!arg) {
998                                 r_usage++;
999                                 badopt = token;
1000                                 continue;
1001                         }
1002                         quotatype_bits = 0;
1003                         ret = parse_quota_types(arg, &quotatype_bits, &errtok);
1004                         if (ret) {
1005                                 if (errtok) {
1006                                         fprintf(stderr,
1007                                 "Failed to parse quota type at %s", errtok);
1008                                         free(errtok);
1009                                 } else
1010                                         com_err(program_name, ret,
1011                                                 "while parsing quota type");
1012                                 r_usage++;
1013                                 badopt = token;
1014                                 continue;
1015                         }
1016                 } else if (!strcmp(token, "android_sparse")) {
1017                         android_sparse_file = 1;
1018                 } else if (!strcmp(token, "encoding")) {
1019                         if (!arg) {
1020                                 r_usage++;
1021                                 continue;
1022                         }
1023
1024                         encoding = e2p_str2encoding(arg);
1025                         if (encoding < 0) {
1026                                 fprintf(stderr, _("Invalid encoding: %s"), arg);
1027                                 r_usage++;
1028                                 continue;
1029                         }
1030                         param->s_encoding = encoding;
1031                         ext2fs_set_feature_casefold(param);
1032                 } else if (!strcmp(token, "encoding_flags")) {
1033                         if (!arg) {
1034                                 r_usage++;
1035                                 continue;
1036                         }
1037                         encoding_flags = arg;
1038                 } else {
1039                         r_usage++;
1040                         badopt = token;
1041                 }
1042         }
1043         if (r_usage) {
1044                 fprintf(stderr, _("\nBad option(s) specified: %s\n\n"
1045                         "Extended options are separated by commas, "
1046                         "and may take an argument which\n"
1047                         "\tis set off by an equals ('=') sign.\n\n"
1048                         "Valid extended options are:\n"
1049                         "\tmmp_update_interval=<interval>\n"
1050                         "\tnum_backup_sb=<0|1|2>\n"
1051                         "\tstride=<RAID per-disk data chunk in blocks>\n"
1052                         "\tstripe-width=<RAID stride * data disks in blocks>\n"
1053                         "\toffset=<offset to create the file system>\n"
1054                         "\tresize=<resize maximum size in blocks>\n"
1055                         "\tpacked_meta_blocks=<0 to disable, 1 to enable>\n"
1056                         "\tlazy_itable_init=<0 to disable, 1 to enable>\n"
1057                         "\tlazy_journal_init=<0 to disable, 1 to enable>\n"
1058                         "\troot_owner=<uid of root dir>:<gid of root dir>\n"
1059                         "\ttest_fs\n"
1060                         "\tdiscard\n"
1061                         "\tnodiscard\n"
1062                         "\tencoding=<encoding>\n"
1063                         "\tencoding_flags=<flags>\n"
1064                         "\tquotatype=<quota type(s) to be enabled>\n\n"),
1065                         badopt ? badopt : "");
1066                 free(buf);
1067                 exit(1);
1068         }
1069         if (param->s_raid_stride &&
1070             (param->s_raid_stripe_width % param->s_raid_stride) != 0)
1071                 fprintf(stderr, _("\nWarning: RAID stripe-width %u not an even "
1072                                   "multiple of stride %u.\n\n"),
1073                         param->s_raid_stripe_width, param->s_raid_stride);
1074
1075         if (ext2fs_has_feature_casefold(param)) {
1076                 param->s_encoding_flags =
1077                         e2p_get_encoding_flags(param->s_encoding);
1078
1079                 if (encoding_flags &&
1080                     e2p_str2encoding_flags(param->s_encoding, encoding_flags,
1081                                            &param->s_encoding_flags)) {
1082                         fprintf(stderr, _("error: Invalid encoding flag: %s\n"),
1083                                 encoding_flags);
1084                         free(buf);
1085                         exit(1);
1086                 }
1087         } else if (encoding_flags) {
1088                 fprintf(stderr, _("error: An encoding must be explicitly "
1089                                   "specified when passing encoding-flags\n"));
1090                 free(buf);
1091                 exit(1);
1092         }
1093
1094         free(buf);
1095 }
1096
1097 static __u32 ok_features[3] = {
1098         /* Compat */
1099         EXT3_FEATURE_COMPAT_HAS_JOURNAL |
1100                 EXT2_FEATURE_COMPAT_RESIZE_INODE |
1101                 EXT2_FEATURE_COMPAT_DIR_INDEX |
1102                 EXT2_FEATURE_COMPAT_EXT_ATTR |
1103                 EXT4_FEATURE_COMPAT_SPARSE_SUPER2 |
1104                 EXT4_FEATURE_COMPAT_FAST_COMMIT |
1105                 EXT4_FEATURE_COMPAT_STABLE_INODES,
1106         /* Incompat */
1107         EXT2_FEATURE_INCOMPAT_FILETYPE|
1108                 EXT3_FEATURE_INCOMPAT_EXTENTS|
1109                 EXT3_FEATURE_INCOMPAT_JOURNAL_DEV|
1110                 EXT2_FEATURE_INCOMPAT_META_BG|
1111                 EXT4_FEATURE_INCOMPAT_FLEX_BG|
1112                 EXT4_FEATURE_INCOMPAT_EA_INODE|
1113                 EXT4_FEATURE_INCOMPAT_MMP |
1114                 EXT4_FEATURE_INCOMPAT_DIRDATA|
1115                 EXT4_FEATURE_INCOMPAT_64BIT|
1116                 EXT4_FEATURE_INCOMPAT_INLINE_DATA|
1117                 EXT4_FEATURE_INCOMPAT_ENCRYPT |
1118                 EXT4_FEATURE_INCOMPAT_CASEFOLD |
1119                 EXT4_FEATURE_INCOMPAT_CSUM_SEED |
1120                 EXT4_FEATURE_INCOMPAT_LARGEDIR,
1121         /* R/O compat */
1122         EXT2_FEATURE_RO_COMPAT_LARGE_FILE|
1123                 EXT4_FEATURE_RO_COMPAT_HUGE_FILE|
1124                 EXT4_FEATURE_RO_COMPAT_DIR_NLINK|
1125                 EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE|
1126                 EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER|
1127                 EXT4_FEATURE_RO_COMPAT_GDT_CSUM|
1128                 EXT4_FEATURE_RO_COMPAT_BIGALLOC|
1129                 EXT4_FEATURE_RO_COMPAT_QUOTA|
1130                 EXT4_FEATURE_RO_COMPAT_METADATA_CSUM|
1131                 EXT4_FEATURE_RO_COMPAT_PROJECT|
1132                 EXT4_FEATURE_RO_COMPAT_VERITY
1133 };
1134
1135
1136 static void syntax_err_report(const char *filename, long err, int line_num)
1137 {
1138         fprintf(stderr,
1139                 _("Syntax error in mke2fs config file (%s, line #%d)\n\t%s\n"),
1140                 filename, line_num, error_message(err));
1141         exit(1);
1142 }
1143
1144 static const char *config_fn[] = { ROOT_SYSCONFDIR "/mke2fs.conf", 0 };
1145
1146 static void edit_feature(const char *str, __u32 *compat_array)
1147 {
1148         if (!str)
1149                 return;
1150
1151         if (e2p_edit_feature(str, compat_array, ok_features)) {
1152                 fprintf(stderr, _("Invalid filesystem option set: %s\n"),
1153                         str);
1154                 exit(1);
1155         }
1156 }
1157
1158 static void edit_mntopts(const char *str, __u32 *mntopts)
1159 {
1160         if (!str)
1161                 return;
1162
1163         if (e2p_edit_mntopts(str, mntopts, ~0)) {
1164                 fprintf(stderr, _("Invalid mount option set: %s\n"),
1165                         str);
1166                 exit(1);
1167         }
1168 }
1169
1170 struct str_list {
1171         char **list;
1172         int num;
1173         int max;
1174 };
1175
1176 static errcode_t init_list(struct str_list *sl)
1177 {
1178         sl->num = 0;
1179         sl->max = 1;
1180         sl->list = malloc((sl->max+1) * sizeof(char *));
1181         if (!sl->list)
1182                 return ENOMEM;
1183         sl->list[0] = 0;
1184         return 0;
1185 }
1186
1187 static errcode_t push_string(struct str_list *sl, const char *str)
1188 {
1189         char **new_list;
1190
1191         if (sl->num >= sl->max) {
1192                 sl->max += 2;
1193                 new_list = realloc(sl->list, (sl->max+1) * sizeof(char *));
1194                 if (!new_list)
1195                         return ENOMEM;
1196                 sl->list = new_list;
1197         }
1198         sl->list[sl->num] = malloc(strlen(str)+1);
1199         if (sl->list[sl->num] == 0)
1200                 return ENOMEM;
1201         strcpy(sl->list[sl->num], str);
1202         sl->num++;
1203         sl->list[sl->num] = 0;
1204         return 0;
1205 }
1206
1207 static void print_str_list(char **list)
1208 {
1209         char **cpp;
1210
1211         for (cpp = list; *cpp; cpp++) {
1212                 printf("'%s'", *cpp);
1213                 if (cpp[1])
1214                         fputs(", ", stdout);
1215         }
1216         fputc('\n', stdout);
1217 }
1218
1219 /*
1220  * Return TRUE if the profile has the given subsection
1221  */
1222 static int profile_has_subsection(profile_t prof, const char *section,
1223                                   const char *subsection)
1224 {
1225         void                    *state;
1226         const char              *names[4];
1227         char                    *name;
1228         int                     ret = 0;
1229
1230         names[0] = section;
1231         names[1] = subsection;
1232         names[2] = 0;
1233
1234         if (profile_iterator_create(prof, names,
1235                                     PROFILE_ITER_LIST_SECTION |
1236                                     PROFILE_ITER_RELATIONS_ONLY, &state))
1237                 return 0;
1238
1239         if ((profile_iterator(&state, &name, 0) == 0) && name) {
1240                 free(name);
1241                 ret = 1;
1242         }
1243
1244         profile_iterator_free(&state);
1245         return ret;
1246 }
1247
1248 static char **parse_fs_type(const char *fs_type,
1249                             const char *usage_types,
1250                             struct ext2_super_block *sb,
1251                             blk64_t fs_blocks_count,
1252                             char *progname)
1253 {
1254         const char      *ext_type = 0;
1255         char            *parse_str;
1256         char            *profile_type = 0;
1257         char            *cp, *t;
1258         const char      *size_type;
1259         struct str_list list;
1260         unsigned long long meg;
1261         int             is_hurd = for_hurd(creator_os);
1262
1263         if (init_list(&list))
1264                 return 0;
1265
1266         if (fs_type)
1267                 ext_type = fs_type;
1268         else if (is_hurd)
1269                 ext_type = "ext2";
1270         else if (!strcmp(program_name, "mke3fs"))
1271                 ext_type = "ext3";
1272         else if (!strcmp(program_name, "mke4fs"))
1273                 ext_type = "ext4";
1274         else if (progname) {
1275                 ext_type = strrchr(progname, '/');
1276                 if (ext_type)
1277                         ext_type++;
1278                 else
1279                         ext_type = progname;
1280
1281                 if (!strncmp(ext_type, "mkfs.", 5)) {
1282                         ext_type += 5;
1283                         if (ext_type[0] == 0)
1284                                 ext_type = 0;
1285                 } else
1286                         ext_type = 0;
1287         }
1288
1289         if (!ext_type) {
1290                 profile_get_string(profile, "defaults", "fs_type", 0,
1291                                    "ext2", &profile_type);
1292                 ext_type = profile_type;
1293                 if (!strcmp(ext_type, "ext2") && (journal_size != 0))
1294                         ext_type = "ext3";
1295         }
1296
1297
1298         if (!profile_has_subsection(profile, "fs_types", ext_type) &&
1299             strcmp(ext_type, "ext2")) {
1300                 printf(_("\nYour mke2fs.conf file does not define the "
1301                          "%s filesystem type.\n"), ext_type);
1302                 if (!strcmp(ext_type, "ext3") || !strcmp(ext_type, "ext4") ||
1303                     !strcmp(ext_type, "ext4dev")) {
1304                         printf("%s", _("You probably need to install an "
1305                                        "updated mke2fs.conf file.\n\n"));
1306                 }
1307                 if (!force) {
1308                         printf("%s", _("Aborting...\n"));
1309                         exit(1);
1310                 }
1311         }
1312
1313         meg = (1024 * 1024) / EXT2_BLOCK_SIZE(sb);
1314         if (fs_blocks_count < 3 * meg)
1315                 size_type = "floppy";
1316         else if (fs_blocks_count < 512 * meg)
1317                 size_type = "small";
1318         else if (fs_blocks_count < 4 * 1024 * 1024 * meg)
1319                 size_type = "default";
1320         else if (fs_blocks_count < 16 * 1024 * 1024 * meg)
1321                 size_type = "big";
1322         else
1323                 size_type = "huge";
1324
1325         if (!usage_types)
1326                 usage_types = size_type;
1327
1328         parse_str = malloc(strlen(usage_types)+1);
1329         if (!parse_str) {
1330                 free(profile_type);
1331                 free(list.list);
1332                 return 0;
1333         }
1334         strcpy(parse_str, usage_types);
1335
1336         if (ext_type)
1337                 push_string(&list, ext_type);
1338         cp = parse_str;
1339         while (1) {
1340                 t = strchr(cp, ',');
1341                 if (t)
1342                         *t = '\0';
1343
1344                 if (*cp) {
1345                         if (profile_has_subsection(profile, "fs_types", cp))
1346                                 push_string(&list, cp);
1347                         else if (strcmp(cp, "default") != 0)
1348                                 fprintf(stderr,
1349                                         _("\nWarning: the fs_type %s is not "
1350                                           "defined in mke2fs.conf\n\n"),
1351                                         cp);
1352                 }
1353                 if (t)
1354                         cp = t+1;
1355                 else
1356                         break;
1357         }
1358         free(parse_str);
1359         free(profile_type);
1360         if (is_hurd)
1361                 push_string(&list, "hurd");
1362         return (list.list);
1363 }
1364
1365 char *get_string_from_profile(char **types, const char *opt,
1366                                      const char *def_val)
1367 {
1368         char *ret = 0;
1369         int i;
1370
1371         for (i=0; types[i]; i++);
1372         for (i-=1; i >=0 ; i--) {
1373                 profile_get_string(profile, "fs_types", types[i],
1374                                    opt, 0, &ret);
1375                 if (ret)
1376                         return ret;
1377         }
1378         profile_get_string(profile, "defaults", opt, 0, def_val, &ret);
1379         return (ret);
1380 }
1381
1382 int get_int_from_profile(char **types, const char *opt, int def_val)
1383 {
1384         int ret;
1385         char **cpp;
1386
1387         profile_get_integer(profile, "defaults", opt, 0, def_val, &ret);
1388         for (cpp = types; *cpp; cpp++)
1389                 profile_get_integer(profile, "fs_types", *cpp, opt, ret, &ret);
1390         return ret;
1391 }
1392
1393 static unsigned int get_uint_from_profile(char **types, const char *opt,
1394                                         unsigned int def_val)
1395 {
1396         unsigned int ret;
1397         char **cpp;
1398
1399         profile_get_uint(profile, "defaults", opt, 0, def_val, &ret);
1400         for (cpp = types; *cpp; cpp++)
1401                 profile_get_uint(profile, "fs_types", *cpp, opt, ret, &ret);
1402         return ret;
1403 }
1404
1405 static double get_double_from_profile(char **types, const char *opt,
1406                                       double def_val)
1407 {
1408         double ret;
1409         char **cpp;
1410
1411         profile_get_double(profile, "defaults", opt, 0, def_val, &ret);
1412         for (cpp = types; *cpp; cpp++)
1413                 profile_get_double(profile, "fs_types", *cpp, opt, ret, &ret);
1414         return ret;
1415 }
1416
1417 int get_bool_from_profile(char **types, const char *opt, int def_val)
1418 {
1419         int ret;
1420         char **cpp;
1421
1422         profile_get_boolean(profile, "defaults", opt, 0, def_val, &ret);
1423         for (cpp = types; *cpp; cpp++)
1424                 profile_get_boolean(profile, "fs_types", *cpp, opt, ret, &ret);
1425         return ret;
1426 }
1427
1428 extern const char *mke2fs_default_profile;
1429 static const char *default_files[] = { "<default>", 0 };
1430
1431 struct device_param {
1432         unsigned long min_io;           /* prefered minimum IO size */
1433         unsigned long opt_io;           /* optimal IO size */
1434         unsigned long alignment_offset; /* alignment offset wrt physical block size */
1435         unsigned int dax:1;             /* supports dax? */
1436 };
1437
1438 #ifdef HAVE_BLKID_PROBE_GET_TOPOLOGY
1439 /*
1440  * Sets the geometry of a device (stripe/stride), and returns the
1441  * device's alignment offset, if any, or a negative error.
1442  */
1443 static int get_device_geometry(const char *file,
1444                                unsigned int blocksize,
1445                                unsigned int psector_size,
1446                                struct device_param *dev_param)
1447 {
1448         int rc = -1;
1449         blkid_probe pr;
1450         blkid_topology tp;
1451         struct stat statbuf;
1452
1453         memset(dev_param, 0, sizeof(*dev_param));
1454
1455         /* Nothing to do for a regular file */
1456         if (!stat(file, &statbuf) && S_ISREG(statbuf.st_mode))
1457                 return 0;
1458
1459         pr = blkid_new_probe_from_filename(file);
1460         if (!pr)
1461                 goto out;
1462
1463         tp = blkid_probe_get_topology(pr);
1464         if (!tp)
1465                 goto out;
1466
1467         dev_param->min_io = blkid_topology_get_minimum_io_size(tp);
1468         dev_param->opt_io = blkid_topology_get_optimal_io_size(tp);
1469         if ((dev_param->min_io == 0) && (psector_size > blocksize))
1470                 dev_param->min_io = psector_size;
1471         if ((dev_param->opt_io == 0) && dev_param->min_io > 0)
1472                 dev_param->opt_io = dev_param->min_io;
1473         if ((dev_param->opt_io == 0) && (psector_size > blocksize))
1474                 dev_param->opt_io = psector_size;
1475
1476         dev_param->alignment_offset = blkid_topology_get_alignment_offset(tp);
1477 #ifdef HAVE_BLKID_TOPOLOGY_GET_DAX
1478         dev_param->dax = blkid_topology_get_dax(tp);
1479 #endif
1480         rc = 0;
1481 out:
1482         blkid_free_probe(pr);
1483         return rc;
1484 }
1485 #endif
1486
1487 static void PRS(int argc, char *argv[])
1488 {
1489         int             b, c, flags;
1490         int             cluster_size = 0;
1491         char            *tmp, **cpp;
1492         int             explicit_fssize = 0;
1493         int             blocksize = 0;
1494         int             inode_ratio = 0;
1495         int             inode_size = 0;
1496         unsigned long   flex_bg_size = 0;
1497         double          reserved_ratio = -1.0;
1498         int             lsector_size = 0, psector_size = 0;
1499         int             show_version_only = 0, is_device = 0;
1500         unsigned long long num_inodes = 0; /* unsigned long long to catch too-large input */
1501         errcode_t       retval;
1502         char *          oldpath = getenv("PATH");
1503         char *          extended_opts = 0;
1504         char *          fs_type = 0;
1505         char *          usage_types = 0;
1506         /*
1507          * NOTE: A few words about fs_blocks_count and blocksize:
1508          *
1509          * Initially, blocksize is set to zero, which implies 1024.
1510          * If -b is specified, blocksize is updated to the user's value.
1511          *
1512          * Next, the device size or the user's "blocks" command line argument
1513          * is used to set fs_blocks_count; the units are blocksize.
1514          *
1515          * Later, if blocksize hasn't been set and the profile specifies a
1516          * blocksize, then blocksize is updated and fs_blocks_count is scaled
1517          * appropriately.  Note the change in units!
1518          *
1519          * Finally, we complain about fs_blocks_count > 2^32 on a non-64bit fs.
1520          */
1521         blk64_t         fs_blocks_count = 0;
1522         long            sysval;
1523         int             s_opt = -1, r_opt = -1;
1524         char            *fs_features = 0;
1525         int             fs_features_size = 0;
1526         int             use_bsize;
1527         char            *newpath;
1528         int             pathlen = sizeof(PATH_SET) + 1;
1529         struct device_param dev_param;
1530
1531         if (oldpath)
1532                 pathlen += strlen(oldpath);
1533         newpath = malloc(pathlen);
1534         if (!newpath) {
1535                 fprintf(stderr, "%s",
1536                         _("Couldn't allocate memory for new PATH.\n"));
1537                 exit(1);
1538         }
1539         strcpy(newpath, PATH_SET);
1540
1541         /* Update our PATH to include /sbin  */
1542         if (oldpath) {
1543                 strcat (newpath, ":");
1544                 strcat (newpath, oldpath);
1545         }
1546         putenv (newpath);
1547
1548         /* Determine the system page size if possible */
1549 #ifdef HAVE_SYSCONF
1550 #if (!defined(_SC_PAGESIZE) && defined(_SC_PAGE_SIZE))
1551 #define _SC_PAGESIZE _SC_PAGE_SIZE
1552 #endif
1553 #ifdef _SC_PAGESIZE
1554         sysval = sysconf(_SC_PAGESIZE);
1555         if (sysval > 0)
1556                 sys_page_size = sysval;
1557 #endif /* _SC_PAGESIZE */
1558 #endif /* HAVE_SYSCONF */
1559
1560         if ((tmp = getenv("MKE2FS_CONFIG")) != NULL)
1561                 config_fn[0] = tmp;
1562         profile_set_syntax_err_cb(syntax_err_report);
1563         retval = profile_init(config_fn, &profile);
1564         if (retval == ENOENT) {
1565                 retval = profile_init(default_files, &profile);
1566                 if (retval)
1567                         goto profile_error;
1568                 retval = profile_set_default(profile, mke2fs_default_profile);
1569                 if (retval)
1570                         goto profile_error;
1571         } else if (retval) {
1572 profile_error:
1573                 fprintf(stderr, _("Couldn't init profile successfully"
1574                                   " (error: %ld).\n"), retval);
1575                 exit(1);
1576         }
1577
1578         setbuf(stdout, NULL);
1579         setbuf(stderr, NULL);
1580         add_error_table(&et_ext2_error_table);
1581         add_error_table(&et_prof_error_table);
1582         memset(&fs_param, 0, sizeof(struct ext2_super_block));
1583         fs_param.s_rev_level = 1;  /* Create revision 1 filesystems now */
1584
1585         if (ext2fs_is_before_linux_ver(2, 2, 0))
1586                 fs_param.s_rev_level = 0;
1587
1588         if (argc && *argv) {
1589                 program_name = get_progname(*argv);
1590
1591                 /* If called as mkfs.ext3, create a journal inode */
1592                 if (!strcmp(program_name, "mkfs.ext3") ||
1593                     !strcmp(program_name, "mke3fs"))
1594                         journal_size = -1;
1595         }
1596
1597         while ((c = getopt (argc, argv,
1598                     "b:cd:e:g:i:jl:m:no:qr:s:t:vC:DE:FG:I:J:KL:M:N:O:R:ST:U:Vz:")) != EOF) {
1599                 switch (c) {
1600                 case 'b':
1601                         blocksize = parse_num_blocks2(optarg, -1);
1602                         b = (blocksize > 0) ? blocksize : -blocksize;
1603                         if (b < EXT2_MIN_BLOCK_SIZE ||
1604                             b > EXT2_MAX_BLOCK_SIZE) {
1605                                 com_err(program_name, 0,
1606                                         _("invalid block size - %s"), optarg);
1607                                 exit(1);
1608                         }
1609                         if (blocksize > 4096)
1610                                 fprintf(stderr, _("Warning: blocksize %d not "
1611                                                   "usable on most systems.\n"),
1612                                         blocksize);
1613                         if (blocksize > 0)
1614                                 fs_param.s_log_block_size =
1615                                         int_log2(blocksize >>
1616                                                  EXT2_MIN_BLOCK_LOG_SIZE);
1617                         break;
1618                 case 'c':       /* Check for bad blocks */
1619                         cflag++;
1620                         break;
1621                 case 'C':
1622                         cluster_size = parse_num_blocks2(optarg, -1);
1623                         if (cluster_size <= EXT2_MIN_CLUSTER_SIZE ||
1624                             cluster_size > EXT2_MAX_CLUSTER_SIZE) {
1625                                 com_err(program_name, 0,
1626                                         _("invalid cluster size - %s"),
1627                                         optarg);
1628                                 exit(1);
1629                         }
1630                         break;
1631                 case 'd':
1632                         src_root_dir = optarg;
1633                         break;
1634                 case 'D':
1635                         direct_io = 1;
1636                         break;
1637                 case 'R':
1638                         com_err(program_name, 0, "%s",
1639                                 _("'-R' is deprecated, use '-E' instead"));
1640                         /* fallthrough */
1641                 case 'E':
1642                         extended_opts = optarg;
1643                         break;
1644                 case 'e':
1645                         if (strcmp(optarg, "continue") == 0)
1646                                 errors_behavior = EXT2_ERRORS_CONTINUE;
1647                         else if (strcmp(optarg, "remount-ro") == 0)
1648                                 errors_behavior = EXT2_ERRORS_RO;
1649                         else if (strcmp(optarg, "panic") == 0)
1650                                 errors_behavior = EXT2_ERRORS_PANIC;
1651                         else {
1652                                 com_err(program_name, 0,
1653                                         _("bad error behavior - %s"),
1654                                         optarg);
1655                                 usage();
1656                         }
1657                         break;
1658                 case 'F':
1659                         force++;
1660                         break;
1661                 case 'g':
1662                         fs_param.s_blocks_per_group = strtoul(optarg, &tmp, 0);
1663                         if (*tmp) {
1664                                 com_err(program_name, 0, "%s",
1665                                 _("Illegal number for blocks per group"));
1666                                 exit(1);
1667                         }
1668                         if ((fs_param.s_blocks_per_group % 8) != 0) {
1669                                 com_err(program_name, 0, "%s",
1670                                 _("blocks per group must be multiple of 8"));
1671                                 exit(1);
1672                         }
1673                         break;
1674                 case 'G':
1675                         flex_bg_size = strtoul(optarg, &tmp, 0);
1676                         if (*tmp) {
1677                                 com_err(program_name, 0, "%s",
1678                                         _("Illegal number for flex_bg size"));
1679                                 exit(1);
1680                         }
1681                         if (flex_bg_size < 1 ||
1682                             (flex_bg_size & (flex_bg_size-1)) != 0) {
1683                                 com_err(program_name, 0, "%s",
1684                                         _("flex_bg size must be a power of 2"));
1685                                 exit(1);
1686                         }
1687                         if (flex_bg_size > MAX_32_NUM) {
1688                                 com_err(program_name, 0,
1689                                 _("flex_bg size (%lu) must be less than"
1690                                 " or equal to 2^31"), flex_bg_size);
1691                                 exit(1);
1692                         }
1693                         break;
1694                 case 'i':
1695                         inode_ratio = parse_num_blocks(optarg, -1);
1696                         if (inode_ratio < EXT2_MIN_BLOCK_SIZE ||
1697                             inode_ratio > EXT2_MAX_BLOCK_SIZE * 1024) {
1698                                 com_err(program_name, 0,
1699                                         _("invalid inode ratio %s (min %d/max %d)"),
1700                                         optarg, EXT2_MIN_BLOCK_SIZE,
1701                                         EXT2_MAX_BLOCK_SIZE * 1024);
1702                                 exit(1);
1703                         }
1704                         break;
1705                 case 'I':
1706                         inode_size = strtoul(optarg, &tmp, 0);
1707                         if (*tmp) {
1708                                 com_err(program_name, 0,
1709                                         _("invalid inode size - %s"), optarg);
1710                                 exit(1);
1711                         }
1712                         break;
1713                 case 'j':
1714                         if (!journal_size)
1715                                 journal_size = -1;
1716                         if (!journal_fc_size)
1717                                 journal_fc_size = -1;
1718                         break;
1719                 case 'J':
1720                         parse_journal_opts(optarg);
1721                         break;
1722                 case 'K':
1723                         fprintf(stderr, "%s",
1724                                 _("Warning: -K option is deprecated and "
1725                                   "should not be used anymore. Use "
1726                                   "\'-E nodiscard\' extended option "
1727                                   "instead!\n"));
1728                         discard = 0;
1729                         break;
1730                 case 'l':
1731                         bad_blocks_filename = realloc(bad_blocks_filename,
1732                                                       strlen(optarg) + 1);
1733                         if (!bad_blocks_filename) {
1734                                 com_err(program_name, ENOMEM, "%s",
1735                                         _("in malloc for bad_blocks_filename"));
1736                                 exit(1);
1737                         }
1738                         strcpy(bad_blocks_filename, optarg);
1739                         break;
1740                 case 'L':
1741                         volume_label = optarg;
1742                         if (strlen(volume_label) > EXT2_LABEL_LEN) {
1743                                 volume_label[EXT2_LABEL_LEN] = '\0';
1744                                 fprintf(stderr, _("Warning: label too long; will be truncated to '%s'\n\n"),
1745                                         volume_label);
1746                         }
1747                         break;
1748                 case 'm':
1749                         reserved_ratio = strtod(optarg, &tmp);
1750                         if ( *tmp || reserved_ratio > 50 ||
1751                              reserved_ratio < 0) {
1752                                 com_err(program_name, 0,
1753                                         _("invalid reserved blocks percent - %s"),
1754                                         optarg);
1755                                 exit(1);
1756                         }
1757                         break;
1758                 case 'M':
1759                         mount_dir = optarg;
1760                         break;
1761                 case 'n':
1762                         noaction++;
1763                         break;
1764                 case 'N':
1765                         num_inodes = strtoul(optarg, &tmp, 0);
1766                         if (*tmp) {
1767                                 com_err(program_name, 0,
1768                                         _("bad num inodes - %s"), optarg);
1769                                         exit(1);
1770                         }
1771                         break;
1772                 case 'o':
1773                         creator_os = optarg;
1774                         break;
1775                 case 'O':
1776                         retval = ext2fs_resize_mem(fs_features_size,
1777                                    fs_features_size + 1 + strlen(optarg),
1778                                                    &fs_features);
1779                         if (retval) {
1780                                 com_err(program_name, retval,
1781                                      _("while allocating fs_feature string"));
1782                                 exit(1);
1783                         }
1784                         if (fs_features_size)
1785                                 strcat(fs_features, ",");
1786                         else
1787                                 fs_features[0] = 0;
1788                         strcat(fs_features, optarg);
1789                         fs_features_size += 1 + strlen(optarg);
1790                         break;
1791                 case 'q':
1792                         quiet = 1;
1793                         break;
1794                 case 'r':
1795                         r_opt = strtoul(optarg, &tmp, 0);
1796                         if (*tmp) {
1797                                 com_err(program_name, 0,
1798                                         _("bad revision level - %s"), optarg);
1799                                 exit(1);
1800                         }
1801                         if (r_opt > EXT2_MAX_SUPP_REV) {
1802                                 com_err(program_name, EXT2_ET_REV_TOO_HIGH,
1803                                         _("while trying to create revision %d"), r_opt);
1804                                 exit(1);
1805                         }
1806                         fs_param.s_rev_level = r_opt;
1807                         break;
1808                 case 's':       /* deprecated */
1809                         s_opt = atoi(optarg);
1810                         break;
1811                 case 'S':
1812                         super_only = 1;
1813                         break;
1814                 case 't':
1815                         if (fs_type) {
1816                                 com_err(program_name, 0, "%s",
1817                                     _("The -t option may only be used once"));
1818                                 exit(1);
1819                         }
1820                         fs_type = strdup(optarg);
1821                         break;
1822                 case 'T':
1823                         if (usage_types) {
1824                                 com_err(program_name, 0, "%s",
1825                                     _("The -T option may only be used once"));
1826                                 exit(1);
1827                         }
1828                         usage_types = strdup(optarg);
1829                         break;
1830                 case 'U':
1831                         fs_uuid = optarg;
1832                         break;
1833                 case 'v':
1834                         verbose = 1;
1835                         break;
1836                 case 'V':
1837                         /* Print version number and exit */
1838                         show_version_only++;
1839                         break;
1840                 case 'z':
1841                         undo_file = optarg;
1842                         break;
1843                 default:
1844                         usage();
1845                 }
1846         }
1847         if ((optind == argc) && !show_version_only)
1848                 usage();
1849         device_name = argv[optind++];
1850
1851         if (!quiet || show_version_only)
1852                 fprintf (stderr, "mke2fs %s (%s)\n", E2FSPROGS_VERSION,
1853                          E2FSPROGS_DATE);
1854
1855         if (show_version_only) {
1856                 fprintf(stderr, _("\tUsing %s\n"),
1857                         error_message(EXT2_ET_BASE));
1858                 exit(0);
1859         }
1860
1861         /*
1862          * If there's no blocksize specified and there is a journal
1863          * device, use it to figure out the blocksize
1864          */
1865         if (blocksize <= 0 && journal_device) {
1866                 ext2_filsys     jfs;
1867                 io_manager      io_ptr;
1868
1869 #ifdef CONFIG_TESTIO_DEBUG
1870                 if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_BLOCK")) {
1871                         io_ptr = test_io_manager;
1872                         test_io_backing_manager = unix_io_manager;
1873                 } else
1874 #endif
1875                         io_ptr = unix_io_manager;
1876                 retval = ext2fs_open(journal_device,
1877                                      EXT2_FLAG_JOURNAL_DEV_OK, 0,
1878                                      0, io_ptr, &jfs);
1879                 if (retval) {
1880                         com_err(program_name, retval,
1881                                 _("while trying to open journal device %s\n"),
1882                                 journal_device);
1883                         exit(1);
1884                 }
1885                 if ((blocksize < 0) && (jfs->blocksize < (unsigned) (-blocksize))) {
1886                         com_err(program_name, 0,
1887                                 _("Journal dev blocksize (%d) smaller than "
1888                                   "minimum blocksize %d\n"), jfs->blocksize,
1889                                 -blocksize);
1890                         exit(1);
1891                 }
1892                 blocksize = jfs->blocksize;
1893                 printf(_("Using journal device's blocksize: %d\n"), blocksize);
1894                 fs_param.s_log_block_size =
1895                         int_log2(blocksize >> EXT2_MIN_BLOCK_LOG_SIZE);
1896                 ext2fs_close_free(&jfs);
1897         }
1898
1899         if (optind < argc) {
1900                 fs_blocks_count = parse_num_blocks2(argv[optind++],
1901                                                    fs_param.s_log_block_size);
1902                 if (!fs_blocks_count) {
1903                         com_err(program_name, 0,
1904                                 _("invalid blocks '%s' on device '%s'"),
1905                                 argv[optind - 1], device_name);
1906                         exit(1);
1907                 }
1908         }
1909         if (optind < argc)
1910                 usage();
1911
1912         profile_get_integer(profile, "options", "sync_kludge", 0, 0,
1913                             &sync_kludge);
1914         tmp = getenv("MKE2FS_SYNC");
1915         if (tmp)
1916                 sync_kludge = atoi(tmp);
1917
1918         profile_get_integer(profile, "options", "proceed_delay", 0, 0,
1919                             &proceed_delay);
1920
1921         /* The isatty() test is so we don't break existing scripts */
1922         flags = CREATE_FILE;
1923         if (isatty(0) && isatty(1) && !offset)
1924                 flags |= CHECK_FS_EXIST;
1925         if (!quiet)
1926                 flags |= VERBOSE_CREATE;
1927         if (fs_blocks_count == 0)
1928                 flags |= NO_SIZE;
1929         else
1930                 explicit_fssize = 1;
1931         if (!check_plausibility(device_name, flags, &is_device) && !force)
1932                 proceed_question(proceed_delay);
1933
1934         check_mount(device_name, force, _("filesystem"));
1935
1936         /* Determine the size of the device (if possible) */
1937         if (noaction && fs_blocks_count) {
1938                 dev_size = fs_blocks_count;
1939                 retval = 0;
1940         } else
1941 #ifndef _WIN32
1942                 retval = ext2fs_get_device_size2(device_name,
1943                                                  EXT2_BLOCK_SIZE(&fs_param),
1944                                                  &dev_size);
1945 #else
1946                 retval = ext2fs_get_device_size(device_name,
1947                                                 EXT2_BLOCK_SIZE(&fs_param),
1948                                                 &dev_size);
1949 #endif
1950         if (retval && (retval != EXT2_ET_UNIMPLEMENTED)) {
1951                 com_err(program_name, retval, "%s",
1952                         _("while trying to determine filesystem size"));
1953                 exit(1);
1954         }
1955         if (!fs_blocks_count) {
1956                 if (retval == EXT2_ET_UNIMPLEMENTED) {
1957                         com_err(program_name, 0, "%s",
1958                                 _("Couldn't determine device size; you "
1959                                 "must specify\nthe size of the "
1960                                 "filesystem\n"));
1961                         exit(1);
1962                 } else {
1963                         if (dev_size == 0) {
1964                                 com_err(program_name, 0, "%s",
1965                                 _("Device size reported to be zero.  "
1966                                   "Invalid partition specified, or\n\t"
1967                                   "partition table wasn't reread "
1968                                   "after running fdisk, due to\n\t"
1969                                   "a modified partition being busy "
1970                                   "and in use.  You may need to reboot\n\t"
1971                                   "to re-read your partition table.\n"
1972                                   ));
1973                                 exit(1);
1974                         }
1975                         fs_blocks_count = dev_size;
1976                         if (sys_page_size > EXT2_BLOCK_SIZE(&fs_param))
1977                                 fs_blocks_count &= ~((blk64_t) ((sys_page_size /
1978                                              EXT2_BLOCK_SIZE(&fs_param))-1));
1979                 }
1980         } else if (!force && is_device && (fs_blocks_count > dev_size)) {
1981                 com_err(program_name, 0, "%s",
1982                         _("Filesystem larger than apparent device size."));
1983                 proceed_question(proceed_delay);
1984         }
1985
1986         if (!fs_type)
1987                 profile_get_string(profile, "devices", device_name,
1988                                    "fs_type", 0, &fs_type);
1989         if (!usage_types)
1990                 profile_get_string(profile, "devices", device_name,
1991                                    "usage_types", 0, &usage_types);
1992
1993         /*
1994          * We have the file system (or device) size, so we can now
1995          * determine the appropriate file system types so the fs can
1996          * be appropriately configured.
1997          */
1998         fs_types = parse_fs_type(fs_type, usage_types, &fs_param,
1999                                  fs_blocks_count ? fs_blocks_count : dev_size,
2000                                  argv[0]);
2001         if (!fs_types) {
2002                 fprintf(stderr, "%s", _("Failed to parse fs types list\n"));
2003                 exit(1);
2004         }
2005
2006         /* Figure out what features should be enabled */
2007
2008         tmp = NULL;
2009         if (fs_param.s_rev_level != EXT2_GOOD_OLD_REV) {
2010                 tmp = get_string_from_profile(fs_types, "base_features",
2011                       "sparse_super,large_file,filetype,resize_inode,dir_index");
2012                 edit_feature(tmp, &fs_param.s_feature_compat);
2013                 free(tmp);
2014
2015                 /* And which mount options as well */
2016                 tmp = get_string_from_profile(fs_types, "default_mntopts",
2017                                               "acl,user_xattr");
2018                 edit_mntopts(tmp, &fs_param.s_default_mount_opts);
2019                 if (tmp)
2020                         free(tmp);
2021
2022                 for (cpp = fs_types; *cpp; cpp++) {
2023                         tmp = NULL;
2024                         profile_get_string(profile, "fs_types", *cpp,
2025                                            "features", "", &tmp);
2026                         if (tmp && *tmp)
2027                                 edit_feature(tmp, &fs_param.s_feature_compat);
2028                         if (tmp)
2029                                 free(tmp);
2030                 }
2031                 tmp = get_string_from_profile(fs_types, "default_features",
2032                                               "");
2033         }
2034         /* Mask off features which aren't supported by the Hurd */
2035         if (for_hurd(creator_os)) {
2036                 ext2fs_clear_feature_filetype(&fs_param);
2037                 ext2fs_clear_feature_huge_file(&fs_param);
2038                 ext2fs_clear_feature_metadata_csum(&fs_param);
2039                 ext2fs_clear_feature_ea_inode(&fs_param);
2040                 ext2fs_clear_feature_casefold(&fs_param);
2041         }
2042         edit_feature(fs_features ? fs_features : tmp,
2043                      &fs_param.s_feature_compat);
2044         if (tmp)
2045                 free(tmp);
2046         (void) ext2fs_free_mem(&fs_features);
2047         /*
2048          * If the user specified features incompatible with the Hurd, complain
2049          */
2050         if (for_hurd(creator_os)) {
2051                 if (ext2fs_has_feature_filetype(&fs_param)) {
2052                         fprintf(stderr, "%s", _("The HURD does not support the "
2053                                                 "filetype feature.\n"));
2054                         exit(1);
2055                 }
2056                 if (ext2fs_has_feature_huge_file(&fs_param)) {
2057                         fprintf(stderr, "%s", _("The HURD does not support the "
2058                                                 "huge_file feature.\n"));
2059                         exit(1);
2060                 }
2061                 if (ext2fs_has_feature_metadata_csum(&fs_param)) {
2062                         fprintf(stderr, "%s", _("The HURD does not support the "
2063                                                 "metadata_csum feature.\n"));
2064                         exit(1);
2065                 }
2066                 if (ext2fs_has_feature_ea_inode(&fs_param)) {
2067                         fprintf(stderr, "%s", _("The HURD does not support the "
2068                                                 "ea_inode feature.\n"));
2069                         exit(1);
2070                 }
2071         }
2072
2073         /* Get the hardware sector sizes, if available */
2074         retval = ext2fs_get_device_sectsize(device_name, &lsector_size);
2075         if (retval) {
2076                 com_err(program_name, retval, "%s",
2077                         _("while trying to determine hardware sector size"));
2078                 exit(1);
2079         }
2080         retval = ext2fs_get_device_phys_sectsize(device_name, &psector_size);
2081         if (retval) {
2082                 com_err(program_name, retval, "%s",
2083                         _("while trying to determine physical sector size"));
2084                 exit(1);
2085         }
2086
2087         tmp = getenv("MKE2FS_DEVICE_SECTSIZE");
2088         if (tmp != NULL)
2089                 lsector_size = atoi(tmp);
2090         tmp = getenv("MKE2FS_DEVICE_PHYS_SECTSIZE");
2091         if (tmp != NULL)
2092                 psector_size = atoi(tmp);
2093
2094         /* Older kernels may not have physical/logical distinction */
2095         if (!psector_size)
2096                 psector_size = lsector_size;
2097
2098         if (blocksize <= 0) {
2099                 use_bsize = get_int_from_profile(fs_types, "blocksize", 4096);
2100
2101                 if (use_bsize == -1) {
2102                         use_bsize = sys_page_size;
2103                         if (ext2fs_is_before_linux_ver(2, 6, 0) &&
2104                             use_bsize > 4096)
2105                                 use_bsize = 4096;
2106                 }
2107                 if (lsector_size && use_bsize < lsector_size)
2108                         use_bsize = lsector_size;
2109                 if ((blocksize < 0) && (use_bsize < (-blocksize)))
2110                         use_bsize = -blocksize;
2111                 blocksize = use_bsize;
2112                 fs_blocks_count /= (blocksize / 1024);
2113         } else {
2114                 if (blocksize < lsector_size) {                 /* Impossible */
2115                         com_err(program_name, EINVAL, "%s",
2116                                 _("while setting blocksize; too small "
2117                                   "for device\n"));
2118                         exit(1);
2119                 } else if ((blocksize < psector_size) &&
2120                            (psector_size <= sys_page_size)) {   /* Suboptimal */
2121                         fprintf(stderr, _("Warning: specified blocksize %d is "
2122                                 "less than device physical sectorsize %d\n"),
2123                                 blocksize, psector_size);
2124                 }
2125         }
2126
2127         fs_param.s_log_block_size =
2128                 int_log2(blocksize >> EXT2_MIN_BLOCK_LOG_SIZE);
2129
2130         /*
2131          * We now need to do a sanity check of fs_blocks_count for
2132          * 32-bit vs 64-bit block number support.
2133          */
2134         if ((fs_blocks_count > MAX_32_NUM) &&
2135             ext2fs_has_feature_64bit(&fs_param))
2136                 ext2fs_clear_feature_resize_inode(&fs_param);
2137         if ((fs_blocks_count > MAX_32_NUM) &&
2138             !ext2fs_has_feature_64bit(&fs_param) &&
2139             get_bool_from_profile(fs_types, "auto_64-bit_support", 0)) {
2140                 ext2fs_set_feature_64bit(&fs_param);
2141                 ext2fs_clear_feature_resize_inode(&fs_param);
2142         }
2143         if ((fs_blocks_count > MAX_32_NUM) &&
2144             !ext2fs_has_feature_64bit(&fs_param)) {
2145                 fprintf(stderr, _("%s: Size of device (0x%llx blocks) %s "
2146                                   "too big to be expressed\n\t"
2147                                   "in 32 bits using a blocksize of %d.\n"),
2148                         program_name, (unsigned long long) fs_blocks_count,
2149                         device_name, EXT2_BLOCK_SIZE(&fs_param));
2150                 exit(1);
2151         }
2152         /*
2153          * Guard against group descriptor count overflowing... Mostly to avoid
2154          * strange results for absurdly large devices.  This is in log2:
2155          * (blocksize) * (bits per byte) * (maximum number of block groups)
2156          */
2157         if (fs_blocks_count >
2158             (1ULL << (EXT2_BLOCK_SIZE_BITS(&fs_param) + 3 + 32)) - 1) {
2159                 fprintf(stderr, _("%s: Size of device (0x%llx blocks) %s "
2160                                   "too big to create\n\t"
2161                                   "a filesystem using a blocksize of %d.\n"),
2162                         program_name, (unsigned long long) fs_blocks_count,
2163                         device_name, EXT2_BLOCK_SIZE(&fs_param));
2164                 exit(1);
2165         }
2166
2167         ext2fs_blocks_count_set(&fs_param, fs_blocks_count);
2168
2169         if (ext2fs_has_feature_journal_dev(&fs_param)) {
2170                 int i;
2171
2172                 for (i=0; fs_types[i]; i++) {
2173                         free(fs_types[i]);
2174                         fs_types[i] = 0;
2175                 }
2176                 fs_types[0] = strdup("journal");
2177                 fs_types[1] = 0;
2178         }
2179
2180         if (verbose) {
2181                 fputs(_("fs_types for mke2fs.conf resolution: "), stdout);
2182                 print_str_list(fs_types);
2183         }
2184
2185         if (r_opt == EXT2_GOOD_OLD_REV &&
2186             (fs_param.s_feature_compat || fs_param.s_feature_incompat ||
2187              fs_param.s_feature_ro_compat)) {
2188                 fprintf(stderr, "%s", _("Filesystem features not supported "
2189                                         "with revision 0 filesystems\n"));
2190                 exit(1);
2191         }
2192
2193         if (s_opt > 0) {
2194                 if (r_opt == EXT2_GOOD_OLD_REV) {
2195                         fprintf(stderr, "%s",
2196                                 _("Sparse superblocks not supported "
2197                                   "with revision 0 filesystems\n"));
2198                         exit(1);
2199                 }
2200                 ext2fs_set_feature_sparse_super(&fs_param);
2201         } else if (s_opt == 0)
2202                 ext2fs_clear_feature_sparse_super(&fs_param);
2203
2204         if (journal_size != 0) {
2205                 if (r_opt == EXT2_GOOD_OLD_REV) {
2206                         fprintf(stderr, "%s", _("Journals not supported with "
2207                                                 "revision 0 filesystems\n"));
2208                         exit(1);
2209                 }
2210                 ext2fs_set_feature_journal(&fs_param);
2211         }
2212
2213         /* Get reserved_ratio from profile if not specified on cmd line. */
2214         if (reserved_ratio < 0.0) {
2215                 reserved_ratio = get_double_from_profile(
2216                                         fs_types, "reserved_ratio", 5.0);
2217                 if (reserved_ratio > 50 || reserved_ratio < 0) {
2218                         com_err(program_name, 0,
2219                                 _("invalid reserved blocks percent - %lf"),
2220                                 reserved_ratio);
2221                         exit(1);
2222                 }
2223         }
2224
2225         if (ext2fs_has_feature_journal_dev(&fs_param)) {
2226                 reserved_ratio = 0;
2227                 fs_param.s_feature_incompat = EXT3_FEATURE_INCOMPAT_JOURNAL_DEV;
2228                 fs_param.s_feature_compat = 0;
2229                 fs_param.s_feature_ro_compat &=
2230                                         EXT4_FEATURE_RO_COMPAT_METADATA_CSUM;
2231         }
2232
2233         /* Check the user's mkfs options for 64bit */
2234         if (ext2fs_has_feature_64bit(&fs_param) &&
2235             !ext2fs_has_feature_extents(&fs_param)) {
2236                 printf("%s", _("Extents MUST be enabled for a 64-bit "
2237                                "filesystem.  Pass -O extents to rectify.\n"));
2238                 exit(1);
2239         }
2240
2241         /* Set first meta blockgroup via an environment variable */
2242         /* (this is mostly for debugging purposes) */
2243         if (ext2fs_has_feature_meta_bg(&fs_param) &&
2244             (tmp = getenv("MKE2FS_FIRST_META_BG")))
2245                 fs_param.s_first_meta_bg = atoi(tmp);
2246         if (ext2fs_has_feature_bigalloc(&fs_param)) {
2247                 if (!cluster_size)
2248                         cluster_size = get_int_from_profile(fs_types,
2249                                                             "cluster_size",
2250                                                             blocksize*16);
2251                 fs_param.s_log_cluster_size =
2252                         int_log2(cluster_size >> EXT2_MIN_CLUSTER_LOG_SIZE);
2253                 if (fs_param.s_log_cluster_size &&
2254                     fs_param.s_log_cluster_size < fs_param.s_log_block_size) {
2255                         com_err(program_name, 0, "%s",
2256                                 _("The cluster size may not be "
2257                                   "smaller than the block size.\n"));
2258                         exit(1);
2259                 }
2260         } else if (cluster_size) {
2261                 com_err(program_name, 0, "%s",
2262                         _("specifying a cluster size requires the "
2263                           "bigalloc feature"));
2264                 exit(1);
2265         } else
2266                 fs_param.s_log_cluster_size = fs_param.s_log_block_size;
2267
2268         if (inode_ratio == 0) {
2269                 inode_ratio = get_int_from_profile(fs_types, "inode_ratio",
2270                                                    8192);
2271                 if (inode_ratio < blocksize)
2272                         inode_ratio = blocksize;
2273                 if (inode_ratio < EXT2_CLUSTER_SIZE(&fs_param))
2274                         inode_ratio = EXT2_CLUSTER_SIZE(&fs_param);
2275         }
2276
2277 #ifdef HAVE_BLKID_PROBE_GET_TOPOLOGY
2278         retval = get_device_geometry(device_name, blocksize,
2279                                      psector_size, &dev_param);
2280         if (retval < 0) {
2281                 fprintf(stderr,
2282                         _("warning: Unable to get device geometry for %s\n"),
2283                         device_name);
2284         } else {
2285                 /* setting stripe/stride to blocksize is pointless */
2286                 if (dev_param.min_io > blocksize)
2287                         fs_param.s_raid_stride = dev_param.min_io / blocksize;
2288                 if (dev_param.opt_io > blocksize) {
2289                         fs_param.s_raid_stripe_width =
2290                                                 dev_param.opt_io / blocksize;
2291                 }
2292
2293                 if (dev_param.alignment_offset) {
2294                         printf(_("%s alignment is offset by %lu bytes.\n"),
2295                                device_name, dev_param.alignment_offset);
2296                         printf(_("This may result in very poor performance, "
2297                                   "(re)-partitioning suggested.\n"));
2298                 }
2299
2300                 if (dev_param.dax && blocksize != sys_page_size) {
2301                         fprintf(stderr,
2302                                 _("%s is capable of DAX but current block size "
2303                                   "%u is different from system page size %u so "
2304                                   "filesystem will not support DAX.\n"),
2305                                 device_name, blocksize, sys_page_size);
2306                 }
2307         }
2308 #endif
2309
2310         num_backups = get_int_from_profile(fs_types, "num_backup_sb", 2);
2311
2312         blocksize = EXT2_BLOCK_SIZE(&fs_param);
2313
2314         /*
2315          * Initialize s_desc_size so that the parse_extended_opts()
2316          * can correctly handle "-E resize=NNN" if the 64-bit option
2317          * is set.
2318          */
2319         if (ext2fs_has_feature_64bit(&fs_param))
2320                 fs_param.s_desc_size = EXT2_MIN_DESC_SIZE_64BIT;
2321
2322         /* This check should happen beyond the last assignment to blocksize */
2323         if (blocksize > sys_page_size) {
2324                 if (!force) {
2325                         com_err(program_name, 0,
2326                                 _("%d-byte blocks too big for system (max %d)"),
2327                                 blocksize, sys_page_size);
2328                         proceed_question(proceed_delay);
2329                 }
2330                 fprintf(stderr, _("Warning: %d-byte blocks too big for system "
2331                                   "(max %d), forced to continue\n"),
2332                         blocksize, sys_page_size);
2333         }
2334
2335         /* Metadata checksumming wasn't totally stable before 3.18. */
2336         if (ext2fs_is_before_linux_ver(3, 18, 0) &&
2337             ext2fs_has_feature_metadata_csum(&fs_param))
2338                 fprintf(stderr, _("Suggestion: Use Linux kernel >= 3.18 for "
2339                         "improved stability of the metadata and journal "
2340                         "checksum features.\n"));
2341
2342         /*
2343          * On newer kernels we do have lazy_itable_init support. So pick the
2344          * right default in case ext4 module is not loaded.
2345          */
2346         if (ext2fs_is_before_linux_ver(2, 6, 37))
2347                 lazy_itable_init = 0;
2348         else
2349                 lazy_itable_init = 1;
2350
2351         if (access("/sys/fs/ext4/features/lazy_itable_init", R_OK) == 0)
2352                 lazy_itable_init = 1;
2353
2354         lazy_itable_init = get_bool_from_profile(fs_types,
2355                                                  "lazy_itable_init",
2356                                                  lazy_itable_init);
2357         discard = get_bool_from_profile(fs_types, "discard" , discard);
2358         journal_flags |= get_bool_from_profile(fs_types,
2359                                                "lazy_journal_init", 0) ?
2360                                                EXT2_MKJOURNAL_LAZYINIT : 0;
2361         journal_flags |= EXT2_MKJOURNAL_NO_MNT_CHECK;
2362
2363         if (!journal_location_string)
2364                 journal_location_string = get_string_from_profile(fs_types,
2365                                                 "journal_location", "");
2366         if ((journal_location == ~0ULL) && journal_location_string &&
2367             *journal_location_string)
2368                 journal_location = parse_num_blocks2(journal_location_string,
2369                                                 fs_param.s_log_block_size);
2370         free(journal_location_string);
2371
2372         packed_meta_blocks = get_bool_from_profile(fs_types,
2373                                                    "packed_meta_blocks", 0);
2374         if (packed_meta_blocks)
2375                 journal_location = 0;
2376
2377         if (ext2fs_has_feature_casefold(&fs_param)) {
2378                 char *ef, *en = get_string_from_profile(fs_types,
2379                                                         "encoding", "utf8");
2380                 int encoding = e2p_str2encoding(en);
2381
2382                 if (encoding < 0) {
2383                         com_err(program_name, 0,
2384                                 _("Unknown filename encoding from profile: %s"),
2385                                 en);
2386                         exit(1);
2387                 }
2388                 free(en);
2389                 fs_param.s_encoding = encoding;
2390                 ef = get_string_from_profile(fs_types, "encoding_flags", NULL);
2391                 if (ef) {
2392                         if (e2p_str2encoding_flags(encoding, ef,
2393                                         &fs_param.s_encoding_flags) < 0) {
2394                                 com_err(program_name, 0,
2395                         _("Unknown encoding flags from profile: %s"), ef);
2396                                 exit(1);
2397                         }
2398                         free(ef);
2399                 } else
2400                         fs_param.s_encoding_flags =
2401                                 e2p_get_encoding_flags(encoding);
2402         }
2403
2404         /* Get options from profile */
2405         for (cpp = fs_types; *cpp; cpp++) {
2406                 tmp = NULL;
2407                 profile_get_string(profile, "fs_types", *cpp, "options", "", &tmp);
2408                         if (tmp && *tmp)
2409                                 parse_extended_opts(&fs_param, tmp);
2410                         free(tmp);
2411         }
2412
2413         if (extended_opts)
2414                 parse_extended_opts(&fs_param, extended_opts);
2415
2416         if (explicit_fssize == 0 && offset > 0) {
2417                 fs_blocks_count -= offset / EXT2_BLOCK_SIZE(&fs_param);
2418                 ext2fs_blocks_count_set(&fs_param, fs_blocks_count);
2419                 fprintf(stderr,
2420                         _("\nWarning: offset specified without an "
2421                           "explicit file system size.\n"
2422                           "Creating a file system with %llu blocks "
2423                           "but this might\n"
2424                           "not be what you want.\n\n"),
2425                         (unsigned long long) fs_blocks_count);
2426         }
2427
2428         if (quotatype_bits & QUOTA_PRJ_BIT)
2429                 ext2fs_set_feature_project(&fs_param);
2430
2431         if (ext2fs_has_feature_project(&fs_param)) {
2432                 quotatype_bits |= QUOTA_PRJ_BIT;
2433                 if (inode_size == EXT2_GOOD_OLD_INODE_SIZE) {
2434                         com_err(program_name, 0,
2435                                 _("%d byte inodes are too small for "
2436                                   "project quota"),
2437                                 inode_size);
2438                         exit(1);
2439                 }
2440                 if (inode_size == 0) {
2441                         inode_size = get_int_from_profile(fs_types,
2442                                                           "inode_size", 0);
2443                         if (inode_size <= EXT2_GOOD_OLD_INODE_SIZE*2)
2444                                 inode_size = EXT2_GOOD_OLD_INODE_SIZE*2;
2445                 }
2446         }
2447
2448         /* Don't allow user to set both metadata_csum and uninit_bg bits. */
2449         if (ext2fs_has_feature_metadata_csum(&fs_param) &&
2450             ext2fs_has_feature_gdt_csum(&fs_param))
2451                 ext2fs_clear_feature_gdt_csum(&fs_param);
2452
2453         /* Can't support bigalloc feature without extents feature */
2454         if (ext2fs_has_feature_bigalloc(&fs_param) &&
2455             !ext2fs_has_feature_extents(&fs_param)) {
2456                 com_err(program_name, 0, "%s",
2457                         _("Can't support bigalloc feature without "
2458                           "extents feature"));
2459                 exit(1);
2460         }
2461
2462         if (ext2fs_has_feature_meta_bg(&fs_param) &&
2463             ext2fs_has_feature_resize_inode(&fs_param)) {
2464                 fprintf(stderr, "%s", _("The resize_inode and meta_bg "
2465                                         "features are not compatible.\n"
2466                                         "They can not be both enabled "
2467                                         "simultaneously.\n"));
2468                 exit(1);
2469         }
2470
2471         if (!quiet && ext2fs_has_feature_bigalloc(&fs_param))
2472                 fprintf(stderr, "%s", _("\nWarning: the bigalloc feature is "
2473                                   "still under development\n"
2474                                   "See https://ext4.wiki.kernel.org/"
2475                                   "index.php/Bigalloc for more information\n\n"));
2476
2477         /*
2478          * Since sparse_super is the default, we would only have a problem
2479          * here if it was explicitly disabled.
2480          */
2481         if (ext2fs_has_feature_resize_inode(&fs_param) &&
2482             !ext2fs_has_feature_sparse_super(&fs_param)) {
2483                 com_err(program_name, 0, "%s",
2484                         _("reserved online resize blocks not supported "
2485                           "on non-sparse filesystem"));
2486                 exit(1);
2487         }
2488
2489         if (fs_param.s_blocks_per_group) {
2490                 if (fs_param.s_blocks_per_group < 256 ||
2491                     fs_param.s_blocks_per_group > 8 * (unsigned) blocksize) {
2492                         com_err(program_name, 0, "%s",
2493                                 _("blocks per group count out of range"));
2494                         exit(1);
2495                 }
2496         }
2497
2498         /*
2499          * If the bigalloc feature is enabled, then the -g option will
2500          * specify the number of clusters per group.
2501          */
2502         if (ext2fs_has_feature_bigalloc(&fs_param)) {
2503                 fs_param.s_clusters_per_group = fs_param.s_blocks_per_group;
2504                 fs_param.s_blocks_per_group = 0;
2505         }
2506
2507         if (inode_size == 0)
2508                 inode_size = get_int_from_profile(fs_types, "inode_size", 0);
2509         if (!flex_bg_size && ext2fs_has_feature_flex_bg(&fs_param))
2510                 flex_bg_size = get_uint_from_profile(fs_types,
2511                                                      "flex_bg_size", 16);
2512         if (flex_bg_size) {
2513                 if (!ext2fs_has_feature_flex_bg(&fs_param)) {
2514                         com_err(program_name, 0, "%s",
2515                                 _("Flex_bg feature not enabled, so "
2516                                   "flex_bg size may not be specified"));
2517                         exit(1);
2518                 }
2519                 fs_param.s_log_groups_per_flex = int_log2(flex_bg_size);
2520         }
2521
2522         if (inode_size && fs_param.s_rev_level >= EXT2_DYNAMIC_REV) {
2523                 if (inode_size < EXT2_GOOD_OLD_INODE_SIZE ||
2524                     inode_size > EXT2_BLOCK_SIZE(&fs_param) ||
2525                     inode_size & (inode_size - 1)) {
2526                         com_err(program_name, 0,
2527                                 _("invalid inode size %d (min %d/max %d)"),
2528                                 inode_size, EXT2_GOOD_OLD_INODE_SIZE,
2529                                 blocksize);
2530                         exit(1);
2531                 }
2532                 fs_param.s_inode_size = inode_size;
2533         }
2534
2535         /*
2536          * If inode size is 128 and inline data is enabled, we need
2537          * to notify users that inline data will never be useful.
2538          */
2539         if (ext2fs_has_feature_inline_data(&fs_param) &&
2540             fs_param.s_inode_size == EXT2_GOOD_OLD_INODE_SIZE) {
2541                 com_err(program_name, 0,
2542                         _("%d byte inodes are too small for inline data; "
2543                           "specify larger size"),
2544                         fs_param.s_inode_size);
2545                 exit(1);
2546         }
2547
2548         /* Make sure number of inodes specified will fit in 32 bits */
2549         if (num_inodes == 0) {
2550                 unsigned long long n;
2551                 n = ext2fs_blocks_count(&fs_param) * blocksize / inode_ratio;
2552                 if (n > MAX_32_NUM) {
2553                         num_inodes = MAX_32_NUM;
2554                         if (!ext2fs_has_feature_64bit(&fs_param))
2555                                 com_err(program_name, 0,
2556                                         _("too many inodes (%llu), reduced to "
2557                                           "%llu"), n, MAX_32_NUM);
2558                 }
2559         } else if (num_inodes > MAX_32_NUM) {
2560                 com_err(program_name, 0,
2561                         _("too many inodes (%llu), specify < 2^32 inodes"),
2562                         (unsigned long long) num_inodes);
2563                 exit(1);
2564         }
2565         /*
2566          * Calculate number of inodes based on the inode ratio
2567          */
2568         fs_param.s_inodes_count = num_inodes ? num_inodes :
2569                 (ext2fs_blocks_count(&fs_param) * blocksize) / inode_ratio;
2570
2571         if ((((unsigned long long)fs_param.s_inodes_count) *
2572              (inode_size ? inode_size : EXT2_GOOD_OLD_INODE_SIZE)) >=
2573             ((ext2fs_blocks_count(&fs_param)) *
2574              EXT2_BLOCK_SIZE(&fs_param))) {
2575                 com_err(program_name, 0, _("inode_size (%u) * inodes_count "
2576                                           "(%u) too big for a\n\t"
2577                                           "filesystem with %llu blocks, "
2578                                           "specify higher inode_ratio (-i)\n\t"
2579                                           "or lower inode count (-N).\n"),
2580                         inode_size ? inode_size : EXT2_GOOD_OLD_INODE_SIZE,
2581                         fs_param.s_inodes_count,
2582                         (unsigned long long) ext2fs_blocks_count(&fs_param));
2583                 exit(1);
2584         }
2585
2586         /*
2587          * Calculate number of blocks to reserve
2588          */
2589         ext2fs_r_blocks_count_set(&fs_param, reserved_ratio *
2590                                   ext2fs_blocks_count(&fs_param) / 100.0);
2591
2592         if (ext2fs_has_feature_sparse_super2(&fs_param)) {
2593                 if (num_backups >= 1)
2594                         fs_param.s_backup_bgs[0] = 1;
2595                 if (num_backups >= 2)
2596                         fs_param.s_backup_bgs[1] = ~0;
2597         }
2598
2599         free(fs_type);
2600         free(usage_types);
2601 }
2602
2603 static int should_do_undo(const char *name)
2604 {
2605         errcode_t retval;
2606         io_channel channel;
2607         __u16   s_magic;
2608         struct ext2_super_block super;
2609         io_manager manager = unix_io_manager;
2610         int csum_flag, force_undo;
2611
2612         csum_flag = ext2fs_has_feature_metadata_csum(&fs_param) ||
2613                     ext2fs_has_feature_gdt_csum(&fs_param);
2614         force_undo = get_int_from_profile(fs_types, "force_undo", 0);
2615         if (!force_undo && (!csum_flag || !lazy_itable_init))
2616                 return 0;
2617
2618         retval = manager->open(name, IO_FLAG_EXCLUSIVE,  &channel);
2619         if (retval) {
2620                 /*
2621                  * We don't handle error cases instead we
2622                  * declare that the file system doesn't exist
2623                  * and let the rest of mke2fs take care of
2624                  * error
2625                  */
2626                 retval = 0;
2627                 goto open_err_out;
2628         }
2629
2630         io_channel_set_blksize(channel, SUPERBLOCK_OFFSET);
2631         retval = io_channel_read_blk64(channel, 1, -SUPERBLOCK_SIZE, &super);
2632         if (retval) {
2633                 retval = 0;
2634                 goto err_out;
2635         }
2636
2637 #if defined(WORDS_BIGENDIAN)
2638         s_magic = ext2fs_swab16(super.s_magic);
2639 #else
2640         s_magic = super.s_magic;
2641 #endif
2642
2643         if (s_magic == EXT2_SUPER_MAGIC)
2644                 retval = 1;
2645
2646 err_out:
2647         io_channel_close(channel);
2648
2649 open_err_out:
2650
2651         return retval;
2652 }
2653
2654 static int mke2fs_setup_tdb(const char *name, io_manager *io_ptr)
2655 {
2656         errcode_t retval = ENOMEM;
2657         char *tdb_dir = NULL, *tdb_file = NULL;
2658         char *dev_name, *tmp_name;
2659         int free_tdb_dir = 0;
2660
2661         /* (re)open a specific undo file */
2662         if (undo_file && undo_file[0] != 0) {
2663                 retval = set_undo_io_backing_manager(*io_ptr);
2664                 if (retval)
2665                         goto err;
2666                 *io_ptr = undo_io_manager;
2667                 retval = set_undo_io_backup_file(undo_file);
2668                 if (retval)
2669                         goto err;
2670                 printf(_("Overwriting existing filesystem; this can be undone "
2671                          "using the command:\n"
2672                          "    e2undo %s %s\n\n"), undo_file, name);
2673                 return retval;
2674         }
2675
2676         /*
2677          * Configuration via a conf file would be
2678          * nice
2679          */
2680         tdb_dir = getenv("E2FSPROGS_UNDO_DIR");
2681         if (!tdb_dir) {
2682                 profile_get_string(profile, "defaults",
2683                                    "undo_dir", 0, "/var/lib/e2fsprogs",
2684                                    &tdb_dir);
2685                 free_tdb_dir = 1;
2686         }
2687
2688         if (!strcmp(tdb_dir, "none") || (tdb_dir[0] == 0) ||
2689             access(tdb_dir, W_OK)) {
2690                 if (free_tdb_dir)
2691                         free(tdb_dir);
2692                 return 0;
2693         }
2694
2695         tmp_name = strdup(name);
2696         if (!tmp_name)
2697                 goto errout;
2698         dev_name = basename(tmp_name);
2699         tdb_file = malloc(strlen(tdb_dir) + 8 + strlen(dev_name) + 7 + 1);
2700         if (!tdb_file) {
2701                 free(tmp_name);
2702                 goto errout;
2703         }
2704         sprintf(tdb_file, "%s/mke2fs-%s.e2undo", tdb_dir, dev_name);
2705         free(tmp_name);
2706
2707         if ((unlink(tdb_file) < 0) && (errno != ENOENT)) {
2708                 retval = errno;
2709                 com_err(program_name, retval,
2710                         _("while trying to delete %s"), tdb_file);
2711                 goto errout;
2712         }
2713
2714         retval = set_undo_io_backing_manager(*io_ptr);
2715         if (retval)
2716                 goto errout;
2717         *io_ptr = undo_io_manager;
2718         retval = set_undo_io_backup_file(tdb_file);
2719         if (retval)
2720                 goto errout;
2721         printf(_("Overwriting existing filesystem; this can be undone "
2722                  "using the command:\n"
2723                  "    e2undo %s %s\n\n"), tdb_file, name);
2724
2725         if (free_tdb_dir)
2726                 free(tdb_dir);
2727         free(tdb_file);
2728         return 0;
2729
2730 errout:
2731         if (free_tdb_dir)
2732                 free(tdb_dir);
2733         free(tdb_file);
2734 err:
2735         com_err(program_name, retval, "%s",
2736                 _("while trying to setup undo file\n"));
2737         return retval;
2738 }
2739
2740 static int mke2fs_discard_device(ext2_filsys fs)
2741 {
2742         struct ext2fs_numeric_progress_struct progress;
2743         blk64_t blocks = ext2fs_blocks_count(fs->super);
2744         blk64_t count = DISCARD_STEP_MB;
2745         blk64_t cur;
2746         int retval = 0;
2747
2748         /*
2749          * Let's try if discard really works on the device, so
2750          * we do not print numeric progress resulting in failure
2751          * afterwards.
2752          */
2753         retval = io_channel_discard(fs->io, 0, fs->blocksize);
2754         if (retval)
2755                 return retval;
2756         cur = fs->blocksize;
2757
2758         count *= (1024 * 1024);
2759         count /= fs->blocksize;
2760
2761         ext2fs_numeric_progress_init(fs, &progress,
2762                                      _("Discarding device blocks: "),
2763                                      blocks);
2764         while (cur < blocks) {
2765                 ext2fs_numeric_progress_update(fs, &progress, cur);
2766
2767                 if (cur + count > blocks)
2768                         count = blocks - cur;
2769
2770                 retval = io_channel_discard(fs->io, cur, count);
2771                 if (retval)
2772                         break;
2773                 cur += count;
2774         }
2775
2776         if (retval) {
2777                 ext2fs_numeric_progress_close(fs, &progress,
2778                                       _("failed - "));
2779                 if (!quiet)
2780                         printf("%s\n",error_message(retval));
2781         } else
2782                 ext2fs_numeric_progress_close(fs, &progress,
2783                                       _("done                            \n"));
2784
2785         return retval;
2786 }
2787
2788 static void fix_cluster_bg_counts(ext2_filsys fs)
2789 {
2790         blk64_t         block, num_blocks, last_block, next;
2791         blk64_t         tot_free = 0;
2792         errcode_t       retval;
2793         dgrp_t          group = 0;
2794         int             grp_free = 0;
2795
2796         num_blocks = ext2fs_blocks_count(fs->super);
2797         last_block = ext2fs_group_last_block2(fs, group);
2798         block = fs->super->s_first_data_block;
2799         while (block < num_blocks) {
2800                 retval = ext2fs_find_first_zero_block_bitmap2(fs->block_map,
2801                                                 block, last_block, &next);
2802                 if (retval == 0)
2803                         block = next;
2804                 else {
2805                         block = last_block + 1;
2806                         goto next_bg;
2807                 }
2808
2809                 retval = ext2fs_find_first_set_block_bitmap2(fs->block_map,
2810                                                 block, last_block, &next);
2811                 if (retval)
2812                         next = last_block + 1;
2813                 grp_free += EXT2FS_NUM_B2C(fs, next - block);
2814                 tot_free += next - block;
2815                 block = next;
2816
2817                 if (block > last_block) {
2818                 next_bg:
2819                         ext2fs_bg_free_blocks_count_set(fs, group, grp_free);
2820                         ext2fs_group_desc_csum_set(fs, group);
2821                         grp_free = 0;
2822                         group++;
2823                         last_block = ext2fs_group_last_block2(fs, group);
2824                 }
2825         }
2826         ext2fs_free_blocks_count_set(fs->super, tot_free);
2827 }
2828
2829 static int create_quota_inodes(ext2_filsys fs)
2830 {
2831         quota_ctx_t qctx;
2832         errcode_t retval;
2833
2834         retval = quota_init_context(&qctx, fs, quotatype_bits);
2835         if (retval) {
2836                 com_err(program_name, retval,
2837                         _("while initializing quota context"));
2838                 exit(1);
2839         }
2840         quota_compute_usage(qctx);
2841         retval = quota_write_inode(qctx, quotatype_bits);
2842         if (retval) {
2843                 com_err(program_name, retval,
2844                         _("while writing quota inodes"));
2845                 exit(1);
2846         }
2847         quota_release_context(&qctx);
2848
2849         return 0;
2850 }
2851
2852 static errcode_t set_error_behavior(ext2_filsys fs)
2853 {
2854         char    *arg = NULL;
2855         short   errors = fs->super->s_errors;
2856
2857         arg = get_string_from_profile(fs_types, "errors", NULL);
2858         if (arg == NULL)
2859                 goto try_user;
2860
2861         if (strcmp(arg, "continue") == 0)
2862                 errors = EXT2_ERRORS_CONTINUE;
2863         else if (strcmp(arg, "remount-ro") == 0)
2864                 errors = EXT2_ERRORS_RO;
2865         else if (strcmp(arg, "panic") == 0)
2866                 errors = EXT2_ERRORS_PANIC;
2867         else {
2868                 com_err(program_name, 0,
2869                         _("bad error behavior in profile - %s"),
2870                         arg);
2871                 free(arg);
2872                 return EXT2_ET_INVALID_ARGUMENT;
2873         }
2874         free(arg);
2875
2876 try_user:
2877         if (errors_behavior)
2878                 errors = errors_behavior;
2879
2880         fs->super->s_errors = errors;
2881         return 0;
2882 }
2883
2884 int main (int argc, char *argv[])
2885 {
2886         errcode_t       retval = 0;
2887         ext2_filsys     fs;
2888         badblocks_list  bb_list = 0;
2889         badblocks_iterate       bb_iter;
2890         blk_t           blk;
2891         struct ext2fs_journal_params    jparams = {0};
2892         unsigned int    i, checkinterval;
2893         int             max_mnt_count;
2894         int             val, hash_alg;
2895         int             flags;
2896         int             old_bitmaps;
2897         io_manager      io_ptr;
2898         char            opt_string[40];
2899         char            *hash_alg_str;
2900         int             itable_zeroed = 0;
2901         blk64_t         overhead;
2902
2903 #ifdef ENABLE_NLS
2904         setlocale(LC_MESSAGES, "");
2905         setlocale(LC_CTYPE, "");
2906         bindtextdomain(NLS_CAT_NAME, LOCALEDIR);
2907         textdomain(NLS_CAT_NAME);
2908         set_com_err_gettext(gettext);
2909 #endif
2910         PRS(argc, argv);
2911
2912 #ifdef CONFIG_TESTIO_DEBUG
2913         if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_BLOCK")) {
2914                 io_ptr = test_io_manager;
2915                 test_io_backing_manager = unix_io_manager;
2916         } else
2917 #endif
2918                 io_ptr = unix_io_manager;
2919
2920         if (undo_file != NULL || should_do_undo(device_name)) {
2921                 retval = mke2fs_setup_tdb(device_name, &io_ptr);
2922                 if (retval)
2923                         exit(1);
2924         }
2925
2926         /*
2927          * Initialize the superblock....
2928          */
2929         flags = EXT2_FLAG_EXCLUSIVE;
2930         if (direct_io)
2931                 flags |= EXT2_FLAG_DIRECT_IO;
2932         profile_get_boolean(profile, "options", "old_bitmaps", 0, 0,
2933                             &old_bitmaps);
2934         if (!old_bitmaps)
2935                 flags |= EXT2_FLAG_64BITS;
2936         /*
2937          * By default, we print how many inode tables or block groups
2938          * or whatever we've written so far.  The quiet flag disables
2939          * this, along with a lot of other output.
2940          */
2941         if (!quiet)
2942                 flags |= EXT2_FLAG_PRINT_PROGRESS;
2943         if (android_sparse_file) {
2944                 char *android_sparse_params = malloc(strlen(device_name) + 48);
2945
2946                 if (!android_sparse_params) {
2947                         com_err(program_name, ENOMEM, "%s",
2948                                 _("in malloc for android_sparse_params"));
2949                         exit(1);
2950                 }
2951                 sprintf(android_sparse_params, "(%s):%u:%u",
2952                          device_name, fs_param.s_blocks_count,
2953                          1024 << fs_param.s_log_block_size);
2954                 retval = ext2fs_initialize(android_sparse_params, flags,
2955                                            &fs_param, sparse_io_manager, &fs);
2956                 free(android_sparse_params);
2957         } else
2958                 retval = ext2fs_initialize(device_name, flags, &fs_param,
2959                                            io_ptr, &fs);
2960         if (retval) {
2961                 com_err(device_name, retval, "%s",
2962                         _("while setting up superblock"));
2963                 exit(1);
2964         }
2965         fs->progress_ops = &ext2fs_numeric_progress_ops;
2966
2967         /* Set the error behavior */
2968         retval = set_error_behavior(fs);
2969         if (retval)
2970                 usage();
2971
2972         /* Check the user's mkfs options for metadata checksumming */
2973         if (!quiet &&
2974             !ext2fs_has_feature_journal_dev(fs->super) &&
2975             ext2fs_has_feature_metadata_csum(fs->super)) {
2976                 if (!ext2fs_has_feature_extents(fs->super))
2977                         printf("%s",
2978                                _("Extents are not enabled.  The file extent "
2979                                  "tree can be checksummed, whereas block maps "
2980                                  "cannot.  Not enabling extents reduces the "
2981                                  "coverage of metadata checksumming.  "
2982                                  "Pass -O extents to rectify.\n"));
2983                 if (!ext2fs_has_feature_64bit(fs->super))
2984                         printf("%s",
2985                                _("64-bit filesystem support is not enabled.  "
2986                                  "The larger fields afforded by this feature "
2987                                  "enable full-strength checksumming.  "
2988                                  "Pass -O 64bit to rectify.\n"));
2989         }
2990
2991         if (ext2fs_has_feature_csum_seed(fs->super) &&
2992             !ext2fs_has_feature_metadata_csum(fs->super)) {
2993                 printf("%s", _("The metadata_csum_seed feature "
2994                                "requires the metadata_csum feature.\n"));
2995                 exit(1);
2996         }
2997
2998         if (ext2fs_has_feature_dirdata(fs->super)) {
2999                 if (ext2fs_has_feature_inline_data(fs->super)) {
3000                         printf("%s", _("The dirdata feature can not enabled "
3001                                        "with inline data feature.\n"));
3002                         exit(1);
3003                 }
3004                 if (ext2fs_has_feature_casefold(fs->super)) {
3005                         printf("%s", _("The dirdata feature can not enabled "
3006                                        "with casefold feature.\n"));
3007                         exit(1);
3008                 }
3009         }
3010
3011         /* Calculate journal blocks */
3012         if (!journal_device && ((journal_size) ||
3013             ext2fs_has_feature_journal(&fs_param)))
3014                 figure_journal_size(&jparams, journal_size, journal_fc_size, fs);
3015
3016         sprintf(opt_string, "tdb_data_size=%d", fs->blocksize <= 4096 ?
3017                 32768 : fs->blocksize * 8);
3018         io_channel_set_options(fs->io, opt_string);
3019         if (offset) {
3020                 sprintf(opt_string, "offset=%llu", (unsigned long long) offset);
3021                 io_channel_set_options(fs->io, opt_string);
3022         }
3023
3024         /* Can't undo discard ... */
3025         if (!noaction && discard && dev_size && (io_ptr != undo_io_manager)) {
3026                 retval = mke2fs_discard_device(fs);
3027                 if (!retval && io_channel_discard_zeroes_data(fs->io)) {
3028                         if (verbose)
3029                                 printf("%s",
3030                                        _("Discard succeeded and will return "
3031                                          "0s - skipping inode table wipe\n"));
3032                         lazy_itable_init = 1;
3033                         itable_zeroed = 1;
3034                         zero_hugefile = 0;
3035                 }
3036         }
3037
3038         if (fs_param.s_flags & EXT2_FLAGS_TEST_FILESYS)
3039                 fs->super->s_flags |= EXT2_FLAGS_TEST_FILESYS;
3040
3041         if (ext2fs_has_feature_flex_bg(&fs_param) ||
3042             ext2fs_has_feature_huge_file(&fs_param) ||
3043             ext2fs_has_feature_gdt_csum(&fs_param) ||
3044             ext2fs_has_feature_dir_nlink(&fs_param) ||
3045             ext2fs_has_feature_metadata_csum(&fs_param) ||
3046             ext2fs_has_feature_extra_isize(&fs_param))
3047                 fs->super->s_kbytes_written = 1;
3048
3049         /*
3050          * Wipe out the old on-disk superblock
3051          */
3052         if (!noaction)
3053                 zap_sector(fs, 2, 6);
3054
3055         /*
3056          * Parse or generate a UUID for the filesystem
3057          */
3058         if (fs_uuid) {
3059                 if ((strcasecmp(fs_uuid, "null") == 0) ||
3060                     (strcasecmp(fs_uuid, "clear") == 0)) {
3061                         uuid_clear(fs->super->s_uuid);
3062                 } else if (strcasecmp(fs_uuid, "time") == 0) {
3063                         uuid_generate_time(fs->super->s_uuid);
3064                 } else if (strcasecmp(fs_uuid, "random") == 0) {
3065                         uuid_generate(fs->super->s_uuid);
3066                 } else if (uuid_parse(fs_uuid, fs->super->s_uuid) != 0) {
3067                         com_err(device_name, 0, "could not parse UUID: %s\n",
3068                                 fs_uuid);
3069                         exit(1);
3070                 }
3071         } else
3072                 uuid_generate(fs->super->s_uuid);
3073
3074         if (ext2fs_has_feature_csum_seed(fs->super))
3075                 fs->super->s_checksum_seed = ext2fs_crc32c_le(~0,
3076                                 fs->super->s_uuid, sizeof(fs->super->s_uuid));
3077
3078         ext2fs_init_csum_seed(fs);
3079
3080         /*
3081          * Initialize the directory index variables
3082          */
3083         hash_alg_str = get_string_from_profile(fs_types, "hash_alg",
3084                                                "half_md4");
3085         hash_alg = e2p_string2hash(hash_alg_str);
3086         free(hash_alg_str);
3087         fs->super->s_def_hash_version = (hash_alg >= 0) ? hash_alg :
3088                 EXT2_HASH_HALF_MD4;
3089
3090         if (memcmp(fs_param.s_hash_seed, zero_buf,
3091                 sizeof(fs_param.s_hash_seed)) != 0) {
3092                 memcpy(fs->super->s_hash_seed, fs_param.s_hash_seed,
3093                         sizeof(fs->super->s_hash_seed));
3094         } else
3095                 uuid_generate((unsigned char *) fs->super->s_hash_seed);
3096
3097         /*
3098          * Periodic checks can be enabled/disabled via config file.
3099          * Note we override the kernel include file's idea of what the default
3100          * check interval (never) should be.  It's a good idea to check at
3101          * least *occasionally*, specially since servers will never rarely get
3102          * to reboot, since Linux is so robust these days.  :-)
3103          *
3104          * 180 days (six months) seems like a good value.
3105          */
3106 #ifdef EXT2_DFL_CHECKINTERVAL
3107 #undef EXT2_DFL_CHECKINTERVAL
3108 #endif
3109 #define EXT2_DFL_CHECKINTERVAL (86400L * 180L)
3110
3111         if (get_bool_from_profile(fs_types, "enable_periodic_fsck", 0)) {
3112                 fs->super->s_checkinterval = EXT2_DFL_CHECKINTERVAL;
3113                 fs->super->s_max_mnt_count = EXT2_DFL_MAX_MNT_COUNT;
3114                 /*
3115                  * Add "jitter" to the superblock's check interval so that we
3116                  * don't check all the filesystems at the same time.  We use a
3117                  * kludgy hack of using the UUID to derive a random jitter value
3118                  */
3119                 for (i = 0, val = 0 ; i < sizeof(fs->super->s_uuid); i++)
3120                         val += fs->super->s_uuid[i];
3121                 fs->super->s_max_mnt_count += val % EXT2_DFL_MAX_MNT_COUNT;
3122         } else
3123                 fs->super->s_max_mnt_count = -1;
3124
3125         /*
3126          * Override the creator OS, if applicable
3127          */
3128         if (creator_os && !set_os(fs->super, creator_os)) {
3129                 com_err (program_name, 0, _("unknown os - %s"), creator_os);
3130                 exit(1);
3131         }
3132
3133         /*
3134          * For the Hurd, we will turn off filetype since it doesn't
3135          * support it.
3136          */
3137         if (fs->super->s_creator_os == EXT2_OS_HURD)
3138                 ext2fs_clear_feature_filetype(fs->super);
3139
3140         /*
3141          * Set the volume label...
3142          */
3143         if (volume_label) {
3144                 memset(fs->super->s_volume_name, 0,
3145                        sizeof(fs->super->s_volume_name));
3146                 strncpy((char *) fs->super->s_volume_name, volume_label,
3147                         sizeof(fs->super->s_volume_name));
3148         }
3149
3150         /*
3151          * Set the last mount directory
3152          */
3153         if (mount_dir) {
3154                 memset(fs->super->s_last_mounted, 0,
3155                        sizeof(fs->super->s_last_mounted));
3156                 strncpy((char *) fs->super->s_last_mounted, mount_dir,
3157                         sizeof(fs->super->s_last_mounted));
3158         }
3159
3160         /* Set current default encryption algorithms for data and
3161          * filename encryption */
3162         if (ext2fs_has_feature_encrypt(fs->super)) {
3163                 fs->super->s_encrypt_algos[0] =
3164                         EXT4_ENCRYPTION_MODE_AES_256_XTS;
3165                 fs->super->s_encrypt_algos[1] =
3166                         EXT4_ENCRYPTION_MODE_AES_256_CTS;
3167         }
3168
3169         if (ext2fs_has_feature_metadata_csum(fs->super))
3170                 fs->super->s_checksum_type = EXT2_CRC32C_CHKSUM;
3171
3172         if (!quiet || noaction)
3173                 show_stats(fs);
3174
3175         if (noaction)
3176                 exit(0);
3177
3178         if (ext2fs_has_feature_journal_dev(fs->super)) {
3179                 create_journal_dev(fs);
3180                 printf("\n");
3181                 exit(ext2fs_close_free(&fs) ? 1 : 0);
3182         }
3183
3184         if (bad_blocks_filename)
3185                 read_bb_file(fs, &bb_list, bad_blocks_filename);
3186         if (cflag)
3187                 test_disk(fs, &bb_list);
3188         handle_bad_blocks(fs, bb_list);
3189
3190         fs->stride = fs_stride = fs->super->s_raid_stride;
3191         if (!quiet)
3192                 printf("%s", _("Allocating group tables: "));
3193         if (ext2fs_has_feature_flex_bg(fs->super) &&
3194             packed_meta_blocks)
3195                 retval = packed_allocate_tables(fs);
3196         else
3197                 retval = ext2fs_allocate_tables(fs);
3198         if (retval) {
3199                 com_err(program_name, retval, "%s",
3200                         _("while trying to allocate filesystem tables"));
3201                 exit(1);
3202         }
3203         if (!quiet)
3204                 printf("%s", _("done                            \n"));
3205
3206         /*
3207          * Unmark bad blocks to calculate overhead, because metadata
3208          * blocks and bad blocks can land on the same allocation cluster.
3209          */
3210         if (bb_list) {
3211                 retval = ext2fs_badblocks_list_iterate_begin(bb_list,
3212                                                              &bb_iter);
3213                 if (retval) {
3214                         com_err("ext2fs_badblocks_list_iterate_begin", retval,
3215                                 "%s", _("while unmarking bad blocks"));
3216                         exit(1);
3217                 }
3218                 while (ext2fs_badblocks_list_iterate(bb_iter, &blk))
3219                         ext2fs_unmark_block_bitmap2(fs->block_map, blk);
3220                 ext2fs_badblocks_list_iterate_end(bb_iter);
3221         }
3222
3223         retval = ext2fs_convert_subcluster_bitmap(fs, &fs->block_map);
3224         if (retval) {
3225                 com_err(program_name, retval, "%s",
3226                         _("\n\twhile converting subcluster bitmap"));
3227                 exit(1);
3228         }
3229
3230         retval = ext2fs_count_used_clusters(fs, fs->super->s_first_data_block,
3231                                         ext2fs_blocks_count(fs->super) - 1,
3232                                         &overhead);
3233         if (retval) {
3234                 com_err(program_name, retval, "%s",
3235                         _("while calculating overhead"));
3236                 exit(1);
3237         }
3238
3239         if (bb_list) {
3240                 retval = ext2fs_badblocks_list_iterate_begin(bb_list,
3241                                                              &bb_iter);
3242                 if (retval) {
3243                         com_err("ext2fs_badblocks_list_iterate_begin", retval,
3244                                 "%s", _("while marking bad blocks as used"));
3245                         exit(1);
3246                 }
3247                 while (ext2fs_badblocks_list_iterate(bb_iter, &blk))
3248                         ext2fs_mark_block_bitmap2(fs->block_map, blk);
3249                 ext2fs_badblocks_list_iterate_end(bb_iter);
3250         }
3251
3252         if (super_only) {
3253                 check_plausibility(device_name, CHECK_FS_EXIST, NULL);
3254                 printf(_("%s may be further corrupted by superblock rewrite\n"),
3255                        device_name);
3256                 if (!force)
3257                         proceed_question(proceed_delay);
3258                 fs->super->s_state |= EXT2_ERROR_FS;
3259                 fs->flags &= ~(EXT2_FLAG_IB_DIRTY|EXT2_FLAG_BB_DIRTY);
3260                 /*
3261                  * The command "mke2fs -S" is used to recover
3262                  * corrupted file systems, so do not mark any of the
3263                  * inodes as unused; we want e2fsck to consider all
3264                  * inodes as potentially containing recoverable data.
3265                  */
3266                 if (ext2fs_has_group_desc_csum(fs)) {
3267                         for (i = 0; i < fs->group_desc_count; i++)
3268                                 ext2fs_bg_itable_unused_set(fs, i, 0);
3269                 }
3270         } else {
3271                 /* rsv must be a power of two (64kB is MD RAID sb alignment) */
3272                 blk64_t rsv = 65536 / fs->blocksize;
3273                 blk64_t blocks = ext2fs_blocks_count(fs->super);
3274                 blk64_t start;
3275                 blk64_t ret_blk;
3276
3277 #ifdef ZAP_BOOTBLOCK
3278                 zap_sector(fs, 0, 2);
3279 #endif
3280
3281                 /*
3282                  * Wipe out any old MD RAID (or other) metadata at the end
3283                  * of the device.  This will also verify that the device is
3284                  * as large as we think.  Be careful with very small devices.
3285                  */
3286                 start = (blocks & ~(rsv - 1));
3287                 if (start > rsv)
3288                         start -= rsv;
3289                 if (start > 0)
3290                         retval = ext2fs_zero_blocks2(fs, start, blocks - start,
3291                                                     &ret_blk, NULL);
3292
3293                 if (retval) {
3294                         com_err(program_name, retval,
3295                                 _("while zeroing block %llu at end of filesystem"),
3296                                 (unsigned long long) ret_blk);
3297                 }
3298                 write_inode_tables(fs, lazy_itable_init, itable_zeroed);
3299                 create_root_dir(fs);
3300                 create_lost_and_found(fs);
3301                 reserve_inodes(fs);
3302                 create_bad_block_inode(fs, bb_list);
3303                 if (ext2fs_has_feature_resize_inode(fs->super)) {
3304                         retval = ext2fs_create_resize_inode(fs);
3305                         if (retval) {
3306                                 com_err("ext2fs_create_resize_inode", retval,
3307                                         "%s",
3308                                 _("while reserving blocks for online resize"));
3309                                 exit(1);
3310                         }
3311                 }
3312         }
3313
3314         if (journal_device) {
3315                 ext2_filsys     jfs;
3316
3317                 if (!check_plausibility(journal_device, CHECK_BLOCK_DEV,
3318                                         NULL) && !force)
3319                         proceed_question(proceed_delay);
3320                 check_mount(journal_device, force, _("journal"));
3321
3322                 retval = ext2fs_open(journal_device, EXT2_FLAG_RW|
3323                                      EXT2_FLAG_JOURNAL_DEV_OK, 0,
3324                                      fs->blocksize, unix_io_manager, &jfs);
3325                 if (retval) {
3326                         com_err(program_name, retval,
3327                                 _("while trying to open journal device %s\n"),
3328                                 journal_device);
3329                         exit(1);
3330                 }
3331                 if (!quiet) {
3332                         printf(_("Adding journal to device %s: "),
3333                                journal_device);
3334                         fflush(stdout);
3335                 }
3336                 retval = ext2fs_add_journal_device(fs, jfs);
3337                 if(retval) {
3338                         com_err (program_name, retval,
3339                                  _("\n\twhile trying to add journal to device %s"),
3340                                  journal_device);
3341                         exit(1);
3342                 }
3343                 if (!quiet)
3344                         printf("%s", _("done\n"));
3345                 ext2fs_close_free(&jfs);
3346                 free(journal_device);
3347         } else if ((journal_size) ||
3348                    ext2fs_has_feature_journal(&fs_param)) {
3349                 overhead += EXT2FS_NUM_B2C(fs, jparams.num_journal_blocks + jparams.num_fc_blocks);
3350                 if (super_only) {
3351                         printf("%s", _("Skipping journal creation in super-only mode\n"));
3352                         fs->super->s_journal_inum = EXT2_JOURNAL_INO;
3353                         goto no_journal;
3354                 }
3355
3356                 if (!jparams.num_journal_blocks) {
3357                         ext2fs_clear_feature_journal(fs->super);
3358                         goto no_journal;
3359                 }
3360                 if (!quiet) {
3361                         printf(_("Creating journal (%u blocks): "),
3362                                jparams.num_journal_blocks + jparams.num_fc_blocks);
3363                         fflush(stdout);
3364                 }
3365                 retval = ext2fs_add_journal_inode3(fs, &jparams,
3366                                                    journal_location,
3367                                                    journal_flags);
3368                 if (retval) {
3369                         com_err(program_name, retval, "%s",
3370                                 _("\n\twhile trying to create journal"));
3371                         exit(1);
3372                 }
3373                 if (!quiet)
3374                         printf("%s", _("done\n"));
3375         }
3376 no_journal:
3377         if (!super_only &&
3378             ext2fs_has_feature_mmp(fs->super)) {
3379                 retval = ext2fs_mmp_init(fs);
3380                 if (retval) {
3381                         fprintf(stderr, "%s",
3382                                 _("\nError while enabling multiple "
3383                                   "mount protection feature."));
3384                         exit(1);
3385                 }
3386                 if (!quiet)
3387                         printf(_("Multiple mount protection is enabled "
3388                                  "with update interval %d seconds.\n"),
3389                                fs->super->s_mmp_update_interval);
3390         }
3391
3392         overhead += fs->super->s_first_data_block;
3393         if (!super_only)
3394                 fs->super->s_overhead_clusters = overhead;
3395
3396         if (ext2fs_has_feature_bigalloc(&fs_param))
3397                 fix_cluster_bg_counts(fs);
3398         if (ext2fs_has_feature_quota(&fs_param))
3399                 create_quota_inodes(fs);
3400
3401         retval = mk_hugefiles(fs, device_name);
3402         if (retval)
3403                 com_err(program_name, retval, "while creating huge files");
3404         /* Copy files from the specified directory */
3405         if (src_root_dir) {
3406                 if (!quiet)
3407                         printf("%s", _("Copying files into the device: "));
3408
3409                 retval = populate_fs(fs, EXT2_ROOT_INO, src_root_dir,
3410                                      EXT2_ROOT_INO);
3411                 if (retval) {
3412                         com_err(program_name, retval, "%s",
3413                                 _("while populating file system"));
3414                         exit(1);
3415                 } else if (!quiet)
3416                         printf("%s", _("done\n"));
3417         }
3418
3419         if (!quiet)
3420                 printf("%s", _("Writing superblocks and "
3421                        "filesystem accounting information: "));
3422         checkinterval = fs->super->s_checkinterval;
3423         max_mnt_count = fs->super->s_max_mnt_count;
3424         retval = ext2fs_close_free(&fs);
3425         if (retval) {
3426                 com_err(program_name, retval, "%s",
3427                         _("while writing out and closing file system"));
3428                 retval = 1;
3429         } else if (!quiet) {
3430                 printf("%s", _("done\n\n"));
3431                 if (!getenv("MKE2FS_SKIP_CHECK_MSG"))
3432                         print_check_message(max_mnt_count, checkinterval);
3433         }
3434
3435         remove_error_table(&et_ext2_error_table);
3436         remove_error_table(&et_prof_error_table);
3437         profile_release(profile);
3438         for (i=0; fs_types[i]; i++)
3439                 free(fs_types[i]);
3440         free(fs_types);
3441         return retval;
3442 }