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