Whamcloud - gitweb
LU-12158 mke2fs: avoid too large stride and stripe_width
[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 #define OPTIMIZED_STRIPE_WIDTH  512
1439 #define OPTIMIZED_STRIDE        512
1440
1441 #ifdef HAVE_BLKID_PROBE_GET_TOPOLOGY
1442 /*
1443  * Sets the geometry of a device (stripe/stride), and returns the
1444  * device's alignment offset, if any, or a negative error.
1445  */
1446 static int get_device_geometry(const char *file,
1447                                unsigned int blocksize,
1448                                unsigned int psector_size,
1449                                struct device_param *dev_param)
1450 {
1451         int rc = -1;
1452         blkid_probe pr;
1453         blkid_topology tp;
1454         struct stat statbuf;
1455
1456         memset(dev_param, 0, sizeof(*dev_param));
1457
1458         /* Nothing to do for a regular file */
1459         if (!stat(file, &statbuf) && S_ISREG(statbuf.st_mode))
1460                 return 0;
1461
1462         pr = blkid_new_probe_from_filename(file);
1463         if (!pr)
1464                 goto out;
1465
1466         tp = blkid_probe_get_topology(pr);
1467         if (!tp)
1468                 goto out;
1469
1470         dev_param->min_io = blkid_topology_get_minimum_io_size(tp);
1471         if (dev_param->min_io > OPTIMIZED_STRIDE) {
1472                 fprintf(stdout,
1473                         "detected raid stride %lu too large, use optimum %lu\n",
1474                         dev_param->min_io, OPTIMIZED_STRIDE);
1475                 dev_param->min_io = OPTIMIZED_STRIDE;
1476         }
1477         dev_param->opt_io = blkid_topology_get_optimal_io_size(tp);
1478         if (dev_param->opt_io > OPTIMIZED_STRIPE_WIDTH) {
1479                 fprintf(stdout,
1480                         "detected raid stripe width %lu too large, use optimum %lu\n",
1481                         dev_param->opt_io, OPTIMIZED_STRIPE_WIDTH);
1482                 dev_param->opt_io = OPTIMIZED_STRIPE_WIDTH;
1483         }
1484         if ((dev_param->min_io == 0) && (psector_size > blocksize))
1485                 dev_param->min_io = psector_size;
1486         if ((dev_param->opt_io == 0) && dev_param->min_io > 0)
1487                 dev_param->opt_io = dev_param->min_io;
1488         if ((dev_param->opt_io == 0) && (psector_size > blocksize))
1489                 dev_param->opt_io = psector_size;
1490
1491         dev_param->alignment_offset = blkid_topology_get_alignment_offset(tp);
1492 #ifdef HAVE_BLKID_TOPOLOGY_GET_DAX
1493         dev_param->dax = blkid_topology_get_dax(tp);
1494 #endif
1495         rc = 0;
1496 out:
1497         blkid_free_probe(pr);
1498         return rc;
1499 }
1500 #endif
1501
1502 static void PRS(int argc, char *argv[])
1503 {
1504         int             b, c, flags;
1505         int             cluster_size = 0;
1506         char            *tmp, **cpp;
1507         int             explicit_fssize = 0;
1508         int             blocksize = 0;
1509         int             inode_ratio = 0;
1510         int             inode_size = 0;
1511         unsigned long   flex_bg_size = 0;
1512         double          reserved_ratio = -1.0;
1513         int             lsector_size = 0, psector_size = 0;
1514         int             show_version_only = 0, is_device = 0;
1515         unsigned long long num_inodes = 0; /* unsigned long long to catch too-large input */
1516         errcode_t       retval;
1517         char *          oldpath = getenv("PATH");
1518         char *          extended_opts = 0;
1519         char *          fs_type = 0;
1520         char *          usage_types = 0;
1521         /*
1522          * NOTE: A few words about fs_blocks_count and blocksize:
1523          *
1524          * Initially, blocksize is set to zero, which implies 1024.
1525          * If -b is specified, blocksize is updated to the user's value.
1526          *
1527          * Next, the device size or the user's "blocks" command line argument
1528          * is used to set fs_blocks_count; the units are blocksize.
1529          *
1530          * Later, if blocksize hasn't been set and the profile specifies a
1531          * blocksize, then blocksize is updated and fs_blocks_count is scaled
1532          * appropriately.  Note the change in units!
1533          *
1534          * Finally, we complain about fs_blocks_count > 2^32 on a non-64bit fs.
1535          */
1536         blk64_t         fs_blocks_count = 0;
1537         long            sysval;
1538         int             s_opt = -1, r_opt = -1;
1539         char            *fs_features = 0;
1540         int             fs_features_size = 0;
1541         int             use_bsize;
1542         char            *newpath;
1543         int             pathlen = sizeof(PATH_SET) + 1;
1544         struct device_param dev_param;
1545
1546         if (oldpath)
1547                 pathlen += strlen(oldpath);
1548         newpath = malloc(pathlen);
1549         if (!newpath) {
1550                 fprintf(stderr, "%s",
1551                         _("Couldn't allocate memory for new PATH.\n"));
1552                 exit(1);
1553         }
1554         strcpy(newpath, PATH_SET);
1555
1556         /* Update our PATH to include /sbin  */
1557         if (oldpath) {
1558                 strcat (newpath, ":");
1559                 strcat (newpath, oldpath);
1560         }
1561         putenv (newpath);
1562
1563         /* Determine the system page size if possible */
1564 #ifdef HAVE_SYSCONF
1565 #if (!defined(_SC_PAGESIZE) && defined(_SC_PAGE_SIZE))
1566 #define _SC_PAGESIZE _SC_PAGE_SIZE
1567 #endif
1568 #ifdef _SC_PAGESIZE
1569         sysval = sysconf(_SC_PAGESIZE);
1570         if (sysval > 0)
1571                 sys_page_size = sysval;
1572 #endif /* _SC_PAGESIZE */
1573 #endif /* HAVE_SYSCONF */
1574
1575         if ((tmp = getenv("MKE2FS_CONFIG")) != NULL)
1576                 config_fn[0] = tmp;
1577         profile_set_syntax_err_cb(syntax_err_report);
1578         retval = profile_init(config_fn, &profile);
1579         if (retval == ENOENT) {
1580                 retval = profile_init(default_files, &profile);
1581                 if (retval)
1582                         goto profile_error;
1583                 retval = profile_set_default(profile, mke2fs_default_profile);
1584                 if (retval)
1585                         goto profile_error;
1586         } else if (retval) {
1587 profile_error:
1588                 fprintf(stderr, _("Couldn't init profile successfully"
1589                                   " (error: %ld).\n"), retval);
1590                 exit(1);
1591         }
1592
1593         setbuf(stdout, NULL);
1594         setbuf(stderr, NULL);
1595         add_error_table(&et_ext2_error_table);
1596         add_error_table(&et_prof_error_table);
1597         memset(&fs_param, 0, sizeof(struct ext2_super_block));
1598         fs_param.s_rev_level = 1;  /* Create revision 1 filesystems now */
1599
1600         if (ext2fs_is_before_linux_ver(2, 2, 0))
1601                 fs_param.s_rev_level = 0;
1602
1603         if (argc && *argv) {
1604                 program_name = get_progname(*argv);
1605
1606                 /* If called as mkfs.ext3, create a journal inode */
1607                 if (!strcmp(program_name, "mkfs.ext3") ||
1608                     !strcmp(program_name, "mke3fs"))
1609                         journal_size = -1;
1610         }
1611
1612         while ((c = getopt (argc, argv,
1613                     "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) {
1614                 switch (c) {
1615                 case 'b':
1616                         blocksize = parse_num_blocks2(optarg, -1);
1617                         b = (blocksize > 0) ? blocksize : -blocksize;
1618                         if (b < EXT2_MIN_BLOCK_SIZE ||
1619                             b > EXT2_MAX_BLOCK_SIZE) {
1620                                 com_err(program_name, 0,
1621                                         _("invalid block size - %s"), optarg);
1622                                 exit(1);
1623                         }
1624                         if (blocksize > 4096)
1625                                 fprintf(stderr, _("Warning: blocksize %d not "
1626                                                   "usable on most systems.\n"),
1627                                         blocksize);
1628                         if (blocksize > 0)
1629                                 fs_param.s_log_block_size =
1630                                         int_log2(blocksize >>
1631                                                  EXT2_MIN_BLOCK_LOG_SIZE);
1632                         break;
1633                 case 'c':       /* Check for bad blocks */
1634                         cflag++;
1635                         break;
1636                 case 'C':
1637                         cluster_size = parse_num_blocks2(optarg, -1);
1638                         if (cluster_size <= EXT2_MIN_CLUSTER_SIZE ||
1639                             cluster_size > EXT2_MAX_CLUSTER_SIZE) {
1640                                 com_err(program_name, 0,
1641                                         _("invalid cluster size - %s"),
1642                                         optarg);
1643                                 exit(1);
1644                         }
1645                         break;
1646                 case 'd':
1647                         src_root_dir = optarg;
1648                         break;
1649                 case 'D':
1650                         direct_io = 1;
1651                         break;
1652                 case 'R':
1653                         com_err(program_name, 0, "%s",
1654                                 _("'-R' is deprecated, use '-E' instead"));
1655                         /* fallthrough */
1656                 case 'E':
1657                         extended_opts = optarg;
1658                         break;
1659                 case 'e':
1660                         if (strcmp(optarg, "continue") == 0)
1661                                 errors_behavior = EXT2_ERRORS_CONTINUE;
1662                         else if (strcmp(optarg, "remount-ro") == 0)
1663                                 errors_behavior = EXT2_ERRORS_RO;
1664                         else if (strcmp(optarg, "panic") == 0)
1665                                 errors_behavior = EXT2_ERRORS_PANIC;
1666                         else {
1667                                 com_err(program_name, 0,
1668                                         _("bad error behavior - %s"),
1669                                         optarg);
1670                                 usage();
1671                         }
1672                         break;
1673                 case 'F':
1674                         force++;
1675                         break;
1676                 case 'g':
1677                         fs_param.s_blocks_per_group = strtoul(optarg, &tmp, 0);
1678                         if (*tmp) {
1679                                 com_err(program_name, 0, "%s",
1680                                 _("Illegal number for blocks per group"));
1681                                 exit(1);
1682                         }
1683                         if ((fs_param.s_blocks_per_group % 8) != 0) {
1684                                 com_err(program_name, 0, "%s",
1685                                 _("blocks per group must be multiple of 8"));
1686                                 exit(1);
1687                         }
1688                         break;
1689                 case 'G':
1690                         flex_bg_size = strtoul(optarg, &tmp, 0);
1691                         if (*tmp) {
1692                                 com_err(program_name, 0, "%s",
1693                                         _("Illegal number for flex_bg size"));
1694                                 exit(1);
1695                         }
1696                         if (flex_bg_size < 1 ||
1697                             (flex_bg_size & (flex_bg_size-1)) != 0) {
1698                                 com_err(program_name, 0, "%s",
1699                                         _("flex_bg size must be a power of 2"));
1700                                 exit(1);
1701                         }
1702                         if (flex_bg_size > MAX_32_NUM) {
1703                                 com_err(program_name, 0,
1704                                 _("flex_bg size (%lu) must be less than"
1705                                 " or equal to 2^31"), flex_bg_size);
1706                                 exit(1);
1707                         }
1708                         break;
1709                 case 'i':
1710                         inode_ratio = parse_num_blocks(optarg, -1);
1711                         if (inode_ratio < EXT2_MIN_BLOCK_SIZE ||
1712                             inode_ratio > EXT2_MAX_BLOCK_SIZE * 1024) {
1713                                 com_err(program_name, 0,
1714                                         _("invalid inode ratio %s (min %d/max %d)"),
1715                                         optarg, EXT2_MIN_BLOCK_SIZE,
1716                                         EXT2_MAX_BLOCK_SIZE * 1024);
1717                                 exit(1);
1718                         }
1719                         break;
1720                 case 'I':
1721                         inode_size = strtoul(optarg, &tmp, 0);
1722                         if (*tmp) {
1723                                 com_err(program_name, 0,
1724                                         _("invalid inode size - %s"), optarg);
1725                                 exit(1);
1726                         }
1727                         break;
1728                 case 'j':
1729                         if (!journal_size)
1730                                 journal_size = -1;
1731                         if (!journal_fc_size)
1732                                 journal_fc_size = -1;
1733                         break;
1734                 case 'J':
1735                         parse_journal_opts(optarg);
1736                         break;
1737                 case 'K':
1738                         fprintf(stderr, "%s",
1739                                 _("Warning: -K option is deprecated and "
1740                                   "should not be used anymore. Use "
1741                                   "\'-E nodiscard\' extended option "
1742                                   "instead!\n"));
1743                         discard = 0;
1744                         break;
1745                 case 'l':
1746                         bad_blocks_filename = realloc(bad_blocks_filename,
1747                                                       strlen(optarg) + 1);
1748                         if (!bad_blocks_filename) {
1749                                 com_err(program_name, ENOMEM, "%s",
1750                                         _("in malloc for bad_blocks_filename"));
1751                                 exit(1);
1752                         }
1753                         strcpy(bad_blocks_filename, optarg);
1754                         break;
1755                 case 'L':
1756                         volume_label = optarg;
1757                         if (strlen(volume_label) > EXT2_LABEL_LEN) {
1758                                 volume_label[EXT2_LABEL_LEN] = '\0';
1759                                 fprintf(stderr, _("Warning: label too long; will be truncated to '%s'\n\n"),
1760                                         volume_label);
1761                         }
1762                         break;
1763                 case 'm':
1764                         reserved_ratio = strtod(optarg, &tmp);
1765                         if ( *tmp || reserved_ratio > 50 ||
1766                              reserved_ratio < 0) {
1767                                 com_err(program_name, 0,
1768                                         _("invalid reserved blocks percent - %s"),
1769                                         optarg);
1770                                 exit(1);
1771                         }
1772                         break;
1773                 case 'M':
1774                         mount_dir = optarg;
1775                         break;
1776                 case 'n':
1777                         noaction++;
1778                         break;
1779                 case 'N':
1780                         num_inodes = strtoul(optarg, &tmp, 0);
1781                         if (*tmp) {
1782                                 com_err(program_name, 0,
1783                                         _("bad num inodes - %s"), optarg);
1784                                         exit(1);
1785                         }
1786                         break;
1787                 case 'o':
1788                         creator_os = optarg;
1789                         break;
1790                 case 'O':
1791                         retval = ext2fs_resize_mem(fs_features_size,
1792                                    fs_features_size + 1 + strlen(optarg),
1793                                                    &fs_features);
1794                         if (retval) {
1795                                 com_err(program_name, retval,
1796                                      _("while allocating fs_feature string"));
1797                                 exit(1);
1798                         }
1799                         if (fs_features_size)
1800                                 strcat(fs_features, ",");
1801                         else
1802                                 fs_features[0] = 0;
1803                         strcat(fs_features, optarg);
1804                         fs_features_size += 1 + strlen(optarg);
1805                         break;
1806                 case 'q':
1807                         quiet = 1;
1808                         break;
1809                 case 'r':
1810                         r_opt = strtoul(optarg, &tmp, 0);
1811                         if (*tmp) {
1812                                 com_err(program_name, 0,
1813                                         _("bad revision level - %s"), optarg);
1814                                 exit(1);
1815                         }
1816                         if (r_opt > EXT2_MAX_SUPP_REV) {
1817                                 com_err(program_name, EXT2_ET_REV_TOO_HIGH,
1818                                         _("while trying to create revision %d"), r_opt);
1819                                 exit(1);
1820                         }
1821                         fs_param.s_rev_level = r_opt;
1822                         break;
1823                 case 's':       /* deprecated */
1824                         s_opt = atoi(optarg);
1825                         break;
1826                 case 'S':
1827                         super_only = 1;
1828                         break;
1829                 case 't':
1830                         if (fs_type) {
1831                                 com_err(program_name, 0, "%s",
1832                                     _("The -t option may only be used once"));
1833                                 exit(1);
1834                         }
1835                         fs_type = strdup(optarg);
1836                         break;
1837                 case 'T':
1838                         if (usage_types) {
1839                                 com_err(program_name, 0, "%s",
1840                                     _("The -T option may only be used once"));
1841                                 exit(1);
1842                         }
1843                         usage_types = strdup(optarg);
1844                         break;
1845                 case 'U':
1846                         fs_uuid = optarg;
1847                         break;
1848                 case 'v':
1849                         verbose = 1;
1850                         break;
1851                 case 'V':
1852                         /* Print version number and exit */
1853                         show_version_only++;
1854                         break;
1855                 case 'z':
1856                         undo_file = optarg;
1857                         break;
1858                 default:
1859                         usage();
1860                 }
1861         }
1862         if ((optind == argc) && !show_version_only)
1863                 usage();
1864         device_name = argv[optind++];
1865
1866         if (!quiet || show_version_only)
1867                 fprintf (stderr, "mke2fs %s (%s)\n", E2FSPROGS_VERSION,
1868                          E2FSPROGS_DATE);
1869
1870         if (show_version_only) {
1871                 fprintf(stderr, _("\tUsing %s\n"),
1872                         error_message(EXT2_ET_BASE));
1873                 exit(0);
1874         }
1875
1876         /*
1877          * If there's no blocksize specified and there is a journal
1878          * device, use it to figure out the blocksize
1879          */
1880         if (blocksize <= 0 && journal_device) {
1881                 ext2_filsys     jfs;
1882                 io_manager      io_ptr;
1883
1884 #ifdef CONFIG_TESTIO_DEBUG
1885                 if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_BLOCK")) {
1886                         io_ptr = test_io_manager;
1887                         test_io_backing_manager = unix_io_manager;
1888                 } else
1889 #endif
1890                         io_ptr = unix_io_manager;
1891                 retval = ext2fs_open(journal_device,
1892                                      EXT2_FLAG_JOURNAL_DEV_OK, 0,
1893                                      0, io_ptr, &jfs);
1894                 if (retval) {
1895                         com_err(program_name, retval,
1896                                 _("while trying to open journal device %s\n"),
1897                                 journal_device);
1898                         exit(1);
1899                 }
1900                 if ((blocksize < 0) && (jfs->blocksize < (unsigned) (-blocksize))) {
1901                         com_err(program_name, 0,
1902                                 _("Journal dev blocksize (%d) smaller than "
1903                                   "minimum blocksize %d\n"), jfs->blocksize,
1904                                 -blocksize);
1905                         exit(1);
1906                 }
1907                 blocksize = jfs->blocksize;
1908                 printf(_("Using journal device's blocksize: %d\n"), blocksize);
1909                 fs_param.s_log_block_size =
1910                         int_log2(blocksize >> EXT2_MIN_BLOCK_LOG_SIZE);
1911                 ext2fs_close_free(&jfs);
1912         }
1913
1914         if (optind < argc) {
1915                 fs_blocks_count = parse_num_blocks2(argv[optind++],
1916                                                    fs_param.s_log_block_size);
1917                 if (!fs_blocks_count) {
1918                         com_err(program_name, 0,
1919                                 _("invalid blocks '%s' on device '%s'"),
1920                                 argv[optind - 1], device_name);
1921                         exit(1);
1922                 }
1923         }
1924         if (optind < argc)
1925                 usage();
1926
1927         profile_get_integer(profile, "options", "sync_kludge", 0, 0,
1928                             &sync_kludge);
1929         tmp = getenv("MKE2FS_SYNC");
1930         if (tmp)
1931                 sync_kludge = atoi(tmp);
1932
1933         profile_get_integer(profile, "options", "proceed_delay", 0, 0,
1934                             &proceed_delay);
1935
1936         /* The isatty() test is so we don't break existing scripts */
1937         flags = CREATE_FILE;
1938         if (isatty(0) && isatty(1) && !offset)
1939                 flags |= CHECK_FS_EXIST;
1940         if (!quiet)
1941                 flags |= VERBOSE_CREATE;
1942         if (fs_blocks_count == 0)
1943                 flags |= NO_SIZE;
1944         else
1945                 explicit_fssize = 1;
1946         if (!check_plausibility(device_name, flags, &is_device) && !force)
1947                 proceed_question(proceed_delay);
1948
1949         check_mount(device_name, force, _("filesystem"));
1950
1951         /* Determine the size of the device (if possible) */
1952         if (noaction && fs_blocks_count) {
1953                 dev_size = fs_blocks_count;
1954                 retval = 0;
1955         } else
1956 #ifndef _WIN32
1957                 retval = ext2fs_get_device_size2(device_name,
1958                                                  EXT2_BLOCK_SIZE(&fs_param),
1959                                                  &dev_size);
1960 #else
1961                 retval = ext2fs_get_device_size(device_name,
1962                                                 EXT2_BLOCK_SIZE(&fs_param),
1963                                                 &dev_size);
1964 #endif
1965         if (retval && (retval != EXT2_ET_UNIMPLEMENTED)) {
1966                 com_err(program_name, retval, "%s",
1967                         _("while trying to determine filesystem size"));
1968                 exit(1);
1969         }
1970         if (!fs_blocks_count) {
1971                 if (retval == EXT2_ET_UNIMPLEMENTED) {
1972                         com_err(program_name, 0, "%s",
1973                                 _("Couldn't determine device size; you "
1974                                 "must specify\nthe size of the "
1975                                 "filesystem\n"));
1976                         exit(1);
1977                 } else {
1978                         if (dev_size == 0) {
1979                                 com_err(program_name, 0, "%s",
1980                                 _("Device size reported to be zero.  "
1981                                   "Invalid partition specified, or\n\t"
1982                                   "partition table wasn't reread "
1983                                   "after running fdisk, due to\n\t"
1984                                   "a modified partition being busy "
1985                                   "and in use.  You may need to reboot\n\t"
1986                                   "to re-read your partition table.\n"
1987                                   ));
1988                                 exit(1);
1989                         }
1990                         fs_blocks_count = dev_size;
1991                         if (sys_page_size > EXT2_BLOCK_SIZE(&fs_param))
1992                                 fs_blocks_count &= ~((blk64_t) ((sys_page_size /
1993                                              EXT2_BLOCK_SIZE(&fs_param))-1));
1994                 }
1995         } else if (!force && is_device && (fs_blocks_count > dev_size)) {
1996                 com_err(program_name, 0, "%s",
1997                         _("Filesystem larger than apparent device size."));
1998                 proceed_question(proceed_delay);
1999         }
2000
2001         if (!fs_type)
2002                 profile_get_string(profile, "devices", device_name,
2003                                    "fs_type", 0, &fs_type);
2004         if (!usage_types)
2005                 profile_get_string(profile, "devices", device_name,
2006                                    "usage_types", 0, &usage_types);
2007
2008         /*
2009          * We have the file system (or device) size, so we can now
2010          * determine the appropriate file system types so the fs can
2011          * be appropriately configured.
2012          */
2013         fs_types = parse_fs_type(fs_type, usage_types, &fs_param,
2014                                  fs_blocks_count, argv[0]);
2015         if (!fs_types) {
2016                 fprintf(stderr, "%s", _("Failed to parse fs types list\n"));
2017                 exit(1);
2018         }
2019
2020         /* Figure out what features should be enabled */
2021
2022         tmp = NULL;
2023         if (fs_param.s_rev_level != EXT2_GOOD_OLD_REV) {
2024                 tmp = get_string_from_profile(fs_types, "base_features",
2025                       "sparse_super,large_file,filetype,resize_inode,dir_index");
2026                 edit_feature(tmp, &fs_param.s_feature_compat);
2027                 free(tmp);
2028
2029                 /* And which mount options as well */
2030                 tmp = get_string_from_profile(fs_types, "default_mntopts",
2031                                               "acl,user_xattr");
2032                 edit_mntopts(tmp, &fs_param.s_default_mount_opts);
2033                 if (tmp)
2034                         free(tmp);
2035
2036                 for (cpp = fs_types; *cpp; cpp++) {
2037                         tmp = NULL;
2038                         profile_get_string(profile, "fs_types", *cpp,
2039                                            "features", "", &tmp);
2040                         if (tmp && *tmp)
2041                                 edit_feature(tmp, &fs_param.s_feature_compat);
2042                         if (tmp)
2043                                 free(tmp);
2044                 }
2045                 tmp = get_string_from_profile(fs_types, "default_features",
2046                                               "");
2047         }
2048         /* Mask off features which aren't supported by the Hurd */
2049         if (for_hurd(creator_os)) {
2050                 ext2fs_clear_feature_filetype(&fs_param);
2051                 ext2fs_clear_feature_huge_file(&fs_param);
2052                 ext2fs_clear_feature_metadata_csum(&fs_param);
2053                 ext2fs_clear_feature_ea_inode(&fs_param);
2054                 ext2fs_clear_feature_casefold(&fs_param);
2055         }
2056         edit_feature(fs_features ? fs_features : tmp,
2057                      &fs_param.s_feature_compat);
2058         if (tmp)
2059                 free(tmp);
2060         (void) ext2fs_free_mem(&fs_features);
2061         /*
2062          * If the user specified features incompatible with the Hurd, complain
2063          */
2064         if (for_hurd(creator_os)) {
2065                 if (ext2fs_has_feature_filetype(&fs_param)) {
2066                         fprintf(stderr, "%s", _("The HURD does not support the "
2067                                                 "filetype feature.\n"));
2068                         exit(1);
2069                 }
2070                 if (ext2fs_has_feature_huge_file(&fs_param)) {
2071                         fprintf(stderr, "%s", _("The HURD does not support the "
2072                                                 "huge_file feature.\n"));
2073                         exit(1);
2074                 }
2075                 if (ext2fs_has_feature_metadata_csum(&fs_param)) {
2076                         fprintf(stderr, "%s", _("The HURD does not support the "
2077                                                 "metadata_csum feature.\n"));
2078                         exit(1);
2079                 }
2080                 if (ext2fs_has_feature_ea_inode(&fs_param)) {
2081                         fprintf(stderr, "%s", _("The HURD does not support the "
2082                                                 "ea_inode feature.\n"));
2083                         exit(1);
2084                 }
2085         }
2086
2087         /* Get the hardware sector sizes, if available */
2088         retval = ext2fs_get_device_sectsize(device_name, &lsector_size);
2089         if (retval) {
2090                 com_err(program_name, retval, "%s",
2091                         _("while trying to determine hardware sector size"));
2092                 exit(1);
2093         }
2094         retval = ext2fs_get_device_phys_sectsize(device_name, &psector_size);
2095         if (retval) {
2096                 com_err(program_name, retval, "%s",
2097                         _("while trying to determine physical sector size"));
2098                 exit(1);
2099         }
2100
2101         tmp = getenv("MKE2FS_DEVICE_SECTSIZE");
2102         if (tmp != NULL)
2103                 lsector_size = atoi(tmp);
2104         tmp = getenv("MKE2FS_DEVICE_PHYS_SECTSIZE");
2105         if (tmp != NULL)
2106                 psector_size = atoi(tmp);
2107
2108         /* Older kernels may not have physical/logical distinction */
2109         if (!psector_size)
2110                 psector_size = lsector_size;
2111
2112         if (blocksize <= 0) {
2113                 use_bsize = get_int_from_profile(fs_types, "blocksize", 4096);
2114
2115                 if (use_bsize == -1) {
2116                         use_bsize = sys_page_size;
2117                         if (ext2fs_is_before_linux_ver(2, 6, 0) &&
2118                             use_bsize > 4096)
2119                                 use_bsize = 4096;
2120                 }
2121                 if (lsector_size && use_bsize < lsector_size)
2122                         use_bsize = lsector_size;
2123                 if ((blocksize < 0) && (use_bsize < (-blocksize)))
2124                         use_bsize = -blocksize;
2125                 blocksize = use_bsize;
2126                 fs_blocks_count /= (blocksize / 1024);
2127         } else {
2128                 if (blocksize < lsector_size) {                 /* Impossible */
2129                         com_err(program_name, EINVAL, "%s",
2130                                 _("while setting blocksize; too small "
2131                                   "for device\n"));
2132                         exit(1);
2133                 } else if ((blocksize < psector_size) &&
2134                            (psector_size <= sys_page_size)) {   /* Suboptimal */
2135                         fprintf(stderr, _("Warning: specified blocksize %d is "
2136                                 "less than device physical sectorsize %d\n"),
2137                                 blocksize, psector_size);
2138                 }
2139         }
2140
2141         fs_param.s_log_block_size =
2142                 int_log2(blocksize >> EXT2_MIN_BLOCK_LOG_SIZE);
2143
2144         /*
2145          * We now need to do a sanity check of fs_blocks_count for
2146          * 32-bit vs 64-bit block number support.
2147          */
2148         if (fs_blocks_count > MAX_32_NUM) {
2149                 if (!ext2fs_has_feature_64bit(&fs_param) &&
2150                     get_bool_from_profile(fs_types, "auto_64-bit_support", 0))
2151                         ext2fs_set_feature_64bit(&fs_param);
2152
2153                 if (ext2fs_has_feature_64bit(&fs_param)) {
2154                         ext2fs_clear_feature_resize_inode(&fs_param);
2155                 } else {
2156                         fprintf(stderr,
2157                                 _("%s: Size of device (0x%llx blocks) %s "
2158                                   "too big to be expressed\n\t"
2159                                   "in 32 bits using a blocksize of %d.\n"),
2160                                 program_name,
2161                                 (unsigned long long) fs_blocks_count,
2162                                 device_name, EXT2_BLOCK_SIZE(&fs_param));
2163                         exit(1);
2164                 }
2165         }
2166
2167         /*
2168          * Guard against group descriptor count overflowing... Mostly to avoid
2169          * strange results for absurdly large devices.  This is in log2:
2170          * (blocksize) * (bits per byte) * (maximum number of block groups)
2171          */
2172         if (fs_blocks_count >
2173             (1ULL << (EXT2_BLOCK_SIZE_BITS(&fs_param) + 3 + 32)) - 1) {
2174                 fprintf(stderr, _("%s: Size of device (0x%llx blocks) %s "
2175                                   "too big to create\n\t"
2176                                   "a filesystem using a blocksize of %d.\n"),
2177                         program_name, (unsigned long long) fs_blocks_count,
2178                         device_name, EXT2_BLOCK_SIZE(&fs_param));
2179                 exit(1);
2180         }
2181
2182         ext2fs_blocks_count_set(&fs_param, fs_blocks_count);
2183
2184         if (ext2fs_has_feature_journal_dev(&fs_param)) {
2185                 int i;
2186
2187                 for (i=0; fs_types[i]; i++) {
2188                         free(fs_types[i]);
2189                         fs_types[i] = 0;
2190                 }
2191                 fs_types[0] = strdup("journal");
2192                 fs_types[1] = 0;
2193         }
2194
2195         if (verbose) {
2196                 fputs(_("fs_types for mke2fs.conf resolution: "), stdout);
2197                 print_str_list(fs_types);
2198         }
2199
2200         if (r_opt == EXT2_GOOD_OLD_REV &&
2201             (fs_param.s_feature_compat || fs_param.s_feature_incompat ||
2202              fs_param.s_feature_ro_compat)) {
2203                 fprintf(stderr, "%s", _("Filesystem features not supported "
2204                                         "with revision 0 filesystems\n"));
2205                 exit(1);
2206         }
2207
2208         if (s_opt > 0) {
2209                 if (r_opt == EXT2_GOOD_OLD_REV) {
2210                         fprintf(stderr, "%s",
2211                                 _("Sparse superblocks not supported "
2212                                   "with revision 0 filesystems\n"));
2213                         exit(1);
2214                 }
2215                 ext2fs_set_feature_sparse_super(&fs_param);
2216         } else if (s_opt == 0)
2217                 ext2fs_clear_feature_sparse_super(&fs_param);
2218
2219         if (journal_size != 0) {
2220                 if (r_opt == EXT2_GOOD_OLD_REV) {
2221                         fprintf(stderr, "%s", _("Journals not supported with "
2222                                                 "revision 0 filesystems\n"));
2223                         exit(1);
2224                 }
2225                 ext2fs_set_feature_journal(&fs_param);
2226         }
2227
2228         /* Get reserved_ratio from profile if not specified on cmd line. */
2229         if (reserved_ratio < 0.0) {
2230                 reserved_ratio = get_double_from_profile(
2231                                         fs_types, "reserved_ratio", 5.0);
2232                 if (reserved_ratio > 50 || reserved_ratio < 0) {
2233                         com_err(program_name, 0,
2234                                 _("invalid reserved blocks percent - %lf"),
2235                                 reserved_ratio);
2236                         exit(1);
2237                 }
2238         }
2239
2240         if (ext2fs_has_feature_journal_dev(&fs_param)) {
2241                 reserved_ratio = 0;
2242                 fs_param.s_feature_incompat = EXT3_FEATURE_INCOMPAT_JOURNAL_DEV;
2243                 fs_param.s_feature_compat = 0;
2244                 fs_param.s_feature_ro_compat &=
2245                                         EXT4_FEATURE_RO_COMPAT_METADATA_CSUM;
2246         }
2247
2248         /* Check the user's mkfs options for 64bit */
2249         if (fs_blocks_count > MAX_32_NUM &&
2250             !ext2fs_has_feature_extents(&fs_param)) {
2251                 printf("%s", _("Extents MUST be enabled for filesystems with "
2252                                "over 2^32 blocks. Use '-O extents' to fix.\n"));
2253                 exit(1);
2254         }
2255
2256         /* Set first meta blockgroup via an environment variable */
2257         /* (this is mostly for debugging purposes) */
2258         if (ext2fs_has_feature_meta_bg(&fs_param) &&
2259             (tmp = getenv("MKE2FS_FIRST_META_BG")))
2260                 fs_param.s_first_meta_bg = atoi(tmp);
2261         if (ext2fs_has_feature_bigalloc(&fs_param)) {
2262                 if (!cluster_size)
2263                         cluster_size = get_int_from_profile(fs_types,
2264                                                             "cluster_size",
2265                                                             blocksize*16);
2266                 fs_param.s_log_cluster_size =
2267                         int_log2(cluster_size >> EXT2_MIN_CLUSTER_LOG_SIZE);
2268                 if (fs_param.s_log_cluster_size &&
2269                     fs_param.s_log_cluster_size < fs_param.s_log_block_size) {
2270                         com_err(program_name, 0, "%s",
2271                                 _("The cluster size may not be "
2272                                   "smaller than the block size.\n"));
2273                         exit(1);
2274                 }
2275         } else if (cluster_size) {
2276                 com_err(program_name, 0, "%s",
2277                         _("specifying a cluster size requires the "
2278                           "bigalloc feature"));
2279                 exit(1);
2280         } else
2281                 fs_param.s_log_cluster_size = fs_param.s_log_block_size;
2282
2283         if (inode_ratio == 0) {
2284                 inode_ratio = get_int_from_profile(fs_types, "inode_ratio",
2285                                                    8192);
2286                 if (inode_ratio < blocksize)
2287                         inode_ratio = blocksize;
2288                 if (inode_ratio < EXT2_CLUSTER_SIZE(&fs_param))
2289                         inode_ratio = EXT2_CLUSTER_SIZE(&fs_param);
2290         }
2291
2292 #ifdef HAVE_BLKID_PROBE_GET_TOPOLOGY
2293         retval = get_device_geometry(device_name, blocksize,
2294                                      psector_size, &dev_param);
2295         if (retval < 0) {
2296                 fprintf(stderr,
2297                         _("warning: Unable to get device geometry for %s\n"),
2298                         device_name);
2299         } else {
2300                 /* setting stripe/stride to blocksize is pointless */
2301                 if (dev_param.min_io > blocksize)
2302                         fs_param.s_raid_stride = dev_param.min_io / blocksize;
2303                 if (dev_param.opt_io > blocksize) {
2304                         fs_param.s_raid_stripe_width =
2305                                                 dev_param.opt_io / blocksize;
2306                 }
2307
2308                 if (dev_param.alignment_offset) {
2309                         printf(_("%s alignment is offset by %lu bytes.\n"),
2310                                device_name, dev_param.alignment_offset);
2311                         printf(_("This may result in very poor performance, "
2312                                   "(re)-partitioning suggested.\n"));
2313                 }
2314
2315                 if (dev_param.dax && blocksize != sys_page_size) {
2316                         fprintf(stderr,
2317                                 _("%s is capable of DAX but current block size "
2318                                   "%u is different from system page size %u so "
2319                                   "filesystem will not support DAX.\n"),
2320                                 device_name, blocksize, sys_page_size);
2321                 }
2322         }
2323 #endif
2324
2325         num_backups = get_int_from_profile(fs_types, "num_backup_sb", 2);
2326
2327         blocksize = EXT2_BLOCK_SIZE(&fs_param);
2328
2329         /*
2330          * Initialize s_desc_size so that the parse_extended_opts()
2331          * can correctly handle "-E resize=NNN" if the 64-bit option
2332          * is set.
2333          */
2334         if (ext2fs_has_feature_64bit(&fs_param))
2335                 fs_param.s_desc_size = EXT2_MIN_DESC_SIZE_64BIT;
2336
2337         /* This check should happen beyond the last assignment to blocksize */
2338         if (blocksize > sys_page_size) {
2339                 if (!force) {
2340                         com_err(program_name, 0,
2341                                 _("%d-byte blocks too big for system (max %d)"),
2342                                 blocksize, sys_page_size);
2343                         proceed_question(proceed_delay);
2344                 }
2345                 fprintf(stderr, _("Warning: %d-byte blocks too big for system "
2346                                   "(max %d), forced to continue\n"),
2347                         blocksize, sys_page_size);
2348         }
2349
2350         /* Metadata checksumming wasn't totally stable before 3.18. */
2351         if (ext2fs_is_before_linux_ver(3, 18, 0) &&
2352             ext2fs_has_feature_metadata_csum(&fs_param))
2353                 fprintf(stderr, _("Suggestion: Use Linux kernel >= 3.18 for "
2354                         "improved stability of the metadata and journal "
2355                         "checksum features.\n"));
2356
2357         /*
2358          * On newer kernels we do have lazy_itable_init support. So pick the
2359          * right default in case ext4 module is not loaded.
2360          */
2361         if (ext2fs_is_before_linux_ver(2, 6, 37))
2362                 lazy_itable_init = 0;
2363         else
2364                 lazy_itable_init = 1;
2365
2366         if (access("/sys/fs/ext4/features/lazy_itable_init", R_OK) == 0)
2367                 lazy_itable_init = 1;
2368
2369         lazy_itable_init = get_bool_from_profile(fs_types,
2370                                                  "lazy_itable_init",
2371                                                  lazy_itable_init);
2372         discard = get_bool_from_profile(fs_types, "discard" , discard);
2373         journal_flags |= get_bool_from_profile(fs_types,
2374                                                "lazy_journal_init", 0) ?
2375                                                EXT2_MKJOURNAL_LAZYINIT : 0;
2376         journal_flags |= EXT2_MKJOURNAL_NO_MNT_CHECK;
2377
2378         if (!journal_location_string)
2379                 journal_location_string = get_string_from_profile(fs_types,
2380                                                 "journal_location", "");
2381         if ((journal_location == ~0ULL) && journal_location_string &&
2382             *journal_location_string)
2383                 journal_location = parse_num_blocks2(journal_location_string,
2384                                                 fs_param.s_log_block_size);
2385         free(journal_location_string);
2386
2387         packed_meta_blocks = get_bool_from_profile(fs_types,
2388                                                    "packed_meta_blocks", 0);
2389         if (packed_meta_blocks)
2390                 journal_location = 0;
2391
2392         if (ext2fs_has_feature_casefold(&fs_param)) {
2393                 char *ef, *en = get_string_from_profile(fs_types,
2394                                                         "encoding", "utf8");
2395                 int encoding = e2p_str2encoding(en);
2396
2397                 if (encoding < 0) {
2398                         com_err(program_name, 0,
2399                                 _("Unknown filename encoding from profile: %s"),
2400                                 en);
2401                         exit(1);
2402                 }
2403                 free(en);
2404                 fs_param.s_encoding = encoding;
2405                 ef = get_string_from_profile(fs_types, "encoding_flags", NULL);
2406                 if (ef) {
2407                         if (e2p_str2encoding_flags(encoding, ef,
2408                                         &fs_param.s_encoding_flags) < 0) {
2409                                 com_err(program_name, 0,
2410                         _("Unknown encoding flags from profile: %s"), ef);
2411                                 exit(1);
2412                         }
2413                         free(ef);
2414                 } else
2415                         fs_param.s_encoding_flags =
2416                                 e2p_get_encoding_flags(encoding);
2417         }
2418
2419         /* Get options from profile */
2420         for (cpp = fs_types; *cpp; cpp++) {
2421                 tmp = NULL;
2422                 profile_get_string(profile, "fs_types", *cpp, "options", "", &tmp);
2423                         if (tmp && *tmp)
2424                                 parse_extended_opts(&fs_param, tmp);
2425                         free(tmp);
2426         }
2427
2428         if (extended_opts)
2429                 parse_extended_opts(&fs_param, extended_opts);
2430
2431         if (explicit_fssize == 0 && offset > 0) {
2432                 fs_blocks_count -= offset / EXT2_BLOCK_SIZE(&fs_param);
2433                 ext2fs_blocks_count_set(&fs_param, fs_blocks_count);
2434                 fprintf(stderr,
2435                         _("\nWarning: offset specified without an "
2436                           "explicit file system size.\n"
2437                           "Creating a file system with %llu blocks "
2438                           "but this might\n"
2439                           "not be what you want.\n\n"),
2440                         (unsigned long long) fs_blocks_count);
2441         }
2442
2443         if (quotatype_bits & QUOTA_PRJ_BIT)
2444                 ext2fs_set_feature_project(&fs_param);
2445
2446         if (ext2fs_has_feature_project(&fs_param)) {
2447                 quotatype_bits |= QUOTA_PRJ_BIT;
2448                 if (inode_size == EXT2_GOOD_OLD_INODE_SIZE) {
2449                         com_err(program_name, 0,
2450                                 _("%d byte inodes are too small for "
2451                                   "project quota"),
2452                                 inode_size);
2453                         exit(1);
2454                 }
2455                 if (inode_size == 0) {
2456                         inode_size = get_int_from_profile(fs_types,
2457                                                           "inode_size", 0);
2458                         if (inode_size <= EXT2_GOOD_OLD_INODE_SIZE*2)
2459                                 inode_size = EXT2_GOOD_OLD_INODE_SIZE*2;
2460                 }
2461         }
2462
2463         /* Don't allow user to set both metadata_csum and uninit_bg bits. */
2464         if (ext2fs_has_feature_metadata_csum(&fs_param) &&
2465             ext2fs_has_feature_gdt_csum(&fs_param))
2466                 ext2fs_clear_feature_gdt_csum(&fs_param);
2467
2468         /* Can't support bigalloc feature without extents feature */
2469         if (ext2fs_has_feature_bigalloc(&fs_param) &&
2470             !ext2fs_has_feature_extents(&fs_param)) {
2471                 com_err(program_name, 0, "%s",
2472                         _("Can't support bigalloc feature without "
2473                           "extents feature"));
2474                 exit(1);
2475         }
2476
2477         if (ext2fs_has_feature_meta_bg(&fs_param) &&
2478             ext2fs_has_feature_resize_inode(&fs_param)) {
2479                 fprintf(stderr, "%s", _("The resize_inode and meta_bg "
2480                                         "features are not compatible.\n"
2481                                         "They can not be both enabled "
2482                                         "simultaneously.\n"));
2483                 exit(1);
2484         }
2485
2486         if (!quiet && ext2fs_has_feature_bigalloc(&fs_param))
2487                 fprintf(stderr, "%s", _("\nWarning: the bigalloc feature is "
2488                                   "still under development\n"
2489                                   "See https://ext4.wiki.kernel.org/"
2490                                   "index.php/Bigalloc for more information\n\n"));
2491
2492         /*
2493          * Since sparse_super is the default, we would only have a problem
2494          * here if it was explicitly disabled.
2495          */
2496         if (ext2fs_has_feature_resize_inode(&fs_param) &&
2497             !ext2fs_has_feature_sparse_super(&fs_param)) {
2498                 com_err(program_name, 0, "%s",
2499                         _("reserved online resize blocks not supported "
2500                           "on non-sparse filesystem"));
2501                 exit(1);
2502         }
2503
2504         if (fs_param.s_blocks_per_group) {
2505                 if (fs_param.s_blocks_per_group < 256 ||
2506                     fs_param.s_blocks_per_group > 8 * (unsigned) blocksize) {
2507                         com_err(program_name, 0, "%s",
2508                                 _("blocks per group count out of range"));
2509                         exit(1);
2510                 }
2511         }
2512
2513         /*
2514          * If the bigalloc feature is enabled, then the -g option will
2515          * specify the number of clusters per group.
2516          */
2517         if (ext2fs_has_feature_bigalloc(&fs_param)) {
2518                 fs_param.s_clusters_per_group = fs_param.s_blocks_per_group;
2519                 fs_param.s_blocks_per_group = 0;
2520         }
2521
2522         if (inode_size == 0)
2523                 inode_size = get_int_from_profile(fs_types, "inode_size", 0);
2524         if (!flex_bg_size && ext2fs_has_feature_flex_bg(&fs_param))
2525                 flex_bg_size = get_uint_from_profile(fs_types,
2526                                                      "flex_bg_size", 16);
2527         if (flex_bg_size) {
2528                 if (!ext2fs_has_feature_flex_bg(&fs_param)) {
2529                         com_err(program_name, 0, "%s",
2530                                 _("Flex_bg feature not enabled, so "
2531                                   "flex_bg size may not be specified"));
2532                         exit(1);
2533                 }
2534                 fs_param.s_log_groups_per_flex = int_log2(flex_bg_size);
2535         }
2536
2537         if (inode_size && fs_param.s_rev_level >= EXT2_DYNAMIC_REV) {
2538                 if (inode_size < EXT2_GOOD_OLD_INODE_SIZE ||
2539                     inode_size > EXT2_BLOCK_SIZE(&fs_param) ||
2540                     inode_size & (inode_size - 1)) {
2541                         com_err(program_name, 0,
2542                                 _("invalid inode size %d (min %d/max %d)"),
2543                                 inode_size, EXT2_GOOD_OLD_INODE_SIZE,
2544                                 blocksize);
2545                         exit(1);
2546                 }
2547                 fs_param.s_inode_size = inode_size;
2548         }
2549
2550         /*
2551          * If inode size is 128 and inline data is enabled, we need
2552          * to notify users that inline data will never be useful.
2553          */
2554         if (ext2fs_has_feature_inline_data(&fs_param) &&
2555             fs_param.s_inode_size == EXT2_GOOD_OLD_INODE_SIZE) {
2556                 com_err(program_name, 0,
2557                         _("%d byte inodes are too small for inline data; "
2558                           "specify larger size"),
2559                         fs_param.s_inode_size);
2560                 exit(1);
2561         }
2562
2563         /* Make sure number of inodes specified will fit in 32 bits */
2564         if (num_inodes == 0) {
2565                 unsigned long long n;
2566                 n = ext2fs_blocks_count(&fs_param) * blocksize / inode_ratio;
2567                 if (n > MAX_32_NUM) {
2568                         num_inodes = MAX_32_NUM;
2569                         if (!ext2fs_has_feature_64bit(&fs_param))
2570                                 com_err(program_name, 0,
2571                                         _("too many inodes (%llu), reduced to "
2572                                           "%llu"), n, MAX_32_NUM);
2573                 }
2574         } else if (num_inodes > MAX_32_NUM) {
2575                 com_err(program_name, 0,
2576                         _("too many inodes (%llu), specify < 2^32 inodes"),
2577                         (unsigned long long) num_inodes);
2578                 exit(1);
2579         }
2580         /*
2581          * Calculate number of inodes based on the inode ratio
2582          */
2583         fs_param.s_inodes_count = num_inodes ? num_inodes :
2584                 (ext2fs_blocks_count(&fs_param) * blocksize) / inode_ratio;
2585
2586         if ((((unsigned long long)fs_param.s_inodes_count) *
2587              (inode_size ? inode_size : EXT2_GOOD_OLD_INODE_SIZE)) >=
2588             ((ext2fs_blocks_count(&fs_param)) *
2589              EXT2_BLOCK_SIZE(&fs_param))) {
2590                 com_err(program_name, 0, _("inode_size (%u) * inodes_count "
2591                                           "(%u) too big for a\n\t"
2592                                           "filesystem with %llu blocks, "
2593                                           "specify higher inode_ratio (-i)\n\t"
2594                                           "or lower inode count (-N).\n"),
2595                         inode_size ? inode_size : EXT2_GOOD_OLD_INODE_SIZE,
2596                         fs_param.s_inodes_count,
2597                         (unsigned long long) ext2fs_blocks_count(&fs_param));
2598                 exit(1);
2599         }
2600
2601         /*
2602          * Calculate number of blocks to reserve
2603          */
2604         ext2fs_r_blocks_count_set(&fs_param, reserved_ratio *
2605                                   ext2fs_blocks_count(&fs_param) / 100.0);
2606
2607         if (ext2fs_has_feature_sparse_super2(&fs_param)) {
2608                 if (num_backups >= 1)
2609                         fs_param.s_backup_bgs[0] = 1;
2610                 if (num_backups >= 2)
2611                         fs_param.s_backup_bgs[1] = ~0;
2612         }
2613
2614         free(fs_type);
2615         free(usage_types);
2616 }
2617
2618 static int should_do_undo(const char *name)
2619 {
2620         errcode_t retval;
2621         io_channel channel;
2622         __u16   s_magic;
2623         struct ext2_super_block super;
2624         io_manager manager = unix_io_manager;
2625         int csum_flag, force_undo;
2626
2627         csum_flag = ext2fs_has_feature_metadata_csum(&fs_param) ||
2628                     ext2fs_has_feature_gdt_csum(&fs_param);
2629         force_undo = get_int_from_profile(fs_types, "force_undo", 0);
2630         if (!force_undo && (!csum_flag || !lazy_itable_init))
2631                 return 0;
2632
2633         retval = manager->open(name, IO_FLAG_EXCLUSIVE,  &channel);
2634         if (retval) {
2635                 /*
2636                  * We don't handle error cases instead we
2637                  * declare that the file system doesn't exist
2638                  * and let the rest of mke2fs take care of
2639                  * error
2640                  */
2641                 retval = 0;
2642                 goto open_err_out;
2643         }
2644
2645         io_channel_set_blksize(channel, SUPERBLOCK_OFFSET);
2646         retval = io_channel_read_blk64(channel, 1, -SUPERBLOCK_SIZE, &super);
2647         if (retval) {
2648                 retval = 0;
2649                 goto err_out;
2650         }
2651
2652 #if defined(WORDS_BIGENDIAN)
2653         s_magic = ext2fs_swab16(super.s_magic);
2654 #else
2655         s_magic = super.s_magic;
2656 #endif
2657
2658         if (s_magic == EXT2_SUPER_MAGIC)
2659                 retval = 1;
2660
2661 err_out:
2662         io_channel_close(channel);
2663
2664 open_err_out:
2665
2666         return retval;
2667 }
2668
2669 static int mke2fs_setup_tdb(const char *name, io_manager *io_ptr)
2670 {
2671         errcode_t retval = ENOMEM;
2672         char *tdb_dir = NULL, *tdb_file = NULL;
2673         char *dev_name, *tmp_name;
2674         int free_tdb_dir = 0;
2675
2676         /* (re)open a specific undo file */
2677         if (undo_file && undo_file[0] != 0) {
2678                 retval = set_undo_io_backing_manager(*io_ptr);
2679                 if (retval)
2680                         goto err;
2681                 *io_ptr = undo_io_manager;
2682                 retval = set_undo_io_backup_file(undo_file);
2683                 if (retval)
2684                         goto err;
2685                 printf(_("Overwriting existing filesystem; this can be undone "
2686                          "using the command:\n"
2687                          "    e2undo %s %s\n\n"), undo_file, name);
2688                 return retval;
2689         }
2690
2691         /*
2692          * Configuration via a conf file would be
2693          * nice
2694          */
2695         tdb_dir = getenv("E2FSPROGS_UNDO_DIR");
2696         if (!tdb_dir) {
2697                 profile_get_string(profile, "defaults",
2698                                    "undo_dir", 0, "/var/lib/e2fsprogs",
2699                                    &tdb_dir);
2700                 free_tdb_dir = 1;
2701         }
2702
2703         if (!strcmp(tdb_dir, "none") || (tdb_dir[0] == 0) ||
2704             access(tdb_dir, W_OK)) {
2705                 if (free_tdb_dir)
2706                         free(tdb_dir);
2707                 return 0;
2708         }
2709
2710         tmp_name = strdup(name);
2711         if (!tmp_name)
2712                 goto errout;
2713         dev_name = basename(tmp_name);
2714         tdb_file = malloc(strlen(tdb_dir) + 8 + strlen(dev_name) + 7 + 1);
2715         if (!tdb_file) {
2716                 free(tmp_name);
2717                 goto errout;
2718         }
2719         sprintf(tdb_file, "%s/mke2fs-%s.e2undo", tdb_dir, dev_name);
2720         free(tmp_name);
2721
2722         if ((unlink(tdb_file) < 0) && (errno != ENOENT)) {
2723                 retval = errno;
2724                 com_err(program_name, retval,
2725                         _("while trying to delete %s"), tdb_file);
2726                 goto errout;
2727         }
2728
2729         retval = set_undo_io_backing_manager(*io_ptr);
2730         if (retval)
2731                 goto errout;
2732         *io_ptr = undo_io_manager;
2733         retval = set_undo_io_backup_file(tdb_file);
2734         if (retval)
2735                 goto errout;
2736         printf(_("Overwriting existing filesystem; this can be undone "
2737                  "using the command:\n"
2738                  "    e2undo %s %s\n\n"), tdb_file, name);
2739
2740         if (free_tdb_dir)
2741                 free(tdb_dir);
2742         free(tdb_file);
2743         return 0;
2744
2745 errout:
2746         if (free_tdb_dir)
2747                 free(tdb_dir);
2748         free(tdb_file);
2749 err:
2750         com_err(program_name, retval, "%s",
2751                 _("while trying to setup undo file\n"));
2752         return retval;
2753 }
2754
2755 static int mke2fs_discard_device(ext2_filsys fs)
2756 {
2757         struct ext2fs_numeric_progress_struct progress;
2758         blk64_t blocks = ext2fs_blocks_count(fs->super);
2759         blk64_t count = DISCARD_STEP_MB;
2760         blk64_t cur;
2761         int retval = 0;
2762
2763         /*
2764          * Let's try if discard really works on the device, so
2765          * we do not print numeric progress resulting in failure
2766          * afterwards.
2767          */
2768         retval = io_channel_discard(fs->io, 0, fs->blocksize);
2769         if (retval)
2770                 return retval;
2771         cur = fs->blocksize;
2772
2773         count *= (1024 * 1024);
2774         count /= fs->blocksize;
2775
2776         ext2fs_numeric_progress_init(fs, &progress,
2777                                      _("Discarding device blocks: "),
2778                                      blocks);
2779         while (cur < blocks) {
2780                 ext2fs_numeric_progress_update(fs, &progress, cur);
2781
2782                 if (cur + count > blocks)
2783                         count = blocks - cur;
2784
2785                 retval = io_channel_discard(fs->io, cur, count);
2786                 if (retval)
2787                         break;
2788                 cur += count;
2789         }
2790
2791         if (retval) {
2792                 ext2fs_numeric_progress_close(fs, &progress,
2793                                       _("failed - "));
2794                 if (!quiet)
2795                         printf("%s\n",error_message(retval));
2796         } else
2797                 ext2fs_numeric_progress_close(fs, &progress,
2798                                       _("done                            \n"));
2799
2800         return retval;
2801 }
2802
2803 static void fix_cluster_bg_counts(ext2_filsys fs)
2804 {
2805         blk64_t         block, num_blocks, last_block, next;
2806         blk64_t         tot_free = 0;
2807         errcode_t       retval;
2808         dgrp_t          group = 0;
2809         int             grp_free = 0;
2810
2811         num_blocks = ext2fs_blocks_count(fs->super);
2812         last_block = ext2fs_group_last_block2(fs, group);
2813         block = fs->super->s_first_data_block;
2814         while (block < num_blocks) {
2815                 retval = ext2fs_find_first_zero_block_bitmap2(fs->block_map,
2816                                                 block, last_block, &next);
2817                 if (retval == 0)
2818                         block = next;
2819                 else {
2820                         block = last_block + 1;
2821                         goto next_bg;
2822                 }
2823
2824                 retval = ext2fs_find_first_set_block_bitmap2(fs->block_map,
2825                                                 block, last_block, &next);
2826                 if (retval)
2827                         next = last_block + 1;
2828                 grp_free += EXT2FS_NUM_B2C(fs, next - block);
2829                 tot_free += next - block;
2830                 block = next;
2831
2832                 if (block > last_block) {
2833                 next_bg:
2834                         ext2fs_bg_free_blocks_count_set(fs, group, grp_free);
2835                         ext2fs_group_desc_csum_set(fs, group);
2836                         grp_free = 0;
2837                         group++;
2838                         last_block = ext2fs_group_last_block2(fs, group);
2839                 }
2840         }
2841         ext2fs_free_blocks_count_set(fs->super, tot_free);
2842 }
2843
2844 static int create_quota_inodes(ext2_filsys fs)
2845 {
2846         quota_ctx_t qctx;
2847         errcode_t retval;
2848
2849         retval = quota_init_context(&qctx, fs, quotatype_bits);
2850         if (retval) {
2851                 com_err(program_name, retval,
2852                         _("while initializing quota context"));
2853                 exit(1);
2854         }
2855         quota_compute_usage(qctx);
2856         retval = quota_write_inode(qctx, quotatype_bits);
2857         if (retval) {
2858                 com_err(program_name, retval,
2859                         _("while writing quota inodes"));
2860                 exit(1);
2861         }
2862         quota_release_context(&qctx);
2863
2864         return 0;
2865 }
2866
2867 static errcode_t set_error_behavior(ext2_filsys fs)
2868 {
2869         char    *arg = NULL;
2870         short   errors = fs->super->s_errors;
2871
2872         arg = get_string_from_profile(fs_types, "errors", NULL);
2873         if (arg == NULL)
2874                 goto try_user;
2875
2876         if (strcmp(arg, "continue") == 0)
2877                 errors = EXT2_ERRORS_CONTINUE;
2878         else if (strcmp(arg, "remount-ro") == 0)
2879                 errors = EXT2_ERRORS_RO;
2880         else if (strcmp(arg, "panic") == 0)
2881                 errors = EXT2_ERRORS_PANIC;
2882         else {
2883                 com_err(program_name, 0,
2884                         _("bad error behavior in profile - %s"),
2885                         arg);
2886                 free(arg);
2887                 return EXT2_ET_INVALID_ARGUMENT;
2888         }
2889         free(arg);
2890
2891 try_user:
2892         if (errors_behavior)
2893                 errors = errors_behavior;
2894
2895         fs->super->s_errors = errors;
2896         return 0;
2897 }
2898
2899 int main (int argc, char *argv[])
2900 {
2901         errcode_t       retval = 0;
2902         ext2_filsys     fs;
2903         badblocks_list  bb_list = 0;
2904         badblocks_iterate       bb_iter;
2905         blk_t           blk;
2906         struct ext2fs_journal_params    jparams = {0};
2907         unsigned int    i, checkinterval;
2908         int             max_mnt_count;
2909         int             val, hash_alg;
2910         int             flags;
2911         int             old_bitmaps;
2912         io_manager      io_ptr;
2913         char            opt_string[40];
2914         char            *hash_alg_str;
2915         int             itable_zeroed = 0;
2916         blk64_t         overhead;
2917
2918 #ifdef ENABLE_NLS
2919         setlocale(LC_MESSAGES, "");
2920         setlocale(LC_CTYPE, "");
2921         bindtextdomain(NLS_CAT_NAME, LOCALEDIR);
2922         textdomain(NLS_CAT_NAME);
2923         set_com_err_gettext(gettext);
2924 #endif
2925         PRS(argc, argv);
2926
2927 #ifdef CONFIG_TESTIO_DEBUG
2928         if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_BLOCK")) {
2929                 io_ptr = test_io_manager;
2930                 test_io_backing_manager = unix_io_manager;
2931         } else
2932 #endif
2933                 io_ptr = unix_io_manager;
2934
2935         if (undo_file != NULL || should_do_undo(device_name)) {
2936                 retval = mke2fs_setup_tdb(device_name, &io_ptr);
2937                 if (retval)
2938                         exit(1);
2939         }
2940
2941         /*
2942          * Initialize the superblock....
2943          */
2944         flags = EXT2_FLAG_EXCLUSIVE;
2945         if (direct_io)
2946                 flags |= EXT2_FLAG_DIRECT_IO;
2947         profile_get_boolean(profile, "options", "old_bitmaps", 0, 0,
2948                             &old_bitmaps);
2949         if (!old_bitmaps)
2950                 flags |= EXT2_FLAG_64BITS;
2951         /*
2952          * By default, we print how many inode tables or block groups
2953          * or whatever we've written so far.  The quiet flag disables
2954          * this, along with a lot of other output.
2955          */
2956         if (!quiet)
2957                 flags |= EXT2_FLAG_PRINT_PROGRESS;
2958         if (android_sparse_file) {
2959                 char *android_sparse_params = malloc(strlen(device_name) + 48);
2960
2961                 if (!android_sparse_params) {
2962                         com_err(program_name, ENOMEM, "%s",
2963                                 _("in malloc for android_sparse_params"));
2964                         exit(1);
2965                 }
2966                 sprintf(android_sparse_params, "(%s):%u:%u",
2967                          device_name, fs_param.s_blocks_count,
2968                          1024 << fs_param.s_log_block_size);
2969                 retval = ext2fs_initialize(android_sparse_params, flags,
2970                                            &fs_param, sparse_io_manager, &fs);
2971                 free(android_sparse_params);
2972         } else
2973                 retval = ext2fs_initialize(device_name, flags, &fs_param,
2974                                            io_ptr, &fs);
2975         if (retval) {
2976                 com_err(device_name, retval, "%s",
2977                         _("while setting up superblock"));
2978                 exit(1);
2979         }
2980         fs->progress_ops = &ext2fs_numeric_progress_ops;
2981
2982         /* Set the error behavior */
2983         retval = set_error_behavior(fs);
2984         if (retval)
2985                 usage();
2986
2987         /* Check the user's mkfs options for metadata checksumming */
2988         if (!quiet &&
2989             !ext2fs_has_feature_journal_dev(fs->super) &&
2990             ext2fs_has_feature_metadata_csum(fs->super)) {
2991                 if (!ext2fs_has_feature_extents(fs->super))
2992                         printf("%s",
2993                                _("Extents are not enabled.  The file extent "
2994                                  "tree can be checksummed, whereas block maps "
2995                                  "cannot.  Not enabling extents reduces the "
2996                                  "coverage of metadata checksumming.  "
2997                                  "Pass -O extents to rectify.\n"));
2998                 if (!ext2fs_has_feature_64bit(fs->super))
2999                         printf("%s",
3000                                _("64-bit filesystem support is not enabled.  "
3001                                  "The larger fields afforded by this feature "
3002                                  "enable full-strength checksumming.  "
3003                                  "Pass -O 64bit to rectify.\n"));
3004         }
3005
3006         if (ext2fs_has_feature_csum_seed(fs->super) &&
3007             !ext2fs_has_feature_metadata_csum(fs->super)) {
3008                 printf("%s", _("The metadata_csum_seed feature "
3009                                "requires the metadata_csum feature.\n"));
3010                 exit(1);
3011         }
3012
3013         if (ext2fs_has_feature_dirdata(fs->super)) {
3014                 if (ext2fs_has_feature_inline_data(fs->super)) {
3015                         printf("%s", _("The dirdata feature can not enabled "
3016                                        "with inline data feature.\n"));
3017                         exit(1);
3018                 }
3019                 if (ext2fs_has_feature_casefold(fs->super)) {
3020                         printf("%s", _("The dirdata feature can not enabled "
3021                                        "with casefold feature.\n"));
3022                         exit(1);
3023                 }
3024         }
3025
3026         /* Calculate journal blocks */
3027         if (!journal_device && ((journal_size) ||
3028             ext2fs_has_feature_journal(&fs_param)))
3029                 figure_journal_size(&jparams, journal_size, journal_fc_size, fs);
3030
3031         sprintf(opt_string, "tdb_data_size=%d", fs->blocksize <= 4096 ?
3032                 32768 : fs->blocksize * 8);
3033         io_channel_set_options(fs->io, opt_string);
3034         if (offset) {
3035                 sprintf(opt_string, "offset=%llu", (unsigned long long) offset);
3036                 io_channel_set_options(fs->io, opt_string);
3037         }
3038
3039         /* Can't undo discard ... */
3040         if (!noaction && discard && dev_size && (io_ptr != undo_io_manager)) {
3041                 retval = mke2fs_discard_device(fs);
3042                 if (!retval && io_channel_discard_zeroes_data(fs->io)) {
3043                         if (verbose)
3044                                 printf("%s",
3045                                        _("Discard succeeded and will return "
3046                                          "0s - skipping inode table wipe\n"));
3047                         lazy_itable_init = 1;
3048                         itable_zeroed = 1;
3049                         zero_hugefile = 0;
3050                 }
3051         }
3052
3053         if (fs_param.s_flags & EXT2_FLAGS_TEST_FILESYS)
3054                 fs->super->s_flags |= EXT2_FLAGS_TEST_FILESYS;
3055
3056         if (ext2fs_has_feature_flex_bg(&fs_param) ||
3057             ext2fs_has_feature_huge_file(&fs_param) ||
3058             ext2fs_has_feature_gdt_csum(&fs_param) ||
3059             ext2fs_has_feature_dir_nlink(&fs_param) ||
3060             ext2fs_has_feature_metadata_csum(&fs_param) ||
3061             ext2fs_has_feature_extra_isize(&fs_param))
3062                 fs->super->s_kbytes_written = 1;
3063
3064         /*
3065          * Wipe out the old on-disk superblock
3066          */
3067         if (!noaction)
3068                 zap_sector(fs, 2, 6);
3069
3070         /*
3071          * Parse or generate a UUID for the filesystem
3072          */
3073         if (fs_uuid) {
3074                 if ((strcasecmp(fs_uuid, "null") == 0) ||
3075                     (strcasecmp(fs_uuid, "clear") == 0)) {
3076                         uuid_clear(fs->super->s_uuid);
3077                 } else if (strcasecmp(fs_uuid, "time") == 0) {
3078                         uuid_generate_time(fs->super->s_uuid);
3079                 } else if (strcasecmp(fs_uuid, "random") == 0) {
3080                         uuid_generate(fs->super->s_uuid);
3081                 } else if (uuid_parse(fs_uuid, fs->super->s_uuid) != 0) {
3082                         com_err(device_name, 0, "could not parse UUID: %s\n",
3083                                 fs_uuid);
3084                         exit(1);
3085                 }
3086         } else
3087                 uuid_generate(fs->super->s_uuid);
3088
3089         if (ext2fs_has_feature_csum_seed(fs->super))
3090                 fs->super->s_checksum_seed = ext2fs_crc32c_le(~0,
3091                                 fs->super->s_uuid, sizeof(fs->super->s_uuid));
3092
3093         ext2fs_init_csum_seed(fs);
3094
3095         /*
3096          * Initialize the directory index variables
3097          */
3098         hash_alg_str = get_string_from_profile(fs_types, "hash_alg",
3099                                                "half_md4");
3100         hash_alg = e2p_string2hash(hash_alg_str);
3101         free(hash_alg_str);
3102         fs->super->s_def_hash_version = (hash_alg >= 0) ? hash_alg :
3103                 EXT2_HASH_HALF_MD4;
3104
3105         if (memcmp(fs_param.s_hash_seed, zero_buf,
3106                 sizeof(fs_param.s_hash_seed)) != 0) {
3107                 memcpy(fs->super->s_hash_seed, fs_param.s_hash_seed,
3108                         sizeof(fs->super->s_hash_seed));
3109         } else
3110                 uuid_generate((unsigned char *) fs->super->s_hash_seed);
3111
3112         /*
3113          * Periodic checks can be enabled/disabled via config file.
3114          * Note we override the kernel include file's idea of what the default
3115          * check interval (never) should be.  It's a good idea to check at
3116          * least *occasionally*, specially since servers will never rarely get
3117          * to reboot, since Linux is so robust these days.  :-)
3118          *
3119          * 180 days (six months) seems like a good value.
3120          */
3121 #ifdef EXT2_DFL_CHECKINTERVAL
3122 #undef EXT2_DFL_CHECKINTERVAL
3123 #endif
3124 #define EXT2_DFL_CHECKINTERVAL (86400L * 180L)
3125
3126         if (get_bool_from_profile(fs_types, "enable_periodic_fsck", 0)) {
3127                 fs->super->s_checkinterval = EXT2_DFL_CHECKINTERVAL;
3128                 fs->super->s_max_mnt_count = EXT2_DFL_MAX_MNT_COUNT;
3129                 /*
3130                  * Add "jitter" to the superblock's check interval so that we
3131                  * don't check all the filesystems at the same time.  We use a
3132                  * kludgy hack of using the UUID to derive a random jitter value
3133                  */
3134                 for (i = 0, val = 0 ; i < sizeof(fs->super->s_uuid); i++)
3135                         val += fs->super->s_uuid[i];
3136                 fs->super->s_max_mnt_count += val % EXT2_DFL_MAX_MNT_COUNT;
3137         } else
3138                 fs->super->s_max_mnt_count = -1;
3139
3140         /*
3141          * Override the creator OS, if applicable
3142          */
3143         if (creator_os && !set_os(fs->super, creator_os)) {
3144                 com_err (program_name, 0, _("unknown os - %s"), creator_os);
3145                 exit(1);
3146         }
3147
3148         /*
3149          * For the Hurd, we will turn off filetype since it doesn't
3150          * support it.
3151          */
3152         if (fs->super->s_creator_os == EXT2_OS_HURD)
3153                 ext2fs_clear_feature_filetype(fs->super);
3154
3155         /*
3156          * Set the volume label...
3157          */
3158         if (volume_label) {
3159                 memset(fs->super->s_volume_name, 0,
3160                        sizeof(fs->super->s_volume_name));
3161                 strncpy((char *) fs->super->s_volume_name, volume_label,
3162                         sizeof(fs->super->s_volume_name));
3163         }
3164
3165         /*
3166          * Set the last mount directory
3167          */
3168         if (mount_dir) {
3169                 memset(fs->super->s_last_mounted, 0,
3170                        sizeof(fs->super->s_last_mounted));
3171                 strncpy((char *) fs->super->s_last_mounted, mount_dir,
3172                         sizeof(fs->super->s_last_mounted));
3173         }
3174
3175         /* Set current default encryption algorithms for data and
3176          * filename encryption */
3177         if (ext2fs_has_feature_encrypt(fs->super)) {
3178                 fs->super->s_encrypt_algos[0] =
3179                         EXT4_ENCRYPTION_MODE_AES_256_XTS;
3180                 fs->super->s_encrypt_algos[1] =
3181                         EXT4_ENCRYPTION_MODE_AES_256_CTS;
3182         }
3183
3184         if (ext2fs_has_feature_metadata_csum(fs->super))
3185                 fs->super->s_checksum_type = EXT2_CRC32C_CHKSUM;
3186
3187         if (!quiet || noaction)
3188                 show_stats(fs);
3189
3190         if (noaction)
3191                 exit(0);
3192
3193         if (ext2fs_has_feature_journal_dev(fs->super)) {
3194                 create_journal_dev(fs);
3195                 printf("\n");
3196                 exit(ext2fs_close_free(&fs) ? 1 : 0);
3197         }
3198
3199         if (bad_blocks_filename)
3200                 read_bb_file(fs, &bb_list, bad_blocks_filename);
3201         if (cflag)
3202                 test_disk(fs, &bb_list);
3203         handle_bad_blocks(fs, bb_list);
3204
3205         fs->stride = fs_stride = fs->super->s_raid_stride;
3206         if (!quiet)
3207                 printf("%s", _("Allocating group tables: "));
3208         if (ext2fs_has_feature_flex_bg(fs->super) &&
3209             packed_meta_blocks)
3210                 retval = packed_allocate_tables(fs);
3211         else
3212                 retval = ext2fs_allocate_tables(fs);
3213         if (retval) {
3214                 com_err(program_name, retval, "%s",
3215                         _("while trying to allocate filesystem tables"));
3216                 exit(1);
3217         }
3218         if (!quiet)
3219                 printf("%s", _("done                            \n"));
3220
3221         /*
3222          * Unmark bad blocks to calculate overhead, because metadata
3223          * blocks and bad blocks can land on the same allocation cluster.
3224          */
3225         if (bb_list) {
3226                 retval = ext2fs_badblocks_list_iterate_begin(bb_list,
3227                                                              &bb_iter);
3228                 if (retval) {
3229                         com_err("ext2fs_badblocks_list_iterate_begin", retval,
3230                                 "%s", _("while unmarking bad blocks"));
3231                         exit(1);
3232                 }
3233                 while (ext2fs_badblocks_list_iterate(bb_iter, &blk))
3234                         ext2fs_unmark_block_bitmap2(fs->block_map, blk);
3235                 ext2fs_badblocks_list_iterate_end(bb_iter);
3236         }
3237
3238         retval = ext2fs_convert_subcluster_bitmap(fs, &fs->block_map);
3239         if (retval) {
3240                 com_err(program_name, retval, "%s",
3241                         _("\n\twhile converting subcluster bitmap"));
3242                 exit(1);
3243         }
3244
3245         retval = ext2fs_count_used_clusters(fs, fs->super->s_first_data_block,
3246                                         ext2fs_blocks_count(fs->super) - 1,
3247                                         &overhead);
3248         if (retval) {
3249                 com_err(program_name, retval, "%s",
3250                         _("while calculating overhead"));
3251                 exit(1);
3252         }
3253
3254         if (bb_list) {
3255                 retval = ext2fs_badblocks_list_iterate_begin(bb_list,
3256                                                              &bb_iter);
3257                 if (retval) {
3258                         com_err("ext2fs_badblocks_list_iterate_begin", retval,
3259                                 "%s", _("while marking bad blocks as used"));
3260                         exit(1);
3261                 }
3262                 while (ext2fs_badblocks_list_iterate(bb_iter, &blk))
3263                         ext2fs_mark_block_bitmap2(fs->block_map, blk);
3264                 ext2fs_badblocks_list_iterate_end(bb_iter);
3265         }
3266
3267         if (super_only) {
3268                 check_plausibility(device_name, CHECK_FS_EXIST, NULL);
3269                 printf(_("%s may be further corrupted by superblock rewrite\n"),
3270                        device_name);
3271                 if (!force)
3272                         proceed_question(proceed_delay);
3273                 fs->super->s_state |= EXT2_ERROR_FS;
3274                 fs->flags &= ~(EXT2_FLAG_IB_DIRTY|EXT2_FLAG_BB_DIRTY);
3275                 /*
3276                  * The command "mke2fs -S" is used to recover
3277                  * corrupted file systems, so do not mark any of the
3278                  * inodes as unused; we want e2fsck to consider all
3279                  * inodes as potentially containing recoverable data.
3280                  */
3281                 if (ext2fs_has_group_desc_csum(fs)) {
3282                         for (i = 0; i < fs->group_desc_count; i++)
3283                                 ext2fs_bg_itable_unused_set(fs, i, 0);
3284                 }
3285         } else {
3286                 /* rsv must be a power of two (64kB is MD RAID sb alignment) */
3287                 blk64_t rsv = 65536 / fs->blocksize;
3288                 blk64_t blocks = ext2fs_blocks_count(fs->super);
3289                 blk64_t start;
3290                 blk64_t ret_blk;
3291
3292 #ifdef ZAP_BOOTBLOCK
3293                 zap_sector(fs, 0, 2);
3294 #endif
3295
3296                 /*
3297                  * Wipe out any old MD RAID (or other) metadata at the end
3298                  * of the device.  This will also verify that the device is
3299                  * as large as we think.  Be careful with very small devices.
3300                  */
3301                 start = (blocks & ~(rsv - 1));
3302                 if (start > rsv)
3303                         start -= rsv;
3304                 if (start > 0)
3305                         retval = ext2fs_zero_blocks2(fs, start, blocks - start,
3306                                                     &ret_blk, NULL);
3307
3308                 if (retval) {
3309                         com_err(program_name, retval,
3310                                 _("while zeroing block %llu at end of filesystem"),
3311                                 (unsigned long long) ret_blk);
3312                 }
3313                 write_inode_tables(fs, lazy_itable_init, itable_zeroed);
3314                 create_root_dir(fs);
3315                 create_lost_and_found(fs);
3316                 reserve_inodes(fs);
3317                 create_bad_block_inode(fs, bb_list);
3318                 if (ext2fs_has_feature_resize_inode(fs->super)) {
3319                         retval = ext2fs_create_resize_inode(fs);
3320                         if (retval) {
3321                                 com_err("ext2fs_create_resize_inode", retval,
3322                                         "%s",
3323                                 _("while reserving blocks for online resize"));
3324                                 exit(1);
3325                         }
3326                 }
3327         }
3328
3329         if (journal_device) {
3330                 ext2_filsys     jfs;
3331
3332                 if (!check_plausibility(journal_device, CHECK_BLOCK_DEV,
3333                                         NULL) && !force)
3334                         proceed_question(proceed_delay);
3335                 check_mount(journal_device, force, _("journal"));
3336
3337                 retval = ext2fs_open(journal_device, EXT2_FLAG_RW|
3338                                      EXT2_FLAG_JOURNAL_DEV_OK, 0,
3339                                      fs->blocksize, unix_io_manager, &jfs);
3340                 if (retval) {
3341                         com_err(program_name, retval,
3342                                 _("while trying to open journal device %s\n"),
3343                                 journal_device);
3344                         exit(1);
3345                 }
3346                 if (!quiet) {
3347                         printf(_("Adding journal to device %s: "),
3348                                journal_device);
3349                         fflush(stdout);
3350                 }
3351                 retval = ext2fs_add_journal_device(fs, jfs);
3352                 if(retval) {
3353                         com_err (program_name, retval,
3354                                  _("\n\twhile trying to add journal to device %s"),
3355                                  journal_device);
3356                         exit(1);
3357                 }
3358                 if (!quiet)
3359                         printf("%s", _("done\n"));
3360                 ext2fs_close_free(&jfs);
3361                 free(journal_device);
3362         } else if ((journal_size) ||
3363                    ext2fs_has_feature_journal(&fs_param)) {
3364                 overhead += EXT2FS_NUM_B2C(fs, jparams.num_journal_blocks + jparams.num_fc_blocks);
3365                 if (super_only) {
3366                         printf("%s", _("Skipping journal creation in super-only mode\n"));
3367                         fs->super->s_journal_inum = EXT2_JOURNAL_INO;
3368                         goto no_journal;
3369                 }
3370
3371                 if (!jparams.num_journal_blocks) {
3372                         ext2fs_clear_feature_journal(fs->super);
3373                         goto no_journal;
3374                 }
3375                 if (!quiet) {
3376                         printf(_("Creating journal (%u blocks): "),
3377                                jparams.num_journal_blocks + jparams.num_fc_blocks);
3378                         fflush(stdout);
3379                 }
3380                 retval = ext2fs_add_journal_inode3(fs, &jparams,
3381                                                    journal_location,
3382                                                    journal_flags);
3383                 if (retval) {
3384                         com_err(program_name, retval, "%s",
3385                                 _("\n\twhile trying to create journal"));
3386                         exit(1);
3387                 }
3388                 if (!quiet)
3389                         printf("%s", _("done\n"));
3390         }
3391 no_journal:
3392         if (!super_only &&
3393             ext2fs_has_feature_mmp(fs->super)) {
3394                 retval = ext2fs_mmp_init(fs);
3395                 if (retval) {
3396                         fprintf(stderr, "%s",
3397                                 _("\nError while enabling multiple "
3398                                   "mount protection feature."));
3399                         exit(1);
3400                 }
3401                 if (!quiet)
3402                         printf(_("Multiple mount protection is enabled "
3403                                  "with update interval %d seconds.\n"),
3404                                fs->super->s_mmp_update_interval);
3405         }
3406
3407         overhead += fs->super->s_first_data_block;
3408         if (!super_only)
3409                 fs->super->s_overhead_clusters = overhead;
3410
3411         if (ext2fs_has_feature_bigalloc(&fs_param))
3412                 fix_cluster_bg_counts(fs);
3413         if (ext2fs_has_feature_quota(&fs_param))
3414                 create_quota_inodes(fs);
3415
3416         retval = mk_hugefiles(fs, device_name);
3417         if (retval)
3418                 com_err(program_name, retval, "while creating huge files");
3419         /* Copy files from the specified directory */
3420         if (src_root_dir) {
3421                 if (!quiet)
3422                         printf("%s", _("Copying files into the device: "));
3423
3424                 retval = populate_fs(fs, EXT2_ROOT_INO, src_root_dir,
3425                                      EXT2_ROOT_INO);
3426                 if (retval) {
3427                         com_err(program_name, retval, "%s",
3428                                 _("while populating file system"));
3429                         exit(1);
3430                 } else if (!quiet)
3431                         printf("%s", _("done\n"));
3432         }
3433
3434         if (!quiet)
3435                 printf("%s", _("Writing superblocks and "
3436                        "filesystem accounting information: "));
3437         checkinterval = fs->super->s_checkinterval;
3438         max_mnt_count = fs->super->s_max_mnt_count;
3439         retval = ext2fs_close_free(&fs);
3440         if (retval) {
3441                 com_err(program_name, retval, "%s",
3442                         _("while writing out and closing file system"));
3443                 retval = 1;
3444         } else if (!quiet) {
3445                 printf("%s", _("done\n\n"));
3446                 if (!getenv("MKE2FS_SKIP_CHECK_MSG"))
3447                         print_check_message(max_mnt_count, checkinterval);
3448         }
3449
3450         remove_error_table(&et_ext2_error_table);
3451         remove_error_table(&et_prof_error_table);
3452         profile_release(profile);
3453         for (i=0; fs_types[i]; i++)
3454                 free(fs_types[i]);
3455         free(fs_types);
3456         return retval;
3457 }