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