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