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