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