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