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