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