Whamcloud - gitweb
tune2fs: fix quota feature removal
[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
95 int journal_size, journal_flags;
96 char *journal_device;
97
98 static struct list_head blk_move_list;
99
100 struct blk_move {
101         struct list_head list;
102         blk64_t old_loc;
103         blk64_t new_loc;
104 };
105
106
107 static const char *please_fsck = N_("Please run e2fsck on the filesystem.\n");
108
109 #ifdef CONFIG_BUILD_FINDFS
110 void do_findfs(int argc, char **argv);
111 #endif
112
113 static void usage(void)
114 {
115         fprintf(stderr,
116                 _("Usage: %s [-c max_mounts_count] [-e errors_behavior] "
117                   "[-g group]\n"
118                   "\t[-i interval[d|m|w]] [-j] [-J journal_options] [-l]\n"
119                   "\t[-m reserved_blocks_percent] "
120                   "[-o [^]mount_options[,...]] [-p mmp_update_interval]\n"
121                   "\t[-r reserved_blocks_count] [-u user] [-C mount_count] "
122                   "[-L volume_label]\n"
123                   "\t[-M last_mounted_dir] [-O [^]feature[,...]]\n"
124                   "\t[-E extended-option[,...]] [-T last_check_time] "
125                   "[-U UUID]\n\t[ -I new_inode_size ] device\n"), program_name);
126         exit(1);
127 }
128
129 static __u32 ok_features[3] = {
130         /* Compat */
131         EXT3_FEATURE_COMPAT_HAS_JOURNAL |
132                 EXT2_FEATURE_COMPAT_DIR_INDEX,
133         /* Incompat */
134         EXT2_FEATURE_INCOMPAT_FILETYPE |
135                 EXT3_FEATURE_INCOMPAT_EXTENTS |
136                 EXT4_FEATURE_INCOMPAT_FLEX_BG |
137                 EXT4_FEATURE_INCOMPAT_MMP,
138         /* R/O compat */
139         EXT2_FEATURE_RO_COMPAT_LARGE_FILE |
140                 EXT4_FEATURE_RO_COMPAT_HUGE_FILE|
141                 EXT4_FEATURE_RO_COMPAT_DIR_NLINK|
142                 EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE|
143                 EXT4_FEATURE_RO_COMPAT_GDT_CSUM |
144                 EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER |
145                 EXT4_FEATURE_RO_COMPAT_QUOTA
146 };
147
148 static __u32 clear_ok_features[3] = {
149         /* Compat */
150         EXT3_FEATURE_COMPAT_HAS_JOURNAL |
151                 EXT2_FEATURE_COMPAT_RESIZE_INODE |
152                 EXT2_FEATURE_COMPAT_DIR_INDEX,
153         /* Incompat */
154         EXT2_FEATURE_INCOMPAT_FILETYPE |
155                 EXT4_FEATURE_INCOMPAT_FLEX_BG |
156                 EXT4_FEATURE_INCOMPAT_MMP,
157         /* R/O compat */
158         EXT2_FEATURE_RO_COMPAT_LARGE_FILE |
159                 EXT4_FEATURE_RO_COMPAT_HUGE_FILE|
160                 EXT4_FEATURE_RO_COMPAT_DIR_NLINK|
161                 EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE|
162                 EXT4_FEATURE_RO_COMPAT_GDT_CSUM |
163                 EXT4_FEATURE_RO_COMPAT_QUOTA
164 };
165
166 /*
167  * Remove an external journal from the filesystem
168  */
169 static int remove_journal_device(ext2_filsys fs)
170 {
171         char            *journal_path;
172         ext2_filsys     jfs;
173         char            buf[1024];
174         journal_superblock_t    *jsb;
175         int             i, nr_users;
176         errcode_t       retval;
177         int             commit_remove_journal = 0;
178         io_manager      io_ptr;
179
180         if (f_flag)
181                 commit_remove_journal = 1; /* force removal even if error */
182
183         uuid_unparse(fs->super->s_journal_uuid, buf);
184         journal_path = blkid_get_devname(NULL, "UUID", buf);
185
186         if (!journal_path) {
187                 journal_path =
188                         ext2fs_find_block_device(fs->super->s_journal_dev);
189                 if (!journal_path)
190                         goto no_valid_journal;
191         }
192
193 #ifdef CONFIG_TESTIO_DEBUG
194         if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_BLOCK")) {
195                 io_ptr = test_io_manager;
196                 test_io_backing_manager = unix_io_manager;
197         } else
198 #endif
199                 io_ptr = unix_io_manager;
200         retval = ext2fs_open(journal_path, EXT2_FLAG_RW|
201                              EXT2_FLAG_JOURNAL_DEV_OK, 0,
202                              fs->blocksize, io_ptr, &jfs);
203         if (retval) {
204                 com_err(program_name, retval,
205                         _("while trying to open external journal"));
206                 goto no_valid_journal;
207         }
208         if (!(jfs->super->s_feature_incompat &
209               EXT3_FEATURE_INCOMPAT_JOURNAL_DEV)) {
210                 fprintf(stderr, _("%s is not a journal device.\n"),
211                         journal_path);
212                 goto no_valid_journal;
213         }
214
215         /* Get the journal superblock */
216         if ((retval = io_channel_read_blk64(jfs->io, 1, -1024, buf))) {
217                 com_err(program_name, retval,
218                         _("while reading journal superblock"));
219                 goto no_valid_journal;
220         }
221
222         jsb = (journal_superblock_t *) buf;
223         if ((jsb->s_header.h_magic != (unsigned)ntohl(JFS_MAGIC_NUMBER)) ||
224             (jsb->s_header.h_blocktype != (unsigned)ntohl(JFS_SUPERBLOCK_V2))) {
225                 fputs(_("Journal superblock not found!\n"), stderr);
226                 goto no_valid_journal;
227         }
228
229         /* Find the filesystem UUID */
230         nr_users = ntohl(jsb->s_nr_users);
231         for (i = 0; i < nr_users; i++) {
232                 if (memcmp(fs->super->s_uuid, &jsb->s_users[i * 16], 16) == 0)
233                         break;
234         }
235         if (i >= nr_users) {
236                 fputs(_("Filesystem's UUID not found on journal device.\n"),
237                       stderr);
238                 commit_remove_journal = 1;
239                 goto no_valid_journal;
240         }
241         nr_users--;
242         for (i = 0; i < nr_users; i++)
243                 memcpy(&jsb->s_users[i * 16], &jsb->s_users[(i + 1) * 16], 16);
244         jsb->s_nr_users = htonl(nr_users);
245
246         /* Write back the journal superblock */
247         if ((retval = io_channel_write_blk64(jfs->io, 1, -1024, buf))) {
248                 com_err(program_name, retval,
249                         "while writing journal superblock.");
250                 goto no_valid_journal;
251         }
252
253         commit_remove_journal = 1;
254
255 no_valid_journal:
256         if (commit_remove_journal == 0) {
257                 fputs(_("Cannot locate journal device. It was NOT removed\n"
258                         "Use -f option to remove missing journal device.\n"),
259                       stderr);
260                 return 1;
261         }
262         fs->super->s_journal_dev = 0;
263         uuid_clear(fs->super->s_journal_uuid);
264         ext2fs_mark_super_dirty(fs);
265         fputs(_("Journal removed\n"), stdout);
266         free(journal_path);
267
268         return 0;
269 }
270
271 /* Helper function for remove_journal_inode */
272 static int release_blocks_proc(ext2_filsys fs, blk64_t *blocknr,
273                                e2_blkcnt_t blockcnt EXT2FS_ATTR((unused)),
274                                blk64_t ref_block EXT2FS_ATTR((unused)),
275                                int ref_offset EXT2FS_ATTR((unused)),
276                                void *private EXT2FS_ATTR((unused)))
277 {
278         blk64_t block;
279         int     group;
280
281         block = *blocknr;
282         ext2fs_unmark_block_bitmap2(fs->block_map, block);
283         group = ext2fs_group_of_blk2(fs, block);
284         ext2fs_bg_free_blocks_count_set(fs, group, ext2fs_bg_free_blocks_count(fs, group) + 1);
285         ext2fs_group_desc_csum_set(fs, group);
286         ext2fs_free_blocks_count_add(fs->super, EXT2FS_CLUSTER_RATIO(fs));
287         return 0;
288 }
289
290 /*
291  * Remove the journal inode from the filesystem
292  */
293 static errcode_t remove_journal_inode(ext2_filsys fs)
294 {
295         struct ext2_inode       inode;
296         errcode_t               retval;
297         ino_t                   ino = fs->super->s_journal_inum;
298
299         retval = ext2fs_read_inode(fs, ino,  &inode);
300         if (retval) {
301                 com_err(program_name, retval,
302                         _("while reading journal inode"));
303                 return retval;
304         }
305         if (ino == EXT2_JOURNAL_INO) {
306                 retval = ext2fs_read_bitmaps(fs);
307                 if (retval) {
308                         com_err(program_name, retval,
309                                 _("while reading bitmaps"));
310                         return retval;
311                 }
312                 retval = ext2fs_block_iterate3(fs, ino,
313                                                BLOCK_FLAG_READ_ONLY, NULL,
314                                                release_blocks_proc, NULL);
315                 if (retval) {
316                         com_err(program_name, retval,
317                                 _("while clearing journal inode"));
318                         return retval;
319                 }
320                 memset(&inode, 0, sizeof(inode));
321                 ext2fs_mark_bb_dirty(fs);
322                 fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
323         } else
324                 inode.i_flags &= ~EXT2_IMMUTABLE_FL;
325         retval = ext2fs_write_inode(fs, ino, &inode);
326         if (retval) {
327                 com_err(program_name, retval,
328                         _("while writing journal inode"));
329                 return retval;
330         }
331         fs->super->s_journal_inum = 0;
332         ext2fs_mark_super_dirty(fs);
333
334         return 0;
335 }
336
337 /*
338  * Update the default mount options
339  */
340 static int update_mntopts(ext2_filsys fs, char *mntopts)
341 {
342         struct ext2_super_block *sb = fs->super;
343
344         if (e2p_edit_mntopts(mntopts, &sb->s_default_mount_opts, ~0)) {
345                 fprintf(stderr, _("Invalid mount option set: %s\n"),
346                         mntopts);
347                 return 1;
348         }
349         ext2fs_mark_super_dirty(fs);
350
351         return 0;
352 }
353
354 static void request_fsck_afterwards(ext2_filsys fs)
355 {
356         static int requested = 0;
357
358         if (requested++)
359                 return;
360         fs->super->s_state &= ~EXT2_VALID_FS;
361         printf("\n%s\n", _(please_fsck));
362         if (mount_flags & EXT2_MF_READONLY)
363                 printf(_("(and reboot afterwards!)\n"));
364 }
365
366 /*
367  * Update the feature set as provided by the user.
368  */
369 static int update_feature_set(ext2_filsys fs, char *features)
370 {
371         struct ext2_super_block *sb = fs->super;
372         struct ext2_group_desc *gd;
373         __u32           old_features[3];
374         int             i, type_err;
375         unsigned int    mask_err;
376
377 #define FEATURE_ON(type, mask) (!(old_features[(type)] & (mask)) && \
378                                 ((&sb->s_feature_compat)[(type)] & (mask)))
379 #define FEATURE_OFF(type, mask) ((old_features[(type)] & (mask)) && \
380                                  !((&sb->s_feature_compat)[(type)] & (mask)))
381 #define FEATURE_CHANGED(type, mask) ((mask) & \
382                      (old_features[(type)] ^ (&sb->s_feature_compat)[(type)]))
383
384         old_features[E2P_FEATURE_COMPAT] = sb->s_feature_compat;
385         old_features[E2P_FEATURE_INCOMPAT] = sb->s_feature_incompat;
386         old_features[E2P_FEATURE_RO_INCOMPAT] = sb->s_feature_ro_compat;
387
388         if (e2p_edit_feature2(features, &sb->s_feature_compat,
389                               ok_features, clear_ok_features,
390                               &type_err, &mask_err)) {
391                 if (!mask_err)
392                         fprintf(stderr,
393                                 _("Invalid filesystem option set: %s\n"),
394                                 features);
395                 else if (type_err & E2P_FEATURE_NEGATE_FLAG)
396                         fprintf(stderr, _("Clearing filesystem feature '%s' "
397                                           "not supported.\n"),
398                                 e2p_feature2string(type_err &
399                                                    E2P_FEATURE_TYPE_MASK,
400                                                    mask_err));
401                 else
402                         fprintf(stderr, _("Setting filesystem feature '%s' "
403                                           "not supported.\n"),
404                                 e2p_feature2string(type_err, mask_err));
405                 return 1;
406         }
407
408         if (FEATURE_OFF(E2P_FEATURE_COMPAT, EXT3_FEATURE_COMPAT_HAS_JOURNAL)) {
409                 if ((mount_flags & EXT2_MF_MOUNTED) &&
410                     !(mount_flags & EXT2_MF_READONLY)) {
411                         fputs(_("The has_journal feature may only be "
412                                 "cleared when the filesystem is\n"
413                                 "unmounted or mounted "
414                                 "read-only.\n"), stderr);
415                         return 1;
416                 }
417                 if (sb->s_feature_incompat &
418                     EXT3_FEATURE_INCOMPAT_RECOVER) {
419                         fputs(_("The needs_recovery flag is set.  "
420                                 "Please run e2fsck before clearing\n"
421                                 "the has_journal flag.\n"), stderr);
422                         return 1;
423                 }
424                 if (sb->s_journal_inum) {
425                         if (remove_journal_inode(fs))
426                                 return 1;
427                 }
428                 if (sb->s_journal_dev) {
429                         if (remove_journal_device(fs))
430                                 return 1;
431                 }
432         }
433         if (FEATURE_ON(E2P_FEATURE_INCOMPAT, EXT4_FEATURE_INCOMPAT_MMP)) {
434                 int error;
435
436                 if ((mount_flags & EXT2_MF_MOUNTED) ||
437                     (mount_flags & EXT2_MF_READONLY)) {
438                         fputs(_("The multiple mount protection feature can't\n"
439                                 "be set if the filesystem is mounted or\n"
440                                 "read-only.\n"), stderr);
441                         return 1;
442                 }
443
444                 error = ext2fs_mmp_init(fs);
445                 if (error) {
446                         fputs(_("\nError while enabling multiple mount "
447                                 "protection feature."), stderr);
448                         return 1;
449                 }
450
451                 /*
452                  * We want to update group desc with the new free blocks count
453                  */
454                 fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
455
456                 printf(_("Multiple mount protection has been enabled "
457                          "with update interval %ds.\n"),
458                        sb->s_mmp_update_interval);
459         }
460
461         if (FEATURE_OFF(E2P_FEATURE_INCOMPAT, EXT4_FEATURE_INCOMPAT_MMP)) {
462                 int error;
463
464                 if (mount_flags & EXT2_MF_READONLY) {
465                         fputs(_("The multiple mount protection feature cannot\n"
466                                 "be disabled if the filesystem is readonly.\n"),
467                                 stderr);
468                         return 1;
469                 }
470
471                 error = ext2fs_read_bitmaps(fs);
472                 if (error) {
473                         fputs(_("Error while reading bitmaps\n"), stderr);
474                         return 1;
475                 }
476
477                 error = ext2fs_mmp_read(fs, sb->s_mmp_block, NULL);
478                 if (error) {
479                         struct mmp_struct *mmp_cmp = fs->mmp_cmp;
480
481                         if (error == EXT2_ET_MMP_MAGIC_INVALID)
482                                 printf(_("Magic number in MMP block does not "
483                                          "match. expected: %x, actual: %x\n"),
484                                          EXT4_MMP_MAGIC, mmp_cmp->mmp_magic);
485                         else
486                                 com_err(program_name, error,
487                                         _("while reading MMP block."));
488                         goto mmp_error;
489                 }
490
491                 /* We need to force out the group descriptors as well */
492                 fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
493                 ext2fs_block_alloc_stats(fs, sb->s_mmp_block, -1);
494 mmp_error:
495                 sb->s_mmp_block = 0;
496                 sb->s_mmp_update_interval = 0;
497         }
498
499         if (FEATURE_ON(E2P_FEATURE_COMPAT, EXT3_FEATURE_COMPAT_HAS_JOURNAL)) {
500                 /*
501                  * If adding a journal flag, let the create journal
502                  * code below handle setting the flag and creating the
503                  * journal.  We supply a default size if necessary.
504                  */
505                 if (!journal_size)
506                         journal_size = -1;
507                 sb->s_feature_compat &= ~EXT3_FEATURE_COMPAT_HAS_JOURNAL;
508         }
509
510         if (FEATURE_ON(E2P_FEATURE_COMPAT, EXT2_FEATURE_COMPAT_DIR_INDEX)) {
511                 if (!sb->s_def_hash_version)
512                         sb->s_def_hash_version = EXT2_HASH_HALF_MD4;
513                 if (uuid_is_null((unsigned char *) sb->s_hash_seed))
514                         uuid_generate((unsigned char *) sb->s_hash_seed);
515         }
516
517         if (FEATURE_OFF(E2P_FEATURE_INCOMPAT, EXT4_FEATURE_INCOMPAT_FLEX_BG)) {
518                 if (ext2fs_check_desc(fs)) {
519                         fputs(_("Clearing the flex_bg flag would "
520                                 "cause the the filesystem to be\n"
521                                 "inconsistent.\n"), stderr);
522                         return 1;
523                 }
524         }
525
526         if (FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
527                             EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
528                 if ((mount_flags & EXT2_MF_MOUNTED) &&
529                     !(mount_flags & EXT2_MF_READONLY)) {
530                         fputs(_("The huge_file feature may only be "
531                                 "cleared when the filesystem is\n"
532                                 "unmounted or mounted "
533                                 "read-only.\n"), stderr);
534                         return 1;
535                 }
536         }
537
538         if (FEATURE_ON(E2P_FEATURE_RO_INCOMPAT,
539                        EXT4_FEATURE_RO_COMPAT_GDT_CSUM)) {
540                 for (i = 0; i < fs->group_desc_count; i++) {
541                         gd = ext2fs_group_desc(fs, fs->group_desc, i);
542                         gd->bg_itable_unused = 0;
543                         gd->bg_flags = EXT2_BG_INODE_ZEROED;
544                         ext2fs_group_desc_csum_set(fs, i);
545                 }
546                 fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
547         }
548
549         if (FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
550                         EXT4_FEATURE_RO_COMPAT_GDT_CSUM)) {
551                 for (i = 0; i < fs->group_desc_count; i++) {
552                         gd = ext2fs_group_desc(fs, fs->group_desc, i);
553                         if ((gd->bg_flags & EXT2_BG_INODE_ZEROED) == 0) {
554                                 /* 
555                                  * XXX what we really should do is zap
556                                  * uninitialized inode tables instead.
557                                  */
558                                 request_fsck_afterwards(fs);
559                                 break;
560                         }
561                         gd->bg_itable_unused = 0;
562                         gd->bg_flags = 0;
563                         gd->bg_checksum = 0;
564                 }
565                 fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
566         }
567
568         if (FEATURE_ON(E2P_FEATURE_RO_INCOMPAT,
569                                 EXT4_FEATURE_RO_COMPAT_QUOTA)) {
570                 /*
571                  * Set the Q_flag here and handle the quota options in the code
572                  * below.
573                  */
574                 if (!Q_flag) {
575                         Q_flag = 1;
576                         /* Enable both user quota and group quota by default */
577                         usrquota = QOPT_ENABLE;
578                         grpquota = QOPT_ENABLE;
579                 }
580                 sb->s_feature_ro_compat &= ~EXT4_FEATURE_RO_COMPAT_QUOTA;
581         }
582
583         if (FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
584                                 EXT4_FEATURE_RO_COMPAT_QUOTA)) {
585                 /*
586                  * Set the Q_flag here and handle the quota options in the code
587                  * below.
588                  */
589                 if (Q_flag)
590                         fputs(_("\nWarning: '^quota' option overrides '-Q'"
591                                 "arguments.\n"), stderr);
592                 Q_flag = 1;
593                 /* Disable both user quota and group quota by default */
594                 usrquota = QOPT_DISABLE;
595                 grpquota = QOPT_DISABLE;
596         }
597
598         if (sb->s_rev_level == EXT2_GOOD_OLD_REV &&
599             (sb->s_feature_compat || sb->s_feature_ro_compat ||
600              sb->s_feature_incompat))
601                 ext2fs_update_dynamic_rev(fs);
602
603         if (FEATURE_CHANGED(E2P_FEATURE_RO_INCOMPAT,
604                             EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER) ||
605             FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
606                         EXT4_FEATURE_RO_COMPAT_HUGE_FILE) ||
607             FEATURE_CHANGED(E2P_FEATURE_INCOMPAT,
608                             EXT2_FEATURE_INCOMPAT_FILETYPE) ||
609             FEATURE_CHANGED(E2P_FEATURE_COMPAT,
610                             EXT2_FEATURE_COMPAT_RESIZE_INODE) ||
611             FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
612                         EXT2_FEATURE_RO_COMPAT_LARGE_FILE))
613                 request_fsck_afterwards(fs);
614
615         if ((old_features[E2P_FEATURE_COMPAT] != sb->s_feature_compat) ||
616             (old_features[E2P_FEATURE_INCOMPAT] != sb->s_feature_incompat) ||
617             (old_features[E2P_FEATURE_RO_INCOMPAT] != sb->s_feature_ro_compat))
618                 ext2fs_mark_super_dirty(fs);
619
620         return 0;
621 }
622
623 /*
624  * Add a journal to the filesystem.
625  */
626 static int add_journal(ext2_filsys fs)
627 {
628         unsigned long journal_blocks;
629         errcode_t       retval;
630         ext2_filsys     jfs;
631         io_manager      io_ptr;
632
633         if (fs->super->s_feature_compat &
634             EXT3_FEATURE_COMPAT_HAS_JOURNAL) {
635                 fputs(_("The filesystem already has a journal.\n"), stderr);
636                 goto err;
637         }
638         if (journal_device) {
639                 check_plausibility(journal_device);
640                 check_mount(journal_device, 0, _("journal"));
641 #ifdef CONFIG_TESTIO_DEBUG
642                 if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_BLOCK")) {
643                         io_ptr = test_io_manager;
644                         test_io_backing_manager = unix_io_manager;
645                 } else
646 #endif
647                         io_ptr = unix_io_manager;
648                 retval = ext2fs_open(journal_device, EXT2_FLAG_RW|
649                                      EXT2_FLAG_JOURNAL_DEV_OK, 0,
650                                      fs->blocksize, io_ptr, &jfs);
651                 if (retval) {
652                         com_err(program_name, retval,
653                                 _("\n\twhile trying to open journal on %s\n"),
654                                 journal_device);
655                         goto err;
656                 }
657                 printf(_("Creating journal on device %s: "),
658                        journal_device);
659                 fflush(stdout);
660
661                 retval = ext2fs_add_journal_device(fs, jfs);
662                 ext2fs_close(jfs);
663                 if (retval) {
664                         com_err(program_name, retval,
665                                 _("while adding filesystem to journal on %s"),
666                                 journal_device);
667                         goto err;
668                 }
669                 fputs(_("done\n"), stdout);
670         } else if (journal_size) {
671                 fputs(_("Creating journal inode: "), stdout);
672                 fflush(stdout);
673                 journal_blocks = figure_journal_size(journal_size, fs);
674
675                 retval = ext2fs_add_journal_inode(fs, journal_blocks,
676                                                   journal_flags);
677                 if (retval) {
678                         fprintf(stderr, "\n");
679                         com_err(program_name, retval,
680                                 _("\n\twhile trying to create journal file"));
681                         return retval;
682                 } else
683                         fputs(_("done\n"), stdout);
684                 /*
685                  * If the filesystem wasn't mounted, we need to force
686                  * the block group descriptors out.
687                  */
688                 if ((mount_flags & EXT2_MF_MOUNTED) == 0)
689                         fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
690         }
691         print_check_message(fs->super->s_max_mnt_count,
692                             fs->super->s_checkinterval);
693         return 0;
694
695 err:
696         free(journal_device);
697         return 1;
698 }
699
700 void handle_quota_options(ext2_filsys fs)
701 {
702         quota_ctx_t qctx;
703         ext2_ino_t qf_ino;
704
705         if (!usrquota && !grpquota)
706                 /* Nothing to do. */
707                 return;
708
709         quota_init_context(&qctx, fs, -1);
710
711         if (usrquota == QOPT_ENABLE || grpquota == QOPT_ENABLE)
712                 quota_compute_usage(qctx);
713
714         if (usrquota == QOPT_ENABLE && !fs->super->s_usr_quota_inum) {
715                 if ((qf_ino = quota_file_exists(fs, USRQUOTA,
716                                                 QFMT_VFS_V1)) > 0)
717                         quota_update_limits(qctx, qf_ino, USRQUOTA);
718                 quota_write_inode(qctx, USRQUOTA);
719         } else if (usrquota == QOPT_DISABLE) {
720                 quota_remove_inode(fs, USRQUOTA);
721         }
722
723         if (grpquota == QOPT_ENABLE && !fs->super->s_grp_quota_inum) {
724                 if ((qf_ino = quota_file_exists(fs, GRPQUOTA,
725                                                 QFMT_VFS_V1)) > 0)
726                         quota_update_limits(qctx, qf_ino, GRPQUOTA);
727                 quota_write_inode(qctx, GRPQUOTA);
728         } else if (grpquota == QOPT_DISABLE) {
729                 quota_remove_inode(fs, GRPQUOTA);
730         }
731
732         quota_release_context(&qctx);
733
734         if ((usrquota == QOPT_ENABLE) || (grpquota == QOPT_ENABLE)) {
735                 fs->super->s_feature_ro_compat |= EXT4_FEATURE_RO_COMPAT_QUOTA;
736                 ext2fs_mark_super_dirty(fs);
737         } else if (!fs->super->s_usr_quota_inum &&
738                    !fs->super->s_grp_quota_inum) {
739                 fs->super->s_feature_ro_compat &= ~EXT4_FEATURE_RO_COMPAT_QUOTA;
740                 ext2fs_mark_super_dirty(fs);
741         }
742
743         return;
744 }
745
746 void parse_quota_opts(const char *opts)
747 {
748         char    *buf, *token, *next, *p;
749         int     len;
750
751         len = strlen(opts);
752         buf = malloc(len+1);
753         if (!buf) {
754                 fputs(_("Couldn't allocate memory to parse quota "
755                         "options!\n"), stderr);
756                 exit(1);
757         }
758         strcpy(buf, opts);
759         for (token = buf; token && *token; token = next) {
760                 p = strchr(token, ',');
761                 next = 0;
762                 if (p) {
763                         *p = 0;
764                         next = p+1;
765                 }
766
767                 if (strcmp(token, "usrquota") == 0) {
768                         usrquota = QOPT_ENABLE;
769                 } else if (strcmp(token, "^usrquota") == 0) {
770                         usrquota = QOPT_DISABLE;
771                 } else if (strcmp(token, "grpquota") == 0) {
772                         grpquota = QOPT_ENABLE;
773                 } else if (strcmp(token, "^grpquota") == 0) {
774                         grpquota = QOPT_DISABLE;
775                 } else {
776                         fputs(_("\nBad quota options specified.\n\n"
777                                 "Following valid quota options are available "
778                                 "(pass by separating with comma):\n"
779                                 "\t[^]usrquota\n"
780                                 "\t[^]grpquota\n"
781                                 "\n\n"), stderr);
782                         free(buf);
783                         exit(1);
784                 }
785         }
786         free(buf);
787 }
788
789
790
791 static void parse_e2label_options(int argc, char ** argv)
792 {
793         if ((argc < 2) || (argc > 3)) {
794                 fputs(_("Usage: e2label device [newlabel]\n"), stderr);
795                 exit(1);
796         }
797         io_options = strchr(argv[1], '?');
798         if (io_options)
799                 *io_options++ = 0;
800         device_name = blkid_get_devname(NULL, argv[1], NULL);
801         if (!device_name) {
802                 com_err("e2label", 0, _("Unable to resolve '%s'"),
803                         argv[1]);
804                 exit(1);
805         }
806         open_flag = EXT2_FLAG_JOURNAL_DEV_OK;
807         if (argc == 3) {
808                 open_flag |= EXT2_FLAG_RW;
809                 L_flag = 1;
810                 new_label = argv[2];
811         } else
812                 print_label++;
813 }
814
815 static time_t parse_time(char *str)
816 {
817         struct  tm      ts;
818
819         if (strcmp(str, "now") == 0) {
820                 return (time(0));
821         }
822         memset(&ts, 0, sizeof(ts));
823 #ifdef HAVE_STRPTIME
824         strptime(str, "%Y%m%d%H%M%S", &ts);
825 #else
826         sscanf(str, "%4d%2d%2d%2d%2d%2d", &ts.tm_year, &ts.tm_mon,
827                &ts.tm_mday, &ts.tm_hour, &ts.tm_min, &ts.tm_sec);
828         ts.tm_year -= 1900;
829         ts.tm_mon -= 1;
830         if (ts.tm_year < 0 || ts.tm_mon < 0 || ts.tm_mon > 11 ||
831             ts.tm_mday < 0 || ts.tm_mday > 31 || ts.tm_hour > 23 ||
832             ts.tm_min > 59 || ts.tm_sec > 61)
833                 ts.tm_mday = 0;
834 #endif
835         if (ts.tm_mday == 0) {
836                 com_err(program_name, 0,
837                         _("Couldn't parse date/time specifier: %s"),
838                         str);
839                 usage();
840         }
841         ts.tm_isdst = -1;
842         return (mktime(&ts));
843 }
844
845 static void parse_tune2fs_options(int argc, char **argv)
846 {
847         int c;
848         char *tmp;
849         struct group *gr;
850         struct passwd *pw;
851
852         open_flag = 0;
853
854         printf("tune2fs %s (%s)\n", E2FSPROGS_VERSION, E2FSPROGS_DATE);
855         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)
856                 switch (c) {
857                 case 'c':
858                         max_mount_count = strtol(optarg, &tmp, 0);
859                         if (*tmp || max_mount_count > 16000) {
860                                 com_err(program_name, 0,
861                                         _("bad mounts count - %s"),
862                                         optarg);
863                                 usage();
864                         }
865                         if (max_mount_count == 0)
866                                 max_mount_count = -1;
867                         c_flag = 1;
868                         open_flag = EXT2_FLAG_RW;
869                         break;
870                 case 'C':
871                         mount_count = strtoul(optarg, &tmp, 0);
872                         if (*tmp || mount_count > 16000) {
873                                 com_err(program_name, 0,
874                                         _("bad mounts count - %s"),
875                                         optarg);
876                                 usage();
877                         }
878                         C_flag = 1;
879                         open_flag = EXT2_FLAG_RW;
880                         break;
881                 case 'e':
882                         if (strcmp(optarg, "continue") == 0)
883                                 errors = EXT2_ERRORS_CONTINUE;
884                         else if (strcmp(optarg, "remount-ro") == 0)
885                                 errors = EXT2_ERRORS_RO;
886                         else if (strcmp(optarg, "panic") == 0)
887                                 errors = EXT2_ERRORS_PANIC;
888                         else {
889                                 com_err(program_name, 0,
890                                         _("bad error behavior - %s"),
891                                         optarg);
892                                 usage();
893                         }
894                         e_flag = 1;
895                         open_flag = EXT2_FLAG_RW;
896                         break;
897                 case 'E':
898                         extended_cmd = optarg;
899                         open_flag |= EXT2_FLAG_RW;
900                         break;
901                 case 'f': /* Force */
902                         f_flag = 1;
903                         break;
904                 case 'g':
905                         resgid = strtoul(optarg, &tmp, 0);
906                         if (*tmp) {
907                                 gr = getgrnam(optarg);
908                                 if (gr == NULL)
909                                         tmp = optarg;
910                                 else {
911                                         resgid = gr->gr_gid;
912                                         *tmp = 0;
913                                 }
914                         }
915                         if (*tmp) {
916                                 com_err(program_name, 0,
917                                         _("bad gid/group name - %s"),
918                                         optarg);
919                                 usage();
920                         }
921                         g_flag = 1;
922                         open_flag = EXT2_FLAG_RW;
923                         break;
924                 case 'i':
925                         interval = strtoul(optarg, &tmp, 0);
926                         switch (*tmp) {
927                         case 's':
928                                 tmp++;
929                                 break;
930                         case '\0':
931                         case 'd':
932                         case 'D': /* days */
933                                 interval *= 86400;
934                                 if (*tmp != '\0')
935                                         tmp++;
936                                 break;
937                         case 'm':
938                         case 'M': /* months! */
939                                 interval *= 86400 * 30;
940                                 tmp++;
941                                 break;
942                         case 'w':
943                         case 'W': /* weeks */
944                                 interval *= 86400 * 7;
945                                 tmp++;
946                                 break;
947                         }
948                         if (*tmp) {
949                                 com_err(program_name, 0,
950                                         _("bad interval - %s"), optarg);
951                                 usage();
952                         }
953                         i_flag = 1;
954                         open_flag = EXT2_FLAG_RW;
955                         break;
956                 case 'j':
957                         if (!journal_size)
958                                 journal_size = -1;
959                         open_flag = EXT2_FLAG_RW;
960                         break;
961                 case 'J':
962                         parse_journal_opts(optarg);
963                         open_flag = EXT2_FLAG_RW;
964                         break;
965                 case 'l':
966                         l_flag = 1;
967                         break;
968                 case 'L':
969                         new_label = optarg;
970                         L_flag = 1;
971                         open_flag |= EXT2_FLAG_RW |
972                                 EXT2_FLAG_JOURNAL_DEV_OK;
973                         break;
974                 case 'm':
975                         reserved_ratio = strtod(optarg, &tmp);
976                         if (*tmp || reserved_ratio > 50 ||
977                             reserved_ratio < 0) {
978                                 com_err(program_name, 0,
979                                         _("bad reserved block ratio - %s"),
980                                         optarg);
981                                 usage();
982                         }
983                         m_flag = 1;
984                         open_flag = EXT2_FLAG_RW;
985                         break;
986                 case 'M':
987                         new_last_mounted = optarg;
988                         M_flag = 1;
989                         open_flag = EXT2_FLAG_RW;
990                         break;
991                 case 'o':
992                         if (mntopts_cmd) {
993                                 com_err(program_name, 0,
994                                         _("-o may only be specified once"));
995                                 usage();
996                         }
997                         mntopts_cmd = optarg;
998                         open_flag = EXT2_FLAG_RW;
999                         break;
1000                 case 'O':
1001                         if (features_cmd) {
1002                                 com_err(program_name, 0,
1003                                         _("-O may only be specified once"));
1004                                 usage();
1005                         }
1006                         features_cmd = optarg;
1007                         open_flag = EXT2_FLAG_RW;
1008                         break;
1009                 case 'Q':
1010                         Q_flag = 1;
1011                         parse_quota_opts(optarg);
1012                         open_flag = EXT2_FLAG_RW;
1013                         break;
1014                 case 'r':
1015                         reserved_blocks = strtoul(optarg, &tmp, 0);
1016                         if (*tmp) {
1017                                 com_err(program_name, 0,
1018                                         _("bad reserved blocks count - %s"),
1019                                         optarg);
1020                                 usage();
1021                         }
1022                         r_flag = 1;
1023                         open_flag = EXT2_FLAG_RW;
1024                         break;
1025                 case 's': /* Deprecated */
1026                         s_flag = atoi(optarg);
1027                         open_flag = EXT2_FLAG_RW;
1028                         break;
1029                 case 'T':
1030                         T_flag = 1;
1031                         last_check_time = parse_time(optarg);
1032                         open_flag = EXT2_FLAG_RW;
1033                         break;
1034                 case 'u':
1035                                 resuid = strtoul(optarg, &tmp, 0);
1036                                 if (*tmp) {
1037                                         pw = getpwnam(optarg);
1038                                         if (pw == NULL)
1039                                                 tmp = optarg;
1040                                         else {
1041                                                 resuid = pw->pw_uid;
1042                                                 *tmp = 0;
1043                                         }
1044                                 }
1045                                 if (*tmp) {
1046                                         com_err(program_name, 0,
1047                                                 _("bad uid/user name - %s"),
1048                                                 optarg);
1049                                         usage();
1050                                 }
1051                                 u_flag = 1;
1052                                 open_flag = EXT2_FLAG_RW;
1053                                 break;
1054                 case 'U':
1055                         new_UUID = optarg;
1056                         U_flag = 1;
1057                         open_flag = EXT2_FLAG_RW |
1058                                 EXT2_FLAG_JOURNAL_DEV_OK;
1059                         break;
1060                 case 'I':
1061                         new_inode_size = strtoul(optarg, &tmp, 0);
1062                         if (*tmp) {
1063                                 com_err(program_name, 0,
1064                                         _("bad inode size - %s"),
1065                                         optarg);
1066                                 usage();
1067                         }
1068                         if (!((new_inode_size &
1069                                (new_inode_size - 1)) == 0)) {
1070                                 com_err(program_name, 0,
1071                                         _("Inode size must be a "
1072                                           "power of two- %s"),
1073                                         optarg);
1074                                 usage();
1075                         }
1076                         open_flag = EXT2_FLAG_RW;
1077                         I_flag = 1;
1078                         break;
1079                 default:
1080                         usage();
1081                 }
1082         if (optind < argc - 1 || optind == argc)
1083                 usage();
1084         if (!open_flag && !l_flag)
1085                 usage();
1086         io_options = strchr(argv[optind], '?');
1087         if (io_options)
1088                 *io_options++ = 0;
1089         device_name = blkid_get_devname(NULL, argv[optind], NULL);
1090         if (!device_name) {
1091                 com_err("tune2fs", 0, _("Unable to resolve '%s'"),
1092                         argv[optind]);
1093                 exit(1);
1094         }
1095 }
1096
1097 #ifdef CONFIG_BUILD_FINDFS
1098 void do_findfs(int argc, char **argv)
1099 {
1100         char    *dev;
1101
1102         if ((argc != 2) ||
1103             (strncmp(argv[1], "LABEL=", 6) && strncmp(argv[1], "UUID=", 5))) {
1104                 fprintf(stderr, "Usage: findfs LABEL=<label>|UUID=<uuid>\n");
1105                 exit(2);
1106         }
1107         dev = blkid_get_devname(NULL, argv[1], NULL);
1108         if (!dev) {
1109                 com_err("findfs", 0, _("Unable to resolve '%s'"),
1110                         argv[1]);
1111                 exit(1);
1112         }
1113         puts(dev);
1114         exit(0);
1115 }
1116 #endif
1117
1118 static int parse_extended_opts(ext2_filsys fs, const char *opts)
1119 {
1120         char    *buf, *token, *next, *p, *arg;
1121         int     len, hash_alg;
1122         int     r_usage = 0;
1123
1124         len = strlen(opts);
1125         buf = malloc(len+1);
1126         if (!buf) {
1127                 fprintf(stderr,
1128                         _("Couldn't allocate memory to parse options!\n"));
1129                 return 1;
1130         }
1131         strcpy(buf, opts);
1132         for (token = buf; token && *token; token = next) {
1133                 p = strchr(token, ',');
1134                 next = 0;
1135                 if (p) {
1136                         *p = 0;
1137                         next = p+1;
1138                 }
1139                 arg = strchr(token, '=');
1140                 if (arg) {
1141                         *arg = 0;
1142                         arg++;
1143                 }
1144                 if (strcmp(token, "clear-mmp") == 0 ||
1145                     strcmp(token, "clear_mmp") == 0) {
1146                         clear_mmp = 1;
1147                 } else if (strcmp(token, "mmp_update_interval") == 0) {
1148                         unsigned long interval;
1149                         if (!arg) {
1150                                 r_usage++;
1151                                 continue;
1152                         }
1153                         interval = strtoul(arg, &p, 0);
1154                         if (*p) {
1155                                 fprintf(stderr,
1156                                         _("Invalid mmp_update_interval: %s\n"),
1157                                         arg);
1158                                 r_usage++;
1159                                 continue;
1160                         }
1161                         if (interval == 0) {
1162                                 interval = EXT4_MMP_UPDATE_INTERVAL;
1163                         } else if (interval > EXT4_MMP_MAX_UPDATE_INTERVAL) {
1164                                 fprintf(stderr,
1165                                         _("mmp_update_interval too big: %lu\n"),
1166                                         interval);
1167                                 r_usage++;
1168                                 continue;
1169                         }
1170                         printf(P_("Setting multiple mount protection update "
1171                                   "interval to %lu second\n",
1172                                   "Setting multiple mount protection update "
1173                                   "interval to %lu seconds\n", interval),
1174                                interval);
1175                         fs->super->s_mmp_update_interval = interval;
1176                         ext2fs_mark_super_dirty(fs);
1177                 } else if (!strcmp(token, "test_fs")) {
1178                         fs->super->s_flags |= EXT2_FLAGS_TEST_FILESYS;
1179                         printf("Setting test filesystem flag\n");
1180                         ext2fs_mark_super_dirty(fs);
1181                 } else if (!strcmp(token, "^test_fs")) {
1182                         fs->super->s_flags &= ~EXT2_FLAGS_TEST_FILESYS;
1183                         printf("Clearing test filesystem flag\n");
1184                         ext2fs_mark_super_dirty(fs);
1185                 } else if (strcmp(token, "stride") == 0) {
1186                         if (!arg) {
1187                                 r_usage++;
1188                                 continue;
1189                         }
1190                         stride = strtoul(arg, &p, 0);
1191                         if (*p) {
1192                                 fprintf(stderr,
1193                                         _("Invalid RAID stride: %s\n"),
1194                                         arg);
1195                                 r_usage++;
1196                                 continue;
1197                         }
1198                         stride_set = 1;
1199                 } else if (strcmp(token, "stripe-width") == 0 ||
1200                            strcmp(token, "stripe_width") == 0) {
1201                         if (!arg) {
1202                                 r_usage++;
1203                                 continue;
1204                         }
1205                         stripe_width = strtoul(arg, &p, 0);
1206                         if (*p) {
1207                                 fprintf(stderr,
1208                                         _("Invalid RAID stripe-width: %s\n"),
1209                                         arg);
1210                                 r_usage++;
1211                                 continue;
1212                         }
1213                         stripe_width_set = 1;
1214                 } else if (strcmp(token, "hash_alg") == 0 ||
1215                            strcmp(token, "hash-alg") == 0) {
1216                         if (!arg) {
1217                                 r_usage++;
1218                                 continue;
1219                         }
1220                         hash_alg = e2p_string2hash(arg);
1221                         if (hash_alg < 0) {
1222                                 fprintf(stderr,
1223                                         _("Invalid hash algorithm: %s\n"),
1224                                         arg);
1225                                 r_usage++;
1226                                 continue;
1227                         }
1228                         fs->super->s_def_hash_version = hash_alg;
1229                         printf(_("Setting default hash algorithm "
1230                                  "to %s (%d)\n"),
1231                                arg, hash_alg);
1232                         ext2fs_mark_super_dirty(fs);
1233                 } else if (!strcmp(token, "mount_opts")) {
1234                         if (!arg) {
1235                                 r_usage++;
1236                                 continue;
1237                         }
1238                         if (strlen(arg) >= sizeof(fs->super->s_mount_opts)) {
1239                                 fprintf(stderr,
1240                                         "Extended mount options too long\n");
1241                                 continue;
1242                         }
1243                         ext_mount_opts = strdup(arg);
1244                 } else
1245                         r_usage++;
1246         }
1247         if (r_usage) {
1248                 fprintf(stderr, _("\nBad options specified.\n\n"
1249                         "Extended options are separated by commas, "
1250                         "and may take an argument which\n"
1251                         "\tis set off by an equals ('=') sign.\n\n"
1252                         "Valid extended options are:\n"
1253                         "\tclear_mmp\n"
1254                         "\thash_alg=<hash algorithm>\n"
1255                         "\tmount_opts=<extended default mount options>\n"
1256                         "\tstride=<RAID per-disk chunk size in blocks>\n"
1257                         "\tstripe_width=<RAID stride*data disks in blocks>\n"
1258                         "\ttest_fs\n"
1259                         "\t^test_fs\n"));
1260                 free(buf);
1261                 return 1;
1262         }
1263         free(buf);
1264
1265         return 0;
1266 }
1267
1268 /*
1269  * Fill in the block bitmap bmap with the information regarding the
1270  * blocks to be moved
1271  */
1272 static int get_move_bitmaps(ext2_filsys fs, int new_ino_blks_per_grp,
1273                             ext2fs_block_bitmap bmap)
1274 {
1275         dgrp_t i;
1276         int retval;
1277         ext2_badblocks_list bb_list = 0;
1278         blk64_t j, needed_blocks = 0;
1279         blk64_t start_blk, end_blk;
1280
1281         retval = ext2fs_read_bb_inode(fs, &bb_list);
1282         if (retval)
1283                 return retval;
1284
1285         for (i = 0; i < fs->group_desc_count; i++) {
1286                 start_blk = ext2fs_inode_table_loc(fs, i) +
1287                                         fs->inode_blocks_per_group;
1288
1289                 end_blk = ext2fs_inode_table_loc(fs, i) +
1290                                         new_ino_blks_per_grp;
1291
1292                 for (j = start_blk; j < end_blk; j++) {
1293                         if (ext2fs_test_block_bitmap2(fs->block_map, j)) {
1294                                 /*
1295                                  * IF the block is a bad block we fail
1296                                  */
1297                                 if (ext2fs_badblocks_list_test(bb_list, j)) {
1298                                         ext2fs_badblocks_list_free(bb_list);
1299                                         return ENOSPC;
1300                                 }
1301
1302                                 ext2fs_mark_block_bitmap2(bmap, j);
1303                         } else {
1304                                 /*
1305                                  * We are going to use this block for
1306                                  * inode table. So mark them used.
1307                                  */
1308                                 ext2fs_mark_block_bitmap2(fs->block_map, j);
1309                         }
1310                 }
1311                 needed_blocks += end_blk - start_blk;
1312         }
1313
1314         ext2fs_badblocks_list_free(bb_list);
1315         if (needed_blocks > ext2fs_free_blocks_count(fs->super))
1316                 return ENOSPC;
1317
1318         return 0;
1319 }
1320
1321 static int ext2fs_is_meta_block(ext2_filsys fs, blk_t blk)
1322 {
1323         dgrp_t group;
1324         group = ext2fs_group_of_blk(fs, blk);
1325         if (ext2fs_block_bitmap_loc(fs, group) == blk)
1326                 return 1;
1327         if (ext2fs_inode_bitmap_loc(fs, group) == blk)
1328                 return 1;
1329         return 0;
1330 }
1331
1332 static int ext2fs_is_block_in_group(ext2_filsys fs, dgrp_t group, blk_t blk)
1333 {
1334         blk_t start_blk, end_blk;
1335         start_blk = fs->super->s_first_data_block +
1336                         EXT2_BLOCKS_PER_GROUP(fs->super) * group;
1337         /*
1338          * We cannot get new block beyond end_blk for for the last block group
1339          * so we can check with EXT2_BLOCKS_PER_GROUP even for last block group
1340          */
1341         end_blk   = start_blk + EXT2_BLOCKS_PER_GROUP(fs->super);
1342         if (blk >= start_blk && blk <= end_blk)
1343                 return 1;
1344         return 0;
1345 }
1346
1347 static int move_block(ext2_filsys fs, ext2fs_block_bitmap bmap)
1348 {
1349
1350         char *buf;
1351         dgrp_t group = 0;
1352         errcode_t retval;
1353         int meta_data = 0;
1354         blk64_t blk, new_blk, goal;
1355         struct blk_move *bmv;
1356
1357         retval = ext2fs_get_mem(fs->blocksize, &buf);
1358         if (retval)
1359                 return retval;
1360
1361         for (new_blk = blk = fs->super->s_first_data_block;
1362              blk < ext2fs_blocks_count(fs->super); blk++) {
1363                 if (!ext2fs_test_block_bitmap2(bmap, blk))
1364                         continue;
1365
1366                 if (ext2fs_is_meta_block(fs, blk)) {
1367                         /*
1368                          * If the block is mapping a fs meta data block
1369                          * like group desc/block bitmap/inode bitmap. We
1370                          * should find a block in the same group and fix
1371                          * the respective fs metadata pointers. Otherwise
1372                          * fail
1373                          */
1374                         group = ext2fs_group_of_blk(fs, blk);
1375                         goal = ext2fs_group_first_block2(fs, group);
1376                         meta_data = 1;
1377
1378                 } else {
1379                         goal = new_blk;
1380                 }
1381                 retval = ext2fs_new_block2(fs, goal, NULL, &new_blk);
1382                 if (retval)
1383                         goto err_out;
1384
1385                 /* new fs meta data block should be in the same group */
1386                 if (meta_data && !ext2fs_is_block_in_group(fs, group, new_blk)) {
1387                         retval = ENOSPC;
1388                         goto err_out;
1389                 }
1390
1391                 /* Mark this block as allocated */
1392                 ext2fs_mark_block_bitmap2(fs->block_map, new_blk);
1393
1394                 /* Add it to block move list */
1395                 retval = ext2fs_get_mem(sizeof(struct blk_move), &bmv);
1396                 if (retval)
1397                         goto err_out;
1398
1399                 bmv->old_loc = blk;
1400                 bmv->new_loc = new_blk;
1401
1402                 list_add(&(bmv->list), &blk_move_list);
1403
1404                 retval = io_channel_read_blk64(fs->io, blk, 1, buf);
1405                 if (retval)
1406                         goto err_out;
1407
1408                 retval = io_channel_write_blk64(fs->io, new_blk, 1, buf);
1409                 if (retval)
1410                         goto err_out;
1411         }
1412
1413 err_out:
1414         ext2fs_free_mem(&buf);
1415         return retval;
1416 }
1417
1418 static blk64_t translate_block(blk64_t blk)
1419 {
1420         struct list_head *entry;
1421         struct blk_move *bmv;
1422
1423         list_for_each(entry, &blk_move_list) {
1424                 bmv = list_entry(entry, struct blk_move, list);
1425                 if (bmv->old_loc == blk)
1426                         return bmv->new_loc;
1427         }
1428
1429         return 0;
1430 }
1431
1432 static int process_block(ext2_filsys fs EXT2FS_ATTR((unused)),
1433                          blk64_t *block_nr,
1434                          e2_blkcnt_t blockcnt EXT2FS_ATTR((unused)),
1435                          blk64_t ref_block EXT2FS_ATTR((unused)),
1436                          int ref_offset EXT2FS_ATTR((unused)),
1437                          void *priv_data)
1438 {
1439         int ret = 0;
1440         blk64_t new_blk;
1441         ext2fs_block_bitmap bmap = (ext2fs_block_bitmap) priv_data;
1442
1443         if (!ext2fs_test_block_bitmap2(bmap, *block_nr))
1444                 return 0;
1445         new_blk = translate_block(*block_nr);
1446         if (new_blk) {
1447                 *block_nr = new_blk;
1448                 /*
1449                  * This will force the ext2fs_write_inode in the iterator
1450                  */
1451                 ret |= BLOCK_CHANGED;
1452         }
1453
1454         return ret;
1455 }
1456
1457 static int inode_scan_and_fix(ext2_filsys fs, ext2fs_block_bitmap bmap)
1458 {
1459         errcode_t retval = 0;
1460         ext2_ino_t ino;
1461         blk64_t blk;
1462         char *block_buf = 0;
1463         struct ext2_inode inode;
1464         ext2_inode_scan scan = NULL;
1465
1466         retval = ext2fs_get_mem(fs->blocksize * 3, &block_buf);
1467         if (retval)
1468                 return retval;
1469
1470         retval = ext2fs_open_inode_scan(fs, 0, &scan);
1471         if (retval)
1472                 goto err_out;
1473
1474         while (1) {
1475                 retval = ext2fs_get_next_inode(scan, &ino, &inode);
1476                 if (retval)
1477                         goto err_out;
1478
1479                 if (!ino)
1480                         break;
1481
1482                 if (inode.i_links_count == 0)
1483                         continue; /* inode not in use */
1484
1485                 /* FIXME!!
1486                  * If we end up modifying the journal inode
1487                  * the sb->s_jnl_blocks will differ. But a
1488                  * subsequent e2fsck fixes that.
1489                  * Do we need to fix this ??
1490                  */
1491
1492                 if (ext2fs_file_acl_block(fs, &inode) &&
1493                     ext2fs_test_block_bitmap2(bmap,
1494                                         ext2fs_file_acl_block(fs, &inode))) {
1495                         blk = translate_block(ext2fs_file_acl_block(fs,
1496                                                                     &inode));
1497                         if (!blk)
1498                                 continue;
1499
1500                         ext2fs_file_acl_block_set(fs, &inode, blk);
1501
1502                         /*
1503                          * Write the inode to disk so that inode table
1504                          * resizing can work
1505                          */
1506                         retval = ext2fs_write_inode(fs, ino, &inode);
1507                         if (retval)
1508                                 goto err_out;
1509                 }
1510
1511                 if (!ext2fs_inode_has_valid_blocks2(fs, &inode))
1512                         continue;
1513
1514                 retval = ext2fs_block_iterate3(fs, ino, 0, block_buf,
1515                                                process_block, bmap);
1516                 if (retval)
1517                         goto err_out;
1518
1519         }
1520
1521 err_out:
1522         ext2fs_free_mem(&block_buf);
1523
1524         return retval;
1525 }
1526
1527 /*
1528  * We need to scan for inode and block bitmaps that may need to be
1529  * moved.  This can take place if the filesystem was formatted for
1530  * RAID arrays using the mke2fs's extended option "stride".
1531  */
1532 static int group_desc_scan_and_fix(ext2_filsys fs, ext2fs_block_bitmap bmap)
1533 {
1534         dgrp_t i;
1535         blk_t blk, new_blk;
1536
1537         for (i = 0; i < fs->group_desc_count; i++) {
1538                 blk = ext2fs_block_bitmap_loc(fs, i);
1539                 if (ext2fs_test_block_bitmap2(bmap, blk)) {
1540                         new_blk = translate_block(blk);
1541                         if (!new_blk)
1542                                 continue;
1543                         ext2fs_block_bitmap_loc_set(fs, i, new_blk);
1544                 }
1545
1546                 blk = ext2fs_inode_bitmap_loc(fs, i);
1547                 if (ext2fs_test_block_bitmap2(bmap, blk)) {
1548                         new_blk = translate_block(blk);
1549                         if (!new_blk)
1550                                 continue;
1551                         ext2fs_inode_bitmap_loc_set(fs, i, new_blk);
1552                 }
1553         }
1554         return 0;
1555 }
1556
1557 static int expand_inode_table(ext2_filsys fs, unsigned long new_ino_size)
1558 {
1559         dgrp_t i;
1560         blk64_t blk;
1561         errcode_t retval;
1562         int new_ino_blks_per_grp;
1563         unsigned int j;
1564         char *old_itable = NULL, *new_itable = NULL;
1565         char *tmp_old_itable = NULL, *tmp_new_itable = NULL;
1566         unsigned long old_ino_size;
1567         int old_itable_size, new_itable_size;
1568
1569         old_itable_size = fs->inode_blocks_per_group * fs->blocksize;
1570         old_ino_size = EXT2_INODE_SIZE(fs->super);
1571
1572         new_ino_blks_per_grp = ext2fs_div_ceil(
1573                                         EXT2_INODES_PER_GROUP(fs->super) *
1574                                         new_ino_size,
1575                                         fs->blocksize);
1576
1577         new_itable_size = new_ino_blks_per_grp * fs->blocksize;
1578
1579         retval = ext2fs_get_mem(old_itable_size, &old_itable);
1580         if (retval)
1581                 return retval;
1582
1583         retval = ext2fs_get_mem(new_itable_size, &new_itable);
1584         if (retval)
1585                 goto err_out;
1586
1587         tmp_old_itable = old_itable;
1588         tmp_new_itable = new_itable;
1589
1590         for (i = 0; i < fs->group_desc_count; i++) {
1591                 blk = ext2fs_inode_table_loc(fs, i);
1592                 retval = io_channel_read_blk64(fs->io, blk,
1593                                 fs->inode_blocks_per_group, old_itable);
1594                 if (retval)
1595                         goto err_out;
1596
1597                 for (j = 0; j < EXT2_INODES_PER_GROUP(fs->super); j++) {
1598                         memcpy(new_itable, old_itable, old_ino_size);
1599
1600                         memset(new_itable+old_ino_size, 0,
1601                                         new_ino_size - old_ino_size);
1602
1603                         new_itable += new_ino_size;
1604                         old_itable += old_ino_size;
1605                 }
1606
1607                 /* reset the pointer */
1608                 old_itable = tmp_old_itable;
1609                 new_itable = tmp_new_itable;
1610
1611                 retval = io_channel_write_blk64(fs->io, blk,
1612                                         new_ino_blks_per_grp, new_itable);
1613                 if (retval)
1614                         goto err_out;
1615         }
1616
1617         /* Update the meta data */
1618         fs->inode_blocks_per_group = new_ino_blks_per_grp;
1619         fs->super->s_inode_size = new_ino_size;
1620
1621 err_out:
1622         if (old_itable)
1623                 ext2fs_free_mem(&old_itable);
1624
1625         if (new_itable)
1626                 ext2fs_free_mem(&new_itable);
1627
1628         return retval;
1629 }
1630
1631 static errcode_t ext2fs_calculate_summary_stats(ext2_filsys fs)
1632 {
1633         blk64_t         blk;
1634         ext2_ino_t      ino;
1635         unsigned int    group = 0;
1636         unsigned int    count = 0;
1637         int             total_free = 0;
1638         int             group_free = 0;
1639
1640         /*
1641          * First calculate the block statistics
1642          */
1643         for (blk = fs->super->s_first_data_block;
1644              blk < ext2fs_blocks_count(fs->super); blk++) {
1645                 if (!ext2fs_fast_test_block_bitmap2(fs->block_map, blk)) {
1646                         group_free++;
1647                         total_free++;
1648                 }
1649                 count++;
1650                 if ((count == fs->super->s_blocks_per_group) ||
1651                     (blk == ext2fs_blocks_count(fs->super)-1)) {
1652                         ext2fs_bg_free_blocks_count_set(fs, group++,
1653                                                         group_free);
1654                         count = 0;
1655                         group_free = 0;
1656                 }
1657         }
1658         total_free = EXT2FS_C2B(fs, total_free);
1659         ext2fs_free_blocks_count_set(fs->super, total_free);
1660
1661         /*
1662          * Next, calculate the inode statistics
1663          */
1664         group_free = 0;
1665         total_free = 0;
1666         count = 0;
1667         group = 0;
1668
1669         /* Protect loop from wrap-around if s_inodes_count maxed */
1670         for (ino = 1; ino <= fs->super->s_inodes_count && ino > 0; ino++) {
1671                 if (!ext2fs_fast_test_inode_bitmap2(fs->inode_map, ino)) {
1672                         group_free++;
1673                         total_free++;
1674                 }
1675                 count++;
1676                 if ((count == fs->super->s_inodes_per_group) ||
1677                     (ino == fs->super->s_inodes_count)) {
1678                         ext2fs_bg_free_inodes_count_set(fs, group++,
1679                                                         group_free);
1680                         count = 0;
1681                         group_free = 0;
1682                 }
1683         }
1684         fs->super->s_free_inodes_count = total_free;
1685         ext2fs_mark_super_dirty(fs);
1686         return 0;
1687 }
1688
1689 #define list_for_each_safe(pos, pnext, head) \
1690         for (pos = (head)->next, pnext = pos->next; pos != (head); \
1691              pos = pnext, pnext = pos->next)
1692
1693 static void free_blk_move_list(void)
1694 {
1695         struct list_head *entry, *tmp;
1696         struct blk_move *bmv;
1697
1698         list_for_each_safe(entry, tmp, &blk_move_list) {
1699                 bmv = list_entry(entry, struct blk_move, list);
1700                 list_del(entry);
1701                 ext2fs_free_mem(&bmv);
1702         }
1703         return;
1704 }
1705
1706 static int resize_inode(ext2_filsys fs, unsigned long new_size)
1707 {
1708         errcode_t retval;
1709         int new_ino_blks_per_grp;
1710         ext2fs_block_bitmap bmap;
1711
1712         retval = ext2fs_read_inode_bitmap(fs);
1713         if (retval) {
1714                 fputs(_("Failed to read inode bitmap\n"), stderr);
1715                 return retval;
1716         }
1717         retval = ext2fs_read_block_bitmap(fs);
1718         if (retval) {
1719                 fputs(_("Failed to read block bitmap\n"), stderr);
1720                 return retval;
1721         }
1722         INIT_LIST_HEAD(&blk_move_list);
1723
1724
1725         new_ino_blks_per_grp = ext2fs_div_ceil(
1726                                         EXT2_INODES_PER_GROUP(fs->super)*
1727                                         new_size,
1728                                         fs->blocksize);
1729
1730         /* We may change the file system.
1731          * Mark the file system as invalid so that
1732          * the user is prompted to run fsck.
1733          */
1734         fs->super->s_state &= ~EXT2_VALID_FS;
1735
1736         retval = ext2fs_allocate_block_bitmap(fs, _("blocks to be moved"),
1737                                                 &bmap);
1738         if (retval) {
1739                 fputs(_("Failed to allocate block bitmap when "
1740                                 "increasing inode size\n"), stderr);
1741                 return retval;
1742         }
1743         retval = get_move_bitmaps(fs, new_ino_blks_per_grp, bmap);
1744         if (retval) {
1745                 fputs(_("Not enough space to increase inode size \n"), stderr);
1746                 goto err_out;
1747         }
1748         retval = move_block(fs, bmap);
1749         if (retval) {
1750                 fputs(_("Failed to relocate blocks during inode resize \n"),
1751                       stderr);
1752                 goto err_out;
1753         }
1754         retval = inode_scan_and_fix(fs, bmap);
1755         if (retval)
1756                 goto err_out_undo;
1757
1758         retval = group_desc_scan_and_fix(fs, bmap);
1759         if (retval)
1760                 goto err_out_undo;
1761
1762         retval = expand_inode_table(fs, new_size);
1763         if (retval)
1764                 goto err_out_undo;
1765
1766         ext2fs_calculate_summary_stats(fs);
1767
1768         fs->super->s_state |= EXT2_VALID_FS;
1769         /* mark super block and block bitmap as dirty */
1770         ext2fs_mark_super_dirty(fs);
1771         ext2fs_mark_bb_dirty(fs);
1772
1773 err_out:
1774         free_blk_move_list();
1775         ext2fs_free_block_bitmap(bmap);
1776
1777         return retval;
1778
1779 err_out_undo:
1780         free_blk_move_list();
1781         ext2fs_free_block_bitmap(bmap);
1782         fputs(_("Error in resizing the inode size.\n"
1783                         "Run e2undo to undo the "
1784                         "file system changes. \n"), stderr);
1785
1786         return retval;
1787 }
1788
1789 static int tune2fs_setup_tdb(const char *name, io_manager *io_ptr)
1790 {
1791         errcode_t retval = 0;
1792         const char *tdb_dir;
1793         char *tdb_file;
1794         char *dev_name, *tmp_name;
1795
1796 #if 0 /* FIXME!! */
1797         /*
1798          * Configuration via a conf file would be
1799          * nice
1800          */
1801         profile_get_string(profile, "scratch_files",
1802                                         "directory", 0, 0,
1803                                         &tdb_dir);
1804 #endif
1805         tmp_name = strdup(name);
1806         if (!tmp_name) {
1807         alloc_fn_fail:
1808                 com_err(program_name, ENOMEM, 
1809                         _("Couldn't allocate memory for tdb filename\n"));
1810                 return ENOMEM;
1811         }
1812         dev_name = basename(tmp_name);
1813
1814         tdb_dir = getenv("E2FSPROGS_UNDO_DIR");
1815         if (!tdb_dir)
1816                 tdb_dir = "/var/lib/e2fsprogs";
1817
1818         if (!strcmp(tdb_dir, "none") || (tdb_dir[0] == 0) ||
1819             access(tdb_dir, W_OK))
1820                 return 0;
1821
1822         tdb_file = malloc(strlen(tdb_dir) + 9 + strlen(dev_name) + 7 + 1);
1823         if (!tdb_file)
1824                 goto alloc_fn_fail;
1825         sprintf(tdb_file, "%s/tune2fs-%s.e2undo", tdb_dir, dev_name);
1826
1827         if (!access(tdb_file, F_OK)) {
1828                 if (unlink(tdb_file) < 0) {
1829                         retval = errno;
1830                         com_err(program_name, retval,
1831                                 _("while trying to delete %s"),
1832                                 tdb_file);
1833                         free(tdb_file);
1834                         return retval;
1835                 }
1836         }
1837
1838         set_undo_io_backing_manager(*io_ptr);
1839         *io_ptr = undo_io_manager;
1840         set_undo_io_backup_file(tdb_file);
1841         printf(_("To undo the tune2fs operation please run "
1842                  "the command\n    e2undo %s %s\n\n"),
1843                  tdb_file, name);
1844         free(tdb_file);
1845         free(tmp_name);
1846         return retval;
1847 }
1848
1849 int main(int argc, char **argv)
1850 {
1851         errcode_t retval;
1852         ext2_filsys fs;
1853         struct ext2_super_block *sb;
1854         io_manager io_ptr, io_ptr_orig = NULL;
1855         int rc = 0;
1856
1857 #ifdef ENABLE_NLS
1858         setlocale(LC_MESSAGES, "");
1859         setlocale(LC_CTYPE, "");
1860         bindtextdomain(NLS_CAT_NAME, LOCALEDIR);
1861         textdomain(NLS_CAT_NAME);
1862         set_com_err_gettext(gettext);
1863 #endif
1864         if (argc && *argv)
1865                 program_name = *argv;
1866         add_error_table(&et_ext2_error_table);
1867
1868 #ifdef CONFIG_BUILD_FINDFS
1869         if (strcmp(get_progname(argv[0]), "findfs") == 0)
1870                 do_findfs(argc, argv);
1871 #endif
1872         if (strcmp(get_progname(argv[0]), "e2label") == 0)
1873                 parse_e2label_options(argc, argv);
1874         else
1875                 parse_tune2fs_options(argc, argv);
1876
1877 #ifdef CONFIG_TESTIO_DEBUG
1878         if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_DEBUG")) {
1879                 io_ptr = test_io_manager;
1880                 test_io_backing_manager = unix_io_manager;
1881         } else
1882 #endif
1883                 io_ptr = unix_io_manager;
1884
1885 retry_open:
1886         if ((open_flag & EXT2_FLAG_RW) == 0 || f_flag)
1887                 open_flag |= EXT2_FLAG_SKIP_MMP;
1888
1889         open_flag |= EXT2_FLAG_64BITS;
1890
1891         /* keep the filesystem struct around to dump MMP data */
1892         open_flag |= EXT2_FLAG_NOFREE_ON_ERROR;
1893
1894         retval = ext2fs_open2(device_name, io_options, open_flag,
1895                               0, 0, io_ptr, &fs);
1896         if (retval) {
1897                 com_err(program_name, retval,
1898                         _("while trying to open %s"),
1899                         device_name);
1900                 if (retval == EXT2_ET_MMP_FSCK_ON ||
1901                     retval == EXT2_ET_MMP_UNKNOWN_SEQ)
1902                         dump_mmp_msg(fs->mmp_buf,
1903                                      _("If you are sure the filesystem "
1904                                        "is not in use on any node, run:\n"
1905                                        "'tune2fs -f -E clear_mmp {device}'\n"));
1906                 else if (retval == EXT2_ET_MMP_FAILED)
1907                         dump_mmp_msg(fs->mmp_buf, NULL);
1908                 else if (retval == EXT2_ET_MMP_MAGIC_INVALID)
1909                         fprintf(stderr,
1910                                 _("MMP block magic is bad. Try to fix it by "
1911                                   "running:\n'e2fsck -f %s'\n"), device_name);
1912                 else if (retval != EXT2_ET_MMP_FAILED)
1913                         fprintf(stderr,
1914                              _("Couldn't find valid filesystem superblock.\n"));
1915
1916                 ext2fs_free(fs);
1917                 exit(1);
1918         }
1919         fs->default_bitmap_type = EXT2FS_BMAP64_RBTREE;
1920
1921         if (I_flag && !io_ptr_orig) {
1922                 /*
1923                  * Check the inode size is right so we can issue an
1924                  * error message and bail before setting up the tdb
1925                  * file.
1926                  */
1927                 if (new_inode_size == EXT2_INODE_SIZE(fs->super)) {
1928                         fprintf(stderr, _("The inode size is already %lu\n"),
1929                                 new_inode_size);
1930                         rc = 1;
1931                         goto closefs;
1932                 }
1933                 if (new_inode_size < EXT2_INODE_SIZE(fs->super)) {
1934                         fprintf(stderr, _("Shrinking the inode size is "
1935                                           "not supported\n"));
1936                         rc = 1;
1937                         goto closefs;
1938                 }
1939
1940                 /*
1941                  * If inode resize is requested use the
1942                  * Undo I/O manager
1943                  */
1944                 io_ptr_orig = io_ptr;
1945                 retval = tune2fs_setup_tdb(device_name, &io_ptr);
1946                 if (retval) {
1947                         rc = 1;
1948                         goto closefs;
1949                 }
1950                 if (io_ptr != io_ptr_orig) {
1951                         ext2fs_close(fs);
1952                         goto retry_open;
1953                 }
1954         }
1955
1956         sb = fs->super;
1957         fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
1958
1959         if (print_label) {
1960                 /* For e2label emulation */
1961                 printf("%.*s\n", (int) sizeof(sb->s_volume_name),
1962                        sb->s_volume_name);
1963                 remove_error_table(&et_ext2_error_table);
1964                 goto closefs;
1965         }
1966
1967         retval = ext2fs_check_if_mounted(device_name, &mount_flags);
1968         if (retval) {
1969                 com_err("ext2fs_check_if_mount", retval,
1970                         _("while determining whether %s is mounted."),
1971                         device_name);
1972                 rc = 1;
1973                 goto closefs;
1974         }
1975         /* Normally we only need to write out the superblock */
1976         fs->flags |= EXT2_FLAG_SUPER_ONLY;
1977
1978         if (c_flag) {
1979                 sb->s_max_mnt_count = max_mount_count;
1980                 ext2fs_mark_super_dirty(fs);
1981                 printf(_("Setting maximal mount count to %d\n"),
1982                        max_mount_count);
1983         }
1984         if (C_flag) {
1985                 sb->s_mnt_count = mount_count;
1986                 ext2fs_mark_super_dirty(fs);
1987                 printf(_("Setting current mount count to %d\n"), mount_count);
1988         }
1989         if (e_flag) {
1990                 sb->s_errors = errors;
1991                 ext2fs_mark_super_dirty(fs);
1992                 printf(_("Setting error behavior to %d\n"), errors);
1993         }
1994         if (g_flag) {
1995                 sb->s_def_resgid = resgid;
1996                 ext2fs_mark_super_dirty(fs);
1997                 printf(_("Setting reserved blocks gid to %lu\n"), resgid);
1998         }
1999         if (i_flag) {
2000                 if (interval >= (1ULL << 32)) {
2001                         com_err(program_name, 0,
2002                                 _("interval between checks is too big (%lu)"),
2003                                 interval);
2004                         rc = 1;
2005                         goto closefs;
2006                 }
2007                 sb->s_checkinterval = interval;
2008                 ext2fs_mark_super_dirty(fs);
2009                 printf(_("Setting interval between checks to %lu seconds\n"),
2010                        interval);
2011         }
2012         if (m_flag) {
2013                 ext2fs_r_blocks_count_set(sb, reserved_ratio *
2014                                           ext2fs_blocks_count(sb) / 100.0);
2015                 ext2fs_mark_super_dirty(fs);
2016                 printf (_("Setting reserved blocks percentage to %g%% (%llu blocks)\n"),
2017                         reserved_ratio, ext2fs_r_blocks_count(sb));
2018         }
2019         if (r_flag) {
2020                 if (reserved_blocks > ext2fs_blocks_count(sb)/2) {
2021                         com_err(program_name, 0,
2022                                 _("reserved blocks count is too big (%llu)"),
2023                                 reserved_blocks);
2024                         rc = 1;
2025                         goto closefs;
2026                 }
2027                 ext2fs_r_blocks_count_set(sb, reserved_blocks);
2028                 ext2fs_mark_super_dirty(fs);
2029                 printf(_("Setting reserved blocks count to %llu\n"),
2030                        reserved_blocks);
2031         }
2032         if (s_flag == 1) {
2033                 if (sb->s_feature_ro_compat &
2034                     EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER)
2035                         fputs(_("\nThe filesystem already has sparse "
2036                                 "superblocks.\n"), stderr);
2037                 else {
2038                         sb->s_feature_ro_compat |=
2039                                 EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER;
2040                         sb->s_state &= ~EXT2_VALID_FS;
2041                         ext2fs_mark_super_dirty(fs);
2042                         printf(_("\nSparse superblock flag set.  %s"),
2043                                _(please_fsck));
2044                 }
2045         }
2046         if (s_flag == 0) {
2047                 fputs(_("\nClearing the sparse superflag not supported.\n"),
2048                       stderr);
2049                 rc = 1;
2050                 goto closefs;
2051         }
2052         if (T_flag) {
2053                 sb->s_lastcheck = last_check_time;
2054                 ext2fs_mark_super_dirty(fs);
2055                 printf(_("Setting time filesystem last checked to %s\n"),
2056                        ctime(&last_check_time));
2057         }
2058         if (u_flag) {
2059                 sb->s_def_resuid = resuid;
2060                 ext2fs_mark_super_dirty(fs);
2061                 printf(_("Setting reserved blocks uid to %lu\n"), resuid);
2062         }
2063         if (L_flag) {
2064                 if (strlen(new_label) > sizeof(sb->s_volume_name))
2065                         fputs(_("Warning: label too long, truncating.\n"),
2066                               stderr);
2067                 memset(sb->s_volume_name, 0, sizeof(sb->s_volume_name));
2068                 strncpy(sb->s_volume_name, new_label,
2069                         sizeof(sb->s_volume_name));
2070                 ext2fs_mark_super_dirty(fs);
2071         }
2072         if (M_flag) {
2073                 memset(sb->s_last_mounted, 0, sizeof(sb->s_last_mounted));
2074                 strncpy(sb->s_last_mounted, new_last_mounted,
2075                         sizeof(sb->s_last_mounted));
2076                 ext2fs_mark_super_dirty(fs);
2077         }
2078         if (mntopts_cmd) {
2079                 rc = update_mntopts(fs, mntopts_cmd);
2080                 if (rc)
2081                         goto closefs;
2082         }
2083         if (features_cmd) {
2084                 rc = update_feature_set(fs, features_cmd);
2085                 if (rc)
2086                         goto closefs;
2087         }
2088         if (extended_cmd) {
2089                 rc = parse_extended_opts(fs, extended_cmd);
2090                 if (rc)
2091                         goto closefs;
2092                 if (clear_mmp && !f_flag) {
2093                         fputs(_("Error in using clear_mmp. "
2094                                 "It must be used with -f\n"),
2095                               stderr);
2096                         goto closefs;
2097                 }
2098         }
2099         if (clear_mmp) {
2100                 rc = ext2fs_mmp_clear(fs);
2101                 goto closefs;
2102         }
2103         if (journal_size || journal_device) {
2104                 rc = add_journal(fs);
2105                 if (rc)
2106                         goto closefs;
2107         }
2108
2109         if (Q_flag) {
2110                 if (mount_flags & EXT2_MF_MOUNTED) {
2111                         fputs(_("The quota feature may only be changed when "
2112                                 "the filesystem is unmounted.\n"), stderr);
2113                         rc = 1;
2114                         goto closefs;
2115                 }
2116                 handle_quota_options(fs);
2117         }
2118
2119         if (U_flag) {
2120                 int set_csum = 0;
2121                 dgrp_t i;
2122
2123                 if (sb->s_feature_ro_compat &
2124                     EXT4_FEATURE_RO_COMPAT_GDT_CSUM) {
2125                         /*
2126                          * Determine if the block group checksums are
2127                          * correct so we know whether or not to set
2128                          * them later on.
2129                          */
2130                         for (i = 0; i < fs->group_desc_count; i++)
2131                                 if (!ext2fs_group_desc_csum_verify(fs, i))
2132                                         break;
2133                         if (i >= fs->group_desc_count)
2134                                 set_csum = 1;
2135                 }
2136                 if ((strcasecmp(new_UUID, "null") == 0) ||
2137                     (strcasecmp(new_UUID, "clear") == 0)) {
2138                         uuid_clear(sb->s_uuid);
2139                 } else if (strcasecmp(new_UUID, "time") == 0) {
2140                         uuid_generate_time(sb->s_uuid);
2141                 } else if (strcasecmp(new_UUID, "random") == 0) {
2142                         uuid_generate(sb->s_uuid);
2143                 } else if (uuid_parse(new_UUID, sb->s_uuid)) {
2144                         com_err(program_name, 0, _("Invalid UUID format\n"));
2145                         rc = 1;
2146                         goto closefs;
2147                 }
2148                 if (set_csum) {
2149                         for (i = 0; i < fs->group_desc_count; i++)
2150                                 ext2fs_group_desc_csum_set(fs, i);
2151                         fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
2152                 }
2153                 ext2fs_mark_super_dirty(fs);
2154         }
2155         if (I_flag) {
2156                 if (mount_flags & EXT2_MF_MOUNTED) {
2157                         fputs(_("The inode size may only be "
2158                                 "changed when the filesystem is "
2159                                 "unmounted.\n"), stderr);
2160                         rc = 1;
2161                         goto closefs;
2162                 }
2163                 if (fs->super->s_feature_incompat &
2164                     EXT4_FEATURE_INCOMPAT_FLEX_BG) {
2165                         fputs(_("Changing the inode size not supported for "
2166                                 "filesystems with the flex_bg\n"
2167                                 "feature enabled.\n"),
2168                               stderr);
2169                         rc = 1;
2170                         goto closefs;
2171                 }
2172                 /*
2173                  * We want to update group descriptor also
2174                  * with the new free inode count
2175                  */
2176                 fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
2177                 if (resize_inode(fs, new_inode_size) == 0) {
2178                         printf(_("Setting inode size %lu\n"),
2179                                                         new_inode_size);
2180                 } else {
2181                         printf(_("Failed to change inode size\n"));
2182                         rc = 1;
2183                         goto closefs;
2184                 }
2185         }
2186
2187         if (l_flag)
2188                 list_super(sb);
2189         if (stride_set) {
2190                 sb->s_raid_stride = stride;
2191                 ext2fs_mark_super_dirty(fs);
2192                 printf(_("Setting stride size to %d\n"), stride);
2193         }
2194         if (stripe_width_set) {
2195                 sb->s_raid_stripe_width = stripe_width;
2196                 ext2fs_mark_super_dirty(fs);
2197                 printf(_("Setting stripe width to %d\n"), stripe_width);
2198         }
2199         if (ext_mount_opts) {
2200                 strncpy((char *)(fs->super->s_mount_opts), ext_mount_opts,
2201                         sizeof(fs->super->s_mount_opts));
2202                 fs->super->s_mount_opts[sizeof(fs->super->s_mount_opts)-1] = 0;
2203                 ext2fs_mark_super_dirty(fs);
2204                 printf(_("Setting extended default mount options to '%s'\n"),
2205                        ext_mount_opts);
2206                 free(ext_mount_opts);
2207         }
2208         free(device_name);
2209         remove_error_table(&et_ext2_error_table);
2210
2211 closefs:
2212         if (rc) {
2213                 ext2fs_mmp_stop(fs);
2214                 exit(1);
2215         }
2216
2217         return (ext2fs_close(fs) ? 1 : 0);
2218 }