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