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