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