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