Whamcloud - gitweb
tune2fs: update journal super block when changing UUID for fs.
[tools/e2fsprogs.git] / misc / tune2fs.c
1 /*
2  * tune2fs.c - Change the file system parameters on an ext2 file system
3  *
4  * Copyright (C) 1992, 1993, 1994  Remy Card <card@masi.ibp.fr>
5  *                                 Laboratoire MASI, Institut Blaise Pascal
6  *                                 Universite Pierre et Marie Curie (Paris VI)
7  *
8  * Copyright 1995, 1996, 1997, 1998, 1999, 2000 by Theodore Ts'o.
9  *
10  * %Begin-Header%
11  * This file may be redistributed under the terms of the GNU Public
12  * License.
13  * %End-Header%
14  */
15
16 /*
17  * History:
18  * 93/06/01     - Creation
19  * 93/10/31     - Added the -c option to change the maximal mount counts
20  * 93/12/14     - Added -l flag to list contents of superblock
21  *                M.J.E. Mol (marcel@duteca.et.tudelft.nl)
22  *                F.W. ten Wolde (franky@duteca.et.tudelft.nl)
23  * 93/12/29     - Added the -e option to change errors behavior
24  * 94/02/27     - Ported to use the ext2fs library
25  * 94/03/06     - Added the checks interval from Uwe Ohse (uwe@tirka.gun.de)
26  */
27
28 #define _XOPEN_SOURCE 600 /* for inclusion of strptime() */
29 #include "config.h"
30 #include <fcntl.h>
31 #include <grp.h>
32 #ifdef HAVE_GETOPT_H
33 #include <getopt.h>
34 #else
35 extern char *optarg;
36 extern int optind;
37 #endif
38 #include <pwd.h>
39 #include <stdio.h>
40 #ifdef HAVE_STDLIB_H
41 #include <stdlib.h>
42 #endif
43 #ifdef HAVE_STRINGS_H
44 #include <strings.h>    /* for strcasecmp() */
45 #else
46 #define _BSD_SOURCE     /* for inclusion of strcasecmp() via <string.h> */
47 #endif
48 #include <string.h>
49 #include <time.h>
50 #include <unistd.h>
51 #include <sys/types.h>
52 #include <libgen.h>
53 #include <limits.h>
54
55 #include "ext2fs/ext2_fs.h"
56 #include "ext2fs/ext2fs.h"
57 #include "et/com_err.h"
58 #include "uuid/uuid.h"
59 #include "e2p/e2p.h"
60 #include "jfs_user.h"
61 #include "util.h"
62 #include "blkid/blkid.h"
63 #include "quota/quotaio.h"
64
65 #include "../version.h"
66 #include "nls-enable.h"
67
68 #define QOPT_ENABLE     (1)
69 #define QOPT_DISABLE    (-1)
70
71 extern int ask_yn(const char *string, int def);
72
73 const char *program_name = "tune2fs";
74 char *device_name;
75 char *new_label, *new_last_mounted, *new_UUID;
76 char *io_options;
77 static int c_flag, C_flag, e_flag, f_flag, g_flag, i_flag, l_flag, L_flag;
78 static int m_flag, M_flag, Q_flag, r_flag, s_flag = -1, u_flag, U_flag, T_flag;
79 static int I_flag;
80 static int clear_mmp;
81 static time_t last_check_time;
82 static int print_label;
83 static int max_mount_count, mount_count, mount_flags;
84 static unsigned long interval;
85 static blk64_t reserved_blocks;
86 static double reserved_ratio;
87 static unsigned long resgid, resuid;
88 static unsigned short errors;
89 static int open_flag;
90 static char *features_cmd;
91 static char *mntopts_cmd;
92 static int stride, stripe_width;
93 static int stride_set, stripe_width_set;
94 static char *extended_cmd;
95 static unsigned long new_inode_size;
96 static char *ext_mount_opts;
97 static int usrquota, grpquota;
98
99 int journal_size, journal_flags;
100 char *journal_device;
101 static blk64_t journal_location = ~0LL;
102
103 static struct list_head blk_move_list;
104
105 struct blk_move {
106         struct list_head list;
107         blk64_t old_loc;
108         blk64_t new_loc;
109 };
110
111
112 static const char *please_fsck = N_("Please run e2fsck on the filesystem.\n");
113
114 #ifdef CONFIG_BUILD_FINDFS
115 void do_findfs(int argc, char **argv);
116 #endif
117
118 static void usage(void)
119 {
120         fprintf(stderr,
121                 _("Usage: %s [-c max_mounts_count] [-e errors_behavior] "
122                   "[-g group]\n"
123                   "\t[-i interval[d|m|w]] [-j] [-J journal_options] [-l]\n"
124                   "\t[-m reserved_blocks_percent] "
125                   "[-o [^]mount_options[,...]] [-p mmp_update_interval]\n"
126                   "\t[-r reserved_blocks_count] [-u user] [-C mount_count] "
127                   "[-L volume_label]\n"
128                   "\t[-M last_mounted_dir] [-O [^]feature[,...]]\n"
129 #ifdef CONFIG_QUOTA
130                   "\t[-Q quota_options]\n"
131 #endif
132                   "\t[-E extended-option[,...]] [-T last_check_time] "
133                   "[-U UUID]\n\t[ -I new_inode_size ] device\n"), program_name);
134         exit(1);
135 }
136
137 static __u32 ok_features[3] = {
138         /* Compat */
139         EXT3_FEATURE_COMPAT_HAS_JOURNAL |
140                 EXT2_FEATURE_COMPAT_DIR_INDEX,
141         /* Incompat */
142         EXT2_FEATURE_INCOMPAT_FILETYPE |
143                 EXT3_FEATURE_INCOMPAT_EXTENTS |
144                 EXT4_FEATURE_INCOMPAT_FLEX_BG |
145                 EXT4_FEATURE_INCOMPAT_MMP,
146         /* R/O compat */
147         EXT2_FEATURE_RO_COMPAT_LARGE_FILE |
148                 EXT4_FEATURE_RO_COMPAT_HUGE_FILE|
149                 EXT4_FEATURE_RO_COMPAT_DIR_NLINK|
150                 EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE|
151                 EXT4_FEATURE_RO_COMPAT_GDT_CSUM |
152 #ifdef CONFIG_QUOTA
153                 EXT4_FEATURE_RO_COMPAT_QUOTA |
154 #endif
155                 EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER
156 };
157
158 static __u32 clear_ok_features[3] = {
159         /* Compat */
160         EXT3_FEATURE_COMPAT_HAS_JOURNAL |
161                 EXT2_FEATURE_COMPAT_RESIZE_INODE |
162                 EXT2_FEATURE_COMPAT_DIR_INDEX,
163         /* Incompat */
164         EXT2_FEATURE_INCOMPAT_FILETYPE |
165                 EXT4_FEATURE_INCOMPAT_FLEX_BG |
166                 EXT4_FEATURE_INCOMPAT_MMP,
167         /* R/O compat */
168         EXT2_FEATURE_RO_COMPAT_LARGE_FILE |
169                 EXT4_FEATURE_RO_COMPAT_HUGE_FILE|
170                 EXT4_FEATURE_RO_COMPAT_DIR_NLINK|
171                 EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE|
172 #ifdef CONFIG_QUOTA
173                 EXT4_FEATURE_RO_COMPAT_QUOTA |
174 #endif
175                 EXT4_FEATURE_RO_COMPAT_GDT_CSUM
176 };
177
178 /**
179  * Try to get journal super block if any
180  */
181 static int get_journal_sb(ext2_filsys jfs, char buf[SUPERBLOCK_SIZE])
182 {
183         int retval;
184         int start;
185         journal_superblock_t *jsb;
186
187         if (!(jfs->super->s_feature_incompat &
188             EXT3_FEATURE_INCOMPAT_JOURNAL_DEV)) {
189                 return EXT2_ET_UNSUPP_FEATURE;
190         }
191
192         /* Get the journal superblock */
193         if ((retval = io_channel_read_blk64(jfs->io,
194             ext2fs_journal_sb_start(jfs->blocksize), -SUPERBLOCK_SIZE, buf))) {
195                 com_err(program_name, retval, "%s",
196                 _("while reading journal superblock"));
197                 return retval;
198         }
199
200         jsb = (journal_superblock_t *) buf;
201         if ((jsb->s_header.h_magic != (unsigned)ntohl(JFS_MAGIC_NUMBER)) ||
202             (jsb->s_header.h_blocktype != (unsigned)ntohl(JFS_SUPERBLOCK_V2))) {
203                 fputs(_("Journal superblock not found!\n"), stderr);
204                 return EXT2_ET_BAD_MAGIC;
205         }
206
207         return 0;
208 }
209
210 /*
211  * Remove an external journal from the filesystem
212  */
213 static int remove_journal_device(ext2_filsys fs)
214 {
215         char            *journal_path;
216         ext2_filsys     jfs;
217         char            buf[SUPERBLOCK_SIZE];
218         journal_superblock_t    *jsb;
219         int             i, nr_users;
220         errcode_t       retval;
221         int             commit_remove_journal = 0;
222         io_manager      io_ptr;
223         int start;
224
225         if (f_flag)
226                 commit_remove_journal = 1; /* force removal even if error */
227
228         uuid_unparse(fs->super->s_journal_uuid, buf);
229         journal_path = blkid_get_devname(NULL, "UUID", buf);
230
231         if (!journal_path) {
232                 journal_path =
233                         ext2fs_find_block_device(fs->super->s_journal_dev);
234                 if (!journal_path)
235                         goto no_valid_journal;
236         }
237
238 #ifdef CONFIG_TESTIO_DEBUG
239         if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_BLOCK")) {
240                 io_ptr = test_io_manager;
241                 test_io_backing_manager = unix_io_manager;
242         } else
243 #endif
244                 io_ptr = unix_io_manager;
245         retval = ext2fs_open(journal_path, EXT2_FLAG_RW|
246                              EXT2_FLAG_JOURNAL_DEV_OK, 0,
247                              fs->blocksize, io_ptr, &jfs);
248         if (retval) {
249                 com_err(program_name, retval, "%s",
250                         _("while trying to open external journal"));
251                 goto no_valid_journal;
252         }
253
254         if ((retval = get_journal_sb(jfs, buf))) {
255                 if (retval == EXT2_ET_UNSUPP_FEATURE)
256                         fprintf(stderr, _("%s is not a journal device.\n"),
257                                 journal_path);
258                 goto no_valid_journal;
259         }
260
261         jsb = (journal_superblock_t *) buf;
262         /* Find the filesystem UUID */
263         nr_users = ntohl(jsb->s_nr_users);
264         for (i = 0; i < nr_users; i++) {
265                 if (memcmp(fs->super->s_uuid, &jsb->s_users[i * 16], 16) == 0)
266                         break;
267         }
268         if (i >= nr_users) {
269                 fputs(_("Filesystem's UUID not found on journal device.\n"),
270                       stderr);
271                 commit_remove_journal = 1;
272                 goto no_valid_journal;
273         }
274         nr_users--;
275         for (i = 0; i < nr_users; i++)
276                 memcpy(&jsb->s_users[i * 16], &jsb->s_users[(i + 1) * 16], 16);
277         jsb->s_nr_users = htonl(nr_users);
278
279         /* Write back the journal superblock */
280         if ((retval = io_channel_write_blk64(jfs->io, start,
281             -SUPERBLOCK_SIZE, buf))) {
282                 com_err(program_name, retval,
283                         "while writing journal superblock.");
284                 goto no_valid_journal;
285         }
286
287         commit_remove_journal = 1;
288
289 no_valid_journal:
290         if (commit_remove_journal == 0) {
291                 fputs(_("Cannot locate journal device. It was NOT removed\n"
292                         "Use -f option to remove missing journal device.\n"),
293                       stderr);
294                 return 1;
295         }
296         fs->super->s_journal_dev = 0;
297         uuid_clear(fs->super->s_journal_uuid);
298         ext2fs_mark_super_dirty(fs);
299         fputs(_("Journal removed\n"), stdout);
300         free(journal_path);
301
302         return 0;
303 }
304
305 /* Helper function for remove_journal_inode */
306 static int release_blocks_proc(ext2_filsys fs, blk64_t *blocknr,
307                                e2_blkcnt_t blockcnt EXT2FS_ATTR((unused)),
308                                blk64_t ref_block EXT2FS_ATTR((unused)),
309                                int ref_offset EXT2FS_ATTR((unused)),
310                                void *private EXT2FS_ATTR((unused)))
311 {
312         blk64_t block;
313         int     group;
314
315         block = *blocknr;
316         ext2fs_unmark_block_bitmap2(fs->block_map, block);
317         group = ext2fs_group_of_blk2(fs, block);
318         ext2fs_bg_free_blocks_count_set(fs, group, ext2fs_bg_free_blocks_count(fs, group) + 1);
319         ext2fs_group_desc_csum_set(fs, group);
320         ext2fs_free_blocks_count_add(fs->super, EXT2FS_CLUSTER_RATIO(fs));
321         return 0;
322 }
323
324 /*
325  * Remove the journal inode from the filesystem
326  */
327 static errcode_t remove_journal_inode(ext2_filsys fs)
328 {
329         struct ext2_inode       inode;
330         errcode_t               retval;
331         ino_t                   ino = fs->super->s_journal_inum;
332
333         retval = ext2fs_read_inode(fs, ino,  &inode);
334         if (retval) {
335                 com_err(program_name, retval, "%s",
336                         _("while reading journal inode"));
337                 return retval;
338         }
339         if (ino == EXT2_JOURNAL_INO) {
340                 retval = ext2fs_read_bitmaps(fs);
341                 if (retval) {
342                         com_err(program_name, retval, "%s",
343                                 _("while reading bitmaps"));
344                         return retval;
345                 }
346                 retval = ext2fs_block_iterate3(fs, ino,
347                                                BLOCK_FLAG_READ_ONLY, NULL,
348                                                release_blocks_proc, NULL);
349                 if (retval) {
350                         com_err(program_name, retval, "%s",
351                                 _("while clearing journal inode"));
352                         return retval;
353                 }
354                 memset(&inode, 0, sizeof(inode));
355                 ext2fs_mark_bb_dirty(fs);
356                 fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
357         } else
358                 inode.i_flags &= ~EXT2_IMMUTABLE_FL;
359         retval = ext2fs_write_inode(fs, ino, &inode);
360         if (retval) {
361                 com_err(program_name, retval, "%s",
362                         _("while writing journal inode"));
363                 return retval;
364         }
365         fs->super->s_journal_inum = 0;
366         ext2fs_mark_super_dirty(fs);
367
368         return 0;
369 }
370
371 /*
372  * Update the default mount options
373  */
374 static int update_mntopts(ext2_filsys fs, char *mntopts)
375 {
376         struct ext2_super_block *sb = fs->super;
377
378         if (e2p_edit_mntopts(mntopts, &sb->s_default_mount_opts, ~0)) {
379                 fprintf(stderr, _("Invalid mount option set: %s\n"),
380                         mntopts);
381                 return 1;
382         }
383         ext2fs_mark_super_dirty(fs);
384
385         return 0;
386 }
387
388 static int check_fsck_needed(ext2_filsys fs)
389 {
390         if (fs->super->s_state & EXT2_VALID_FS)
391                 return 0;
392         printf("\n%s\n", _(please_fsck));
393         if (mount_flags & EXT2_MF_READONLY)
394                 printf("%s", _("(and reboot afterwards!)\n"));
395         return 1;
396 }
397
398 static void request_fsck_afterwards(ext2_filsys fs)
399 {
400         static int requested = 0;
401
402         if (requested++)
403                 return;
404         fs->super->s_state &= ~EXT2_VALID_FS;
405         printf("\n%s\n", _(please_fsck));
406         if (mount_flags & EXT2_MF_READONLY)
407                 printf("%s", _("(and reboot afterwards!)\n"));
408 }
409
410 /*
411  * Update the feature set as provided by the user.
412  */
413 static int update_feature_set(ext2_filsys fs, char *features)
414 {
415         struct ext2_super_block *sb = fs->super;
416         struct ext2_group_desc *gd;
417         __u32           old_features[3];
418         dgrp_t          i;
419         int             type_err;
420         unsigned int    mask_err;
421
422 #define FEATURE_ON(type, mask) (!(old_features[(type)] & (mask)) && \
423                                 ((&sb->s_feature_compat)[(type)] & (mask)))
424 #define FEATURE_OFF(type, mask) ((old_features[(type)] & (mask)) && \
425                                  !((&sb->s_feature_compat)[(type)] & (mask)))
426 #define FEATURE_CHANGED(type, mask) ((mask) & \
427                      (old_features[(type)] ^ (&sb->s_feature_compat)[(type)]))
428
429         old_features[E2P_FEATURE_COMPAT] = sb->s_feature_compat;
430         old_features[E2P_FEATURE_INCOMPAT] = sb->s_feature_incompat;
431         old_features[E2P_FEATURE_RO_INCOMPAT] = sb->s_feature_ro_compat;
432
433         if (e2p_edit_feature2(features, &sb->s_feature_compat,
434                               ok_features, clear_ok_features,
435                               &type_err, &mask_err)) {
436                 if (!mask_err)
437                         fprintf(stderr,
438                                 _("Invalid filesystem option set: %s\n"),
439                                 features);
440                 else if (type_err & E2P_FEATURE_NEGATE_FLAG)
441                         fprintf(stderr, _("Clearing filesystem feature '%s' "
442                                           "not supported.\n"),
443                                 e2p_feature2string(type_err &
444                                                    E2P_FEATURE_TYPE_MASK,
445                                                    mask_err));
446                 else
447                         fprintf(stderr, _("Setting filesystem feature '%s' "
448                                           "not supported.\n"),
449                                 e2p_feature2string(type_err, mask_err));
450                 return 1;
451         }
452
453         if (FEATURE_OFF(E2P_FEATURE_COMPAT, EXT3_FEATURE_COMPAT_HAS_JOURNAL)) {
454                 if ((mount_flags & EXT2_MF_MOUNTED) &&
455                     !(mount_flags & EXT2_MF_READONLY)) {
456                         fputs(_("The has_journal feature may only be "
457                                 "cleared when the filesystem is\n"
458                                 "unmounted or mounted "
459                                 "read-only.\n"), stderr);
460                         return 1;
461                 }
462                 if ((sb->s_feature_incompat &
463                     EXT3_FEATURE_INCOMPAT_RECOVER) &&
464                     f_flag < 2) {
465                         fputs(_("The needs_recovery flag is set.  "
466                                 "Please run e2fsck before clearing\n"
467                                 "the has_journal flag.\n"), stderr);
468                         return 1;
469                 }
470                 if (sb->s_journal_inum) {
471                         if (remove_journal_inode(fs))
472                                 return 1;
473                 }
474                 if (sb->s_journal_dev) {
475                         if (remove_journal_device(fs))
476                                 return 1;
477                 }
478         }
479
480         if (FEATURE_ON(E2P_FEATURE_RO_INCOMPAT,
481                 EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER)) {
482                 if (sb->s_feature_incompat &
483                         EXT2_FEATURE_INCOMPAT_META_BG) {
484                         fputs(_("Setting filesystem feature 'sparse_super' "
485                                 "not supported\nfor filesystems with "
486                                 "the meta_bg feature enabled.\n"),
487                                 stderr);
488                         return 1;
489                 }
490         }
491
492         if (FEATURE_ON(E2P_FEATURE_INCOMPAT, EXT4_FEATURE_INCOMPAT_MMP)) {
493                 int error;
494
495                 if ((mount_flags & EXT2_MF_MOUNTED) ||
496                     (mount_flags & EXT2_MF_READONLY)) {
497                         fputs(_("The multiple mount protection feature can't\n"
498                                 "be set if the filesystem is mounted or\n"
499                                 "read-only.\n"), stderr);
500                         return 1;
501                 }
502
503                 error = ext2fs_mmp_init(fs);
504                 if (error) {
505                         fputs(_("\nError while enabling multiple mount "
506                                 "protection feature."), stderr);
507                         return 1;
508                 }
509
510                 /*
511                  * We want to update group desc with the new free blocks count
512                  */
513                 fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
514
515                 printf(_("Multiple mount protection has been enabled "
516                          "with update interval %ds.\n"),
517                        sb->s_mmp_update_interval);
518         }
519
520         if (FEATURE_OFF(E2P_FEATURE_INCOMPAT, EXT4_FEATURE_INCOMPAT_MMP)) {
521                 int error;
522
523                 if (mount_flags & EXT2_MF_READONLY) {
524                         fputs(_("The multiple mount protection feature cannot\n"
525                                 "be disabled if the filesystem is readonly.\n"),
526                                 stderr);
527                         return 1;
528                 }
529
530                 error = ext2fs_read_bitmaps(fs);
531                 if (error) {
532                         fputs(_("Error while reading bitmaps\n"), stderr);
533                         return 1;
534                 }
535
536                 error = ext2fs_mmp_read(fs, sb->s_mmp_block, NULL);
537                 if (error) {
538                         struct mmp_struct *mmp_cmp = fs->mmp_cmp;
539
540                         if (error == EXT2_ET_MMP_MAGIC_INVALID)
541                                 printf(_("Magic number in MMP block does not "
542                                          "match. expected: %x, actual: %x\n"),
543                                          EXT4_MMP_MAGIC, mmp_cmp->mmp_magic);
544                         else
545                                 com_err(program_name, error, "%s",
546                                         _("while reading MMP block."));
547                         goto mmp_error;
548                 }
549
550                 /* We need to force out the group descriptors as well */
551                 fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
552                 ext2fs_block_alloc_stats2(fs, sb->s_mmp_block, -1);
553 mmp_error:
554                 sb->s_mmp_block = 0;
555                 sb->s_mmp_update_interval = 0;
556         }
557
558         if (FEATURE_ON(E2P_FEATURE_COMPAT, EXT3_FEATURE_COMPAT_HAS_JOURNAL)) {
559                 /*
560                  * If adding a journal flag, let the create journal
561                  * code below handle setting the flag and creating the
562                  * journal.  We supply a default size if necessary.
563                  */
564                 if (!journal_size)
565                         journal_size = -1;
566                 sb->s_feature_compat &= ~EXT3_FEATURE_COMPAT_HAS_JOURNAL;
567         }
568
569         if (FEATURE_ON(E2P_FEATURE_COMPAT, EXT2_FEATURE_COMPAT_DIR_INDEX)) {
570                 if (!sb->s_def_hash_version)
571                         sb->s_def_hash_version = EXT2_HASH_HALF_MD4;
572                 if (uuid_is_null((unsigned char *) sb->s_hash_seed))
573                         uuid_generate((unsigned char *) sb->s_hash_seed);
574         }
575
576         if (FEATURE_OFF(E2P_FEATURE_INCOMPAT, EXT4_FEATURE_INCOMPAT_FLEX_BG)) {
577                 if (ext2fs_check_desc(fs)) {
578                         fputs(_("Clearing the flex_bg flag would "
579                                 "cause the the filesystem to be\n"
580                                 "inconsistent.\n"), stderr);
581                         return 1;
582                 }
583         }
584
585         if (FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
586                             EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
587                 if ((mount_flags & EXT2_MF_MOUNTED) &&
588                     !(mount_flags & EXT2_MF_READONLY)) {
589                         fputs(_("The huge_file feature may only be "
590                                 "cleared when the filesystem is\n"
591                                 "unmounted or mounted "
592                                 "read-only.\n"), stderr);
593                         return 1;
594                 }
595         }
596
597         if (FEATURE_ON(E2P_FEATURE_RO_INCOMPAT,
598                        EXT4_FEATURE_RO_COMPAT_GDT_CSUM)) {
599                 for (i = 0; i < fs->group_desc_count; i++) {
600                         gd = ext2fs_group_desc(fs, fs->group_desc, i);
601                         gd->bg_itable_unused = 0;
602                         gd->bg_flags = EXT2_BG_INODE_ZEROED;
603                         ext2fs_group_desc_csum_set(fs, i);
604                 }
605                 fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
606         }
607
608         if (FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
609                         EXT4_FEATURE_RO_COMPAT_GDT_CSUM)) {
610                 for (i = 0; i < fs->group_desc_count; i++) {
611                         gd = ext2fs_group_desc(fs, fs->group_desc, i);
612                         if ((gd->bg_flags & EXT2_BG_INODE_ZEROED) == 0) {
613                                 /* 
614                                  * XXX what we really should do is zap
615                                  * uninitialized inode tables instead.
616                                  */
617                                 request_fsck_afterwards(fs);
618                                 break;
619                         }
620                         gd->bg_itable_unused = 0;
621                         gd->bg_flags = 0;
622                         gd->bg_checksum = 0;
623                 }
624                 fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
625         }
626
627         if (FEATURE_ON(E2P_FEATURE_RO_INCOMPAT,
628                                 EXT4_FEATURE_RO_COMPAT_QUOTA)) {
629                 /*
630                  * Set the Q_flag here and handle the quota options in the code
631                  * below.
632                  */
633                 if (!Q_flag) {
634                         Q_flag = 1;
635                         /* Enable both user quota and group quota by default */
636                         usrquota = QOPT_ENABLE;
637                         grpquota = QOPT_ENABLE;
638                 }
639                 sb->s_feature_ro_compat &= ~EXT4_FEATURE_RO_COMPAT_QUOTA;
640         }
641
642         if (FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
643                                 EXT4_FEATURE_RO_COMPAT_QUOTA)) {
644                 /*
645                  * Set the Q_flag here and handle the quota options in the code
646                  * below.
647                  */
648                 if (Q_flag)
649                         fputs(_("\nWarning: '^quota' option overrides '-Q'"
650                                 "arguments.\n"), stderr);
651                 Q_flag = 1;
652                 /* Disable both user quota and group quota by default */
653                 usrquota = QOPT_DISABLE;
654                 grpquota = QOPT_DISABLE;
655         }
656
657         if (sb->s_rev_level == EXT2_GOOD_OLD_REV &&
658             (sb->s_feature_compat || sb->s_feature_ro_compat ||
659              sb->s_feature_incompat))
660                 ext2fs_update_dynamic_rev(fs);
661
662         if (FEATURE_CHANGED(E2P_FEATURE_RO_INCOMPAT,
663                             EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER) ||
664             FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
665                         EXT4_FEATURE_RO_COMPAT_HUGE_FILE) ||
666             FEATURE_CHANGED(E2P_FEATURE_INCOMPAT,
667                             EXT2_FEATURE_INCOMPAT_FILETYPE) ||
668             FEATURE_CHANGED(E2P_FEATURE_COMPAT,
669                             EXT2_FEATURE_COMPAT_RESIZE_INODE) ||
670             FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
671                         EXT2_FEATURE_RO_COMPAT_LARGE_FILE))
672                 request_fsck_afterwards(fs);
673
674         if ((old_features[E2P_FEATURE_COMPAT] != sb->s_feature_compat) ||
675             (old_features[E2P_FEATURE_INCOMPAT] != sb->s_feature_incompat) ||
676             (old_features[E2P_FEATURE_RO_INCOMPAT] != sb->s_feature_ro_compat))
677                 ext2fs_mark_super_dirty(fs);
678
679         return 0;
680 }
681
682 /*
683  * Add a journal to the filesystem.
684  */
685 static int add_journal(ext2_filsys fs)
686 {
687         unsigned long journal_blocks;
688         errcode_t       retval;
689         ext2_filsys     jfs;
690         io_manager      io_ptr;
691
692         if (fs->super->s_feature_compat &
693             EXT3_FEATURE_COMPAT_HAS_JOURNAL) {
694                 fputs(_("The filesystem already has a journal.\n"), stderr);
695                 goto err;
696         }
697         if (journal_device) {
698                 if (!check_plausibility(journal_device, CHECK_BLOCK_DEV,
699                                         NULL))
700                         proceed_question(-1);
701                 check_mount(journal_device, 0, _("journal"));
702 #ifdef CONFIG_TESTIO_DEBUG
703                 if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_BLOCK")) {
704                         io_ptr = test_io_manager;
705                         test_io_backing_manager = unix_io_manager;
706                 } else
707 #endif
708                         io_ptr = unix_io_manager;
709                 retval = ext2fs_open(journal_device, EXT2_FLAG_RW|
710                                      EXT2_FLAG_JOURNAL_DEV_OK, 0,
711                                      fs->blocksize, io_ptr, &jfs);
712                 if (retval) {
713                         com_err(program_name, retval,
714                                 _("\n\twhile trying to open journal on %s\n"),
715                                 journal_device);
716                         goto err;
717                 }
718                 printf(_("Creating journal on device %s: "),
719                        journal_device);
720                 fflush(stdout);
721
722                 retval = ext2fs_add_journal_device(fs, jfs);
723                 ext2fs_close_free(&jfs);
724                 if (retval) {
725                         com_err(program_name, retval,
726                                 _("while adding filesystem to journal on %s"),
727                                 journal_device);
728                         goto err;
729                 }
730                 fputs(_("done\n"), stdout);
731         } else if (journal_size) {
732                 fputs(_("Creating journal inode: "), stdout);
733                 fflush(stdout);
734                 journal_blocks = figure_journal_size(journal_size, fs);
735
736                 if (journal_location_string)
737                         journal_location =
738                                 parse_num_blocks2(journal_location_string,
739                                                   fs->super->s_log_block_size);
740                 retval = ext2fs_add_journal_inode2(fs, journal_blocks,
741                                                    journal_location,
742                                                    journal_flags);
743                 if (retval) {
744                         fprintf(stderr, "\n");
745                         com_err(program_name, retval, "%s",
746                                 _("\n\twhile trying to create journal file"));
747                         return retval;
748                 } else
749                         fputs(_("done\n"), stdout);
750                 /*
751                  * If the filesystem wasn't mounted, we need to force
752                  * the block group descriptors out.
753                  */
754                 if ((mount_flags & EXT2_MF_MOUNTED) == 0)
755                         fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
756         }
757         print_check_message(fs->super->s_max_mnt_count,
758                             fs->super->s_checkinterval);
759         return 0;
760
761 err:
762         free(journal_device);
763         return 1;
764 }
765
766 static void handle_quota_options(ext2_filsys fs)
767 {
768         quota_ctx_t qctx;
769         ext2_ino_t qf_ino;
770
771         if (!usrquota && !grpquota)
772                 /* Nothing to do. */
773                 return;
774
775         quota_init_context(&qctx, fs, -1);
776
777         if (usrquota == QOPT_ENABLE || grpquota == QOPT_ENABLE)
778                 quota_compute_usage(qctx);
779
780         if (usrquota == QOPT_ENABLE && !fs->super->s_usr_quota_inum) {
781                 if ((qf_ino = quota_file_exists(fs, USRQUOTA,
782                                                 QFMT_VFS_V1)) > 0)
783                         quota_update_limits(qctx, qf_ino, USRQUOTA);
784                 quota_write_inode(qctx, USRQUOTA);
785         } else if (usrquota == QOPT_DISABLE) {
786                 quota_remove_inode(fs, USRQUOTA);
787         }
788
789         if (grpquota == QOPT_ENABLE && !fs->super->s_grp_quota_inum) {
790                 if ((qf_ino = quota_file_exists(fs, GRPQUOTA,
791                                                 QFMT_VFS_V1)) > 0)
792                         quota_update_limits(qctx, qf_ino, GRPQUOTA);
793                 quota_write_inode(qctx, GRPQUOTA);
794         } else if (grpquota == QOPT_DISABLE) {
795                 quota_remove_inode(fs, GRPQUOTA);
796         }
797
798         quota_release_context(&qctx);
799
800         if ((usrquota == QOPT_ENABLE) || (grpquota == QOPT_ENABLE)) {
801                 fs->super->s_feature_ro_compat |= EXT4_FEATURE_RO_COMPAT_QUOTA;
802                 ext2fs_mark_super_dirty(fs);
803         } else if (!fs->super->s_usr_quota_inum &&
804                    !fs->super->s_grp_quota_inum) {
805                 fs->super->s_feature_ro_compat &= ~EXT4_FEATURE_RO_COMPAT_QUOTA;
806                 ext2fs_mark_super_dirty(fs);
807         }
808
809         return;
810 }
811
812 #ifdef CONFIG_QUOTA
813 static void parse_quota_opts(const char *opts)
814 {
815         char    *buf, *token, *next, *p;
816         int     len;
817
818         len = strlen(opts);
819         buf = malloc(len+1);
820         if (!buf) {
821                 fputs(_("Couldn't allocate memory to parse quota "
822                         "options!\n"), stderr);
823                 exit(1);
824         }
825         strcpy(buf, opts);
826         for (token = buf; token && *token; token = next) {
827                 p = strchr(token, ',');
828                 next = 0;
829                 if (p) {
830                         *p = 0;
831                         next = p+1;
832                 }
833
834                 if (strcmp(token, "usrquota") == 0) {
835                         usrquota = QOPT_ENABLE;
836                 } else if (strcmp(token, "^usrquota") == 0) {
837                         usrquota = QOPT_DISABLE;
838                 } else if (strcmp(token, "grpquota") == 0) {
839                         grpquota = QOPT_ENABLE;
840                 } else if (strcmp(token, "^grpquota") == 0) {
841                         grpquota = QOPT_DISABLE;
842                 } else {
843                         fputs(_("\nBad quota options specified.\n\n"
844                                 "Following valid quota options are available "
845                                 "(pass by separating with comma):\n"
846                                 "\t[^]usrquota\n"
847                                 "\t[^]grpquota\n"
848                                 "\n\n"), stderr);
849                         free(buf);
850                         exit(1);
851                 }
852         }
853         free(buf);
854 }
855 #endif
856
857 static void parse_e2label_options(int argc, char ** argv)
858 {
859         if ((argc < 2) || (argc > 3)) {
860                 fputs(_("Usage: e2label device [newlabel]\n"), stderr);
861                 exit(1);
862         }
863         io_options = strchr(argv[1], '?');
864         if (io_options)
865                 *io_options++ = 0;
866         device_name = blkid_get_devname(NULL, argv[1], NULL);
867         if (!device_name) {
868                 com_err("e2label", 0, _("Unable to resolve '%s'"),
869                         argv[1]);
870                 exit(1);
871         }
872         open_flag = EXT2_FLAG_JOURNAL_DEV_OK;
873         if (argc == 3) {
874                 open_flag |= EXT2_FLAG_RW;
875                 L_flag = 1;
876                 new_label = argv[2];
877         } else
878                 print_label++;
879 }
880
881 static time_t parse_time(char *str)
882 {
883         struct  tm      ts;
884
885         if (strcmp(str, "now") == 0) {
886                 return (time(0));
887         }
888         memset(&ts, 0, sizeof(ts));
889 #ifdef HAVE_STRPTIME
890         strptime(str, "%Y%m%d%H%M%S", &ts);
891 #else
892         sscanf(str, "%4d%2d%2d%2d%2d%2d", &ts.tm_year, &ts.tm_mon,
893                &ts.tm_mday, &ts.tm_hour, &ts.tm_min, &ts.tm_sec);
894         ts.tm_year -= 1900;
895         ts.tm_mon -= 1;
896         if (ts.tm_year < 0 || ts.tm_mon < 0 || ts.tm_mon > 11 ||
897             ts.tm_mday < 0 || ts.tm_mday > 31 || ts.tm_hour > 23 ||
898             ts.tm_min > 59 || ts.tm_sec > 61)
899                 ts.tm_mday = 0;
900 #endif
901         if (ts.tm_mday == 0) {
902                 com_err(program_name, 0,
903                         _("Couldn't parse date/time specifier: %s"),
904                         str);
905                 usage();
906         }
907         ts.tm_isdst = -1;
908         return (mktime(&ts));
909 }
910
911 static void parse_tune2fs_options(int argc, char **argv)
912 {
913         int c;
914         char *tmp;
915         struct group *gr;
916         struct passwd *pw;
917         char optstring[100] = "c:e:fg:i:jlm:o:r:s:u:C:E:I:J:L:M:O:T:U:";
918
919 #ifdef CONFIG_QUOTA
920         strcat(optstring, "Q:");
921 #endif
922         open_flag = 0;
923
924         printf("tune2fs %s (%s)\n", E2FSPROGS_VERSION, E2FSPROGS_DATE);
925         while ((c = getopt(argc, argv, optstring)) != EOF)
926                 switch (c) {
927                 case 'c':
928                         max_mount_count = strtol(optarg, &tmp, 0);
929                         if (*tmp || max_mount_count > 16000) {
930                                 com_err(program_name, 0,
931                                         _("bad mounts count - %s"),
932                                         optarg);
933                                 usage();
934                         }
935                         if (max_mount_count == 0)
936                                 max_mount_count = -1;
937                         c_flag = 1;
938                         open_flag = EXT2_FLAG_RW;
939                         break;
940                 case 'C':
941                         mount_count = strtoul(optarg, &tmp, 0);
942                         if (*tmp || mount_count > 16000) {
943                                 com_err(program_name, 0,
944                                         _("bad mounts count - %s"),
945                                         optarg);
946                                 usage();
947                         }
948                         C_flag = 1;
949                         open_flag = EXT2_FLAG_RW;
950                         break;
951                 case 'e':
952                         if (strcmp(optarg, "continue") == 0)
953                                 errors = EXT2_ERRORS_CONTINUE;
954                         else if (strcmp(optarg, "remount-ro") == 0)
955                                 errors = EXT2_ERRORS_RO;
956                         else if (strcmp(optarg, "panic") == 0)
957                                 errors = EXT2_ERRORS_PANIC;
958                         else {
959                                 com_err(program_name, 0,
960                                         _("bad error behavior - %s"),
961                                         optarg);
962                                 usage();
963                         }
964                         e_flag = 1;
965                         open_flag = EXT2_FLAG_RW;
966                         break;
967                 case 'E':
968                         extended_cmd = optarg;
969                         open_flag |= EXT2_FLAG_RW;
970                         break;
971                 case 'f': /* Force */
972                         f_flag++;
973                         break;
974                 case 'g':
975                         resgid = strtoul(optarg, &tmp, 0);
976                         if (*tmp) {
977                                 gr = getgrnam(optarg);
978                                 if (gr == NULL)
979                                         tmp = optarg;
980                                 else {
981                                         resgid = gr->gr_gid;
982                                         *tmp = 0;
983                                 }
984                         }
985                         if (*tmp) {
986                                 com_err(program_name, 0,
987                                         _("bad gid/group name - %s"),
988                                         optarg);
989                                 usage();
990                         }
991                         g_flag = 1;
992                         open_flag = EXT2_FLAG_RW;
993                         break;
994                 case 'i':
995                         interval = strtoul(optarg, &tmp, 0);
996                         switch (*tmp) {
997                         case 's':
998                                 tmp++;
999                                 break;
1000                         case '\0':
1001                         case 'd':
1002                         case 'D': /* days */
1003                                 interval *= 86400;
1004                                 if (*tmp != '\0')
1005                                         tmp++;
1006                                 break;
1007                         case 'm':
1008                         case 'M': /* months! */
1009                                 interval *= 86400 * 30;
1010                                 tmp++;
1011                                 break;
1012                         case 'w':
1013                         case 'W': /* weeks */
1014                                 interval *= 86400 * 7;
1015                                 tmp++;
1016                                 break;
1017                         }
1018                         if (*tmp) {
1019                                 com_err(program_name, 0,
1020                                         _("bad interval - %s"), optarg);
1021                                 usage();
1022                         }
1023                         i_flag = 1;
1024                         open_flag = EXT2_FLAG_RW;
1025                         break;
1026                 case 'j':
1027                         if (!journal_size)
1028                                 journal_size = -1;
1029                         open_flag = EXT2_FLAG_RW;
1030                         break;
1031                 case 'J':
1032                         parse_journal_opts(optarg);
1033                         open_flag = EXT2_FLAG_RW;
1034                         break;
1035                 case 'l':
1036                         l_flag = 1;
1037                         break;
1038                 case 'L':
1039                         new_label = optarg;
1040                         L_flag = 1;
1041                         open_flag |= EXT2_FLAG_RW |
1042                                 EXT2_FLAG_JOURNAL_DEV_OK;
1043                         break;
1044                 case 'm':
1045                         reserved_ratio = strtod(optarg, &tmp);
1046                         if (*tmp || reserved_ratio > 50 ||
1047                             reserved_ratio < 0) {
1048                                 com_err(program_name, 0,
1049                                         _("bad reserved block ratio - %s"),
1050                                         optarg);
1051                                 usage();
1052                         }
1053                         m_flag = 1;
1054                         open_flag = EXT2_FLAG_RW;
1055                         break;
1056                 case 'M':
1057                         new_last_mounted = optarg;
1058                         M_flag = 1;
1059                         open_flag = EXT2_FLAG_RW;
1060                         break;
1061                 case 'o':
1062                         if (mntopts_cmd) {
1063                                 com_err(program_name, 0, "%s",
1064                                         _("-o may only be specified once"));
1065                                 usage();
1066                         }
1067                         mntopts_cmd = optarg;
1068                         open_flag = EXT2_FLAG_RW;
1069                         break;
1070                 case 'O':
1071                         if (features_cmd) {
1072                                 com_err(program_name, 0, "%s",
1073                                         _("-O may only be specified once"));
1074                                 usage();
1075                         }
1076                         features_cmd = optarg;
1077                         open_flag = EXT2_FLAG_RW;
1078                         break;
1079 #ifdef CONFIG_QUOTA
1080                 case 'Q':
1081                         Q_flag = 1;
1082                         parse_quota_opts(optarg);
1083                         open_flag = EXT2_FLAG_RW;
1084                         break;
1085 #endif
1086                 case 'r':
1087                         reserved_blocks = strtoul(optarg, &tmp, 0);
1088                         if (*tmp) {
1089                                 com_err(program_name, 0,
1090                                         _("bad reserved blocks count - %s"),
1091                                         optarg);
1092                                 usage();
1093                         }
1094                         r_flag = 1;
1095                         open_flag = EXT2_FLAG_RW;
1096                         break;
1097                 case 's': /* Deprecated */
1098                         s_flag = atoi(optarg);
1099                         open_flag = EXT2_FLAG_RW;
1100                         break;
1101                 case 'T':
1102                         T_flag = 1;
1103                         last_check_time = parse_time(optarg);
1104                         open_flag = EXT2_FLAG_RW;
1105                         break;
1106                 case 'u':
1107                                 resuid = strtoul(optarg, &tmp, 0);
1108                                 if (*tmp) {
1109                                         pw = getpwnam(optarg);
1110                                         if (pw == NULL)
1111                                                 tmp = optarg;
1112                                         else {
1113                                                 resuid = pw->pw_uid;
1114                                                 *tmp = 0;
1115                                         }
1116                                 }
1117                                 if (*tmp) {
1118                                         com_err(program_name, 0,
1119                                                 _("bad uid/user name - %s"),
1120                                                 optarg);
1121                                         usage();
1122                                 }
1123                                 u_flag = 1;
1124                                 open_flag = EXT2_FLAG_RW;
1125                                 break;
1126                 case 'U':
1127                         new_UUID = optarg;
1128                         U_flag = 1;
1129                         open_flag = EXT2_FLAG_RW |
1130                                 EXT2_FLAG_JOURNAL_DEV_OK;
1131                         break;
1132                 case 'I':
1133                         new_inode_size = strtoul(optarg, &tmp, 0);
1134                         if (*tmp) {
1135                                 com_err(program_name, 0,
1136                                         _("bad inode size - %s"),
1137                                         optarg);
1138                                 usage();
1139                         }
1140                         if (!((new_inode_size &
1141                                (new_inode_size - 1)) == 0)) {
1142                                 com_err(program_name, 0,
1143                                         _("Inode size must be a "
1144                                           "power of two- %s"),
1145                                         optarg);
1146                                 usage();
1147                         }
1148                         open_flag = EXT2_FLAG_RW;
1149                         I_flag = 1;
1150                         break;
1151                 default:
1152                         usage();
1153                 }
1154         if (optind < argc - 1 || optind == argc)
1155                 usage();
1156         if (!open_flag && !l_flag)
1157                 usage();
1158         io_options = strchr(argv[optind], '?');
1159         if (io_options)
1160                 *io_options++ = 0;
1161         device_name = blkid_get_devname(NULL, argv[optind], NULL);
1162         if (!device_name) {
1163                 com_err(program_name, 0, _("Unable to resolve '%s'"),
1164                         argv[optind]);
1165                 exit(1);
1166         }
1167 }
1168
1169 #ifdef CONFIG_BUILD_FINDFS
1170 void do_findfs(int argc, char **argv)
1171 {
1172         char    *dev;
1173
1174         if ((argc != 2) ||
1175             (strncmp(argv[1], "LABEL=", 6) && strncmp(argv[1], "UUID=", 5))) {
1176                 fprintf(stderr, "Usage: findfs LABEL=<label>|UUID=<uuid>\n");
1177                 exit(2);
1178         }
1179         dev = blkid_get_devname(NULL, argv[1], NULL);
1180         if (!dev) {
1181                 com_err("findfs", 0, _("Unable to resolve '%s'"),
1182                         argv[1]);
1183                 exit(1);
1184         }
1185         puts(dev);
1186         exit(0);
1187 }
1188 #endif
1189
1190 static int parse_extended_opts(ext2_filsys fs, const char *opts)
1191 {
1192         char    *buf, *token, *next, *p, *arg;
1193         int     len, hash_alg;
1194         int     r_usage = 0;
1195
1196         len = strlen(opts);
1197         buf = malloc(len+1);
1198         if (!buf) {
1199                 fprintf(stderr, "%s",
1200                         _("Couldn't allocate memory to parse options!\n"));
1201                 return 1;
1202         }
1203         strcpy(buf, opts);
1204         for (token = buf; token && *token; token = next) {
1205                 p = strchr(token, ',');
1206                 next = 0;
1207                 if (p) {
1208                         *p = 0;
1209                         next = p+1;
1210                 }
1211                 arg = strchr(token, '=');
1212                 if (arg) {
1213                         *arg = 0;
1214                         arg++;
1215                 }
1216                 if (strcmp(token, "clear-mmp") == 0 ||
1217                     strcmp(token, "clear_mmp") == 0) {
1218                         clear_mmp = 1;
1219                 } else if (strcmp(token, "mmp_update_interval") == 0) {
1220                         unsigned long intv;
1221                         if (!arg) {
1222                                 r_usage++;
1223                                 continue;
1224                         }
1225                         intv = strtoul(arg, &p, 0);
1226                         if (*p) {
1227                                 fprintf(stderr,
1228                                         _("Invalid mmp_update_interval: %s\n"),
1229                                         arg);
1230                                 r_usage++;
1231                                 continue;
1232                         }
1233                         if (intv == 0) {
1234                                 intv = EXT4_MMP_UPDATE_INTERVAL;
1235                         } else if (intv > EXT4_MMP_MAX_UPDATE_INTERVAL) {
1236                                 fprintf(stderr,
1237                                         _("mmp_update_interval too big: %lu\n"),
1238                                         intv);
1239                                 r_usage++;
1240                                 continue;
1241                         }
1242                         printf(P_("Setting multiple mount protection update "
1243                                   "interval to %lu second\n",
1244                                   "Setting multiple mount protection update "
1245                                   "interval to %lu seconds\n", intv),
1246                                intv);
1247                         fs->super->s_mmp_update_interval = intv;
1248                         ext2fs_mark_super_dirty(fs);
1249                 } else if (!strcmp(token, "test_fs")) {
1250                         fs->super->s_flags |= EXT2_FLAGS_TEST_FILESYS;
1251                         printf("Setting test filesystem flag\n");
1252                         ext2fs_mark_super_dirty(fs);
1253                 } else if (!strcmp(token, "^test_fs")) {
1254                         fs->super->s_flags &= ~EXT2_FLAGS_TEST_FILESYS;
1255                         printf("Clearing test filesystem flag\n");
1256                         ext2fs_mark_super_dirty(fs);
1257                 } else if (strcmp(token, "stride") == 0) {
1258                         if (!arg) {
1259                                 r_usage++;
1260                                 continue;
1261                         }
1262                         stride = strtoul(arg, &p, 0);
1263                         if (*p) {
1264                                 fprintf(stderr,
1265                                         _("Invalid RAID stride: %s\n"),
1266                                         arg);
1267                                 r_usage++;
1268                                 continue;
1269                         }
1270                         stride_set = 1;
1271                 } else if (strcmp(token, "stripe-width") == 0 ||
1272                            strcmp(token, "stripe_width") == 0) {
1273                         if (!arg) {
1274                                 r_usage++;
1275                                 continue;
1276                         }
1277                         stripe_width = strtoul(arg, &p, 0);
1278                         if (*p) {
1279                                 fprintf(stderr,
1280                                         _("Invalid RAID stripe-width: %s\n"),
1281                                         arg);
1282                                 r_usage++;
1283                                 continue;
1284                         }
1285                         stripe_width_set = 1;
1286                 } else if (strcmp(token, "hash_alg") == 0 ||
1287                            strcmp(token, "hash-alg") == 0) {
1288                         if (!arg) {
1289                                 r_usage++;
1290                                 continue;
1291                         }
1292                         hash_alg = e2p_string2hash(arg);
1293                         if (hash_alg < 0) {
1294                                 fprintf(stderr,
1295                                         _("Invalid hash algorithm: %s\n"),
1296                                         arg);
1297                                 r_usage++;
1298                                 continue;
1299                         }
1300                         fs->super->s_def_hash_version = hash_alg;
1301                         printf(_("Setting default hash algorithm "
1302                                  "to %s (%d)\n"),
1303                                arg, hash_alg);
1304                         ext2fs_mark_super_dirty(fs);
1305                 } else if (!strcmp(token, "mount_opts")) {
1306                         if (!arg) {
1307                                 r_usage++;
1308                                 continue;
1309                         }
1310                         if (strlen(arg) >= sizeof(fs->super->s_mount_opts)) {
1311                                 fprintf(stderr,
1312                                         "Extended mount options too long\n");
1313                                 continue;
1314                         }
1315                         ext_mount_opts = strdup(arg);
1316                 } else
1317                         r_usage++;
1318         }
1319         if (r_usage) {
1320                 fprintf(stderr, "%s", _("\nBad options specified.\n\n"
1321                         "Extended options are separated by commas, "
1322                         "and may take an argument which\n"
1323                         "\tis set off by an equals ('=') sign.\n\n"
1324                         "Valid extended options are:\n"
1325                         "\tclear_mmp\n"
1326                         "\thash_alg=<hash algorithm>\n"
1327                         "\tmount_opts=<extended default mount options>\n"
1328                         "\tstride=<RAID per-disk chunk size in blocks>\n"
1329                         "\tstripe_width=<RAID stride*data disks in blocks>\n"
1330                         "\ttest_fs\n"
1331                         "\t^test_fs\n"));
1332                 free(buf);
1333                 return 1;
1334         }
1335         free(buf);
1336
1337         return 0;
1338 }
1339
1340 /*
1341  * Fill in the block bitmap bmap with the information regarding the
1342  * blocks to be moved
1343  */
1344 static int get_move_bitmaps(ext2_filsys fs, int new_ino_blks_per_grp,
1345                             ext2fs_block_bitmap bmap)
1346 {
1347         dgrp_t i;
1348         int retval;
1349         ext2_badblocks_list bb_list = 0;
1350         blk64_t j, needed_blocks = 0;
1351         blk64_t start_blk, end_blk;
1352
1353         retval = ext2fs_read_bb_inode(fs, &bb_list);
1354         if (retval)
1355                 return retval;
1356
1357         for (i = 0; i < fs->group_desc_count; i++) {
1358                 start_blk = ext2fs_inode_table_loc(fs, i) +
1359                                         fs->inode_blocks_per_group;
1360
1361                 end_blk = ext2fs_inode_table_loc(fs, i) +
1362                                         new_ino_blks_per_grp;
1363
1364                 for (j = start_blk; j < end_blk; j++) {
1365                         if (ext2fs_test_block_bitmap2(fs->block_map, j)) {
1366                                 /*
1367                                  * IF the block is a bad block we fail
1368                                  */
1369                                 if (ext2fs_badblocks_list_test(bb_list, j)) {
1370                                         ext2fs_badblocks_list_free(bb_list);
1371                                         return ENOSPC;
1372                                 }
1373
1374                                 ext2fs_mark_block_bitmap2(bmap, j);
1375                         } else {
1376                                 /*
1377                                  * We are going to use this block for
1378                                  * inode table. So mark them used.
1379                                  */
1380                                 ext2fs_mark_block_bitmap2(fs->block_map, j);
1381                         }
1382                 }
1383                 needed_blocks += end_blk - start_blk;
1384         }
1385
1386         ext2fs_badblocks_list_free(bb_list);
1387         if (needed_blocks > ext2fs_free_blocks_count(fs->super))
1388                 return ENOSPC;
1389
1390         return 0;
1391 }
1392
1393 static int ext2fs_is_meta_block(ext2_filsys fs, blk64_t blk)
1394 {
1395         dgrp_t group;
1396         group = ext2fs_group_of_blk2(fs, blk);
1397         if (ext2fs_block_bitmap_loc(fs, group) == blk)
1398                 return 1;
1399         if (ext2fs_inode_bitmap_loc(fs, group) == blk)
1400                 return 1;
1401         return 0;
1402 }
1403
1404 static int ext2fs_is_block_in_group(ext2_filsys fs, dgrp_t group, blk64_t blk)
1405 {
1406         blk64_t start_blk, end_blk;
1407         start_blk = fs->super->s_first_data_block +
1408                         EXT2_GROUPS_TO_BLOCKS(fs->super, group);
1409         /*
1410          * We cannot get new block beyond end_blk for for the last block group
1411          * so we can check with EXT2_BLOCKS_PER_GROUP even for last block group
1412          */
1413         end_blk   = start_blk + EXT2_BLOCKS_PER_GROUP(fs->super);
1414         if (blk >= start_blk && blk <= end_blk)
1415                 return 1;
1416         return 0;
1417 }
1418
1419 static int move_block(ext2_filsys fs, ext2fs_block_bitmap bmap)
1420 {
1421
1422         char *buf;
1423         dgrp_t group = 0;
1424         errcode_t retval;
1425         int meta_data = 0;
1426         blk64_t blk, new_blk, goal;
1427         struct blk_move *bmv;
1428
1429         retval = ext2fs_get_mem(fs->blocksize, &buf);
1430         if (retval)
1431                 return retval;
1432
1433         for (new_blk = blk = fs->super->s_first_data_block;
1434              blk < ext2fs_blocks_count(fs->super); blk++) {
1435                 if (!ext2fs_test_block_bitmap2(bmap, blk))
1436                         continue;
1437
1438                 if (ext2fs_is_meta_block(fs, blk)) {
1439                         /*
1440                          * If the block is mapping a fs meta data block
1441                          * like group desc/block bitmap/inode bitmap. We
1442                          * should find a block in the same group and fix
1443                          * the respective fs metadata pointers. Otherwise
1444                          * fail
1445                          */
1446                         group = ext2fs_group_of_blk2(fs, blk);
1447                         goal = ext2fs_group_first_block2(fs, group);
1448                         meta_data = 1;
1449
1450                 } else {
1451                         goal = new_blk;
1452                 }
1453                 retval = ext2fs_new_block2(fs, goal, NULL, &new_blk);
1454                 if (retval)
1455                         goto err_out;
1456
1457                 /* new fs meta data block should be in the same group */
1458                 if (meta_data && !ext2fs_is_block_in_group(fs, group, new_blk)) {
1459                         retval = ENOSPC;
1460                         goto err_out;
1461                 }
1462
1463                 /* Mark this block as allocated */
1464                 ext2fs_mark_block_bitmap2(fs->block_map, new_blk);
1465
1466                 /* Add it to block move list */
1467                 retval = ext2fs_get_mem(sizeof(struct blk_move), &bmv);
1468                 if (retval)
1469                         goto err_out;
1470
1471                 bmv->old_loc = blk;
1472                 bmv->new_loc = new_blk;
1473
1474                 list_add(&(bmv->list), &blk_move_list);
1475
1476                 retval = io_channel_read_blk64(fs->io, blk, 1, buf);
1477                 if (retval)
1478                         goto err_out;
1479
1480                 retval = io_channel_write_blk64(fs->io, new_blk, 1, buf);
1481                 if (retval)
1482                         goto err_out;
1483         }
1484
1485 err_out:
1486         ext2fs_free_mem(&buf);
1487         return retval;
1488 }
1489
1490 static blk64_t translate_block(blk64_t blk)
1491 {
1492         struct list_head *entry;
1493         struct blk_move *bmv;
1494
1495         list_for_each(entry, &blk_move_list) {
1496                 bmv = list_entry(entry, struct blk_move, list);
1497                 if (bmv->old_loc == blk)
1498                         return bmv->new_loc;
1499         }
1500
1501         return 0;
1502 }
1503
1504 static int process_block(ext2_filsys fs EXT2FS_ATTR((unused)),
1505                          blk64_t *block_nr,
1506                          e2_blkcnt_t blockcnt EXT2FS_ATTR((unused)),
1507                          blk64_t ref_block EXT2FS_ATTR((unused)),
1508                          int ref_offset EXT2FS_ATTR((unused)),
1509                          void *priv_data)
1510 {
1511         int ret = 0;
1512         blk64_t new_blk;
1513         ext2fs_block_bitmap bmap = (ext2fs_block_bitmap) priv_data;
1514
1515         if (!ext2fs_test_block_bitmap2(bmap, *block_nr))
1516                 return 0;
1517         new_blk = translate_block(*block_nr);
1518         if (new_blk) {
1519                 *block_nr = new_blk;
1520                 /*
1521                  * This will force the ext2fs_write_inode in the iterator
1522                  */
1523                 ret |= BLOCK_CHANGED;
1524         }
1525
1526         return ret;
1527 }
1528
1529 static int inode_scan_and_fix(ext2_filsys fs, ext2fs_block_bitmap bmap)
1530 {
1531         errcode_t retval = 0;
1532         ext2_ino_t ino;
1533         blk64_t blk;
1534         char *block_buf = 0;
1535         struct ext2_inode inode;
1536         ext2_inode_scan scan = NULL;
1537
1538         retval = ext2fs_get_mem(fs->blocksize * 3, &block_buf);
1539         if (retval)
1540                 return retval;
1541
1542         retval = ext2fs_open_inode_scan(fs, 0, &scan);
1543         if (retval)
1544                 goto err_out;
1545
1546         while (1) {
1547                 retval = ext2fs_get_next_inode(scan, &ino, &inode);
1548                 if (retval)
1549                         goto err_out;
1550
1551                 if (!ino)
1552                         break;
1553
1554                 if (inode.i_links_count == 0)
1555                         continue; /* inode not in use */
1556
1557                 /* FIXME!!
1558                  * If we end up modifying the journal inode
1559                  * the sb->s_jnl_blocks will differ. But a
1560                  * subsequent e2fsck fixes that.
1561                  * Do we need to fix this ??
1562                  */
1563
1564                 if (ext2fs_file_acl_block(fs, &inode) &&
1565                     ext2fs_test_block_bitmap2(bmap,
1566                                         ext2fs_file_acl_block(fs, &inode))) {
1567                         blk = translate_block(ext2fs_file_acl_block(fs,
1568                                                                     &inode));
1569                         if (!blk)
1570                                 continue;
1571
1572                         ext2fs_file_acl_block_set(fs, &inode, blk);
1573
1574                         /*
1575                          * Write the inode to disk so that inode table
1576                          * resizing can work
1577                          */
1578                         retval = ext2fs_write_inode(fs, ino, &inode);
1579                         if (retval)
1580                                 goto err_out;
1581                 }
1582
1583                 if (!ext2fs_inode_has_valid_blocks2(fs, &inode))
1584                         continue;
1585
1586                 retval = ext2fs_block_iterate3(fs, ino, 0, block_buf,
1587                                                process_block, bmap);
1588                 if (retval)
1589                         goto err_out;
1590
1591         }
1592
1593 err_out:
1594         ext2fs_free_mem(&block_buf);
1595
1596         return retval;
1597 }
1598
1599 /*
1600  * We need to scan for inode and block bitmaps that may need to be
1601  * moved.  This can take place if the filesystem was formatted for
1602  * RAID arrays using the mke2fs's extended option "stride".
1603  */
1604 static int group_desc_scan_and_fix(ext2_filsys fs, ext2fs_block_bitmap bmap)
1605 {
1606         dgrp_t i;
1607         blk64_t blk, new_blk;
1608
1609         for (i = 0; i < fs->group_desc_count; i++) {
1610                 blk = ext2fs_block_bitmap_loc(fs, i);
1611                 if (ext2fs_test_block_bitmap2(bmap, blk)) {
1612                         new_blk = translate_block(blk);
1613                         if (!new_blk)
1614                                 continue;
1615                         ext2fs_block_bitmap_loc_set(fs, i, new_blk);
1616                 }
1617
1618                 blk = ext2fs_inode_bitmap_loc(fs, i);
1619                 if (ext2fs_test_block_bitmap2(bmap, blk)) {
1620                         new_blk = translate_block(blk);
1621                         if (!new_blk)
1622                                 continue;
1623                         ext2fs_inode_bitmap_loc_set(fs, i, new_blk);
1624                 }
1625         }
1626         return 0;
1627 }
1628
1629 static int expand_inode_table(ext2_filsys fs, unsigned long new_ino_size)
1630 {
1631         dgrp_t i;
1632         blk64_t blk;
1633         errcode_t retval;
1634         int new_ino_blks_per_grp;
1635         unsigned int j;
1636         char *old_itable = NULL, *new_itable = NULL;
1637         char *tmp_old_itable = NULL, *tmp_new_itable = NULL;
1638         unsigned long old_ino_size;
1639         int old_itable_size, new_itable_size;
1640
1641         old_itable_size = fs->inode_blocks_per_group * fs->blocksize;
1642         old_ino_size = EXT2_INODE_SIZE(fs->super);
1643
1644         new_ino_blks_per_grp = ext2fs_div_ceil(
1645                                         EXT2_INODES_PER_GROUP(fs->super) *
1646                                         new_ino_size,
1647                                         fs->blocksize);
1648
1649         new_itable_size = new_ino_blks_per_grp * fs->blocksize;
1650
1651         retval = ext2fs_get_mem(old_itable_size, &old_itable);
1652         if (retval)
1653                 return retval;
1654
1655         retval = ext2fs_get_mem(new_itable_size, &new_itable);
1656         if (retval)
1657                 goto err_out;
1658
1659         tmp_old_itable = old_itable;
1660         tmp_new_itable = new_itable;
1661
1662         for (i = 0; i < fs->group_desc_count; i++) {
1663                 blk = ext2fs_inode_table_loc(fs, i);
1664                 retval = io_channel_read_blk64(fs->io, blk,
1665                                 fs->inode_blocks_per_group, old_itable);
1666                 if (retval)
1667                         goto err_out;
1668
1669                 for (j = 0; j < EXT2_INODES_PER_GROUP(fs->super); j++) {
1670                         memcpy(new_itable, old_itable, old_ino_size);
1671
1672                         memset(new_itable+old_ino_size, 0,
1673                                         new_ino_size - old_ino_size);
1674
1675                         new_itable += new_ino_size;
1676                         old_itable += old_ino_size;
1677                 }
1678
1679                 /* reset the pointer */
1680                 old_itable = tmp_old_itable;
1681                 new_itable = tmp_new_itable;
1682
1683                 retval = io_channel_write_blk64(fs->io, blk,
1684                                         new_ino_blks_per_grp, new_itable);
1685                 if (retval)
1686                         goto err_out;
1687         }
1688
1689         /* Update the meta data */
1690         fs->inode_blocks_per_group = new_ino_blks_per_grp;
1691         fs->super->s_inode_size = new_ino_size;
1692
1693 err_out:
1694         if (old_itable)
1695                 ext2fs_free_mem(&old_itable);
1696
1697         if (new_itable)
1698                 ext2fs_free_mem(&new_itable);
1699
1700         return retval;
1701 }
1702
1703 static errcode_t ext2fs_calculate_summary_stats(ext2_filsys fs)
1704 {
1705         blk64_t         blk;
1706         ext2_ino_t      ino;
1707         unsigned int    group = 0;
1708         unsigned int    count = 0;
1709         int             total_free = 0;
1710         int             group_free = 0;
1711
1712         /*
1713          * First calculate the block statistics
1714          */
1715         for (blk = fs->super->s_first_data_block;
1716              blk < ext2fs_blocks_count(fs->super); blk++) {
1717                 if (!ext2fs_fast_test_block_bitmap2(fs->block_map, blk)) {
1718                         group_free++;
1719                         total_free++;
1720                 }
1721                 count++;
1722                 if ((count == fs->super->s_blocks_per_group) ||
1723                     (blk == ext2fs_blocks_count(fs->super)-1)) {
1724                         ext2fs_bg_free_blocks_count_set(fs, group++,
1725                                                         group_free);
1726                         count = 0;
1727                         group_free = 0;
1728                 }
1729         }
1730         total_free = EXT2FS_C2B(fs, total_free);
1731         ext2fs_free_blocks_count_set(fs->super, total_free);
1732
1733         /*
1734          * Next, calculate the inode statistics
1735          */
1736         group_free = 0;
1737         total_free = 0;
1738         count = 0;
1739         group = 0;
1740
1741         /* Protect loop from wrap-around if s_inodes_count maxed */
1742         for (ino = 1; ino <= fs->super->s_inodes_count && ino > 0; ino++) {
1743                 if (!ext2fs_fast_test_inode_bitmap2(fs->inode_map, ino)) {
1744                         group_free++;
1745                         total_free++;
1746                 }
1747                 count++;
1748                 if ((count == fs->super->s_inodes_per_group) ||
1749                     (ino == fs->super->s_inodes_count)) {
1750                         ext2fs_bg_free_inodes_count_set(fs, group++,
1751                                                         group_free);
1752                         count = 0;
1753                         group_free = 0;
1754                 }
1755         }
1756         fs->super->s_free_inodes_count = total_free;
1757         ext2fs_mark_super_dirty(fs);
1758         return 0;
1759 }
1760
1761 #define list_for_each_safe(pos, pnext, head) \
1762         for (pos = (head)->next, pnext = pos->next; pos != (head); \
1763              pos = pnext, pnext = pos->next)
1764
1765 static void free_blk_move_list(void)
1766 {
1767         struct list_head *entry, *tmp;
1768         struct blk_move *bmv;
1769
1770         list_for_each_safe(entry, tmp, &blk_move_list) {
1771                 bmv = list_entry(entry, struct blk_move, list);
1772                 list_del(entry);
1773                 ext2fs_free_mem(&bmv);
1774         }
1775         return;
1776 }
1777
1778 static int resize_inode(ext2_filsys fs, unsigned long new_size)
1779 {
1780         errcode_t retval;
1781         int new_ino_blks_per_grp;
1782         ext2fs_block_bitmap bmap;
1783
1784         retval = ext2fs_read_inode_bitmap(fs);
1785         if (retval) {
1786                 fputs(_("Failed to read inode bitmap\n"), stderr);
1787                 return retval;
1788         }
1789         retval = ext2fs_read_block_bitmap(fs);
1790         if (retval) {
1791                 fputs(_("Failed to read block bitmap\n"), stderr);
1792                 return retval;
1793         }
1794         INIT_LIST_HEAD(&blk_move_list);
1795
1796
1797         new_ino_blks_per_grp = ext2fs_div_ceil(
1798                                         EXT2_INODES_PER_GROUP(fs->super)*
1799                                         new_size,
1800                                         fs->blocksize);
1801
1802         /* We may change the file system.
1803          * Mark the file system as invalid so that
1804          * the user is prompted to run fsck.
1805          */
1806         fs->super->s_state &= ~EXT2_VALID_FS;
1807
1808         retval = ext2fs_allocate_block_bitmap(fs, _("blocks to be moved"),
1809                                                 &bmap);
1810         if (retval) {
1811                 fputs(_("Failed to allocate block bitmap when "
1812                                 "increasing inode size\n"), stderr);
1813                 return retval;
1814         }
1815         retval = get_move_bitmaps(fs, new_ino_blks_per_grp, bmap);
1816         if (retval) {
1817                 fputs(_("Not enough space to increase inode size \n"), stderr);
1818                 goto err_out;
1819         }
1820         retval = move_block(fs, bmap);
1821         if (retval) {
1822                 fputs(_("Failed to relocate blocks during inode resize \n"),
1823                       stderr);
1824                 goto err_out;
1825         }
1826         retval = inode_scan_and_fix(fs, bmap);
1827         if (retval)
1828                 goto err_out_undo;
1829
1830         retval = group_desc_scan_and_fix(fs, bmap);
1831         if (retval)
1832                 goto err_out_undo;
1833
1834         retval = expand_inode_table(fs, new_size);
1835         if (retval)
1836                 goto err_out_undo;
1837
1838         ext2fs_calculate_summary_stats(fs);
1839
1840         fs->super->s_state |= EXT2_VALID_FS;
1841         /* mark super block and block bitmap as dirty */
1842         ext2fs_mark_super_dirty(fs);
1843         ext2fs_mark_bb_dirty(fs);
1844
1845 err_out:
1846         free_blk_move_list();
1847         ext2fs_free_block_bitmap(bmap);
1848
1849         return retval;
1850
1851 err_out_undo:
1852         free_blk_move_list();
1853         ext2fs_free_block_bitmap(bmap);
1854         fputs(_("Error in resizing the inode size.\n"
1855                         "Run e2undo to undo the "
1856                         "file system changes. \n"), stderr);
1857
1858         return retval;
1859 }
1860
1861 static int tune2fs_setup_tdb(const char *name, io_manager *io_ptr)
1862 {
1863         errcode_t retval = 0;
1864         const char *tdb_dir;
1865         char *tdb_file;
1866         char *dev_name, *tmp_name;
1867
1868 #if 0 /* FIXME!! */
1869         /*
1870          * Configuration via a conf file would be
1871          * nice
1872          */
1873         profile_get_string(profile, "scratch_files",
1874                                         "directory", 0, 0,
1875                                         &tdb_dir);
1876 #endif
1877         tmp_name = strdup(name);
1878         if (!tmp_name) {
1879         alloc_fn_fail:
1880                 com_err(program_name, ENOMEM, "%s",
1881                         _("Couldn't allocate memory for tdb filename\n"));
1882                 return ENOMEM;
1883         }
1884         dev_name = basename(tmp_name);
1885
1886         tdb_dir = getenv("E2FSPROGS_UNDO_DIR");
1887         if (!tdb_dir)
1888                 tdb_dir = "/var/lib/e2fsprogs";
1889
1890         if (!strcmp(tdb_dir, "none") || (tdb_dir[0] == 0) ||
1891             access(tdb_dir, W_OK))
1892                 return 0;
1893
1894         tdb_file = malloc(strlen(tdb_dir) + 9 + strlen(dev_name) + 7 + 1);
1895         if (!tdb_file)
1896                 goto alloc_fn_fail;
1897         sprintf(tdb_file, "%s/tune2fs-%s.e2undo", tdb_dir, dev_name);
1898
1899         if ((unlink(tdb_file) < 0) && (errno != ENOENT)) {
1900                 retval = errno;
1901                 com_err(program_name, retval,
1902                         _("while trying to delete %s"), tdb_file);
1903                 free(tdb_file);
1904                 return retval;
1905         }
1906
1907         set_undo_io_backing_manager(*io_ptr);
1908         *io_ptr = undo_io_manager;
1909         set_undo_io_backup_file(tdb_file);
1910         printf(_("To undo the tune2fs operation please run "
1911                  "the command\n    e2undo %s %s\n\n"),
1912                  tdb_file, name);
1913         free(tdb_file);
1914         free(tmp_name);
1915         return retval;
1916 }
1917
1918 int main(int argc, char **argv)
1919 {
1920         errcode_t retval;
1921         ext2_filsys fs;
1922         struct ext2_super_block *sb;
1923         io_manager io_ptr, io_ptr_orig = NULL;
1924         int rc = 0;
1925
1926 #ifdef ENABLE_NLS
1927         setlocale(LC_MESSAGES, "");
1928         setlocale(LC_CTYPE, "");
1929         bindtextdomain(NLS_CAT_NAME, LOCALEDIR);
1930         textdomain(NLS_CAT_NAME);
1931         set_com_err_gettext(gettext);
1932 #endif
1933         if (argc && *argv)
1934                 program_name = *argv;
1935         add_error_table(&et_ext2_error_table);
1936
1937 #ifdef CONFIG_BUILD_FINDFS
1938         if (strcmp(get_progname(argv[0]), "findfs") == 0)
1939                 do_findfs(argc, argv);
1940 #endif
1941         if (strcmp(get_progname(argv[0]), "e2label") == 0)
1942                 parse_e2label_options(argc, argv);
1943         else
1944                 parse_tune2fs_options(argc, argv);
1945
1946 #ifdef CONFIG_TESTIO_DEBUG
1947         if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_DEBUG")) {
1948                 io_ptr = test_io_manager;
1949                 test_io_backing_manager = unix_io_manager;
1950         } else
1951 #endif
1952                 io_ptr = unix_io_manager;
1953
1954 retry_open:
1955         if ((open_flag & EXT2_FLAG_RW) == 0 || f_flag)
1956                 open_flag |= EXT2_FLAG_SKIP_MMP;
1957
1958         open_flag |= EXT2_FLAG_64BITS;
1959
1960         /* keep the filesystem struct around to dump MMP data */
1961         open_flag |= EXT2_FLAG_NOFREE_ON_ERROR;
1962
1963         retval = ext2fs_open2(device_name, io_options, open_flag,
1964                               0, 0, io_ptr, &fs);
1965         if (retval) {
1966                 com_err(program_name, retval,
1967                         _("while trying to open %s"),
1968                         device_name);
1969                 if (retval == EXT2_ET_MMP_FSCK_ON ||
1970                     retval == EXT2_ET_MMP_UNKNOWN_SEQ)
1971                         dump_mmp_msg(fs->mmp_buf,
1972                                      _("If you are sure the filesystem "
1973                                        "is not in use on any node, run:\n"
1974                                        "'tune2fs -f -E clear_mmp {device}'\n"));
1975                 else if (retval == EXT2_ET_MMP_FAILED)
1976                         dump_mmp_msg(fs->mmp_buf, NULL);
1977                 else if (retval == EXT2_ET_MMP_MAGIC_INVALID)
1978                         fprintf(stderr,
1979                                 _("MMP block magic is bad. Try to fix it by "
1980                                   "running:\n'e2fsck -f %s'\n"), device_name);
1981                 else if (retval != EXT2_ET_MMP_FAILED)
1982                         fprintf(stderr, "%s",
1983                              _("Couldn't find valid filesystem superblock.\n"));
1984
1985                 ext2fs_free(fs);
1986                 exit(1);
1987         }
1988         fs->default_bitmap_type = EXT2FS_BMAP64_RBTREE;
1989
1990         if (I_flag && !io_ptr_orig) {
1991                 /*
1992                  * Check the inode size is right so we can issue an
1993                  * error message and bail before setting up the tdb
1994                  * file.
1995                  */
1996                 if (new_inode_size == EXT2_INODE_SIZE(fs->super)) {
1997                         fprintf(stderr, _("The inode size is already %lu\n"),
1998                                 new_inode_size);
1999                         rc = 1;
2000                         goto closefs;
2001                 }
2002                 if (new_inode_size < EXT2_INODE_SIZE(fs->super)) {
2003                         fprintf(stderr, "%s",
2004                                 _("Shrinking inode size is not supported\n"));
2005                         rc = 1;
2006                         goto closefs;
2007                 }
2008                 if (new_inode_size > fs->blocksize) {
2009                         fprintf(stderr, _("Invalid inode size %lu (max %d)\n"),
2010                                 new_inode_size, fs->blocksize);
2011                         rc = 1;
2012                         goto closefs;
2013                 }
2014
2015                 /*
2016                  * If inode resize is requested use the
2017                  * Undo I/O manager
2018                  */
2019                 io_ptr_orig = io_ptr;
2020                 retval = tune2fs_setup_tdb(device_name, &io_ptr);
2021                 if (retval) {
2022                         rc = 1;
2023                         goto closefs;
2024                 }
2025                 if (io_ptr != io_ptr_orig) {
2026                         ext2fs_close_free(&fs);
2027                         goto retry_open;
2028                 }
2029         }
2030
2031         sb = fs->super;
2032         fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
2033
2034         if (print_label) {
2035                 /* For e2label emulation */
2036                 printf("%.*s\n", (int) sizeof(sb->s_volume_name),
2037                        sb->s_volume_name);
2038                 remove_error_table(&et_ext2_error_table);
2039                 goto closefs;
2040         }
2041
2042         retval = ext2fs_check_if_mounted(device_name, &mount_flags);
2043         if (retval) {
2044                 com_err("ext2fs_check_if_mount", retval,
2045                         _("while determining whether %s is mounted."),
2046                         device_name);
2047                 rc = 1;
2048                 goto closefs;
2049         }
2050         /* Normally we only need to write out the superblock */
2051         fs->flags |= EXT2_FLAG_SUPER_ONLY;
2052
2053         if (c_flag) {
2054                 sb->s_max_mnt_count = max_mount_count;
2055                 ext2fs_mark_super_dirty(fs);
2056                 printf(_("Setting maximal mount count to %d\n"),
2057                        max_mount_count);
2058         }
2059         if (C_flag) {
2060                 sb->s_mnt_count = mount_count;
2061                 ext2fs_mark_super_dirty(fs);
2062                 printf(_("Setting current mount count to %d\n"), mount_count);
2063         }
2064         if (e_flag) {
2065                 sb->s_errors = errors;
2066                 ext2fs_mark_super_dirty(fs);
2067                 printf(_("Setting error behavior to %d\n"), errors);
2068         }
2069         if (g_flag) {
2070                 sb->s_def_resgid = resgid;
2071                 ext2fs_mark_super_dirty(fs);
2072                 printf(_("Setting reserved blocks gid to %lu\n"), resgid);
2073         }
2074         if (i_flag) {
2075                 if ((unsigned long long)interval >= (1ULL << 32)) {
2076                         com_err(program_name, 0,
2077                                 _("interval between checks is too big (%lu)"),
2078                                 interval);
2079                         rc = 1;
2080                         goto closefs;
2081                 }
2082                 sb->s_checkinterval = interval;
2083                 ext2fs_mark_super_dirty(fs);
2084                 printf(_("Setting interval between checks to %lu seconds\n"),
2085                        interval);
2086         }
2087         if (m_flag) {
2088                 ext2fs_r_blocks_count_set(sb, reserved_ratio *
2089                                           ext2fs_blocks_count(sb) / 100.0);
2090                 ext2fs_mark_super_dirty(fs);
2091                 printf (_("Setting reserved blocks percentage to %g%% (%llu blocks)\n"),
2092                         reserved_ratio, ext2fs_r_blocks_count(sb));
2093         }
2094         if (r_flag) {
2095                 if (reserved_blocks > ext2fs_blocks_count(sb)/2) {
2096                         com_err(program_name, 0,
2097                                 _("reserved blocks count is too big (%llu)"),
2098                                 reserved_blocks);
2099                         rc = 1;
2100                         goto closefs;
2101                 }
2102                 ext2fs_r_blocks_count_set(sb, reserved_blocks);
2103                 ext2fs_mark_super_dirty(fs);
2104                 printf(_("Setting reserved blocks count to %llu\n"),
2105                        reserved_blocks);
2106         }
2107         if (s_flag == 1) {
2108                 if (sb->s_feature_ro_compat &
2109                     EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER) {
2110                         fputs(_("\nThe filesystem already has sparse "
2111                                 "superblocks.\n"), stderr);
2112                 } else if (sb->s_feature_incompat &
2113                         EXT2_FEATURE_INCOMPAT_META_BG) {
2114                         fputs(_("\nSetting the sparse superblock flag not "
2115                                 "supported\nfor filesystems with "
2116                                 "the meta_bg feature enabled.\n"),
2117                                 stderr);
2118                         rc = 1;
2119                         goto closefs;
2120                 } else {
2121                         sb->s_feature_ro_compat |=
2122                                 EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER;
2123                         sb->s_state &= ~EXT2_VALID_FS;
2124                         ext2fs_mark_super_dirty(fs);
2125                         printf(_("\nSparse superblock flag set.  %s"),
2126                                _(please_fsck));
2127                 }
2128         }
2129         if (s_flag == 0) {
2130                 fputs(_("\nClearing the sparse superblock flag not supported.\n"),
2131                       stderr);
2132                 rc = 1;
2133                 goto closefs;
2134         }
2135         if (T_flag) {
2136                 sb->s_lastcheck = last_check_time;
2137                 ext2fs_mark_super_dirty(fs);
2138                 printf(_("Setting time filesystem last checked to %s\n"),
2139                        ctime(&last_check_time));
2140         }
2141         if (u_flag) {
2142                 sb->s_def_resuid = resuid;
2143                 ext2fs_mark_super_dirty(fs);
2144                 printf(_("Setting reserved blocks uid to %lu\n"), resuid);
2145         }
2146         if (L_flag) {
2147                 if (strlen(new_label) > sizeof(sb->s_volume_name))
2148                         fputs(_("Warning: label too long, truncating.\n"),
2149                               stderr);
2150                 memset(sb->s_volume_name, 0, sizeof(sb->s_volume_name));
2151                 strncpy(sb->s_volume_name, new_label,
2152                         sizeof(sb->s_volume_name));
2153                 ext2fs_mark_super_dirty(fs);
2154         }
2155         if (M_flag) {
2156                 memset(sb->s_last_mounted, 0, sizeof(sb->s_last_mounted));
2157                 strncpy(sb->s_last_mounted, new_last_mounted,
2158                         sizeof(sb->s_last_mounted));
2159                 ext2fs_mark_super_dirty(fs);
2160         }
2161         if (mntopts_cmd) {
2162                 rc = update_mntopts(fs, mntopts_cmd);
2163                 if (rc)
2164                         goto closefs;
2165         }
2166         if (features_cmd) {
2167                 rc = update_feature_set(fs, features_cmd);
2168                 if (rc)
2169                         goto closefs;
2170         }
2171         if (extended_cmd) {
2172                 rc = parse_extended_opts(fs, extended_cmd);
2173                 if (rc)
2174                         goto closefs;
2175                 if (clear_mmp && !f_flag) {
2176                         fputs(_("Error in using clear_mmp. "
2177                                 "It must be used with -f\n"),
2178                               stderr);
2179                         goto closefs;
2180                 }
2181         }
2182         if (clear_mmp) {
2183                 rc = ext2fs_mmp_clear(fs);
2184                 goto closefs;
2185         }
2186         if (journal_size || journal_device) {
2187                 rc = add_journal(fs);
2188                 if (rc)
2189                         goto closefs;
2190         }
2191
2192         if (Q_flag) {
2193                 if (mount_flags & EXT2_MF_MOUNTED) {
2194                         fputs(_("The quota feature may only be changed when "
2195                                 "the filesystem is unmounted.\n"), stderr);
2196                         rc = 1;
2197                         goto closefs;
2198                 }
2199                 handle_quota_options(fs);
2200         }
2201
2202         if (U_flag) {
2203                 int set_csum = 0;
2204                 dgrp_t i;
2205                 char buf[SUPERBLOCK_SIZE];
2206
2207                 if (sb->s_feature_ro_compat &
2208                     EXT4_FEATURE_RO_COMPAT_GDT_CSUM) {
2209                         /*
2210                          * Changing the UUID requires rewriting all metadata,
2211                          * which can race with a mounted fs.  Don't allow that.
2212                          */
2213                         if (mount_flags & EXT2_MF_MOUNTED) {
2214                                 fputs(_("The UUID may only be "
2215                                         "changed when the filesystem is "
2216                                         "unmounted.\n"), stderr);
2217                                 exit(1);
2218                         }
2219                         if (check_fsck_needed(fs))
2220                                 exit(1);
2221
2222                         /*
2223                          * Determine if the block group checksums are
2224                          * correct so we know whether or not to set
2225                          * them later on.
2226                          */
2227                         for (i = 0; i < fs->group_desc_count; i++)
2228                                 if (!ext2fs_group_desc_csum_verify(fs, i))
2229                                         break;
2230                         if (i >= fs->group_desc_count)
2231                                 set_csum = 1;
2232                 }
2233                 if ((strcasecmp(new_UUID, "null") == 0) ||
2234                     (strcasecmp(new_UUID, "clear") == 0)) {
2235                         uuid_clear(sb->s_uuid);
2236                 } else if (strcasecmp(new_UUID, "time") == 0) {
2237                         uuid_generate_time(sb->s_uuid);
2238                 } else if (strcasecmp(new_UUID, "random") == 0) {
2239                         uuid_generate(sb->s_uuid);
2240                 } else if (uuid_parse(new_UUID, sb->s_uuid)) {
2241                         com_err(program_name, 0, "%s",
2242                                 _("Invalid UUID format\n"));
2243                         rc = 1;
2244                         goto closefs;
2245                 }
2246                 if (set_csum) {
2247                         for (i = 0; i < fs->group_desc_count; i++)
2248                                 ext2fs_group_desc_csum_set(fs, i);
2249                         fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
2250                 }
2251
2252                 /* If this is a journal dev, we need to copy UUID into jsb */
2253                 if (!(rc = get_journal_sb(fs, buf))) {
2254                         journal_superblock_t *jsb;
2255
2256                         jsb = (journal_superblock_t *) buf;
2257                         fputs(_("Need to update journal superblock.\n"), stdout);
2258                         memcpy(jsb->s_uuid, sb->s_uuid, sizeof(sb->s_uuid));
2259
2260                         /* Writeback the journal superblock */
2261                         if ((rc = io_channel_write_blk64(fs->io,
2262                                 ext2fs_journal_sb_start(fs->blocksize),
2263                                         -SUPERBLOCK_SIZE, buf)))
2264                                 goto closefs;
2265                 } else if (rc != EXT2_ET_UNSUPP_FEATURE)
2266                         goto closefs;
2267                 else
2268                         rc = 0; /** Reset rc to avoid ext2fs_mmp_stop() */
2269
2270                 ext2fs_mark_super_dirty(fs);
2271         }
2272         if (I_flag) {
2273                 if (mount_flags & EXT2_MF_MOUNTED) {
2274                         fputs(_("The inode size may only be "
2275                                 "changed when the filesystem is "
2276                                 "unmounted.\n"), stderr);
2277                         rc = 1;
2278                         goto closefs;
2279                 }
2280                 if (fs->super->s_feature_incompat &
2281                     EXT4_FEATURE_INCOMPAT_FLEX_BG) {
2282                         fputs(_("Changing the inode size not supported for "
2283                                 "filesystems with the flex_bg\n"
2284                                 "feature enabled.\n"),
2285                               stderr);
2286                         rc = 1;
2287                         goto closefs;
2288                 }
2289                 /*
2290                  * We want to update group descriptor also
2291                  * with the new free inode count
2292                  */
2293                 fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
2294                 if (resize_inode(fs, new_inode_size) == 0) {
2295                         printf(_("Setting inode size %lu\n"),
2296                                                         new_inode_size);
2297                 } else {
2298                         printf("%s", _("Failed to change inode size\n"));
2299                         rc = 1;
2300                         goto closefs;
2301                 }
2302         }
2303
2304         if (l_flag)
2305                 list_super(sb);
2306         if (stride_set) {
2307                 sb->s_raid_stride = stride;
2308                 ext2fs_mark_super_dirty(fs);
2309                 printf(_("Setting stride size to %d\n"), stride);
2310         }
2311         if (stripe_width_set) {
2312                 sb->s_raid_stripe_width = stripe_width;
2313                 ext2fs_mark_super_dirty(fs);
2314                 printf(_("Setting stripe width to %d\n"), stripe_width);
2315         }
2316         if (ext_mount_opts) {
2317                 strncpy((char *)(fs->super->s_mount_opts), ext_mount_opts,
2318                         sizeof(fs->super->s_mount_opts));
2319                 fs->super->s_mount_opts[sizeof(fs->super->s_mount_opts)-1] = 0;
2320                 ext2fs_mark_super_dirty(fs);
2321                 printf(_("Setting extended default mount options to '%s'\n"),
2322                        ext_mount_opts);
2323                 free(ext_mount_opts);
2324         }
2325         free(device_name);
2326         remove_error_table(&et_ext2_error_table);
2327
2328 closefs:
2329         if (rc) {
2330                 ext2fs_mmp_stop(fs);
2331                 exit(1);
2332         }
2333
2334         return (ext2fs_close_free(&fs) ? 1 : 0);
2335 }