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