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