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