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