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