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