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