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