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