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