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