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