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