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