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