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