Whamcloud - gitweb
Add basic BIGALLOC support for cluster-based allocation
[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         if (EXT2_HAS_RO_COMPAT_FEATURE(fs->super,
620                                        EXT4_FEATURE_RO_COMPAT_BIGALLOC))
621                 printf(_("Cluster size=%u (log=%u)\n"),
622                        fs->clustersize, s->s_log_cluster_size);
623         else
624                 printf(_("Fragment size=%u (log=%u)\n"), fs->clustersize,
625                        s->s_log_cluster_size);
626         printf(_("Stride=%u blocks, Stripe width=%u blocks\n"),
627                s->s_raid_stride, s->s_raid_stripe_width);
628         printf(_("%u inodes, %u blocks\n"), s->s_inodes_count,
629                s->s_blocks_count);
630         printf(_("%u blocks (%2.2f%%) reserved for the super user\n"),
631                 s->s_r_blocks_count,
632                100.0 * s->s_r_blocks_count / s->s_blocks_count);
633         printf(_("First data block=%u\n"), s->s_first_data_block);
634         if (s->s_reserved_gdt_blocks)
635                 printf(_("Maximum filesystem blocks=%lu\n"),
636                        (s->s_reserved_gdt_blocks + fs->desc_blocks) *
637                        EXT2_DESC_PER_BLOCK(s) * s->s_blocks_per_group);
638         if (fs->group_desc_count > 1)
639                 printf(_("%u block groups\n"), fs->group_desc_count);
640         else
641                 printf(_("%u block group\n"), fs->group_desc_count);
642         if (EXT2_HAS_RO_COMPAT_FEATURE(fs->super,
643                                        EXT4_FEATURE_RO_COMPAT_BIGALLOC))
644                 printf(_("%u blocks per group, %u clusters per group\n"),
645                        s->s_blocks_per_group, s->s_clusters_per_group);
646         else
647                 printf(_("%u blocks per group, %u fragments per group\n"),
648                        s->s_blocks_per_group, s->s_clusters_per_group);
649         printf(_("%u inodes per group\n"), s->s_inodes_per_group);
650
651         if (fs->group_desc_count == 1) {
652                 printf("\n");
653                 return;
654         }
655
656         printf(_("Superblock backups stored on blocks: "));
657         group_block = s->s_first_data_block;
658         col_left = 0;
659         for (i = 1; i < fs->group_desc_count; i++) {
660                 group_block += s->s_blocks_per_group;
661                 if (!ext2fs_bg_has_super(fs, i))
662                         continue;
663                 if (i != 1)
664                         printf(", ");
665                 need = int_log10(group_block) + 2;
666                 if (need > col_left) {
667                         printf("\n\t");
668                         col_left = 72;
669                 }
670                 col_left -= need;
671                 printf("%u", group_block);
672         }
673         printf("\n\n");
674 }
675
676 /*
677  * Set the S_CREATOR_OS field.  Return true if OS is known,
678  * otherwise, 0.
679  */
680 static int set_os(struct ext2_super_block *sb, char *os)
681 {
682         if (isdigit (*os))
683                 sb->s_creator_os = atoi (os);
684         else if (strcasecmp(os, "linux") == 0)
685                 sb->s_creator_os = EXT2_OS_LINUX;
686         else if (strcasecmp(os, "GNU") == 0 || strcasecmp(os, "hurd") == 0)
687                 sb->s_creator_os = EXT2_OS_HURD;
688         else if (strcasecmp(os, "freebsd") == 0)
689                 sb->s_creator_os = EXT2_OS_FREEBSD;
690         else if (strcasecmp(os, "lites") == 0)
691                 sb->s_creator_os = EXT2_OS_LITES;
692         else
693                 return 0;
694         return 1;
695 }
696
697 #define PATH_SET "PATH=/sbin"
698
699 static void parse_extended_opts(struct ext2_super_block *param,
700                                 const char *opts)
701 {
702         char    *buf, *token, *next, *p, *arg, *badopt = 0;
703         int     len;
704         int     r_usage = 0;
705
706         len = strlen(opts);
707         buf = malloc(len+1);
708         if (!buf) {
709                 fprintf(stderr,
710                         _("Couldn't allocate memory to parse options!\n"));
711                 exit(1);
712         }
713         strcpy(buf, opts);
714         for (token = buf; token && *token; token = next) {
715                 p = strchr(token, ',');
716                 next = 0;
717                 if (p) {
718                         *p = 0;
719                         next = p+1;
720                 }
721                 arg = strchr(token, '=');
722                 if (arg) {
723                         *arg = 0;
724                         arg++;
725                 }
726                 if (strcmp(token, "stride") == 0) {
727                         if (!arg) {
728                                 r_usage++;
729                                 badopt = token;
730                                 continue;
731                         }
732                         param->s_raid_stride = strtoul(arg, &p, 0);
733                         if (*p || (param->s_raid_stride == 0)) {
734                                 fprintf(stderr,
735                                         _("Invalid stride parameter: %s\n"),
736                                         arg);
737                                 r_usage++;
738                                 continue;
739                         }
740                 } else if (strcmp(token, "stripe-width") == 0 ||
741                            strcmp(token, "stripe_width") == 0) {
742                         if (!arg) {
743                                 r_usage++;
744                                 badopt = token;
745                                 continue;
746                         }
747                         param->s_raid_stripe_width = strtoul(arg, &p, 0);
748                         if (*p || (param->s_raid_stripe_width == 0)) {
749                                 fprintf(stderr,
750                                         _("Invalid stripe-width parameter: %s\n"),
751                                         arg);
752                                 r_usage++;
753                                 continue;
754                         }
755                 } else if (!strcmp(token, "resize")) {
756                         unsigned long resize, bpg, rsv_groups;
757                         unsigned long group_desc_count, desc_blocks;
758                         unsigned int gdpb, blocksize;
759                         int rsv_gdb;
760
761                         if (!arg) {
762                                 r_usage++;
763                                 badopt = token;
764                                 continue;
765                         }
766
767                         resize = parse_num_blocks(arg,
768                                                   param->s_log_block_size);
769
770                         if (resize == 0) {
771                                 fprintf(stderr,
772                                         _("Invalid resize parameter: %s\n"),
773                                         arg);
774                                 r_usage++;
775                                 continue;
776                         }
777                         if (resize <= param->s_blocks_count) {
778                                 fprintf(stderr,
779                                         _("The resize maximum must be greater "
780                                           "than the filesystem size.\n"));
781                                 r_usage++;
782                                 continue;
783                         }
784
785                         blocksize = EXT2_BLOCK_SIZE(param);
786                         bpg = param->s_blocks_per_group;
787                         if (!bpg)
788                                 bpg = blocksize * 8;
789                         gdpb = EXT2_DESC_PER_BLOCK(param);
790                         group_desc_count =
791                                 ext2fs_div_ceil(param->s_blocks_count, bpg);
792                         desc_blocks = (group_desc_count +
793                                        gdpb - 1) / gdpb;
794                         rsv_groups = ext2fs_div_ceil(resize, bpg);
795                         rsv_gdb = ext2fs_div_ceil(rsv_groups, gdpb) -
796                                 desc_blocks;
797                         if (rsv_gdb > (int) EXT2_ADDR_PER_BLOCK(param))
798                                 rsv_gdb = EXT2_ADDR_PER_BLOCK(param);
799
800                         if (rsv_gdb > 0) {
801                                 if (param->s_rev_level == EXT2_GOOD_OLD_REV) {
802                                         fprintf(stderr,
803         _("On-line resizing not supported with revision 0 filesystems\n"));
804                                         free(buf);
805                                         exit(1);
806                                 }
807                                 param->s_feature_compat |=
808                                         EXT2_FEATURE_COMPAT_RESIZE_INODE;
809
810                                 param->s_reserved_gdt_blocks = rsv_gdb;
811                         }
812                 } else if (!strcmp(token, "test_fs")) {
813                         param->s_flags |= EXT2_FLAGS_TEST_FILESYS;
814                 } else if (!strcmp(token, "lazy_itable_init")) {
815                         if (arg)
816                                 lazy_itable_init = strtoul(arg, &p, 0);
817                         else
818                                 lazy_itable_init = 1;
819                 } else if (!strcmp(token, "discard")) {
820                         discard = 1;
821                 } else if (!strcmp(token, "nodiscard")) {
822                         discard = 0;
823                 } else {
824                         r_usage++;
825                         badopt = token;
826                 }
827         }
828         if (r_usage) {
829                 fprintf(stderr, _("\nBad option(s) specified: %s\n\n"
830                         "Extended options are separated by commas, "
831                         "and may take an argument which\n"
832                         "\tis set off by an equals ('=') sign.\n\n"
833                         "Valid extended options are:\n"
834                         "\tstride=<RAID per-disk data chunk in blocks>\n"
835                         "\tstripe-width=<RAID stride * data disks in blocks>\n"
836                         "\tresize=<resize maximum size in blocks>\n"
837                         "\tlazy_itable_init=<0 to disable, 1 to enable>\n"
838                         "\ttest_fs\n"
839                         "\tdiscard\n"
840                         "\tnodiscard\n\n"),
841                         badopt ? badopt : "");
842                 free(buf);
843                 exit(1);
844         }
845         if (param->s_raid_stride &&
846             (param->s_raid_stripe_width % param->s_raid_stride) != 0)
847                 fprintf(stderr, _("\nWarning: RAID stripe-width %u not an even "
848                                   "multiple of stride %u.\n\n"),
849                         param->s_raid_stripe_width, param->s_raid_stride);
850
851         free(buf);
852 }
853
854 static __u32 ok_features[3] = {
855         /* Compat */
856         EXT3_FEATURE_COMPAT_HAS_JOURNAL |
857                 EXT2_FEATURE_COMPAT_RESIZE_INODE |
858                 EXT2_FEATURE_COMPAT_DIR_INDEX |
859                 EXT2_FEATURE_COMPAT_EXT_ATTR,
860         /* Incompat */
861         EXT2_FEATURE_INCOMPAT_FILETYPE|
862                 EXT3_FEATURE_INCOMPAT_EXTENTS|
863                 EXT3_FEATURE_INCOMPAT_JOURNAL_DEV|
864                 EXT2_FEATURE_INCOMPAT_META_BG|
865                 EXT4_FEATURE_INCOMPAT_FLEX_BG,
866         /* R/O compat */
867         EXT2_FEATURE_RO_COMPAT_LARGE_FILE|
868                 EXT4_FEATURE_RO_COMPAT_HUGE_FILE|
869                 EXT4_FEATURE_RO_COMPAT_DIR_NLINK|
870                 EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE|
871                 EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER|
872                 EXT4_FEATURE_RO_COMPAT_GDT_CSUM
873 };
874
875
876 static void syntax_err_report(const char *filename, long err, int line_num)
877 {
878         fprintf(stderr,
879                 _("Syntax error in mke2fs config file (%s, line #%d)\n\t%s\n"),
880                 filename, line_num, error_message(err));
881         exit(1);
882 }
883
884 static const char *config_fn[] = { ROOT_SYSCONFDIR "/mke2fs.conf", 0 };
885
886 static void edit_feature(const char *str, __u32 *compat_array)
887 {
888         if (!str)
889                 return;
890
891         if (e2p_edit_feature(str, compat_array, ok_features)) {
892                 fprintf(stderr, _("Invalid filesystem option set: %s\n"),
893                         str);
894                 exit(1);
895         }
896 }
897
898 static void edit_mntopts(const char *str, __u32 *mntopts)
899 {
900         if (!str)
901                 return;
902
903         if (e2p_edit_mntopts(str, mntopts, ~0)) {
904                 fprintf(stderr, _("Invalid mount option set: %s\n"),
905                         str);
906                 exit(1);
907         }
908 }
909
910 struct str_list {
911         char **list;
912         int num;
913         int max;
914 };
915
916 static errcode_t init_list(struct str_list *sl)
917 {
918         sl->num = 0;
919         sl->max = 0;
920         sl->list = malloc((sl->max+1) * sizeof(char *));
921         if (!sl->list)
922                 return ENOMEM;
923         sl->list[0] = 0;
924         return 0;
925 }
926
927 static errcode_t push_string(struct str_list *sl, const char *str)
928 {
929         char **new_list;
930
931         if (sl->num >= sl->max) {
932                 sl->max += 2;
933                 new_list = realloc(sl->list, (sl->max+1) * sizeof(char *));
934                 if (!new_list)
935                         return ENOMEM;
936                 sl->list = new_list;
937         }
938         sl->list[sl->num] = malloc(strlen(str)+1);
939         if (sl->list[sl->num] == 0)
940                 return ENOMEM;
941         strcpy(sl->list[sl->num], str);
942         sl->num++;
943         sl->list[sl->num] = 0;
944         return 0;
945 }
946
947 static void print_str_list(char **list)
948 {
949         char **cpp;
950
951         for (cpp = list; *cpp; cpp++) {
952                 printf("'%s'", *cpp);
953                 if (cpp[1])
954                         fputs(", ", stdout);
955         }
956         fputc('\n', stdout);
957 }
958
959 /*
960  * Return TRUE if the profile has the given subsection
961  */
962 static int profile_has_subsection(profile_t profile, const char *section,
963                                   const char *subsection)
964 {
965         void                    *state;
966         const char              *names[4];
967         char                    *name;
968         int                     ret = 0;
969
970         names[0] = section;
971         names[1] = subsection;
972         names[2] = 0;
973
974         if (profile_iterator_create(profile, names,
975                                     PROFILE_ITER_LIST_SECTION |
976                                     PROFILE_ITER_RELATIONS_ONLY, &state))
977                 return 0;
978
979         if ((profile_iterator(&state, &name, 0) == 0) && name) {
980                 free(name);
981                 ret = 1;
982         }
983
984         profile_iterator_free(&state);
985         return ret;
986 }
987
988 static char **parse_fs_type(const char *fs_type,
989                             const char *usage_types,
990                             struct ext2_super_block *fs_param,
991                             char *progname)
992 {
993         const char      *ext_type = 0;
994         char            *parse_str;
995         char            *profile_type = 0;
996         char            *cp, *t;
997         const char      *size_type;
998         struct str_list list;
999         unsigned long   meg;
1000         int             is_hurd = 0;
1001
1002         if (init_list(&list))
1003                 return 0;
1004
1005         if (creator_os && (!strcasecmp(creator_os, "GNU") ||
1006                            !strcasecmp(creator_os, "hurd")))
1007                 is_hurd = 1;
1008
1009         if (fs_type)
1010                 ext_type = fs_type;
1011         else if (is_hurd)
1012                 ext_type = "ext2";
1013         else if (!strcmp(program_name, "mke3fs"))
1014                 ext_type = "ext3";
1015         else if (progname) {
1016                 ext_type = strrchr(progname, '/');
1017                 if (ext_type)
1018                         ext_type++;
1019                 else
1020                         ext_type = progname;
1021
1022                 if (!strncmp(ext_type, "mkfs.", 5)) {
1023                         ext_type += 5;
1024                         if (ext_type[0] == 0)
1025                                 ext_type = 0;
1026                 } else
1027                         ext_type = 0;
1028         }
1029
1030         if (!ext_type) {
1031                 profile_get_string(profile, "defaults", "fs_type", 0,
1032                                    "ext2", &profile_type);
1033                 ext_type = profile_type;
1034                 if (!strcmp(ext_type, "ext2") && (journal_size != 0))
1035                         ext_type = "ext3";
1036         }
1037
1038
1039         if (!profile_has_subsection(profile, "fs_types", ext_type) &&
1040             strcmp(ext_type, "ext2")) {
1041                 printf(_("\nYour mke2fs.conf file does not define the "
1042                          "%s filesystem type.\n"), ext_type);
1043                 if (!strcmp(ext_type, "ext3") || !strcmp(ext_type, "ext4") ||
1044                     !strcmp(ext_type, "ext4dev")) {
1045                         printf(_("You probably need to install an updated "
1046                                  "mke2fs.conf file.\n\n"));
1047                 }
1048                 if (!force) {
1049                         printf(_("Aborting...\n"));
1050                         exit(1);
1051                 }
1052         }
1053
1054         meg = (1024 * 1024) / EXT2_BLOCK_SIZE(fs_param);
1055         if (fs_param->s_blocks_count < 3 * meg)
1056                 size_type = "floppy";
1057         else if (fs_param->s_blocks_count < 512 * meg)
1058                 size_type = "small";
1059         else
1060                 size_type = "default";
1061
1062         if (!usage_types)
1063                 usage_types = size_type;
1064
1065         parse_str = malloc(usage_types ? strlen(usage_types)+1 : 1);
1066         if (!parse_str) {
1067                 free(list.list);
1068                 return 0;
1069         }
1070         if (usage_types)
1071                 strcpy(parse_str, usage_types);
1072         else
1073                 *parse_str = '\0';
1074
1075         if (ext_type)
1076                 push_string(&list, ext_type);
1077         cp = parse_str;
1078         while (1) {
1079                 t = strchr(cp, ',');
1080                 if (t)
1081                         *t = '\0';
1082
1083                 if (*cp) {
1084                         if (profile_has_subsection(profile, "fs_types", cp))
1085                                 push_string(&list, cp);
1086                         else if (strcmp(cp, "default") != 0)
1087                                 fprintf(stderr,
1088                                         _("\nWarning: the fs_type %s is not "
1089                                           "defined in mke2fs.conf\n\n"),
1090                                         cp);
1091                 }
1092                 if (t)
1093                         cp = t+1;
1094                 else {
1095                         cp = "";
1096                         break;
1097                 }
1098         }
1099         free(parse_str);
1100         free(profile_type);
1101         if (is_hurd)
1102                 push_string(&list, "hurd");
1103         return (list.list);
1104 }
1105
1106 static char *get_string_from_profile(char **fs_types, const char *opt,
1107                                      const char *def_val)
1108 {
1109         char *ret = 0;
1110         int i;
1111
1112         for (i=0; fs_types[i]; i++);
1113         for (i-=1; i >=0 ; i--) {
1114                 profile_get_string(profile, "fs_types", fs_types[i],
1115                                    opt, 0, &ret);
1116                 if (ret)
1117                         return ret;
1118         }
1119         profile_get_string(profile, "defaults", opt, 0, def_val, &ret);
1120         return (ret);
1121 }
1122
1123 static int get_int_from_profile(char **fs_types, const char *opt, int def_val)
1124 {
1125         int ret;
1126         char **cpp;
1127
1128         profile_get_integer(profile, "defaults", opt, 0, def_val, &ret);
1129         for (cpp = fs_types; *cpp; cpp++)
1130                 profile_get_integer(profile, "fs_types", *cpp, opt, ret, &ret);
1131         return ret;
1132 }
1133
1134 static int get_bool_from_profile(char **fs_types, const char *opt, int def_val)
1135 {
1136         int ret;
1137         char **cpp;
1138
1139         profile_get_boolean(profile, "defaults", opt, 0, def_val, &ret);
1140         for (cpp = fs_types; *cpp; cpp++)
1141                 profile_get_boolean(profile, "fs_types", *cpp, opt, ret, &ret);
1142         return ret;
1143 }
1144
1145 extern const char *mke2fs_default_profile;
1146 static const char *default_files[] = { "<default>", 0 };
1147
1148 #ifdef HAVE_BLKID_PROBE_GET_TOPOLOGY
1149 /*
1150  * Sets the geometry of a device (stripe/stride), and returns the
1151  * device's alignment offset, if any, or a negative error.
1152  */
1153 static int get_device_geometry(const char *file,
1154                                struct ext2_super_block *fs_param,
1155                                int psector_size)
1156 {
1157         int rc = -1;
1158         int blocksize;
1159         blkid_probe pr;
1160         blkid_topology tp;
1161         unsigned long min_io;
1162         unsigned long opt_io;
1163         struct stat statbuf;
1164
1165         /* Nothing to do for a regular file */
1166         if (!stat(file, &statbuf) && S_ISREG(statbuf.st_mode))
1167                 return 0;
1168
1169         pr = blkid_new_probe_from_filename(file);
1170         if (!pr)
1171                 goto out;
1172
1173         tp = blkid_probe_get_topology(pr);
1174         if (!tp)
1175                 goto out;
1176
1177         min_io = blkid_topology_get_minimum_io_size(tp);
1178         opt_io = blkid_topology_get_optimal_io_size(tp);
1179         blocksize = EXT2_BLOCK_SIZE(fs_param);
1180         if ((min_io == 0) && (psector_size > blocksize))
1181                 min_io = psector_size;
1182         if ((opt_io == 0) && min_io)
1183                 opt_io = min_io;
1184         if ((opt_io == 0) && (psector_size > blocksize))
1185                 opt_io = psector_size;
1186
1187         fs_param->s_raid_stride = min_io / blocksize;
1188         fs_param->s_raid_stripe_width = opt_io / blocksize;
1189
1190         rc = blkid_topology_get_alignment_offset(tp);
1191 out:
1192         blkid_free_probe(pr);
1193         return rc;
1194 }
1195 #endif
1196
1197 static void PRS(int argc, char *argv[])
1198 {
1199         int             b, c;
1200         int             size;
1201         char            *tmp, **cpp;
1202         int             blocksize = 0;
1203         int             inode_ratio = 0;
1204         int             inode_size = 0;
1205         unsigned long   flex_bg_size = 0;
1206         double          reserved_ratio = 5.0;
1207         int             lsector_size = 0, psector_size = 0;
1208         int             show_version_only = 0;
1209         unsigned long long num_inodes = 0; /* unsigned long long to catch too-large input */
1210         errcode_t       retval;
1211         char *          oldpath = getenv("PATH");
1212         char *          extended_opts = 0;
1213         const char *    fs_type = 0;
1214         const char *    usage_types = 0;
1215         blk_t           dev_size;
1216 #ifdef __linux__
1217         struct          utsname ut;
1218 #endif
1219         long            sysval;
1220         int             s_opt = -1, r_opt = -1;
1221         char            *fs_features = 0;
1222         int             use_bsize;
1223         char            *newpath;
1224         int             pathlen = sizeof(PATH_SET) + 1;
1225
1226         if (oldpath)
1227                 pathlen += strlen(oldpath);
1228         newpath = malloc(pathlen);
1229         strcpy(newpath, PATH_SET);
1230
1231         /* Update our PATH to include /sbin  */
1232         if (oldpath) {
1233                 strcat (newpath, ":");
1234                 strcat (newpath, oldpath);
1235         }
1236         putenv (newpath);
1237
1238         tmp = getenv("MKE2FS_SYNC");
1239         if (tmp)
1240                 sync_kludge = atoi(tmp);
1241
1242         /* Determine the system page size if possible */
1243 #ifdef HAVE_SYSCONF
1244 #if (!defined(_SC_PAGESIZE) && defined(_SC_PAGE_SIZE))
1245 #define _SC_PAGESIZE _SC_PAGE_SIZE
1246 #endif
1247 #ifdef _SC_PAGESIZE
1248         sysval = sysconf(_SC_PAGESIZE);
1249         if (sysval > 0)
1250                 sys_page_size = sysval;
1251 #endif /* _SC_PAGESIZE */
1252 #endif /* HAVE_SYSCONF */
1253
1254         if ((tmp = getenv("MKE2FS_CONFIG")) != NULL)
1255                 config_fn[0] = tmp;
1256         profile_set_syntax_err_cb(syntax_err_report);
1257         retval = profile_init(config_fn, &profile);
1258         if (retval == ENOENT) {
1259                 profile_init(default_files, &profile);
1260                 profile_set_default(profile, mke2fs_default_profile);
1261         }
1262
1263         setbuf(stdout, NULL);
1264         setbuf(stderr, NULL);
1265         add_error_table(&et_ext2_error_table);
1266         add_error_table(&et_prof_error_table);
1267         memset(&fs_param, 0, sizeof(struct ext2_super_block));
1268         fs_param.s_rev_level = 1;  /* Create revision 1 filesystems now */
1269
1270 #ifdef __linux__
1271         if (uname(&ut)) {
1272                 perror("uname");
1273                 exit(1);
1274         }
1275         linux_version_code = parse_version_number(ut.release);
1276         if (linux_version_code && linux_version_code < (2*65536 + 2*256))
1277                 fs_param.s_rev_level = 0;
1278 #endif
1279
1280         if (argc && *argv) {
1281                 program_name = get_progname(*argv);
1282
1283                 /* If called as mkfs.ext3, create a journal inode */
1284                 if (!strcmp(program_name, "mkfs.ext3") ||
1285                     !strcmp(program_name, "mke3fs"))
1286                         journal_size = -1;
1287         }
1288
1289         while ((c = getopt (argc, argv,
1290                     "b:cf:g:G:i:jl:m:no:qr:s:t:vE:FI:J:KL:M:N:O:R:ST:U:V")) != EOF) {
1291                 switch (c) {
1292                 case 'b':
1293                         blocksize = strtol(optarg, &tmp, 0);
1294                         b = (blocksize > 0) ? blocksize : -blocksize;
1295                         if (b < EXT2_MIN_BLOCK_SIZE ||
1296                             b > EXT2_MAX_BLOCK_SIZE || *tmp) {
1297                                 com_err(program_name, 0,
1298                                         _("invalid block size - %s"), optarg);
1299                                 exit(1);
1300                         }
1301                         if (blocksize > 4096)
1302                                 fprintf(stderr, _("Warning: blocksize %d not "
1303                                                   "usable on most systems.\n"),
1304                                         blocksize);
1305                         if (blocksize > 0)
1306                                 fs_param.s_log_block_size =
1307                                         int_log2(blocksize >>
1308                                                  EXT2_MIN_BLOCK_LOG_SIZE);
1309                         break;
1310                 case 'c':       /* Check for bad blocks */
1311                         cflag++;
1312                         break;
1313                 case 'f':
1314                         size = strtoul(optarg, &tmp, 0);
1315                         if (size < EXT2_MIN_BLOCK_SIZE ||
1316                             size > EXT2_MAX_BLOCK_SIZE || *tmp) {
1317                                 com_err(program_name, 0,
1318                                         _("invalid fragment size - %s"),
1319                                         optarg);
1320                                 exit(1);
1321                         }
1322                         fprintf(stderr, _("Warning: fragments not supported.  "
1323                                "Ignoring -f option\n"));
1324                         break;
1325                 case 'g':
1326                         fs_param.s_blocks_per_group = strtoul(optarg, &tmp, 0);
1327                         if (*tmp) {
1328                                 com_err(program_name, 0,
1329                                         _("Illegal number for blocks per group"));
1330                                 exit(1);
1331                         }
1332                         if ((fs_param.s_blocks_per_group % 8) != 0) {
1333                                 com_err(program_name, 0,
1334                                 _("blocks per group must be multiple of 8"));
1335                                 exit(1);
1336                         }
1337                         break;
1338                 case 'G':
1339                         flex_bg_size = strtoul(optarg, &tmp, 0);
1340                         if (*tmp) {
1341                                 com_err(program_name, 0,
1342                                         _("Illegal number for flex_bg size"));
1343                                 exit(1);
1344                         }
1345                         if (flex_bg_size < 1 ||
1346                             (flex_bg_size & (flex_bg_size-1)) != 0) {
1347                                 com_err(program_name, 0,
1348                                         _("flex_bg size must be a power of 2"));
1349                                 exit(1);
1350                         }
1351                         break;
1352                 case 'i':
1353                         inode_ratio = strtoul(optarg, &tmp, 0);
1354                         if (inode_ratio < EXT2_MIN_BLOCK_SIZE ||
1355                             inode_ratio > EXT2_MAX_BLOCK_SIZE * 1024 ||
1356                             *tmp) {
1357                                 com_err(program_name, 0,
1358                                         _("invalid inode ratio %s (min %d/max %d)"),
1359                                         optarg, EXT2_MIN_BLOCK_SIZE,
1360                                         EXT2_MAX_BLOCK_SIZE * 1024);
1361                                 exit(1);
1362                         }
1363                         break;
1364                 case 'J':
1365                         parse_journal_opts(optarg);
1366                         break;
1367                 case 'K':
1368                         fprintf(stderr, _("Warning: -K option is deprecated and "
1369                                           "should not be used anymore. Use "
1370                                           "\'-E nodiscard\' extended option "
1371                                           "instead!\n"));
1372                         discard = 0;
1373                         break;
1374                 case 'j':
1375                         if (!journal_size)
1376                                 journal_size = -1;
1377                         break;
1378                 case 'l':
1379                         bad_blocks_filename = malloc(strlen(optarg)+1);
1380                         if (!bad_blocks_filename) {
1381                                 com_err(program_name, ENOMEM,
1382                                         _("in malloc for bad_blocks_filename"));
1383                                 exit(1);
1384                         }
1385                         strcpy(bad_blocks_filename, optarg);
1386                         break;
1387                 case 'm':
1388                         reserved_ratio = strtod(optarg, &tmp);
1389                         if ( *tmp || reserved_ratio > 50 ||
1390                              reserved_ratio < 0) {
1391                                 com_err(program_name, 0,
1392                                         _("invalid reserved blocks percent - %s"),
1393                                         optarg);
1394                                 exit(1);
1395                         }
1396                         break;
1397                 case 'n':
1398                         noaction++;
1399                         break;
1400                 case 'o':
1401                         creator_os = optarg;
1402                         break;
1403                 case 'q':
1404                         quiet = 1;
1405                         break;
1406                 case 'r':
1407                         r_opt = strtoul(optarg, &tmp, 0);
1408                         if (*tmp) {
1409                                 com_err(program_name, 0,
1410                                         _("bad revision level - %s"), optarg);
1411                                 exit(1);
1412                         }
1413                         fs_param.s_rev_level = r_opt;
1414                         break;
1415                 case 's':       /* deprecated */
1416                         s_opt = atoi(optarg);
1417                         break;
1418                 case 'I':
1419                         inode_size = strtoul(optarg, &tmp, 0);
1420                         if (*tmp) {
1421                                 com_err(program_name, 0,
1422                                         _("invalid inode size - %s"), optarg);
1423                                 exit(1);
1424                         }
1425                         break;
1426                 case 'v':
1427                         verbose = 1;
1428                         break;
1429                 case 'F':
1430                         force++;
1431                         break;
1432                 case 'L':
1433                         volume_label = optarg;
1434                         break;
1435                 case 'M':
1436                         mount_dir = optarg;
1437                         break;
1438                 case 'N':
1439                         num_inodes = strtoul(optarg, &tmp, 0);
1440                         if (*tmp) {
1441                                 com_err(program_name, 0,
1442                                         _("bad num inodes - %s"), optarg);
1443                                         exit(1);
1444                         }
1445                         break;
1446                 case 'O':
1447                         fs_features = optarg;
1448                         break;
1449                 case 'E':
1450                 case 'R':
1451                         extended_opts = optarg;
1452                         break;
1453                 case 'S':
1454                         super_only = 1;
1455                         break;
1456                 case 't':
1457                         fs_type = optarg;
1458                         break;
1459                 case 'T':
1460                         usage_types = optarg;
1461                         break;
1462                 case 'U':
1463                         fs_uuid = optarg;
1464                         break;
1465                 case 'V':
1466                         /* Print version number and exit */
1467                         show_version_only++;
1468                         break;
1469                 default:
1470                         usage();
1471                 }
1472         }
1473         if ((optind == argc) && !show_version_only)
1474                 usage();
1475         device_name = argv[optind++];
1476
1477         if (!quiet || show_version_only)
1478                 fprintf (stderr, "mke2fs %s (%s)\n", E2FSPROGS_VERSION,
1479                          E2FSPROGS_DATE);
1480
1481         if (show_version_only) {
1482                 fprintf(stderr, _("\tUsing %s\n"),
1483                         error_message(EXT2_ET_BASE));
1484                 exit(0);
1485         }
1486
1487         /*
1488          * If there's no blocksize specified and there is a journal
1489          * device, use it to figure out the blocksize
1490          */
1491         if (blocksize <= 0 && journal_device) {
1492                 ext2_filsys     jfs;
1493                 io_manager      io_ptr;
1494
1495 #ifdef CONFIG_TESTIO_DEBUG
1496                 if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_BLOCK")) {
1497                         io_ptr = test_io_manager;
1498                         test_io_backing_manager = unix_io_manager;
1499                 } else
1500 #endif
1501                         io_ptr = unix_io_manager;
1502                 retval = ext2fs_open(journal_device,
1503                                      EXT2_FLAG_JOURNAL_DEV_OK, 0,
1504                                      0, io_ptr, &jfs);
1505                 if (retval) {
1506                         com_err(program_name, retval,
1507                                 _("while trying to open journal device %s\n"),
1508                                 journal_device);
1509                         exit(1);
1510                 }
1511                 if ((blocksize < 0) && (jfs->blocksize < (unsigned) (-blocksize))) {
1512                         com_err(program_name, 0,
1513                                 _("Journal dev blocksize (%d) smaller than "
1514                                   "minimum blocksize %d\n"), jfs->blocksize,
1515                                 -blocksize);
1516                         exit(1);
1517                 }
1518                 blocksize = jfs->blocksize;
1519                 printf(_("Using journal device's blocksize: %d\n"), blocksize);
1520                 fs_param.s_log_block_size =
1521                         int_log2(blocksize >> EXT2_MIN_BLOCK_LOG_SIZE);
1522                 ext2fs_close(jfs);
1523         }
1524
1525         if (blocksize > sys_page_size) {
1526                 if (!force) {
1527                         com_err(program_name, 0,
1528                                 _("%d-byte blocks too big for system (max %d)"),
1529                                 blocksize, sys_page_size);
1530                         proceed_question();
1531                 }
1532                 fprintf(stderr, _("Warning: %d-byte blocks too big for system "
1533                                   "(max %d), forced to continue\n"),
1534                         blocksize, sys_page_size);
1535         }
1536         if (optind < argc) {
1537                 fs_param.s_blocks_count = parse_num_blocks(argv[optind++],
1538                                 fs_param.s_log_block_size);
1539                 if (!fs_param.s_blocks_count) {
1540                         com_err(program_name, 0,
1541                                 _("invalid blocks count '%s' on device '%s'"),
1542                                 argv[optind - 1], device_name);
1543                         exit(1);
1544                 }
1545         }
1546         if (optind < argc)
1547                 usage();
1548
1549         if (!force)
1550                 check_plausibility(device_name);
1551         check_mount(device_name, force, _("filesystem"));
1552
1553         fs_param.s_log_cluster_size = fs_param.s_log_block_size;
1554
1555         if (noaction && fs_param.s_blocks_count) {
1556                 dev_size = fs_param.s_blocks_count;
1557                 retval = 0;
1558         } else {
1559         retry:
1560                 retval = ext2fs_get_device_size(device_name,
1561                                                 EXT2_BLOCK_SIZE(&fs_param),
1562                                                 &dev_size);
1563                 if ((retval == EFBIG) &&
1564                     (blocksize == 0) &&
1565                     (fs_param.s_log_block_size == 0)) {
1566                         fs_param.s_log_block_size = 2;
1567                         blocksize = 4096;
1568                         goto retry;
1569                 }
1570         }
1571
1572         if (retval == EFBIG) {
1573                 blk64_t big_dev_size;
1574
1575                 if (blocksize < 4096) {
1576                         fs_param.s_log_block_size = 2;
1577                         blocksize = 4096;
1578                 }
1579                 retval = ext2fs_get_device_size2(device_name,
1580                                  EXT2_BLOCK_SIZE(&fs_param), &big_dev_size);
1581                 if (retval)
1582                         goto get_size_failure;
1583                 if (big_dev_size == (1ULL << 32)) {
1584                         dev_size = (blk_t) (big_dev_size - 1);
1585                         goto got_size;
1586                 }
1587                 fprintf(stderr, _("%s: Size of device %s too big "
1588                                   "to be expressed in 32 bits\n\t"
1589                                   "using a blocksize of %d.\n"),
1590                         program_name, device_name, EXT2_BLOCK_SIZE(&fs_param));
1591                 exit(1);
1592         }
1593 get_size_failure:
1594         if (retval && (retval != EXT2_ET_UNIMPLEMENTED)) {
1595                 com_err(program_name, retval,
1596                         _("while trying to determine filesystem size"));
1597                 exit(1);
1598         }
1599 got_size:
1600         if (!fs_param.s_blocks_count) {
1601                 if (retval == EXT2_ET_UNIMPLEMENTED) {
1602                         com_err(program_name, 0,
1603                                 _("Couldn't determine device size; you "
1604                                 "must specify\nthe size of the "
1605                                 "filesystem\n"));
1606                         exit(1);
1607                 } else {
1608                         if (dev_size == 0) {
1609                                 com_err(program_name, 0,
1610                                 _("Device size reported to be zero.  "
1611                                   "Invalid partition specified, or\n\t"
1612                                   "partition table wasn't reread "
1613                                   "after running fdisk, due to\n\t"
1614                                   "a modified partition being busy "
1615                                   "and in use.  You may need to reboot\n\t"
1616                                   "to re-read your partition table.\n"
1617                                   ));
1618                                 exit(1);
1619                         }
1620                         fs_param.s_blocks_count = dev_size;
1621                         if (sys_page_size > EXT2_BLOCK_SIZE(&fs_param))
1622                                 fs_param.s_blocks_count &= ~((sys_page_size /
1623                                            EXT2_BLOCK_SIZE(&fs_param))-1);
1624                 }
1625
1626         } else if (!force && (fs_param.s_blocks_count > dev_size)) {
1627                 com_err(program_name, 0,
1628                         _("Filesystem larger than apparent device size."));
1629                 proceed_question();
1630         }
1631
1632         fs_types = parse_fs_type(fs_type, usage_types, &fs_param, argv[0]);
1633         if (!fs_types) {
1634                 fprintf(stderr, _("Failed to parse fs types list\n"));
1635                 exit(1);
1636         }
1637
1638         /* Figure out what features should be enabled */
1639
1640         tmp = NULL;
1641         if (fs_param.s_rev_level != EXT2_GOOD_OLD_REV) {
1642                 tmp = get_string_from_profile(fs_types, "base_features",
1643                       "sparse_super,filetype,resize_inode,dir_index");
1644                 edit_feature(tmp, &fs_param.s_feature_compat);
1645                 free(tmp);
1646
1647                 /* And which mount options as well */
1648                 tmp = get_string_from_profile(fs_types, "default_mntopts",
1649                                               "acl,user_xattr");
1650                 edit_mntopts(tmp, &fs_param.s_default_mount_opts);
1651                 if (tmp)
1652                         free(tmp);
1653
1654                 for (cpp = fs_types; *cpp; cpp++) {
1655                         tmp = NULL;
1656                         profile_get_string(profile, "fs_types", *cpp,
1657                                            "features", "", &tmp);
1658                         if (tmp && *tmp)
1659                                 edit_feature(tmp, &fs_param.s_feature_compat);
1660                         free(tmp);
1661                 }
1662                 tmp = get_string_from_profile(fs_types, "default_features",
1663                                               "");
1664         }
1665         edit_feature(fs_features ? fs_features : tmp,
1666                      &fs_param.s_feature_compat);
1667         free(tmp);
1668
1669         if (fs_param.s_feature_incompat & EXT3_FEATURE_INCOMPAT_JOURNAL_DEV) {
1670                 fs_types[0] = strdup("journal");
1671                 fs_types[1] = 0;
1672         }
1673
1674         if (verbose) {
1675                 fputs(_("fs_types for mke2fs.conf resolution: "), stdout);
1676                 print_str_list(fs_types);
1677         }
1678
1679         if (r_opt == EXT2_GOOD_OLD_REV &&
1680             (fs_param.s_feature_compat || fs_param.s_feature_incompat ||
1681              fs_param.s_feature_ro_compat)) {
1682                 fprintf(stderr, _("Filesystem features not supported "
1683                                   "with revision 0 filesystems\n"));
1684                 exit(1);
1685         }
1686
1687         if (s_opt > 0) {
1688                 if (r_opt == EXT2_GOOD_OLD_REV) {
1689                         fprintf(stderr, _("Sparse superblocks not supported "
1690                                   "with revision 0 filesystems\n"));
1691                         exit(1);
1692                 }
1693                 fs_param.s_feature_ro_compat |=
1694                         EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER;
1695         } else if (s_opt == 0)
1696                 fs_param.s_feature_ro_compat &=
1697                         ~EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER;
1698
1699         if (journal_size != 0) {
1700                 if (r_opt == EXT2_GOOD_OLD_REV) {
1701                         fprintf(stderr, _("Journals not supported "
1702                                   "with revision 0 filesystems\n"));
1703                         exit(1);
1704                 }
1705                 fs_param.s_feature_compat |=
1706                         EXT3_FEATURE_COMPAT_HAS_JOURNAL;
1707         }
1708
1709         if (fs_param.s_feature_incompat &
1710             EXT3_FEATURE_INCOMPAT_JOURNAL_DEV) {
1711                 reserved_ratio = 0;
1712                 fs_param.s_feature_incompat = EXT3_FEATURE_INCOMPAT_JOURNAL_DEV;
1713                 fs_param.s_feature_compat = 0;
1714                 fs_param.s_feature_ro_compat = 0;
1715         }
1716
1717         if ((fs_param.s_feature_incompat & EXT2_FEATURE_INCOMPAT_META_BG) &&
1718             (fs_param.s_feature_compat & EXT2_FEATURE_COMPAT_RESIZE_INODE)) {
1719                 fprintf(stderr, _("The resize_inode and meta_bg features "
1720                                   "are not compatible.\n"
1721                                   "They can not be both enabled "
1722                                   "simultaneously.\n"));
1723                 exit(1);
1724         }
1725
1726         /* Set first meta blockgroup via an environment variable */
1727         /* (this is mostly for debugging purposes) */
1728         if ((fs_param.s_feature_incompat & EXT2_FEATURE_INCOMPAT_META_BG) &&
1729             ((tmp = getenv("MKE2FS_FIRST_META_BG"))))
1730                 fs_param.s_first_meta_bg = atoi(tmp);
1731
1732         /* Get the hardware sector sizes, if available */
1733         retval = ext2fs_get_device_sectsize(device_name, &lsector_size);
1734         if (retval) {
1735                 com_err(program_name, retval,
1736                         _("while trying to determine hardware sector size"));
1737                 exit(1);
1738         }
1739         retval = ext2fs_get_device_phys_sectsize(device_name, &psector_size);
1740         if (retval) {
1741                 com_err(program_name, retval,
1742                         _("while trying to determine physical sector size"));
1743                 exit(1);
1744         }
1745
1746         if ((tmp = getenv("MKE2FS_DEVICE_SECTSIZE")) != NULL)
1747                 lsector_size = atoi(tmp);
1748         if ((tmp = getenv("MKE2FS_DEVICE_PHYS_SECTSIZE")) != NULL)
1749                 psector_size = atoi(tmp);
1750
1751         /* Older kernels may not have physical/logical distinction */
1752         if (!psector_size)
1753                 psector_size = lsector_size;
1754
1755         if (blocksize <= 0) {
1756                 use_bsize = get_int_from_profile(fs_types, "blocksize", 4096);
1757
1758                 if (use_bsize == -1) {
1759                         use_bsize = sys_page_size;
1760                         if ((linux_version_code < (2*65536 + 6*256)) &&
1761                             (use_bsize > 4096))
1762                                 use_bsize = 4096;
1763                 }
1764                 if (lsector_size && use_bsize < lsector_size)
1765                         use_bsize = lsector_size;
1766                 if ((blocksize < 0) && (use_bsize < (-blocksize)))
1767                         use_bsize = -blocksize;
1768                 blocksize = use_bsize;
1769                 fs_param.s_blocks_count /= blocksize / 1024;
1770         } else {
1771                 if (blocksize < lsector_size) {                 /* Impossible */
1772                         com_err(program_name, EINVAL,
1773                                 _("while setting blocksize; too small "
1774                                   "for device\n"));
1775                         exit(1);
1776                 } else if ((blocksize < psector_size) &&
1777                            (psector_size <= sys_page_size)) {   /* Suboptimal */
1778                         fprintf(stderr, _("Warning: specified blocksize %d is "
1779                                 "less than device physical sectorsize %d\n"),
1780                                 blocksize, psector_size);
1781                 }
1782         }
1783
1784         if (inode_ratio == 0) {
1785                 inode_ratio = get_int_from_profile(fs_types, "inode_ratio",
1786                                                    8192);
1787                 if (inode_ratio < blocksize)
1788                         inode_ratio = blocksize;
1789         }
1790
1791         fs_param.s_log_cluster_size = fs_param.s_log_block_size =
1792                 int_log2(blocksize >> EXT2_MIN_BLOCK_LOG_SIZE);
1793
1794 #ifdef HAVE_BLKID_PROBE_GET_TOPOLOGY
1795         retval = get_device_geometry(device_name, &fs_param, psector_size);
1796         if (retval < 0) {
1797                 fprintf(stderr,
1798                         _("warning: Unable to get device geometry for %s\n"),
1799                         device_name);
1800         } else if (retval) {
1801                 printf(_("%s alignment is offset by %lu bytes.\n"),
1802                        device_name, retval);
1803                 printf(_("This may result in very poor performance, "
1804                           "(re)-partitioning suggested.\n"));
1805         }
1806 #endif
1807
1808         blocksize = EXT2_BLOCK_SIZE(&fs_param);
1809
1810         lazy_itable_init = 0;
1811         if (access("/sys/fs/ext4/features/lazy_itable_init", R_OK) == 0)
1812                 lazy_itable_init = 1;
1813
1814         lazy_itable_init = get_bool_from_profile(fs_types,
1815                                                  "lazy_itable_init",
1816                                                  lazy_itable_init);
1817         discard = get_bool_from_profile(fs_types, "discard" , discard);
1818
1819         /* Get options from profile */
1820         for (cpp = fs_types; *cpp; cpp++) {
1821                 tmp = NULL;
1822                 profile_get_string(profile, "fs_types", *cpp, "options", "", &tmp);
1823                         if (tmp && *tmp)
1824                                 parse_extended_opts(&fs_param, tmp);
1825                         free(tmp);
1826         }
1827
1828         if (extended_opts)
1829                 parse_extended_opts(&fs_param, extended_opts);
1830
1831         /* Since sparse_super is the default, we would only have a problem
1832          * here if it was explicitly disabled.
1833          */
1834         if ((fs_param.s_feature_compat & EXT2_FEATURE_COMPAT_RESIZE_INODE) &&
1835             !(fs_param.s_feature_ro_compat&EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER)) {
1836                 com_err(program_name, 0,
1837                         _("reserved online resize blocks not supported "
1838                           "on non-sparse filesystem"));
1839                 exit(1);
1840         }
1841
1842         if (fs_param.s_blocks_per_group) {
1843                 if (fs_param.s_blocks_per_group < 256 ||
1844                     fs_param.s_blocks_per_group > 8 * (unsigned) blocksize) {
1845                         com_err(program_name, 0,
1846                                 _("blocks per group count out of range"));
1847                         exit(1);
1848                 }
1849         }
1850
1851         if (inode_size == 0)
1852                 inode_size = get_int_from_profile(fs_types, "inode_size", 0);
1853         if (!flex_bg_size && (fs_param.s_feature_incompat &
1854                               EXT4_FEATURE_INCOMPAT_FLEX_BG))
1855                 flex_bg_size = get_int_from_profile(fs_types,
1856                                                     "flex_bg_size", 16);
1857         if (flex_bg_size) {
1858                 if (!(fs_param.s_feature_incompat &
1859                       EXT4_FEATURE_INCOMPAT_FLEX_BG)) {
1860                         com_err(program_name, 0,
1861                                 _("Flex_bg feature not enabled, so "
1862                                   "flex_bg size may not be specified"));
1863                         exit(1);
1864                 }
1865                 fs_param.s_log_groups_per_flex = int_log2(flex_bg_size);
1866         }
1867
1868         if (inode_size && fs_param.s_rev_level >= EXT2_DYNAMIC_REV) {
1869                 if (inode_size < EXT2_GOOD_OLD_INODE_SIZE ||
1870                     inode_size > EXT2_BLOCK_SIZE(&fs_param) ||
1871                     inode_size & (inode_size - 1)) {
1872                         com_err(program_name, 0,
1873                                 _("invalid inode size %d (min %d/max %d)"),
1874                                 inode_size, EXT2_GOOD_OLD_INODE_SIZE,
1875                                 blocksize);
1876                         exit(1);
1877                 }
1878                 fs_param.s_inode_size = inode_size;
1879         }
1880
1881         /* Make sure number of inodes specified will fit in 32 bits */
1882         if (num_inodes == 0) {
1883                 unsigned long long n;
1884                 n = (unsigned long long) fs_param.s_blocks_count * blocksize / inode_ratio;
1885                 if (n > ~0U) {
1886                         com_err(program_name, 0,
1887                             _("too many inodes (%llu), raise inode ratio?"), n);
1888                         exit(1);
1889                 }
1890         } else if (num_inodes > ~0U) {
1891                 com_err(program_name, 0,
1892                         _("too many inodes (%llu), specify < 2^32 inodes"),
1893                           num_inodes);
1894                 exit(1);
1895         }
1896         /*
1897          * Calculate number of inodes based on the inode ratio
1898          */
1899         fs_param.s_inodes_count = num_inodes ? num_inodes :
1900                 ((__u64) fs_param.s_blocks_count * blocksize)
1901                         / inode_ratio;
1902
1903         if ((((long long)fs_param.s_inodes_count) *
1904              (inode_size ? inode_size : EXT2_GOOD_OLD_INODE_SIZE)) >=
1905             (((long long)fs_param.s_blocks_count) *
1906              EXT2_BLOCK_SIZE(&fs_param))) {
1907                 com_err(program_name, 0, _("inode_size (%u) * inodes_count "
1908                                           "(%u) too big for a\n\t"
1909                                           "filesystem with %lu blocks, "
1910                                           "specify higher inode_ratio (-i)\n\t"
1911                                           "or lower inode count (-N).\n"),
1912                         inode_size ? inode_size : EXT2_GOOD_OLD_INODE_SIZE,
1913                         fs_param.s_inodes_count,
1914                         (unsigned long) fs_param.s_blocks_count);
1915                 exit(1);
1916         }
1917
1918         /*
1919          * Calculate number of blocks to reserve
1920          */
1921         fs_param.s_r_blocks_count = (unsigned int) (reserved_ratio *
1922                                         fs_param.s_blocks_count / 100.0);
1923 }
1924
1925 static int should_do_undo(const char *name)
1926 {
1927         errcode_t retval;
1928         io_channel channel;
1929         __u16   s_magic;
1930         struct ext2_super_block super;
1931         io_manager manager = unix_io_manager;
1932         int csum_flag, force_undo;
1933
1934         csum_flag = EXT2_HAS_RO_COMPAT_FEATURE(&fs_param,
1935                                                EXT4_FEATURE_RO_COMPAT_GDT_CSUM);
1936         force_undo = get_int_from_profile(fs_types, "force_undo", 0);
1937         if (!force_undo && (!csum_flag || !lazy_itable_init))
1938                 return 0;
1939
1940         retval = manager->open(name, IO_FLAG_EXCLUSIVE,  &channel);
1941         if (retval) {
1942                 /*
1943                  * We don't handle error cases instead we
1944                  * declare that the file system doesn't exist
1945                  * and let the rest of mke2fs take care of
1946                  * error
1947                  */
1948                 retval = 0;
1949                 goto open_err_out;
1950         }
1951
1952         io_channel_set_blksize(channel, SUPERBLOCK_OFFSET);
1953         retval = io_channel_read_blk(channel, 1, -SUPERBLOCK_SIZE, &super);
1954         if (retval) {
1955                 retval = 0;
1956                 goto err_out;
1957         }
1958
1959 #if defined(WORDS_BIGENDIAN)
1960         s_magic = ext2fs_swab16(super.s_magic);
1961 #else
1962         s_magic = super.s_magic;
1963 #endif
1964
1965         if (s_magic == EXT2_SUPER_MAGIC)
1966                 retval = 1;
1967
1968 err_out:
1969         io_channel_close(channel);
1970
1971 open_err_out:
1972
1973         return retval;
1974 }
1975
1976 static int mke2fs_setup_tdb(const char *name, io_manager *io_ptr)
1977 {
1978         errcode_t retval = 0;
1979         char *tdb_dir, *tdb_file;
1980         char *device_name, *tmp_name;
1981
1982         /*
1983          * Configuration via a conf file would be
1984          * nice
1985          */
1986         tdb_dir = getenv("E2FSPROGS_UNDO_DIR");
1987         if (!tdb_dir)
1988                 profile_get_string(profile, "defaults",
1989                                    "undo_dir", 0, "/var/lib/e2fsprogs",
1990                                    &tdb_dir);
1991
1992         if (!strcmp(tdb_dir, "none") || (tdb_dir[0] == 0) ||
1993             access(tdb_dir, W_OK))
1994                 return 0;
1995
1996         tmp_name = strdup(name);
1997         if (!tmp_name) {
1998         alloc_fn_fail:
1999                 com_err(program_name, ENOMEM, 
2000                         _("Couldn't allocate memory for tdb filename\n"));
2001                 return ENOMEM;
2002         }
2003         device_name = basename(tmp_name);
2004         tdb_file = malloc(strlen(tdb_dir) + 8 + strlen(device_name) + 7 + 1);
2005         if (!tdb_file)
2006                 goto alloc_fn_fail;
2007         sprintf(tdb_file, "%s/mke2fs-%s.e2undo", tdb_dir, device_name);
2008
2009         if (!access(tdb_file, F_OK)) {
2010                 if (unlink(tdb_file) < 0) {
2011                         retval = errno;
2012                         com_err(program_name, retval,
2013                                 _("while trying to delete %s"),
2014                                 tdb_file);
2015                         free(tdb_file);
2016                         return retval;
2017                 }
2018         }
2019
2020         set_undo_io_backing_manager(*io_ptr);
2021         *io_ptr = undo_io_manager;
2022         set_undo_io_backup_file(tdb_file);
2023         printf(_("Overwriting existing filesystem; this can be undone "
2024                  "using the command:\n"
2025                  "    e2undo %s %s\n\n"), tdb_file, name);
2026
2027         free(tdb_file);
2028         free(tmp_name);
2029         return retval;
2030 }
2031
2032 #ifdef __linux__
2033
2034 #ifndef BLKDISCARD
2035 #define BLKDISCARD      _IO(0x12,119)
2036 #endif
2037
2038 #ifndef BLKDISCARDZEROES
2039 #define BLKDISCARDZEROES _IO(0x12,124)
2040 #endif
2041
2042 /*
2043  * Return zero if the discard succeeds, and -1 if the discard fails.
2044  */
2045 static int mke2fs_discard_blocks(ext2_filsys fs)
2046 {
2047         int fd;
2048         int ret;
2049         int blocksize;
2050         __u64 blocks;
2051         __uint64_t range[2];
2052
2053         blocks = fs->super->s_blocks_count;
2054         blocksize = EXT2_BLOCK_SIZE(fs->super);
2055         range[0] = 0;
2056         range[1] = blocks * blocksize;
2057
2058         fd = open64(fs->device_name, O_RDWR);
2059
2060         if (fd > 0) {
2061                 ret = ioctl(fd, BLKDISCARD, &range);
2062                 if (verbose) {
2063                         printf(_("Calling BLKDISCARD from %llu to %llu "),
2064                                (unsigned long long) range[0],
2065                                (unsigned long long) range[1]);
2066                         if (ret)
2067                                 printf(_("failed.\n"));
2068                         else
2069                                 printf(_("succeeded.\n"));
2070                 }
2071                 close(fd);
2072         }
2073         return ret;
2074 }
2075
2076 static int mke2fs_discard_zeroes_data(ext2_filsys fs)
2077 {
2078         int fd;
2079         int ret;
2080         int discard_zeroes_data = 0;
2081
2082         fd = open64(fs->device_name, O_RDWR);
2083
2084         if (fd > 0) {
2085                 ioctl(fd, BLKDISCARDZEROES, &discard_zeroes_data);
2086                 close(fd);
2087         }
2088         return discard_zeroes_data;
2089 }
2090 #else
2091 #define mke2fs_discard_blocks(fs)       1
2092 #define mke2fs_discard_zeroes_data(fs)  0
2093 #endif
2094
2095 int main (int argc, char *argv[])
2096 {
2097         errcode_t       retval = 0;
2098         ext2_filsys     fs;
2099         badblocks_list  bb_list = 0;
2100         unsigned int    journal_blocks;
2101         unsigned int    i;
2102         int             val, hash_alg;
2103         io_manager      io_ptr;
2104         char            tdb_string[40];
2105         char            *hash_alg_str;
2106         int             itable_zeroed = 0;
2107
2108 #ifdef ENABLE_NLS
2109         setlocale(LC_MESSAGES, "");
2110         setlocale(LC_CTYPE, "");
2111         bindtextdomain(NLS_CAT_NAME, LOCALEDIR);
2112         textdomain(NLS_CAT_NAME);
2113 #endif
2114         PRS(argc, argv);
2115
2116 #ifdef CONFIG_TESTIO_DEBUG
2117         if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_BLOCK")) {
2118                 io_ptr = test_io_manager;
2119                 test_io_backing_manager = unix_io_manager;
2120         } else
2121 #endif
2122                 io_ptr = unix_io_manager;
2123
2124         if (should_do_undo(device_name)) {
2125                 retval = mke2fs_setup_tdb(device_name, &io_ptr);
2126                 if (retval)
2127                         exit(1);
2128         }
2129
2130         /*
2131          * Initialize the superblock....
2132          */
2133         retval = ext2fs_initialize(device_name, EXT2_FLAG_EXCLUSIVE, &fs_param,
2134                                    io_ptr, &fs);
2135         if (retval) {
2136                 com_err(device_name, retval, _("while setting up superblock"));
2137                 exit(1);
2138         }
2139
2140         /* Can't undo discard ... */
2141         if (discard && (io_ptr != undo_io_manager)) {
2142                 retval = mke2fs_discard_blocks(fs);
2143
2144                 if (!retval && mke2fs_discard_zeroes_data(fs)) {
2145                         if (verbose)
2146                                 printf(_("Discard succeeded and will return 0s "
2147                                          " - skipping inode table wipe\n"));
2148                         lazy_itable_init = 1;
2149                         itable_zeroed = 1;
2150                 }
2151         }
2152
2153         sprintf(tdb_string, "tdb_data_size=%d", fs->blocksize <= 4096 ?
2154                 32768 : fs->blocksize * 8);
2155         io_channel_set_options(fs->io, tdb_string);
2156
2157         if (fs_param.s_flags & EXT2_FLAGS_TEST_FILESYS)
2158                 fs->super->s_flags |= EXT2_FLAGS_TEST_FILESYS;
2159
2160         if ((fs_param.s_feature_incompat &
2161              (EXT3_FEATURE_INCOMPAT_EXTENTS|EXT4_FEATURE_INCOMPAT_FLEX_BG)) ||
2162             (fs_param.s_feature_ro_compat &
2163              (EXT4_FEATURE_RO_COMPAT_HUGE_FILE|EXT4_FEATURE_RO_COMPAT_GDT_CSUM|
2164               EXT4_FEATURE_RO_COMPAT_DIR_NLINK|
2165               EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE)))
2166                 fs->super->s_kbytes_written = 1;
2167
2168         /*
2169          * Wipe out the old on-disk superblock
2170          */
2171         if (!noaction)
2172                 zap_sector(fs, 2, 6);
2173
2174         /*
2175          * Parse or generate a UUID for the filesystem
2176          */
2177         if (fs_uuid) {
2178                 if (uuid_parse(fs_uuid, fs->super->s_uuid) !=0) {
2179                         com_err(device_name, 0, "could not parse UUID: %s\n",
2180                                 fs_uuid);
2181                         exit(1);
2182                 }
2183         } else
2184                 uuid_generate(fs->super->s_uuid);
2185
2186         /*
2187          * Initialize the directory index variables
2188          */
2189         hash_alg_str = get_string_from_profile(fs_types, "hash_alg",
2190                                                "half_md4");
2191         hash_alg = e2p_string2hash(hash_alg_str);
2192         free(hash_alg_str);
2193         fs->super->s_def_hash_version = (hash_alg >= 0) ? hash_alg :
2194                 EXT2_HASH_HALF_MD4;
2195         uuid_generate((unsigned char *) fs->super->s_hash_seed);
2196
2197         /*
2198          * Periodic checks can be enabled/disabled via config file.
2199          * Note we override the kernel include file's idea of what the default
2200          * check interval (never) should be.  It's a good idea to check at
2201          * least *occasionally*, specially since servers will never rarely get
2202          * to reboot, since Linux is so robust these days.  :-)
2203          *
2204          * 180 days (six months) seems like a good value.
2205          */
2206 #ifdef EXT2_DFL_CHECKINTERVAL
2207 #undef EXT2_DFL_CHECKINTERVAL
2208 #endif
2209 #define EXT2_DFL_CHECKINTERVAL (86400L * 180L)
2210
2211         if (get_bool_from_profile(fs_types, "enable_periodic_fsck", 0)) {
2212                 fs->super->s_checkinterval = EXT2_DFL_CHECKINTERVAL;
2213                 fs->super->s_max_mnt_count = EXT2_DFL_MAX_MNT_COUNT;
2214                 /*
2215                  * Add "jitter" to the superblock's check interval so that we
2216                  * don't check all the filesystems at the same time.  We use a
2217                  * kludgy hack of using the UUID to derive a random jitter value
2218                  */
2219                 for (i = 0, val = 0 ; i < sizeof(fs->super->s_uuid); i++)
2220                         val += fs->super->s_uuid[i];
2221                 fs->super->s_max_mnt_count += val % EXT2_DFL_MAX_MNT_COUNT;
2222         }
2223
2224         /*
2225          * Override the creator OS, if applicable
2226          */
2227         if (creator_os && !set_os(fs->super, creator_os)) {
2228                 com_err (program_name, 0, _("unknown os - %s"), creator_os);
2229                 exit(1);
2230         }
2231
2232         /*
2233          * For the Hurd, we will turn off filetype since it doesn't
2234          * support it.
2235          */
2236         if (fs->super->s_creator_os == EXT2_OS_HURD)
2237                 fs->super->s_feature_incompat &=
2238                         ~EXT2_FEATURE_INCOMPAT_FILETYPE;
2239
2240         /*
2241          * Set the volume label...
2242          */
2243         if (volume_label) {
2244                 memset(fs->super->s_volume_name, 0,
2245                        sizeof(fs->super->s_volume_name));
2246                 strncpy(fs->super->s_volume_name, volume_label,
2247                         sizeof(fs->super->s_volume_name));
2248         }
2249
2250         /*
2251          * Set the last mount directory
2252          */
2253         if (mount_dir) {
2254                 memset(fs->super->s_last_mounted, 0,
2255                        sizeof(fs->super->s_last_mounted));
2256                 strncpy(fs->super->s_last_mounted, mount_dir,
2257                         sizeof(fs->super->s_last_mounted));
2258         }
2259
2260         if (!quiet || noaction)
2261                 show_stats(fs);
2262
2263         if (noaction)
2264                 exit(0);
2265
2266         if (fs->super->s_feature_incompat &
2267             EXT3_FEATURE_INCOMPAT_JOURNAL_DEV) {
2268                 create_journal_dev(fs);
2269                 exit(ext2fs_close(fs) ? 1 : 0);
2270         }
2271
2272         if (bad_blocks_filename)
2273                 read_bb_file(fs, &bb_list, bad_blocks_filename);
2274         if (cflag)
2275                 test_disk(fs, &bb_list);
2276
2277         handle_bad_blocks(fs, bb_list);
2278         fs->stride = fs_stride = fs->super->s_raid_stride;
2279         retval = ext2fs_allocate_tables(fs);
2280         if (retval) {
2281                 com_err(program_name, retval,
2282                         _("while trying to allocate filesystem tables"));
2283                 exit(1);
2284         }
2285         if (super_only) {
2286                 fs->super->s_state |= EXT2_ERROR_FS;
2287                 fs->flags &= ~(EXT2_FLAG_IB_DIRTY|EXT2_FLAG_BB_DIRTY);
2288         } else {
2289                 /* rsv must be a power of two (64kB is MD RAID sb alignment) */
2290                 unsigned int rsv = 65536 / fs->blocksize;
2291                 unsigned long blocks = fs->super->s_blocks_count;
2292                 unsigned long start;
2293                 blk_t ret_blk;
2294
2295 #ifdef ZAP_BOOTBLOCK
2296                 zap_sector(fs, 0, 2);
2297 #endif
2298
2299                 /*
2300                  * Wipe out any old MD RAID (or other) metadata at the end
2301                  * of the device.  This will also verify that the device is
2302                  * as large as we think.  Be careful with very small devices.
2303                  */
2304                 start = (blocks & ~(rsv - 1));
2305                 if (start > rsv)
2306                         start -= rsv;
2307                 if (start > 0)
2308                         retval = ext2fs_zero_blocks(fs, start, blocks - start,
2309                                                     &ret_blk, NULL);
2310
2311                 if (retval) {
2312                         com_err(program_name, retval,
2313                                 _("while zeroing block %u at end of filesystem"),
2314                                 ret_blk);
2315                 }
2316                 write_inode_tables(fs, lazy_itable_init, itable_zeroed);
2317                 create_root_dir(fs);
2318                 create_lost_and_found(fs);
2319                 reserve_inodes(fs);
2320                 create_bad_block_inode(fs, bb_list);
2321                 if (fs->super->s_feature_compat &
2322                     EXT2_FEATURE_COMPAT_RESIZE_INODE) {
2323                         retval = ext2fs_create_resize_inode(fs);
2324                         if (retval) {
2325                                 com_err("ext2fs_create_resize_inode", retval,
2326                                 _("while reserving blocks for online resize"));
2327                                 exit(1);
2328                         }
2329                 }
2330         }
2331
2332         if (journal_device) {
2333                 ext2_filsys     jfs;
2334
2335                 if (!force)
2336                         check_plausibility(journal_device);
2337                 check_mount(journal_device, force, _("journal"));
2338
2339                 retval = ext2fs_open(journal_device, EXT2_FLAG_RW|
2340                                      EXT2_FLAG_JOURNAL_DEV_OK, 0,
2341                                      fs->blocksize, unix_io_manager, &jfs);
2342                 if (retval) {
2343                         com_err(program_name, retval,
2344                                 _("while trying to open journal device %s\n"),
2345                                 journal_device);
2346                         exit(1);
2347                 }
2348                 if (!quiet) {
2349                         printf(_("Adding journal to device %s: "),
2350                                journal_device);
2351                         fflush(stdout);
2352                 }
2353                 retval = ext2fs_add_journal_device(fs, jfs);
2354                 if(retval) {
2355                         com_err (program_name, retval,
2356                                  _("\n\twhile trying to add journal to device %s"),
2357                                  journal_device);
2358                         exit(1);
2359                 }
2360                 if (!quiet)
2361                         printf(_("done\n"));
2362                 ext2fs_close(jfs);
2363                 free(journal_device);
2364         } else if ((journal_size) ||
2365                    (fs_param.s_feature_compat &
2366                     EXT3_FEATURE_COMPAT_HAS_JOURNAL)) {
2367                 journal_blocks = figure_journal_size(journal_size, fs);
2368
2369                 if (super_only) {
2370                         printf(_("Skipping journal creation in super-only mode\n"));
2371                         fs->super->s_journal_inum = EXT2_JOURNAL_INO;
2372                         goto no_journal;
2373                 }
2374
2375                 if (!journal_blocks) {
2376                         fs->super->s_feature_compat &=
2377                                 ~EXT3_FEATURE_COMPAT_HAS_JOURNAL;
2378                         goto no_journal;
2379                 }
2380                 if (!quiet) {
2381                         printf(_("Creating journal (%u blocks): "),
2382                                journal_blocks);
2383                         fflush(stdout);
2384                 }
2385                 retval = ext2fs_add_journal_inode(fs, journal_blocks,
2386                                                   journal_flags);
2387                 if (retval) {
2388                         com_err (program_name, retval,
2389                                  _("\n\twhile trying to create journal"));
2390                         exit(1);
2391                 }
2392                 if (!quiet)
2393                         printf(_("done\n"));
2394         }
2395 no_journal:
2396
2397         if (!quiet)
2398                 printf(_("Writing superblocks and "
2399                        "filesystem accounting information: "));
2400         retval = ext2fs_flush(fs);
2401         if (retval) {
2402                 fprintf(stderr,
2403                         _("\nWarning, had trouble writing out superblocks."));
2404         }
2405         if (!quiet) {
2406                 printf(_("done\n\n"));
2407                 if (!getenv("MKE2FS_SKIP_CHECK_MSG"))
2408                         print_check_message(fs);
2409         }
2410         val = ext2fs_close(fs);
2411         remove_error_table(&et_ext2_error_table);
2412         remove_error_table(&et_prof_error_table);
2413         profile_release(profile);
2414         for (i=0; fs_types[i]; i++)
2415                 free(fs_types[i]);
2416         free(fs_types);
2417         return (retval || val) ? 1 : 0;
2418 }