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