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