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