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