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