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