Whamcloud - gitweb
2f7d9f3cb0e9fd250aa259871c34b4de5c89bee1
[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 #define _DEFAULT_SOURCE   /* since glibc 2.20 _BSD_SOURCE is deprecated */
48 #endif
49 #include <string.h>
50 #include <time.h>
51 #include <unistd.h>
52 #include <sys/types.h>
53 #include <libgen.h>
54 #include <limits.h>
55 #ifdef HAVE_SYS_IOCTL_H
56 #include <sys/ioctl.h>
57 #endif
58
59 #include "ext2fs/ext2_fs.h"
60 #include "ext2fs/ext2fs.h"
61 #include "ext2fs/kernel-jbd.h"
62 #include "et/com_err.h"
63 #include "support/plausible.h"
64 #include "support/quotaio.h"
65 #include "support/devname.h"
66 #include "uuid/uuid.h"
67 #include "e2p/e2p.h"
68 #include "util.h"
69 #include "blkid/blkid.h"
70
71 #include "../version.h"
72 #include "support/nls-enable.h"
73
74 #define QOPT_ENABLE     (1)
75 #define QOPT_DISABLE    (-1)
76
77 #ifndef FS_IOC_SETFSLABEL
78 #define FSLABEL_MAX 256
79 #define FS_IOC_SETFSLABEL       _IOW(0x94, 50, char[FSLABEL_MAX])
80 #endif
81
82 #ifndef FS_IOC_GETFSLABEL
83 #define FS_IOC_GETFSLABEL       _IOR(0x94, 49, char[FSLABEL_MAX])
84 #endif
85
86 struct fsuuid {
87         __u32   fsu_len;
88         __u32   fsu_flags;
89         __u8    fsu_uuid[];
90 };
91
92 #ifndef EXT4_IOC_GETFSUUID
93 #define EXT4_IOC_GETFSUUID      _IOR('f', 44, struct fsuuid)
94 #endif
95
96 #ifndef EXT4_IOC_SETFSUUID
97 #define EXT4_IOC_SETFSUUID      _IOW('f', 44, struct fsuuid)
98 #endif
99
100 extern int ask_yn(const char *string, int def);
101
102 const char *program_name = "tune2fs";
103 char *device_name;
104 char *new_label, *new_last_mounted, *requested_uuid;
105 char *io_options;
106 static int c_flag, C_flag, e_flag, f_flag, g_flag, i_flag, l_flag, L_flag;
107 static int m_flag, M_flag, Q_flag, r_flag, s_flag = -1, u_flag, U_flag, T_flag;
108 static int I_flag;
109 static int clear_mmp;
110 static time_t last_check_time;
111 static int print_label;
112 static int max_mount_count, mount_count, mount_flags;
113 static unsigned long interval;
114 static blk64_t reserved_blocks;
115 static double reserved_ratio;
116 static unsigned long resgid, resuid;
117 static unsigned short errors;
118 static int open_flag;
119 static char *features_cmd;
120 static char *mntopts_cmd;
121 static int stride, stripe_width;
122 static int stride_set, stripe_width_set;
123 static char *extended_cmd;
124 static unsigned long new_inode_size;
125 static char *ext_mount_opts;
126 static int quota_enable[MAXQUOTAS];
127 static int rewrite_checksums;
128 static int feature_64bit;
129 static int fsck_requested;
130 static char *undo_file;
131 int enabling_casefold;
132
133 int journal_size, journal_fc_size, journal_flags;
134 char *journal_device;
135 static blk64_t journal_location = ~0LL;
136 static e2_blkcnt_t orphan_file_blocks;
137
138 static struct list_head blk_move_list;
139
140 struct blk_move {
141         struct list_head list;
142         blk64_t old_loc;
143         blk64_t new_loc;
144 };
145
146 errcode_t ext2fs_run_ext3_journal(ext2_filsys *fs);
147
148 static const char *fsck_explain = N_("\nThis operation requires a freshly checked filesystem.\n");
149
150 static const char *please_fsck = N_("Please run e2fsck -f on the filesystem.\n");
151 static const char *please_dir_fsck =
152                 N_("Please run e2fsck -fD on the filesystem.\n");
153
154 #ifdef CONFIG_BUILD_FINDFS
155 void do_findfs(int argc, char **argv);
156 #endif
157
158 #ifdef CONFIG_JBD_DEBUG         /* Enabled by configure --enable-jbd-debug */
159 int journal_enable_debug = -1;
160 #endif
161
162 static void usage(void)
163 {
164         fprintf(stderr,
165                 _("Usage: %s [-c max_mounts_count] [-e errors_behavior] [-f] "
166                   "[-g group]\n"
167                   "\t[-i interval[d|m|w]] [-j] [-J journal_options] [-l]\n"
168                   "\t[-m reserved_blocks_percent] [-o [^]mount_options[,...]]\n"
169                   "\t[-r reserved_blocks_count] [-u user] [-C mount_count]\n"
170                   "\t[-L volume_label] [-M last_mounted_dir]\n"
171                   "\t[-O [^]feature[,...]] [-Q quota_options]\n"
172                   "\t[-E extended-option[,...]] [-T last_check_time] "
173                   "[-U UUID]\n\t[-I new_inode_size] [-z undo_file] device\n"),
174                 program_name);
175         exit(1);
176 }
177
178 static __u32 ok_features[3] = {
179         /* Compat */
180         EXT3_FEATURE_COMPAT_HAS_JOURNAL |
181                 EXT2_FEATURE_COMPAT_DIR_INDEX |
182                 EXT4_FEATURE_COMPAT_FAST_COMMIT |
183                 EXT4_FEATURE_COMPAT_STABLE_INODES |
184                 EXT4_FEATURE_COMPAT_ORPHAN_FILE,
185         /* Incompat */
186         EXT2_FEATURE_INCOMPAT_FILETYPE |
187                 EXT3_FEATURE_INCOMPAT_EXTENTS |
188                 EXT4_FEATURE_INCOMPAT_FLEX_BG |
189                 EXT4_FEATURE_INCOMPAT_EA_INODE|
190                 EXT4_FEATURE_INCOMPAT_MMP |
191                 EXT4_FEATURE_INCOMPAT_64BIT |
192                 EXT4_FEATURE_INCOMPAT_ENCRYPT |
193                 EXT4_FEATURE_INCOMPAT_CSUM_SEED |
194                 EXT4_FEATURE_INCOMPAT_LARGEDIR |
195                 EXT4_FEATURE_INCOMPAT_CASEFOLD,
196         /* R/O compat */
197         EXT2_FEATURE_RO_COMPAT_LARGE_FILE |
198                 EXT4_FEATURE_RO_COMPAT_HUGE_FILE|
199                 EXT4_FEATURE_RO_COMPAT_DIR_NLINK|
200                 EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE|
201                 EXT4_FEATURE_RO_COMPAT_GDT_CSUM |
202                 EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER |
203                 EXT4_FEATURE_RO_COMPAT_QUOTA |
204                 EXT4_FEATURE_RO_COMPAT_METADATA_CSUM |
205                 EXT4_FEATURE_RO_COMPAT_READONLY |
206                 EXT4_FEATURE_RO_COMPAT_PROJECT |
207                 EXT4_FEATURE_RO_COMPAT_VERITY
208 };
209
210 static __u32 clear_ok_features[3] = {
211         /* Compat */
212         EXT3_FEATURE_COMPAT_HAS_JOURNAL |
213                 EXT2_FEATURE_COMPAT_RESIZE_INODE |
214                 EXT2_FEATURE_COMPAT_DIR_INDEX |
215                 EXT4_FEATURE_COMPAT_FAST_COMMIT |
216                 EXT4_FEATURE_COMPAT_ORPHAN_FILE,
217         /* Incompat */
218         EXT2_FEATURE_INCOMPAT_FILETYPE |
219                 EXT4_FEATURE_INCOMPAT_FLEX_BG |
220                 EXT4_FEATURE_INCOMPAT_MMP |
221                 EXT4_FEATURE_INCOMPAT_64BIT |
222                 EXT4_FEATURE_INCOMPAT_CSUM_SEED |
223                 EXT4_FEATURE_INCOMPAT_CASEFOLD,
224         /* R/O compat */
225         EXT2_FEATURE_RO_COMPAT_LARGE_FILE |
226                 EXT4_FEATURE_RO_COMPAT_HUGE_FILE|
227                 EXT4_FEATURE_RO_COMPAT_DIR_NLINK|
228                 EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE|
229                 EXT4_FEATURE_RO_COMPAT_GDT_CSUM |
230                 EXT4_FEATURE_RO_COMPAT_QUOTA |
231                 EXT4_FEATURE_RO_COMPAT_PROJECT |
232                 EXT4_FEATURE_RO_COMPAT_METADATA_CSUM |
233                 EXT4_FEATURE_RO_COMPAT_READONLY
234 };
235
236 /**
237  * Try to get journal super block if any
238  */
239 static int get_journal_sb(ext2_filsys jfs, char buf[SUPERBLOCK_SIZE])
240 {
241         int retval;
242         journal_superblock_t *jsb;
243
244         if (!ext2fs_has_feature_journal_dev(jfs->super)) {
245                 return EXT2_ET_UNSUPP_FEATURE;
246         }
247
248         /* Get the journal superblock */
249         if ((retval = io_channel_read_blk64(jfs->io,
250             ext2fs_journal_sb_start(jfs->blocksize), -SUPERBLOCK_SIZE, buf))) {
251                 com_err(program_name, retval, "%s",
252                 _("while reading journal superblock"));
253                 return retval;
254         }
255
256         jsb = (journal_superblock_t *) buf;
257         if ((jsb->s_header.h_magic != (unsigned)ntohl(JBD2_MAGIC_NUMBER)) ||
258             (jsb->s_header.h_blocktype != (unsigned)ntohl(JBD2_SUPERBLOCK_V2))) {
259                 fputs(_("Journal superblock not found!\n"), stderr);
260                 return EXT2_ET_BAD_MAGIC;
261         }
262
263         return 0;
264 }
265
266 static __u8 *journal_user(__u8 uuid[UUID_SIZE], __u8 s_users[JBD2_USERS_SIZE],
267                           int nr_users)
268 {
269         int i;
270         for (i = 0; i < nr_users; i++) {
271                 if (memcmp(uuid, &s_users[i * UUID_SIZE], UUID_SIZE) == 0)
272                         return &s_users[i * UUID_SIZE];
273         }
274
275         return NULL;
276 }
277
278 /*
279  * Remove an external journal from the filesystem
280  */
281 static int remove_journal_device(ext2_filsys fs)
282 {
283         char            *journal_path;
284         ext2_filsys     jfs;
285         char            buf[SUPERBLOCK_SIZE] __attribute__ ((aligned(8)));
286         journal_superblock_t    *jsb;
287         int             i, nr_users;
288         errcode_t       retval;
289         int             commit_remove_journal = 0;
290         io_manager      io_ptr;
291
292         if (f_flag)
293                 commit_remove_journal = 1; /* force removal even if error */
294
295         uuid_unparse(fs->super->s_journal_uuid, buf);
296         journal_path = blkid_get_devname(NULL, "UUID", buf);
297
298         if (!journal_path) {
299                 journal_path =
300                         ext2fs_find_block_device(fs->super->s_journal_dev);
301                 if (!journal_path)
302                         goto no_valid_journal;
303         }
304
305 #ifdef CONFIG_TESTIO_DEBUG
306         if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_BLOCK")) {
307                 io_ptr = test_io_manager;
308                 test_io_backing_manager = unix_io_manager;
309         } else
310 #endif
311                 io_ptr = unix_io_manager;
312         retval = ext2fs_open(journal_path, EXT2_FLAG_RW|
313                              EXT2_FLAG_JOURNAL_DEV_OK, 0,
314                              fs->blocksize, io_ptr, &jfs);
315         if (retval) {
316                 com_err(program_name, retval, "%s",
317                         _("while trying to open external journal"));
318                 goto no_valid_journal;
319         }
320
321         if ((retval = get_journal_sb(jfs, buf))) {
322                 if (retval == EXT2_ET_UNSUPP_FEATURE)
323                         fprintf(stderr, _("%s is not a journal device.\n"),
324                                 journal_path);
325                 goto no_valid_journal;
326         }
327
328         jsb = (journal_superblock_t *) buf;
329         /* Find the filesystem UUID */
330         nr_users = ntohl(jsb->s_nr_users);
331         if (nr_users > JBD2_USERS_MAX) {
332                 fprintf(stderr, _("Journal superblock is corrupted, nr_users\n"
333                                  "is too high (%d).\n"), nr_users);
334                 commit_remove_journal = 1;
335                 goto no_valid_journal;
336         }
337
338         if (!journal_user(fs->super->s_uuid, jsb->s_users, nr_users)) {
339                 fputs(_("Filesystem's UUID not found on journal device.\n"),
340                       stderr);
341                 commit_remove_journal = 1;
342                 goto no_valid_journal;
343         }
344         nr_users--;
345         for (i = 0; i < nr_users; i++)
346                 memcpy(&jsb->s_users[i * 16], &jsb->s_users[(i + 1) * 16], 16);
347         jsb->s_nr_users = htonl(nr_users);
348
349         /* Write back the journal superblock */
350         retval = io_channel_write_blk64(jfs->io,
351                                         ext2fs_journal_sb_start(fs->blocksize),
352                                         -SUPERBLOCK_SIZE, buf);
353         if (retval) {
354                 com_err(program_name, retval,
355                         "while writing journal superblock.");
356                 goto no_valid_journal;
357         }
358
359         commit_remove_journal = 1;
360
361 no_valid_journal:
362         if (commit_remove_journal == 0) {
363                 fputs(_("Cannot locate journal device. It was NOT removed\n"
364                         "Use -f option to remove missing journal device.\n"),
365                       stderr);
366                 return 1;
367         }
368         fs->super->s_journal_dev = 0;
369         memset(fs->super->s_jnl_blocks, 0, sizeof(fs->super->s_jnl_blocks));
370         uuid_clear(fs->super->s_journal_uuid);
371         ext2fs_mark_super_dirty(fs);
372         fputs(_("Journal removed\n"), stdout);
373         free(journal_path);
374
375         return 0;
376 }
377
378 /* Helper function for remove_journal_inode */
379 static int release_blocks_proc(ext2_filsys fs, blk64_t *blocknr,
380                                e2_blkcnt_t blockcnt EXT2FS_ATTR((unused)),
381                                blk64_t ref_block EXT2FS_ATTR((unused)),
382                                int ref_offset EXT2FS_ATTR((unused)),
383                                void *private EXT2FS_ATTR((unused)))
384 {
385         blk64_t block;
386         int     group;
387
388         block = *blocknr;
389         ext2fs_unmark_block_bitmap2(fs->block_map, block);
390         group = ext2fs_group_of_blk2(fs, block);
391         ext2fs_bg_free_blocks_count_set(fs, group, ext2fs_bg_free_blocks_count(fs, group) + 1);
392         ext2fs_group_desc_csum_set(fs, group);
393         ext2fs_free_blocks_count_add(fs->super, EXT2FS_CLUSTER_RATIO(fs));
394         return 0;
395 }
396
397 /*
398  * Remove the journal inode from the filesystem
399  */
400 static errcode_t remove_journal_inode(ext2_filsys fs)
401 {
402         struct ext2_inode       inode;
403         errcode_t               retval;
404         ext2_ino_t              ino = fs->super->s_journal_inum;
405
406         retval = ext2fs_read_inode(fs, ino,  &inode);
407         if (retval) {
408                 com_err(program_name, retval, "%s",
409                         _("while reading journal inode"));
410                 return retval;
411         }
412         if (ino == EXT2_JOURNAL_INO) {
413                 retval = ext2fs_read_bitmaps(fs);
414                 if (retval) {
415                         com_err(program_name, retval, "%s",
416                                 _("while reading bitmaps"));
417                         return retval;
418                 }
419                 retval = ext2fs_block_iterate3(fs, ino,
420                                                BLOCK_FLAG_READ_ONLY, NULL,
421                                                release_blocks_proc, NULL);
422                 if (retval) {
423                         com_err(program_name, retval, "%s",
424                                 _("while clearing journal inode"));
425                         return retval;
426                 }
427                 fs->super->s_overhead_clusters -=
428                         EXT2FS_NUM_B2C(fs, EXT2_I_SIZE(&inode) / fs->blocksize);
429                 memset(&inode, 0, sizeof(inode));
430                 ext2fs_mark_bb_dirty(fs);
431                 fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
432         } else
433                 inode.i_flags &= ~EXT2_IMMUTABLE_FL;
434         retval = ext2fs_write_inode(fs, ino, &inode);
435         if (retval) {
436                 com_err(program_name, retval, "%s",
437                         _("while writing journal inode"));
438                 return retval;
439         }
440         fs->super->s_journal_inum = 0;
441         memset(fs->super->s_jnl_blocks, 0, sizeof(fs->super->s_jnl_blocks));
442         ext2fs_mark_super_dirty(fs);
443
444         return 0;
445 }
446
447 /*
448  * Update the default mount options
449  */
450 static int update_mntopts(ext2_filsys fs, char *mntopts)
451 {
452         struct ext2_super_block *sb = fs->super;
453
454         if (e2p_edit_mntopts(mntopts, &sb->s_default_mount_opts, ~0)) {
455                 fprintf(stderr, _("Invalid mount option set: %s\n"),
456                         mntopts);
457                 return 1;
458         }
459         ext2fs_mark_super_dirty(fs);
460
461         return 0;
462 }
463
464 static int check_fsck_needed(ext2_filsys fs, const char *prompt)
465 {
466         /* Refuse to modify anything but a freshly checked valid filesystem. */
467         if (!(fs->super->s_state & EXT2_VALID_FS) ||
468             (fs->super->s_state & EXT2_ERROR_FS) ||
469             (fs->super->s_lastcheck < fs->super->s_mtime)) {
470                 puts(_(fsck_explain));
471                 puts(_(please_fsck));
472                 if (mount_flags & EXT2_MF_READONLY)
473                         printf("%s", _("(and reboot afterwards!)\n"));
474                 return 1;
475         }
476
477         /* Give the admin a few seconds to bail out of a dangerous op. */
478         if (!getenv("TUNE2FS_FORCE_PROMPT") && (!isatty(0) || !isatty(1)))
479                 return 0;
480
481         puts(prompt);
482         proceed_question(5);
483
484         return 0;
485 }
486
487 static void request_dir_fsck_afterwards(ext2_filsys fs)
488 {
489         static int requested;
490
491         if (requested++)
492                 return;
493         fsck_requested++;
494         fs->super->s_state &= ~EXT2_VALID_FS;
495         puts(_(fsck_explain));
496         puts(_(please_dir_fsck));
497         if (mount_flags & EXT2_MF_READONLY)
498                 printf("%s", _("(and reboot afterwards!)\n"));
499 }
500
501 static void request_fsck_afterwards(ext2_filsys fs)
502 {
503         static int requested = 0;
504
505         if (requested++)
506                 return;
507         fsck_requested++;
508         fs->super->s_state &= ~EXT2_VALID_FS;
509         printf("\n%s\n", _(please_fsck));
510         if (mount_flags & EXT2_MF_READONLY)
511                 printf("%s", _("(and reboot afterwards!)\n"));
512 }
513
514 static void convert_64bit(ext2_filsys fs, int direction)
515 {
516         /*
517          * Is resize2fs going to demand a fsck run? Might as well tell the
518          * user now.
519          */
520         if (!fsck_requested &&
521             ((fs->super->s_state & EXT2_ERROR_FS) ||
522              !(fs->super->s_state & EXT2_VALID_FS) ||
523              fs->super->s_lastcheck < fs->super->s_mtime))
524                 request_fsck_afterwards(fs);
525         if (fsck_requested)
526                 fprintf(stderr, _("After running e2fsck, please run `resize2fs %s %s"),
527                         direction > 0 ? "-b" : "-s", fs->device_name);
528         else
529                 fprintf(stderr, _("Please run `resize2fs %s %s"),
530                         direction > 0 ? "-b" : "-s", fs->device_name);
531
532         if (undo_file)
533                 fprintf(stderr, _(" -z \"%s\""), undo_file);
534         if (direction > 0)
535                 fprintf(stderr, _("' to enable 64-bit mode.\n"));
536         else
537                 fprintf(stderr, _("' to disable 64-bit mode.\n"));
538 }
539
540 /*
541  * Rewrite directory blocks with checksums
542  */
543 struct rewrite_dir_context {
544         char *buf;
545         errcode_t errcode;
546         ext2_ino_t dir;
547         int is_htree:1;
548         int clear_htree:1;
549 };
550
551 static int rewrite_dir_block(ext2_filsys fs,
552                              blk64_t    *blocknr,
553                              e2_blkcnt_t blockcnt EXT2FS_ATTR((unused)),
554                              blk64_t    ref_block EXT2FS_ATTR((unused)),
555                              int        ref_offset EXT2FS_ATTR((unused)),
556                              void       *priv_data)
557 {
558         struct ext2_dx_countlimit *dcl = NULL;
559         struct rewrite_dir_context *ctx = priv_data;
560         int dcl_offset, changed = 0;
561
562         ctx->errcode = ext2fs_read_dir_block4(fs, *blocknr, ctx->buf, 0,
563                                               ctx->dir);
564         if (ctx->errcode)
565                 return BLOCK_ABORT;
566
567         /*
568          * if htree node... Note that if we are clearing htree structures from
569          * the directory, we treat the htree internal block as an ordinary leaf.
570          * The code below will do the right thing and make space for checksum
571          * there.
572          */
573         if (ctx->is_htree && !ctx->clear_htree)
574                 ext2fs_get_dx_countlimit(fs, (struct ext2_dir_entry *)ctx->buf,
575                                          &dcl, &dcl_offset);
576         if (dcl) {
577                 if (!ext2fs_has_feature_metadata_csum(fs->super)) {
578                         /* Ensure limit is the max size */
579                         int max_entries = (fs->blocksize - dcl_offset) /
580                                           sizeof(struct ext2_dx_entry);
581                         if (ext2fs_le16_to_cpu(dcl->limit) != max_entries) {
582                                 changed = 1;
583                                 dcl->limit = ext2fs_cpu_to_le16(max_entries);
584                         }
585                 } else {
586                         /* If htree block is full then rebuild the dir */
587                         if (ext2fs_le16_to_cpu(dcl->count) ==
588                             ext2fs_le16_to_cpu(dcl->limit)) {
589                                 request_dir_fsck_afterwards(fs);
590                                 return 0;
591                         }
592                         /*
593                          * Ensure dcl->limit is small enough to leave room for
594                          * the checksum tail.
595                          */
596                         int max_entries = (fs->blocksize - (dcl_offset +
597                                                 sizeof(struct ext2_dx_tail))) /
598                                           sizeof(struct ext2_dx_entry);
599                         if (ext2fs_le16_to_cpu(dcl->limit) != max_entries)
600                                 dcl->limit = ext2fs_cpu_to_le16(max_entries);
601                         /* Always rewrite checksum */
602                         changed = 1;
603                 }
604         } else {
605                 unsigned int rec_len, name_size;
606                 char *top = ctx->buf + fs->blocksize;
607                 struct ext2_dir_entry *de = (struct ext2_dir_entry *)ctx->buf;
608                 struct ext2_dir_entry *last_de = NULL, *penultimate_de = NULL;
609
610                 /* Find last and penultimate dirent */
611                 while ((char *)de < top) {
612                         penultimate_de = last_de;
613                         last_de = de;
614                         ctx->errcode = ext2fs_get_rec_len(fs, de, &rec_len);
615                         if (!ctx->errcode && !rec_len)
616                                 ctx->errcode = EXT2_ET_DIR_CORRUPTED;
617                         if (ctx->errcode)
618                                 return BLOCK_ABORT;
619                         de = (struct ext2_dir_entry *)(((char *)de) + rec_len);
620                 }
621                 ctx->errcode = ext2fs_get_rec_len(fs, last_de, &rec_len);
622                 if (ctx->errcode)
623                         return BLOCK_ABORT;
624                 name_size = ext2fs_dirent_name_len(last_de);
625
626                 if (!ext2fs_has_feature_metadata_csum(fs->super)) {
627                         if (!penultimate_de)
628                                 return 0;
629                         if (last_de->inode ||
630                             name_size ||
631                             rec_len != sizeof(struct ext2_dir_entry_tail))
632                                 return 0;
633                         /*
634                          * The last dirent is unused and the right length to
635                          * have stored a checksum.  Erase it.
636                          */
637                         ctx->errcode = ext2fs_get_rec_len(fs, penultimate_de,
638                                                           &rec_len);
639                         if (!rec_len)
640                                 ctx->errcode = EXT2_ET_DIR_CORRUPTED;
641                         if (ctx->errcode)
642                                 return BLOCK_ABORT;
643                         ext2fs_set_rec_len(fs, rec_len +
644                                         sizeof(struct ext2_dir_entry_tail),
645                                         penultimate_de);
646                         changed = 1;
647                 } else {
648                         unsigned csum_size = sizeof(struct ext2_dir_entry_tail);
649                         struct ext2_dir_entry_tail *t;
650
651                         /*
652                          * If the last dirent looks like the tail, just update
653                          * the checksum.
654                          */
655                         if (!last_de->inode &&
656                             rec_len == csum_size) {
657                                 t = (struct ext2_dir_entry_tail *)last_de;
658                                 t->det_reserved_name_len =
659                                                 EXT2_DIR_NAME_LEN_CSUM;
660                                 changed = 1;
661                                 goto out;
662                         }
663                         if (name_size & 3)
664                                 name_size = (name_size & ~3) + 4;
665                         /* If there's not enough space for the tail, e2fsck */
666                         if (rec_len <= (8 + name_size + csum_size)) {
667                                 request_dir_fsck_afterwards(fs);
668                                 return 0;
669                         }
670                         /* Shorten that last de and insert the tail */
671                         ext2fs_set_rec_len(fs, rec_len - csum_size, last_de);
672                         t = EXT2_DIRENT_TAIL(ctx->buf, fs->blocksize);
673                         ext2fs_initialize_dirent_tail(fs, t);
674
675                         /* Always update checksum */
676                         changed = 1;
677                 }
678         }
679
680 out:
681         if (!changed)
682                 return 0;
683
684         ctx->errcode = ext2fs_write_dir_block4(fs, *blocknr, ctx->buf,
685                                                0, ctx->dir);
686         if (ctx->errcode)
687                 return BLOCK_ABORT;
688
689         return 0;
690 }
691
692 static errcode_t rewrite_directory(ext2_filsys fs, ext2_ino_t dir,
693                                    struct ext2_inode *inode)
694 {
695         errcode_t       retval;
696         struct rewrite_dir_context ctx;
697
698         retval = ext2fs_get_mem(fs->blocksize, &ctx.buf);
699         if (retval)
700                 return retval;
701
702         ctx.is_htree = !!(inode->i_flags & EXT2_INDEX_FL);
703         ctx.clear_htree = !ext2fs_has_feature_dir_index(fs->super);
704         ctx.dir = dir;
705         ctx.errcode = 0;
706         retval = ext2fs_block_iterate3(fs, dir, BLOCK_FLAG_READ_ONLY |
707                                                 BLOCK_FLAG_DATA_ONLY,
708                                        0, rewrite_dir_block, &ctx);
709
710         ext2fs_free_mem(&ctx.buf);
711         if (retval)
712                 return retval;
713
714         if (ctx.is_htree && ctx.clear_htree) {
715                 inode->i_flags &= ~EXT2_INDEX_FL;
716                 retval = ext2fs_write_inode(fs, dir, inode);
717                 if (retval)
718                         return retval;
719         }
720
721         return ctx.errcode;
722 }
723
724 /*
725  * Context information that does not change across rewrite_one_inode()
726  * invocations.
727  */
728 struct rewrite_context {
729         ext2_filsys fs;
730         struct ext2_inode *zero_inode;
731         char *ea_buf;
732         int inode_size;
733 };
734
735 #define fatal_err(code, args...)                \
736         do {                                    \
737                 com_err(__func__, code, args);  \
738                 exit(1);                        \
739         } while (0);
740
741 static void update_ea_inode_hash(struct rewrite_context *ctx, ext2_ino_t ino,
742                                  struct ext2_inode *inode)
743 {
744         errcode_t retval;
745         ext2_file_t file;
746         __u32 hash;
747
748         retval = ext2fs_file_open(ctx->fs, ino, 0, &file);
749         if (retval)
750                 fatal_err(retval, "open ea_inode");
751         retval = ext2fs_file_read(file, ctx->ea_buf, inode->i_size,
752                                   NULL);
753         if (retval)
754                 fatal_err(retval, "read ea_inode");
755         retval = ext2fs_file_close(file);
756         if (retval)
757                 fatal_err(retval, "close ea_inode");
758
759         hash = ext2fs_crc32c_le(ctx->fs->csum_seed,
760                                 (unsigned char *) ctx->ea_buf, inode->i_size);
761         ext2fs_set_ea_inode_hash(inode, hash);
762 }
763
764 static int update_xattr_entry_hashes(ext2_filsys fs,
765                                      struct ext2_ext_attr_entry *entry,
766                                      struct ext2_ext_attr_entry *end)
767 {
768         int modified = 0;
769         errcode_t retval;
770
771         while (entry < end && !EXT2_EXT_IS_LAST_ENTRY(entry)) {
772                 if (entry->e_value_inum) {
773                         retval = ext2fs_ext_attr_hash_entry2(fs, entry, NULL,
774                                                              &entry->e_hash);
775                         if (retval)
776                                 fatal_err(retval, "hash ea_inode entry");
777                         modified = 1;
778                 }
779                 entry = EXT2_EXT_ATTR_NEXT(entry);
780         }
781         return modified;
782 }
783
784 static void update_inline_xattr_hashes(struct rewrite_context *ctx,
785                                        struct ext2_inode_large *inode)
786 {
787         struct ext2_ext_attr_entry *start, *end;
788         __u32 *ea_magic;
789
790         if (inode->i_extra_isize == 0)
791                 return;
792
793         if (inode->i_extra_isize & 3 ||
794             inode->i_extra_isize > ctx->inode_size - EXT2_GOOD_OLD_INODE_SIZE)
795                 fatal_err(EXT2_ET_INODE_CORRUPTED, "bad i_extra_isize")
796
797         ea_magic = (__u32 *)((char *)inode + EXT2_GOOD_OLD_INODE_SIZE +
798                                 inode->i_extra_isize);
799         if (*ea_magic != EXT2_EXT_ATTR_MAGIC)
800                 return;
801
802         start = (struct ext2_ext_attr_entry *)(ea_magic + 1);
803         end = (struct ext2_ext_attr_entry *)((char *)inode + ctx->inode_size);
804
805         update_xattr_entry_hashes(ctx->fs, start, end);
806 }
807
808 static void update_block_xattr_hashes(struct rewrite_context *ctx,
809                                       char *block_buf)
810 {
811         struct ext2_ext_attr_header *header;
812         struct ext2_ext_attr_entry *start, *end;
813
814         header = (struct ext2_ext_attr_header *)block_buf;
815         if (header->h_magic != EXT2_EXT_ATTR_MAGIC)
816                 return;
817
818         start = (struct ext2_ext_attr_entry *)(header+1);
819         end = (struct ext2_ext_attr_entry *)(block_buf + ctx->fs->blocksize);
820
821         if (update_xattr_entry_hashes(ctx->fs, start, end))
822                 ext2fs_ext_attr_block_rehash(header, end);
823 }
824
825 static void rewrite_one_inode(struct rewrite_context *ctx, ext2_ino_t ino,
826                               struct ext2_inode *inode)
827 {
828         blk64_t file_acl_block;
829         errcode_t retval;
830
831         if (!ext2fs_test_inode_bitmap2(ctx->fs->inode_map, ino)) {
832                 if (!memcmp(inode, ctx->zero_inode, ctx->inode_size))
833                         return;
834                 memset(inode, 0, ctx->inode_size);
835         }
836
837         if (inode->i_flags & EXT4_EA_INODE_FL)
838                 update_ea_inode_hash(ctx, ino, inode);
839
840         if (ctx->inode_size != EXT2_GOOD_OLD_INODE_SIZE)
841                 update_inline_xattr_hashes(ctx,
842                                            (struct ext2_inode_large *)inode);
843
844         retval = ext2fs_write_inode_full(ctx->fs, ino, inode, ctx->inode_size);
845         if (retval)
846                 fatal_err(retval, "while writing inode");
847
848         retval = ext2fs_fix_extents_checksums(ctx->fs, ino, inode);
849         if (retval)
850                 fatal_err(retval, "while rewriting extents");
851
852         if (LINUX_S_ISDIR(inode->i_mode) &&
853             ext2fs_inode_has_valid_blocks2(ctx->fs, inode)) {
854                 retval = rewrite_directory(ctx->fs, ino, inode);
855                 if (retval)
856                         fatal_err(retval, "while rewriting directories");
857         }
858
859         file_acl_block = ext2fs_file_acl_block(ctx->fs, inode);
860         if (!file_acl_block)
861                 return;
862
863         retval = ext2fs_read_ext_attr3(ctx->fs, file_acl_block, ctx->ea_buf,
864                                        ino);
865         if (retval)
866                 fatal_err(retval, "while rewriting extended attribute");
867
868         update_block_xattr_hashes(ctx, ctx->ea_buf);
869         retval = ext2fs_write_ext_attr3(ctx->fs, file_acl_block, ctx->ea_buf,
870                                         ino);
871         if (retval)
872                 fatal_err(retval, "while rewriting extended attribute");
873 }
874
875 #define REWRITE_EA_FL           0x01    /* Rewrite EA inodes */
876 #define REWRITE_DIR_FL          0x02    /* Rewrite directories */
877 #define REWRITE_NONDIR_FL       0x04    /* Rewrite other inodes */
878 #define REWRITE_ALL (REWRITE_EA_FL | REWRITE_DIR_FL | REWRITE_NONDIR_FL)
879
880 static void rewrite_inodes_pass(struct rewrite_context *ctx, unsigned int flags)
881 {
882         ext2_inode_scan scan;
883         errcode_t       retval;
884         ext2_ino_t      ino;
885         struct ext2_inode *inode;
886         int rewrite;
887
888         retval = ext2fs_get_mem(ctx->inode_size, &inode);
889         if (retval)
890                 fatal_err(retval, "while allocating memory");
891
892         retval = ext2fs_open_inode_scan(ctx->fs, 0, &scan);
893         if (retval)
894                 fatal_err(retval, "while opening inode scan");
895
896         do {
897                 retval = ext2fs_get_next_inode_full(scan, &ino, inode,
898                                                     ctx->inode_size);
899                 if (retval)
900                         fatal_err(retval, "while getting next inode");
901                 if (!ino)
902                         break;
903
904                 rewrite = 0;
905                 if (inode->i_flags & EXT4_EA_INODE_FL) {
906                         if (flags & REWRITE_EA_FL)
907                                 rewrite = 1;
908                 } else if (LINUX_S_ISDIR(inode->i_mode)) {
909                         if (flags & REWRITE_DIR_FL)
910                                 rewrite = 1;
911                 } else {
912                         if (flags & REWRITE_NONDIR_FL)
913                                 rewrite = 1;
914                 }
915                 if (rewrite)
916                         rewrite_one_inode(ctx, ino, inode);
917         } while (ino);
918         ext2fs_close_inode_scan(scan);
919         ext2fs_free_mem(&inode);
920 }
921
922 /*
923  * Forcibly rewrite checksums in inodes specified by 'flags'
924  */
925 static void rewrite_inodes(ext2_filsys fs, unsigned int flags)
926 {
927         struct rewrite_context ctx = {
928                 .fs = fs,
929                 .inode_size = EXT2_INODE_SIZE(fs->super),
930         };
931         errcode_t retval;
932
933         if (fs->super->s_creator_os == EXT2_OS_HURD)
934                 return;
935
936         retval = ext2fs_get_memzero(ctx.inode_size, &ctx.zero_inode);
937         if (retval)
938                 fatal_err(retval, "while allocating memory");
939
940         retval = ext2fs_get_mem(64 * 1024, &ctx.ea_buf);
941         if (retval)
942                 fatal_err(retval, "while allocating memory");
943
944         /*
945          * Extended attribute inodes have a lookup hash that needs to be
946          * recalculated with the new csum_seed. Other inodes referencing xattr
947          * inodes need this value to be up to date. That's why we do two passes:
948          *
949          * pass 1: update xattr inodes to update their lookup hash as well as
950          *         other checksums.
951          *
952          * pass 2: go over other inodes to update their checksums.
953          */
954         if (ext2fs_has_feature_ea_inode(fs->super) && (flags & REWRITE_EA_FL))
955                 rewrite_inodes_pass(&ctx, REWRITE_EA_FL);
956         flags &= ~REWRITE_EA_FL;
957         rewrite_inodes_pass(&ctx, flags);
958
959         ext2fs_free_mem(&ctx.zero_inode);
960         ext2fs_free_mem(&ctx.ea_buf);
961 }
962
963 static errcode_t rewrite_metadata_checksums(ext2_filsys fs, unsigned int flags)
964 {
965         errcode_t retval;
966         dgrp_t i;
967
968         fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS;
969         ext2fs_init_csum_seed(fs);
970         for (i = 0; i < fs->group_desc_count; i++)
971                 ext2fs_group_desc_csum_set(fs, i);
972         retval = ext2fs_read_bitmaps(fs);
973         if (retval)
974                 fatal_err(retval, "while reading bitmaps");
975         rewrite_inodes(fs, flags);
976         ext2fs_mark_ib_dirty(fs);
977         ext2fs_mark_bb_dirty(fs);
978         retval = ext2fs_mmp_update2(fs, 1);
979         if (retval)
980                 return retval;
981         fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
982         fs->flags &= ~EXT2_FLAG_IGNORE_CSUM_ERRORS;
983         if (ext2fs_has_feature_metadata_csum(fs->super))
984                 fs->super->s_checksum_type = EXT2_CRC32C_CHKSUM;
985         else
986                 fs->super->s_checksum_type = 0;
987         ext2fs_mark_super_dirty(fs);
988         return 0;
989 }
990
991 static void enable_uninit_bg(ext2_filsys fs)
992 {
993         struct ext2_group_desc *gd;
994         dgrp_t i;
995
996         for (i = 0; i < fs->group_desc_count; i++) {
997                 gd = ext2fs_group_desc(fs, fs->group_desc, i);
998                 gd->bg_itable_unused = 0;
999                 gd->bg_flags = EXT2_BG_INODE_ZEROED;
1000                 ext2fs_group_desc_csum_set(fs, i);
1001         }
1002         fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
1003 }
1004
1005 static errcode_t zero_empty_inodes(ext2_filsys fs)
1006 {
1007         int length = EXT2_INODE_SIZE(fs->super);
1008         struct ext2_inode *inode = NULL;
1009         ext2_inode_scan scan;
1010         errcode_t       retval;
1011         ext2_ino_t      ino;
1012
1013         retval = ext2fs_open_inode_scan(fs, 0, &scan);
1014         if (retval)
1015                 goto out;
1016
1017         retval = ext2fs_get_mem(length, &inode);
1018         if (retval)
1019                 goto out;
1020
1021         do {
1022                 retval = ext2fs_get_next_inode_full(scan, &ino, inode, length);
1023                 if (retval)
1024                         goto out;
1025                 if (!ino)
1026                         break;
1027                 if (!ext2fs_test_inode_bitmap2(fs->inode_map, ino)) {
1028                         memset(inode, 0, length);
1029                         retval = ext2fs_write_inode_full(fs, ino, inode,
1030                                                          length);
1031                         if (retval)
1032                                 goto out;
1033                 }
1034         } while (1);
1035
1036 out:
1037         ext2fs_free_mem(&inode);
1038         ext2fs_close_inode_scan(scan);
1039         return retval;
1040 }
1041
1042 static int has_casefold_inode(ext2_filsys fs)
1043 {
1044         int length = EXT2_INODE_SIZE(fs->super);
1045         struct ext2_inode *inode = NULL;
1046         ext2_inode_scan scan;
1047         errcode_t       retval;
1048         ext2_ino_t      ino;
1049         int found_casefold = 0;
1050
1051         retval = ext2fs_get_mem(length, &inode);
1052         if (retval)
1053                 fatal_err(retval, "while allocating memory");
1054
1055         retval = ext2fs_open_inode_scan(fs, 0, &scan);
1056         if (retval)
1057                 fatal_err(retval, "while opening inode scan");
1058
1059         do {
1060                 retval = ext2fs_get_next_inode_full(scan, &ino, inode, length);
1061                 if (retval)
1062                         fatal_err(retval, "while getting next inode");
1063                 if (!ino)
1064                         break;
1065
1066                 if(inode->i_flags & EXT4_CASEFOLD_FL) {
1067                         found_casefold = 1;
1068                         break;
1069                 }
1070         } while(1);
1071
1072         ext2fs_free_mem(&inode);
1073         ext2fs_close_inode_scan(scan);
1074         return found_casefold;
1075 }
1076
1077 static errcode_t disable_uninit_bg(ext2_filsys fs, __u32 csum_feature_flag)
1078 {
1079         struct ext2_group_desc *gd;
1080         dgrp_t i;
1081         errcode_t retval;
1082         blk64_t b, c, d;
1083
1084         /* Load bitmaps to ensure that the uninit ones get written out */
1085         fs->super->s_feature_ro_compat |= csum_feature_flag;
1086         retval = ext2fs_read_bitmaps(fs);
1087         fs->super->s_feature_ro_compat &= ~csum_feature_flag;
1088         if (retval) {
1089                 com_err("disable_uninit_bg", retval,
1090                         "while reading bitmaps");
1091                 request_fsck_afterwards(fs);
1092                 return retval;
1093         }
1094         ext2fs_mark_ib_dirty(fs);
1095         ext2fs_mark_bb_dirty(fs);
1096
1097         /* If we're only turning off uninit_bg, zero the inodes */
1098         if (csum_feature_flag == EXT4_FEATURE_RO_COMPAT_GDT_CSUM) {
1099                 retval = zero_empty_inodes(fs);
1100                 if (retval) {
1101                         com_err("disable_uninit_bg", retval,
1102                                 "while zeroing unused inodes");
1103                         request_fsck_afterwards(fs);
1104                         return retval;
1105                 }
1106         }
1107
1108         /* The bbitmap is zeroed; we must mark group metadata blocks in use */
1109         for (i = 0; i < fs->group_desc_count; i++) {
1110                 b = ext2fs_block_bitmap_loc(fs, i);
1111                 ext2fs_mark_block_bitmap2(fs->block_map, b);
1112                 b = ext2fs_inode_bitmap_loc(fs, i);
1113                 ext2fs_mark_block_bitmap2(fs->block_map, b);
1114
1115                 retval = ext2fs_super_and_bgd_loc2(fs, i, &b, &c, &d, NULL);
1116                 if (retval == 0 && b)
1117                         ext2fs_mark_block_bitmap2(fs->block_map, b);
1118                 if (retval == 0 && c)
1119                         ext2fs_mark_block_bitmap2(fs->block_map, c);
1120                 if (retval == 0 && d)
1121                         ext2fs_mark_block_bitmap2(fs->block_map, d);
1122                 if (retval) {
1123                         com_err("disable_uninit_bg", retval,
1124                                 "while initializing block bitmaps");
1125                         request_fsck_afterwards(fs);
1126                 }
1127
1128                 gd = ext2fs_group_desc(fs, fs->group_desc, i);
1129                 gd->bg_itable_unused = 0;
1130                 gd->bg_flags = 0;
1131                 ext2fs_group_desc_csum_set(fs, i);
1132         }
1133         fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
1134         ext2fs_mark_super_dirty(fs);
1135
1136         return 0;
1137 }
1138
1139 static void
1140 try_confirm_csum_seed_support(void)
1141 {
1142         if (access("/sys/fs/ext4/features/metadata_csum_seed", R_OK))
1143                 fputs(_("WARNING: Could not confirm kernel support for "
1144                         "metadata_csum_seed.\n  This requires Linux >= "
1145                         "v4.4.\n"), stderr);
1146 }
1147
1148 /*
1149  * Update the feature set as provided by the user.
1150  */
1151 static int update_feature_set(ext2_filsys fs, char *features)
1152 {
1153         struct ext2_super_block *sb = fs->super;
1154         __u32           old_features[3];
1155         int             type_err;
1156         unsigned int    mask_err;
1157         errcode_t       err;
1158         enum quota_type qtype;
1159
1160 #define FEATURE_ON(type, mask) (!(old_features[(type)] & (mask)) && \
1161                                 ((&sb->s_feature_compat)[(type)] & (mask)))
1162 #define FEATURE_OFF(type, mask) ((old_features[(type)] & (mask)) && \
1163                                  !((&sb->s_feature_compat)[(type)] & (mask)))
1164 #define FEATURE_CHANGED(type, mask) ((mask) & \
1165                      (old_features[(type)] ^ (&sb->s_feature_compat)[(type)]))
1166
1167         old_features[E2P_FEATURE_COMPAT] = sb->s_feature_compat;
1168         old_features[E2P_FEATURE_INCOMPAT] = sb->s_feature_incompat;
1169         old_features[E2P_FEATURE_RO_INCOMPAT] = sb->s_feature_ro_compat;
1170
1171         if (e2p_edit_feature2(features, &sb->s_feature_compat,
1172                               ok_features, clear_ok_features,
1173                               &type_err, &mask_err)) {
1174                 if (!mask_err)
1175                         fprintf(stderr,
1176                                 _("Invalid filesystem option set: %s\n"),
1177                                 features);
1178                 else if (type_err & E2P_FEATURE_NEGATE_FLAG)
1179                         fprintf(stderr, _("Clearing filesystem feature '%s' "
1180                                           "not supported.\n"),
1181                                 e2p_feature2string(type_err &
1182                                                    E2P_FEATURE_TYPE_MASK,
1183                                                    mask_err));
1184                 else
1185                         fprintf(stderr, _("Setting filesystem feature '%s' "
1186                                           "not supported.\n"),
1187                                 e2p_feature2string(type_err, mask_err));
1188                 return 1;
1189         }
1190
1191         if (FEATURE_OFF(E2P_FEATURE_COMPAT, EXT3_FEATURE_COMPAT_HAS_JOURNAL)) {
1192                 if ((mount_flags & EXT2_MF_MOUNTED) &&
1193                     !(mount_flags & EXT2_MF_READONLY)) {
1194                         fputs(_("The has_journal feature may only be "
1195                                 "cleared when the filesystem is\n"
1196                                 "unmounted or mounted "
1197                                 "read-only.\n"), stderr);
1198                         return 1;
1199                 }
1200                 if (ext2fs_has_feature_journal_needs_recovery(sb) &&
1201                     f_flag < 2) {
1202                         fputs(_("The needs_recovery flag is set.  "
1203                                 "Please run e2fsck before clearing\n"
1204                                 "the has_journal flag.\n"), stderr);
1205                         return 1;
1206                 }
1207                 if (sb->s_journal_inum) {
1208                         if (remove_journal_inode(fs))
1209                                 return 1;
1210                 }
1211                 if (sb->s_journal_dev) {
1212                         if (remove_journal_device(fs))
1213                                 return 1;
1214                 }
1215         }
1216
1217         if (FEATURE_OFF(E2P_FEATURE_COMPAT, EXT4_FEATURE_COMPAT_ORPHAN_FILE)) {
1218                 ext2_ino_t ino;
1219
1220                 if (mount_flags & EXT2_MF_MOUNTED) {
1221                         fputs(_("The orphan_file feature may only be cleared "
1222                                 "when the filesystem is unmounted.\n"), stderr);
1223                         return 1;
1224                 }
1225                 if (ext2fs_has_feature_orphan_present(sb) && f_flag < 2) {
1226                         fputs(_("The orphan_present feature is set. Please "
1227                                 "run e2fsck before clearing orphan_file "
1228                                 "feature.\n"),
1229                               stderr);
1230                         return 1;
1231                 }
1232                 err = ext2fs_read_bitmaps(fs);
1233                 if (err) {
1234                         com_err(program_name, err, "%s",
1235                                 _("while loading bitmaps"));
1236                         return 1;
1237                 }
1238                 err = ext2fs_truncate_orphan_file(fs);
1239                 if (err) {
1240                         com_err(program_name, err,
1241                                 _("\n\twhile trying to delete orphan file\n"));
1242                         return 1;
1243                 }
1244                 ino = sb->s_orphan_file_inum;
1245                 sb->s_orphan_file_inum = 0;
1246                 ext2fs_inode_alloc_stats2(fs, ino, -1, 0);
1247                 ext2fs_clear_feature_orphan_file(sb);
1248                 ext2fs_clear_feature_orphan_present(sb);
1249                 ext2fs_mark_super_dirty(fs);
1250         }
1251
1252         if (FEATURE_ON(E2P_FEATURE_COMPAT, EXT4_FEATURE_COMPAT_ORPHAN_FILE)) {
1253                 if (!ext2fs_has_feature_journal(sb)) {
1254                         fputs(_("orphan_file feature can be set only for "
1255                                 "filesystems with journal.\n"), stderr);
1256                         return 1;
1257                 }
1258                 /*
1259                  * If adding an orphan file, let the create orphan file
1260                  * code below handle setting the flag and creating it.
1261                  * We supply a default size if necessary.
1262                  */
1263                 orphan_file_blocks = ext2fs_default_orphan_file_blocks(fs);
1264                 ext2fs_set_feature_orphan_file(sb);
1265         }
1266
1267         if (FEATURE_ON(E2P_FEATURE_RO_INCOMPAT,
1268                 EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER)) {
1269                 if (ext2fs_has_feature_meta_bg(sb)) {
1270                         fputs(_("Setting filesystem feature 'sparse_super' "
1271                                 "not supported\nfor filesystems with "
1272                                 "the meta_bg feature enabled.\n"),
1273                                 stderr);
1274                         return 1;
1275                 }
1276         }
1277
1278         if (FEATURE_ON(E2P_FEATURE_INCOMPAT, EXT4_FEATURE_INCOMPAT_MMP)) {
1279                 int error;
1280
1281                 if ((mount_flags & EXT2_MF_MOUNTED) ||
1282                     (mount_flags & EXT2_MF_READONLY)) {
1283                         fputs(_("The multiple mount protection feature can't\n"
1284                                 "be set if the filesystem is mounted or\n"
1285                                 "read-only.\n"), stderr);
1286                         return 1;
1287                 }
1288
1289                 error = ext2fs_mmp_init(fs);
1290                 if (error) {
1291                         fputs(_("\nError while enabling multiple mount "
1292                                 "protection feature."), stderr);
1293                         return 1;
1294                 }
1295
1296                 /*
1297                  * We want to update group desc with the new free blocks count
1298                  */
1299                 fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
1300
1301                 printf(_("Multiple mount protection has been enabled "
1302                          "with update interval %ds.\n"),
1303                        sb->s_mmp_update_interval);
1304         }
1305
1306         if (FEATURE_OFF(E2P_FEATURE_INCOMPAT, EXT4_FEATURE_INCOMPAT_MMP)) {
1307                 int error;
1308
1309                 if (mount_flags & EXT2_MF_READONLY) {
1310                         fputs(_("The multiple mount protection feature cannot\n"
1311                                 "be disabled if the filesystem is readonly.\n"),
1312                                 stderr);
1313                         return 1;
1314                 }
1315
1316                 error = ext2fs_read_bitmaps(fs);
1317                 if (error) {
1318                         fputs(_("Error while reading bitmaps\n"), stderr);
1319                         return 1;
1320                 }
1321
1322                 error = ext2fs_mmp_read(fs, sb->s_mmp_block, NULL);
1323                 if (error) {
1324                         struct mmp_struct *mmp_cmp = fs->mmp_cmp;
1325
1326                         if (error == EXT2_ET_MMP_MAGIC_INVALID)
1327                                 printf(_("Magic number in MMP block does not "
1328                                          "match. expected: %x, actual: %x\n"),
1329                                          EXT4_MMP_MAGIC, mmp_cmp->mmp_magic);
1330                         else
1331                                 com_err(program_name, error, "%s",
1332                                         _("while reading MMP block."));
1333                         goto mmp_error;
1334                 }
1335
1336                 /* We need to force out the group descriptors as well */
1337                 fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
1338                 ext2fs_block_alloc_stats2(fs, sb->s_mmp_block, -1);
1339 mmp_error:
1340                 sb->s_mmp_block = 0;
1341                 sb->s_mmp_update_interval = 0;
1342         }
1343
1344         if (FEATURE_ON(E2P_FEATURE_COMPAT, EXT3_FEATURE_COMPAT_HAS_JOURNAL)) {
1345                 /*
1346                  * If adding a journal flag, let the create journal
1347                  * code below handle setting the flag and creating the
1348                  * journal.  We supply a default size if necessary.
1349                  */
1350                 if (!journal_size)
1351                         journal_size = -1;
1352                 ext2fs_clear_feature_journal(sb);
1353         }
1354
1355         if (FEATURE_ON(E2P_FEATURE_COMPAT, EXT2_FEATURE_COMPAT_DIR_INDEX)) {
1356                 if (!sb->s_def_hash_version)
1357                         sb->s_def_hash_version = EXT2_HASH_HALF_MD4;
1358                 if (uuid_is_null((unsigned char *) sb->s_hash_seed))
1359                         uuid_generate((unsigned char *) sb->s_hash_seed);
1360         }
1361
1362         if (FEATURE_OFF(E2P_FEATURE_COMPAT, EXT2_FEATURE_COMPAT_DIR_INDEX) &&
1363             ext2fs_has_feature_metadata_csum(sb)) {
1364                 if (check_fsck_needed(fs,
1365                         _("Disabling directory index on filesystem with "
1366                           "checksums could take some time.")))
1367                         return 1;
1368                 if (mount_flags & EXT2_MF_MOUNTED) {
1369                         fputs(_("Cannot disable dir_index on a mounted "
1370                                 "filesystem!\n"), stderr);
1371                         exit(1);
1372                 }
1373                 /*
1374                  * Clearing dir_index on checksummed filesystem requires
1375                  * rewriting all directories to update checksums.
1376                  */
1377                 rewrite_checksums |= REWRITE_DIR_FL;
1378         }
1379
1380         if (FEATURE_OFF(E2P_FEATURE_INCOMPAT, EXT4_FEATURE_INCOMPAT_FLEX_BG)) {
1381                 if (ext2fs_check_desc(fs)) {
1382                         fputs(_("Clearing the flex_bg flag would "
1383                                 "cause the the filesystem to be\n"
1384                                 "inconsistent.\n"), stderr);
1385                         return 1;
1386                 }
1387         }
1388
1389         if (FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
1390                             EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
1391                 if ((mount_flags & EXT2_MF_MOUNTED) &&
1392                     !(mount_flags & EXT2_MF_READONLY)) {
1393                         fputs(_("The huge_file feature may only be "
1394                                 "cleared when the filesystem is\n"
1395                                 "unmounted or mounted "
1396                                 "read-only.\n"), stderr);
1397                         return 1;
1398                 }
1399         }
1400
1401         if (FEATURE_ON(E2P_FEATURE_RO_INCOMPAT,
1402                        EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) {
1403                 if (check_fsck_needed(fs,
1404                         _("Enabling checksums could take some time.")))
1405                         return 1;
1406                 if (mount_flags & EXT2_MF_MOUNTED) {
1407                         fputs(_("Cannot enable metadata_csum on a mounted "
1408                                 "filesystem!\n"), stderr);
1409                         return 1;
1410                 }
1411                 if (!ext2fs_has_feature_extents(fs->super))
1412                         printf("%s",
1413                                _("Extents are not enabled.  The file extent "
1414                                  "tree can be checksummed, whereas block maps "
1415                                  "cannot.  Not enabling extents reduces the "
1416                                  "coverage of metadata checksumming.  "
1417                                  "Re-run with -O extent to rectify.\n"));
1418                 if (!ext2fs_has_feature_64bit(fs->super))
1419                         printf("%s",
1420                                _("64-bit filesystem support is not enabled.  "
1421                                  "The larger fields afforded by this feature "
1422                                  "enable full-strength checksumming.  "
1423                                  "Run resize2fs -b to rectify.\n"));
1424                 rewrite_checksums = REWRITE_ALL;
1425                 /* metadata_csum supersedes uninit_bg */
1426                 ext2fs_clear_feature_gdt_csum(fs->super);
1427
1428                 /* if uninit_bg was previously off, rewrite group desc */
1429                 if (!(old_features[E2P_FEATURE_RO_INCOMPAT] &
1430                       EXT4_FEATURE_RO_COMPAT_GDT_CSUM))
1431                         enable_uninit_bg(fs);
1432
1433                 /*
1434                  * Since metadata_csum supersedes uninit_bg, pretend like
1435                  * uninit_bg has been off all along.
1436                  */
1437                 old_features[E2P_FEATURE_RO_INCOMPAT] &=
1438                         ~EXT4_FEATURE_RO_COMPAT_GDT_CSUM;
1439         }
1440
1441         if (FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
1442                         EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) {
1443                 __u32   test_features[3];
1444
1445                 if (check_fsck_needed(fs,
1446                         _("Disabling checksums could take some time.")))
1447                         return 1;
1448                 if (mount_flags & EXT2_MF_MOUNTED) {
1449                         fputs(_("Cannot disable metadata_csum on a mounted "
1450                                 "filesystem!\n"), stderr);
1451                         return 1;
1452                 }
1453                 rewrite_checksums = REWRITE_ALL;
1454
1455                 /* Enable uninit_bg unless the user expressly turned it off */
1456                 memcpy(test_features, old_features, sizeof(test_features));
1457                 test_features[E2P_FEATURE_RO_INCOMPAT] |=
1458                                                 EXT4_FEATURE_RO_COMPAT_GDT_CSUM;
1459                 e2p_edit_feature2(features, test_features, ok_features,
1460                                   clear_ok_features, NULL, NULL);
1461                 if (test_features[E2P_FEATURE_RO_INCOMPAT] &
1462                                                 EXT4_FEATURE_RO_COMPAT_GDT_CSUM)
1463                         ext2fs_set_feature_gdt_csum(fs->super);
1464
1465                 /*
1466                  * If we're turning off metadata_csum and not turning on
1467                  * uninit_bg, rewrite group desc.
1468                  */
1469                 if (!ext2fs_has_feature_gdt_csum(fs->super)) {
1470                         err = disable_uninit_bg(fs,
1471                                         EXT4_FEATURE_RO_COMPAT_METADATA_CSUM);
1472                         if (err)
1473                                 return 1;
1474                 } else
1475                         /*
1476                          * metadata_csum previously provided uninit_bg, so if
1477                          * we're also setting the uninit_bg feature bit,
1478                          * pretend like it was previously enabled.  Checksums
1479                          * will be rewritten with crc16 later.
1480                          */
1481                         old_features[E2P_FEATURE_RO_INCOMPAT] |=
1482                                 EXT4_FEATURE_RO_COMPAT_GDT_CSUM;
1483                 fs->super->s_checksum_seed = 0;
1484                 ext2fs_clear_feature_csum_seed(fs->super);
1485         }
1486
1487         if (FEATURE_ON(E2P_FEATURE_RO_INCOMPAT,
1488                        EXT4_FEATURE_RO_COMPAT_GDT_CSUM)) {
1489                 if (mount_flags & EXT2_MF_MOUNTED) {
1490                         fputs(_("Cannot enable uninit_bg on a mounted "
1491                                 "filesystem!\n"), stderr);
1492                         return 1;
1493                 }
1494
1495                 /* Do not enable uninit_bg when metadata_csum enabled */
1496                 if (ext2fs_has_feature_metadata_csum(fs->super))
1497                         ext2fs_clear_feature_gdt_csum(fs->super);
1498                 else
1499                         enable_uninit_bg(fs);
1500         }
1501
1502         if (FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
1503                         EXT4_FEATURE_RO_COMPAT_GDT_CSUM)) {
1504                 if (mount_flags & EXT2_MF_MOUNTED) {
1505                         fputs(_("Cannot disable uninit_bg on a mounted "
1506                                 "filesystem!\n"), stderr);
1507                         return 1;
1508                 }
1509
1510                 err = disable_uninit_bg(fs,
1511                                 EXT4_FEATURE_RO_COMPAT_GDT_CSUM);
1512                 if (err)
1513                         return 1;
1514         }
1515
1516         /*
1517          * We don't actually toggle 64bit; resize2fs does that.  But this
1518          * must come after the metadata_csum feature_on so that it won't
1519          * complain about the lack of 64bit.
1520          */
1521         if (FEATURE_ON(E2P_FEATURE_INCOMPAT,
1522                        EXT4_FEATURE_INCOMPAT_64BIT)) {
1523                 if (mount_flags & EXT2_MF_MOUNTED) {
1524                         fprintf(stderr, _("Cannot enable 64-bit mode "
1525                                           "while mounted!\n"));
1526                         return 1;
1527                 }
1528                 ext2fs_clear_feature_64bit(sb);
1529                 feature_64bit = 1;
1530         }
1531         if (FEATURE_OFF(E2P_FEATURE_INCOMPAT,
1532                         EXT4_FEATURE_INCOMPAT_64BIT)) {
1533                 if (mount_flags & EXT2_MF_MOUNTED) {
1534                         fprintf(stderr, _("Cannot disable 64-bit mode "
1535                                           "while mounted!\n"));
1536                         return 1;
1537                 }
1538                 ext2fs_set_feature_64bit(sb);
1539                 feature_64bit = -1;
1540         }
1541
1542         if (FEATURE_ON(E2P_FEATURE_RO_INCOMPAT,
1543                                 EXT4_FEATURE_RO_COMPAT_QUOTA)) {
1544                 /*
1545                  * Set the Q_flag here and handle the quota options in the code
1546                  * below.
1547                  */
1548                 if (!Q_flag) {
1549                         Q_flag = 1;
1550                         /* Enable usr/grp quota by default */
1551                         for (qtype = 0; qtype < MAXQUOTAS; qtype++) {
1552                                 if (qtype != PRJQUOTA)
1553                                         quota_enable[qtype] = QOPT_ENABLE;
1554                                 else
1555                                         quota_enable[qtype] = QOPT_DISABLE;
1556                         }
1557                 }
1558                 ext2fs_clear_feature_quota(sb);
1559         }
1560
1561         if (FEATURE_ON(E2P_FEATURE_RO_INCOMPAT,
1562                        EXT4_FEATURE_RO_COMPAT_PROJECT)) {
1563                 if (fs->super->s_inode_size == EXT2_GOOD_OLD_INODE_SIZE) {
1564                         fprintf(stderr, _("Cannot enable project feature; "
1565                                           "inode size too small.\n"));
1566                         return 1;
1567                 }
1568                 Q_flag = 1;
1569                 quota_enable[PRJQUOTA] = QOPT_ENABLE;
1570         }
1571
1572         if (FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
1573                         EXT4_FEATURE_RO_COMPAT_PROJECT)) {
1574                 Q_flag = 1;
1575                 quota_enable[PRJQUOTA] = QOPT_DISABLE;
1576         }
1577
1578         if (FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
1579                                 EXT4_FEATURE_RO_COMPAT_QUOTA)) {
1580                 /*
1581                  * Set the Q_flag here and handle the quota options in the code
1582                  * below.
1583                  */
1584                 if (Q_flag)
1585                         fputs(_("\nWarning: '^quota' option overrides '-Q'"
1586                                 "arguments.\n"), stderr);
1587                 Q_flag = 1;
1588                 /* Disable all quota by default */
1589                 for (qtype = 0; qtype < MAXQUOTAS; qtype++)
1590                         quota_enable[qtype] = QOPT_DISABLE;
1591         }
1592
1593         if (FEATURE_ON(E2P_FEATURE_INCOMPAT, EXT4_FEATURE_INCOMPAT_ENCRYPT)) {
1594                 fs->super->s_encrypt_algos[0] =
1595                         EXT4_ENCRYPTION_MODE_AES_256_XTS;
1596                 fs->super->s_encrypt_algos[1] =
1597                         EXT4_ENCRYPTION_MODE_AES_256_CTS;
1598         }
1599
1600         if (FEATURE_ON(E2P_FEATURE_INCOMPAT, EXT4_FEATURE_INCOMPAT_CASEFOLD)) {
1601                 if (mount_flags & EXT2_MF_MOUNTED) {
1602                         fputs(_("The casefold feature may only be enabled when "
1603                                 "the filesystem is unmounted.\n"), stderr);
1604                         return 1;
1605                 }
1606                 fs->super->s_encoding = EXT4_ENC_UTF8_12_1;
1607                 fs->super->s_encoding_flags = e2p_get_encoding_flags(EXT4_ENC_UTF8_12_1);
1608                 enabling_casefold = 1;
1609         }
1610
1611         if (FEATURE_OFF(E2P_FEATURE_INCOMPAT, EXT4_FEATURE_INCOMPAT_CASEFOLD)) {
1612                 if (mount_flags & EXT2_MF_MOUNTED) {
1613                         fputs(_("The casefold feature may only be disabled when "
1614                                 "the filesystem is unmounted.\n"), stderr);
1615                         return 1;
1616                 }
1617                 if (has_casefold_inode(fs)) {
1618                         fputs(_("The casefold feature can't be cleared when "
1619                                         "there are inodes with +F flag.\n"), stderr);
1620                         return 1;
1621                 }
1622                 fs->super->s_encoding = 0;
1623                 fs->super->s_encoding_flags = 0;
1624                 enabling_casefold = 0;
1625         }
1626
1627         if (FEATURE_ON(E2P_FEATURE_INCOMPAT,
1628                 EXT4_FEATURE_INCOMPAT_CSUM_SEED)) {
1629                 if (!ext2fs_has_feature_metadata_csum(sb)) {
1630                         fputs(_("Setting feature 'metadata_csum_seed' "
1631                                 "is only supported\non filesystems with "
1632                                 "the metadata_csum feature enabled.\n"),
1633                                 stderr);
1634                         return 1;
1635                 }
1636                 try_confirm_csum_seed_support();
1637                 fs->super->s_checksum_seed = fs->csum_seed;
1638         }
1639
1640         if (FEATURE_OFF(E2P_FEATURE_INCOMPAT,
1641                 EXT4_FEATURE_INCOMPAT_CSUM_SEED)) {
1642                 __le32 uuid_seed;
1643
1644                 uuid_seed = ext2fs_crc32c_le(~0, fs->super->s_uuid,
1645                                         sizeof(fs->super->s_uuid));
1646                 if (fs->super->s_checksum_seed != uuid_seed) {
1647                         if (mount_flags & (EXT2_MF_BUSY|EXT2_MF_MOUNTED)) {
1648                                 fputs(_("UUID has changed since enabling "
1649                 "metadata_csum.  Filesystem must be unmounted "
1650                 "\nto safely rewrite all metadata to match the new UUID.\n"),
1651                                       stderr);
1652                                 return 1;
1653                         }
1654                         if (check_fsck_needed(fs, _("Recalculating checksums "
1655                                                     "could take some time.")))
1656                                 return 1;
1657                         rewrite_checksums = REWRITE_ALL;
1658                 }
1659         }
1660
1661         if (sb->s_rev_level == EXT2_GOOD_OLD_REV &&
1662             (sb->s_feature_compat || sb->s_feature_ro_compat ||
1663              sb->s_feature_incompat))
1664                 ext2fs_update_dynamic_rev(fs);
1665
1666         if (FEATURE_CHANGED(E2P_FEATURE_RO_INCOMPAT,
1667                             EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER) ||
1668             FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
1669                         EXT4_FEATURE_RO_COMPAT_HUGE_FILE) ||
1670             FEATURE_CHANGED(E2P_FEATURE_INCOMPAT,
1671                             EXT2_FEATURE_INCOMPAT_FILETYPE) ||
1672             FEATURE_CHANGED(E2P_FEATURE_COMPAT,
1673                             EXT2_FEATURE_COMPAT_RESIZE_INODE) ||
1674             FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
1675                         EXT2_FEATURE_RO_COMPAT_LARGE_FILE))
1676                 request_fsck_afterwards(fs);
1677
1678         if ((old_features[E2P_FEATURE_COMPAT] != sb->s_feature_compat) ||
1679             (old_features[E2P_FEATURE_INCOMPAT] != sb->s_feature_incompat) ||
1680             (old_features[E2P_FEATURE_RO_INCOMPAT] != sb->s_feature_ro_compat))
1681                 ext2fs_mark_super_dirty(fs);
1682
1683         return 0;
1684 }
1685
1686 /*
1687  * Add a journal to the filesystem.
1688  */
1689 static int add_journal(ext2_filsys fs)
1690 {
1691         struct ext2fs_journal_params    jparams;
1692         errcode_t       retval;
1693         ext2_filsys     jfs;
1694         io_manager      io_ptr;
1695
1696         if (ext2fs_has_feature_journal(fs->super)) {
1697                 fputs(_("The filesystem already has a journal.\n"), stderr);
1698                 goto err;
1699         }
1700         if (journal_device) {
1701                 if (!check_plausibility(journal_device, CHECK_BLOCK_DEV,
1702                                         NULL))
1703                         proceed_question(-1);
1704                 check_mount(journal_device, 0, _("journal"));
1705 #ifdef CONFIG_TESTIO_DEBUG
1706                 if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_BLOCK")) {
1707                         io_ptr = test_io_manager;
1708                         test_io_backing_manager = unix_io_manager;
1709                 } else
1710 #endif
1711                         io_ptr = unix_io_manager;
1712                 retval = ext2fs_open(journal_device, EXT2_FLAG_RW|
1713                                      EXT2_FLAG_JOURNAL_DEV_OK, 0,
1714                                      fs->blocksize, io_ptr, &jfs);
1715                 if (retval) {
1716                         com_err(program_name, retval,
1717                                 _("\n\twhile trying to open journal on %s\n"),
1718                                 journal_device);
1719                         goto err;
1720                 }
1721                 printf(_("Creating journal on device %s: "),
1722                        journal_device);
1723                 fflush(stdout);
1724
1725                 retval = ext2fs_add_journal_device(fs, jfs);
1726                 ext2fs_close_free(&jfs);
1727                 if (retval) {
1728                         com_err(program_name, retval,
1729                                 _("while adding filesystem to journal on %s"),
1730                                 journal_device);
1731                         goto err;
1732                 }
1733                 fputs(_("done\n"), stdout);
1734         } else if (journal_size) {
1735                 fputs(_("Creating journal inode: "), stdout);
1736                 fflush(stdout);
1737                 figure_journal_size(&jparams, journal_size, journal_fc_size, fs);
1738
1739                 if (journal_location_string)
1740                         journal_location =
1741                                 parse_num_blocks2(journal_location_string,
1742                                                   fs->super->s_log_block_size);
1743                 retval = ext2fs_add_journal_inode3(fs, &jparams,
1744                                                    journal_location,
1745                                                    journal_flags);
1746                 if (retval) {
1747                         fprintf(stderr, "\n");
1748                         com_err(program_name, retval, "%s",
1749                                 _("\n\twhile trying to create journal file"));
1750                         return retval;
1751                 }
1752                 fs->super->s_overhead_clusters += EXT2FS_NUM_B2C(fs,
1753                         jparams.num_journal_blocks + jparams.num_fc_blocks);
1754                 ext2fs_mark_super_dirty(fs);
1755                 fputs(_("done\n"), stdout);
1756
1757                 /*
1758                  * If the filesystem wasn't mounted, we need to force
1759                  * the block group descriptors out.
1760                  */
1761                 if ((mount_flags & EXT2_MF_MOUNTED) == 0)
1762                         fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
1763         }
1764         print_check_message(fs->super->s_max_mnt_count,
1765                             fs->super->s_checkinterval);
1766         return 0;
1767
1768 err:
1769         free(journal_device);
1770         return 1;
1771 }
1772
1773 static int handle_quota_options(ext2_filsys fs)
1774 {
1775         errcode_t retval;
1776         quota_ctx_t qctx;
1777         ext2_ino_t qf_ino;
1778         enum quota_type qtype;
1779         unsigned int qtype_bits = 0;
1780         int need_dirty = 0;
1781
1782         for (qtype = 0 ; qtype < MAXQUOTAS; qtype++)
1783                 if (quota_enable[qtype] != 0)
1784                         break;
1785         if (qtype == MAXQUOTAS)
1786                 /* Nothing to do. */
1787                 return 0;
1788
1789         if (quota_enable[PRJQUOTA] == QOPT_ENABLE &&
1790             fs->super->s_inode_size == EXT2_GOOD_OLD_INODE_SIZE) {
1791                 fprintf(stderr, _("Cannot enable project quota; "
1792                                   "inode size too small.\n"));
1793                 return 1;
1794         }
1795
1796         for (qtype = 0; qtype < MAXQUOTAS; qtype++) {
1797                 if (quota_enable[qtype] == QOPT_ENABLE)
1798                         qtype_bits |= 1 << qtype;
1799         }
1800
1801         retval = quota_init_context(&qctx, fs, qtype_bits);
1802         if (retval) {
1803                 com_err(program_name, retval,
1804                         _("while initializing quota context in support library"));
1805                 return 1;
1806         }
1807
1808         if (qtype_bits)
1809                 quota_compute_usage(qctx);
1810
1811         for (qtype = 0 ; qtype < MAXQUOTAS; qtype++) {
1812                 if (quota_enable[qtype] == QOPT_ENABLE &&
1813                     *quota_sb_inump(fs->super, qtype) == 0) {
1814                         if ((qf_ino = quota_file_exists(fs, qtype)) > 0) {
1815                                 retval = quota_read_all_dquots(qctx, qf_ino,
1816                                                                qtype,
1817                                                                QREAD_LIMITS);
1818                                 if (retval) {
1819                                         com_err(program_name, retval,
1820                                                 _("while updating quota limits (%d)"),
1821                                                 qtype);
1822                                 quota_errout:
1823                                         quota_release_context(&qctx);
1824                                         return 1;
1825                                 }
1826                         }
1827                         retval = quota_write_inode(qctx, 1 << qtype);
1828                         if (retval) {
1829                                 com_err(program_name, retval,
1830                                         _("while writing quota file (%d)"),
1831                                         qtype);
1832                                 goto quota_errout;
1833                         }
1834                         /* Enable Quota feature if one of quota enabled */
1835                         if (!ext2fs_has_feature_quota(fs->super)) {
1836                                 ext2fs_set_feature_quota(fs->super);
1837                                 need_dirty = 1;
1838                         }
1839                         if (qtype == PRJQUOTA &&
1840                             !ext2fs_has_feature_project(fs->super)) {
1841                                 ext2fs_set_feature_project(fs->super);
1842                                 need_dirty = 1;
1843                         }
1844                 } else if (quota_enable[qtype] == QOPT_DISABLE) {
1845                         retval = quota_remove_inode(fs, qtype);
1846                         if (retval) {
1847                                 com_err(program_name, retval,
1848                                         _("while removing quota file (%d)"),
1849                                         qtype);
1850                                 goto quota_errout;
1851                         }
1852                         if (qtype == PRJQUOTA) {
1853                                 ext2fs_clear_feature_project(fs->super);
1854                                 need_dirty = 1;
1855                         }
1856                 }
1857         }
1858
1859         quota_release_context(&qctx);
1860         /* Clear Quota feature if all quota types disabled. */
1861         if (!qtype_bits) {
1862                 for (qtype = 0 ; qtype < MAXQUOTAS; qtype++)
1863                         if (*quota_sb_inump(fs->super, qtype))
1864                                 break;
1865                 if (qtype == MAXQUOTAS) {
1866                         ext2fs_clear_feature_quota(fs->super);
1867                         need_dirty = 1;
1868                 }
1869
1870         }
1871         if (need_dirty)
1872                 ext2fs_mark_super_dirty(fs);
1873         return 0;
1874 }
1875
1876 static int option_handle_function(char *token)
1877 {
1878         if (strncmp(token, "usr", 3) == 0) {
1879                 quota_enable[USRQUOTA] = QOPT_ENABLE;
1880         } else if (strncmp(token, "^usr", 4) == 0) {
1881                 quota_enable[USRQUOTA] = QOPT_DISABLE;
1882         } else if (strncmp(token, "grp", 3) == 0) {
1883                 quota_enable[GRPQUOTA] = QOPT_ENABLE;
1884         } else if (strncmp(token, "^grp", 4) == 0) {
1885                 quota_enable[GRPQUOTA] = QOPT_DISABLE;
1886         } else if (strncmp(token, "prj", 3) == 0) {
1887                 quota_enable[PRJQUOTA] = QOPT_ENABLE;
1888         } else if (strncmp(token, "^prj", 4) == 0) {
1889                 quota_enable[PRJQUOTA] = QOPT_DISABLE;
1890         } else {
1891                 fputs(_("\nBad quota options specified.\n\n"
1892                         "Following valid quota options are available "
1893                         "(pass by separating with comma):\n"
1894                         "\t[^]usr[quota]\n"
1895                         "\t[^]grp[quota]\n"
1896                         "\t[^]prj[quota]\n"
1897                         "\n\n"), stderr);
1898                 return 1;
1899         }
1900         return 0;
1901 }
1902
1903 static void parse_e2label_options(int argc, char ** argv)
1904 {
1905         if ((argc < 2) || (argc > 3)) {
1906                 fputs(_("Usage: e2label device [newlabel]\n"), stderr);
1907                 exit(1);
1908         }
1909         io_options = strchr(argv[1], '?');
1910         if (io_options)
1911                 *io_options++ = 0;
1912         device_name = get_devname(NULL, argv[1], NULL);
1913         if (!device_name) {
1914                 com_err("e2label", 0, _("Unable to resolve '%s'"),
1915                         argv[1]);
1916                 exit(1);
1917         }
1918         open_flag = EXT2_FLAG_JOURNAL_DEV_OK | EXT2_FLAG_SUPER_ONLY;
1919         if (argc == 3) {
1920                 open_flag |= EXT2_FLAG_RW;
1921                 L_flag = 1;
1922                 new_label = argv[2];
1923         } else
1924                 print_label++;
1925 }
1926
1927 static time_t parse_time(char *str)
1928 {
1929         struct  tm      ts;
1930
1931         if (strcmp(str, "now") == 0) {
1932                 return (time(0));
1933         }
1934         memset(&ts, 0, sizeof(ts));
1935 #ifdef HAVE_STRPTIME
1936         strptime(str, "%Y%m%d%H%M%S", &ts);
1937 #else
1938         sscanf(str, "%4d%2d%2d%2d%2d%2d", &ts.tm_year, &ts.tm_mon,
1939                &ts.tm_mday, &ts.tm_hour, &ts.tm_min, &ts.tm_sec);
1940         ts.tm_year -= 1900;
1941         ts.tm_mon -= 1;
1942         if (ts.tm_year < 0 || ts.tm_mon < 0 || ts.tm_mon > 11 ||
1943             ts.tm_mday < 0 || ts.tm_mday > 31 || ts.tm_hour > 23 ||
1944             ts.tm_min > 59 || ts.tm_sec > 61)
1945                 ts.tm_mday = 0;
1946 #endif
1947         if (ts.tm_mday == 0) {
1948                 com_err(program_name, 0,
1949                         _("Couldn't parse date/time specifier: %s"),
1950                         str);
1951                 usage();
1952         }
1953         ts.tm_isdst = -1;
1954         return (mktime(&ts));
1955 }
1956
1957 static void parse_tune2fs_options(int argc, char **argv)
1958 {
1959         int c;
1960         char *tmp;
1961         struct group *gr;
1962         struct passwd *pw;
1963         int ret;
1964         char optstring[100] = "c:e:fg:i:jlm:o:r:s:u:C:E:I:J:L:M:O:T:U:z:Q:";
1965
1966         open_flag = 0;
1967         printf("tune2fs %s (%s)\n", E2FSPROGS_VERSION, E2FSPROGS_DATE);
1968         while ((c = getopt(argc, argv, optstring)) != EOF)
1969                 switch (c) {
1970                 case 'c':
1971                         open_flag = EXT2_FLAG_RW;
1972                         c_flag = 1;
1973                         if (strcmp(optarg, "random") == 0) {
1974                                 max_mount_count = 65536;
1975                                 break;
1976                         }
1977                         max_mount_count = strtol(optarg, &tmp, 0);
1978                         if (*tmp || max_mount_count > 16000 ||
1979                             max_mount_count < -16000) {
1980                                 com_err(program_name, 0,
1981                                         _("bad mounts count - %s"),
1982                                         optarg);
1983                                 usage();
1984                         }
1985                         if (max_mount_count == 0)
1986                                 max_mount_count = -1;
1987                         break;
1988                 case 'C':
1989                         mount_count = strtoul(optarg, &tmp, 0);
1990                         if (*tmp || mount_count > 16000) {
1991                                 com_err(program_name, 0,
1992                                         _("bad mounts count - %s"),
1993                                         optarg);
1994                                 usage();
1995                         }
1996                         C_flag = 1;
1997                         open_flag = EXT2_FLAG_RW;
1998                         break;
1999                 case 'e':
2000                         if (strcmp(optarg, "continue") == 0)
2001                                 errors = EXT2_ERRORS_CONTINUE;
2002                         else if (strcmp(optarg, "remount-ro") == 0)
2003                                 errors = EXT2_ERRORS_RO;
2004                         else if (strcmp(optarg, "panic") == 0)
2005                                 errors = EXT2_ERRORS_PANIC;
2006                         else {
2007                                 com_err(program_name, 0,
2008                                         _("bad error behavior - %s"),
2009                                         optarg);
2010                                 usage();
2011                         }
2012                         e_flag = 1;
2013                         open_flag = EXT2_FLAG_RW;
2014                         break;
2015                 case 'E':
2016                         extended_cmd = optarg;
2017                         open_flag |= EXT2_FLAG_RW;
2018                         break;
2019                 case 'f': /* Force */
2020                         f_flag++;
2021                         break;
2022                 case 'g':
2023                         resgid = strtoul(optarg, &tmp, 0);
2024                         if (*tmp) {
2025                                 gr = getgrnam(optarg);
2026                                 if (gr == NULL)
2027                                         tmp = optarg;
2028                                 else {
2029                                         resgid = gr->gr_gid;
2030                                         *tmp = 0;
2031                                 }
2032                         }
2033                         if (*tmp) {
2034                                 com_err(program_name, 0,
2035                                         _("bad gid/group name - %s"),
2036                                         optarg);
2037                                 usage();
2038                         }
2039                         g_flag = 1;
2040                         open_flag = EXT2_FLAG_RW;
2041                         break;
2042                 case 'i':
2043                         interval = strtoul(optarg, &tmp, 0);
2044                         switch (*tmp) {
2045                         case 's':
2046                                 tmp++;
2047                                 break;
2048                         case '\0':
2049                         case 'd':
2050                         case 'D': /* days */
2051                                 interval *= 86400;
2052                                 if (*tmp != '\0')
2053                                         tmp++;
2054                                 break;
2055                         case 'm':
2056                         case 'M': /* months! */
2057                                 interval *= 86400 * 30;
2058                                 tmp++;
2059                                 break;
2060                         case 'w':
2061                         case 'W': /* weeks */
2062                                 interval *= 86400 * 7;
2063                                 tmp++;
2064                                 break;
2065                         }
2066                         if (*tmp) {
2067                                 com_err(program_name, 0,
2068                                         _("bad interval - %s"), optarg);
2069                                 usage();
2070                         }
2071                         i_flag = 1;
2072                         open_flag = EXT2_FLAG_RW;
2073                         break;
2074                 case 'j':
2075                         if (!journal_size)
2076                                 journal_size = -1;
2077                         open_flag = EXT2_FLAG_RW;
2078                         break;
2079                 case 'J':
2080                         parse_journal_opts(optarg);
2081                         open_flag = EXT2_FLAG_RW;
2082                         break;
2083                 case 'l':
2084                         l_flag = 1;
2085                         break;
2086                 case 'L':
2087                         new_label = optarg;
2088                         L_flag = 1;
2089                         open_flag |= EXT2_FLAG_RW |
2090                                 EXT2_FLAG_JOURNAL_DEV_OK;
2091                         break;
2092                 case 'm':
2093                         reserved_ratio = strtod(optarg, &tmp);
2094                         if (*tmp || reserved_ratio > 50 ||
2095                             reserved_ratio < 0) {
2096                                 com_err(program_name, 0,
2097                                         _("bad reserved block ratio - %s"),
2098                                         optarg);
2099                                 usage();
2100                         }
2101                         m_flag = 1;
2102                         open_flag = EXT2_FLAG_RW;
2103                         break;
2104                 case 'M':
2105                         new_last_mounted = optarg;
2106                         M_flag = 1;
2107                         open_flag = EXT2_FLAG_RW;
2108                         break;
2109                 case 'o':
2110                         if (mntopts_cmd) {
2111                                 com_err(program_name, 0, "%s",
2112                                         _("-o may only be specified once"));
2113                                 usage();
2114                         }
2115                         mntopts_cmd = optarg;
2116                         open_flag = EXT2_FLAG_RW;
2117                         break;
2118                 case 'O':
2119                         if (features_cmd) {
2120                                 com_err(program_name, 0, "%s",
2121                                         _("-O may only be specified once"));
2122                                 usage();
2123                         }
2124                         features_cmd = optarg;
2125                         open_flag = EXT2_FLAG_RW;
2126                         break;
2127                 case 'Q':
2128                         Q_flag = 1;
2129                         ret = parse_quota_opts(optarg, option_handle_function);
2130                         if (ret)
2131                                 exit(1);
2132                         open_flag = EXT2_FLAG_RW;
2133                         break;
2134                 case 'r':
2135                         reserved_blocks = strtoul(optarg, &tmp, 0);
2136                         if (*tmp) {
2137                                 com_err(program_name, 0,
2138                                         _("bad reserved blocks count - %s"),
2139                                         optarg);
2140                                 usage();
2141                         }
2142                         r_flag = 1;
2143                         open_flag = EXT2_FLAG_RW;
2144                         break;
2145                 case 's': /* Deprecated */
2146                         s_flag = atoi(optarg);
2147                         open_flag = EXT2_FLAG_RW;
2148                         break;
2149                 case 'T':
2150                         T_flag = 1;
2151                         last_check_time = parse_time(optarg);
2152                         open_flag = EXT2_FLAG_RW;
2153                         break;
2154                 case 'u':
2155                                 resuid = strtoul(optarg, &tmp, 0);
2156                                 if (*tmp) {
2157                                         pw = getpwnam(optarg);
2158                                         if (pw == NULL)
2159                                                 tmp = optarg;
2160                                         else {
2161                                                 resuid = pw->pw_uid;
2162                                                 *tmp = 0;
2163                                         }
2164                                 }
2165                                 if (*tmp) {
2166                                         com_err(program_name, 0,
2167                                                 _("bad uid/user name - %s"),
2168                                                 optarg);
2169                                         usage();
2170                                 }
2171                                 u_flag = 1;
2172                                 open_flag = EXT2_FLAG_RW;
2173                                 break;
2174                 case 'U':
2175                         requested_uuid = optarg;
2176                         U_flag = 1;
2177                         open_flag = EXT2_FLAG_RW |
2178                                 EXT2_FLAG_JOURNAL_DEV_OK;
2179                         break;
2180                 case 'I':
2181                         new_inode_size = strtoul(optarg, &tmp, 0);
2182                         if (*tmp) {
2183                                 com_err(program_name, 0,
2184                                         _("bad inode size - %s"),
2185                                         optarg);
2186                                 usage();
2187                         }
2188                         if (!((new_inode_size &
2189                                (new_inode_size - 1)) == 0)) {
2190                                 com_err(program_name, 0,
2191                                         _("Inode size must be a "
2192                                           "power of two- %s"),
2193                                         optarg);
2194                                 usage();
2195                         }
2196                         open_flag = EXT2_FLAG_RW;
2197                         I_flag = 1;
2198                         break;
2199                 case 'z':
2200                         undo_file = optarg;
2201                         break;
2202                 default:
2203                         usage();
2204                 }
2205         if (optind < argc - 1 || optind == argc)
2206                 usage();
2207         if (!open_flag && !l_flag)
2208                 usage();
2209         io_options = strchr(argv[optind], '?');
2210         if (io_options)
2211                 *io_options++ = 0;
2212         device_name = get_devname(NULL, argv[optind], NULL);
2213         if (!device_name) {
2214                 com_err(program_name, 0, _("Unable to resolve '%s'"),
2215                         argv[optind]);
2216                 exit(1);
2217         }
2218 }
2219
2220 #ifdef CONFIG_BUILD_FINDFS
2221 void do_findfs(int argc, char **argv)
2222 {
2223         char    *dev;
2224
2225         if ((argc != 2) ||
2226             (strncmp(argv[1], "LABEL=", 6) && strncmp(argv[1], "UUID=", 5))) {
2227                 fprintf(stderr, "Usage: findfs LABEL=<label>|UUID=<uuid>\n");
2228                 exit(2);
2229         }
2230         dev = blkid_get_devname(NULL, argv[1], NULL);
2231         if (!dev) {
2232                 com_err("findfs", 0, _("Unable to resolve '%s'"),
2233                         argv[1]);
2234                 exit(1);
2235         }
2236         puts(dev);
2237         exit(0);
2238 }
2239 #endif
2240
2241 static int parse_extended_opts(ext2_filsys fs, const char *opts)
2242 {
2243         struct ext2_super_block *sb = fs->super;
2244         char    *buf, *token, *next, *p, *arg;
2245         int     len, hash_alg;
2246         int     r_usage = 0;
2247         int encoding = 0;
2248         char    *encoding_flags = NULL;
2249
2250         len = strlen(opts);
2251         buf = malloc(len+1);
2252         if (!buf) {
2253                 fprintf(stderr, "%s",
2254                         _("Couldn't allocate memory to parse options!\n"));
2255                 return 1;
2256         }
2257         strcpy(buf, opts);
2258         for (token = buf; token && *token; token = next) {
2259                 p = strchr(token, ',');
2260                 next = 0;
2261                 if (p) {
2262                         *p = 0;
2263                         next = p+1;
2264                 }
2265                 arg = strchr(token, '=');
2266                 if (arg) {
2267                         *arg = 0;
2268                         arg++;
2269                 }
2270                 if (strcmp(token, "clear-mmp") == 0 ||
2271                     strcmp(token, "clear_mmp") == 0) {
2272                         clear_mmp = 1;
2273                 } else if (strcmp(token, "mmp_update_interval") == 0) {
2274                         unsigned long intv;
2275                         if (!arg) {
2276                                 r_usage++;
2277                                 continue;
2278                         }
2279                         intv = strtoul(arg, &p, 0);
2280                         if (*p) {
2281                                 fprintf(stderr,
2282                                         _("Invalid mmp_update_interval: %s\n"),
2283                                         arg);
2284                                 r_usage++;
2285                                 continue;
2286                         }
2287                         if (intv == 0) {
2288                                 intv = EXT4_MMP_UPDATE_INTERVAL;
2289                         } else if (intv > EXT4_MMP_MAX_UPDATE_INTERVAL) {
2290                                 fprintf(stderr,
2291                                         _("mmp_update_interval too big: %lu\n"),
2292                                         intv);
2293                                 r_usage++;
2294                                 continue;
2295                         }
2296                         printf(P_("Setting multiple mount protection update "
2297                                   "interval to %lu second\n",
2298                                   "Setting multiple mount protection update "
2299                                   "interval to %lu seconds\n", intv),
2300                                intv);
2301                         sb->s_mmp_update_interval = intv;
2302                         ext2fs_mark_super_dirty(fs);
2303                 } else if (!strcmp(token, "force_fsck")) {
2304                         sb->s_state |= EXT2_ERROR_FS;
2305                         printf(_("Setting filesystem error flag to force fsck.\n"));
2306                         ext2fs_mark_super_dirty(fs);
2307                 } else if (!strcmp(token, "test_fs")) {
2308                         sb->s_flags |= EXT2_FLAGS_TEST_FILESYS;
2309                         printf("Setting test filesystem flag\n");
2310                         ext2fs_mark_super_dirty(fs);
2311                 } else if (!strcmp(token, "^test_fs")) {
2312                         sb->s_flags &= ~EXT2_FLAGS_TEST_FILESYS;
2313                         printf("Clearing test filesystem flag\n");
2314                         ext2fs_mark_super_dirty(fs);
2315                 } else if (strcmp(token, "stride") == 0) {
2316                         if (!arg) {
2317                                 r_usage++;
2318                                 continue;
2319                         }
2320                         stride = strtoul(arg, &p, 0);
2321                         if (*p) {
2322                                 fprintf(stderr,
2323                                         _("Invalid RAID stride: %s\n"),
2324                                         arg);
2325                                 r_usage++;
2326                                 continue;
2327                         }
2328                         stride_set = 1;
2329                 } else if (strcmp(token, "stripe-width") == 0 ||
2330                            strcmp(token, "stripe_width") == 0) {
2331                         if (!arg) {
2332                                 r_usage++;
2333                                 continue;
2334                         }
2335                         stripe_width = strtoul(arg, &p, 0);
2336                         if (*p) {
2337                                 fprintf(stderr,
2338                                         _("Invalid RAID stripe-width: %s\n"),
2339                                         arg);
2340                                 r_usage++;
2341                                 continue;
2342                         }
2343                         stripe_width_set = 1;
2344                 } else if (strcmp(token, "hash_alg") == 0 ||
2345                            strcmp(token, "hash-alg") == 0) {
2346                         if (!arg) {
2347                                 r_usage++;
2348                                 continue;
2349                         }
2350                         hash_alg = e2p_string2hash(arg);
2351                         if (hash_alg < 0) {
2352                                 fprintf(stderr,
2353                                         _("Invalid hash algorithm: %s\n"),
2354                                         arg);
2355                                 r_usage++;
2356                                 continue;
2357                         }
2358                         sb->s_def_hash_version = hash_alg;
2359                         printf(_("Setting default hash algorithm "
2360                                  "to %s (%d)\n"),
2361                                arg, hash_alg);
2362                         ext2fs_mark_super_dirty(fs);
2363                 } else if (!strcmp(token, "mount_opts")) {
2364                         if (!arg) {
2365                                 r_usage++;
2366                                 continue;
2367                         }
2368                         if (strlen(arg) >= sizeof(fs->super->s_mount_opts)) {
2369                                 fprintf(stderr,
2370                                         "Extended mount options too long\n");
2371                                 continue;
2372                         }
2373                         ext_mount_opts = strdup(arg);
2374                 } else if (!strcmp(token, "encoding")) {
2375                         if (!arg) {
2376                                 r_usage++;
2377                                 continue;
2378                         }
2379                         if (mount_flags & EXT2_MF_MOUNTED) {
2380                                 fputs(_("The casefold feature may only be enabled when "
2381                                         "the filesystem is unmounted.\n"), stderr);
2382                                 r_usage++;
2383                                 continue;
2384                         }
2385                         if (ext2fs_has_feature_casefold(sb) && !enabling_casefold) {
2386                                 fprintf(stderr, _("Cannot alter existing encoding\n"));
2387                                 r_usage++;
2388                                 continue;
2389                         }
2390                         encoding = e2p_str2encoding(arg);
2391                         if (encoding < 0) {
2392                                 fprintf(stderr, _("Invalid encoding: %s\n"), arg);
2393                                 r_usage++;
2394                                 continue;
2395                         }
2396                         enabling_casefold = 1;
2397                         sb->s_encoding = encoding;
2398                         printf(_("Setting encoding to '%s'\n"), arg);
2399                         sb->s_encoding_flags =
2400                                 e2p_get_encoding_flags(sb->s_encoding);
2401                 } else if (!strcmp(token, "encoding_flags")) {
2402                         if (!arg) {
2403                                 r_usage++;
2404                                 continue;
2405                         }
2406                         encoding_flags = arg;
2407                 } else if (!strcmp(token, "orphan_file_size")) {
2408                         if (!arg) {
2409                                 r_usage++;
2410                                 continue;
2411                         }
2412                         orphan_file_blocks = parse_num_blocks2(arg,
2413                                                  fs->super->s_log_block_size);
2414
2415                         if (orphan_file_blocks < 1) {
2416                                 fprintf(stderr,
2417                                         _("Invalid size of orphan file %s\n"),
2418                                         arg);
2419                                 r_usage++;
2420                                 continue;
2421                         }
2422                 } else
2423                         r_usage++;
2424         }
2425
2426         if (encoding > 0 && !r_usage) {
2427                 sb->s_encoding_flags =
2428                         e2p_get_encoding_flags(sb->s_encoding);
2429
2430                 if (encoding_flags &&
2431                     e2p_str2encoding_flags(sb->s_encoding, encoding_flags,
2432                                            &sb->s_encoding_flags)) {
2433                         fprintf(stderr, _("error: Invalid encoding flag: %s\n"),
2434                                         encoding_flags);
2435                         r_usage++;
2436                 } else if (encoding_flags)
2437                         printf(_("Setting encoding_flags to '%s'\n"),
2438                                  encoding_flags);
2439                 ext2fs_set_feature_casefold(sb);
2440                 ext2fs_mark_super_dirty(fs);
2441         } else if (encoding_flags && !r_usage) {
2442                 fprintf(stderr, _("error: An encoding must be explicitly "
2443                                   "specified when passing encoding-flags\n"));
2444                 r_usage++;
2445         }
2446         if (r_usage) {
2447                 fprintf(stderr, "%s", _("\nBad options specified.\n\n"
2448                         "Extended options are separated by commas, "
2449                         "and may take an argument which\n"
2450                         "\tis set off by an equals ('=') sign.\n\n"
2451                         "Valid extended options are:\n"
2452                         "\tclear_mmp\n"
2453                         "\thash_alg=<hash algorithm>\n"
2454                         "\tmount_opts=<extended default mount options>\n"
2455                         "\tmmp_update_interval=<mmp update interval in seconds>\n"
2456                         "\tstride=<RAID per-disk chunk size in blocks>\n"
2457                         "\tstripe_width=<RAID stride*data disks in blocks>\n"
2458                         "\tforce_fsck\n"
2459                         "\ttest_fs\n"
2460                         "\t^test_fs\n"
2461                         "\tencoding=<encoding>\n"
2462                         "\tencoding_flags=<flags>\n"));
2463                 free(buf);
2464                 return 1;
2465         }
2466         free(buf);
2467
2468         return 0;
2469 }
2470
2471 /*
2472  * Fill in the block bitmap bmap with the information regarding the
2473  * blocks to be moved
2474  */
2475 static int get_move_bitmaps(ext2_filsys fs, int new_ino_blks_per_grp,
2476                             ext2fs_block_bitmap bmap)
2477 {
2478         dgrp_t i;
2479         int retval;
2480         ext2_badblocks_list bb_list = 0;
2481         blk64_t j, needed_blocks = 0;
2482         blk64_t start_blk, end_blk;
2483
2484         retval = ext2fs_read_bb_inode(fs, &bb_list);
2485         if (retval)
2486                 return retval;
2487
2488         for (i = 0; i < fs->group_desc_count; i++) {
2489                 start_blk = ext2fs_inode_table_loc(fs, i) +
2490                                         fs->inode_blocks_per_group;
2491
2492                 end_blk = ext2fs_inode_table_loc(fs, i) +
2493                                         new_ino_blks_per_grp;
2494
2495                 for (j = start_blk; j < end_blk; j++) {
2496                         if (ext2fs_test_block_bitmap2(fs->block_map, j)) {
2497                                 /*
2498                                  * IF the block is a bad block we fail
2499                                  */
2500                                 if (ext2fs_badblocks_list_test(bb_list, j)) {
2501                                         ext2fs_badblocks_list_free(bb_list);
2502                                         return ENOSPC;
2503                                 }
2504
2505                                 ext2fs_mark_block_bitmap2(bmap, j);
2506                         } else {
2507                                 /*
2508                                  * We are going to use this block for
2509                                  * inode table. So mark them used.
2510                                  */
2511                                 ext2fs_mark_block_bitmap2(fs->block_map, j);
2512                         }
2513                 }
2514                 needed_blocks += end_blk - start_blk;
2515         }
2516
2517         ext2fs_badblocks_list_free(bb_list);
2518         if (needed_blocks > ext2fs_free_blocks_count(fs->super))
2519                 return ENOSPC;
2520
2521         return 0;
2522 }
2523
2524 static int ext2fs_is_meta_block(ext2_filsys fs, blk64_t blk)
2525 {
2526         dgrp_t group;
2527         group = ext2fs_group_of_blk2(fs, blk);
2528         if (ext2fs_block_bitmap_loc(fs, group) == blk)
2529                 return 1;
2530         if (ext2fs_inode_bitmap_loc(fs, group) == blk)
2531                 return 1;
2532         return 0;
2533 }
2534
2535 static int ext2fs_is_block_in_group(ext2_filsys fs, dgrp_t group, blk64_t blk)
2536 {
2537         blk64_t start_blk, end_blk;
2538         start_blk = fs->super->s_first_data_block +
2539                         EXT2_GROUPS_TO_BLOCKS(fs->super, group);
2540         /*
2541          * We cannot get new block beyond end_blk for for the last block group
2542          * so we can check with EXT2_BLOCKS_PER_GROUP even for last block group
2543          */
2544         end_blk   = start_blk + EXT2_BLOCKS_PER_GROUP(fs->super);
2545         if (blk >= start_blk && blk <= end_blk)
2546                 return 1;
2547         return 0;
2548 }
2549
2550 static int move_block(ext2_filsys fs, ext2fs_block_bitmap bmap)
2551 {
2552
2553         char *buf;
2554         dgrp_t group = 0;
2555         errcode_t retval;
2556         int meta_data = 0;
2557         blk64_t blk, new_blk, goal;
2558         struct blk_move *bmv;
2559
2560         retval = ext2fs_get_mem(fs->blocksize, &buf);
2561         if (retval)
2562                 return retval;
2563
2564         for (new_blk = blk = fs->super->s_first_data_block;
2565              blk < ext2fs_blocks_count(fs->super); blk++) {
2566                 if (!ext2fs_test_block_bitmap2(bmap, blk))
2567                         continue;
2568
2569                 if (ext2fs_is_meta_block(fs, blk)) {
2570                         /*
2571                          * If the block is mapping a fs meta data block
2572                          * like group desc/block bitmap/inode bitmap. We
2573                          * should find a block in the same group and fix
2574                          * the respective fs metadata pointers. Otherwise
2575                          * fail
2576                          */
2577                         group = ext2fs_group_of_blk2(fs, blk);
2578                         goal = ext2fs_group_first_block2(fs, group);
2579                         meta_data = 1;
2580
2581                 } else {
2582                         goal = new_blk;
2583                 }
2584                 retval = ext2fs_new_block2(fs, goal, NULL, &new_blk);
2585                 if (retval)
2586                         goto err_out;
2587
2588                 /* new fs meta data block should be in the same group */
2589                 if (meta_data && !ext2fs_is_block_in_group(fs, group, new_blk)) {
2590                         retval = ENOSPC;
2591                         goto err_out;
2592                 }
2593
2594                 /* Mark this block as allocated */
2595                 ext2fs_mark_block_bitmap2(fs->block_map, new_blk);
2596
2597                 /* Add it to block move list */
2598                 retval = ext2fs_get_mem(sizeof(struct blk_move), &bmv);
2599                 if (retval)
2600                         goto err_out;
2601
2602                 bmv->old_loc = blk;
2603                 bmv->new_loc = new_blk;
2604
2605                 list_add(&(bmv->list), &blk_move_list);
2606
2607                 retval = io_channel_read_blk64(fs->io, blk, 1, buf);
2608                 if (retval)
2609                         goto err_out;
2610
2611                 retval = io_channel_write_blk64(fs->io, new_blk, 1, buf);
2612                 if (retval)
2613                         goto err_out;
2614         }
2615
2616 err_out:
2617         ext2fs_free_mem(&buf);
2618         return retval;
2619 }
2620
2621 static blk64_t translate_block(blk64_t blk)
2622 {
2623         struct list_head *entry;
2624         struct blk_move *bmv;
2625
2626         list_for_each(entry, &blk_move_list) {
2627                 bmv = list_entry(entry, struct blk_move, list);
2628                 if (bmv->old_loc == blk)
2629                         return bmv->new_loc;
2630         }
2631
2632         return 0;
2633 }
2634
2635 static int process_block(ext2_filsys fs EXT2FS_ATTR((unused)),
2636                          blk64_t *block_nr,
2637                          e2_blkcnt_t blockcnt EXT2FS_ATTR((unused)),
2638                          blk64_t ref_block EXT2FS_ATTR((unused)),
2639                          int ref_offset EXT2FS_ATTR((unused)),
2640                          void *priv_data)
2641 {
2642         int ret = 0;
2643         blk64_t new_blk;
2644         ext2fs_block_bitmap bmap = (ext2fs_block_bitmap) priv_data;
2645
2646         if (!ext2fs_test_block_bitmap2(bmap, *block_nr))
2647                 return 0;
2648         new_blk = translate_block(*block_nr);
2649         if (new_blk) {
2650                 *block_nr = new_blk;
2651                 /*
2652                  * This will force the ext2fs_write_inode in the iterator
2653                  */
2654                 ret |= BLOCK_CHANGED;
2655         }
2656
2657         return ret;
2658 }
2659
2660 static int inode_scan_and_fix(ext2_filsys fs, ext2fs_block_bitmap bmap)
2661 {
2662         errcode_t retval = 0;
2663         ext2_ino_t ino;
2664         blk64_t blk;
2665         char *block_buf = 0;
2666         struct ext2_inode inode;
2667         ext2_inode_scan scan = NULL;
2668
2669         retval = ext2fs_get_mem(fs->blocksize * 3, &block_buf);
2670         if (retval)
2671                 return retval;
2672
2673         retval = ext2fs_open_inode_scan(fs, 0, &scan);
2674         if (retval)
2675                 goto err_out;
2676
2677         while (1) {
2678                 retval = ext2fs_get_next_inode(scan, &ino, &inode);
2679                 if (retval)
2680                         goto err_out;
2681
2682                 if (!ino)
2683                         break;
2684
2685                 if (inode.i_links_count == 0)
2686                         continue; /* inode not in use */
2687
2688                 /* FIXME!!
2689                  * If we end up modifying the journal inode
2690                  * the sb->s_jnl_blocks will differ. But a
2691                  * subsequent e2fsck fixes that.
2692                  * Do we need to fix this ??
2693                  */
2694
2695                 if (ext2fs_file_acl_block(fs, &inode) &&
2696                     ext2fs_test_block_bitmap2(bmap,
2697                                         ext2fs_file_acl_block(fs, &inode))) {
2698                         blk = translate_block(ext2fs_file_acl_block(fs,
2699                                                                     &inode));
2700                         if (!blk)
2701                                 continue;
2702
2703                         ext2fs_file_acl_block_set(fs, &inode, blk);
2704
2705                         /*
2706                          * Write the inode to disk so that inode table
2707                          * resizing can work
2708                          */
2709                         retval = ext2fs_write_inode(fs, ino, &inode);
2710                         if (retval)
2711                                 goto err_out;
2712                 }
2713
2714                 if (!ext2fs_inode_has_valid_blocks2(fs, &inode))
2715                         continue;
2716
2717                 retval = ext2fs_block_iterate3(fs, ino, 0, block_buf,
2718                                                process_block, bmap);
2719                 if (retval)
2720                         goto err_out;
2721
2722         }
2723
2724 err_out:
2725         ext2fs_free_mem(&block_buf);
2726         ext2fs_close_inode_scan(scan);
2727
2728         return retval;
2729 }
2730
2731 /*
2732  * We need to scan for inode and block bitmaps that may need to be
2733  * moved.  This can take place if the filesystem was formatted for
2734  * RAID arrays using the mke2fs's extended option "stride".
2735  */
2736 static int group_desc_scan_and_fix(ext2_filsys fs, ext2fs_block_bitmap bmap)
2737 {
2738         dgrp_t i;
2739         blk64_t blk, new_blk;
2740
2741         for (i = 0; i < fs->group_desc_count; i++) {
2742                 blk = ext2fs_block_bitmap_loc(fs, i);
2743                 if (ext2fs_test_block_bitmap2(bmap, blk)) {
2744                         new_blk = translate_block(blk);
2745                         if (!new_blk)
2746                                 continue;
2747                         ext2fs_block_bitmap_loc_set(fs, i, new_blk);
2748                 }
2749
2750                 blk = ext2fs_inode_bitmap_loc(fs, i);
2751                 if (ext2fs_test_block_bitmap2(bmap, blk)) {
2752                         new_blk = translate_block(blk);
2753                         if (!new_blk)
2754                                 continue;
2755                         ext2fs_inode_bitmap_loc_set(fs, i, new_blk);
2756                 }
2757         }
2758         return 0;
2759 }
2760
2761 static int expand_inode_table(ext2_filsys fs, unsigned long new_ino_size)
2762 {
2763         dgrp_t i;
2764         blk64_t blk;
2765         errcode_t retval;
2766         int new_ino_blks_per_grp;
2767         unsigned int j;
2768         char *old_itable = NULL, *new_itable = NULL;
2769         char *tmp_old_itable = NULL, *tmp_new_itable = NULL;
2770         unsigned long old_ino_size;
2771         int old_itable_size, new_itable_size;
2772
2773         old_itable_size = fs->inode_blocks_per_group * fs->blocksize;
2774         old_ino_size = EXT2_INODE_SIZE(fs->super);
2775
2776         new_ino_blks_per_grp = ext2fs_div_ceil(
2777                                         EXT2_INODES_PER_GROUP(fs->super) *
2778                                         new_ino_size,
2779                                         fs->blocksize);
2780
2781         new_itable_size = new_ino_blks_per_grp * fs->blocksize;
2782
2783         retval = ext2fs_get_mem(old_itable_size, &old_itable);
2784         if (retval)
2785                 return retval;
2786
2787         retval = ext2fs_get_mem(new_itable_size, &new_itable);
2788         if (retval)
2789                 goto err_out;
2790
2791         tmp_old_itable = old_itable;
2792         tmp_new_itable = new_itable;
2793
2794         for (i = 0; i < fs->group_desc_count; i++) {
2795                 blk = ext2fs_inode_table_loc(fs, i);
2796                 retval = io_channel_read_blk64(fs->io, blk,
2797                                 fs->inode_blocks_per_group, old_itable);
2798                 if (retval)
2799                         goto err_out;
2800
2801                 for (j = 0; j < EXT2_INODES_PER_GROUP(fs->super); j++) {
2802                         memcpy(new_itable, old_itable, old_ino_size);
2803
2804                         memset(new_itable+old_ino_size, 0,
2805                                         new_ino_size - old_ino_size);
2806
2807                         new_itable += new_ino_size;
2808                         old_itable += old_ino_size;
2809                 }
2810
2811                 /* reset the pointer */
2812                 old_itable = tmp_old_itable;
2813                 new_itable = tmp_new_itable;
2814
2815                 retval = io_channel_write_blk64(fs->io, blk,
2816                                         new_ino_blks_per_grp, new_itable);
2817                 if (retval)
2818                         goto err_out;
2819         }
2820
2821         /* Update the meta data */
2822         fs->inode_blocks_per_group = new_ino_blks_per_grp;
2823         ext2fs_free_inode_cache(fs->icache);
2824         fs->icache = 0;
2825         fs->super->s_inode_size = new_ino_size;
2826
2827 err_out:
2828         if (old_itable)
2829                 ext2fs_free_mem(&old_itable);
2830
2831         if (new_itable)
2832                 ext2fs_free_mem(&new_itable);
2833
2834         return retval;
2835 }
2836
2837
2838 #define list_for_each_safe(pos, pnext, head) \
2839         for (pos = (head)->next, pnext = pos->next; pos != (head); \
2840              pos = pnext, pnext = pos->next)
2841
2842 static void free_blk_move_list(void)
2843 {
2844         struct list_head *entry, *tmp;
2845         struct blk_move *bmv;
2846
2847         list_for_each_safe(entry, tmp, &blk_move_list) {
2848                 bmv = list_entry(entry, struct blk_move, list);
2849                 list_del(entry);
2850                 ext2fs_free_mem(&bmv);
2851         }
2852         return;
2853 }
2854
2855 static int resize_inode(ext2_filsys fs, unsigned long new_size)
2856 {
2857         errcode_t retval;
2858         int new_ino_blks_per_grp;
2859         ext2fs_block_bitmap bmap;
2860
2861         retval = ext2fs_read_inode_bitmap(fs);
2862         if (retval) {
2863                 fputs(_("Failed to read inode bitmap\n"), stderr);
2864                 return retval;
2865         }
2866         retval = ext2fs_read_block_bitmap(fs);
2867         if (retval) {
2868                 fputs(_("Failed to read block bitmap\n"), stderr);
2869                 return retval;
2870         }
2871         INIT_LIST_HEAD(&blk_move_list);
2872
2873
2874         new_ino_blks_per_grp = ext2fs_div_ceil(
2875                                         EXT2_INODES_PER_GROUP(fs->super)*
2876                                         new_size,
2877                                         fs->blocksize);
2878
2879         /* We may change the file system.
2880          * Mark the file system as invalid so that
2881          * the user is prompted to run fsck.
2882          */
2883         fs->super->s_state &= ~EXT2_VALID_FS;
2884
2885         retval = ext2fs_allocate_block_bitmap(fs, _("blocks to be moved"),
2886                                                 &bmap);
2887         if (retval) {
2888                 fputs(_("Failed to allocate block bitmap when "
2889                                 "increasing inode size\n"), stderr);
2890                 return retval;
2891         }
2892         retval = get_move_bitmaps(fs, new_ino_blks_per_grp, bmap);
2893         if (retval) {
2894                 fputs(_("Not enough space to increase inode size \n"), stderr);
2895                 goto err_out;
2896         }
2897         retval = move_block(fs, bmap);
2898         if (retval) {
2899                 fputs(_("Failed to relocate blocks during inode resize \n"),
2900                       stderr);
2901                 goto err_out;
2902         }
2903         retval = inode_scan_and_fix(fs, bmap);
2904         if (retval)
2905                 goto err_out_undo;
2906
2907         retval = group_desc_scan_and_fix(fs, bmap);
2908         if (retval)
2909                 goto err_out_undo;
2910
2911         retval = expand_inode_table(fs, new_size);
2912         if (retval)
2913                 goto err_out_undo;
2914
2915         ext2fs_calculate_summary_stats(fs, 1 /* super only */);
2916
2917         fs->super->s_state |= EXT2_VALID_FS;
2918         /* mark super block and block bitmap as dirty */
2919         ext2fs_mark_super_dirty(fs);
2920         ext2fs_mark_bb_dirty(fs);
2921
2922 err_out:
2923         free_blk_move_list();
2924         ext2fs_free_block_bitmap(bmap);
2925
2926         return retval;
2927
2928 err_out_undo:
2929         free_blk_move_list();
2930         ext2fs_free_block_bitmap(bmap);
2931         fputs(_("Error in resizing the inode size.\n"
2932                         "Run e2undo to undo the "
2933                         "file system changes. \n"), stderr);
2934
2935         return retval;
2936 }
2937
2938 static int tune2fs_setup_tdb(const char *name, io_manager *io_ptr)
2939 {
2940         errcode_t retval = 0;
2941         const char *tdb_dir;
2942         char *tdb_file = NULL;
2943         char *dev_name, *tmp_name;
2944
2945         /* (re)open a specific undo file */
2946         if (undo_file && undo_file[0] != 0) {
2947                 retval = set_undo_io_backing_manager(*io_ptr);
2948                 if (retval)
2949                         goto err;
2950                 *io_ptr = undo_io_manager;
2951                 retval = set_undo_io_backup_file(undo_file);
2952                 if (retval)
2953                         goto err;
2954                 printf(_("Overwriting existing filesystem; this can be undone "
2955                          "using the command:\n"
2956                          "    e2undo %s %s\n\n"),
2957                          undo_file, name);
2958                 return retval;
2959         }
2960
2961         /*
2962          * Configuration via a conf file would be
2963          * nice
2964          */
2965         tdb_dir = getenv("E2FSPROGS_UNDO_DIR");
2966         if (!tdb_dir)
2967                 tdb_dir = "/var/lib/e2fsprogs";
2968
2969         if (!strcmp(tdb_dir, "none") || (tdb_dir[0] == 0) ||
2970             access(tdb_dir, W_OK))
2971                 return 0;
2972
2973         tmp_name = strdup(name);
2974         if (!tmp_name)
2975                 goto errout;
2976         dev_name = basename(tmp_name);
2977         tdb_file = malloc(strlen(tdb_dir) + 9 + strlen(dev_name) + 7 + 1);
2978         if (!tdb_file) {
2979                 free(tmp_name);
2980                 goto errout;
2981         }
2982         sprintf(tdb_file, "%s/tune2fs-%s.e2undo", tdb_dir, dev_name);
2983         free(tmp_name);
2984
2985         if ((unlink(tdb_file) < 0) && (errno != ENOENT)) {
2986                 retval = errno;
2987                 com_err(program_name, retval,
2988                         _("while trying to delete %s"), tdb_file);
2989                 goto errout;
2990         }
2991
2992         retval = set_undo_io_backing_manager(*io_ptr);
2993         if (retval)
2994                 goto errout;
2995         *io_ptr = undo_io_manager;
2996         retval = set_undo_io_backup_file(tdb_file);
2997         if (retval)
2998                 goto errout;
2999         printf(_("Overwriting existing filesystem; this can be undone "
3000                  "using the command:\n"
3001                  "    e2undo %s %s\n\n"),
3002                  tdb_file, name);
3003
3004         free(tdb_file);
3005         return 0;
3006 errout:
3007         free(tdb_file);
3008 err:
3009         com_err("tune2fs", retval, "while trying to setup undo file\n");
3010         return retval;
3011 }
3012
3013 static int
3014 fs_update_journal_user(struct ext2_super_block *sb, __u8 old_uuid[UUID_SIZE])
3015 {
3016         int retval, nr_users, start;
3017         journal_superblock_t *jsb;
3018         ext2_filsys jfs;
3019         __u8 *j_uuid;
3020         char *journal_path;
3021         char uuid[UUID_STR_SIZE];
3022         char buf[SUPERBLOCK_SIZE] __attribute__ ((aligned(8)));
3023
3024         if (!ext2fs_has_feature_journal(sb) || uuid_is_null(sb->s_journal_uuid))
3025                 return 0;
3026
3027         uuid_unparse(sb->s_journal_uuid, uuid);
3028         journal_path = blkid_get_devname(NULL, "UUID", uuid);
3029         if (!journal_path)
3030                 return 0;
3031
3032         retval = ext2fs_open2(journal_path, io_options,
3033                               EXT2_FLAG_JOURNAL_DEV_OK | EXT2_FLAG_RW,
3034                               0, 0, unix_io_manager, &jfs);
3035         if (retval) {
3036                 com_err(program_name, retval,
3037                         _("while trying to open %s"),
3038                         journal_path);
3039                 return retval;
3040         }
3041
3042         retval = get_journal_sb(jfs, buf);
3043         if (retval != 0) {
3044                 if (retval == EXT2_ET_UNSUPP_FEATURE)
3045                         fprintf(stderr, _("%s is not a journal device.\n"),
3046                                 journal_path);
3047                 return retval;
3048         }
3049
3050         jsb = (journal_superblock_t *) buf;
3051         /* Find the filesystem UUID */
3052         nr_users = ntohl(jsb->s_nr_users);
3053         if (nr_users > JBD2_USERS_MAX) {
3054                 fprintf(stderr, _("Journal superblock is corrupted, nr_users\n"
3055                                  "is too high (%d).\n"), nr_users);
3056                 return EXT2_ET_CORRUPT_JOURNAL_SB;
3057         }
3058
3059         j_uuid = journal_user(old_uuid, jsb->s_users, nr_users);
3060         if (j_uuid == NULL) {
3061                 fputs(_("Filesystem's UUID not found on journal device.\n"),
3062                       stderr);
3063                 return EXT2_ET_LOAD_EXT_JOURNAL;
3064         }
3065
3066         memcpy(j_uuid, sb->s_uuid, UUID_SIZE);
3067
3068         start = ext2fs_journal_sb_start(jfs->blocksize);
3069         /* Write back the journal superblock */
3070         retval = io_channel_write_blk64(jfs->io, start, -SUPERBLOCK_SIZE, buf);
3071         if (retval != 0) {
3072                 com_err(program_name, retval,
3073                         "while writing journal superblock.");
3074                 return retval;
3075         }
3076
3077         ext2fs_close(jfs);
3078
3079         return 0;
3080 }
3081
3082 /*
3083  * Use FS_IOC_SETFSLABEL or FS_IOC_GETFSLABEL to set/get file system label
3084  * Return:      0 on success
3085  *              1 on error
3086  *              -1 when the old method should be used
3087  */
3088 int handle_fslabel(int setlabel) {
3089         errcode_t ret;
3090         int mnt_flags, fd;
3091         char label[FSLABEL_MAX];
3092         int maxlen = FSLABEL_MAX - 1;
3093         char mntpt[PATH_MAX + 1];
3094
3095 #ifdef __linux__
3096         ret = ext2fs_check_mount_point(device_name, &mnt_flags,
3097                                           mntpt, sizeof(mntpt));
3098         if (ret) {
3099                 com_err(device_name, ret, _("while checking mount status"));
3100                 return 1;
3101         }
3102         if (!(mnt_flags & EXT2_MF_MOUNTED) ||
3103             (setlabel && (mnt_flags & EXT2_MF_READONLY)))
3104                 return -1;
3105
3106         if (!mntpt[0]) {
3107                 fprintf(stderr,_("Unknown mount point for %s\n"), device_name);
3108                 return 1;
3109         }
3110
3111         fd = open(mntpt, O_RDONLY);
3112         if (fd < 0) {
3113                 com_err(mntpt, errno, _("while opening mount point"));
3114                 return 1;
3115         }
3116
3117         /* Get fs label */
3118         if (!setlabel) {
3119                 if (ioctl(fd, FS_IOC_GETFSLABEL, &label)) {
3120                         close(fd);
3121                         if (errno == ENOTTY)
3122                                 return -1;
3123                         com_err(mntpt, errno, _("while trying to get fs label"));
3124                         return 1;
3125                 }
3126                 close(fd);
3127                 printf("%.*s\n", EXT2_LEN_STR(label));
3128                 return 0;
3129         }
3130
3131         /* If it's extN file system, truncate the label to appropriate size */
3132         if (mnt_flags & EXT2_MF_EXTFS)
3133                 maxlen = EXT2_LABEL_LEN;
3134         if (strlen(new_label) > maxlen) {
3135                 fputs(_("Warning: label too long, truncating.\n"),
3136                       stderr);
3137                 new_label[maxlen] = '\0';
3138         }
3139
3140         /* Set fs label */
3141         if (ioctl(fd, FS_IOC_SETFSLABEL, new_label)) {
3142                 close(fd);
3143                 if (errno == ENOTTY)
3144                         return -1;
3145                 com_err(mntpt, errno, _("while trying to set fs label"));
3146                 return 1;
3147         }
3148         close(fd);
3149         return 0;
3150 #else
3151         return -1;
3152 #endif
3153 }
3154
3155 #ifndef BUILD_AS_LIB
3156 int main(int argc, char **argv)
3157 #else
3158 int tune2fs_main(int argc, char **argv)
3159 #endif  /* BUILD_AS_LIB */
3160 {
3161         errcode_t retval;
3162         ext2_filsys fs;
3163         struct ext2_super_block *sb;
3164         io_manager io_ptr, io_ptr_orig = NULL;
3165         int rc = 0;
3166         char default_undo_file[1] = { 0 };
3167         char mntpt[PATH_MAX + 1] = { 0 };
3168         int fd = -1;
3169         struct fsuuid *fsuuid = NULL;
3170
3171 #ifdef ENABLE_NLS
3172         setlocale(LC_MESSAGES, "");
3173         setlocale(LC_CTYPE, "");
3174         bindtextdomain(NLS_CAT_NAME, LOCALEDIR);
3175         textdomain(NLS_CAT_NAME);
3176         set_com_err_gettext(gettext);
3177 #endif
3178         if (argc && *argv)
3179                 program_name = *argv;
3180         else
3181                 usage();
3182         add_error_table(&et_ext2_error_table);
3183
3184 #ifdef CONFIG_BUILD_FINDFS
3185         if (strcmp(get_progname(argv[0]), "findfs") == 0)
3186                 do_findfs(argc, argv);
3187 #endif
3188         if (strcmp(get_progname(argv[0]), "e2label") == 0)
3189                 parse_e2label_options(argc, argv);
3190         else
3191                 parse_tune2fs_options(argc, argv);
3192
3193 #ifdef CONFIG_TESTIO_DEBUG
3194         if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_DEBUG")) {
3195                 io_ptr = test_io_manager;
3196                 test_io_backing_manager = unix_io_manager;
3197         } else
3198 #endif
3199                 io_ptr = unix_io_manager;
3200
3201         /*
3202          * Try the get/set fs label using ioctls before we even attempt
3203          * to open the file system.
3204          */
3205         if (L_flag || print_label) {
3206                 rc = handle_fslabel(L_flag);
3207                 if (rc != -1) {
3208 #ifndef BUILD_AS_LIB
3209                         exit(rc);
3210 #endif
3211                         return rc;
3212                 }
3213                 rc = 0;
3214         }
3215
3216 retry_open:
3217         if ((open_flag & EXT2_FLAG_RW) == 0 || f_flag)
3218                 open_flag |= EXT2_FLAG_SKIP_MMP;
3219
3220         open_flag |= EXT2_FLAG_64BITS | EXT2_FLAG_THREADS |
3221                 EXT2_FLAG_JOURNAL_DEV_OK;
3222
3223         /* keep the filesystem struct around to dump MMP data */
3224         open_flag |= EXT2_FLAG_NOFREE_ON_ERROR;
3225
3226         retval = ext2fs_open2(device_name, io_options, open_flag,
3227                               0, 0, io_ptr, &fs);
3228         if (retval) {
3229                 com_err(program_name, retval,
3230                         _("while trying to open %s"),
3231                         device_name);
3232                 if (retval == EXT2_ET_MMP_FSCK_ON ||
3233                     retval == EXT2_ET_MMP_UNKNOWN_SEQ)
3234                         dump_mmp_msg(fs->mmp_buf,
3235                                      _("If you are sure the filesystem "
3236                                        "is not in use on any node, run:\n"
3237                                        "'tune2fs -f -E clear_mmp {device}'\n"));
3238                 else if (retval == EXT2_ET_MMP_FAILED)
3239                         dump_mmp_msg(fs->mmp_buf, NULL);
3240                 else if (retval == EXT2_ET_MMP_MAGIC_INVALID)
3241                         fprintf(stderr,
3242                                 _("MMP block magic is bad. Try to fix it by "
3243                                   "running:\n'e2fsck -f %s'\n"), device_name);
3244                 else if (retval == EXT2_ET_BAD_MAGIC)
3245                         check_plausibility(device_name, CHECK_FS_EXIST, NULL);
3246                 else if (retval != EXT2_ET_MMP_FAILED)
3247                         fprintf(stderr, "%s",
3248                              _("Couldn't find valid filesystem superblock.\n"));
3249
3250                 ext2fs_free(fs);
3251                 exit(1);
3252         }
3253         if (ext2fs_has_feature_journal_dev(fs->super)) {
3254                 fprintf(stderr, "%s", _("Cannot modify a journal device.\n"));
3255                 ext2fs_free(fs);
3256                 exit(1);
3257         }
3258         fs->default_bitmap_type = EXT2FS_BMAP64_RBTREE;
3259
3260         if (I_flag) {
3261                 /*
3262                  * Check the inode size is right so we can issue an
3263                  * error message and bail before setting up the tdb
3264                  * file.
3265                  */
3266                 if (new_inode_size == EXT2_INODE_SIZE(fs->super)) {
3267                         fprintf(stderr, _("The inode size is already %lu\n"),
3268                                 new_inode_size);
3269                         rc = 1;
3270                         goto closefs;
3271                 }
3272                 if (new_inode_size < EXT2_INODE_SIZE(fs->super)) {
3273                         fprintf(stderr, "%s",
3274                                 _("Shrinking inode size is not supported\n"));
3275                         rc = 1;
3276                         goto closefs;
3277                 }
3278                 if (new_inode_size > fs->blocksize) {
3279                         fprintf(stderr, _("Invalid inode size %lu (max %d)\n"),
3280                                 new_inode_size, fs->blocksize);
3281                         rc = 1;
3282                         goto closefs;
3283                 }
3284                 rc = check_fsck_needed(fs,
3285                         _("Resizing inodes could take some time."));
3286                 if (rc)
3287                         goto closefs;
3288                 /*
3289                  * If inode resize is requested use the
3290                  * Undo I/O manager
3291                  */
3292                 undo_file = default_undo_file;
3293         }
3294
3295         /* Set up an undo file */
3296         if (undo_file && io_ptr_orig == NULL) {
3297                 io_ptr_orig = io_ptr;
3298                 retval = tune2fs_setup_tdb(device_name, &io_ptr);
3299                 if (retval) {
3300                         rc = 1;
3301                         goto closefs;
3302                 }
3303                 if (io_ptr != io_ptr_orig) {
3304                         ext2fs_close_free(&fs);
3305                         goto retry_open;
3306                 }
3307         }
3308
3309         sb = fs->super;
3310         fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
3311
3312         if (print_label) {
3313                 /* For e2label emulation */
3314                 printf("%.*s\n", EXT2_LEN_STR(sb->s_volume_name));
3315                 remove_error_table(&et_ext2_error_table);
3316                 goto closefs;
3317         }
3318
3319         retval = ext2fs_check_mount_point(device_name, &mount_flags,
3320                                         mntpt, sizeof(mntpt));
3321         if (retval) {
3322                 com_err("ext2fs_check_mount_point", retval,
3323                         _("while determining whether %s is mounted."),
3324                         device_name);
3325                 rc = 1;
3326                 goto closefs;
3327         }
3328
3329 #ifdef NO_RECOVERY
3330         /* Warn if file system needs recovery and it is opened for writing. */
3331         if ((open_flag & EXT2_FLAG_RW) && !(mount_flags & EXT2_MF_MOUNTED) &&
3332             (sb->s_feature_compat & EXT3_FEATURE_COMPAT_HAS_JOURNAL) &&
3333             (sb->s_feature_incompat & EXT3_FEATURE_INCOMPAT_RECOVER)) {
3334                 fprintf(stderr,
3335 _("Warning: The journal is dirty. You may wish to replay the journal like:\n\n"
3336   "\te2fsck -E journal_only %s\n\n"
3337   "then rerun this command.  Otherwise, any changes made may be overwritten\n"
3338   "by journal recovery.\n"), device_name);
3339         }
3340 #else
3341         /* Recover the journal if possible. */
3342         if ((open_flag & EXT2_FLAG_RW) && !(mount_flags & (EXT2_MF_BUSY | EXT2_MF_MOUNTED)) &&
3343             ext2fs_has_feature_journal_needs_recovery(fs->super)) {
3344                 printf(_("Recovering journal.\n"));
3345                 retval = ext2fs_run_ext3_journal(&fs);
3346                 if (retval) {
3347                         com_err("tune2fs", retval,
3348                                 "while recovering journal.\n");
3349                         printf(_("Please run e2fsck -fy %s.\n"), device_name);
3350                         if (!fs)
3351                                 exit(1);
3352                         rc = 1;
3353                         goto closefs;
3354                 }
3355                 sb = fs->super;
3356         }
3357 #endif
3358
3359         /* Normally we only need to write out the superblock */
3360         fs->flags |= EXT2_FLAG_SUPER_ONLY;
3361
3362         if (c_flag) {
3363                 if (max_mount_count == 65536)
3364                         max_mount_count = EXT2_DFL_MAX_MNT_COUNT +
3365                                 (random() % EXT2_DFL_MAX_MNT_COUNT);
3366                 sb->s_max_mnt_count = max_mount_count;
3367                 ext2fs_mark_super_dirty(fs);
3368                 printf(_("Setting maximal mount count to %d\n"),
3369                        max_mount_count);
3370         }
3371         if (C_flag) {
3372                 sb->s_mnt_count = mount_count;
3373                 ext2fs_mark_super_dirty(fs);
3374                 printf(_("Setting current mount count to %d\n"), mount_count);
3375         }
3376         if (e_flag) {
3377                 sb->s_errors = errors;
3378                 ext2fs_mark_super_dirty(fs);
3379                 printf(_("Setting error behavior to %d\n"), errors);
3380         }
3381         if (g_flag) {
3382                 sb->s_def_resgid = resgid;
3383                 ext2fs_mark_super_dirty(fs);
3384                 printf(_("Setting reserved blocks gid to %lu\n"), resgid);
3385         }
3386         if (i_flag) {
3387                 if ((unsigned long long)interval >= (1ULL << 32)) {
3388                         com_err(program_name, 0,
3389                                 _("interval between checks is too big (%lu)"),
3390                                 interval);
3391                         rc = 1;
3392                         goto closefs;
3393                 }
3394                 sb->s_checkinterval = interval;
3395                 ext2fs_mark_super_dirty(fs);
3396                 printf(_("Setting interval between checks to %lu seconds\n"),
3397                        interval);
3398         }
3399         if (m_flag) {
3400                 ext2fs_r_blocks_count_set(sb, reserved_ratio *
3401                                           ext2fs_blocks_count(sb) / 100.0);
3402                 ext2fs_mark_super_dirty(fs);
3403                 printf (_("Setting reserved blocks percentage to %g%% (%llu blocks)\n"),
3404                         reserved_ratio,
3405                         (unsigned long long) ext2fs_r_blocks_count(sb));
3406         }
3407         if (r_flag) {
3408                 if (reserved_blocks > ext2fs_blocks_count(sb)/2) {
3409                         com_err(program_name, 0,
3410                                 _("reserved blocks count is too big (%llu)"),
3411                                 (unsigned long long) reserved_blocks);
3412                         rc = 1;
3413                         goto closefs;
3414                 }
3415                 ext2fs_r_blocks_count_set(sb, reserved_blocks);
3416                 ext2fs_mark_super_dirty(fs);
3417                 printf(_("Setting reserved blocks count to %llu\n"),
3418                        (unsigned long long) reserved_blocks);
3419         }
3420         if (s_flag == 1) {
3421                 if (ext2fs_has_feature_sparse_super(sb)) {
3422                         fputs(_("\nThe filesystem already has sparse "
3423                                 "superblocks.\n"), stderr);
3424                 } else if (ext2fs_has_feature_meta_bg(sb)) {
3425                         fputs(_("\nSetting the sparse superblock flag not "
3426                                 "supported\nfor filesystems with "
3427                                 "the meta_bg feature enabled.\n"),
3428                                 stderr);
3429                         rc = 1;
3430                         goto closefs;
3431                 } else {
3432                         ext2fs_set_feature_sparse_super(sb);
3433                         sb->s_state &= ~EXT2_VALID_FS;
3434                         ext2fs_mark_super_dirty(fs);
3435                         printf(_("\nSparse superblock flag set.  %s"),
3436                                _(please_fsck));
3437                 }
3438         }
3439         if (s_flag == 0) {
3440                 fputs(_("\nClearing the sparse superblock flag not supported.\n"),
3441                       stderr);
3442                 rc = 1;
3443                 goto closefs;
3444         }
3445         if (T_flag) {
3446                 sb->s_lastcheck = last_check_time;
3447                 ext2fs_mark_super_dirty(fs);
3448                 printf(_("Setting time filesystem last checked to %s\n"),
3449                        ctime(&last_check_time));
3450         }
3451         if (u_flag) {
3452                 sb->s_def_resuid = resuid;
3453                 ext2fs_mark_super_dirty(fs);
3454                 printf(_("Setting reserved blocks uid to %lu\n"), resuid);
3455         }
3456         if (L_flag) {
3457                 if (strlen(new_label) > sizeof(sb->s_volume_name))
3458                         fputs(_("Warning: label too long, truncating.\n"),
3459                               stderr);
3460                 memset(sb->s_volume_name, 0, sizeof(sb->s_volume_name));
3461                 strncpy((char *)sb->s_volume_name, new_label,
3462                         sizeof(sb->s_volume_name));
3463                 ext2fs_mark_super_dirty(fs);
3464         }
3465         if (M_flag) {
3466                 memset(sb->s_last_mounted, 0, sizeof(sb->s_last_mounted));
3467                 strncpy((char *)sb->s_last_mounted, new_last_mounted,
3468                         sizeof(sb->s_last_mounted));
3469                 ext2fs_mark_super_dirty(fs);
3470         }
3471         if (mntopts_cmd) {
3472                 rc = update_mntopts(fs, mntopts_cmd);
3473                 if (rc)
3474                         goto closefs;
3475         }
3476         if (features_cmd) {
3477                 rc = update_feature_set(fs, features_cmd);
3478                 if (rc)
3479                         goto closefs;
3480         }
3481         if (extended_cmd) {
3482                 rc = parse_extended_opts(fs, extended_cmd);
3483                 if (rc)
3484                         goto closefs;
3485                 if (clear_mmp && !f_flag) {
3486                         fputs(_("Error in using clear_mmp. "
3487                                 "It must be used with -f\n"),
3488                               stderr);
3489                         rc = 1;
3490                         goto closefs;
3491                 }
3492         }
3493         if (clear_mmp) {
3494                 rc = ext2fs_mmp_clear(fs);
3495                 goto closefs;
3496         }
3497         if (journal_size || journal_device) {
3498                 rc = add_journal(fs);
3499                 if (rc)
3500                         goto closefs;
3501         }
3502         if (orphan_file_blocks) {
3503                 errcode_t err;
3504
3505                 err = ext2fs_read_bitmaps(fs);
3506                 if (err) {
3507                         com_err(program_name, err, "%s",
3508                                 _("while loading bitmaps"));
3509                         rc = 1;
3510                         goto closefs;
3511                 }
3512                 err = ext2fs_create_orphan_file(fs, orphan_file_blocks);
3513                 if (err) {
3514                         com_err(program_name, err, "%s",
3515                                 _("while creating orphan file"));
3516                         rc = 1;
3517                         goto closefs;
3518                 }
3519         }
3520
3521         if (Q_flag) {
3522                 if (mount_flags & EXT2_MF_MOUNTED) {
3523                         fputs(_("The quota feature may only be changed when "
3524                                 "the filesystem is unmounted.\n"), stderr);
3525                         rc = 1;
3526                         goto closefs;
3527                 }
3528                 rc = handle_quota_options(fs);
3529                 if (rc)
3530                         goto closefs;
3531         }
3532
3533         if (U_flag) {
3534                 int set_csum = 0;
3535                 dgrp_t i;
3536                 char buf[SUPERBLOCK_SIZE] __attribute__ ((aligned(8)));
3537                 __u8 old_uuid[UUID_SIZE];
3538                 uuid_t new_uuid;
3539                 errcode_t ret = -1;
3540
3541                 if (ext2fs_has_feature_stable_inodes(fs->super)) {
3542                         fputs(_("Cannot change the UUID of this filesystem "
3543                                 "because it has the stable_inodes feature "
3544                                 "flag.\n"), stderr);
3545                         exit(1);
3546                 }
3547
3548                 if (!ext2fs_has_feature_csum_seed(fs->super) &&
3549                     (ext2fs_has_feature_metadata_csum(fs->super) ||
3550                      ext2fs_has_feature_ea_inode(fs->super))) {
3551                         rc = check_fsck_needed(fs,
3552                                 _("Setting the UUID on this "
3553                                   "filesystem could take some time."));
3554                         if (rc)
3555                                 goto closefs;
3556                         rewrite_checksums = REWRITE_ALL;
3557                 }
3558
3559                 if (ext2fs_has_group_desc_csum(fs)) {
3560                         /*
3561                          * Changing the UUID on a metadata_csum FS requires
3562                          * rewriting all metadata, which can race with a
3563                          * mounted fs.  Don't allow that unless we're saving
3564                          * the checksum seed.
3565                          */
3566                         if ((mount_flags & EXT2_MF_MOUNTED) &&
3567                             !ext2fs_has_feature_csum_seed(fs->super) &&
3568                             ext2fs_has_feature_metadata_csum(fs->super)) {
3569                                 fputs(_("The UUID may only be "
3570                                         "changed when the filesystem is "
3571                                         "unmounted.\n"), stderr);
3572                                 fputs(_("If you only use kernels newer than "
3573                                         "v4.4, run 'tune2fs -O "
3574                                         "metadata_csum_seed' and re-run this "
3575                                         "command.\n"), stderr);
3576                                 try_confirm_csum_seed_support();
3577                                 rc = 1;
3578                                 goto closefs;
3579                         }
3580
3581                         /*
3582                          * Determine if the block group checksums are
3583                          * correct so we know whether or not to set
3584                          * them later on.
3585                          */
3586                         for (i = 0; i < fs->group_desc_count; i++)
3587                                 if (!ext2fs_group_desc_csum_verify(fs, i))
3588                                         break;
3589                         if (i >= fs->group_desc_count)
3590                                 set_csum = 1;
3591                 }
3592
3593 #ifdef __linux__
3594                 if ((mount_flags & EXT2_MF_MOUNTED) &&
3595                     !(mount_flags & EXT2_MF_READONLY) && mntpt[0]) {
3596                         fd = open(mntpt, O_RDONLY);
3597                         if (fd >= 0)
3598                                 fsuuid = malloc(sizeof(*fsuuid) + UUID_SIZE);
3599                         if (fsuuid) {
3600                                 fsuuid->fsu_len = UUID_SIZE;
3601                                 fsuuid->fsu_flags = 0;
3602                                 ret = ioctl(fd, EXT4_IOC_GETFSUUID, fsuuid);
3603                                 if (ret || fsuuid->fsu_len != UUID_SIZE) {
3604                                         free(fsuuid);
3605                                         fsuuid = NULL;
3606                                 }
3607                         }
3608                 }
3609 #endif
3610
3611                 memcpy(old_uuid, fsuuid ? fsuuid->fsu_uuid : sb->s_uuid,
3612                        UUID_SIZE);
3613                 if ((strcasecmp(requested_uuid, "null") == 0) ||
3614                     (strcasecmp(requested_uuid, "clear") == 0)) {
3615                         uuid_clear(new_uuid);
3616                 } else if (strcasecmp(requested_uuid, "time") == 0) {
3617                         uuid_generate_time(new_uuid);
3618                 } else if (strcasecmp(requested_uuid, "random") == 0) {
3619                         uuid_generate(new_uuid);
3620                 } else if (uuid_parse(requested_uuid, new_uuid)) {
3621                         com_err(program_name, 0, "%s",
3622                                 _("Invalid UUID format\n"));
3623                         rc = 1;
3624                         goto closefs;
3625                 }
3626
3627                 ret = -1;
3628 #ifdef __linux__
3629                 if (fsuuid) {
3630                         fsuuid->fsu_len = UUID_SIZE;
3631                         fsuuid->fsu_flags = 0;
3632                         memcpy(&fsuuid->fsu_uuid, new_uuid, UUID_SIZE);
3633                         ret = ioctl(fd, EXT4_IOC_SETFSUUID, fsuuid);
3634                 }
3635 #endif
3636                 /*
3637                  * If we can't set the UUID via the ioctl, fall
3638                  * back to directly modifying the superblock
3639                  .*/
3640                 if (ret) {
3641                         memcpy(sb->s_uuid, new_uuid, UUID_SIZE);
3642                         ext2fs_init_csum_seed(fs);
3643                         if (set_csum) {
3644                                 for (i = 0; i < fs->group_desc_count; i++)
3645                                         ext2fs_group_desc_csum_set(fs, i);
3646                                 fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
3647                         }
3648                         ext2fs_mark_super_dirty(fs);
3649                 }
3650
3651                 /* If this is a journal dev, we need to copy UUID into jsb */
3652                 if (!(rc = get_journal_sb(fs, buf))) {
3653                         journal_superblock_t *jsb;
3654
3655                         jsb = (journal_superblock_t *) buf;
3656                         fputs(_("Need to update journal superblock.\n"), stdout);
3657                         memcpy(jsb->s_uuid, sb->s_uuid, sizeof(sb->s_uuid));
3658
3659                         /* Writeback the journal superblock */
3660                         if ((rc = io_channel_write_blk64(fs->io,
3661                                 ext2fs_journal_sb_start(fs->blocksize),
3662                                         -SUPERBLOCK_SIZE, buf)))
3663                                 goto closefs;
3664                 } else if (rc != EXT2_ET_UNSUPP_FEATURE)
3665                         goto closefs;
3666                 else {
3667                         rc = 0; /** Reset rc to avoid ext2fs_mmp_stop() */
3668
3669                         if ((rc = fs_update_journal_user(sb, old_uuid)))
3670                                 goto closefs;
3671                 }
3672         }
3673
3674         if (I_flag) {
3675                 if (mount_flags & EXT2_MF_MOUNTED) {
3676                         fputs(_("The inode size may only be "
3677                                 "changed when the filesystem is "
3678                                 "unmounted.\n"), stderr);
3679                         rc = 1;
3680                         goto closefs;
3681                 }
3682                 if (ext2fs_has_feature_flex_bg(fs->super)) {
3683                         fputs(_("Changing the inode size not supported for "
3684                                 "filesystems with the flex_bg\n"
3685                                 "feature enabled.\n"),
3686                               stderr);
3687                         rc = 1;
3688                         goto closefs;
3689                 }
3690                 /*
3691                  * We want to update group descriptor also
3692                  * with the new free inode count
3693                  */
3694                 if (rewrite_checksums)
3695                         fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS;
3696                 fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
3697                 retval = resize_inode(fs, new_inode_size);
3698                 if (rewrite_checksums)
3699                         fs->flags &= ~EXT2_FLAG_IGNORE_CSUM_ERRORS;
3700                 if (retval == 0) {
3701                         printf(_("Setting inode size %lu\n"),
3702                                                         new_inode_size);
3703                         rewrite_checksums = REWRITE_ALL;
3704                 } else {
3705                         printf("%s", _("Failed to change inode size\n"));
3706                         rc = 1;
3707                         goto closefs;
3708                 }
3709         }
3710
3711         if (rewrite_checksums) {
3712                 retval = rewrite_metadata_checksums(fs, rewrite_checksums);
3713                 if (retval != 0) {
3714                         printf("Failed to rewrite metadata checksums\n");
3715                         rc = 1;
3716                         goto closefs;
3717                 }
3718         }
3719
3720         if (l_flag)
3721                 list_super(sb);
3722         if (stride_set) {
3723                 sb->s_raid_stride = stride;
3724                 ext2fs_mark_super_dirty(fs);
3725                 printf(_("Setting stride size to %d\n"), stride);
3726         }
3727         if (stripe_width_set) {
3728                 sb->s_raid_stripe_width = stripe_width;
3729                 ext2fs_mark_super_dirty(fs);
3730                 printf(_("Setting stripe width to %d\n"), stripe_width);
3731         }
3732         if (ext_mount_opts) {
3733                 strncpy((char *)(fs->super->s_mount_opts), ext_mount_opts,
3734                         sizeof(fs->super->s_mount_opts));
3735                 fs->super->s_mount_opts[sizeof(fs->super->s_mount_opts)-1] = 0;
3736                 ext2fs_mark_super_dirty(fs);
3737                 printf(_("Setting extended default mount options to '%s'\n"),
3738                        ext_mount_opts);
3739                 free(ext_mount_opts);
3740         }
3741
3742         free(device_name);
3743         remove_error_table(&et_ext2_error_table);
3744
3745 closefs:
3746         if (fd >= 0)
3747                 close(fd);
3748         if (fsuuid)
3749                 free(fsuuid);
3750         if (rc) {
3751                 ext2fs_mmp_stop(fs);
3752 #ifndef BUILD_AS_LIB
3753                 exit(1);
3754 #endif
3755         }
3756
3757         if (feature_64bit)
3758                 convert_64bit(fs, feature_64bit);
3759
3760         retval = ext2fs_close_free(&fs);
3761         if (retval) {
3762                 com_err("tune2fs", retval,
3763                         _("while writing out and closing file system"));
3764                 rc = 1;
3765         }
3766
3767         return rc;
3768 }