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