Whamcloud - gitweb
misc: fix compile warnings on master branch
[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/quotaio.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("%s", _("(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                     ext2fs_inode_has_valid_blocks2(fs, inode)) {
698                         retval = rewrite_directory(fs, ino, inode);
699                         if (retval) {
700                                 com_err("rewrite_directory", retval,
701                                         "while rewriting directories");
702                                 exit(1);
703                         }
704                 }
705
706                 file_acl_block = ext2fs_file_acl_block(fs, inode);
707                 if (!file_acl_block)
708                         continue;
709                 retval = ext2fs_read_ext_attr3(fs, file_acl_block, ea_buf, ino);
710                 if (retval) {
711                         com_err("rewrite_eablock", retval,
712                                 "while rewriting extended attribute");
713                         exit(1);
714                 }
715                 retval = ext2fs_write_ext_attr3(fs, file_acl_block, ea_buf,
716                                                 ino);
717                 if (retval) {
718                         com_err("rewrite_eablock", retval,
719                                 "while rewriting extended attribute");
720                         exit(1);
721                 }
722         } while (ino);
723
724         ext2fs_free_mem(&zero);
725         ext2fs_free_mem(&inode);
726         ext2fs_free_mem(&ea_buf);
727         ext2fs_close_inode_scan(scan);
728 }
729
730 static void rewrite_metadata_checksums(ext2_filsys fs)
731 {
732         errcode_t retval;
733         dgrp_t i;
734
735         fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS;
736         ext2fs_init_csum_seed(fs);
737         for (i = 0; i < fs->group_desc_count; i++)
738                 ext2fs_group_desc_csum_set(fs, i);
739         retval = ext2fs_read_bitmaps(fs);
740         if (retval) {
741                 com_err("rewrite_metadata_checksums", retval,
742                         "while reading bitmaps");
743                 exit(1);
744         }
745         rewrite_inodes(fs);
746         ext2fs_mark_ib_dirty(fs);
747         ext2fs_mark_bb_dirty(fs);
748         ext2fs_mmp_update2(fs, 1);
749         fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
750         fs->flags &= ~EXT2_FLAG_IGNORE_CSUM_ERRORS;
751         if (EXT2_HAS_RO_COMPAT_FEATURE(fs->super,
752                                        EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
753                 fs->super->s_checksum_type = EXT2_CRC32C_CHKSUM;
754         else
755                 fs->super->s_checksum_type = 0;
756         ext2fs_mark_super_dirty(fs);
757 }
758
759 static void enable_uninit_bg(ext2_filsys fs)
760 {
761         struct ext2_group_desc *gd;
762         dgrp_t i;
763
764         for (i = 0; i < fs->group_desc_count; i++) {
765                 gd = ext2fs_group_desc(fs, fs->group_desc, i);
766                 gd->bg_itable_unused = 0;
767                 gd->bg_flags = EXT2_BG_INODE_ZEROED;
768                 ext2fs_group_desc_csum_set(fs, i);
769         }
770         fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
771 }
772
773 static errcode_t zero_empty_inodes(ext2_filsys fs)
774 {
775         int length = EXT2_INODE_SIZE(fs->super);
776         struct ext2_inode *inode;
777         ext2_inode_scan scan;
778         errcode_t       retval;
779         ext2_ino_t      ino;
780
781         retval = ext2fs_open_inode_scan(fs, 0, &scan);
782         if (retval)
783                 goto out;
784
785         retval = ext2fs_get_mem(length, &inode);
786         if (retval)
787                 goto out;
788
789         do {
790                 retval = ext2fs_get_next_inode_full(scan, &ino, inode, length);
791                 if (retval)
792                         goto out;
793                 if (!ino)
794                         break;
795                 if (!ext2fs_test_inode_bitmap2(fs->inode_map, ino)) {
796                         memset(inode, 0, length);
797                         retval = ext2fs_write_inode_full(fs, ino, inode,
798                                                          length);
799                         if (retval)
800                                 goto out;
801                 }
802         } while (1);
803
804 out:
805         ext2fs_free_mem(&inode);
806         ext2fs_close_inode_scan(scan);
807         return retval;
808 }
809
810 static void disable_uninit_bg(ext2_filsys fs, __u32 csum_feature_flag)
811 {
812         struct ext2_group_desc *gd;
813         dgrp_t i;
814         errcode_t retval;
815         blk64_t b, c, d;
816         int has_super;
817
818         /* Load bitmaps to ensure that the uninit ones get written out */
819         fs->super->s_feature_ro_compat |= csum_feature_flag;
820         retval = ext2fs_read_bitmaps(fs);
821         if (retval) {
822                 com_err("disable_uninit_bg", retval,
823                         "while reading bitmaps");
824                 return;
825         }
826         ext2fs_mark_ib_dirty(fs);
827         ext2fs_mark_bb_dirty(fs);
828         fs->super->s_feature_ro_compat &= ~csum_feature_flag;
829
830         /* If we're only turning off uninit_bg, zero the inodes */
831         if (csum_feature_flag == EXT4_FEATURE_RO_COMPAT_GDT_CSUM) {
832                 retval = zero_empty_inodes(fs);
833                 if (retval) {
834                         com_err("disable_uninit_bg", retval,
835                                 "while zeroing unused inodes");
836                         request_fsck_afterwards(fs);
837                 }
838         }
839
840         /* The bbitmap is zeroed; we must mark group metadata blocks in use */
841         for (i = 0; i < fs->group_desc_count; i++) {
842                 b = ext2fs_block_bitmap_loc(fs, i);
843                 ext2fs_mark_block_bitmap2(fs->block_map, b);
844                 b = ext2fs_inode_bitmap_loc(fs, i);
845                 ext2fs_mark_block_bitmap2(fs->block_map, b);
846
847                 retval = ext2fs_super_and_bgd_loc2(fs, i, &b, &c, &d, NULL);
848                 if (retval == 0 && b)
849                         ext2fs_mark_block_bitmap2(fs->block_map, b);
850                 if (retval == 0 && c)
851                         ext2fs_mark_block_bitmap2(fs->block_map, c);
852                 if (retval == 0 && d)
853                         ext2fs_mark_block_bitmap2(fs->block_map, d);
854                 if (retval) {
855                         com_err("disable_uninit_bg", retval,
856                                 "while initializing block bitmaps");
857                         request_fsck_afterwards(fs);
858                 }
859
860                 gd = ext2fs_group_desc(fs, fs->group_desc, i);
861                 gd->bg_itable_unused = 0;
862                 gd->bg_flags = 0;
863                 ext2fs_group_desc_csum_set(fs, i);
864         }
865         fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
866         ext2fs_mark_super_dirty(fs);
867 }
868
869 /*
870  * Update the feature set as provided by the user.
871  */
872 static int update_feature_set(ext2_filsys fs, char *features)
873 {
874         struct ext2_super_block *sb = fs->super;
875         __u32           old_features[3];
876         int             type_err;
877         unsigned int    mask_err;
878
879 #define FEATURE_ON(type, mask) (!(old_features[(type)] & (mask)) && \
880                                 ((&sb->s_feature_compat)[(type)] & (mask)))
881 #define FEATURE_OFF(type, mask) ((old_features[(type)] & (mask)) && \
882                                  !((&sb->s_feature_compat)[(type)] & (mask)))
883 #define FEATURE_CHANGED(type, mask) ((mask) & \
884                      (old_features[(type)] ^ (&sb->s_feature_compat)[(type)]))
885
886         old_features[E2P_FEATURE_COMPAT] = sb->s_feature_compat;
887         old_features[E2P_FEATURE_INCOMPAT] = sb->s_feature_incompat;
888         old_features[E2P_FEATURE_RO_INCOMPAT] = sb->s_feature_ro_compat;
889
890         if (e2p_edit_feature2(features, &sb->s_feature_compat,
891                               ok_features, clear_ok_features,
892                               &type_err, &mask_err)) {
893                 if (!mask_err)
894                         fprintf(stderr,
895                                 _("Invalid filesystem option set: %s\n"),
896                                 features);
897                 else if (type_err & E2P_FEATURE_NEGATE_FLAG)
898                         fprintf(stderr, _("Clearing filesystem feature '%s' "
899                                           "not supported.\n"),
900                                 e2p_feature2string(type_err &
901                                                    E2P_FEATURE_TYPE_MASK,
902                                                    mask_err));
903                 else
904                         fprintf(stderr, _("Setting filesystem feature '%s' "
905                                           "not supported.\n"),
906                                 e2p_feature2string(type_err, mask_err));
907                 return 1;
908         }
909
910         if (FEATURE_OFF(E2P_FEATURE_COMPAT, EXT3_FEATURE_COMPAT_HAS_JOURNAL)) {
911                 if ((mount_flags & EXT2_MF_MOUNTED) &&
912                     !(mount_flags & EXT2_MF_READONLY)) {
913                         fputs(_("The has_journal feature may only be "
914                                 "cleared when the filesystem is\n"
915                                 "unmounted or mounted "
916                                 "read-only.\n"), stderr);
917                         return 1;
918                 }
919                 if ((sb->s_feature_incompat &
920                     EXT3_FEATURE_INCOMPAT_RECOVER) &&
921                     f_flag < 2) {
922                         fputs(_("The needs_recovery flag is set.  "
923                                 "Please run e2fsck before clearing\n"
924                                 "the has_journal flag.\n"), stderr);
925                         return 1;
926                 }
927                 if (sb->s_journal_inum) {
928                         if (remove_journal_inode(fs))
929                                 return 1;
930                 }
931                 if (sb->s_journal_dev) {
932                         if (remove_journal_device(fs))
933                                 return 1;
934                 }
935         }
936
937         if (FEATURE_ON(E2P_FEATURE_RO_INCOMPAT,
938                 EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER)) {
939                 if (sb->s_feature_incompat &
940                         EXT2_FEATURE_INCOMPAT_META_BG) {
941                         fputs(_("Setting filesystem feature 'sparse_super' "
942                                 "not supported\nfor filesystems with "
943                                 "the meta_bg feature enabled.\n"),
944                                 stderr);
945                         return 1;
946                 }
947         }
948
949         if (FEATURE_ON(E2P_FEATURE_INCOMPAT, EXT4_FEATURE_INCOMPAT_MMP)) {
950                 int error;
951
952                 if ((mount_flags & EXT2_MF_MOUNTED) ||
953                     (mount_flags & EXT2_MF_READONLY)) {
954                         fputs(_("The multiple mount protection feature can't\n"
955                                 "be set if the filesystem is mounted or\n"
956                                 "read-only.\n"), stderr);
957                         return 1;
958                 }
959
960                 error = ext2fs_mmp_init(fs);
961                 if (error) {
962                         fputs(_("\nError while enabling multiple mount "
963                                 "protection feature."), stderr);
964                         return 1;
965                 }
966
967                 /*
968                  * We want to update group desc with the new free blocks count
969                  */
970                 fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
971
972                 printf(_("Multiple mount protection has been enabled "
973                          "with update interval %ds.\n"),
974                        sb->s_mmp_update_interval);
975         }
976
977         if (FEATURE_OFF(E2P_FEATURE_INCOMPAT, EXT4_FEATURE_INCOMPAT_MMP)) {
978                 int error;
979
980                 if (mount_flags & EXT2_MF_READONLY) {
981                         fputs(_("The multiple mount protection feature cannot\n"
982                                 "be disabled if the filesystem is readonly.\n"),
983                                 stderr);
984                         return 1;
985                 }
986
987                 error = ext2fs_read_bitmaps(fs);
988                 if (error) {
989                         fputs(_("Error while reading bitmaps\n"), stderr);
990                         return 1;
991                 }
992
993                 error = ext2fs_mmp_read(fs, sb->s_mmp_block, NULL);
994                 if (error) {
995                         struct mmp_struct *mmp_cmp = fs->mmp_cmp;
996
997                         if (error == EXT2_ET_MMP_MAGIC_INVALID)
998                                 printf(_("Magic number in MMP block does not "
999                                          "match. expected: %x, actual: %x\n"),
1000                                          EXT4_MMP_MAGIC, mmp_cmp->mmp_magic);
1001                         else
1002                                 com_err(program_name, error, "%s",
1003                                         _("while reading MMP block."));
1004                         goto mmp_error;
1005                 }
1006
1007                 /* We need to force out the group descriptors as well */
1008                 fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
1009                 ext2fs_block_alloc_stats2(fs, sb->s_mmp_block, -1);
1010 mmp_error:
1011                 sb->s_mmp_block = 0;
1012                 sb->s_mmp_update_interval = 0;
1013         }
1014
1015         if (FEATURE_ON(E2P_FEATURE_COMPAT, EXT3_FEATURE_COMPAT_HAS_JOURNAL)) {
1016                 /*
1017                  * If adding a journal flag, let the create journal
1018                  * code below handle setting the flag and creating the
1019                  * journal.  We supply a default size if necessary.
1020                  */
1021                 if (!journal_size)
1022                         journal_size = -1;
1023                 sb->s_feature_compat &= ~EXT3_FEATURE_COMPAT_HAS_JOURNAL;
1024         }
1025
1026         if (FEATURE_ON(E2P_FEATURE_COMPAT, EXT2_FEATURE_COMPAT_DIR_INDEX)) {
1027                 if (!sb->s_def_hash_version)
1028                         sb->s_def_hash_version = EXT2_HASH_HALF_MD4;
1029                 if (uuid_is_null((unsigned char *) sb->s_hash_seed))
1030                         uuid_generate((unsigned char *) sb->s_hash_seed);
1031         }
1032
1033         if (FEATURE_OFF(E2P_FEATURE_INCOMPAT, EXT4_FEATURE_INCOMPAT_FLEX_BG)) {
1034                 if (ext2fs_check_desc(fs)) {
1035                         fputs(_("Clearing the flex_bg flag would "
1036                                 "cause the the filesystem to be\n"
1037                                 "inconsistent.\n"), stderr);
1038                         return 1;
1039                 }
1040         }
1041
1042         if (FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
1043                             EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
1044                 if ((mount_flags & EXT2_MF_MOUNTED) &&
1045                     !(mount_flags & EXT2_MF_READONLY)) {
1046                         fputs(_("The huge_file feature may only be "
1047                                 "cleared when the filesystem is\n"
1048                                 "unmounted or mounted "
1049                                 "read-only.\n"), stderr);
1050                         return 1;
1051                 }
1052         }
1053
1054         if (FEATURE_ON(E2P_FEATURE_RO_INCOMPAT,
1055                        EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) {
1056                 if (check_fsck_needed(fs))
1057                         exit(1);
1058                 rewrite_checksums = 1;
1059                 /* metadata_csum supersedes uninit_bg */
1060                 fs->super->s_feature_ro_compat &=
1061                         ~EXT4_FEATURE_RO_COMPAT_GDT_CSUM;
1062
1063                 /* if uninit_bg was previously off, rewrite group desc */
1064                 if (!(old_features[E2P_FEATURE_RO_INCOMPAT] &
1065                       EXT4_FEATURE_RO_COMPAT_GDT_CSUM))
1066                         enable_uninit_bg(fs);
1067
1068                 /*
1069                  * Since metadata_csum supersedes uninit_bg, pretend like
1070                  * uninit_bg has been off all along.
1071                  */
1072                 old_features[E2P_FEATURE_RO_INCOMPAT] &=
1073                         ~EXT4_FEATURE_RO_COMPAT_GDT_CSUM;
1074         }
1075
1076         if (FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
1077                         EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) {
1078                 if (check_fsck_needed(fs))
1079                         exit(1);
1080                 rewrite_checksums = 1;
1081                 /*
1082                  * If we're turning off metadata_csum and not turning on
1083                  * uninit_bg, rewrite group desc.
1084                  */
1085                 if (!(fs->super->s_feature_ro_compat &
1086                       EXT4_FEATURE_RO_COMPAT_GDT_CSUM))
1087                         disable_uninit_bg(fs,
1088                                 EXT4_FEATURE_RO_COMPAT_METADATA_CSUM);
1089                 else
1090                         /*
1091                          * metadata_csum previously provided uninit_bg, so if
1092                          * we're also setting the uninit_bg feature bit,
1093                          * pretend like it was previously enabled.  Checksums
1094                          * will be rewritten with crc16 later.
1095                          */
1096                         old_features[E2P_FEATURE_RO_INCOMPAT] |=
1097                                 EXT4_FEATURE_RO_COMPAT_GDT_CSUM;
1098         }
1099
1100         if (FEATURE_ON(E2P_FEATURE_RO_INCOMPAT,
1101                        EXT4_FEATURE_RO_COMPAT_GDT_CSUM)) {
1102                 /* Do not enable uninit_bg when metadata_csum enabled */
1103                 if (fs->super->s_feature_ro_compat &
1104                     EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)
1105                         fs->super->s_feature_ro_compat &=
1106                                 ~EXT4_FEATURE_RO_COMPAT_GDT_CSUM;
1107                 else
1108                         enable_uninit_bg(fs);
1109         }
1110
1111         if (FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
1112                         EXT4_FEATURE_RO_COMPAT_GDT_CSUM))
1113                 disable_uninit_bg(fs,
1114                                 EXT4_FEATURE_RO_COMPAT_GDT_CSUM);
1115
1116         if (FEATURE_ON(E2P_FEATURE_RO_INCOMPAT,
1117                                 EXT4_FEATURE_RO_COMPAT_QUOTA)) {
1118                 /*
1119                  * Set the Q_flag here and handle the quota options in the code
1120                  * below.
1121                  */
1122                 if (!Q_flag) {
1123                         Q_flag = 1;
1124                         /* Enable both user quota and group quota by default */
1125                         usrquota = QOPT_ENABLE;
1126                         grpquota = QOPT_ENABLE;
1127                 }
1128                 sb->s_feature_ro_compat &= ~EXT4_FEATURE_RO_COMPAT_QUOTA;
1129         }
1130
1131         if (FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
1132                                 EXT4_FEATURE_RO_COMPAT_QUOTA)) {
1133                 /*
1134                  * Set the Q_flag here and handle the quota options in the code
1135                  * below.
1136                  */
1137                 if (Q_flag)
1138                         fputs(_("\nWarning: '^quota' option overrides '-Q'"
1139                                 "arguments.\n"), stderr);
1140                 Q_flag = 1;
1141                 /* Disable both user quota and group quota by default */
1142                 usrquota = QOPT_DISABLE;
1143                 grpquota = QOPT_DISABLE;
1144         }
1145
1146         if (sb->s_rev_level == EXT2_GOOD_OLD_REV &&
1147             (sb->s_feature_compat || sb->s_feature_ro_compat ||
1148              sb->s_feature_incompat))
1149                 ext2fs_update_dynamic_rev(fs);
1150
1151         if (FEATURE_CHANGED(E2P_FEATURE_RO_INCOMPAT,
1152                             EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER) ||
1153             FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
1154                         EXT4_FEATURE_RO_COMPAT_HUGE_FILE) ||
1155             FEATURE_CHANGED(E2P_FEATURE_INCOMPAT,
1156                             EXT2_FEATURE_INCOMPAT_FILETYPE) ||
1157             FEATURE_CHANGED(E2P_FEATURE_COMPAT,
1158                             EXT2_FEATURE_COMPAT_RESIZE_INODE) ||
1159             FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
1160                         EXT2_FEATURE_RO_COMPAT_LARGE_FILE))
1161                 request_fsck_afterwards(fs);
1162
1163         if ((old_features[E2P_FEATURE_COMPAT] != sb->s_feature_compat) ||
1164             (old_features[E2P_FEATURE_INCOMPAT] != sb->s_feature_incompat) ||
1165             (old_features[E2P_FEATURE_RO_INCOMPAT] != sb->s_feature_ro_compat))
1166                 ext2fs_mark_super_dirty(fs);
1167
1168         return 0;
1169 }
1170
1171 /*
1172  * Add a journal to the filesystem.
1173  */
1174 static int add_journal(ext2_filsys fs)
1175 {
1176         unsigned long journal_blocks;
1177         errcode_t       retval;
1178         ext2_filsys     jfs;
1179         io_manager      io_ptr;
1180
1181         if (fs->super->s_feature_compat &
1182             EXT3_FEATURE_COMPAT_HAS_JOURNAL) {
1183                 fputs(_("The filesystem already has a journal.\n"), stderr);
1184                 goto err;
1185         }
1186         if (journal_device) {
1187                 if (!check_plausibility(journal_device, CHECK_BLOCK_DEV,
1188                                         NULL))
1189                         proceed_question(-1);
1190                 check_mount(journal_device, 0, _("journal"));
1191 #ifdef CONFIG_TESTIO_DEBUG
1192                 if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_BLOCK")) {
1193                         io_ptr = test_io_manager;
1194                         test_io_backing_manager = unix_io_manager;
1195                 } else
1196 #endif
1197                         io_ptr = unix_io_manager;
1198                 retval = ext2fs_open(journal_device, EXT2_FLAG_RW|
1199                                      EXT2_FLAG_JOURNAL_DEV_OK, 0,
1200                                      fs->blocksize, io_ptr, &jfs);
1201                 if (retval) {
1202                         com_err(program_name, retval,
1203                                 _("\n\twhile trying to open journal on %s\n"),
1204                                 journal_device);
1205                         goto err;
1206                 }
1207                 printf(_("Creating journal on device %s: "),
1208                        journal_device);
1209                 fflush(stdout);
1210
1211                 retval = ext2fs_add_journal_device(fs, jfs);
1212                 ext2fs_close(jfs);
1213                 if (retval) {
1214                         com_err(program_name, retval,
1215                                 _("while adding filesystem to journal on %s"),
1216                                 journal_device);
1217                         goto err;
1218                 }
1219                 fputs(_("done\n"), stdout);
1220         } else if (journal_size) {
1221                 fputs(_("Creating journal inode: "), stdout);
1222                 fflush(stdout);
1223                 journal_blocks = figure_journal_size(journal_size, fs);
1224
1225                 if (journal_location_string)
1226                         journal_location =
1227                                 parse_num_blocks2(journal_location_string,
1228                                                   fs->super->s_log_block_size);
1229                 retval = ext2fs_add_journal_inode2(fs, journal_blocks,
1230                                                    journal_location,
1231                                                    journal_flags);
1232                 if (retval) {
1233                         fprintf(stderr, "\n");
1234                         com_err(program_name, retval, "%s",
1235                                 _("\n\twhile trying to create journal file"));
1236                         return retval;
1237                 } else
1238                         fputs(_("done\n"), stdout);
1239                 /*
1240                  * If the filesystem wasn't mounted, we need to force
1241                  * the block group descriptors out.
1242                  */
1243                 if ((mount_flags & EXT2_MF_MOUNTED) == 0)
1244                         fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
1245         }
1246         print_check_message(fs->super->s_max_mnt_count,
1247                             fs->super->s_checkinterval);
1248         return 0;
1249
1250 err:
1251         free(journal_device);
1252         return 1;
1253 }
1254
1255 static void handle_quota_options(ext2_filsys fs)
1256 {
1257         quota_ctx_t qctx;
1258         ext2_ino_t qf_ino;
1259
1260         if (!usrquota && !grpquota)
1261                 /* Nothing to do. */
1262                 return;
1263
1264         quota_init_context(&qctx, fs, -1);
1265
1266         if (usrquota == QOPT_ENABLE || grpquota == QOPT_ENABLE)
1267                 quota_compute_usage(qctx);
1268
1269         if (usrquota == QOPT_ENABLE && !fs->super->s_usr_quota_inum) {
1270                 if ((qf_ino = quota_file_exists(fs, USRQUOTA,
1271                                                 QFMT_VFS_V1)) > 0)
1272                         quota_update_limits(qctx, qf_ino, USRQUOTA);
1273                 quota_write_inode(qctx, USRQUOTA);
1274         } else if (usrquota == QOPT_DISABLE) {
1275                 quota_remove_inode(fs, USRQUOTA);
1276         }
1277
1278         if (grpquota == QOPT_ENABLE && !fs->super->s_grp_quota_inum) {
1279                 if ((qf_ino = quota_file_exists(fs, GRPQUOTA,
1280                                                 QFMT_VFS_V1)) > 0)
1281                         quota_update_limits(qctx, qf_ino, GRPQUOTA);
1282                 quota_write_inode(qctx, GRPQUOTA);
1283         } else if (grpquota == QOPT_DISABLE) {
1284                 quota_remove_inode(fs, GRPQUOTA);
1285         }
1286
1287         quota_release_context(&qctx);
1288
1289         if ((usrquota == QOPT_ENABLE) || (grpquota == QOPT_ENABLE)) {
1290                 fs->super->s_feature_ro_compat |= EXT4_FEATURE_RO_COMPAT_QUOTA;
1291                 ext2fs_mark_super_dirty(fs);
1292         } else if (!fs->super->s_usr_quota_inum &&
1293                    !fs->super->s_grp_quota_inum) {
1294                 fs->super->s_feature_ro_compat &= ~EXT4_FEATURE_RO_COMPAT_QUOTA;
1295                 ext2fs_mark_super_dirty(fs);
1296         }
1297
1298         return;
1299 }
1300
1301 #ifdef CONFIG_QUOTA
1302 static void parse_quota_opts(const char *opts)
1303 {
1304         char    *buf, *token, *next, *p;
1305         int     len;
1306
1307         len = strlen(opts);
1308         buf = malloc(len+1);
1309         if (!buf) {
1310                 fputs(_("Couldn't allocate memory to parse quota "
1311                         "options!\n"), stderr);
1312                 exit(1);
1313         }
1314         strcpy(buf, opts);
1315         for (token = buf; token && *token; token = next) {
1316                 p = strchr(token, ',');
1317                 next = 0;
1318                 if (p) {
1319                         *p = 0;
1320                         next = p+1;
1321                 }
1322
1323                 if (strcmp(token, "usrquota") == 0) {
1324                         usrquota = QOPT_ENABLE;
1325                 } else if (strcmp(token, "^usrquota") == 0) {
1326                         usrquota = QOPT_DISABLE;
1327                 } else if (strcmp(token, "grpquota") == 0) {
1328                         grpquota = QOPT_ENABLE;
1329                 } else if (strcmp(token, "^grpquota") == 0) {
1330                         grpquota = QOPT_DISABLE;
1331                 } else {
1332                         fputs(_("\nBad quota options specified.\n\n"
1333                                 "Following valid quota options are available "
1334                                 "(pass by separating with comma):\n"
1335                                 "\t[^]usrquota\n"
1336                                 "\t[^]grpquota\n"
1337                                 "\n\n"), stderr);
1338                         free(buf);
1339                         exit(1);
1340                 }
1341         }
1342         free(buf);
1343 }
1344 #endif
1345
1346 static void parse_e2label_options(int argc, char ** argv)
1347 {
1348         if ((argc < 2) || (argc > 3)) {
1349                 fputs(_("Usage: e2label device [newlabel]\n"), stderr);
1350                 exit(1);
1351         }
1352         io_options = strchr(argv[1], '?');
1353         if (io_options)
1354                 *io_options++ = 0;
1355         device_name = blkid_get_devname(NULL, argv[1], NULL);
1356         if (!device_name) {
1357                 com_err("e2label", 0, _("Unable to resolve '%s'"),
1358                         argv[1]);
1359                 exit(1);
1360         }
1361         open_flag = EXT2_FLAG_JOURNAL_DEV_OK;
1362         if (argc == 3) {
1363                 open_flag |= EXT2_FLAG_RW;
1364                 L_flag = 1;
1365                 new_label = argv[2];
1366         } else
1367                 print_label++;
1368 }
1369
1370 static time_t parse_time(char *str)
1371 {
1372         struct  tm      ts;
1373
1374         if (strcmp(str, "now") == 0) {
1375                 return (time(0));
1376         }
1377         memset(&ts, 0, sizeof(ts));
1378 #ifdef HAVE_STRPTIME
1379         strptime(str, "%Y%m%d%H%M%S", &ts);
1380 #else
1381         sscanf(str, "%4d%2d%2d%2d%2d%2d", &ts.tm_year, &ts.tm_mon,
1382                &ts.tm_mday, &ts.tm_hour, &ts.tm_min, &ts.tm_sec);
1383         ts.tm_year -= 1900;
1384         ts.tm_mon -= 1;
1385         if (ts.tm_year < 0 || ts.tm_mon < 0 || ts.tm_mon > 11 ||
1386             ts.tm_mday < 0 || ts.tm_mday > 31 || ts.tm_hour > 23 ||
1387             ts.tm_min > 59 || ts.tm_sec > 61)
1388                 ts.tm_mday = 0;
1389 #endif
1390         if (ts.tm_mday == 0) {
1391                 com_err(program_name, 0,
1392                         _("Couldn't parse date/time specifier: %s"),
1393                         str);
1394                 usage();
1395         }
1396         ts.tm_isdst = -1;
1397         return (mktime(&ts));
1398 }
1399
1400 static void parse_tune2fs_options(int argc, char **argv)
1401 {
1402         int c;
1403         char *tmp;
1404         struct group *gr;
1405         struct passwd *pw;
1406         char optstring[100] = "c:e:fg:i:jlm:o:r:s:u:C:E:I:J:L:M:O:T:U:";
1407
1408 #ifdef CONFIG_QUOTA
1409         strcat(optstring, "Q:");
1410 #endif
1411         open_flag = 0;
1412
1413         printf("tune2fs %s (%s)\n", E2FSPROGS_VERSION, E2FSPROGS_DATE);
1414         while ((c = getopt(argc, argv, optstring)) != EOF)
1415                 switch (c) {
1416                 case 'c':
1417                         max_mount_count = strtol(optarg, &tmp, 0);
1418                         if (*tmp || max_mount_count > 16000) {
1419                                 com_err(program_name, 0,
1420                                         _("bad mounts count - %s"),
1421                                         optarg);
1422                                 usage();
1423                         }
1424                         if (max_mount_count == 0)
1425                                 max_mount_count = -1;
1426                         c_flag = 1;
1427                         open_flag = EXT2_FLAG_RW;
1428                         break;
1429                 case 'C':
1430                         mount_count = strtoul(optarg, &tmp, 0);
1431                         if (*tmp || mount_count > 16000) {
1432                                 com_err(program_name, 0,
1433                                         _("bad mounts count - %s"),
1434                                         optarg);
1435                                 usage();
1436                         }
1437                         C_flag = 1;
1438                         open_flag = EXT2_FLAG_RW;
1439                         break;
1440                 case 'e':
1441                         if (strcmp(optarg, "continue") == 0)
1442                                 errors = EXT2_ERRORS_CONTINUE;
1443                         else if (strcmp(optarg, "remount-ro") == 0)
1444                                 errors = EXT2_ERRORS_RO;
1445                         else if (strcmp(optarg, "panic") == 0)
1446                                 errors = EXT2_ERRORS_PANIC;
1447                         else {
1448                                 com_err(program_name, 0,
1449                                         _("bad error behavior - %s"),
1450                                         optarg);
1451                                 usage();
1452                         }
1453                         e_flag = 1;
1454                         open_flag = EXT2_FLAG_RW;
1455                         break;
1456                 case 'E':
1457                         extended_cmd = optarg;
1458                         open_flag |= EXT2_FLAG_RW;
1459                         break;
1460                 case 'f': /* Force */
1461                         f_flag++;
1462                         break;
1463                 case 'g':
1464                         resgid = strtoul(optarg, &tmp, 0);
1465                         if (*tmp) {
1466                                 gr = getgrnam(optarg);
1467                                 if (gr == NULL)
1468                                         tmp = optarg;
1469                                 else {
1470                                         resgid = gr->gr_gid;
1471                                         *tmp = 0;
1472                                 }
1473                         }
1474                         if (*tmp) {
1475                                 com_err(program_name, 0,
1476                                         _("bad gid/group name - %s"),
1477                                         optarg);
1478                                 usage();
1479                         }
1480                         g_flag = 1;
1481                         open_flag = EXT2_FLAG_RW;
1482                         break;
1483                 case 'i':
1484                         interval = strtoul(optarg, &tmp, 0);
1485                         switch (*tmp) {
1486                         case 's':
1487                                 tmp++;
1488                                 break;
1489                         case '\0':
1490                         case 'd':
1491                         case 'D': /* days */
1492                                 interval *= 86400;
1493                                 if (*tmp != '\0')
1494                                         tmp++;
1495                                 break;
1496                         case 'm':
1497                         case 'M': /* months! */
1498                                 interval *= 86400 * 30;
1499                                 tmp++;
1500                                 break;
1501                         case 'w':
1502                         case 'W': /* weeks */
1503                                 interval *= 86400 * 7;
1504                                 tmp++;
1505                                 break;
1506                         }
1507                         if (*tmp) {
1508                                 com_err(program_name, 0,
1509                                         _("bad interval - %s"), optarg);
1510                                 usage();
1511                         }
1512                         i_flag = 1;
1513                         open_flag = EXT2_FLAG_RW;
1514                         break;
1515                 case 'j':
1516                         if (!journal_size)
1517                                 journal_size = -1;
1518                         open_flag = EXT2_FLAG_RW;
1519                         break;
1520                 case 'J':
1521                         parse_journal_opts(optarg);
1522                         open_flag = EXT2_FLAG_RW;
1523                         break;
1524                 case 'l':
1525                         l_flag = 1;
1526                         break;
1527                 case 'L':
1528                         new_label = optarg;
1529                         L_flag = 1;
1530                         open_flag |= EXT2_FLAG_RW |
1531                                 EXT2_FLAG_JOURNAL_DEV_OK;
1532                         break;
1533                 case 'm':
1534                         reserved_ratio = strtod(optarg, &tmp);
1535                         if (*tmp || reserved_ratio > 50 ||
1536                             reserved_ratio < 0) {
1537                                 com_err(program_name, 0,
1538                                         _("bad reserved block ratio - %s"),
1539                                         optarg);
1540                                 usage();
1541                         }
1542                         m_flag = 1;
1543                         open_flag = EXT2_FLAG_RW;
1544                         break;
1545                 case 'M':
1546                         new_last_mounted = optarg;
1547                         M_flag = 1;
1548                         open_flag = EXT2_FLAG_RW;
1549                         break;
1550                 case 'o':
1551                         if (mntopts_cmd) {
1552                                 com_err(program_name, 0, "%s",
1553                                         _("-o may only be specified once"));
1554                                 usage();
1555                         }
1556                         mntopts_cmd = optarg;
1557                         open_flag = EXT2_FLAG_RW;
1558                         break;
1559                 case 'O':
1560                         if (features_cmd) {
1561                                 com_err(program_name, 0, "%s",
1562                                         _("-O may only be specified once"));
1563                                 usage();
1564                         }
1565                         features_cmd = optarg;
1566                         open_flag = EXT2_FLAG_RW;
1567                         break;
1568 #ifdef CONFIG_QUOTA
1569                 case 'Q':
1570                         Q_flag = 1;
1571                         parse_quota_opts(optarg);
1572                         open_flag = EXT2_FLAG_RW;
1573                         break;
1574 #endif
1575                 case 'r':
1576                         reserved_blocks = strtoul(optarg, &tmp, 0);
1577                         if (*tmp) {
1578                                 com_err(program_name, 0,
1579                                         _("bad reserved blocks count - %s"),
1580                                         optarg);
1581                                 usage();
1582                         }
1583                         r_flag = 1;
1584                         open_flag = EXT2_FLAG_RW;
1585                         break;
1586                 case 's': /* Deprecated */
1587                         s_flag = atoi(optarg);
1588                         open_flag = EXT2_FLAG_RW;
1589                         break;
1590                 case 'T':
1591                         T_flag = 1;
1592                         last_check_time = parse_time(optarg);
1593                         open_flag = EXT2_FLAG_RW;
1594                         break;
1595                 case 'u':
1596                                 resuid = strtoul(optarg, &tmp, 0);
1597                                 if (*tmp) {
1598                                         pw = getpwnam(optarg);
1599                                         if (pw == NULL)
1600                                                 tmp = optarg;
1601                                         else {
1602                                                 resuid = pw->pw_uid;
1603                                                 *tmp = 0;
1604                                         }
1605                                 }
1606                                 if (*tmp) {
1607                                         com_err(program_name, 0,
1608                                                 _("bad uid/user name - %s"),
1609                                                 optarg);
1610                                         usage();
1611                                 }
1612                                 u_flag = 1;
1613                                 open_flag = EXT2_FLAG_RW;
1614                                 break;
1615                 case 'U':
1616                         new_UUID = optarg;
1617                         U_flag = 1;
1618                         open_flag = EXT2_FLAG_RW |
1619                                 EXT2_FLAG_JOURNAL_DEV_OK;
1620                         break;
1621                 case 'I':
1622                         new_inode_size = strtoul(optarg, &tmp, 0);
1623                         if (*tmp) {
1624                                 com_err(program_name, 0,
1625                                         _("bad inode size - %s"),
1626                                         optarg);
1627                                 usage();
1628                         }
1629                         if (!((new_inode_size &
1630                                (new_inode_size - 1)) == 0)) {
1631                                 com_err(program_name, 0,
1632                                         _("Inode size must be a "
1633                                           "power of two- %s"),
1634                                         optarg);
1635                                 usage();
1636                         }
1637                         open_flag = EXT2_FLAG_RW;
1638                         I_flag = 1;
1639                         break;
1640                 default:
1641                         usage();
1642                 }
1643         if (optind < argc - 1 || optind == argc)
1644                 usage();
1645         if (!open_flag && !l_flag)
1646                 usage();
1647         io_options = strchr(argv[optind], '?');
1648         if (io_options)
1649                 *io_options++ = 0;
1650         device_name = blkid_get_devname(NULL, argv[optind], NULL);
1651         if (!device_name) {
1652                 com_err(program_name, 0, _("Unable to resolve '%s'"),
1653                         argv[optind]);
1654                 exit(1);
1655         }
1656 }
1657
1658 #ifdef CONFIG_BUILD_FINDFS
1659 void do_findfs(int argc, char **argv)
1660 {
1661         char    *dev;
1662
1663         if ((argc != 2) ||
1664             (strncmp(argv[1], "LABEL=", 6) && strncmp(argv[1], "UUID=", 5))) {
1665                 fprintf(stderr, "Usage: findfs LABEL=<label>|UUID=<uuid>\n");
1666                 exit(2);
1667         }
1668         dev = blkid_get_devname(NULL, argv[1], NULL);
1669         if (!dev) {
1670                 com_err("findfs", 0, _("Unable to resolve '%s'"),
1671                         argv[1]);
1672                 exit(1);
1673         }
1674         puts(dev);
1675         exit(0);
1676 }
1677 #endif
1678
1679 static int parse_extended_opts(ext2_filsys fs, const char *opts)
1680 {
1681         char    *buf, *token, *next, *p, *arg;
1682         int     len, hash_alg;
1683         int     r_usage = 0;
1684
1685         len = strlen(opts);
1686         buf = malloc(len+1);
1687         if (!buf) {
1688                 fprintf(stderr, "%s",
1689                         _("Couldn't allocate memory to parse options!\n"));
1690                 return 1;
1691         }
1692         strcpy(buf, opts);
1693         for (token = buf; token && *token; token = next) {
1694                 p = strchr(token, ',');
1695                 next = 0;
1696                 if (p) {
1697                         *p = 0;
1698                         next = p+1;
1699                 }
1700                 arg = strchr(token, '=');
1701                 if (arg) {
1702                         *arg = 0;
1703                         arg++;
1704                 }
1705                 if (strcmp(token, "clear-mmp") == 0 ||
1706                     strcmp(token, "clear_mmp") == 0) {
1707                         clear_mmp = 1;
1708                 } else if (strcmp(token, "mmp_update_interval") == 0) {
1709                         unsigned long intv;
1710                         if (!arg) {
1711                                 r_usage++;
1712                                 continue;
1713                         }
1714                         intv = strtoul(arg, &p, 0);
1715                         if (*p) {
1716                                 fprintf(stderr,
1717                                         _("Invalid mmp_update_interval: %s\n"),
1718                                         arg);
1719                                 r_usage++;
1720                                 continue;
1721                         }
1722                         if (intv == 0) {
1723                                 intv = EXT4_MMP_UPDATE_INTERVAL;
1724                         } else if (intv > EXT4_MMP_MAX_UPDATE_INTERVAL) {
1725                                 fprintf(stderr,
1726                                         _("mmp_update_interval too big: %lu\n"),
1727                                         intv);
1728                                 r_usage++;
1729                                 continue;
1730                         }
1731                         printf(P_("Setting multiple mount protection update "
1732                                   "interval to %lu second\n",
1733                                   "Setting multiple mount protection update "
1734                                   "interval to %lu seconds\n", intv),
1735                                intv);
1736                         fs->super->s_mmp_update_interval = intv;
1737                         ext2fs_mark_super_dirty(fs);
1738                 } else if (!strcmp(token, "test_fs")) {
1739                         fs->super->s_flags |= EXT2_FLAGS_TEST_FILESYS;
1740                         printf("Setting test filesystem flag\n");
1741                         ext2fs_mark_super_dirty(fs);
1742                 } else if (!strcmp(token, "^test_fs")) {
1743                         fs->super->s_flags &= ~EXT2_FLAGS_TEST_FILESYS;
1744                         printf("Clearing test filesystem flag\n");
1745                         ext2fs_mark_super_dirty(fs);
1746                 } else if (strcmp(token, "stride") == 0) {
1747                         if (!arg) {
1748                                 r_usage++;
1749                                 continue;
1750                         }
1751                         stride = strtoul(arg, &p, 0);
1752                         if (*p) {
1753                                 fprintf(stderr,
1754                                         _("Invalid RAID stride: %s\n"),
1755                                         arg);
1756                                 r_usage++;
1757                                 continue;
1758                         }
1759                         stride_set = 1;
1760                 } else if (strcmp(token, "stripe-width") == 0 ||
1761                            strcmp(token, "stripe_width") == 0) {
1762                         if (!arg) {
1763                                 r_usage++;
1764                                 continue;
1765                         }
1766                         stripe_width = strtoul(arg, &p, 0);
1767                         if (*p) {
1768                                 fprintf(stderr,
1769                                         _("Invalid RAID stripe-width: %s\n"),
1770                                         arg);
1771                                 r_usage++;
1772                                 continue;
1773                         }
1774                         stripe_width_set = 1;
1775                 } else if (strcmp(token, "hash_alg") == 0 ||
1776                            strcmp(token, "hash-alg") == 0) {
1777                         if (!arg) {
1778                                 r_usage++;
1779                                 continue;
1780                         }
1781                         hash_alg = e2p_string2hash(arg);
1782                         if (hash_alg < 0) {
1783                                 fprintf(stderr,
1784                                         _("Invalid hash algorithm: %s\n"),
1785                                         arg);
1786                                 r_usage++;
1787                                 continue;
1788                         }
1789                         fs->super->s_def_hash_version = hash_alg;
1790                         printf(_("Setting default hash algorithm "
1791                                  "to %s (%d)\n"),
1792                                arg, hash_alg);
1793                         ext2fs_mark_super_dirty(fs);
1794                 } else if (!strcmp(token, "mount_opts")) {
1795                         if (!arg) {
1796                                 r_usage++;
1797                                 continue;
1798                         }
1799                         if (strlen(arg) >= sizeof(fs->super->s_mount_opts)) {
1800                                 fprintf(stderr,
1801                                         "Extended mount options too long\n");
1802                                 continue;
1803                         }
1804                         ext_mount_opts = strdup(arg);
1805                 } else
1806                         r_usage++;
1807         }
1808         if (r_usage) {
1809                 fprintf(stderr, "%s", _("\nBad options specified.\n\n"
1810                         "Extended options are separated by commas, "
1811                         "and may take an argument which\n"
1812                         "\tis set off by an equals ('=') sign.\n\n"
1813                         "Valid extended options are:\n"
1814                         "\tclear_mmp\n"
1815                         "\thash_alg=<hash algorithm>\n"
1816                         "\tmount_opts=<extended default mount options>\n"
1817                         "\tstride=<RAID per-disk chunk size in blocks>\n"
1818                         "\tstripe_width=<RAID stride*data disks in blocks>\n"
1819                         "\ttest_fs\n"
1820                         "\t^test_fs\n"));
1821                 free(buf);
1822                 return 1;
1823         }
1824         free(buf);
1825
1826         return 0;
1827 }
1828
1829 /*
1830  * Fill in the block bitmap bmap with the information regarding the
1831  * blocks to be moved
1832  */
1833 static int get_move_bitmaps(ext2_filsys fs, int new_ino_blks_per_grp,
1834                             ext2fs_block_bitmap bmap)
1835 {
1836         dgrp_t i;
1837         int retval;
1838         ext2_badblocks_list bb_list = 0;
1839         blk64_t j, needed_blocks = 0;
1840         blk64_t start_blk, end_blk;
1841
1842         retval = ext2fs_read_bb_inode(fs, &bb_list);
1843         if (retval)
1844                 return retval;
1845
1846         for (i = 0; i < fs->group_desc_count; i++) {
1847                 start_blk = ext2fs_inode_table_loc(fs, i) +
1848                                         fs->inode_blocks_per_group;
1849
1850                 end_blk = ext2fs_inode_table_loc(fs, i) +
1851                                         new_ino_blks_per_grp;
1852
1853                 for (j = start_blk; j < end_blk; j++) {
1854                         if (ext2fs_test_block_bitmap2(fs->block_map, j)) {
1855                                 /*
1856                                  * IF the block is a bad block we fail
1857                                  */
1858                                 if (ext2fs_badblocks_list_test(bb_list, j)) {
1859                                         ext2fs_badblocks_list_free(bb_list);
1860                                         return ENOSPC;
1861                                 }
1862
1863                                 ext2fs_mark_block_bitmap2(bmap, j);
1864                         } else {
1865                                 /*
1866                                  * We are going to use this block for
1867                                  * inode table. So mark them used.
1868                                  */
1869                                 ext2fs_mark_block_bitmap2(fs->block_map, j);
1870                         }
1871                 }
1872                 needed_blocks += end_blk - start_blk;
1873         }
1874
1875         ext2fs_badblocks_list_free(bb_list);
1876         if (needed_blocks > ext2fs_free_blocks_count(fs->super))
1877                 return ENOSPC;
1878
1879         return 0;
1880 }
1881
1882 static int ext2fs_is_meta_block(ext2_filsys fs, blk64_t blk)
1883 {
1884         dgrp_t group;
1885         group = ext2fs_group_of_blk2(fs, blk);
1886         if (ext2fs_block_bitmap_loc(fs, group) == blk)
1887                 return 1;
1888         if (ext2fs_inode_bitmap_loc(fs, group) == blk)
1889                 return 1;
1890         return 0;
1891 }
1892
1893 static int ext2fs_is_block_in_group(ext2_filsys fs, dgrp_t group, blk64_t blk)
1894 {
1895         blk64_t start_blk, end_blk;
1896         start_blk = fs->super->s_first_data_block +
1897                         EXT2_BLOCKS_PER_GROUP(fs->super) * group;
1898         /*
1899          * We cannot get new block beyond end_blk for for the last block group
1900          * so we can check with EXT2_BLOCKS_PER_GROUP even for last block group
1901          */
1902         end_blk   = start_blk + EXT2_BLOCKS_PER_GROUP(fs->super);
1903         if (blk >= start_blk && blk <= end_blk)
1904                 return 1;
1905         return 0;
1906 }
1907
1908 static int move_block(ext2_filsys fs, ext2fs_block_bitmap bmap)
1909 {
1910
1911         char *buf;
1912         dgrp_t group = 0;
1913         errcode_t retval;
1914         int meta_data = 0;
1915         blk64_t blk, new_blk, goal;
1916         struct blk_move *bmv;
1917
1918         retval = ext2fs_get_mem(fs->blocksize, &buf);
1919         if (retval)
1920                 return retval;
1921
1922         for (new_blk = blk = fs->super->s_first_data_block;
1923              blk < ext2fs_blocks_count(fs->super); blk++) {
1924                 if (!ext2fs_test_block_bitmap2(bmap, blk))
1925                         continue;
1926
1927                 if (ext2fs_is_meta_block(fs, blk)) {
1928                         /*
1929                          * If the block is mapping a fs meta data block
1930                          * like group desc/block bitmap/inode bitmap. We
1931                          * should find a block in the same group and fix
1932                          * the respective fs metadata pointers. Otherwise
1933                          * fail
1934                          */
1935                         group = ext2fs_group_of_blk2(fs, blk);
1936                         goal = ext2fs_group_first_block2(fs, group);
1937                         meta_data = 1;
1938
1939                 } else {
1940                         goal = new_blk;
1941                 }
1942                 retval = ext2fs_new_block2(fs, goal, NULL, &new_blk);
1943                 if (retval)
1944                         goto err_out;
1945
1946                 /* new fs meta data block should be in the same group */
1947                 if (meta_data && !ext2fs_is_block_in_group(fs, group, new_blk)) {
1948                         retval = ENOSPC;
1949                         goto err_out;
1950                 }
1951
1952                 /* Mark this block as allocated */
1953                 ext2fs_mark_block_bitmap2(fs->block_map, new_blk);
1954
1955                 /* Add it to block move list */
1956                 retval = ext2fs_get_mem(sizeof(struct blk_move), &bmv);
1957                 if (retval)
1958                         goto err_out;
1959
1960                 bmv->old_loc = blk;
1961                 bmv->new_loc = new_blk;
1962
1963                 list_add(&(bmv->list), &blk_move_list);
1964
1965                 retval = io_channel_read_blk64(fs->io, blk, 1, buf);
1966                 if (retval)
1967                         goto err_out;
1968
1969                 retval = io_channel_write_blk64(fs->io, new_blk, 1, buf);
1970                 if (retval)
1971                         goto err_out;
1972         }
1973
1974 err_out:
1975         ext2fs_free_mem(&buf);
1976         return retval;
1977 }
1978
1979 static blk64_t translate_block(blk64_t blk)
1980 {
1981         struct list_head *entry;
1982         struct blk_move *bmv;
1983
1984         list_for_each(entry, &blk_move_list) {
1985                 bmv = list_entry(entry, struct blk_move, list);
1986                 if (bmv->old_loc == blk)
1987                         return bmv->new_loc;
1988         }
1989
1990         return 0;
1991 }
1992
1993 static int process_block(ext2_filsys fs EXT2FS_ATTR((unused)),
1994                          blk64_t *block_nr,
1995                          e2_blkcnt_t blockcnt EXT2FS_ATTR((unused)),
1996                          blk64_t ref_block EXT2FS_ATTR((unused)),
1997                          int ref_offset EXT2FS_ATTR((unused)),
1998                          void *priv_data)
1999 {
2000         int ret = 0;
2001         blk64_t new_blk;
2002         ext2fs_block_bitmap bmap = (ext2fs_block_bitmap) priv_data;
2003
2004         if (!ext2fs_test_block_bitmap2(bmap, *block_nr))
2005                 return 0;
2006         new_blk = translate_block(*block_nr);
2007         if (new_blk) {
2008                 *block_nr = new_blk;
2009                 /*
2010                  * This will force the ext2fs_write_inode in the iterator
2011                  */
2012                 ret |= BLOCK_CHANGED;
2013         }
2014
2015         return ret;
2016 }
2017
2018 static int inode_scan_and_fix(ext2_filsys fs, ext2fs_block_bitmap bmap)
2019 {
2020         errcode_t retval = 0;
2021         ext2_ino_t ino;
2022         blk64_t blk;
2023         char *block_buf = 0;
2024         struct ext2_inode inode;
2025         ext2_inode_scan scan = NULL;
2026
2027         retval = ext2fs_get_mem(fs->blocksize * 3, &block_buf);
2028         if (retval)
2029                 return retval;
2030
2031         retval = ext2fs_open_inode_scan(fs, 0, &scan);
2032         if (retval)
2033                 goto err_out;
2034
2035         while (1) {
2036                 retval = ext2fs_get_next_inode(scan, &ino, &inode);
2037                 if (retval)
2038                         goto err_out;
2039
2040                 if (!ino)
2041                         break;
2042
2043                 if (inode.i_links_count == 0)
2044                         continue; /* inode not in use */
2045
2046                 /* FIXME!!
2047                  * If we end up modifying the journal inode
2048                  * the sb->s_jnl_blocks will differ. But a
2049                  * subsequent e2fsck fixes that.
2050                  * Do we need to fix this ??
2051                  */
2052
2053                 if (ext2fs_file_acl_block(fs, &inode) &&
2054                     ext2fs_test_block_bitmap2(bmap,
2055                                         ext2fs_file_acl_block(fs, &inode))) {
2056                         blk = translate_block(ext2fs_file_acl_block(fs,
2057                                                                     &inode));
2058                         if (!blk)
2059                                 continue;
2060
2061                         ext2fs_file_acl_block_set(fs, &inode, blk);
2062
2063                         /*
2064                          * Write the inode to disk so that inode table
2065                          * resizing can work
2066                          */
2067                         retval = ext2fs_write_inode(fs, ino, &inode);
2068                         if (retval)
2069                                 goto err_out;
2070                 }
2071
2072                 if (!ext2fs_inode_has_valid_blocks2(fs, &inode))
2073                         continue;
2074
2075                 retval = ext2fs_block_iterate3(fs, ino, 0, block_buf,
2076                                                process_block, bmap);
2077                 if (retval)
2078                         goto err_out;
2079
2080         }
2081
2082 err_out:
2083         ext2fs_free_mem(&block_buf);
2084
2085         return retval;
2086 }
2087
2088 /*
2089  * We need to scan for inode and block bitmaps that may need to be
2090  * moved.  This can take place if the filesystem was formatted for
2091  * RAID arrays using the mke2fs's extended option "stride".
2092  */
2093 static int group_desc_scan_and_fix(ext2_filsys fs, ext2fs_block_bitmap bmap)
2094 {
2095         dgrp_t i;
2096         blk64_t blk, new_blk;
2097
2098         for (i = 0; i < fs->group_desc_count; i++) {
2099                 blk = ext2fs_block_bitmap_loc(fs, i);
2100                 if (ext2fs_test_block_bitmap2(bmap, blk)) {
2101                         new_blk = translate_block(blk);
2102                         if (!new_blk)
2103                                 continue;
2104                         ext2fs_block_bitmap_loc_set(fs, i, new_blk);
2105                 }
2106
2107                 blk = ext2fs_inode_bitmap_loc(fs, i);
2108                 if (ext2fs_test_block_bitmap2(bmap, blk)) {
2109                         new_blk = translate_block(blk);
2110                         if (!new_blk)
2111                                 continue;
2112                         ext2fs_inode_bitmap_loc_set(fs, i, new_blk);
2113                 }
2114         }
2115         return 0;
2116 }
2117
2118 static int expand_inode_table(ext2_filsys fs, unsigned long new_ino_size)
2119 {
2120         dgrp_t i;
2121         blk64_t blk;
2122         errcode_t retval;
2123         int new_ino_blks_per_grp;
2124         unsigned int j;
2125         char *old_itable = NULL, *new_itable = NULL;
2126         char *tmp_old_itable = NULL, *tmp_new_itable = NULL;
2127         unsigned long old_ino_size;
2128         int old_itable_size, new_itable_size;
2129
2130         old_itable_size = fs->inode_blocks_per_group * fs->blocksize;
2131         old_ino_size = EXT2_INODE_SIZE(fs->super);
2132
2133         new_ino_blks_per_grp = ext2fs_div_ceil(
2134                                         EXT2_INODES_PER_GROUP(fs->super) *
2135                                         new_ino_size,
2136                                         fs->blocksize);
2137
2138         new_itable_size = new_ino_blks_per_grp * fs->blocksize;
2139
2140         retval = ext2fs_get_mem(old_itable_size, &old_itable);
2141         if (retval)
2142                 return retval;
2143
2144         retval = ext2fs_get_mem(new_itable_size, &new_itable);
2145         if (retval)
2146                 goto err_out;
2147
2148         tmp_old_itable = old_itable;
2149         tmp_new_itable = new_itable;
2150
2151         for (i = 0; i < fs->group_desc_count; i++) {
2152                 blk = ext2fs_inode_table_loc(fs, i);
2153                 retval = io_channel_read_blk64(fs->io, blk,
2154                                 fs->inode_blocks_per_group, old_itable);
2155                 if (retval)
2156                         goto err_out;
2157
2158                 for (j = 0; j < EXT2_INODES_PER_GROUP(fs->super); j++) {
2159                         memcpy(new_itable, old_itable, old_ino_size);
2160
2161                         memset(new_itable+old_ino_size, 0,
2162                                         new_ino_size - old_ino_size);
2163
2164                         new_itable += new_ino_size;
2165                         old_itable += old_ino_size;
2166                 }
2167
2168                 /* reset the pointer */
2169                 old_itable = tmp_old_itable;
2170                 new_itable = tmp_new_itable;
2171
2172                 retval = io_channel_write_blk64(fs->io, blk,
2173                                         new_ino_blks_per_grp, new_itable);
2174                 if (retval)
2175                         goto err_out;
2176         }
2177
2178         /* Update the meta data */
2179         fs->inode_blocks_per_group = new_ino_blks_per_grp;
2180         fs->super->s_inode_size = new_ino_size;
2181
2182 err_out:
2183         if (old_itable)
2184                 ext2fs_free_mem(&old_itable);
2185
2186         if (new_itable)
2187                 ext2fs_free_mem(&new_itable);
2188
2189         return retval;
2190 }
2191
2192 static errcode_t ext2fs_calculate_summary_stats(ext2_filsys fs)
2193 {
2194         blk64_t         blk;
2195         ext2_ino_t      ino;
2196         unsigned int    group = 0;
2197         unsigned int    count = 0;
2198         int             total_free = 0;
2199         int             group_free = 0;
2200
2201         /*
2202          * First calculate the block statistics
2203          */
2204         for (blk = fs->super->s_first_data_block;
2205              blk < ext2fs_blocks_count(fs->super); blk++) {
2206                 if (!ext2fs_fast_test_block_bitmap2(fs->block_map, blk)) {
2207                         group_free++;
2208                         total_free++;
2209                 }
2210                 count++;
2211                 if ((count == fs->super->s_blocks_per_group) ||
2212                     (blk == ext2fs_blocks_count(fs->super)-1)) {
2213                         ext2fs_bg_free_blocks_count_set(fs, group++,
2214                                                         group_free);
2215                         count = 0;
2216                         group_free = 0;
2217                 }
2218         }
2219         total_free = EXT2FS_C2B(fs, total_free);
2220         ext2fs_free_blocks_count_set(fs->super, total_free);
2221
2222         /*
2223          * Next, calculate the inode statistics
2224          */
2225         group_free = 0;
2226         total_free = 0;
2227         count = 0;
2228         group = 0;
2229
2230         /* Protect loop from wrap-around if s_inodes_count maxed */
2231         for (ino = 1; ino <= fs->super->s_inodes_count && ino > 0; ino++) {
2232                 if (!ext2fs_fast_test_inode_bitmap2(fs->inode_map, ino)) {
2233                         group_free++;
2234                         total_free++;
2235                 }
2236                 count++;
2237                 if ((count == fs->super->s_inodes_per_group) ||
2238                     (ino == fs->super->s_inodes_count)) {
2239                         ext2fs_bg_free_inodes_count_set(fs, group++,
2240                                                         group_free);
2241                         count = 0;
2242                         group_free = 0;
2243                 }
2244         }
2245         fs->super->s_free_inodes_count = total_free;
2246         ext2fs_mark_super_dirty(fs);
2247         return 0;
2248 }
2249
2250 #define list_for_each_safe(pos, pnext, head) \
2251         for (pos = (head)->next, pnext = pos->next; pos != (head); \
2252              pos = pnext, pnext = pos->next)
2253
2254 static void free_blk_move_list(void)
2255 {
2256         struct list_head *entry, *tmp;
2257         struct blk_move *bmv;
2258
2259         list_for_each_safe(entry, tmp, &blk_move_list) {
2260                 bmv = list_entry(entry, struct blk_move, list);
2261                 list_del(entry);
2262                 ext2fs_free_mem(&bmv);
2263         }
2264         return;
2265 }
2266
2267 static int resize_inode(ext2_filsys fs, unsigned long new_size)
2268 {
2269         errcode_t retval;
2270         int new_ino_blks_per_grp;
2271         ext2fs_block_bitmap bmap;
2272
2273         retval = ext2fs_read_inode_bitmap(fs);
2274         if (retval) {
2275                 fputs(_("Failed to read inode bitmap\n"), stderr);
2276                 return retval;
2277         }
2278         retval = ext2fs_read_block_bitmap(fs);
2279         if (retval) {
2280                 fputs(_("Failed to read block bitmap\n"), stderr);
2281                 return retval;
2282         }
2283         INIT_LIST_HEAD(&blk_move_list);
2284
2285
2286         new_ino_blks_per_grp = ext2fs_div_ceil(
2287                                         EXT2_INODES_PER_GROUP(fs->super)*
2288                                         new_size,
2289                                         fs->blocksize);
2290
2291         /* We may change the file system.
2292          * Mark the file system as invalid so that
2293          * the user is prompted to run fsck.
2294          */
2295         fs->super->s_state &= ~EXT2_VALID_FS;
2296
2297         retval = ext2fs_allocate_block_bitmap(fs, _("blocks to be moved"),
2298                                                 &bmap);
2299         if (retval) {
2300                 fputs(_("Failed to allocate block bitmap when "
2301                                 "increasing inode size\n"), stderr);
2302                 return retval;
2303         }
2304         retval = get_move_bitmaps(fs, new_ino_blks_per_grp, bmap);
2305         if (retval) {
2306                 fputs(_("Not enough space to increase inode size \n"), stderr);
2307                 goto err_out;
2308         }
2309         retval = move_block(fs, bmap);
2310         if (retval) {
2311                 fputs(_("Failed to relocate blocks during inode resize \n"),
2312                       stderr);
2313                 goto err_out;
2314         }
2315         retval = inode_scan_and_fix(fs, bmap);
2316         if (retval)
2317                 goto err_out_undo;
2318
2319         retval = group_desc_scan_and_fix(fs, bmap);
2320         if (retval)
2321                 goto err_out_undo;
2322
2323         retval = expand_inode_table(fs, new_size);
2324         if (retval)
2325                 goto err_out_undo;
2326
2327         ext2fs_calculate_summary_stats(fs);
2328
2329         fs->super->s_state |= EXT2_VALID_FS;
2330         /* mark super block and block bitmap as dirty */
2331         ext2fs_mark_super_dirty(fs);
2332         ext2fs_mark_bb_dirty(fs);
2333
2334 err_out:
2335         free_blk_move_list();
2336         ext2fs_free_block_bitmap(bmap);
2337
2338         return retval;
2339
2340 err_out_undo:
2341         free_blk_move_list();
2342         ext2fs_free_block_bitmap(bmap);
2343         fputs(_("Error in resizing the inode size.\n"
2344                         "Run e2undo to undo the "
2345                         "file system changes. \n"), stderr);
2346
2347         return retval;
2348 }
2349
2350 static int tune2fs_setup_tdb(const char *name, io_manager *io_ptr)
2351 {
2352         errcode_t retval = 0;
2353         const char *tdb_dir;
2354         char *tdb_file;
2355         char *dev_name, *tmp_name;
2356
2357 #if 0 /* FIXME!! */
2358         /*
2359          * Configuration via a conf file would be
2360          * nice
2361          */
2362         profile_get_string(profile, "scratch_files",
2363                                         "directory", 0, 0,
2364                                         &tdb_dir);
2365 #endif
2366         tmp_name = strdup(name);
2367         if (!tmp_name) {
2368         alloc_fn_fail:
2369                 com_err(program_name, ENOMEM, "%s",
2370                         _("Couldn't allocate memory for tdb filename\n"));
2371                 return ENOMEM;
2372         }
2373         dev_name = basename(tmp_name);
2374
2375         tdb_dir = getenv("E2FSPROGS_UNDO_DIR");
2376         if (!tdb_dir)
2377                 tdb_dir = "/var/lib/e2fsprogs";
2378
2379         if (!strcmp(tdb_dir, "none") || (tdb_dir[0] == 0) ||
2380             access(tdb_dir, W_OK))
2381                 return 0;
2382
2383         tdb_file = malloc(strlen(tdb_dir) + 9 + strlen(dev_name) + 7 + 1);
2384         if (!tdb_file)
2385                 goto alloc_fn_fail;
2386         sprintf(tdb_file, "%s/tune2fs-%s.e2undo", tdb_dir, dev_name);
2387
2388         if ((unlink(tdb_file) < 0) && (errno != ENOENT)) {
2389                 retval = errno;
2390                 com_err(program_name, retval,
2391                         _("while trying to delete %s"), tdb_file);
2392                 free(tdb_file);
2393                 return retval;
2394         }
2395
2396         set_undo_io_backing_manager(*io_ptr);
2397         *io_ptr = undo_io_manager;
2398         set_undo_io_backup_file(tdb_file);
2399         printf(_("To undo the tune2fs operation please run "
2400                  "the command\n    e2undo %s %s\n\n"),
2401                  tdb_file, name);
2402         free(tdb_file);
2403         free(tmp_name);
2404         return retval;
2405 }
2406
2407 int main(int argc, char **argv)
2408 {
2409         errcode_t retval;
2410         ext2_filsys fs;
2411         struct ext2_super_block *sb;
2412         io_manager io_ptr, io_ptr_orig = NULL;
2413         int rc = 0;
2414
2415 #ifdef ENABLE_NLS
2416         setlocale(LC_MESSAGES, "");
2417         setlocale(LC_CTYPE, "");
2418         bindtextdomain(NLS_CAT_NAME, LOCALEDIR);
2419         textdomain(NLS_CAT_NAME);
2420         set_com_err_gettext(gettext);
2421 #endif
2422         if (argc && *argv)
2423                 program_name = *argv;
2424         add_error_table(&et_ext2_error_table);
2425
2426 #ifdef CONFIG_BUILD_FINDFS
2427         if (strcmp(get_progname(argv[0]), "findfs") == 0)
2428                 do_findfs(argc, argv);
2429 #endif
2430         if (strcmp(get_progname(argv[0]), "e2label") == 0)
2431                 parse_e2label_options(argc, argv);
2432         else
2433                 parse_tune2fs_options(argc, argv);
2434
2435 #ifdef CONFIG_TESTIO_DEBUG
2436         if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_DEBUG")) {
2437                 io_ptr = test_io_manager;
2438                 test_io_backing_manager = unix_io_manager;
2439         } else
2440 #endif
2441                 io_ptr = unix_io_manager;
2442
2443 retry_open:
2444         if ((open_flag & EXT2_FLAG_RW) == 0 || f_flag)
2445                 open_flag |= EXT2_FLAG_SKIP_MMP;
2446
2447         open_flag |= EXT2_FLAG_64BITS;
2448
2449         /* keep the filesystem struct around to dump MMP data */
2450         open_flag |= EXT2_FLAG_NOFREE_ON_ERROR;
2451
2452         retval = ext2fs_open2(device_name, io_options, open_flag,
2453                               0, 0, io_ptr, &fs);
2454         if (retval) {
2455                 com_err(program_name, retval,
2456                         _("while trying to open %s"),
2457                         device_name);
2458                 if (retval == EXT2_ET_MMP_FSCK_ON ||
2459                     retval == EXT2_ET_MMP_UNKNOWN_SEQ)
2460                         dump_mmp_msg(fs->mmp_buf,
2461                                      _("If you are sure the filesystem "
2462                                        "is not in use on any node, run:\n"
2463                                        "'tune2fs -f -E clear_mmp {device}'\n"));
2464                 else if (retval == EXT2_ET_MMP_FAILED)
2465                         dump_mmp_msg(fs->mmp_buf, NULL);
2466                 else if (retval == EXT2_ET_MMP_MAGIC_INVALID)
2467                         fprintf(stderr,
2468                                 _("MMP block magic is bad. Try to fix it by "
2469                                   "running:\n'e2fsck -f %s'\n"), device_name);
2470                 else if (retval != EXT2_ET_MMP_FAILED)
2471                         fprintf(stderr, "%s",
2472                              _("Couldn't find valid filesystem superblock.\n"));
2473
2474                 ext2fs_free(fs);
2475                 exit(1);
2476         }
2477         fs->default_bitmap_type = EXT2FS_BMAP64_RBTREE;
2478
2479         if (I_flag && !io_ptr_orig) {
2480                 /*
2481                  * Check the inode size is right so we can issue an
2482                  * error message and bail before setting up the tdb
2483                  * file.
2484                  */
2485                 if (new_inode_size == EXT2_INODE_SIZE(fs->super)) {
2486                         fprintf(stderr, _("The inode size is already %lu\n"),
2487                                 new_inode_size);
2488                         rc = 1;
2489                         goto closefs;
2490                 }
2491                 if (new_inode_size < EXT2_INODE_SIZE(fs->super)) {
2492                         fprintf(stderr, "%s",
2493                                 _("Shrinking inode size is not supported\n"));
2494                         rc = 1;
2495                         goto closefs;
2496                 }
2497                 if (new_inode_size > fs->blocksize) {
2498                         fprintf(stderr, _("Invalid inode size %lu (max %d)\n"),
2499                                 new_inode_size, fs->blocksize);
2500                         rc = 1;
2501                         goto closefs;
2502                 }
2503
2504                 /*
2505                  * If inode resize is requested use the
2506                  * Undo I/O manager
2507                  */
2508                 io_ptr_orig = io_ptr;
2509                 retval = tune2fs_setup_tdb(device_name, &io_ptr);
2510                 if (retval) {
2511                         rc = 1;
2512                         goto closefs;
2513                 }
2514                 if (io_ptr != io_ptr_orig) {
2515                         ext2fs_close(fs);
2516                         goto retry_open;
2517                 }
2518         }
2519
2520         sb = fs->super;
2521         fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
2522
2523         if (print_label) {
2524                 /* For e2label emulation */
2525                 printf("%.*s\n", (int) sizeof(sb->s_volume_name),
2526                        sb->s_volume_name);
2527                 remove_error_table(&et_ext2_error_table);
2528                 goto closefs;
2529         }
2530
2531         retval = ext2fs_check_if_mounted(device_name, &mount_flags);
2532         if (retval) {
2533                 com_err("ext2fs_check_if_mount", retval,
2534                         _("while determining whether %s is mounted."),
2535                         device_name);
2536                 rc = 1;
2537                 goto closefs;
2538         }
2539         /* Normally we only need to write out the superblock */
2540         fs->flags |= EXT2_FLAG_SUPER_ONLY;
2541
2542         if (c_flag) {
2543                 sb->s_max_mnt_count = max_mount_count;
2544                 ext2fs_mark_super_dirty(fs);
2545                 printf(_("Setting maximal mount count to %d\n"),
2546                        max_mount_count);
2547         }
2548         if (C_flag) {
2549                 sb->s_mnt_count = mount_count;
2550                 ext2fs_mark_super_dirty(fs);
2551                 printf(_("Setting current mount count to %d\n"), mount_count);
2552         }
2553         if (e_flag) {
2554                 sb->s_errors = errors;
2555                 ext2fs_mark_super_dirty(fs);
2556                 printf(_("Setting error behavior to %d\n"), errors);
2557         }
2558         if (g_flag) {
2559                 sb->s_def_resgid = resgid;
2560                 ext2fs_mark_super_dirty(fs);
2561                 printf(_("Setting reserved blocks gid to %lu\n"), resgid);
2562         }
2563         if (i_flag) {
2564                 if ((unsigned long long)interval >= (1ULL << 32)) {
2565                         com_err(program_name, 0,
2566                                 _("interval between checks is too big (%lu)"),
2567                                 interval);
2568                         rc = 1;
2569                         goto closefs;
2570                 }
2571                 sb->s_checkinterval = interval;
2572                 ext2fs_mark_super_dirty(fs);
2573                 printf(_("Setting interval between checks to %lu seconds\n"),
2574                        interval);
2575         }
2576         if (m_flag) {
2577                 ext2fs_r_blocks_count_set(sb, reserved_ratio *
2578                                           ext2fs_blocks_count(sb) / 100.0);
2579                 ext2fs_mark_super_dirty(fs);
2580                 printf (_("Setting reserved blocks percentage to %g%% (%llu blocks)\n"),
2581                         reserved_ratio, ext2fs_r_blocks_count(sb));
2582         }
2583         if (r_flag) {
2584                 if (reserved_blocks > ext2fs_blocks_count(sb)/2) {
2585                         com_err(program_name, 0,
2586                                 _("reserved blocks count is too big (%llu)"),
2587                                 reserved_blocks);
2588                         rc = 1;
2589                         goto closefs;
2590                 }
2591                 ext2fs_r_blocks_count_set(sb, reserved_blocks);
2592                 ext2fs_mark_super_dirty(fs);
2593                 printf(_("Setting reserved blocks count to %llu\n"),
2594                        reserved_blocks);
2595         }
2596         if (s_flag == 1) {
2597                 if (sb->s_feature_ro_compat &
2598                     EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER) {
2599                         fputs(_("\nThe filesystem already has sparse "
2600                                 "superblocks.\n"), stderr);
2601                 } else if (sb->s_feature_incompat &
2602                         EXT2_FEATURE_INCOMPAT_META_BG) {
2603                         fputs(_("\nSetting the sparse superblock flag not "
2604                                 "supported\nfor filesystems with "
2605                                 "the meta_bg feature enabled.\n"),
2606                                 stderr);
2607                         rc = 1;
2608                         goto closefs;
2609                 } else {
2610                         sb->s_feature_ro_compat |=
2611                                 EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER;
2612                         sb->s_state &= ~EXT2_VALID_FS;
2613                         ext2fs_mark_super_dirty(fs);
2614                         printf(_("\nSparse superblock flag set.  %s"),
2615                                _(please_fsck));
2616                 }
2617         }
2618         if (s_flag == 0) {
2619                 fputs(_("\nClearing the sparse superblock flag not supported.\n"),
2620                       stderr);
2621                 rc = 1;
2622                 goto closefs;
2623         }
2624         if (T_flag) {
2625                 sb->s_lastcheck = last_check_time;
2626                 ext2fs_mark_super_dirty(fs);
2627                 printf(_("Setting time filesystem last checked to %s\n"),
2628                        ctime(&last_check_time));
2629         }
2630         if (u_flag) {
2631                 sb->s_def_resuid = resuid;
2632                 ext2fs_mark_super_dirty(fs);
2633                 printf(_("Setting reserved blocks uid to %lu\n"), resuid);
2634         }
2635         if (L_flag) {
2636                 if (strlen(new_label) > sizeof(sb->s_volume_name))
2637                         fputs(_("Warning: label too long, truncating.\n"),
2638                               stderr);
2639                 memset(sb->s_volume_name, 0, sizeof(sb->s_volume_name));
2640                 strncpy(sb->s_volume_name, new_label,
2641                         sizeof(sb->s_volume_name));
2642                 ext2fs_mark_super_dirty(fs);
2643         }
2644         if (M_flag) {
2645                 memset(sb->s_last_mounted, 0, sizeof(sb->s_last_mounted));
2646                 strncpy(sb->s_last_mounted, new_last_mounted,
2647                         sizeof(sb->s_last_mounted));
2648                 ext2fs_mark_super_dirty(fs);
2649         }
2650         if (mntopts_cmd) {
2651                 rc = update_mntopts(fs, mntopts_cmd);
2652                 if (rc)
2653                         goto closefs;
2654         }
2655         if (features_cmd) {
2656                 rc = update_feature_set(fs, features_cmd);
2657                 if (rc)
2658                         goto closefs;
2659         }
2660         if (extended_cmd) {
2661                 rc = parse_extended_opts(fs, extended_cmd);
2662                 if (rc)
2663                         goto closefs;
2664                 if (clear_mmp && !f_flag) {
2665                         fputs(_("Error in using clear_mmp. "
2666                                 "It must be used with -f\n"),
2667                               stderr);
2668                         goto closefs;
2669                 }
2670         }
2671         if (clear_mmp) {
2672                 rc = ext2fs_mmp_clear(fs);
2673                 goto closefs;
2674         }
2675         if (journal_size || journal_device) {
2676                 rc = add_journal(fs);
2677                 if (rc)
2678                         goto closefs;
2679         }
2680
2681         if (Q_flag) {
2682                 if (mount_flags & EXT2_MF_MOUNTED) {
2683                         fputs(_("The quota feature may only be changed when "
2684                                 "the filesystem is unmounted.\n"), stderr);
2685                         rc = 1;
2686                         goto closefs;
2687                 }
2688                 handle_quota_options(fs);
2689         }
2690
2691         if (U_flag) {
2692                 int set_csum = 0;
2693                 dgrp_t i;
2694
2695                 if (ext2fs_has_group_desc_csum(fs)) {
2696                         /*
2697                          * Changing the UUID requires rewriting all metadata,
2698                          * which can race with a mounted fs.  Don't allow that.
2699                          */
2700                         if (mount_flags & EXT2_MF_MOUNTED) {
2701                                 fputs(_("The UUID may only be "
2702                                         "changed when the filesystem is "
2703                                         "unmounted.\n"), stderr);
2704                                 exit(1);
2705                         }
2706                         if (check_fsck_needed(fs))
2707                                 exit(1);
2708
2709                         /*
2710                          * Determine if the block group checksums are
2711                          * correct so we know whether or not to set
2712                          * them later on.
2713                          */
2714                         for (i = 0; i < fs->group_desc_count; i++)
2715                                 if (!ext2fs_group_desc_csum_verify(fs, i))
2716                                         break;
2717                         if (i >= fs->group_desc_count)
2718                                 set_csum = 1;
2719                 }
2720                 if ((strcasecmp(new_UUID, "null") == 0) ||
2721                     (strcasecmp(new_UUID, "clear") == 0)) {
2722                         uuid_clear(sb->s_uuid);
2723                 } else if (strcasecmp(new_UUID, "time") == 0) {
2724                         uuid_generate_time(sb->s_uuid);
2725                 } else if (strcasecmp(new_UUID, "random") == 0) {
2726                         uuid_generate(sb->s_uuid);
2727                 } else if (uuid_parse(new_UUID, sb->s_uuid)) {
2728                         com_err(program_name, 0, "%s",
2729                                 _("Invalid UUID format\n"));
2730                         rc = 1;
2731                         goto closefs;
2732                 }
2733                 ext2fs_init_csum_seed(fs);
2734                 if (set_csum) {
2735                         for (i = 0; i < fs->group_desc_count; i++)
2736                                 ext2fs_group_desc_csum_set(fs, i);
2737                         fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
2738                 }
2739                 ext2fs_mark_super_dirty(fs);
2740                 if (EXT2_HAS_RO_COMPAT_FEATURE(fs->super,
2741                                 EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
2742                         rewrite_checksums = 1;
2743         }
2744         if (rewrite_checksums)
2745                 rewrite_metadata_checksums(fs);
2746         if (I_flag) {
2747                 if (mount_flags & EXT2_MF_MOUNTED) {
2748                         fputs(_("The inode size may only be "
2749                                 "changed when the filesystem is "
2750                                 "unmounted.\n"), stderr);
2751                         rc = 1;
2752                         goto closefs;
2753                 }
2754                 if (fs->super->s_feature_incompat &
2755                     EXT4_FEATURE_INCOMPAT_FLEX_BG) {
2756                         fputs(_("Changing the inode size not supported for "
2757                                 "filesystems with the flex_bg\n"
2758                                 "feature enabled.\n"),
2759                               stderr);
2760                         rc = 1;
2761                         goto closefs;
2762                 }
2763                 /*
2764                  * We want to update group descriptor also
2765                  * with the new free inode count
2766                  */
2767                 fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
2768                 if (resize_inode(fs, new_inode_size) == 0) {
2769                         printf(_("Setting inode size %lu\n"),
2770                                                         new_inode_size);
2771                 } else {
2772                         printf("%s", _("Failed to change inode size\n"));
2773                         rc = 1;
2774                         goto closefs;
2775                 }
2776         }
2777
2778         if (l_flag)
2779                 list_super(sb);
2780         if (stride_set) {
2781                 sb->s_raid_stride = stride;
2782                 ext2fs_mark_super_dirty(fs);
2783                 printf(_("Setting stride size to %d\n"), stride);
2784         }
2785         if (stripe_width_set) {
2786                 sb->s_raid_stripe_width = stripe_width;
2787                 ext2fs_mark_super_dirty(fs);
2788                 printf(_("Setting stripe width to %d\n"), stripe_width);
2789         }
2790         if (ext_mount_opts) {
2791                 strncpy((char *)(fs->super->s_mount_opts), ext_mount_opts,
2792                         sizeof(fs->super->s_mount_opts));
2793                 fs->super->s_mount_opts[sizeof(fs->super->s_mount_opts)-1] = 0;
2794                 ext2fs_mark_super_dirty(fs);
2795                 printf(_("Setting extended default mount options to '%s'\n"),
2796                        ext_mount_opts);
2797                 free(ext_mount_opts);
2798         }
2799         free(device_name);
2800         remove_error_table(&et_ext2_error_table);
2801
2802 closefs:
2803         if (rc) {
2804                 ext2fs_mmp_stop(fs);
2805                 exit(1);
2806         }
2807
2808         return (ext2fs_close(fs) ? 1 : 0);
2809 }