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