Whamcloud - gitweb
ChangeLog, mke2fs.c:
[tools/e2fsprogs.git] / misc / mke2fs.c
1 /*
2  * mke2fs.c - Make a ext2fs filesystem.
3  * 
4  * Copyright (C) 1994, 1995, 1996, 1997 Theodore Ts'o.
5  *
6  * %Begin-Header%
7  * This file may be redistributed under the terms of the GNU Public
8  * License.
9  * %End-Header%
10  */
11
12 /* Usage: mke2fs [options] device
13  * 
14  * The device may be a block device or a image of one, but this isn't
15  * enforced (but it's not much fun on a character device :-). 
16  */
17
18 #include <stdio.h>
19 #include <string.h>
20 #include <fcntl.h>
21 #include <ctype.h>
22 #include <time.h>
23 #ifdef linux
24 #include <sys/utsname.h>
25 #endif
26 #ifdef HAVE_GETOPT_H
27 #include <getopt.h>
28 #else
29 extern char *optarg;
30 extern int optind;
31 #endif
32 #ifdef HAVE_UNISTD_H
33 #include <unistd.h>
34 #endif
35 #ifdef HAVE_STDLIB_H
36 #include <stdlib.h>
37 #endif
38 #ifdef HAVE_ERRNO_H
39 #include <errno.h>
40 #endif
41 #ifdef HAVE_MNTENT_H
42 #include <mntent.h>
43 #endif
44 #include <sys/ioctl.h>
45 #include <sys/types.h>
46
47 #include <linux/ext2_fs.h>
48
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 "../version.h"
55 #include "nls-enable.h"
56
57 #define STRIDE_LENGTH 8
58
59 #ifndef __sparc__
60 #define ZAP_BOOTBLOCK
61 #endif
62
63 extern int isatty(int);
64 extern FILE *fpopen(const char *cmd, const char *mode);
65
66 const char * program_name = "mke2fs";
67 const char * device_name /* = NULL */;
68
69 /* Command line options */
70 int     cflag;
71 int     verbose;
72 int     quiet;
73 int     super_only;
74 int     force;
75 int     noaction;
76 int     journal_size;
77 int     journal_flags;
78 char    *bad_blocks_filename;
79 __u32   fs_stride;
80
81 struct ext2_super_block param;
82 char *creator_os;
83 char *volume_label;
84 char *mount_dir;
85 char *journal_device;
86 int sync_kludge;        /* Set using the MKE2FS_SYNC env. option */
87
88 static void usage(void)
89 {
90         fprintf(stderr, _("Usage: %s [-c|-t|-l filename] [-b block-size] "
91         "[-f fragment-size]\n\t[-i bytes-per-inode] [-j] [-J journal-options]"
92         " [-N number-of-inodes]\n\t[-m reserved-blocks-percentage] "
93         "[-o creator-os] [-g blocks-per-group]\n\t[-L volume-label] "
94         "[-M last-mounted-directory] [-O feature[,...]]\n\t"
95         "[-r fs-revision] [-R raid_opts] [-qvSV] device [blocks-count]\n"),
96                 program_name);
97         exit(1);
98 }
99
100 static int int_log2(int arg)
101 {
102         int     l = 0;
103
104         arg >>= 1;
105         while (arg) {
106                 l++;
107                 arg >>= 1;
108         }
109         return l;
110 }
111
112 static int int_log10(unsigned int arg)
113 {
114         int     l;
115
116         for (l=0; arg ; l++)
117                 arg = arg / 10;
118         return l;
119 }
120
121 /*
122  * This function sets the default parameters for a filesystem
123  *
124  * The type is specified by the user.  The size is the maximum size
125  * (in megabytes) for which a set of parameters applies, with a size
126  * of zero meaning that it is the default parameter for the type.
127  * Note that order is important in the table below.
128  */
129 static char default_str[] = "default";
130 struct mke2fs_defaults {
131         const char      *type;
132         int             size;
133         int             blocksize;
134         int             inode_ratio;
135 } settings[] = {
136         { default_str, 0, 4096, 8192 },
137         { default_str, 512, 1024, 4096 },
138         { default_str, 3, 1024, 8192 },
139         { "journal", 0, 4096, 8192 },
140         { "news", 0, 4096, 4096 },
141         { "largefile", 0, 4096, 1024 * 1024 },
142         { "largefile4", 0, 4096, 4096 * 1024 },
143         { 0, 0, 0, 0},
144 };
145
146 static void set_fs_defaults(char *fs_type, struct ext2_super_block *super,
147                             int blocksize, int *inode_ratio)
148 {
149         int     megs;
150         int     ratio = 0;
151         struct mke2fs_defaults *p;
152
153         megs = (super->s_blocks_count * (EXT2_BLOCK_SIZE(super) / 1024) /
154                 1024);
155         if (inode_ratio)
156                 ratio = *inode_ratio;
157         if (!fs_type)
158                 fs_type = default_str;
159         for (p = settings; p->type; p++) {
160                 if ((strcmp(p->type, fs_type) != 0) &&
161                     (strcmp(p->type, default_str) != 0))
162                         continue;
163                 if ((p->size != 0) &&
164                     (megs > p->size))
165                         continue;
166                 if (ratio == 0)
167                         *inode_ratio = p->inode_ratio;
168                 if (blocksize == 0) {
169                         super->s_log_frag_size = super->s_log_block_size =
170                                 int_log2(p->blocksize >> EXT2_MIN_BLOCK_LOG_SIZE);
171                 }
172         }
173         if (blocksize == 0)
174                 super->s_blocks_count /= EXT2_BLOCK_SIZE(super) / 1024;
175 }
176
177 /*
178  * Helper function for read_bb_file and test_disk
179  */
180 static void invalid_block(ext2_filsys fs, blk_t blk)
181 {
182         printf(_("Bad block %u out of range; ignored.\n"), blk);
183         return;
184 }
185
186 /*
187  * Reads the bad blocks list from a file
188  */
189 static void read_bb_file(ext2_filsys fs, badblocks_list *bb_list,
190                          const char *bad_blocks_file)
191 {
192         FILE            *f;
193         errcode_t       retval;
194
195         f = fopen(bad_blocks_file, "r");
196         if (!f) {
197                 com_err("read_bad_blocks_file", errno,
198                         _("while trying to open %s"), bad_blocks_file);
199                 exit(1);
200         }
201         retval = ext2fs_read_bb_FILE(fs, f, bb_list, invalid_block);
202         fclose (f);
203         if (retval) {
204                 com_err("ext2fs_read_bb_FILE", retval,
205                         _("while reading in list of bad blocks from file"));
206                 exit(1);
207         }
208 }
209
210 /*
211  * Runs the badblocks program to test the disk
212  */
213 static void test_disk(ext2_filsys fs, badblocks_list *bb_list)
214 {
215         FILE            *f;
216         errcode_t       retval;
217         char            buf[1024];
218
219         sprintf(buf, "badblocks -b %d %s%s %d", fs->blocksize,
220                 quiet ? "" : "-s ", fs->device_name,
221                 fs->super->s_blocks_count);
222         if (verbose)
223                 printf(_("Running command: %s\n"), buf);
224         f = popen(buf, "r");
225         if (!f) {
226                 com_err("popen", errno,
227                         _("while trying run '%s'"), buf);
228                 exit(1);
229         }
230         retval = ext2fs_read_bb_FILE(fs, f, bb_list, invalid_block);
231         pclose(f);
232         if (retval) {
233                 com_err("ext2fs_read_bb_FILE", retval,
234                         _("while processing list of bad blocks from program"));
235                 exit(1);
236         }
237 }
238
239 static void handle_bad_blocks(ext2_filsys fs, badblocks_list bb_list)
240 {
241         int                     i, j;
242         int                     must_be_good;
243         blk_t                   blk;
244         badblocks_iterate       bb_iter;
245         errcode_t               retval;
246         blk_t                   group_block;
247         int                     group;
248         int                     group_bad;
249
250         if (!bb_list)
251                 return;
252         
253         /*
254          * The primary superblock and group descriptors *must* be
255          * good; if not, abort.
256          */
257         must_be_good = fs->super->s_first_data_block + 1 + fs->desc_blocks;
258         for (i = fs->super->s_first_data_block; i <= must_be_good; i++) {
259                 if (badblocks_list_test(bb_list, i)) {
260                         fprintf(stderr, _("Block %d in primary "
261                                 "superblock/group descriptor area bad.\n"), i);
262                         fprintf(stderr, _("Blocks %d through %d must be good "
263                                 "in order to build a filesystem.\n"),
264                                 fs->super->s_first_data_block, must_be_good);
265                         fprintf(stderr, _("Aborting....\n"));
266                         exit(1);
267                 }
268         }
269
270         /*
271          * See if any of the bad blocks are showing up in the backup
272          * superblocks and/or group descriptors.  If so, issue a
273          * warning and adjust the block counts appropriately.
274          */
275         group_block = fs->super->s_first_data_block +
276                 fs->super->s_blocks_per_group;
277         
278         for (i = 1; i < fs->group_desc_count; i++) {
279                 group_bad = 0;
280                 for (j=0; j < fs->desc_blocks+1; j++) {
281                         if (badblocks_list_test(bb_list, group_block +
282                                                 j)) {
283                                 if (!group_bad) 
284                                         fprintf(stderr,
285 _("Warning: the backup superblock/group descriptors at block %d contain\n"
286 "       bad blocks.\n\n"),
287                                                 group_block);
288                                 group_bad++;
289                                 group = ext2fs_group_of_blk(fs, group_block+j);
290                                 fs->group_desc[group].bg_free_blocks_count++;
291                                 fs->super->s_free_blocks_count++;
292                         }
293                 }
294                 group_block += fs->super->s_blocks_per_group;
295         }
296         
297         /*
298          * Mark all the bad blocks as used...
299          */
300         retval = badblocks_list_iterate_begin(bb_list, &bb_iter);
301         if (retval) {
302                 com_err("badblocks_list_iterate_begin", retval,
303                         _("while marking bad blocks as used"));
304                 exit(1);
305         }
306         while (badblocks_list_iterate(bb_iter, &blk)) 
307                 ext2fs_mark_block_bitmap(fs->block_map, blk);
308         badblocks_list_iterate_end(bb_iter);
309 }
310
311 /*
312  * These functions implement a generalized progress meter.
313  */
314 struct progress_struct {
315         char            format[20];
316         char            backup[80];
317         __u32           max;
318 };
319
320 static void progress_init(struct progress_struct *progress,
321                           char *label,__u32 max)
322 {
323         int     i;
324
325         memset(progress, 0, sizeof(struct progress_struct));
326         if (quiet)
327                 return;
328
329         /*
330          * Figure out how many digits we need
331          */
332         i = int_log10(max);
333         sprintf(progress->format, "%%%dd/%%%dld", i, i);
334         memset(progress->backup, '\b', sizeof(progress->backup)-1);
335         progress->backup[sizeof(progress->backup)-1] = 0;
336         if ((2*i)+1 < sizeof(progress->backup))
337                 progress->backup[(2*i)+1] = 0;
338         progress->max = max;
339
340         fputs(label, stdout);
341         fflush(stdout);
342 }
343
344 static void progress_update(struct progress_struct *progress, __u32 val)
345 {
346         if (progress->format[0] == 0)
347                 return;
348         printf(progress->format, val, progress->max);
349         fputs(progress->backup, stdout);
350 }
351
352 static void progress_close(struct progress_struct *progress)
353 {
354         if (progress->format[0] == 0)
355                 return;
356         fputs(_("done                            \n"), stdout);
357 }
358
359
360 /*
361  * Helper function which zeros out _num_ blocks starting at _blk_.  In
362  * case of an error, the details of the error is returned via _ret_blk_
363  * and _ret_count_ if they are non-NULL pointers.  Returns 0 on
364  * success, and an error code on an error.
365  *
366  * As a special case, if the first argument is NULL, then it will
367  * attempt to free the static zeroizing buffer.  (This is to keep
368  * programs that check for memory leaks happy.)
369  */
370 static errcode_t zero_blocks(ext2_filsys fs, blk_t blk, int num,
371                              struct progress_struct *progress,
372                              blk_t *ret_blk, int *ret_count)
373 {
374         int             j, count, next_update, next_update_incr;
375         static char     *buf;
376         errcode_t       retval;
377
378         /* If fs is null, clean up the static buffer and return */
379         if (!fs) {
380                 if (buf) {
381                         free(buf);
382                         buf = 0;
383                 }
384                 return 0;
385         }
386         /* Allocate the zeroizing buffer if necessary */
387         if (!buf) {
388                 buf = malloc(fs->blocksize * STRIDE_LENGTH);
389                 if (!buf) {
390                         com_err("malloc", ENOMEM,
391                                 _("while allocating zeroizing buffer"));
392                         exit(1);
393                 }
394                 memset(buf, 0, fs->blocksize * STRIDE_LENGTH);
395         }
396         /* OK, do the write loop */
397         next_update = 0;
398         next_update_incr = num / 100;
399         if (next_update_incr < 1)
400                 next_update_incr = 1;
401         for (j=0; j < num; j += STRIDE_LENGTH, blk += STRIDE_LENGTH) {
402                 if (num-j > STRIDE_LENGTH)
403                         count = STRIDE_LENGTH;
404                 else
405                         count = num - j;
406                 retval = io_channel_write_blk(fs->io, blk, count, buf);
407                 if (retval) {
408                         if (ret_count)
409                                 *ret_count = count;
410                         if (ret_blk)
411                                 *ret_blk = blk;
412                         return retval;
413                 }
414                 if (progress && j > next_update) {
415                         next_update += num / 100;
416                         progress_update(progress, blk);
417                 }
418         }
419         return 0;
420 }       
421
422 static void write_inode_tables(ext2_filsys fs)
423 {
424         errcode_t       retval;
425         blk_t           blk;
426         int             i, num;
427         struct progress_struct progress;
428
429         if (quiet)
430                 memset(&progress, 0, sizeof(progress));
431         else
432                 progress_init(&progress, _("Writing inode tables: "),
433                               fs->group_desc_count);
434
435         for (i = 0; i < fs->group_desc_count; i++) {
436                 progress_update(&progress, i);
437                 
438                 blk = fs->group_desc[i].bg_inode_table;
439                 num = fs->inode_blocks_per_group;
440
441                 retval = zero_blocks(fs, blk, num, 0, &blk, &num);
442                 if (retval) {
443                         printf(_("\nCould not write %d blocks "
444                                  "in inode table starting at %d: %s\n"),
445                                num, blk, error_message(retval));
446                         exit(1);
447                 }
448                 if (sync_kludge) {
449                         if (sync_kludge == 1)
450                                 sync();
451                         else if ((i % sync_kludge) == 0)
452                                 sync();
453                 }
454         }
455         zero_blocks(0, 0, 0, 0, 0, 0);
456         progress_close(&progress);
457 }
458
459 static void create_root_dir(ext2_filsys fs)
460 {
461         errcode_t       retval;
462         struct ext2_inode       inode;
463
464         retval = ext2fs_mkdir(fs, EXT2_ROOT_INO, EXT2_ROOT_INO, 0);
465         if (retval) {
466                 com_err("ext2fs_mkdir", retval, _("while creating root dir"));
467                 exit(1);
468         }
469         if (geteuid()) {
470                 retval = ext2fs_read_inode(fs, EXT2_ROOT_INO, &inode);
471                 if (retval) {
472                         com_err("ext2fs_read_inode", retval,
473                                 _("while reading root inode"));
474                         exit(1);
475                 }
476                 inode.i_uid = getuid();
477                 if (inode.i_uid)
478                         inode.i_gid = getgid();
479                 retval = ext2fs_write_inode(fs, EXT2_ROOT_INO, &inode);
480                 if (retval) {
481                         com_err("ext2fs_write_inode", retval,
482                                 _("while setting root inode ownership"));
483                         exit(1);
484                 }
485         }
486 }
487
488 static void create_lost_and_found(ext2_filsys fs)
489 {
490         errcode_t               retval;
491         ext2_ino_t              ino;
492         const char              *name = "lost+found";
493         int                     i;
494         int                     lpf_size = 0;
495
496         retval = ext2fs_mkdir(fs, EXT2_ROOT_INO, 0, name);
497         if (retval) {
498                 com_err("ext2fs_mkdir", retval,
499                         _("while creating /lost+found"));
500                 exit(1);
501         }
502
503         retval = ext2fs_lookup(fs, EXT2_ROOT_INO, name, strlen(name), 0, &ino);
504         if (retval) {
505                 com_err("ext2_lookup", retval,
506                         _("while looking up /lost+found"));
507                 exit(1);
508         }
509         
510         for (i=1; i < EXT2_NDIR_BLOCKS; i++) {
511                 if ((lpf_size += fs->blocksize) >= 16*1024)
512                         break;
513                 retval = ext2fs_expand_dir(fs, ino);
514                 if (retval) {
515                         com_err("ext2fs_expand_dir", retval,
516                                 _("while expanding /lost+found"));
517                         exit(1);
518                 }
519         }               
520 }
521
522 static void create_bad_block_inode(ext2_filsys fs, badblocks_list bb_list)
523 {
524         errcode_t       retval;
525         
526         ext2fs_mark_inode_bitmap(fs->inode_map, EXT2_BAD_INO);
527         fs->group_desc[0].bg_free_inodes_count--;
528         fs->super->s_free_inodes_count--;
529         retval = ext2fs_update_bb_inode(fs, bb_list);
530         if (retval) {
531                 com_err("ext2fs_update_bb_inode", retval,
532                         _("while setting bad block inode"));
533                 exit(1);
534         }
535
536 }
537
538 static void reserve_inodes(ext2_filsys fs)
539 {
540         ext2_ino_t      i;
541         int             group;
542
543         for (i = EXT2_ROOT_INO + 1; i < EXT2_FIRST_INODE(fs->super); i++) {
544                 ext2fs_mark_inode_bitmap(fs->inode_map, i);
545                 group = ext2fs_group_of_ino(fs, i);
546                 fs->group_desc[group].bg_free_inodes_count--;
547                 fs->super->s_free_inodes_count--;
548         }
549         ext2fs_mark_ib_dirty(fs);
550 }
551
552 static void zap_sector(ext2_filsys fs, int sect)
553 {
554         char buf[512];
555         int retval;
556
557         memset(buf, 0, 512);
558         
559         io_channel_set_blksize(fs->io, 512);
560         retval = io_channel_write_blk(fs->io, sect, -512, buf);
561         io_channel_set_blksize(fs->io, fs->blocksize);
562         if (retval)
563                 printf(_("Warning: could not erase sector %d: %s\n"), sect,
564                        error_message(retval));
565 }
566
567 static void create_journal_dev(ext2_filsys fs)
568 {
569         struct progress_struct progress;
570         errcode_t               retval;
571         char                    *buf;
572         blk_t                   blk;
573         int                     count;
574
575         retval = ext2fs_create_journal_superblock(fs,
576                                   fs->super->s_blocks_count, 0, &buf);
577         if (retval) {
578                 com_err("create_journal_dev", retval,
579                         _("while initializing journal superblock"));
580                 exit(1);
581         }
582         if (quiet)
583                 memset(&progress, 0, sizeof(progress));
584         else
585                 progress_init(&progress, _("Zeroing journal device: "),
586                               fs->super->s_blocks_count);
587
588         retval = zero_blocks(fs, 0, fs->super->s_blocks_count,
589                              &progress, &blk, &count);
590         if (retval) {
591                 com_err("create_journal_dev", retval,
592                         _("while zeroing journal device (block %u, count %d)"),
593                         blk, count);
594                 exit(1);
595         }
596         zero_blocks(0, 0, 0, 0, 0, 0);
597
598         retval = io_channel_write_blk(fs->io,
599                                       fs->super->s_first_data_block+1,
600                                       1, buf);
601         if (retval) {
602                 com_err("create_journal_dev", retval,
603                         _("while writing journal superblock"));
604                 exit(1);
605         }
606         progress_close(&progress);
607 }
608
609 static void show_stats(ext2_filsys fs)
610 {
611         struct ext2_super_block *s = fs->super;
612         char                    buf[80];
613         blk_t                   group_block;
614         int                     i, need, col_left;
615         
616         if (param.s_blocks_count != s->s_blocks_count)
617                 printf(_("warning: %d blocks unused.\n\n"),
618                        param.s_blocks_count - s->s_blocks_count);
619
620         memset(buf, 0, sizeof(buf));
621         strncpy(buf, s->s_volume_name, sizeof(s->s_volume_name));
622         printf(_("Filesystem label=%s\n"), buf);
623         printf(_("OS type: "));
624         switch (fs->super->s_creator_os) {
625             case EXT2_OS_LINUX: printf ("Linux"); break;
626             case EXT2_OS_HURD:  printf ("GNU/Hurd");   break;
627             case EXT2_OS_MASIX: printf ("Masix"); break;
628             default:            printf (_("(unknown os)"));
629         }
630         printf("\n");
631         printf(_("Block size=%u (log=%u)\n"), fs->blocksize,
632                 s->s_log_block_size);
633         printf(_("Fragment size=%u (log=%u)\n"), fs->fragsize,
634                 s->s_log_frag_size);
635         printf(_("%u inodes, %u blocks\n"), s->s_inodes_count,
636                s->s_blocks_count);
637         printf(_("%u blocks (%2.2f%%) reserved for the super user\n"),
638                 s->s_r_blocks_count,
639                100.0 * s->s_r_blocks_count / s->s_blocks_count);
640         printf(_("First data block=%u\n"), s->s_first_data_block);
641         if (fs->group_desc_count > 1)
642                 printf(_("%u block groups\n"), fs->group_desc_count);
643         else
644                 printf(_("%u block group\n"), fs->group_desc_count);
645         printf(_("%u blocks per group, %u fragments per group\n"),
646                s->s_blocks_per_group, s->s_frags_per_group);
647         printf(_("%u inodes per group\n"), s->s_inodes_per_group);
648
649         if (fs->group_desc_count == 1) {
650                 printf("\n");
651                 return;
652         }
653         
654         printf(_("Superblock backups stored on blocks: "));
655         group_block = s->s_first_data_block;
656         col_left = 0;
657         for (i = 1; i < fs->group_desc_count; i++) {
658                 group_block += s->s_blocks_per_group;
659                 if (!ext2fs_bg_has_super(fs, i))
660                         continue;
661                 if (i != 1)
662                         printf(", ");
663                 need = int_log10(group_block) + 2;
664                 if (need > col_left) {
665                         printf("\n\t");
666                         col_left = 72;
667                 }
668                 col_left -= need;
669                 printf("%u", group_block);
670         }
671         printf("\n\n");
672 }
673
674 /*
675  * Set the S_CREATOR_OS field.  Return true if OS is known,
676  * otherwise, 0.
677  */
678 static int set_os(struct ext2_super_block *sb, char *os)
679 {
680         if (isdigit (*os))
681                 sb->s_creator_os = atoi (os);
682         else if (strcasecmp(os, "linux") == 0)
683                 sb->s_creator_os = EXT2_OS_LINUX;
684         else if (strcasecmp(os, "GNU") == 0 || strcasecmp(os, "hurd") == 0)
685                 sb->s_creator_os = EXT2_OS_HURD;
686         else if (strcasecmp(os, "masix") == 0)
687                 sb->s_creator_os = EXT2_OS_MASIX;
688         else
689                 return 0;
690         return 1;
691 }
692
693 #define PATH_SET "PATH=/sbin"
694
695 static void parse_raid_opts(const char *opts)
696 {
697         char    *buf, *token, *next, *p, *arg;
698         int     len;
699         int     raid_usage = 0;
700
701         len = strlen(opts);
702         buf = malloc(len+1);
703         if (!buf) {
704                 fprintf(stderr, _("Couldn't allocate memory to parse "
705                         "raid options!\n"));
706                 exit(1);
707         }
708         strcpy(buf, opts);
709         for (token = buf; token && *token; token = next) {
710                 p = strchr(token, ',');
711                 next = 0;
712                 if (p) {
713                         *p = 0;
714                         next = p+1;
715                 } 
716                 arg = strchr(token, '=');
717                 if (arg) {
718                         *arg = 0;
719                         arg++;
720                 }
721                 if (strcmp(token, "stride") == 0) {
722                         if (!arg) {
723                                 raid_usage++;
724                                 continue;
725                         }
726                         fs_stride = strtoul(arg, &p, 0);
727                         if (*p || (fs_stride == 0)) {
728                                 fprintf(stderr,
729                                         _("Invalid stride parameter.\n"));
730                                 raid_usage++;
731                                 continue;
732                         }
733                 } else
734                         raid_usage++;
735         }
736         if (raid_usage) {
737                 fprintf(stderr, _("\nBad raid options specified.\n\n"
738                         "Raid options are separated by commas, "
739                         "and may take an argument which\n"
740                         "\tis set off by an equals ('=') sign.\n\n"
741                         "Valid raid options are:\n"
742                         "\tstride=<stride length in blocks>\n\n"));
743                 exit(1);
744         }
745 }       
746
747 static __u32 ok_features[3] = {
748         EXT3_FEATURE_COMPAT_HAS_JOURNAL,        /* Compat */
749         EXT2_FEATURE_INCOMPAT_FILETYPE|         /* Incompat */
750                 EXT3_FEATURE_INCOMPAT_JOURNAL_DEV,
751         EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER     /* R/O compat */
752 };
753
754
755 static void PRS(int argc, char *argv[])
756 {
757         int             c;
758         int             size;
759         char *          tmp;
760         blk_t           group_blk_max = 8192;
761         int             blocksize = 0;
762         int             inode_ratio = 0;
763         int             reserved_ratio = 5;
764         ext2_ino_t      num_inodes = 0;
765         errcode_t       retval;
766         int             sparse_option = 1;
767         char *          oldpath = getenv("PATH");
768         char *          raid_opts = 0;
769         char *          fs_type = 0;
770         const char *    feature_set = "filetype";
771         blk_t           dev_size;
772 #ifdef linux
773         struct          utsname ut;
774 #endif
775
776         /* Update our PATH to include /sbin  */
777         if (oldpath) {
778                 char *newpath;
779                 
780                 newpath = malloc(sizeof (PATH_SET) + 1 + strlen (oldpath));
781                 strcpy (newpath, PATH_SET);
782                 strcat (newpath, ":");
783                 strcat (newpath, oldpath);
784                 putenv (newpath);
785         } else
786                 putenv (PATH_SET);
787
788         tmp = getenv("MKE2FS_SYNC");
789         if (tmp)
790                 sync_kludge = atoi(tmp);
791         
792         setbuf(stdout, NULL);
793         setbuf(stderr, NULL);
794         initialize_ext2_error_table();
795         memset(&param, 0, sizeof(struct ext2_super_block));
796         param.s_rev_level = 1;  /* Create revision 1 filesystems now */
797         
798 #ifdef linux
799         if (uname(&ut)) {
800                 perror("uname");
801                 exit(1);
802         }
803         if ((ut.release[0] == '1') ||
804             (ut.release[0] == '2' && ut.release[1] == '.' &&
805              ut.release[2] < '2' && ut.release[3] == '.')) {
806                 sparse_option = 0;
807                 feature_set = NULL;
808                 param.s_rev_level = 0;
809         }
810 #endif
811         fprintf (stderr, _("mke2fs %s, %s for EXT2 FS %s, %s\n"),
812                  E2FSPROGS_VERSION, E2FSPROGS_DATE,
813                  EXT2FS_VERSION, EXT2FS_DATE);
814         if (argc && *argv)
815                 program_name = *argv;
816         while ((c = getopt (argc, argv,
817                     "b:cf:g:i:jl:m:no:qr:R:s:tvI:J:ST:FL:M:N:O:V")) != EOF)
818                 switch (c) {
819                 case 'b':
820                         blocksize = strtoul(optarg, &tmp, 0);
821                         if (blocksize < 1024 || blocksize > 4096 || *tmp) {
822                                 com_err(program_name, 0,
823                                         _("bad block size - %s"), optarg);
824                                 exit(1);
825                         }
826                         param.s_log_block_size =
827                                 int_log2(blocksize >> EXT2_MIN_BLOCK_LOG_SIZE);
828                         group_blk_max = blocksize * 8;
829                         break;
830                 case 'c':       /* Check for bad blocks */
831                 case 't':       /* deprecated */
832                         cflag = 1;
833                         break;
834                 case 'f':
835                         size = strtoul(optarg, &tmp, 0);
836                         if (size < 1024 || size > 4096 || *tmp) {
837                                 com_err(program_name, 0,
838                                         _("bad fragment size - %s"),
839                                         optarg);
840                                 exit(1);
841                         }
842                         param.s_log_frag_size =
843                                 int_log2(size >> EXT2_MIN_BLOCK_LOG_SIZE);
844                         printf(_("Warning: fragments not supported.  "
845                                "Ignoring -f option\n"));
846                         break;
847                 case 'g':
848                         param.s_blocks_per_group = strtoul(optarg, &tmp, 0);
849                         if (*tmp) {
850                                 com_err(program_name, 0,
851                                         _("Illegal number for blocks per group"));
852                                 exit(1);
853                         }
854                         if ((param.s_blocks_per_group % 8) != 0) {
855                                 com_err(program_name, 0,
856                                 _("blocks per group must be multiple of 8"));
857                                 exit(1);
858                         }
859                         break;
860                 case 'i':
861                         inode_ratio = strtoul(optarg, &tmp, 0);
862                         if (inode_ratio < 1024 || inode_ratio > 4096 * 1024 ||
863                             *tmp) {
864                                 com_err(program_name, 0,
865                                         _("bad inode ratio - %s"), optarg);
866                                 exit(1);
867                         }
868                         break;
869                 case 'J':
870                         parse_journal_opts(optarg);
871                         break;
872                 case 'j':
873                         param.s_feature_compat |=
874                                 EXT3_FEATURE_COMPAT_HAS_JOURNAL;
875                         if (!journal_size)
876                                 journal_size = -1;
877                         break;
878                 case 'l':
879                         bad_blocks_filename = malloc(strlen(optarg)+1);
880                         if (!bad_blocks_filename) {
881                                 com_err(program_name, ENOMEM,
882                                         _("in malloc for bad_blocks_filename"));
883                                 exit(1);
884                         }
885                         strcpy(bad_blocks_filename, optarg);
886                         break;
887                 case 'm':
888                         reserved_ratio = strtoul(optarg, &tmp, 0);
889                         if (reserved_ratio > 50 || *tmp) {
890                                 com_err(program_name, 0,
891                                         _("bad reserved blocks percent - %s"),
892                                         optarg);
893                                 exit(1);
894                         }
895                         break;
896                 case 'n':
897                         noaction++;
898                         break;
899                 case 'o':
900                         creator_os = optarg;
901                         break;
902                 case 'r':
903                         param.s_rev_level = atoi(optarg);
904                         if (param.s_rev_level == EXT2_GOOD_OLD_REV) {
905                                 sparse_option = 0;
906                                 feature_set = NULL;
907                         }
908                         break;
909                 case 's':       /* deprecated */
910                         sparse_option = atoi(optarg);
911                         break;
912 #ifdef EXT2_DYNAMIC_REV
913                 case 'I':
914                         param.s_inode_size = atoi(optarg);
915                         break;
916 #endif
917                 case 'N':
918                         num_inodes = atoi(optarg);
919                         break;
920                 case 'v':
921                         verbose = 1;
922                         break;
923                 case 'q':
924                         quiet = 1;
925                         break;
926                 case 'F':
927                         force = 1;
928                         break;
929                 case 'L':
930                         volume_label = optarg;
931                         break;
932                 case 'M':
933                         mount_dir = optarg;
934                         break;
935                 case 'O':
936                         feature_set = optarg;
937                         break;
938                 case 'R':
939                         raid_opts = optarg;
940                         break;
941                 case 'S':
942                         super_only = 1;
943                         break;
944                 case 'T':
945                         fs_type = optarg;
946                         break;
947                 case 'V':
948                         /* Print version number and exit */
949                         fprintf(stderr, _("\tUsing %s\n"),
950                                 error_message(EXT2_ET_BASE));
951                         exit(0);
952                 default:
953                         usage();
954                 }
955         if (optind == argc)
956                 usage();
957         device_name = argv[optind];
958         optind++;
959         if (optind < argc) {
960                 unsigned long tmp2  = strtoul(argv[optind++], &tmp, 0);
961
962                 if ((*tmp) || (tmp2 > 0xfffffffful)) {
963                         com_err(program_name, 0, _("bad blocks count - %s"),
964                                 argv[optind - 1]);
965                         exit(1);
966                 }
967                 param.s_blocks_count = tmp2;
968         }
969         if (optind < argc)
970                 usage();
971
972         if (raid_opts)
973                 parse_raid_opts(raid_opts);
974
975         /* Parse the user-supplied feature_set, if any. */
976         if (feature_set && !strncasecmp(feature_set, "none", 4))
977                 feature_set = NULL;
978         if (feature_set && e2p_edit_feature(feature_set,
979                                             &param.s_feature_compat,
980                                             ok_features)) {
981                 fprintf(stderr, _("Invalid filesystem option set: %s\n"),
982                         feature_set);
983                 exit(1);
984         }
985
986         if (sparse_option)
987                 param.s_feature_ro_compat |=
988                         EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER;
989
990         if (param.s_rev_level == EXT2_GOOD_OLD_REV &&
991             (param.s_feature_compat || param.s_feature_ro_compat ||
992              param.s_feature_incompat))
993                 param.s_rev_level = 1;  /* Create a revision 1 filesystem */
994
995         if (!force)
996                 check_plausibility(device_name);
997         check_mount(device_name, force, _("filesystem"));
998
999         param.s_log_frag_size = param.s_log_block_size;
1000
1001         if (noaction && param.s_blocks_count) {
1002                 dev_size = param.s_blocks_count;
1003                 retval = 0;
1004         } else
1005                 retval = ext2fs_get_device_size(device_name,
1006                                                 EXT2_BLOCK_SIZE(&param),
1007                                                 &dev_size);
1008         if (retval && (retval != EXT2_ET_UNIMPLEMENTED)) {
1009                 com_err(program_name, retval,
1010                         _("while trying to determine filesystem size"));
1011                 exit(1);
1012         }
1013         if (!param.s_blocks_count) {
1014                 if (retval == EXT2_ET_UNIMPLEMENTED) {
1015                         com_err(program_name, 0,
1016                                 _("Couldn't determine device size; you "
1017                                 "must specify\nthe size of the "
1018                                 "filesystem\n"));
1019                         exit(1);
1020                 } else {
1021                         if (dev_size == 0) {
1022                                 com_err(program_name, 0,
1023                                 _("Device size reported to be zero.  "
1024                                   "Invalid partition specified, or\n\t"
1025                                   "partition table wasn't reread "
1026                                   "after running fdisk, due to\n\t"
1027                                   "a modified partition being busy "
1028                                   "and in use.  You may need to reboot\n\t"
1029                                   "to re-read your partition table.\n"
1030                                   ));
1031                                 exit(1);
1032                         }
1033                         param.s_blocks_count = dev_size;
1034                 }
1035                 
1036         } else if (!force && (param.s_blocks_count > dev_size)) {
1037                 com_err(program_name, 0,
1038                         _("Filesystem larger than apparent filesystem size."));
1039                 proceed_question();
1040         }
1041
1042         /*
1043          * If the user asked for HAS_JOURNAL, then make sure a journal
1044          * gets created.
1045          */
1046         if ((param.s_feature_compat & EXT3_FEATURE_COMPAT_HAS_JOURNAL) &&
1047             !journal_size)
1048                 journal_size = -1;
1049         if (!fs_type &&
1050             (param.s_feature_incompat & EXT3_FEATURE_INCOMPAT_JOURNAL_DEV)) {
1051                 if (!fs_type)
1052                         fs_type = "journal";
1053                 reserved_ratio = 0;
1054         }
1055         set_fs_defaults(fs_type, &param, blocksize, &inode_ratio);
1056
1057         if (param.s_blocks_per_group) {
1058                 if (param.s_blocks_per_group < 256 ||
1059                     param.s_blocks_per_group > group_blk_max || *tmp) {
1060                         com_err(program_name, 0,
1061                                 _("blocks per group count out of range"));
1062                         exit(1);
1063                 }
1064         }
1065
1066         /*
1067          * Calculate number of inodes based on the inode ratio
1068          */
1069         param.s_inodes_count = num_inodes ? num_inodes : 
1070                 ((__u64) param.s_blocks_count * EXT2_BLOCK_SIZE(&param))
1071                         / inode_ratio;
1072
1073         /*
1074          * Calculate number of blocks to reserve
1075          */
1076         param.s_r_blocks_count = (param.s_blocks_count * reserved_ratio) / 100;
1077
1078 }
1079                                         
1080 int main (int argc, char *argv[])
1081 {
1082         errcode_t       retval = 0;
1083         ext2_filsys     fs;
1084         badblocks_list  bb_list = 0;
1085         int             journal_blocks;
1086         int             i, val;
1087
1088 #ifdef ENABLE_NLS
1089         setlocale(LC_MESSAGES, "");
1090         bindtextdomain(NLS_CAT_NAME, LOCALEDIR);
1091         textdomain(NLS_CAT_NAME);
1092 #endif
1093         PRS(argc, argv);
1094
1095         /*
1096          * Initialize the superblock....
1097          */
1098         retval = ext2fs_initialize(device_name, 0, &param,
1099                                    unix_io_manager, &fs);
1100         if (retval) {
1101                 com_err(device_name, retval, _("while setting up superblock"));
1102                 exit(1);
1103         }
1104
1105         /*
1106          * Wipe out the old on-disk superblock
1107          */
1108         if (!noaction) {
1109                 zap_sector(fs, 2);
1110                 zap_sector(fs, 3);
1111         }
1112
1113         /*
1114          * Generate a UUID for it...
1115          */
1116         uuid_generate(fs->super->s_uuid);
1117
1118         /*
1119          * Add "jitter" to the superblock's check interval so that we
1120          * don't check all the filesystems at the same time.  We use a
1121          * kludgy hack of using the UUID to derive a random jitter value.
1122          */
1123         for (i = 0, val = 0 ; i < sizeof(fs->super->s_uuid); i++)
1124                 val += fs->super->s_uuid[i];
1125         fs->super->s_max_mnt_count += val % EXT2_DFL_MAX_MNT_COUNT;
1126
1127         /*
1128          * Override the creator OS, if applicable
1129          */
1130         if (creator_os && !set_os(fs->super, creator_os)) {
1131                 com_err (program_name, 0, _("unknown os - %s"), creator_os);
1132                 exit(1);
1133         }
1134
1135         /*
1136          * For the Hurd, we will turn off filetype since it doesn't
1137          * support it.
1138          */
1139         if (fs->super->s_creator_os == EXT2_OS_HURD)
1140                 fs->super->s_feature_incompat &=
1141                         ~EXT2_FEATURE_INCOMPAT_FILETYPE;
1142
1143         /*
1144          * Set the volume label...
1145          */
1146         if (volume_label) {
1147                 memset(fs->super->s_volume_name, 0,
1148                        sizeof(fs->super->s_volume_name));
1149                 strncpy(fs->super->s_volume_name, volume_label,
1150                         sizeof(fs->super->s_volume_name));
1151         }
1152
1153         /*
1154          * Set the last mount directory
1155          */
1156         if (mount_dir) {
1157                 memset(fs->super->s_last_mounted, 0,
1158                        sizeof(fs->super->s_last_mounted));
1159                 strncpy(fs->super->s_last_mounted, mount_dir,
1160                         sizeof(fs->super->s_last_mounted));
1161         }
1162         
1163         if (!quiet || noaction)
1164                 show_stats(fs);
1165
1166         if (noaction)
1167                 exit(0);
1168
1169         if (fs->super->s_feature_incompat &
1170             EXT3_FEATURE_INCOMPAT_JOURNAL_DEV) {
1171                 create_journal_dev(fs);
1172                 ext2fs_close(fs);
1173                 exit(0);
1174         }
1175
1176         if (bad_blocks_filename)
1177                 read_bb_file(fs, &bb_list, bad_blocks_filename);
1178         if (cflag)
1179                 test_disk(fs, &bb_list);
1180
1181         handle_bad_blocks(fs, bb_list);
1182         fs->stride = fs_stride;
1183         retval = ext2fs_allocate_tables(fs);
1184         if (retval) {
1185                 com_err(program_name, retval,
1186                         _("while trying to allocate filesystem tables"));
1187                 exit(1);
1188         }
1189         if (super_only) {
1190                 fs->super->s_state |= EXT2_ERROR_FS;
1191                 fs->flags &= ~(EXT2_FLAG_IB_DIRTY|EXT2_FLAG_BB_DIRTY);
1192         } else {
1193                 int rsv = 65536 / EXT2_BLOCK_SIZE(fs->super);
1194                 unsigned long blocks = fs->super->s_blocks_count;
1195                 unsigned long start = (blocks & ~(rsv - 1)) - rsv;
1196                 blk_t ret_blk;
1197
1198 #ifdef ZAP_BOOTBLOCK
1199                 zap_sector(fs, 0);
1200 #endif
1201                 /*
1202                  * Wipe out any old MD RAID (or other) metadata at the end
1203                  * of the device.  This will also verify that the device is
1204                  * as large as we think it is.
1205                  */
1206                 retval = zero_blocks(fs, start, blocks - start,
1207                                      NULL, &ret_blk, NULL);
1208                 if (retval) {
1209                         com_err(program_name, retval,
1210                                 _("zeroing block %u at end of filesystem"),
1211                                 ret_blk);
1212                         exit(1);
1213                 }
1214                 write_inode_tables(fs);
1215                 create_root_dir(fs);
1216                 create_lost_and_found(fs);
1217                 reserve_inodes(fs);
1218                 create_bad_block_inode(fs, bb_list);
1219         }
1220
1221         if (journal_device) {
1222                 ext2_filsys     jfs;
1223                 
1224                 if (!force)
1225                         check_plausibility(journal_device); 
1226                 check_mount(journal_device, force, _("journal"));
1227
1228                 retval = ext2fs_open(journal_device, EXT2_FLAG_RW|
1229                                      EXT2_FLAG_JOURNAL_DEV_OK, 0,
1230                                      fs->blocksize, unix_io_manager, &jfs);
1231                 if (retval) {
1232                         com_err(program_name, retval,
1233                                 _("while trying to open journal device %s\n"),
1234                                 journal_device);
1235                         exit(1);
1236                 }
1237                 if (!quiet) {
1238                         printf(_("Creating journal on device %s: "), 
1239                                journal_device);
1240                         fflush(stdout);
1241                 }
1242                 retval = ext2fs_add_journal_device(fs, jfs);
1243                 if(retval) {
1244                         com_err (program_name, retval, 
1245                                  _("\n\twhile trying to add journal to device %s"), 
1246                                  journal_device);
1247                         exit(1);
1248                 }
1249                 if (!quiet)
1250                         printf(_("done\n"));
1251                 ext2fs_close(jfs);
1252         } else if (journal_size) {
1253                 journal_blocks = figure_journal_size(journal_size, fs);
1254
1255                 if (!journal_blocks) {
1256                         fs->super->s_feature_compat &=
1257                                 ~EXT3_FEATURE_COMPAT_HAS_JOURNAL;
1258                         goto no_journal;
1259                 }
1260                 if (!quiet) {
1261                         printf(_("Creating journal (%d blocks): "),
1262                                journal_blocks);
1263                         fflush(stdout);
1264                 }
1265                 retval = ext2fs_add_journal_inode(fs, journal_blocks,
1266                                                   journal_flags);
1267                 if (retval) {
1268                         com_err (program_name, retval,
1269                                  _("\n\twhile trying to create journal"));
1270                         exit(1);
1271                 }
1272                 if (!quiet)
1273                         printf(_("done\n"));
1274         }
1275 no_journal:
1276
1277         if (!quiet)
1278                 printf(_("Writing superblocks and "
1279                        "filesystem accounting information: "));
1280         retval = ext2fs_flush(fs);
1281         if (retval) {
1282                 printf(_("\nWarning, had trouble writing out superblocks."));
1283         }
1284         if (!quiet) {
1285                 printf(_("done\n\n"));
1286                 printf(_("This filesystem will be automatically "
1287                          "checked every %d mounts or\n"
1288                          "%g days, whichever comes first.  "
1289                          "Use tune2fs -c or -i to override.\n"),
1290                        fs->super->s_max_mnt_count,
1291                        (double)fs->super->s_checkinterval / (3600 * 24));
1292         }
1293         ext2fs_close(fs);
1294         return 0;
1295 }