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