Whamcloud - gitweb
Clean up codes for adding new quota type
[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 quota_enable[MAXQUOTAS];
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         enum quota_type qtype;
962
963 #define FEATURE_ON(type, mask) (!(old_features[(type)] & (mask)) && \
964                                 ((&sb->s_feature_compat)[(type)] & (mask)))
965 #define FEATURE_OFF(type, mask) ((old_features[(type)] & (mask)) && \
966                                  !((&sb->s_feature_compat)[(type)] & (mask)))
967 #define FEATURE_CHANGED(type, mask) ((mask) & \
968                      (old_features[(type)] ^ (&sb->s_feature_compat)[(type)]))
969
970         old_features[E2P_FEATURE_COMPAT] = sb->s_feature_compat;
971         old_features[E2P_FEATURE_INCOMPAT] = sb->s_feature_incompat;
972         old_features[E2P_FEATURE_RO_INCOMPAT] = sb->s_feature_ro_compat;
973
974         if (e2p_edit_feature2(features, &sb->s_feature_compat,
975                               ok_features, clear_ok_features,
976                               &type_err, &mask_err)) {
977                 if (!mask_err)
978                         fprintf(stderr,
979                                 _("Invalid filesystem option set: %s\n"),
980                                 features);
981                 else if (type_err & E2P_FEATURE_NEGATE_FLAG)
982                         fprintf(stderr, _("Clearing filesystem feature '%s' "
983                                           "not supported.\n"),
984                                 e2p_feature2string(type_err &
985                                                    E2P_FEATURE_TYPE_MASK,
986                                                    mask_err));
987                 else
988                         fprintf(stderr, _("Setting filesystem feature '%s' "
989                                           "not supported.\n"),
990                                 e2p_feature2string(type_err, mask_err));
991                 return 1;
992         }
993
994         if (FEATURE_OFF(E2P_FEATURE_COMPAT, EXT3_FEATURE_COMPAT_HAS_JOURNAL)) {
995                 if ((mount_flags & EXT2_MF_MOUNTED) &&
996                     !(mount_flags & EXT2_MF_READONLY)) {
997                         fputs(_("The has_journal feature may only be "
998                                 "cleared when the filesystem is\n"
999                                 "unmounted or mounted "
1000                                 "read-only.\n"), stderr);
1001                         return 1;
1002                 }
1003                 if (ext2fs_has_feature_journal_needs_recovery(sb) &&
1004                     f_flag < 2) {
1005                         fputs(_("The needs_recovery flag is set.  "
1006                                 "Please run e2fsck before clearing\n"
1007                                 "the has_journal flag.\n"), stderr);
1008                         return 1;
1009                 }
1010                 if (sb->s_journal_inum) {
1011                         if (remove_journal_inode(fs))
1012                                 return 1;
1013                 }
1014                 if (sb->s_journal_dev) {
1015                         if (remove_journal_device(fs))
1016                                 return 1;
1017                 }
1018         }
1019
1020         if (FEATURE_ON(E2P_FEATURE_RO_INCOMPAT,
1021                 EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER)) {
1022                 if (ext2fs_has_feature_meta_bg(sb)) {
1023                         fputs(_("Setting filesystem feature 'sparse_super' "
1024                                 "not supported\nfor filesystems with "
1025                                 "the meta_bg feature enabled.\n"),
1026                                 stderr);
1027                         return 1;
1028                 }
1029         }
1030
1031         if (FEATURE_ON(E2P_FEATURE_INCOMPAT, EXT4_FEATURE_INCOMPAT_MMP)) {
1032                 int error;
1033
1034                 if ((mount_flags & EXT2_MF_MOUNTED) ||
1035                     (mount_flags & EXT2_MF_READONLY)) {
1036                         fputs(_("The multiple mount protection feature can't\n"
1037                                 "be set if the filesystem is mounted or\n"
1038                                 "read-only.\n"), stderr);
1039                         return 1;
1040                 }
1041
1042                 error = ext2fs_mmp_init(fs);
1043                 if (error) {
1044                         fputs(_("\nError while enabling multiple mount "
1045                                 "protection feature."), stderr);
1046                         return 1;
1047                 }
1048
1049                 /*
1050                  * We want to update group desc with the new free blocks count
1051                  */
1052                 fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
1053
1054                 printf(_("Multiple mount protection has been enabled "
1055                          "with update interval %ds.\n"),
1056                        sb->s_mmp_update_interval);
1057         }
1058
1059         if (FEATURE_OFF(E2P_FEATURE_INCOMPAT, EXT4_FEATURE_INCOMPAT_MMP)) {
1060                 int error;
1061
1062                 if (mount_flags & EXT2_MF_READONLY) {
1063                         fputs(_("The multiple mount protection feature cannot\n"
1064                                 "be disabled if the filesystem is readonly.\n"),
1065                                 stderr);
1066                         return 1;
1067                 }
1068
1069                 error = ext2fs_read_bitmaps(fs);
1070                 if (error) {
1071                         fputs(_("Error while reading bitmaps\n"), stderr);
1072                         return 1;
1073                 }
1074
1075                 error = ext2fs_mmp_read(fs, sb->s_mmp_block, NULL);
1076                 if (error) {
1077                         struct mmp_struct *mmp_cmp = fs->mmp_cmp;
1078
1079                         if (error == EXT2_ET_MMP_MAGIC_INVALID)
1080                                 printf(_("Magic number in MMP block does not "
1081                                          "match. expected: %x, actual: %x\n"),
1082                                          EXT4_MMP_MAGIC, mmp_cmp->mmp_magic);
1083                         else
1084                                 com_err(program_name, error, "%s",
1085                                         _("while reading MMP block."));
1086                         goto mmp_error;
1087                 }
1088
1089                 /* We need to force out the group descriptors as well */
1090                 fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
1091                 ext2fs_block_alloc_stats2(fs, sb->s_mmp_block, -1);
1092 mmp_error:
1093                 sb->s_mmp_block = 0;
1094                 sb->s_mmp_update_interval = 0;
1095         }
1096
1097         if (FEATURE_ON(E2P_FEATURE_COMPAT, EXT3_FEATURE_COMPAT_HAS_JOURNAL)) {
1098                 /*
1099                  * If adding a journal flag, let the create journal
1100                  * code below handle setting the flag and creating the
1101                  * journal.  We supply a default size if necessary.
1102                  */
1103                 if (!journal_size)
1104                         journal_size = -1;
1105                 ext2fs_clear_feature_journal(sb);
1106         }
1107
1108         if (FEATURE_ON(E2P_FEATURE_COMPAT, EXT2_FEATURE_COMPAT_DIR_INDEX)) {
1109                 if (!sb->s_def_hash_version)
1110                         sb->s_def_hash_version = EXT2_HASH_HALF_MD4;
1111                 if (uuid_is_null((unsigned char *) sb->s_hash_seed))
1112                         uuid_generate((unsigned char *) sb->s_hash_seed);
1113         }
1114
1115         if (FEATURE_OFF(E2P_FEATURE_INCOMPAT, EXT4_FEATURE_INCOMPAT_FLEX_BG)) {
1116                 if (ext2fs_check_desc(fs)) {
1117                         fputs(_("Clearing the flex_bg flag would "
1118                                 "cause the the filesystem to be\n"
1119                                 "inconsistent.\n"), stderr);
1120                         return 1;
1121                 }
1122         }
1123
1124         if (FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
1125                             EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
1126                 if ((mount_flags & EXT2_MF_MOUNTED) &&
1127                     !(mount_flags & EXT2_MF_READONLY)) {
1128                         fputs(_("The huge_file feature may only be "
1129                                 "cleared when the filesystem is\n"
1130                                 "unmounted or mounted "
1131                                 "read-only.\n"), stderr);
1132                         return 1;
1133                 }
1134         }
1135
1136         if (FEATURE_ON(E2P_FEATURE_RO_INCOMPAT,
1137                        EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) {
1138                 if (check_fsck_needed(fs))
1139                         exit(1);
1140                 if (mount_flags & EXT2_MF_MOUNTED) {
1141                         fputs(_("Cannot enable metadata_csum on a mounted "
1142                                 "filesystem!\n"), stderr);
1143                         exit(1);
1144                 }
1145                 if (!ext2fs_has_feature_extents(fs->super))
1146                         printf("%s",
1147                                _("Extents are not enabled.  The file extent "
1148                                  "tree can be checksummed, whereas block maps "
1149                                  "cannot.  Not enabling extents reduces the "
1150                                  "coverage of metadata checksumming.  "
1151                                  "Re-run with -O extent to rectify.\n"));
1152                 if (!ext2fs_has_feature_64bit(fs->super))
1153                         printf("%s",
1154                                _("64-bit filesystem support is not enabled.  "
1155                                  "The larger fields afforded by this feature "
1156                                  "enable full-strength checksumming.  "
1157                                  "Run resize2fs -b to rectify.\n"));
1158                 rewrite_checksums = 1;
1159                 /* metadata_csum supersedes uninit_bg */
1160                 ext2fs_clear_feature_gdt_csum(fs->super);
1161
1162                 /* if uninit_bg was previously off, rewrite group desc */
1163                 if (!(old_features[E2P_FEATURE_RO_INCOMPAT] &
1164                       EXT4_FEATURE_RO_COMPAT_GDT_CSUM))
1165                         enable_uninit_bg(fs);
1166
1167                 /*
1168                  * Since metadata_csum supersedes uninit_bg, pretend like
1169                  * uninit_bg has been off all along.
1170                  */
1171                 old_features[E2P_FEATURE_RO_INCOMPAT] &=
1172                         ~EXT4_FEATURE_RO_COMPAT_GDT_CSUM;
1173         }
1174
1175         if (FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
1176                         EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) {
1177                 __u32   test_features[3];
1178
1179                 if (check_fsck_needed(fs))
1180                         exit(1);
1181                 if (mount_flags & EXT2_MF_MOUNTED) {
1182                         fputs(_("Cannot disable metadata_csum on a mounted "
1183                                 "filesystem!\n"), stderr);
1184                         exit(1);
1185                 }
1186                 rewrite_checksums = 1;
1187
1188                 /* Enable uninit_bg unless the user expressly turned it off */
1189                 memcpy(test_features, old_features, sizeof(test_features));
1190                 test_features[E2P_FEATURE_RO_INCOMPAT] |=
1191                                                 EXT4_FEATURE_RO_COMPAT_GDT_CSUM;
1192                 e2p_edit_feature2(features, test_features, ok_features,
1193                                   clear_ok_features, NULL, NULL);
1194                 if (test_features[E2P_FEATURE_RO_INCOMPAT] &
1195                                                 EXT4_FEATURE_RO_COMPAT_GDT_CSUM)
1196                         ext2fs_set_feature_gdt_csum(fs->super);
1197
1198                 /*
1199                  * If we're turning off metadata_csum and not turning on
1200                  * uninit_bg, rewrite group desc.
1201                  */
1202                 if (!ext2fs_has_feature_gdt_csum(fs->super)) {
1203                         err = disable_uninit_bg(fs,
1204                                         EXT4_FEATURE_RO_COMPAT_METADATA_CSUM);
1205                         if (err)
1206                                 return 1;
1207                 } else
1208                         /*
1209                          * metadata_csum previously provided uninit_bg, so if
1210                          * we're also setting the uninit_bg feature bit,
1211                          * pretend like it was previously enabled.  Checksums
1212                          * will be rewritten with crc16 later.
1213                          */
1214                         old_features[E2P_FEATURE_RO_INCOMPAT] |=
1215                                 EXT4_FEATURE_RO_COMPAT_GDT_CSUM;
1216         }
1217
1218         if (FEATURE_ON(E2P_FEATURE_RO_INCOMPAT,
1219                        EXT4_FEATURE_RO_COMPAT_GDT_CSUM)) {
1220                 /* Do not enable uninit_bg when metadata_csum enabled */
1221                 if (ext2fs_has_feature_metadata_csum(fs->super))
1222                         ext2fs_clear_feature_gdt_csum(fs->super);
1223                 else
1224                         enable_uninit_bg(fs);
1225         }
1226
1227         if (FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
1228                         EXT4_FEATURE_RO_COMPAT_GDT_CSUM)) {
1229                 err = disable_uninit_bg(fs,
1230                                 EXT4_FEATURE_RO_COMPAT_GDT_CSUM);
1231                 if (err)
1232                         return 1;
1233         }
1234
1235         /*
1236          * We don't actually toggle 64bit; resize2fs does that.  But this
1237          * must come after the metadata_csum feature_on so that it won't
1238          * complain about the lack of 64bit.
1239          */
1240         if (FEATURE_ON(E2P_FEATURE_INCOMPAT,
1241                        EXT4_FEATURE_INCOMPAT_64BIT)) {
1242                 if (mount_flags & EXT2_MF_MOUNTED) {
1243                         fprintf(stderr, _("Cannot enable 64-bit mode "
1244                                           "while mounted!\n"));
1245                         exit(1);
1246                 }
1247                 ext2fs_clear_feature_64bit(sb);
1248                 feature_64bit = 1;
1249         }
1250         if (FEATURE_OFF(E2P_FEATURE_INCOMPAT,
1251                         EXT4_FEATURE_INCOMPAT_64BIT)) {
1252                 if (mount_flags & EXT2_MF_MOUNTED) {
1253                         fprintf(stderr, _("Cannot disable 64-bit mode "
1254                                           "while mounted!\n"));
1255                         exit(1);
1256                 }
1257                 ext2fs_set_feature_64bit(sb);
1258                 feature_64bit = -1;
1259         }
1260
1261         if (FEATURE_ON(E2P_FEATURE_RO_INCOMPAT,
1262                                 EXT4_FEATURE_RO_COMPAT_QUOTA)) {
1263                 /*
1264                  * Set the Q_flag here and handle the quota options in the code
1265                  * below.
1266                  */
1267                 if (!Q_flag) {
1268                         Q_flag = 1;
1269                         /* Enable all quota by default */
1270                         for (qtype = 0; qtype < MAXQUOTAS; qtype++)
1271                                 quota_enable[qtype] = QOPT_ENABLE;
1272                 }
1273                 ext2fs_clear_feature_quota(sb);
1274         }
1275
1276         if (FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
1277                                 EXT4_FEATURE_RO_COMPAT_QUOTA)) {
1278                 /*
1279                  * Set the Q_flag here and handle the quota options in the code
1280                  * below.
1281                  */
1282                 if (Q_flag)
1283                         fputs(_("\nWarning: '^quota' option overrides '-Q'"
1284                                 "arguments.\n"), stderr);
1285                 Q_flag = 1;
1286                 /* Disable all quota by default */
1287                 for (qtype = 0; qtype < MAXQUOTAS; qtype++)
1288                         quota_enable[qtype] = QOPT_DISABLE;
1289         }
1290
1291         if (FEATURE_ON(E2P_FEATURE_INCOMPAT, EXT4_FEATURE_INCOMPAT_ENCRYPT)) {
1292                 fs->super->s_encrypt_algos[0] =
1293                         EXT4_ENCRYPTION_MODE_AES_256_XTS;
1294                 fs->super->s_encrypt_algos[1] =
1295                         EXT4_ENCRYPTION_MODE_AES_256_CTS;
1296         }
1297
1298         if (sb->s_rev_level == EXT2_GOOD_OLD_REV &&
1299             (sb->s_feature_compat || sb->s_feature_ro_compat ||
1300              sb->s_feature_incompat))
1301                 ext2fs_update_dynamic_rev(fs);
1302
1303         if (FEATURE_CHANGED(E2P_FEATURE_RO_INCOMPAT,
1304                             EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER) ||
1305             FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
1306                         EXT4_FEATURE_RO_COMPAT_HUGE_FILE) ||
1307             FEATURE_CHANGED(E2P_FEATURE_INCOMPAT,
1308                             EXT2_FEATURE_INCOMPAT_FILETYPE) ||
1309             FEATURE_CHANGED(E2P_FEATURE_COMPAT,
1310                             EXT2_FEATURE_COMPAT_RESIZE_INODE) ||
1311             FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
1312                         EXT2_FEATURE_RO_COMPAT_LARGE_FILE))
1313                 request_fsck_afterwards(fs);
1314
1315         if ((old_features[E2P_FEATURE_COMPAT] != sb->s_feature_compat) ||
1316             (old_features[E2P_FEATURE_INCOMPAT] != sb->s_feature_incompat) ||
1317             (old_features[E2P_FEATURE_RO_INCOMPAT] != sb->s_feature_ro_compat))
1318                 ext2fs_mark_super_dirty(fs);
1319
1320         return 0;
1321 }
1322
1323 /*
1324  * Add a journal to the filesystem.
1325  */
1326 static int add_journal(ext2_filsys fs)
1327 {
1328         unsigned long journal_blocks;
1329         errcode_t       retval;
1330         ext2_filsys     jfs;
1331         io_manager      io_ptr;
1332
1333         if (ext2fs_has_feature_journal(fs->super)) {
1334                 fputs(_("The filesystem already has a journal.\n"), stderr);
1335                 goto err;
1336         }
1337         if (journal_device) {
1338                 if (!check_plausibility(journal_device, CHECK_BLOCK_DEV,
1339                                         NULL))
1340                         proceed_question(-1);
1341                 check_mount(journal_device, 0, _("journal"));
1342 #ifdef CONFIG_TESTIO_DEBUG
1343                 if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_BLOCK")) {
1344                         io_ptr = test_io_manager;
1345                         test_io_backing_manager = unix_io_manager;
1346                 } else
1347 #endif
1348                         io_ptr = unix_io_manager;
1349                 retval = ext2fs_open(journal_device, EXT2_FLAG_RW|
1350                                      EXT2_FLAG_JOURNAL_DEV_OK, 0,
1351                                      fs->blocksize, io_ptr, &jfs);
1352                 if (retval) {
1353                         com_err(program_name, retval,
1354                                 _("\n\twhile trying to open journal on %s\n"),
1355                                 journal_device);
1356                         goto err;
1357                 }
1358                 printf(_("Creating journal on device %s: "),
1359                        journal_device);
1360                 fflush(stdout);
1361
1362                 retval = ext2fs_add_journal_device(fs, jfs);
1363                 ext2fs_close_free(&jfs);
1364                 if (retval) {
1365                         com_err(program_name, retval,
1366                                 _("while adding filesystem to journal on %s"),
1367                                 journal_device);
1368                         goto err;
1369                 }
1370                 fputs(_("done\n"), stdout);
1371         } else if (journal_size) {
1372                 fputs(_("Creating journal inode: "), stdout);
1373                 fflush(stdout);
1374                 journal_blocks = figure_journal_size(journal_size, fs);
1375
1376                 if (journal_location_string)
1377                         journal_location =
1378                                 parse_num_blocks2(journal_location_string,
1379                                                   fs->super->s_log_block_size);
1380                 retval = ext2fs_add_journal_inode2(fs, journal_blocks,
1381                                                    journal_location,
1382                                                    journal_flags);
1383                 if (retval) {
1384                         fprintf(stderr, "\n");
1385                         com_err(program_name, retval, "%s",
1386                                 _("\n\twhile trying to create journal file"));
1387                         return retval;
1388                 } else
1389                         fputs(_("done\n"), stdout);
1390                 /*
1391                  * If the filesystem wasn't mounted, we need to force
1392                  * the block group descriptors out.
1393                  */
1394                 if ((mount_flags & EXT2_MF_MOUNTED) == 0)
1395                         fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
1396         }
1397         print_check_message(fs->super->s_max_mnt_count,
1398                             fs->super->s_checkinterval);
1399         return 0;
1400
1401 err:
1402         free(journal_device);
1403         return 1;
1404 }
1405
1406 static void handle_quota_options(ext2_filsys fs)
1407 {
1408         quota_ctx_t qctx;
1409         ext2_ino_t qf_ino;
1410         enum quota_type qtype;
1411         int enable = 0;
1412
1413         for (qtype = 0 ; qtype < MAXQUOTAS; qtype++)
1414                 if (quota_enable[qtype] != 0)
1415                         break;
1416         if (qtype == MAXQUOTAS)
1417                 /* Nothing to do. */
1418                 return;
1419
1420         quota_init_context(&qctx, fs, QUOTA_ALL_BIT);
1421         for (qtype = 0 ; qtype < MAXQUOTAS; qtype++) {
1422                 if (quota_enable[qtype] == QOPT_ENABLE) {
1423                         enable = 1;
1424                         break;
1425                 }
1426         }
1427         if (enable)
1428                 quota_compute_usage(qctx);
1429
1430         for (qtype = 0 ; qtype < MAXQUOTAS; qtype++) {
1431                 if (quota_enable[qtype] == QOPT_ENABLE &&
1432                     *quota_sb_inump(fs->super, qtype) == 0) {
1433                         if ((qf_ino = quota_file_exists(fs, qtype)) > 0)
1434                                 quota_update_limits(qctx, qf_ino, qtype);
1435                         quota_write_inode(qctx, 1 << qtype);
1436                 } else if (quota_enable[qtype] == QOPT_DISABLE) {
1437                         quota_remove_inode(fs, qtype);
1438                 }
1439         }
1440
1441         quota_release_context(&qctx);
1442
1443         if (enable) {
1444                 ext2fs_set_feature_quota(fs->super);
1445                 ext2fs_mark_super_dirty(fs);
1446         } else {
1447                 for (qtype = 0 ; qtype < MAXQUOTAS; qtype++)
1448                         if (*quota_sb_inump(fs->super, qtype) != 0)
1449                                 break;
1450                 if (qtype == MAXQUOTAS) {
1451                         fs->super->s_feature_ro_compat &=
1452                                         ~EXT4_FEATURE_RO_COMPAT_QUOTA;
1453                         ext2fs_mark_super_dirty(fs);
1454                 }
1455         }
1456
1457         return;
1458 }
1459
1460 static int option_handle_function(char *token, void *data)
1461 {
1462         if (strncmp(token, "usr", 3) == 0) {
1463                 quota_enable[USRQUOTA] = QOPT_ENABLE;
1464         } else if (strncmp(token, "^usr", 4) == 0) {
1465                 quota_enable[USRQUOTA] = QOPT_DISABLE;
1466         } else if (strncmp(token, "grp", 3) == 0) {
1467                 quota_enable[GRPQUOTA] = QOPT_ENABLE;
1468         } else if (strncmp(token, "^grp", 4) == 0) {
1469                 quota_enable[GRPQUOTA] = QOPT_DISABLE;
1470         } else {
1471                 fputs(_("\nBad quota options specified.\n\n"
1472                         "Following valid quota options are available "
1473                         "(pass by separating with comma):\n"
1474                         "\t[^]usr[quota]\n"
1475                         "\t[^]grp[quota]\n"
1476                         "\n\n"), stderr);
1477                 return 1;
1478         }
1479         return 0;
1480 }
1481
1482 static void parse_e2label_options(int argc, char ** argv)
1483 {
1484         if ((argc < 2) || (argc > 3)) {
1485                 fputs(_("Usage: e2label device [newlabel]\n"), stderr);
1486                 exit(1);
1487         }
1488         io_options = strchr(argv[1], '?');
1489         if (io_options)
1490                 *io_options++ = 0;
1491         device_name = blkid_get_devname(NULL, argv[1], NULL);
1492         if (!device_name) {
1493                 com_err("e2label", 0, _("Unable to resolve '%s'"),
1494                         argv[1]);
1495                 exit(1);
1496         }
1497         open_flag = EXT2_FLAG_JOURNAL_DEV_OK;
1498         if (argc == 3) {
1499                 open_flag |= EXT2_FLAG_RW;
1500                 L_flag = 1;
1501                 new_label = argv[2];
1502         } else
1503                 print_label++;
1504 }
1505
1506 static time_t parse_time(char *str)
1507 {
1508         struct  tm      ts;
1509
1510         if (strcmp(str, "now") == 0) {
1511                 return (time(0));
1512         }
1513         memset(&ts, 0, sizeof(ts));
1514 #ifdef HAVE_STRPTIME
1515         strptime(str, "%Y%m%d%H%M%S", &ts);
1516 #else
1517         sscanf(str, "%4d%2d%2d%2d%2d%2d", &ts.tm_year, &ts.tm_mon,
1518                &ts.tm_mday, &ts.tm_hour, &ts.tm_min, &ts.tm_sec);
1519         ts.tm_year -= 1900;
1520         ts.tm_mon -= 1;
1521         if (ts.tm_year < 0 || ts.tm_mon < 0 || ts.tm_mon > 11 ||
1522             ts.tm_mday < 0 || ts.tm_mday > 31 || ts.tm_hour > 23 ||
1523             ts.tm_min > 59 || ts.tm_sec > 61)
1524                 ts.tm_mday = 0;
1525 #endif
1526         if (ts.tm_mday == 0) {
1527                 com_err(program_name, 0,
1528                         _("Couldn't parse date/time specifier: %s"),
1529                         str);
1530                 usage();
1531         }
1532         ts.tm_isdst = -1;
1533         return (mktime(&ts));
1534 }
1535
1536 static void parse_tune2fs_options(int argc, char **argv)
1537 {
1538         int c;
1539         char *tmp;
1540         struct group *gr;
1541         struct passwd *pw;
1542         int ret;
1543         char optstring[100] = "c:e:fg:i:jlm:o:r:s:u:C:E:I:J:L:M:O:T:U:z:Q:";
1544
1545         open_flag = 0;
1546         printf("tune2fs %s (%s)\n", E2FSPROGS_VERSION, E2FSPROGS_DATE);
1547         while ((c = getopt(argc, argv, optstring)) != EOF)
1548                 switch (c) {
1549                 case 'c':
1550                         max_mount_count = strtol(optarg, &tmp, 0);
1551                         if (*tmp || max_mount_count > 16000) {
1552                                 com_err(program_name, 0,
1553                                         _("bad mounts count - %s"),
1554                                         optarg);
1555                                 usage();
1556                         }
1557                         if (max_mount_count == 0)
1558                                 max_mount_count = -1;
1559                         c_flag = 1;
1560                         open_flag = EXT2_FLAG_RW;
1561                         break;
1562                 case 'C':
1563                         mount_count = strtoul(optarg, &tmp, 0);
1564                         if (*tmp || mount_count > 16000) {
1565                                 com_err(program_name, 0,
1566                                         _("bad mounts count - %s"),
1567                                         optarg);
1568                                 usage();
1569                         }
1570                         C_flag = 1;
1571                         open_flag = EXT2_FLAG_RW;
1572                         break;
1573                 case 'e':
1574                         if (strcmp(optarg, "continue") == 0)
1575                                 errors = EXT2_ERRORS_CONTINUE;
1576                         else if (strcmp(optarg, "remount-ro") == 0)
1577                                 errors = EXT2_ERRORS_RO;
1578                         else if (strcmp(optarg, "panic") == 0)
1579                                 errors = EXT2_ERRORS_PANIC;
1580                         else {
1581                                 com_err(program_name, 0,
1582                                         _("bad error behavior - %s"),
1583                                         optarg);
1584                                 usage();
1585                         }
1586                         e_flag = 1;
1587                         open_flag = EXT2_FLAG_RW;
1588                         break;
1589                 case 'E':
1590                         extended_cmd = optarg;
1591                         open_flag |= EXT2_FLAG_RW;
1592                         break;
1593                 case 'f': /* Force */
1594                         f_flag++;
1595                         break;
1596                 case 'g':
1597                         resgid = strtoul(optarg, &tmp, 0);
1598                         if (*tmp) {
1599                                 gr = getgrnam(optarg);
1600                                 if (gr == NULL)
1601                                         tmp = optarg;
1602                                 else {
1603                                         resgid = gr->gr_gid;
1604                                         *tmp = 0;
1605                                 }
1606                         }
1607                         if (*tmp) {
1608                                 com_err(program_name, 0,
1609                                         _("bad gid/group name - %s"),
1610                                         optarg);
1611                                 usage();
1612                         }
1613                         g_flag = 1;
1614                         open_flag = EXT2_FLAG_RW;
1615                         break;
1616                 case 'i':
1617                         interval = strtoul(optarg, &tmp, 0);
1618                         switch (*tmp) {
1619                         case 's':
1620                                 tmp++;
1621                                 break;
1622                         case '\0':
1623                         case 'd':
1624                         case 'D': /* days */
1625                                 interval *= 86400;
1626                                 if (*tmp != '\0')
1627                                         tmp++;
1628                                 break;
1629                         case 'm':
1630                         case 'M': /* months! */
1631                                 interval *= 86400 * 30;
1632                                 tmp++;
1633                                 break;
1634                         case 'w':
1635                         case 'W': /* weeks */
1636                                 interval *= 86400 * 7;
1637                                 tmp++;
1638                                 break;
1639                         }
1640                         if (*tmp) {
1641                                 com_err(program_name, 0,
1642                                         _("bad interval - %s"), optarg);
1643                                 usage();
1644                         }
1645                         i_flag = 1;
1646                         open_flag = EXT2_FLAG_RW;
1647                         break;
1648                 case 'j':
1649                         if (!journal_size)
1650                                 journal_size = -1;
1651                         open_flag = EXT2_FLAG_RW;
1652                         break;
1653                 case 'J':
1654                         parse_journal_opts(optarg);
1655                         open_flag = EXT2_FLAG_RW;
1656                         break;
1657                 case 'l':
1658                         l_flag = 1;
1659                         break;
1660                 case 'L':
1661                         new_label = optarg;
1662                         L_flag = 1;
1663                         open_flag |= EXT2_FLAG_RW |
1664                                 EXT2_FLAG_JOURNAL_DEV_OK;
1665                         break;
1666                 case 'm':
1667                         reserved_ratio = strtod(optarg, &tmp);
1668                         if (*tmp || reserved_ratio > 50 ||
1669                             reserved_ratio < 0) {
1670                                 com_err(program_name, 0,
1671                                         _("bad reserved block ratio - %s"),
1672                                         optarg);
1673                                 usage();
1674                         }
1675                         m_flag = 1;
1676                         open_flag = EXT2_FLAG_RW;
1677                         break;
1678                 case 'M':
1679                         new_last_mounted = optarg;
1680                         M_flag = 1;
1681                         open_flag = EXT2_FLAG_RW;
1682                         break;
1683                 case 'o':
1684                         if (mntopts_cmd) {
1685                                 com_err(program_name, 0, "%s",
1686                                         _("-o may only be specified once"));
1687                                 usage();
1688                         }
1689                         mntopts_cmd = optarg;
1690                         open_flag = EXT2_FLAG_RW;
1691                         break;
1692                 case 'O':
1693                         if (features_cmd) {
1694                                 com_err(program_name, 0, "%s",
1695                                         _("-O may only be specified once"));
1696                                 usage();
1697                         }
1698                         features_cmd = optarg;
1699                         open_flag = EXT2_FLAG_RW;
1700                         break;
1701                 case 'Q':
1702                         Q_flag = 1;
1703                         ret = parse_quota_opts(optarg, option_handle_function,
1704                                                NULL);
1705                         if (ret)
1706                                 exit(1);
1707                         open_flag = EXT2_FLAG_RW;
1708                         break;
1709                 case 'r':
1710                         reserved_blocks = strtoul(optarg, &tmp, 0);
1711                         if (*tmp) {
1712                                 com_err(program_name, 0,
1713                                         _("bad reserved blocks count - %s"),
1714                                         optarg);
1715                                 usage();
1716                         }
1717                         r_flag = 1;
1718                         open_flag = EXT2_FLAG_RW;
1719                         break;
1720                 case 's': /* Deprecated */
1721                         s_flag = atoi(optarg);
1722                         open_flag = EXT2_FLAG_RW;
1723                         break;
1724                 case 'T':
1725                         T_flag = 1;
1726                         last_check_time = parse_time(optarg);
1727                         open_flag = EXT2_FLAG_RW;
1728                         break;
1729                 case 'u':
1730                                 resuid = strtoul(optarg, &tmp, 0);
1731                                 if (*tmp) {
1732                                         pw = getpwnam(optarg);
1733                                         if (pw == NULL)
1734                                                 tmp = optarg;
1735                                         else {
1736                                                 resuid = pw->pw_uid;
1737                                                 *tmp = 0;
1738                                         }
1739                                 }
1740                                 if (*tmp) {
1741                                         com_err(program_name, 0,
1742                                                 _("bad uid/user name - %s"),
1743                                                 optarg);
1744                                         usage();
1745                                 }
1746                                 u_flag = 1;
1747                                 open_flag = EXT2_FLAG_RW;
1748                                 break;
1749                 case 'U':
1750                         new_UUID = optarg;
1751                         U_flag = 1;
1752                         open_flag = EXT2_FLAG_RW |
1753                                 EXT2_FLAG_JOURNAL_DEV_OK;
1754                         break;
1755                 case 'I':
1756                         new_inode_size = strtoul(optarg, &tmp, 0);
1757                         if (*tmp) {
1758                                 com_err(program_name, 0,
1759                                         _("bad inode size - %s"),
1760                                         optarg);
1761                                 usage();
1762                         }
1763                         if (!((new_inode_size &
1764                                (new_inode_size - 1)) == 0)) {
1765                                 com_err(program_name, 0,
1766                                         _("Inode size must be a "
1767                                           "power of two- %s"),
1768                                         optarg);
1769                                 usage();
1770                         }
1771                         open_flag = EXT2_FLAG_RW;
1772                         I_flag = 1;
1773                         break;
1774                 case 'z':
1775                         undo_file = optarg;
1776                         break;
1777                 default:
1778                         usage();
1779                 }
1780         if (optind < argc - 1 || optind == argc)
1781                 usage();
1782         if (!open_flag && !l_flag)
1783                 usage();
1784         io_options = strchr(argv[optind], '?');
1785         if (io_options)
1786                 *io_options++ = 0;
1787         device_name = blkid_get_devname(NULL, argv[optind], NULL);
1788         if (!device_name) {
1789                 com_err(program_name, 0, _("Unable to resolve '%s'"),
1790                         argv[optind]);
1791                 exit(1);
1792         }
1793 }
1794
1795 #ifdef CONFIG_BUILD_FINDFS
1796 void do_findfs(int argc, char **argv)
1797 {
1798         char    *dev;
1799
1800         if ((argc != 2) ||
1801             (strncmp(argv[1], "LABEL=", 6) && strncmp(argv[1], "UUID=", 5))) {
1802                 fprintf(stderr, "Usage: findfs LABEL=<label>|UUID=<uuid>\n");
1803                 exit(2);
1804         }
1805         dev = blkid_get_devname(NULL, argv[1], NULL);
1806         if (!dev) {
1807                 com_err("findfs", 0, _("Unable to resolve '%s'"),
1808                         argv[1]);
1809                 exit(1);
1810         }
1811         puts(dev);
1812         exit(0);
1813 }
1814 #endif
1815
1816 static int parse_extended_opts(ext2_filsys fs, const char *opts)
1817 {
1818         char    *buf, *token, *next, *p, *arg;
1819         int     len, hash_alg;
1820         int     r_usage = 0;
1821
1822         len = strlen(opts);
1823         buf = malloc(len+1);
1824         if (!buf) {
1825                 fprintf(stderr, "%s",
1826                         _("Couldn't allocate memory to parse options!\n"));
1827                 return 1;
1828         }
1829         strcpy(buf, opts);
1830         for (token = buf; token && *token; token = next) {
1831                 p = strchr(token, ',');
1832                 next = 0;
1833                 if (p) {
1834                         *p = 0;
1835                         next = p+1;
1836                 }
1837                 arg = strchr(token, '=');
1838                 if (arg) {
1839                         *arg = 0;
1840                         arg++;
1841                 }
1842                 if (strcmp(token, "clear-mmp") == 0 ||
1843                     strcmp(token, "clear_mmp") == 0) {
1844                         clear_mmp = 1;
1845                 } else if (strcmp(token, "mmp_update_interval") == 0) {
1846                         unsigned long intv;
1847                         if (!arg) {
1848                                 r_usage++;
1849                                 continue;
1850                         }
1851                         intv = strtoul(arg, &p, 0);
1852                         if (*p) {
1853                                 fprintf(stderr,
1854                                         _("Invalid mmp_update_interval: %s\n"),
1855                                         arg);
1856                                 r_usage++;
1857                                 continue;
1858                         }
1859                         if (intv == 0) {
1860                                 intv = EXT4_MMP_UPDATE_INTERVAL;
1861                         } else if (intv > EXT4_MMP_MAX_UPDATE_INTERVAL) {
1862                                 fprintf(stderr,
1863                                         _("mmp_update_interval too big: %lu\n"),
1864                                         intv);
1865                                 r_usage++;
1866                                 continue;
1867                         }
1868                         printf(P_("Setting multiple mount protection update "
1869                                   "interval to %lu second\n",
1870                                   "Setting multiple mount protection update "
1871                                   "interval to %lu seconds\n", intv),
1872                                intv);
1873                         fs->super->s_mmp_update_interval = intv;
1874                         ext2fs_mark_super_dirty(fs);
1875                 } else if (!strcmp(token, "test_fs")) {
1876                         fs->super->s_flags |= EXT2_FLAGS_TEST_FILESYS;
1877                         printf("Setting test filesystem flag\n");
1878                         ext2fs_mark_super_dirty(fs);
1879                 } else if (!strcmp(token, "^test_fs")) {
1880                         fs->super->s_flags &= ~EXT2_FLAGS_TEST_FILESYS;
1881                         printf("Clearing test filesystem flag\n");
1882                         ext2fs_mark_super_dirty(fs);
1883                 } else if (strcmp(token, "stride") == 0) {
1884                         if (!arg) {
1885                                 r_usage++;
1886                                 continue;
1887                         }
1888                         stride = strtoul(arg, &p, 0);
1889                         if (*p) {
1890                                 fprintf(stderr,
1891                                         _("Invalid RAID stride: %s\n"),
1892                                         arg);
1893                                 r_usage++;
1894                                 continue;
1895                         }
1896                         stride_set = 1;
1897                 } else if (strcmp(token, "stripe-width") == 0 ||
1898                            strcmp(token, "stripe_width") == 0) {
1899                         if (!arg) {
1900                                 r_usage++;
1901                                 continue;
1902                         }
1903                         stripe_width = strtoul(arg, &p, 0);
1904                         if (*p) {
1905                                 fprintf(stderr,
1906                                         _("Invalid RAID stripe-width: %s\n"),
1907                                         arg);
1908                                 r_usage++;
1909                                 continue;
1910                         }
1911                         stripe_width_set = 1;
1912                 } else if (strcmp(token, "hash_alg") == 0 ||
1913                            strcmp(token, "hash-alg") == 0) {
1914                         if (!arg) {
1915                                 r_usage++;
1916                                 continue;
1917                         }
1918                         hash_alg = e2p_string2hash(arg);
1919                         if (hash_alg < 0) {
1920                                 fprintf(stderr,
1921                                         _("Invalid hash algorithm: %s\n"),
1922                                         arg);
1923                                 r_usage++;
1924                                 continue;
1925                         }
1926                         fs->super->s_def_hash_version = hash_alg;
1927                         printf(_("Setting default hash algorithm "
1928                                  "to %s (%d)\n"),
1929                                arg, hash_alg);
1930                         ext2fs_mark_super_dirty(fs);
1931                 } else if (!strcmp(token, "mount_opts")) {
1932                         if (!arg) {
1933                                 r_usage++;
1934                                 continue;
1935                         }
1936                         if (strlen(arg) >= sizeof(fs->super->s_mount_opts)) {
1937                                 fprintf(stderr,
1938                                         "Extended mount options too long\n");
1939                                 continue;
1940                         }
1941                         ext_mount_opts = strdup(arg);
1942                 } else
1943                         r_usage++;
1944         }
1945         if (r_usage) {
1946                 fprintf(stderr, "%s", _("\nBad options specified.\n\n"
1947                         "Extended options are separated by commas, "
1948                         "and may take an argument which\n"
1949                         "\tis set off by an equals ('=') sign.\n\n"
1950                         "Valid extended options are:\n"
1951                         "\tclear_mmp\n"
1952                         "\thash_alg=<hash algorithm>\n"
1953                         "\tmount_opts=<extended default mount options>\n"
1954                         "\tstride=<RAID per-disk chunk size in blocks>\n"
1955                         "\tstripe_width=<RAID stride*data disks in blocks>\n"
1956                         "\ttest_fs\n"
1957                         "\t^test_fs\n"));
1958                 free(buf);
1959                 return 1;
1960         }
1961         free(buf);
1962
1963         return 0;
1964 }
1965
1966 /*
1967  * Fill in the block bitmap bmap with the information regarding the
1968  * blocks to be moved
1969  */
1970 static int get_move_bitmaps(ext2_filsys fs, int new_ino_blks_per_grp,
1971                             ext2fs_block_bitmap bmap)
1972 {
1973         dgrp_t i;
1974         int retval;
1975         ext2_badblocks_list bb_list = 0;
1976         blk64_t j, needed_blocks = 0;
1977         blk64_t start_blk, end_blk;
1978
1979         retval = ext2fs_read_bb_inode(fs, &bb_list);
1980         if (retval)
1981                 return retval;
1982
1983         for (i = 0; i < fs->group_desc_count; i++) {
1984                 start_blk = ext2fs_inode_table_loc(fs, i) +
1985                                         fs->inode_blocks_per_group;
1986
1987                 end_blk = ext2fs_inode_table_loc(fs, i) +
1988                                         new_ino_blks_per_grp;
1989
1990                 for (j = start_blk; j < end_blk; j++) {
1991                         if (ext2fs_test_block_bitmap2(fs->block_map, j)) {
1992                                 /*
1993                                  * IF the block is a bad block we fail
1994                                  */
1995                                 if (ext2fs_badblocks_list_test(bb_list, j)) {
1996                                         ext2fs_badblocks_list_free(bb_list);
1997                                         return ENOSPC;
1998                                 }
1999
2000                                 ext2fs_mark_block_bitmap2(bmap, j);
2001                         } else {
2002                                 /*
2003                                  * We are going to use this block for
2004                                  * inode table. So mark them used.
2005                                  */
2006                                 ext2fs_mark_block_bitmap2(fs->block_map, j);
2007                         }
2008                 }
2009                 needed_blocks += end_blk - start_blk;
2010         }
2011
2012         ext2fs_badblocks_list_free(bb_list);
2013         if (needed_blocks > ext2fs_free_blocks_count(fs->super))
2014                 return ENOSPC;
2015
2016         return 0;
2017 }
2018
2019 static int ext2fs_is_meta_block(ext2_filsys fs, blk64_t blk)
2020 {
2021         dgrp_t group;
2022         group = ext2fs_group_of_blk2(fs, blk);
2023         if (ext2fs_block_bitmap_loc(fs, group) == blk)
2024                 return 1;
2025         if (ext2fs_inode_bitmap_loc(fs, group) == blk)
2026                 return 1;
2027         return 0;
2028 }
2029
2030 static int ext2fs_is_block_in_group(ext2_filsys fs, dgrp_t group, blk64_t blk)
2031 {
2032         blk64_t start_blk, end_blk;
2033         start_blk = fs->super->s_first_data_block +
2034                         EXT2_GROUPS_TO_BLOCKS(fs->super, group);
2035         /*
2036          * We cannot get new block beyond end_blk for for the last block group
2037          * so we can check with EXT2_BLOCKS_PER_GROUP even for last block group
2038          */
2039         end_blk   = start_blk + EXT2_BLOCKS_PER_GROUP(fs->super);
2040         if (blk >= start_blk && blk <= end_blk)
2041                 return 1;
2042         return 0;
2043 }
2044
2045 static int move_block(ext2_filsys fs, ext2fs_block_bitmap bmap)
2046 {
2047
2048         char *buf;
2049         dgrp_t group = 0;
2050         errcode_t retval;
2051         int meta_data = 0;
2052         blk64_t blk, new_blk, goal;
2053         struct blk_move *bmv;
2054
2055         retval = ext2fs_get_mem(fs->blocksize, &buf);
2056         if (retval)
2057                 return retval;
2058
2059         for (new_blk = blk = fs->super->s_first_data_block;
2060              blk < ext2fs_blocks_count(fs->super); blk++) {
2061                 if (!ext2fs_test_block_bitmap2(bmap, blk))
2062                         continue;
2063
2064                 if (ext2fs_is_meta_block(fs, blk)) {
2065                         /*
2066                          * If the block is mapping a fs meta data block
2067                          * like group desc/block bitmap/inode bitmap. We
2068                          * should find a block in the same group and fix
2069                          * the respective fs metadata pointers. Otherwise
2070                          * fail
2071                          */
2072                         group = ext2fs_group_of_blk2(fs, blk);
2073                         goal = ext2fs_group_first_block2(fs, group);
2074                         meta_data = 1;
2075
2076                 } else {
2077                         goal = new_blk;
2078                 }
2079                 retval = ext2fs_new_block2(fs, goal, NULL, &new_blk);
2080                 if (retval)
2081                         goto err_out;
2082
2083                 /* new fs meta data block should be in the same group */
2084                 if (meta_data && !ext2fs_is_block_in_group(fs, group, new_blk)) {
2085                         retval = ENOSPC;
2086                         goto err_out;
2087                 }
2088
2089                 /* Mark this block as allocated */
2090                 ext2fs_mark_block_bitmap2(fs->block_map, new_blk);
2091
2092                 /* Add it to block move list */
2093                 retval = ext2fs_get_mem(sizeof(struct blk_move), &bmv);
2094                 if (retval)
2095                         goto err_out;
2096
2097                 bmv->old_loc = blk;
2098                 bmv->new_loc = new_blk;
2099
2100                 list_add(&(bmv->list), &blk_move_list);
2101
2102                 retval = io_channel_read_blk64(fs->io, blk, 1, buf);
2103                 if (retval)
2104                         goto err_out;
2105
2106                 retval = io_channel_write_blk64(fs->io, new_blk, 1, buf);
2107                 if (retval)
2108                         goto err_out;
2109         }
2110
2111 err_out:
2112         ext2fs_free_mem(&buf);
2113         return retval;
2114 }
2115
2116 static blk64_t translate_block(blk64_t blk)
2117 {
2118         struct list_head *entry;
2119         struct blk_move *bmv;
2120
2121         list_for_each(entry, &blk_move_list) {
2122                 bmv = list_entry(entry, struct blk_move, list);
2123                 if (bmv->old_loc == blk)
2124                         return bmv->new_loc;
2125         }
2126
2127         return 0;
2128 }
2129
2130 static int process_block(ext2_filsys fs EXT2FS_ATTR((unused)),
2131                          blk64_t *block_nr,
2132                          e2_blkcnt_t blockcnt EXT2FS_ATTR((unused)),
2133                          blk64_t ref_block EXT2FS_ATTR((unused)),
2134                          int ref_offset EXT2FS_ATTR((unused)),
2135                          void *priv_data)
2136 {
2137         int ret = 0;
2138         blk64_t new_blk;
2139         ext2fs_block_bitmap bmap = (ext2fs_block_bitmap) priv_data;
2140
2141         if (!ext2fs_test_block_bitmap2(bmap, *block_nr))
2142                 return 0;
2143         new_blk = translate_block(*block_nr);
2144         if (new_blk) {
2145                 *block_nr = new_blk;
2146                 /*
2147                  * This will force the ext2fs_write_inode in the iterator
2148                  */
2149                 ret |= BLOCK_CHANGED;
2150         }
2151
2152         return ret;
2153 }
2154
2155 static int inode_scan_and_fix(ext2_filsys fs, ext2fs_block_bitmap bmap)
2156 {
2157         errcode_t retval = 0;
2158         ext2_ino_t ino;
2159         blk64_t blk;
2160         char *block_buf = 0;
2161         struct ext2_inode inode;
2162         ext2_inode_scan scan = NULL;
2163
2164         retval = ext2fs_get_mem(fs->blocksize * 3, &block_buf);
2165         if (retval)
2166                 return retval;
2167
2168         retval = ext2fs_open_inode_scan(fs, 0, &scan);
2169         if (retval)
2170                 goto err_out;
2171
2172         while (1) {
2173                 retval = ext2fs_get_next_inode(scan, &ino, &inode);
2174                 if (retval)
2175                         goto err_out;
2176
2177                 if (!ino)
2178                         break;
2179
2180                 if (inode.i_links_count == 0)
2181                         continue; /* inode not in use */
2182
2183                 /* FIXME!!
2184                  * If we end up modifying the journal inode
2185                  * the sb->s_jnl_blocks will differ. But a
2186                  * subsequent e2fsck fixes that.
2187                  * Do we need to fix this ??
2188                  */
2189
2190                 if (ext2fs_file_acl_block(fs, &inode) &&
2191                     ext2fs_test_block_bitmap2(bmap,
2192                                         ext2fs_file_acl_block(fs, &inode))) {
2193                         blk = translate_block(ext2fs_file_acl_block(fs,
2194                                                                     &inode));
2195                         if (!blk)
2196                                 continue;
2197
2198                         ext2fs_file_acl_block_set(fs, &inode, blk);
2199
2200                         /*
2201                          * Write the inode to disk so that inode table
2202                          * resizing can work
2203                          */
2204                         retval = ext2fs_write_inode(fs, ino, &inode);
2205                         if (retval)
2206                                 goto err_out;
2207                 }
2208
2209                 if (!ext2fs_inode_has_valid_blocks2(fs, &inode))
2210                         continue;
2211
2212                 retval = ext2fs_block_iterate3(fs, ino, 0, block_buf,
2213                                                process_block, bmap);
2214                 if (retval)
2215                         goto err_out;
2216
2217         }
2218
2219 err_out:
2220         ext2fs_free_mem(&block_buf);
2221         ext2fs_close_inode_scan(scan);
2222
2223         return retval;
2224 }
2225
2226 /*
2227  * We need to scan for inode and block bitmaps that may need to be
2228  * moved.  This can take place if the filesystem was formatted for
2229  * RAID arrays using the mke2fs's extended option "stride".
2230  */
2231 static int group_desc_scan_and_fix(ext2_filsys fs, ext2fs_block_bitmap bmap)
2232 {
2233         dgrp_t i;
2234         blk64_t blk, new_blk;
2235
2236         for (i = 0; i < fs->group_desc_count; i++) {
2237                 blk = ext2fs_block_bitmap_loc(fs, i);
2238                 if (ext2fs_test_block_bitmap2(bmap, blk)) {
2239                         new_blk = translate_block(blk);
2240                         if (!new_blk)
2241                                 continue;
2242                         ext2fs_block_bitmap_loc_set(fs, i, new_blk);
2243                 }
2244
2245                 blk = ext2fs_inode_bitmap_loc(fs, i);
2246                 if (ext2fs_test_block_bitmap2(bmap, blk)) {
2247                         new_blk = translate_block(blk);
2248                         if (!new_blk)
2249                                 continue;
2250                         ext2fs_inode_bitmap_loc_set(fs, i, new_blk);
2251                 }
2252         }
2253         return 0;
2254 }
2255
2256 static int expand_inode_table(ext2_filsys fs, unsigned long new_ino_size)
2257 {
2258         dgrp_t i;
2259         blk64_t blk;
2260         errcode_t retval;
2261         int new_ino_blks_per_grp;
2262         unsigned int j;
2263         char *old_itable = NULL, *new_itable = NULL;
2264         char *tmp_old_itable = NULL, *tmp_new_itable = NULL;
2265         unsigned long old_ino_size;
2266         int old_itable_size, new_itable_size;
2267
2268         old_itable_size = fs->inode_blocks_per_group * fs->blocksize;
2269         old_ino_size = EXT2_INODE_SIZE(fs->super);
2270
2271         new_ino_blks_per_grp = ext2fs_div_ceil(
2272                                         EXT2_INODES_PER_GROUP(fs->super) *
2273                                         new_ino_size,
2274                                         fs->blocksize);
2275
2276         new_itable_size = new_ino_blks_per_grp * fs->blocksize;
2277
2278         retval = ext2fs_get_mem(old_itable_size, &old_itable);
2279         if (retval)
2280                 return retval;
2281
2282         retval = ext2fs_get_mem(new_itable_size, &new_itable);
2283         if (retval)
2284                 goto err_out;
2285
2286         tmp_old_itable = old_itable;
2287         tmp_new_itable = new_itable;
2288
2289         for (i = 0; i < fs->group_desc_count; i++) {
2290                 blk = ext2fs_inode_table_loc(fs, i);
2291                 retval = io_channel_read_blk64(fs->io, blk,
2292                                 fs->inode_blocks_per_group, old_itable);
2293                 if (retval)
2294                         goto err_out;
2295
2296                 for (j = 0; j < EXT2_INODES_PER_GROUP(fs->super); j++) {
2297                         memcpy(new_itable, old_itable, old_ino_size);
2298
2299                         memset(new_itable+old_ino_size, 0,
2300                                         new_ino_size - old_ino_size);
2301
2302                         new_itable += new_ino_size;
2303                         old_itable += old_ino_size;
2304                 }
2305
2306                 /* reset the pointer */
2307                 old_itable = tmp_old_itable;
2308                 new_itable = tmp_new_itable;
2309
2310                 retval = io_channel_write_blk64(fs->io, blk,
2311                                         new_ino_blks_per_grp, new_itable);
2312                 if (retval)
2313                         goto err_out;
2314         }
2315
2316         /* Update the meta data */
2317         fs->inode_blocks_per_group = new_ino_blks_per_grp;
2318         ext2fs_free_inode_cache(fs->icache);
2319         fs->icache = 0;
2320         fs->super->s_inode_size = new_ino_size;
2321
2322 err_out:
2323         if (old_itable)
2324                 ext2fs_free_mem(&old_itable);
2325
2326         if (new_itable)
2327                 ext2fs_free_mem(&new_itable);
2328
2329         return retval;
2330 }
2331
2332 static errcode_t ext2fs_calculate_summary_stats(ext2_filsys fs)
2333 {
2334         blk64_t         blk;
2335         ext2_ino_t      ino;
2336         unsigned int    group = 0;
2337         unsigned int    count = 0;
2338         int             total_free = 0;
2339         int             group_free = 0;
2340
2341         /*
2342          * First calculate the block statistics
2343          */
2344         for (blk = fs->super->s_first_data_block;
2345              blk < ext2fs_blocks_count(fs->super); blk++) {
2346                 if (!ext2fs_fast_test_block_bitmap2(fs->block_map, blk)) {
2347                         group_free++;
2348                         total_free++;
2349                 }
2350                 count++;
2351                 if ((count == fs->super->s_blocks_per_group) ||
2352                     (blk == ext2fs_blocks_count(fs->super)-1)) {
2353                         ext2fs_bg_free_blocks_count_set(fs, group++,
2354                                                         group_free);
2355                         count = 0;
2356                         group_free = 0;
2357                 }
2358         }
2359         total_free = EXT2FS_C2B(fs, total_free);
2360         ext2fs_free_blocks_count_set(fs->super, total_free);
2361
2362         /*
2363          * Next, calculate the inode statistics
2364          */
2365         group_free = 0;
2366         total_free = 0;
2367         count = 0;
2368         group = 0;
2369
2370         /* Protect loop from wrap-around if s_inodes_count maxed */
2371         for (ino = 1; ino <= fs->super->s_inodes_count && ino > 0; ino++) {
2372                 if (!ext2fs_fast_test_inode_bitmap2(fs->inode_map, ino)) {
2373                         group_free++;
2374                         total_free++;
2375                 }
2376                 count++;
2377                 if ((count == fs->super->s_inodes_per_group) ||
2378                     (ino == fs->super->s_inodes_count)) {
2379                         ext2fs_bg_free_inodes_count_set(fs, group++,
2380                                                         group_free);
2381                         count = 0;
2382                         group_free = 0;
2383                 }
2384         }
2385         fs->super->s_free_inodes_count = total_free;
2386         ext2fs_mark_super_dirty(fs);
2387         return 0;
2388 }
2389
2390 #define list_for_each_safe(pos, pnext, head) \
2391         for (pos = (head)->next, pnext = pos->next; pos != (head); \
2392              pos = pnext, pnext = pos->next)
2393
2394 static void free_blk_move_list(void)
2395 {
2396         struct list_head *entry, *tmp;
2397         struct blk_move *bmv;
2398
2399         list_for_each_safe(entry, tmp, &blk_move_list) {
2400                 bmv = list_entry(entry, struct blk_move, list);
2401                 list_del(entry);
2402                 ext2fs_free_mem(&bmv);
2403         }
2404         return;
2405 }
2406
2407 static int resize_inode(ext2_filsys fs, unsigned long new_size)
2408 {
2409         errcode_t retval;
2410         int new_ino_blks_per_grp;
2411         ext2fs_block_bitmap bmap;
2412
2413         retval = ext2fs_read_inode_bitmap(fs);
2414         if (retval) {
2415                 fputs(_("Failed to read inode bitmap\n"), stderr);
2416                 return retval;
2417         }
2418         retval = ext2fs_read_block_bitmap(fs);
2419         if (retval) {
2420                 fputs(_("Failed to read block bitmap\n"), stderr);
2421                 return retval;
2422         }
2423         INIT_LIST_HEAD(&blk_move_list);
2424
2425
2426         new_ino_blks_per_grp = ext2fs_div_ceil(
2427                                         EXT2_INODES_PER_GROUP(fs->super)*
2428                                         new_size,
2429                                         fs->blocksize);
2430
2431         /* We may change the file system.
2432          * Mark the file system as invalid so that
2433          * the user is prompted to run fsck.
2434          */
2435         fs->super->s_state &= ~EXT2_VALID_FS;
2436
2437         retval = ext2fs_allocate_block_bitmap(fs, _("blocks to be moved"),
2438                                                 &bmap);
2439         if (retval) {
2440                 fputs(_("Failed to allocate block bitmap when "
2441                                 "increasing inode size\n"), stderr);
2442                 return retval;
2443         }
2444         retval = get_move_bitmaps(fs, new_ino_blks_per_grp, bmap);
2445         if (retval) {
2446                 fputs(_("Not enough space to increase inode size \n"), stderr);
2447                 goto err_out;
2448         }
2449         retval = move_block(fs, bmap);
2450         if (retval) {
2451                 fputs(_("Failed to relocate blocks during inode resize \n"),
2452                       stderr);
2453                 goto err_out;
2454         }
2455         retval = inode_scan_and_fix(fs, bmap);
2456         if (retval)
2457                 goto err_out_undo;
2458
2459         retval = group_desc_scan_and_fix(fs, bmap);
2460         if (retval)
2461                 goto err_out_undo;
2462
2463         retval = expand_inode_table(fs, new_size);
2464         if (retval)
2465                 goto err_out_undo;
2466
2467         ext2fs_calculate_summary_stats(fs);
2468
2469         fs->super->s_state |= EXT2_VALID_FS;
2470         /* mark super block and block bitmap as dirty */
2471         ext2fs_mark_super_dirty(fs);
2472         ext2fs_mark_bb_dirty(fs);
2473
2474 err_out:
2475         free_blk_move_list();
2476         ext2fs_free_block_bitmap(bmap);
2477
2478         return retval;
2479
2480 err_out_undo:
2481         free_blk_move_list();
2482         ext2fs_free_block_bitmap(bmap);
2483         fputs(_("Error in resizing the inode size.\n"
2484                         "Run e2undo to undo the "
2485                         "file system changes. \n"), stderr);
2486
2487         return retval;
2488 }
2489
2490 static int tune2fs_setup_tdb(const char *name, io_manager *io_ptr)
2491 {
2492         errcode_t retval = 0;
2493         const char *tdb_dir;
2494         char *tdb_file = NULL;
2495         char *dev_name, *tmp_name;
2496
2497         /* (re)open a specific undo file */
2498         if (undo_file && undo_file[0] != 0) {
2499                 retval = set_undo_io_backing_manager(*io_ptr);
2500                 if (retval)
2501                         goto err;
2502                 *io_ptr = undo_io_manager;
2503                 retval = set_undo_io_backup_file(undo_file);
2504                 if (retval)
2505                         goto err;
2506                 printf(_("Overwriting existing filesystem; this can be undone "
2507                          "using the command:\n"
2508                          "    e2undo %s %s\n\n"),
2509                          undo_file, name);
2510                 return retval;
2511         }
2512
2513         /*
2514          * Configuration via a conf file would be
2515          * nice
2516          */
2517         tdb_dir = getenv("E2FSPROGS_UNDO_DIR");
2518         if (!tdb_dir)
2519                 tdb_dir = "/var/lib/e2fsprogs";
2520
2521         if (!strcmp(tdb_dir, "none") || (tdb_dir[0] == 0) ||
2522             access(tdb_dir, W_OK))
2523                 return 0;
2524
2525         tmp_name = strdup(name);
2526         if (!tmp_name)
2527                 goto errout;
2528         dev_name = basename(tmp_name);
2529         tdb_file = malloc(strlen(tdb_dir) + 9 + strlen(dev_name) + 7 + 1);
2530         if (!tdb_file) {
2531                 free(tmp_name);
2532                 goto errout;
2533         }
2534         sprintf(tdb_file, "%s/tune2fs-%s.e2undo", tdb_dir, dev_name);
2535         free(tmp_name);
2536
2537         if ((unlink(tdb_file) < 0) && (errno != ENOENT)) {
2538                 retval = errno;
2539                 com_err(program_name, retval,
2540                         _("while trying to delete %s"), tdb_file);
2541                 goto errout;
2542         }
2543
2544         retval = set_undo_io_backing_manager(*io_ptr);
2545         if (retval)
2546                 goto errout;
2547         *io_ptr = undo_io_manager;
2548         retval = set_undo_io_backup_file(tdb_file);
2549         if (retval)
2550                 goto errout;
2551         printf(_("Overwriting existing filesystem; this can be undone "
2552                  "using the command:\n"
2553                  "    e2undo %s %s\n\n"),
2554                  tdb_file, name);
2555
2556         free(tdb_file);
2557         return 0;
2558 errout:
2559         free(tdb_file);
2560 err:
2561         com_err("tune2fs", retval, "while trying to setup undo file\n");
2562         return retval;
2563 }
2564
2565 static int
2566 fs_update_journal_user(struct ext2_super_block *sb, __u8 old_uuid[UUID_SIZE])
2567 {
2568         int retval, nr_users, start;
2569         journal_superblock_t *jsb;
2570         ext2_filsys jfs;
2571         __u8 *j_uuid;
2572         char *journal_path;
2573         char uuid[UUID_STR_SIZE];
2574         char buf[SUPERBLOCK_SIZE] __attribute__ ((aligned(8)));
2575
2576         if (!ext2fs_has_feature_journal(sb) || uuid_is_null(sb->s_journal_uuid))
2577                 return 0;
2578
2579         uuid_unparse(sb->s_journal_uuid, uuid);
2580         journal_path = blkid_get_devname(NULL, "UUID", uuid);
2581         if (!journal_path)
2582                 return 0;
2583
2584         retval = ext2fs_open2(journal_path, io_options,
2585                               EXT2_FLAG_JOURNAL_DEV_OK | EXT2_FLAG_RW,
2586                               0, 0, unix_io_manager, &jfs);
2587         if (retval) {
2588                 com_err(program_name, retval,
2589                         _("while trying to open %s"),
2590                         journal_path);
2591                 return retval;
2592         }
2593
2594         retval = get_journal_sb(jfs, buf);
2595         if (retval != 0) {
2596                 if (retval == EXT2_ET_UNSUPP_FEATURE)
2597                         fprintf(stderr, _("%s is not a journal device.\n"),
2598                                 journal_path);
2599                 return retval;
2600         }
2601
2602         jsb = (journal_superblock_t *) buf;
2603         /* Find the filesystem UUID */
2604         nr_users = ntohl(jsb->s_nr_users);
2605
2606         j_uuid = journal_user(old_uuid, jsb->s_users, nr_users);
2607         if (j_uuid == NULL) {
2608                 fputs(_("Filesystem's UUID not found on journal device.\n"),
2609                       stderr);
2610                 return EXT2_ET_LOAD_EXT_JOURNAL;
2611         }
2612
2613         memcpy(j_uuid, sb->s_uuid, UUID_SIZE);
2614
2615         start = ext2fs_journal_sb_start(jfs->blocksize);
2616         /* Write back the journal superblock */
2617         retval = io_channel_write_blk64(jfs->io, start, -SUPERBLOCK_SIZE, buf);
2618         if (retval != 0) {
2619                 com_err(program_name, retval,
2620                         "while writing journal superblock.");
2621                 return retval;
2622         }
2623
2624         ext2fs_close(jfs);
2625
2626         return 0;
2627 }
2628
2629 #ifndef BUILD_AS_LIB
2630 int main(int argc, char **argv)
2631 #else
2632 int tune2fs_main(int argc, char **argv)
2633 #endif  /* BUILD_AS_LIB */
2634 {
2635         errcode_t retval;
2636         ext2_filsys fs;
2637         struct ext2_super_block *sb;
2638         io_manager io_ptr, io_ptr_orig = NULL;
2639         int rc = 0;
2640         char default_undo_file[1] = { 0 };
2641
2642 #ifdef ENABLE_NLS
2643         setlocale(LC_MESSAGES, "");
2644         setlocale(LC_CTYPE, "");
2645         bindtextdomain(NLS_CAT_NAME, LOCALEDIR);
2646         textdomain(NLS_CAT_NAME);
2647         set_com_err_gettext(gettext);
2648 #endif
2649         if (argc && *argv)
2650                 program_name = *argv;
2651         add_error_table(&et_ext2_error_table);
2652
2653 #ifdef CONFIG_BUILD_FINDFS
2654         if (strcmp(get_progname(argv[0]), "findfs") == 0)
2655                 do_findfs(argc, argv);
2656 #endif
2657         if (strcmp(get_progname(argv[0]), "e2label") == 0)
2658                 parse_e2label_options(argc, argv);
2659         else
2660                 parse_tune2fs_options(argc, argv);
2661
2662 #ifdef CONFIG_TESTIO_DEBUG
2663         if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_DEBUG")) {
2664                 io_ptr = test_io_manager;
2665                 test_io_backing_manager = unix_io_manager;
2666         } else
2667 #endif
2668                 io_ptr = unix_io_manager;
2669
2670 retry_open:
2671         if ((open_flag & EXT2_FLAG_RW) == 0 || f_flag)
2672                 open_flag |= EXT2_FLAG_SKIP_MMP;
2673
2674         open_flag |= EXT2_FLAG_64BITS | EXT2_FLAG_JOURNAL_DEV_OK;
2675
2676         /* keep the filesystem struct around to dump MMP data */
2677         open_flag |= EXT2_FLAG_NOFREE_ON_ERROR;
2678
2679         retval = ext2fs_open2(device_name, io_options, open_flag,
2680                               0, 0, io_ptr, &fs);
2681         if (retval) {
2682                 com_err(program_name, retval,
2683                         _("while trying to open %s"),
2684                         device_name);
2685                 if (retval == EXT2_ET_MMP_FSCK_ON ||
2686                     retval == EXT2_ET_MMP_UNKNOWN_SEQ)
2687                         dump_mmp_msg(fs->mmp_buf,
2688                                      _("If you are sure the filesystem "
2689                                        "is not in use on any node, run:\n"
2690                                        "'tune2fs -f -E clear_mmp {device}'\n"));
2691                 else if (retval == EXT2_ET_MMP_FAILED)
2692                         dump_mmp_msg(fs->mmp_buf, NULL);
2693                 else if (retval == EXT2_ET_MMP_MAGIC_INVALID)
2694                         fprintf(stderr,
2695                                 _("MMP block magic is bad. Try to fix it by "
2696                                   "running:\n'e2fsck -f %s'\n"), device_name);
2697                 else if (retval == EXT2_ET_BAD_MAGIC)
2698                         check_plausibility(device_name, CHECK_FS_EXIST, NULL);
2699                 else if (retval != EXT2_ET_MMP_FAILED)
2700                         fprintf(stderr, "%s",
2701                              _("Couldn't find valid filesystem superblock.\n"));
2702
2703                 ext2fs_free(fs);
2704                 exit(1);
2705         }
2706         if (ext2fs_has_feature_journal_dev(fs->super)) {
2707                 fprintf(stderr, "%s", _("Cannot modify a journal device.\n"));
2708                 ext2fs_free(fs);
2709                 exit(1);
2710         }
2711         fs->default_bitmap_type = EXT2FS_BMAP64_RBTREE;
2712
2713         if (I_flag) {
2714                 /*
2715                  * Check the inode size is right so we can issue an
2716                  * error message and bail before setting up the tdb
2717                  * file.
2718                  */
2719                 if (new_inode_size == EXT2_INODE_SIZE(fs->super)) {
2720                         fprintf(stderr, _("The inode size is already %lu\n"),
2721                                 new_inode_size);
2722                         rc = 1;
2723                         goto closefs;
2724                 }
2725                 if (new_inode_size < EXT2_INODE_SIZE(fs->super)) {
2726                         fprintf(stderr, "%s",
2727                                 _("Shrinking inode size is not supported\n"));
2728                         rc = 1;
2729                         goto closefs;
2730                 }
2731                 if (new_inode_size > fs->blocksize) {
2732                         fprintf(stderr, _("Invalid inode size %lu (max %d)\n"),
2733                                 new_inode_size, fs->blocksize);
2734                         rc = 1;
2735                         goto closefs;
2736                 }
2737                 /*
2738                  * If inode resize is requested use the
2739                  * Undo I/O manager
2740                  */
2741                 undo_file = default_undo_file;
2742         }
2743
2744         /* Set up an undo file */
2745         if (undo_file && io_ptr_orig == NULL) {
2746                 io_ptr_orig = io_ptr;
2747                 retval = tune2fs_setup_tdb(device_name, &io_ptr);
2748                 if (retval) {
2749                         rc = 1;
2750                         goto closefs;
2751                 }
2752                 if (io_ptr != io_ptr_orig) {
2753                         ext2fs_close_free(&fs);
2754                         goto retry_open;
2755                 }
2756         }
2757
2758         sb = fs->super;
2759         fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
2760
2761         if (print_label) {
2762                 /* For e2label emulation */
2763                 printf("%.*s\n", (int) sizeof(sb->s_volume_name),
2764                        sb->s_volume_name);
2765                 remove_error_table(&et_ext2_error_table);
2766                 goto closefs;
2767         }
2768
2769         retval = ext2fs_check_if_mounted(device_name, &mount_flags);
2770         if (retval) {
2771                 com_err("ext2fs_check_if_mount", retval,
2772                         _("while determining whether %s is mounted."),
2773                         device_name);
2774                 rc = 1;
2775                 goto closefs;
2776         }
2777         /* Normally we only need to write out the superblock */
2778         fs->flags |= EXT2_FLAG_SUPER_ONLY;
2779
2780         if (c_flag) {
2781                 sb->s_max_mnt_count = max_mount_count;
2782                 ext2fs_mark_super_dirty(fs);
2783                 printf(_("Setting maximal mount count to %d\n"),
2784                        max_mount_count);
2785         }
2786         if (C_flag) {
2787                 sb->s_mnt_count = mount_count;
2788                 ext2fs_mark_super_dirty(fs);
2789                 printf(_("Setting current mount count to %d\n"), mount_count);
2790         }
2791         if (e_flag) {
2792                 sb->s_errors = errors;
2793                 ext2fs_mark_super_dirty(fs);
2794                 printf(_("Setting error behavior to %d\n"), errors);
2795         }
2796         if (g_flag) {
2797                 sb->s_def_resgid = resgid;
2798                 ext2fs_mark_super_dirty(fs);
2799                 printf(_("Setting reserved blocks gid to %lu\n"), resgid);
2800         }
2801         if (i_flag) {
2802                 if ((unsigned long long)interval >= (1ULL << 32)) {
2803                         com_err(program_name, 0,
2804                                 _("interval between checks is too big (%lu)"),
2805                                 interval);
2806                         rc = 1;
2807                         goto closefs;
2808                 }
2809                 sb->s_checkinterval = interval;
2810                 ext2fs_mark_super_dirty(fs);
2811                 printf(_("Setting interval between checks to %lu seconds\n"),
2812                        interval);
2813         }
2814         if (m_flag) {
2815                 ext2fs_r_blocks_count_set(sb, reserved_ratio *
2816                                           ext2fs_blocks_count(sb) / 100.0);
2817                 ext2fs_mark_super_dirty(fs);
2818                 printf (_("Setting reserved blocks percentage to %g%% (%llu blocks)\n"),
2819                         reserved_ratio, ext2fs_r_blocks_count(sb));
2820         }
2821         if (r_flag) {
2822                 if (reserved_blocks > ext2fs_blocks_count(sb)/2) {
2823                         com_err(program_name, 0,
2824                                 _("reserved blocks count is too big (%llu)"),
2825                                 reserved_blocks);
2826                         rc = 1;
2827                         goto closefs;
2828                 }
2829                 ext2fs_r_blocks_count_set(sb, reserved_blocks);
2830                 ext2fs_mark_super_dirty(fs);
2831                 printf(_("Setting reserved blocks count to %llu\n"),
2832                        reserved_blocks);
2833         }
2834         if (s_flag == 1) {
2835                 if (ext2fs_has_feature_sparse_super(sb)) {
2836                         fputs(_("\nThe filesystem already has sparse "
2837                                 "superblocks.\n"), stderr);
2838                 } else if (ext2fs_has_feature_meta_bg(sb)) {
2839                         fputs(_("\nSetting the sparse superblock flag not "
2840                                 "supported\nfor filesystems with "
2841                                 "the meta_bg feature enabled.\n"),
2842                                 stderr);
2843                         rc = 1;
2844                         goto closefs;
2845                 } else {
2846                         ext2fs_set_feature_sparse_super(sb);
2847                         sb->s_state &= ~EXT2_VALID_FS;
2848                         ext2fs_mark_super_dirty(fs);
2849                         printf(_("\nSparse superblock flag set.  %s"),
2850                                _(please_fsck));
2851                 }
2852         }
2853         if (s_flag == 0) {
2854                 fputs(_("\nClearing the sparse superblock flag not supported.\n"),
2855                       stderr);
2856                 rc = 1;
2857                 goto closefs;
2858         }
2859         if (T_flag) {
2860                 sb->s_lastcheck = last_check_time;
2861                 ext2fs_mark_super_dirty(fs);
2862                 printf(_("Setting time filesystem last checked to %s\n"),
2863                        ctime(&last_check_time));
2864         }
2865         if (u_flag) {
2866                 sb->s_def_resuid = resuid;
2867                 ext2fs_mark_super_dirty(fs);
2868                 printf(_("Setting reserved blocks uid to %lu\n"), resuid);
2869         }
2870         if (L_flag) {
2871                 if (strlen(new_label) > sizeof(sb->s_volume_name))
2872                         fputs(_("Warning: label too long, truncating.\n"),
2873                               stderr);
2874                 memset(sb->s_volume_name, 0, sizeof(sb->s_volume_name));
2875                 strncpy(sb->s_volume_name, new_label,
2876                         sizeof(sb->s_volume_name));
2877                 ext2fs_mark_super_dirty(fs);
2878         }
2879         if (M_flag) {
2880                 memset(sb->s_last_mounted, 0, sizeof(sb->s_last_mounted));
2881                 strncpy(sb->s_last_mounted, new_last_mounted,
2882                         sizeof(sb->s_last_mounted));
2883                 ext2fs_mark_super_dirty(fs);
2884         }
2885         if (mntopts_cmd) {
2886                 rc = update_mntopts(fs, mntopts_cmd);
2887                 if (rc)
2888                         goto closefs;
2889         }
2890         if (features_cmd) {
2891                 rc = update_feature_set(fs, features_cmd);
2892                 if (rc)
2893                         goto closefs;
2894         }
2895         if (extended_cmd) {
2896                 rc = parse_extended_opts(fs, extended_cmd);
2897                 if (rc)
2898                         goto closefs;
2899                 if (clear_mmp && !f_flag) {
2900                         fputs(_("Error in using clear_mmp. "
2901                                 "It must be used with -f\n"),
2902                               stderr);
2903                         goto closefs;
2904                 }
2905         }
2906         if (clear_mmp) {
2907                 rc = ext2fs_mmp_clear(fs);
2908                 goto closefs;
2909         }
2910         if (journal_size || journal_device) {
2911                 rc = add_journal(fs);
2912                 if (rc)
2913                         goto closefs;
2914         }
2915
2916         if (Q_flag) {
2917                 if (mount_flags & EXT2_MF_MOUNTED) {
2918                         fputs(_("The quota feature may only be changed when "
2919                                 "the filesystem is unmounted.\n"), stderr);
2920                         rc = 1;
2921                         goto closefs;
2922                 }
2923                 handle_quota_options(fs);
2924         }
2925
2926         if (U_flag) {
2927                 int set_csum = 0;
2928                 dgrp_t i;
2929                 char buf[SUPERBLOCK_SIZE] __attribute__ ((aligned(8)));
2930                 __u8 old_uuid[UUID_SIZE];
2931
2932                 if (ext2fs_has_group_desc_csum(fs)) {
2933                         /*
2934                          * Changing the UUID requires rewriting all metadata,
2935                          * which can race with a mounted fs.  Don't allow that.
2936                          */
2937                         if ((mount_flags & EXT2_MF_MOUNTED) && !f_flag) {
2938                                 fputs(_("The UUID may only be "
2939                                         "changed when the filesystem is "
2940                                         "unmounted.\n"), stderr);
2941                                 exit(1);
2942                         }
2943                         if (check_fsck_needed(fs))
2944                                 exit(1);
2945
2946                         /*
2947                          * Determine if the block group checksums are
2948                          * correct so we know whether or not to set
2949                          * them later on.
2950                          */
2951                         for (i = 0; i < fs->group_desc_count; i++)
2952                                 if (!ext2fs_group_desc_csum_verify(fs, i))
2953                                         break;
2954                         if (i >= fs->group_desc_count)
2955                                 set_csum = 1;
2956                 }
2957
2958                 memcpy(old_uuid, sb->s_uuid, UUID_SIZE);
2959                 if ((strcasecmp(new_UUID, "null") == 0) ||
2960                     (strcasecmp(new_UUID, "clear") == 0)) {
2961                         uuid_clear(sb->s_uuid);
2962                 } else if (strcasecmp(new_UUID, "time") == 0) {
2963                         uuid_generate_time(sb->s_uuid);
2964                 } else if (strcasecmp(new_UUID, "random") == 0) {
2965                         uuid_generate(sb->s_uuid);
2966                 } else if (uuid_parse(new_UUID, sb->s_uuid)) {
2967                         com_err(program_name, 0, "%s",
2968                                 _("Invalid UUID format\n"));
2969                         rc = 1;
2970                         goto closefs;
2971                 }
2972                 ext2fs_init_csum_seed(fs);
2973                 if (set_csum) {
2974                         for (i = 0; i < fs->group_desc_count; i++)
2975                                 ext2fs_group_desc_csum_set(fs, i);
2976                         fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
2977                 }
2978
2979                 /* If this is a journal dev, we need to copy UUID into jsb */
2980                 if (!(rc = get_journal_sb(fs, buf))) {
2981                         journal_superblock_t *jsb;
2982
2983                         jsb = (journal_superblock_t *) buf;
2984                         fputs(_("Need to update journal superblock.\n"), stdout);
2985                         memcpy(jsb->s_uuid, sb->s_uuid, sizeof(sb->s_uuid));
2986
2987                         /* Writeback the journal superblock */
2988                         if ((rc = io_channel_write_blk64(fs->io,
2989                                 ext2fs_journal_sb_start(fs->blocksize),
2990                                         -SUPERBLOCK_SIZE, buf)))
2991                                 goto closefs;
2992                 } else if (rc != EXT2_ET_UNSUPP_FEATURE)
2993                         goto closefs;
2994                 else {
2995                         rc = 0; /** Reset rc to avoid ext2fs_mmp_stop() */
2996
2997                         if ((rc = fs_update_journal_user(sb, old_uuid)))
2998                                 goto closefs;
2999                 }
3000
3001                 ext2fs_mark_super_dirty(fs);
3002                 if (ext2fs_has_feature_metadata_csum(fs->super))
3003                         rewrite_checksums = 1;
3004         }
3005
3006         if (I_flag) {
3007                 if (mount_flags & EXT2_MF_MOUNTED) {
3008                         fputs(_("The inode size may only be "
3009                                 "changed when the filesystem is "
3010                                 "unmounted.\n"), stderr);
3011                         rc = 1;
3012                         goto closefs;
3013                 }
3014                 if (ext2fs_has_feature_flex_bg(fs->super)) {
3015                         fputs(_("Changing the inode size not supported for "
3016                                 "filesystems with the flex_bg\n"
3017                                 "feature enabled.\n"),
3018                               stderr);
3019                         rc = 1;
3020                         goto closefs;
3021                 }
3022                 /*
3023                  * We want to update group descriptor also
3024                  * with the new free inode count
3025                  */
3026                 if (rewrite_checksums)
3027                         fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS;
3028                 fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
3029                 retval = resize_inode(fs, new_inode_size);
3030                 if (rewrite_checksums)
3031                         fs->flags &= ~EXT2_FLAG_IGNORE_CSUM_ERRORS;
3032                 if (retval == 0) {
3033                         printf(_("Setting inode size %lu\n"),
3034                                                         new_inode_size);
3035                         rewrite_checksums = 1;
3036                 } else {
3037                         printf("%s", _("Failed to change inode size\n"));
3038                         rc = 1;
3039                         goto closefs;
3040                 }
3041         }
3042
3043         if (rewrite_checksums)
3044                 rewrite_metadata_checksums(fs);
3045
3046         if (l_flag)
3047                 list_super(sb);
3048         if (stride_set) {
3049                 sb->s_raid_stride = stride;
3050                 ext2fs_mark_super_dirty(fs);
3051                 printf(_("Setting stride size to %d\n"), stride);
3052         }
3053         if (stripe_width_set) {
3054                 sb->s_raid_stripe_width = stripe_width;
3055                 ext2fs_mark_super_dirty(fs);
3056                 printf(_("Setting stripe width to %d\n"), stripe_width);
3057         }
3058         if (ext_mount_opts) {
3059                 strncpy((char *)(fs->super->s_mount_opts), ext_mount_opts,
3060                         sizeof(fs->super->s_mount_opts));
3061                 fs->super->s_mount_opts[sizeof(fs->super->s_mount_opts)-1] = 0;
3062                 ext2fs_mark_super_dirty(fs);
3063                 printf(_("Setting extended default mount options to '%s'\n"),
3064                        ext_mount_opts);
3065                 free(ext_mount_opts);
3066         }
3067
3068         /* Warn if file system needs recovery and it is opened for writing. */
3069         if ((open_flag & EXT2_FLAG_RW) && !(mount_flags & EXT2_MF_MOUNTED) &&
3070             (sb->s_feature_compat & EXT3_FEATURE_COMPAT_HAS_JOURNAL) &&
3071             (sb->s_feature_incompat & EXT3_FEATURE_INCOMPAT_RECOVER)) {
3072                 fprintf(stderr,
3073 _("Warning: The journal is dirty. You may wish to replay the journal like:\n\n"
3074   "\te2fsck -E journal_only %s\n\n"
3075   "then rerun this command.  Otherwise, any changes made may be overwritten\n"
3076   "by journal recovery.\n"), device_name);
3077         }
3078
3079         free(device_name);
3080         remove_error_table(&et_ext2_error_table);
3081
3082 closefs:
3083         if (rc) {
3084                 ext2fs_mmp_stop(fs);
3085 #ifndef BUILD_AS_LIB
3086                 exit(1);
3087 #endif
3088         }
3089
3090         convert_64bit(fs, feature_64bit);
3091         return (ext2fs_close_free(&fs) ? 1 : 0);
3092 }