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