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