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