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