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