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