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