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