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