tune2fs.c revision 8d8224550c1f5b5c77afbf5acd95f73979276a0a
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 <fcntl.h>
31#include <grp.h>
32#ifdef HAVE_GETOPT_H
33#include <getopt.h>
34#else
35extern char *optarg;
36extern int optind;
37#endif
38#include <pwd.h>
39#include <stdio.h>
40#ifdef HAVE_STDLIB_H
41#include <stdlib.h>
42#endif
43#include <string.h>
44#include <time.h>
45#include <unistd.h>
46#include <sys/types.h>
47#include <libgen.h>
48#include <limits.h>
49
50#include "ext2fs/ext2_fs.h"
51#include "ext2fs/ext2fs.h"
52#include "et/com_err.h"
53#include "uuid/uuid.h"
54#include "e2p/e2p.h"
55#include "jfs_user.h"
56#include "util.h"
57#include "blkid/blkid.h"
58
59#include "../version.h"
60#include "nls-enable.h"
61
62const char *program_name = "tune2fs";
63char *device_name;
64char *new_label, *new_last_mounted, *new_UUID;
65char *io_options;
66static int c_flag, C_flag, e_flag, f_flag, g_flag, i_flag, l_flag, L_flag;
67static int m_flag, M_flag, r_flag, s_flag = -1, u_flag, U_flag, T_flag;
68static int I_flag;
69static time_t last_check_time;
70static int print_label;
71static int max_mount_count, mount_count, mount_flags;
72static unsigned long interval, reserved_blocks;
73static double reserved_ratio;
74static unsigned long resgid, resuid;
75static unsigned short errors;
76static int open_flag;
77static char *features_cmd;
78static char *mntopts_cmd;
79static int stride, stripe_width;
80static int stride_set, stripe_width_set;
81static char *extended_cmd;
82static unsigned long new_inode_size;
83
84int journal_size, journal_flags;
85char *journal_device;
86
87static struct list_head blk_move_list;
88
89struct blk_move {
90	struct list_head list;
91	blk_t old_loc;
92	blk_t new_loc;
93};
94
95
96static const char *please_fsck = N_("Please run e2fsck on the filesystem.\n");
97
98void do_findfs(int argc, char **argv);
99
100static void usage(void)
101{
102	fprintf(stderr,
103		_("Usage: %s [-c max_mounts_count] [-e errors_behavior] "
104		  "[-g group]\n"
105		  "\t[-i interval[d|m|w]] [-j] [-J journal_options] [-l]\n"
106		  "\t[-m reserved_blocks_percent] "
107		  "[-o [^]mount_options[,...]] \n"
108		  "\t[-r reserved_blocks_count] [-u user] [-C mount_count] "
109		  "[-L volume_label]\n"
110		  "\t[-M last_mounted_dir] [-O [^]feature[,...]]\n"
111		  "\t[-E extended-option[,...]] [-T last_check_time] "
112		  "[-U UUID]\n\t[ -I new_inode_size ] device\n"), program_name);
113	exit(1);
114}
115
116static __u32 ok_features[3] = {
117	/* Compat */
118	EXT3_FEATURE_COMPAT_HAS_JOURNAL |
119		EXT2_FEATURE_COMPAT_DIR_INDEX,
120	/* Incompat */
121	EXT2_FEATURE_INCOMPAT_FILETYPE |
122		EXT3_FEATURE_INCOMPAT_EXTENTS |
123		EXT4_FEATURE_INCOMPAT_FLEX_BG,
124	/* R/O compat */
125	EXT2_FEATURE_RO_COMPAT_LARGE_FILE |
126		EXT4_FEATURE_RO_COMPAT_HUGE_FILE|
127		EXT4_FEATURE_RO_COMPAT_DIR_NLINK|
128		EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE|
129		EXT4_FEATURE_RO_COMPAT_GDT_CSUM |
130		EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER
131};
132
133static __u32 clear_ok_features[3] = {
134	/* Compat */
135	EXT3_FEATURE_COMPAT_HAS_JOURNAL |
136		EXT2_FEATURE_COMPAT_RESIZE_INODE |
137		EXT2_FEATURE_COMPAT_DIR_INDEX,
138	/* Incompat */
139	EXT2_FEATURE_INCOMPAT_FILETYPE |
140		EXT4_FEATURE_INCOMPAT_FLEX_BG,
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};
148
149/*
150 * Remove an external journal from the filesystem
151 */
152static void remove_journal_device(ext2_filsys fs)
153{
154	char		*journal_path;
155	ext2_filsys	jfs;
156	char		buf[1024];
157	journal_superblock_t	*jsb;
158	int		i, nr_users;
159	errcode_t	retval;
160	int		commit_remove_journal = 0;
161	io_manager	io_ptr;
162
163	if (f_flag)
164		commit_remove_journal = 1; /* force removal even if error */
165
166	uuid_unparse(fs->super->s_journal_uuid, buf);
167	journal_path = blkid_get_devname(NULL, "UUID", buf);
168
169	if (!journal_path) {
170		journal_path =
171			ext2fs_find_block_device(fs->super->s_journal_dev);
172		if (!journal_path)
173			return;
174	}
175
176#ifdef CONFIG_TESTIO_DEBUG
177	if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_BLOCK")) {
178		io_ptr = test_io_manager;
179		test_io_backing_manager = unix_io_manager;
180	} else
181#endif
182		io_ptr = unix_io_manager;
183	retval = ext2fs_open(journal_path, EXT2_FLAG_RW|
184			     EXT2_FLAG_JOURNAL_DEV_OK, 0,
185			     fs->blocksize, io_ptr, &jfs);
186	if (retval) {
187		com_err(program_name, retval,
188			_("while trying to open external journal"));
189		goto no_valid_journal;
190	}
191	if (!(jfs->super->s_feature_incompat & EXT3_FEATURE_INCOMPAT_JOURNAL_DEV)) {
192		fprintf(stderr, _("%s is not a journal device.\n"),
193			journal_path);
194		goto no_valid_journal;
195	}
196
197	/* Get the journal superblock */
198	if ((retval = io_channel_read_blk(jfs->io, 1, -1024, buf))) {
199		com_err(program_name, retval,
200			_("while reading journal superblock"));
201		goto no_valid_journal;
202	}
203
204	jsb = (journal_superblock_t *) buf;
205	if ((jsb->s_header.h_magic != (unsigned) ntohl(JFS_MAGIC_NUMBER)) ||
206	    (jsb->s_header.h_blocktype != (unsigned) ntohl(JFS_SUPERBLOCK_V2))) {
207		fputs(_("Journal superblock not found!\n"), stderr);
208		goto no_valid_journal;
209	}
210
211	/* Find the filesystem UUID */
212	nr_users = ntohl(jsb->s_nr_users);
213	for (i = 0; i < nr_users; i++) {
214		if (memcmp(fs->super->s_uuid,
215			   &jsb->s_users[i*16], 16) == 0)
216			break;
217	}
218	if (i >= nr_users) {
219		fputs(_("Filesystem's UUID not found on journal device.\n"),
220		      stderr);
221		commit_remove_journal = 1;
222		goto no_valid_journal;
223	}
224	nr_users--;
225	for (i = 0; i < nr_users; i++)
226		memcpy(&jsb->s_users[i*16], &jsb->s_users[(i+1)*16], 16);
227	jsb->s_nr_users = htonl(nr_users);
228
229	/* Write back the journal superblock */
230	if ((retval = io_channel_write_blk(jfs->io, 1, -1024, buf))) {
231		com_err(program_name, retval,
232			"while writing journal superblock.");
233		goto no_valid_journal;
234	}
235
236	commit_remove_journal = 1;
237
238no_valid_journal:
239	if (commit_remove_journal == 0) {
240		fputs(_("Journal NOT removed\n"), stderr);
241		exit(1);
242	}
243	fs->super->s_journal_dev = 0;
244	uuid_clear(fs->super->s_journal_uuid);
245	ext2fs_mark_super_dirty(fs);
246	fputs(_("Journal removed\n"), stdout);
247	free(journal_path);
248}
249
250/* Helper function for remove_journal_inode */
251static int release_blocks_proc(ext2_filsys fs, blk_t *blocknr,
252			       int blockcnt EXT2FS_ATTR((unused)),
253			       void *private EXT2FS_ATTR((unused)))
254{
255	blk_t	block;
256	int	group;
257
258	block = *blocknr;
259	ext2fs_unmark_block_bitmap(fs->block_map, block);
260	group = ext2fs_group_of_blk(fs, block);
261	fs->group_desc[group].bg_free_blocks_count++;
262	ext2fs_group_desc_csum_set(fs, group);
263	fs->super->s_free_blocks_count++;
264	return 0;
265}
266
267/*
268 * Remove the journal inode from the filesystem
269 */
270static void remove_journal_inode(ext2_filsys fs)
271{
272	struct ext2_inode	inode;
273	errcode_t		retval;
274	ino_t			ino = fs->super->s_journal_inum;
275
276	retval = ext2fs_read_inode(fs, ino,  &inode);
277	if (retval) {
278		com_err(program_name, retval,
279			_("while reading journal inode"));
280		exit(1);
281	}
282	if (ino == EXT2_JOURNAL_INO) {
283		retval = ext2fs_read_bitmaps(fs);
284		if (retval) {
285			com_err(program_name, retval,
286				_("while reading bitmaps"));
287			exit(1);
288		}
289		retval = ext2fs_block_iterate(fs, ino,
290					      BLOCK_FLAG_READ_ONLY, NULL,
291					      release_blocks_proc, NULL);
292		if (retval) {
293			com_err(program_name, retval,
294				_("while clearing journal inode"));
295			exit(1);
296		}
297		memset(&inode, 0, sizeof(inode));
298		ext2fs_mark_bb_dirty(fs);
299		fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
300	} else
301		inode.i_flags &= ~EXT2_IMMUTABLE_FL;
302	retval = ext2fs_write_inode(fs, ino, &inode);
303	if (retval) {
304		com_err(program_name, retval,
305			_("while writing journal inode"));
306		exit(1);
307	}
308	fs->super->s_journal_inum = 0;
309	ext2fs_mark_super_dirty(fs);
310}
311
312/*
313 * Update the default mount options
314 */
315static void update_mntopts(ext2_filsys fs, char *mntopts)
316{
317	struct ext2_super_block *sb = fs->super;
318
319	if (e2p_edit_mntopts(mntopts, &sb->s_default_mount_opts, ~0)) {
320		fprintf(stderr, _("Invalid mount option set: %s\n"),
321			mntopts);
322		exit(1);
323	}
324	ext2fs_mark_super_dirty(fs);
325}
326
327/*
328 * Update the feature set as provided by the user.
329 */
330static void update_feature_set(ext2_filsys fs, char *features)
331{
332	struct ext2_super_block *sb = fs->super;
333	__u32		old_features[3];
334	int		type_err;
335	unsigned int	mask_err;
336
337#define FEATURE_ON(type, mask) (!(old_features[(type)] & (mask)) && \
338				((&sb->s_feature_compat)[(type)] & (mask)))
339#define FEATURE_OFF(type, mask) ((old_features[(type)] & (mask)) && \
340				 !((&sb->s_feature_compat)[(type)] & (mask)))
341#define FEATURE_CHANGED(type, mask) ((mask) & \
342		     (old_features[(type)] ^ (&sb->s_feature_compat)[(type)]))
343
344	old_features[E2P_FEATURE_COMPAT] = sb->s_feature_compat;
345	old_features[E2P_FEATURE_INCOMPAT] = sb->s_feature_incompat;
346	old_features[E2P_FEATURE_RO_INCOMPAT] = sb->s_feature_ro_compat;
347
348	if (e2p_edit_feature2(features, &sb->s_feature_compat,
349			      ok_features, clear_ok_features,
350			      &type_err, &mask_err)) {
351		if (!mask_err)
352			fprintf(stderr,
353				_("Invalid filesystem option set: %s\n"),
354				features);
355		else if (type_err & E2P_FEATURE_NEGATE_FLAG)
356			fprintf(stderr, _("Clearing filesystem feature '%s' "
357					  "not supported.\n"),
358				e2p_feature2string(type_err &
359						   E2P_FEATURE_TYPE_MASK,
360						   mask_err));
361		else
362			fprintf(stderr, _("Setting filesystem feature '%s' "
363					  "not supported.\n"),
364				e2p_feature2string(type_err, mask_err));
365		exit(1);
366	}
367
368	if (FEATURE_OFF(E2P_FEATURE_COMPAT, EXT3_FEATURE_COMPAT_HAS_JOURNAL)) {
369		if ((mount_flags & EXT2_MF_MOUNTED) &&
370		    !(mount_flags & EXT2_MF_READONLY)) {
371			fputs(_("The has_journal feature may only be "
372				"cleared when the filesystem is\n"
373				"unmounted or mounted "
374				"read-only.\n"), stderr);
375			exit(1);
376		}
377		if (sb->s_feature_incompat &
378		    EXT3_FEATURE_INCOMPAT_RECOVER) {
379			fputs(_("The needs_recovery flag is set.  "
380				"Please run e2fsck before clearing\n"
381				"the has_journal flag.\n"), stderr);
382			exit(1);
383		}
384		if (sb->s_journal_inum) {
385			remove_journal_inode(fs);
386		}
387		if (sb->s_journal_dev) {
388			remove_journal_device(fs);
389		}
390	}
391
392	if (FEATURE_ON(E2P_FEATURE_COMPAT, EXT3_FEATURE_COMPAT_HAS_JOURNAL)) {
393		/*
394		 * If adding a journal flag, let the create journal
395		 * code below handle setting the flag and creating the
396		 * journal.  We supply a default size if necessary.
397		 */
398		if (!journal_size)
399			journal_size = -1;
400		sb->s_feature_compat &= ~EXT3_FEATURE_COMPAT_HAS_JOURNAL;
401	}
402
403	if (FEATURE_ON(E2P_FEATURE_COMPAT, EXT2_FEATURE_COMPAT_DIR_INDEX)) {
404		if (!sb->s_def_hash_version)
405			sb->s_def_hash_version = EXT2_HASH_HALF_MD4;
406		if (uuid_is_null((unsigned char *) sb->s_hash_seed))
407			uuid_generate((unsigned char *) sb->s_hash_seed);
408	}
409
410	if (FEATURE_OFF(E2P_FEATURE_INCOMPAT, EXT4_FEATURE_INCOMPAT_FLEX_BG)) {
411		if (ext2fs_check_desc(fs)) {
412			fputs(_("Clearing the flex_bg flag would "
413				"cause the the filesystem to be\n"
414				"inconsistent.\n"), stderr);
415			exit(1);
416		}
417	}
418
419	if (FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
420			    EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
421		if ((mount_flags & EXT2_MF_MOUNTED) &&
422		    !(mount_flags & EXT2_MF_READONLY)) {
423			fputs(_("The huge_file feature may only be "
424				"cleared when the filesystem is\n"
425				"unmounted or mounted "
426				"read-only.\n"), stderr);
427			exit(1);
428		}
429	}
430
431	if (sb->s_rev_level == EXT2_GOOD_OLD_REV &&
432	    (sb->s_feature_compat || sb->s_feature_ro_compat ||
433	     sb->s_feature_incompat))
434		ext2fs_update_dynamic_rev(fs);
435
436	if (FEATURE_CHANGED(E2P_FEATURE_RO_INCOMPAT,
437			    EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER) ||
438	    FEATURE_CHANGED(E2P_FEATURE_RO_INCOMPAT,
439			    EXT4_FEATURE_RO_COMPAT_GDT_CSUM) ||
440	    FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
441			EXT4_FEATURE_RO_COMPAT_HUGE_FILE) ||
442	    FEATURE_CHANGED(E2P_FEATURE_INCOMPAT,
443			    EXT2_FEATURE_INCOMPAT_FILETYPE) ||
444	    FEATURE_CHANGED(E2P_FEATURE_COMPAT,
445			    EXT2_FEATURE_COMPAT_RESIZE_INODE) ||
446	    FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
447			EXT2_FEATURE_RO_COMPAT_LARGE_FILE)) {
448		sb->s_state &= ~EXT2_VALID_FS;
449		printf("\n%s\n", _(please_fsck));
450		if (mount_flags & EXT2_MF_READONLY)
451			printf(_("(and reboot afterwards!)\n"));
452	}
453
454	if ((old_features[E2P_FEATURE_COMPAT] != sb->s_feature_compat) ||
455	    (old_features[E2P_FEATURE_INCOMPAT] != sb->s_feature_incompat) ||
456	    (old_features[E2P_FEATURE_RO_INCOMPAT] != sb->s_feature_ro_compat))
457		ext2fs_mark_super_dirty(fs);
458}
459
460/*
461 * Add a journal to the filesystem.
462 */
463static void add_journal(ext2_filsys fs)
464{
465	unsigned long journal_blocks;
466	errcode_t	retval;
467	ext2_filsys	jfs;
468	io_manager	io_ptr;
469
470	if (fs->super->s_feature_compat &
471	    EXT3_FEATURE_COMPAT_HAS_JOURNAL) {
472		fputs(_("The filesystem already has a journal.\n"), stderr);
473		goto err;
474	}
475	if (journal_device) {
476		check_plausibility(journal_device);
477		check_mount(journal_device, 0, _("journal"));
478#ifdef CONFIG_TESTIO_DEBUG
479		if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_BLOCK")) {
480			io_ptr = test_io_manager;
481			test_io_backing_manager = unix_io_manager;
482		} else
483#endif
484			io_ptr = unix_io_manager;
485		retval = ext2fs_open(journal_device, EXT2_FLAG_RW|
486				     EXT2_FLAG_JOURNAL_DEV_OK, 0,
487				     fs->blocksize, io_ptr, &jfs);
488		if (retval) {
489			com_err(program_name, retval,
490				_("\n\twhile trying to open journal on %s\n"),
491				journal_device);
492			goto err;
493		}
494		printf(_("Creating journal on device %s: "),
495		       journal_device);
496		fflush(stdout);
497
498		retval = ext2fs_add_journal_device(fs, jfs);
499		ext2fs_close(jfs);
500		if (retval) {
501			com_err(program_name, retval,
502				_("while adding filesystem to journal on %s"),
503				journal_device);
504			goto err;
505		}
506		fputs(_("done\n"), stdout);
507	} else if (journal_size) {
508		fputs(_("Creating journal inode: "), stdout);
509		fflush(stdout);
510		journal_blocks = figure_journal_size(journal_size, fs);
511
512		retval = ext2fs_add_journal_inode(fs, journal_blocks,
513						  journal_flags);
514		if (retval) {
515			fprintf(stderr, "\n");
516			com_err(program_name, retval,
517				_("\n\twhile trying to create journal file"));
518			exit(1);
519		} else
520			fputs(_("done\n"), stdout);
521		/*
522		 * If the filesystem wasn't mounted, we need to force
523		 * the block group descriptors out.
524		 */
525		if ((mount_flags & EXT2_MF_MOUNTED) == 0)
526			fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
527	}
528	print_check_message(fs);
529	return;
530
531err:
532	if (journal_device)
533		free(journal_device);
534	exit(1);
535}
536
537
538static void parse_e2label_options(int argc, char ** argv)
539{
540	if ((argc < 2) || (argc > 3)) {
541		fputs(_("Usage: e2label device [newlabel]\n"), stderr);
542		exit(1);
543	}
544	io_options = strchr(argv[1], '?');
545	if (io_options)
546		*io_options++ = 0;
547	device_name = blkid_get_devname(NULL, argv[1], NULL);
548	if (!device_name) {
549		com_err("e2label", 0, _("Unable to resolve '%s'"),
550			argv[1]);
551		exit(1);
552	}
553	open_flag = EXT2_FLAG_JOURNAL_DEV_OK;
554	if (argc == 3) {
555		open_flag |= EXT2_FLAG_RW;
556		L_flag = 1;
557		new_label = argv[2];
558	} else
559		print_label++;
560}
561
562static time_t parse_time(char *str)
563{
564	struct	tm	ts;
565
566	if (strcmp(str, "now") == 0) {
567		return (time(0));
568	}
569	memset(&ts, 0, sizeof(ts));
570#ifdef HAVE_STRPTIME
571	strptime(str, "%Y%m%d%H%M%S", &ts);
572#else
573	sscanf(str, "%4d%2d%2d%2d%2d%2d", &ts.tm_year, &ts.tm_mon,
574	       &ts.tm_mday, &ts.tm_hour, &ts.tm_min, &ts.tm_sec);
575	ts.tm_year -= 1900;
576	ts.tm_mon -= 1;
577	if (ts.tm_year < 0 || ts.tm_mon < 0 || ts.tm_mon > 11 ||
578	    ts.tm_mday < 0 || ts.tm_mday > 31 || ts.tm_hour > 23 ||
579	    ts.tm_min > 59 || ts.tm_sec > 61)
580		ts.tm_mday = 0;
581#endif
582	if (ts.tm_mday == 0) {
583		com_err(program_name, 0,
584			_("Couldn't parse date/time specifier: %s"),
585			str);
586		usage();
587	}
588	ts.tm_isdst = -1;
589	return (mktime(&ts));
590}
591
592static void parse_tune2fs_options(int argc, char **argv)
593{
594	int c;
595	char *tmp;
596	struct group *gr;
597	struct passwd *pw;
598
599	open_flag = 0;
600
601	printf("tune2fs %s (%s)\n", E2FSPROGS_VERSION, E2FSPROGS_DATE);
602	while ((c = getopt(argc, argv, "c:e:fg:i:jlm:o:r:s:u:C:E:I:J:L:M:O:T:U:")) != EOF)
603		switch (c) {
604		case 'c':
605			max_mount_count = strtol(optarg, &tmp, 0);
606			if (*tmp || max_mount_count > 16000) {
607				com_err(program_name, 0,
608					_("bad mounts count - %s"),
609					optarg);
610				usage();
611			}
612			if (max_mount_count == 0)
613				max_mount_count = -1;
614			c_flag = 1;
615			open_flag = EXT2_FLAG_RW;
616			break;
617		case 'C':
618			mount_count = strtoul(optarg, &tmp, 0);
619			if (*tmp || mount_count > 16000) {
620				com_err(program_name, 0,
621					_("bad mounts count - %s"),
622					optarg);
623				usage();
624			}
625			C_flag = 1;
626			open_flag = EXT2_FLAG_RW;
627			break;
628		case 'e':
629			if (strcmp(optarg, "continue") == 0)
630				errors = EXT2_ERRORS_CONTINUE;
631			else if (strcmp(optarg, "remount-ro") == 0)
632				errors = EXT2_ERRORS_RO;
633			else if (strcmp(optarg, "panic") == 0)
634				errors = EXT2_ERRORS_PANIC;
635			else {
636				com_err(program_name, 0,
637					_("bad error behavior - %s"),
638					optarg);
639				usage();
640			}
641			e_flag = 1;
642			open_flag = EXT2_FLAG_RW;
643			break;
644		case 'E':
645			extended_cmd = optarg;
646			open_flag |= EXT2_FLAG_RW;
647			break;
648		case 'f': /* Force */
649			f_flag = 1;
650			break;
651		case 'g':
652			resgid = strtoul(optarg, &tmp, 0);
653			if (*tmp) {
654				gr = getgrnam(optarg);
655				if (gr == NULL)
656					tmp = optarg;
657				else {
658					resgid = gr->gr_gid;
659					*tmp = 0;
660				}
661			}
662			if (*tmp) {
663				com_err(program_name, 0,
664					_("bad gid/group name - %s"),
665					optarg);
666				usage();
667			}
668			g_flag = 1;
669			open_flag = EXT2_FLAG_RW;
670			break;
671		case 'i':
672			interval = strtoul(optarg, &tmp, 0);
673			switch (*tmp) {
674			case 's':
675				tmp++;
676				break;
677			case '\0':
678			case 'd':
679			case 'D': /* days */
680				interval *= 86400;
681				if (*tmp != '\0')
682					tmp++;
683				break;
684			case 'm':
685			case 'M': /* months! */
686				interval *= 86400 * 30;
687				tmp++;
688				break;
689			case 'w':
690			case 'W': /* weeks */
691				interval *= 86400 * 7;
692				tmp++;
693				break;
694			}
695			if (*tmp) {
696				com_err(program_name, 0,
697					_("bad interval - %s"), optarg);
698				usage();
699			}
700			i_flag = 1;
701			open_flag = EXT2_FLAG_RW;
702			break;
703		case 'j':
704			if (!journal_size)
705				journal_size = -1;
706			open_flag = EXT2_FLAG_RW;
707			break;
708		case 'J':
709			parse_journal_opts(optarg);
710			open_flag = EXT2_FLAG_RW;
711			break;
712		case 'l':
713			l_flag = 1;
714			break;
715		case 'L':
716			new_label = optarg;
717			L_flag = 1;
718			open_flag |= EXT2_FLAG_RW |
719				EXT2_FLAG_JOURNAL_DEV_OK;
720			break;
721		case 'm':
722			reserved_ratio = strtod(optarg, &tmp);
723			if (*tmp || reserved_ratio > 50 ||
724			    reserved_ratio < 0) {
725				com_err(program_name, 0,
726					_("bad reserved block ratio - %s"),
727					optarg);
728				usage();
729			}
730			m_flag = 1;
731			open_flag = EXT2_FLAG_RW;
732			break;
733		case 'M':
734			new_last_mounted = optarg;
735			M_flag = 1;
736			open_flag = EXT2_FLAG_RW;
737			break;
738		case 'o':
739			if (mntopts_cmd) {
740				com_err(program_name, 0,
741					_("-o may only be specified once"));
742				usage();
743			}
744			mntopts_cmd = optarg;
745			open_flag = EXT2_FLAG_RW;
746			break;
747
748		case 'O':
749			if (features_cmd) {
750				com_err(program_name, 0,
751					_("-O may only be specified once"));
752				usage();
753			}
754			features_cmd = optarg;
755			open_flag = EXT2_FLAG_RW;
756			break;
757		case 'r':
758			reserved_blocks = strtoul(optarg, &tmp, 0);
759			if (*tmp) {
760				com_err(program_name, 0,
761					_("bad reserved blocks count - %s"),
762					optarg);
763				usage();
764			}
765			r_flag = 1;
766			open_flag = EXT2_FLAG_RW;
767			break;
768		case 's': /* Deprecated */
769			s_flag = atoi(optarg);
770			open_flag = EXT2_FLAG_RW;
771			break;
772		case 'T':
773			T_flag = 1;
774			last_check_time = parse_time(optarg);
775			open_flag = EXT2_FLAG_RW;
776			break;
777		case 'u':
778				resuid = strtoul(optarg, &tmp, 0);
779				if (*tmp) {
780					pw = getpwnam(optarg);
781					if (pw == NULL)
782						tmp = optarg;
783					else {
784						resuid = pw->pw_uid;
785						*tmp = 0;
786					}
787				}
788				if (*tmp) {
789					com_err(program_name, 0,
790						_("bad uid/user name - %s"),
791						optarg);
792					usage();
793				}
794				u_flag = 1;
795				open_flag = EXT2_FLAG_RW;
796				break;
797		case 'U':
798			new_UUID = optarg;
799			U_flag = 1;
800			open_flag = EXT2_FLAG_RW |
801				EXT2_FLAG_JOURNAL_DEV_OK;
802			break;
803		case 'I':
804			new_inode_size = strtoul(optarg, &tmp, 0);
805			if (*tmp) {
806				com_err(program_name, 0,
807					_("bad inode size - %s"),
808					optarg);
809				usage();
810			}
811			if (!((new_inode_size &
812			       (new_inode_size - 1)) == 0)) {
813				com_err(program_name, 0,
814					_("Inode size must be a "
815					  "power of two- %s"),
816					optarg);
817				usage();
818			}
819			open_flag = EXT2_FLAG_RW;
820			I_flag = 1;
821			break;
822		default:
823			usage();
824		}
825	if (optind < argc - 1 || optind == argc)
826		usage();
827	if (!open_flag && !l_flag)
828		usage();
829	io_options = strchr(argv[optind], '?');
830	if (io_options)
831		*io_options++ = 0;
832	device_name = blkid_get_devname(NULL, argv[optind], NULL);
833	if (!device_name) {
834		com_err("tune2fs", 0, _("Unable to resolve '%s'"),
835			argv[optind]);
836		exit(1);
837	}
838}
839
840void do_findfs(int argc, char **argv)
841{
842	char	*dev;
843
844	if ((argc != 2) ||
845	    (strncmp(argv[1], "LABEL=", 6) && strncmp(argv[1], "UUID=", 5))) {
846		fprintf(stderr, "Usage: findfs LABEL=<label>|UUID=<uuid>\n");
847		exit(2);
848	}
849	dev = blkid_get_devname(NULL, argv[1], NULL);
850	if (!dev) {
851		com_err("findfs", 0, _("Unable to resolve '%s'"),
852			argv[1]);
853		exit(1);
854	}
855	puts(dev);
856	exit(0);
857}
858
859static void parse_extended_opts(ext2_filsys fs, const char *opts)
860{
861	char	*buf, *token, *next, *p, *arg;
862	int	len, hash_alg;
863	int	r_usage = 0;
864
865	len = strlen(opts);
866	buf = malloc(len+1);
867	if (!buf) {
868		fprintf(stderr,
869			_("Couldn't allocate memory to parse options!\n"));
870		exit(1);
871	}
872	strcpy(buf, opts);
873	for (token = buf; token && *token; token = next) {
874		p = strchr(token, ',');
875		next = 0;
876		if (p) {
877			*p = 0;
878			next = p+1;
879		}
880		arg = strchr(token, '=');
881		if (arg) {
882			*arg = 0;
883			arg++;
884		}
885		if (!strcmp(token, "test_fs")) {
886			fs->super->s_flags |= EXT2_FLAGS_TEST_FILESYS;
887			printf("Setting test filesystem flag\n");
888			ext2fs_mark_super_dirty(fs);
889		} else if (!strcmp(token, "^test_fs")) {
890			fs->super->s_flags &= ~EXT2_FLAGS_TEST_FILESYS;
891			printf("Clearing test filesystem flag\n");
892			ext2fs_mark_super_dirty(fs);
893		} else if (strcmp(token, "stride") == 0) {
894			if (!arg) {
895				r_usage++;
896				continue;
897			}
898			stride = strtoul(arg, &p, 0);
899			if (*p || (stride == 0)) {
900				fprintf(stderr,
901				       _("Invalid RAID stride: %s\n"),
902					arg);
903				r_usage++;
904				continue;
905			}
906			stride_set = 1;
907		} else if (strcmp(token, "stripe-width") == 0 ||
908			   strcmp(token, "stripe_width") == 0) {
909			if (!arg) {
910				r_usage++;
911				continue;
912			}
913			stripe_width = strtoul(arg, &p, 0);
914			if (*p || (stripe_width == 0)) {
915				fprintf(stderr,
916					_("Invalid RAID stripe-width: %s\n"),
917					arg);
918				r_usage++;
919				continue;
920			}
921			stripe_width_set = 1;
922		} else if (strcmp(token, "hash_alg") == 0 ||
923			   strcmp(token, "hash-alg") == 0) {
924			if (!arg) {
925				r_usage++;
926				continue;
927			}
928			hash_alg = e2p_string2hash(arg);
929			if (hash_alg < 0) {
930				fprintf(stderr,
931					_("Invalid hash algorithm: %s\n"),
932					arg);
933				r_usage++;
934				continue;
935			}
936			fs->super->s_def_hash_version = hash_alg;
937			printf(_("Setting default hash algorithm "
938				 "to %s (%d)\n"),
939			       arg, hash_alg);
940			ext2fs_mark_super_dirty(fs);
941		} else
942			r_usage++;
943	}
944	if (r_usage) {
945		fprintf(stderr, _("\nBad options specified.\n\n"
946			"Extended options are separated by commas, "
947			"and may take an argument which\n"
948			"\tis set off by an equals ('=') sign.\n\n"
949			"Valid extended options are:\n"
950			"\tstride=<RAID per-disk chunk size in blocks>\n"
951			"\tstripe_width=<RAID stride*data disks in blocks>\n"
952			"\thash_alg=<hash algorithm>\n"
953			"\ttest_fs\n"
954			"\t^test_fs\n"));
955		free(buf);
956		exit(1);
957	}
958	free(buf);
959}
960
961/*
962 * Fill in two bitmaps that we need to to control the inode resizing
963 * process.  The first is the set of blocks that must be moved, and
964 * the second is the set of blocks which are allocation bitmap blocks
965 * and must be treated specially.
966 */
967static int get_move_bitmaps(ext2_filsys fs, int new_ino_blks_per_grp,
968			    ext2fs_block_bitmap bmap,
969			    ext2fs_block_bitmap metadata_bmap)
970{
971	dgrp_t i;
972	blk_t j, needed_blocks = 0;
973	blk_t i_bmap, b_bmap;
974	blk_t start_blk, end_blk;
975	int num, k;
976
977	for (i = 0; i < fs->group_desc_count; i++) {
978		b_bmap = fs->group_desc[i].bg_block_bitmap;
979		ext2fs_mark_block_bitmap(metadata_bmap, b_bmap);
980		i_bmap = fs->group_desc[i].bg_inode_bitmap;
981		ext2fs_mark_block_bitmap(metadata_bmap, i_bmap);
982
983		start_blk = fs->group_desc[i].bg_inode_table +
984					fs->inode_blocks_per_group;
985
986		end_blk = fs->group_desc[i].bg_inode_table +
987					new_ino_blks_per_grp;
988
989		num=0;
990		for (j = start_blk; j < end_blk; j++) {
991			if (ext2fs_test_block_bitmap(fs->block_map, j)) {
992				/* FIXME!!
993				 * What happens if the block is marked
994				 * as a bad block
995				 */
996				ext2fs_mark_block_bitmap(bmap, j);
997				needed_blocks++;
998			} else {
999				/*
1000				 * We are going to use this block for
1001				 * inode table. So mark them used.
1002				 */
1003				ext2fs_mark_block_bitmap(fs->block_map, j);
1004			}
1005			if ((j == i_bmap) || (j == b_bmap))
1006				num++;
1007		}
1008		if (num <= fs->group_desc[i].bg_free_blocks_count)
1009			continue;
1010	}
1011
1012	if (needed_blocks > fs->super->s_free_blocks_count)
1013		return ENOSPC;
1014
1015	return 0;
1016}
1017
1018static int move_block(ext2_filsys fs, ext2fs_block_bitmap bmap,
1019		      ext2fs_block_bitmap metadata_bmap)
1020{
1021	char *buf;
1022	errcode_t retval;
1023	blk_t blk, new_blk, goal;
1024	struct blk_move *bmv;
1025	dgrp_t		group;
1026
1027	retval = ext2fs_get_mem(fs->blocksize, &buf);
1028	if (retval)
1029		return retval;
1030
1031	for (new_blk = blk = fs->super->s_first_data_block;
1032	     blk < fs->super->s_blocks_count; blk++) {
1033		if (!ext2fs_test_block_bitmap(bmap, blk))
1034			continue;
1035
1036		/*
1037		 * If the block is a bitmap block, find a new block in
1038		 * the same block group.
1039		 */
1040		if (ext2fs_test_block_bitmap(metadata_bmap, blk)) {
1041			group = ext2fs_group_of_blk(fs, blk);
1042			goal = ext2fs_group_first_block(fs, group);
1043		} else
1044			goal = new_blk;
1045
1046		retval = ext2fs_new_block(fs, goal, NULL, &new_blk);
1047		if (retval)
1048			goto err_out;
1049
1050		/* Mark this block as allocated */
1051		ext2fs_mark_block_bitmap(fs->block_map, new_blk);
1052
1053		/* Add it to block move list */
1054		retval = ext2fs_get_mem(sizeof(struct blk_move), &bmv);
1055		if (retval)
1056			goto err_out;
1057
1058		bmv->old_loc = blk;
1059		bmv->new_loc = new_blk;
1060
1061		list_add(&(bmv->list), &blk_move_list);
1062
1063		retval = io_channel_read_blk(fs->io, blk, 1, buf);
1064		if (retval)
1065			goto err_out;
1066
1067		retval = io_channel_write_blk(fs->io, new_blk, 1, buf);
1068		if (retval)
1069			goto err_out;
1070	}
1071
1072err_out:
1073	ext2fs_free_mem(&buf);
1074	return retval;
1075}
1076
1077static blk_t translate_block(blk_t blk)
1078{
1079	struct list_head *entry;
1080	struct blk_move *bmv;
1081
1082	list_for_each(entry, &blk_move_list) {
1083		bmv = list_entry(entry, struct blk_move, list);
1084		if (bmv->old_loc == blk)
1085			return bmv->new_loc;
1086	}
1087
1088	return 0;
1089}
1090
1091static int process_block(ext2_filsys fs EXT2FS_ATTR((unused)),
1092			 blk_t *block_nr,
1093			 e2_blkcnt_t blockcnt EXT2FS_ATTR((unused)),
1094			 blk_t ref_block EXT2FS_ATTR((unused)),
1095			 int ref_offset EXT2FS_ATTR((unused)),
1096			 void *priv_data)
1097{
1098	int ret = 0;
1099	blk_t new_blk;
1100	ext2fs_block_bitmap bmap = (ext2fs_block_bitmap) priv_data;
1101
1102	if (!ext2fs_test_block_bitmap(bmap, *block_nr))
1103		return 0;
1104	new_blk = translate_block(*block_nr);
1105	if (new_blk) {
1106		*block_nr = new_blk;
1107		/*
1108		 * This will force the ext2fs_write_inode in the iterator
1109		 */
1110		ret |= BLOCK_CHANGED;
1111	}
1112
1113	return ret;
1114}
1115
1116static int inode_scan_and_fix(ext2_filsys fs, ext2fs_block_bitmap bmap)
1117{
1118	errcode_t retval = 0;
1119	ext2_ino_t ino;
1120	blk_t blk;
1121	char *block_buf = 0;
1122	struct ext2_inode inode;
1123	ext2_inode_scan	scan = NULL;
1124
1125	retval = ext2fs_get_mem(fs->blocksize * 3, &block_buf);
1126	if (retval)
1127		return retval;
1128
1129	retval = ext2fs_open_inode_scan(fs, 0, &scan);
1130	if (retval)
1131		goto err_out;
1132
1133	while (1) {
1134		retval = ext2fs_get_next_inode(scan, &ino, &inode);
1135		if (retval)
1136			goto err_out;
1137
1138		if (!ino)
1139			break;
1140
1141		if (inode.i_links_count == 0)
1142			continue; /* inode not in use */
1143
1144		/* FIXME!!
1145		 * If we end up modifying the journal inode
1146		 * the sb->s_jnl_blocks will differ. But a
1147		 * subsequent e2fsck fixes that.
1148		 * Do we need to fix this ??
1149		 */
1150
1151		if (inode.i_file_acl &&
1152		    ext2fs_test_block_bitmap(bmap, inode.i_file_acl)) {
1153			blk = translate_block(inode.i_file_acl);
1154			if (!blk)
1155				continue;
1156
1157			inode.i_file_acl = blk;
1158
1159			/*
1160			 * Write the inode to disk so that inode table
1161			 * resizing can work
1162			 */
1163			retval = ext2fs_write_inode(fs, ino, &inode);
1164			if (retval)
1165				goto err_out;
1166		}
1167
1168		if (!ext2fs_inode_has_valid_blocks(&inode))
1169			continue;
1170
1171		retval = ext2fs_block_iterate2(fs, ino, 0, block_buf,
1172					       process_block, bmap);
1173		if (retval)
1174			goto err_out;
1175
1176	}
1177
1178err_out:
1179	ext2fs_free_mem(&block_buf);
1180
1181	return retval;
1182}
1183
1184/*
1185 * We need to scan for inode and block bitmaps that may need to be
1186 * moved.  This can take place if the filesystem was formatted for
1187 * RAID arrays using the mke2fs's extended option "stride".
1188 */
1189static int group_desc_scan_and_fix(ext2_filsys fs, ext2fs_block_bitmap bmap)
1190{
1191	dgrp_t i;
1192	blk_t blk, new_blk;
1193
1194	for (i = 0; i < fs->group_desc_count; i++) {
1195		blk = fs->group_desc[i].bg_block_bitmap;
1196		if (ext2fs_test_block_bitmap(bmap, blk)) {
1197			new_blk = translate_block(blk);
1198			if (!new_blk)
1199				continue;
1200			fs->group_desc[i].bg_block_bitmap = new_blk;
1201		}
1202
1203		blk = fs->group_desc[i].bg_inode_bitmap;
1204		if (ext2fs_test_block_bitmap(bmap, blk)) {
1205			new_blk = translate_block(blk);
1206			if (!new_blk)
1207				continue;
1208			fs->group_desc[i].bg_inode_bitmap = new_blk;
1209		}
1210	}
1211	return 0;
1212}
1213
1214
1215static int expand_inode_table(ext2_filsys fs, unsigned long new_ino_size)
1216{
1217	dgrp_t i;
1218	blk_t blk;
1219	errcode_t retval;
1220	int new_ino_blks_per_grp;
1221	unsigned int j;
1222	char *old_itable = NULL, *new_itable = NULL;
1223	char *tmp_old_itable = NULL, *tmp_new_itable = NULL;
1224	unsigned long old_ino_size;
1225	int old_itable_size, new_itable_size;
1226
1227	old_itable_size = fs->inode_blocks_per_group * fs->blocksize;
1228	old_ino_size = EXT2_INODE_SIZE(fs->super);
1229
1230	new_ino_blks_per_grp = ext2fs_div_ceil(
1231					EXT2_INODES_PER_GROUP(fs->super) *
1232					new_ino_size,
1233					fs->blocksize);
1234
1235	new_itable_size = new_ino_blks_per_grp * fs->blocksize;
1236
1237	retval = ext2fs_get_mem(old_itable_size, &old_itable);
1238	if (retval)
1239		return retval;
1240
1241	retval = ext2fs_get_mem(new_itable_size, &new_itable);
1242	if (retval)
1243		goto err_out;
1244
1245	tmp_old_itable = old_itable;
1246	tmp_new_itable = new_itable;
1247
1248	for (i = 0; i < fs->group_desc_count; i++) {
1249		blk = fs->group_desc[i].bg_inode_table;
1250		retval = io_channel_read_blk(fs->io, blk,
1251				fs->inode_blocks_per_group, old_itable);
1252		if (retval)
1253			goto err_out;
1254
1255		for (j = 0; j < EXT2_INODES_PER_GROUP(fs->super); j++) {
1256			memcpy(new_itable, old_itable, old_ino_size);
1257
1258			memset(new_itable+old_ino_size, 0,
1259					new_ino_size - old_ino_size);
1260
1261			new_itable += new_ino_size;
1262			old_itable += old_ino_size;
1263		}
1264
1265		/* reset the pointer */
1266		old_itable = tmp_old_itable;
1267		new_itable = tmp_new_itable;
1268
1269		retval = io_channel_write_blk(fs->io, blk,
1270					new_ino_blks_per_grp, new_itable);
1271		if (retval)
1272			goto err_out;
1273	}
1274
1275	/* Update the meta data */
1276	fs->inode_blocks_per_group = new_ino_blks_per_grp;
1277	fs->super->s_inode_size = new_ino_size;
1278
1279err_out:
1280	if (old_itable)
1281		ext2fs_free_mem(&old_itable);
1282
1283	if (new_itable)
1284		ext2fs_free_mem(&new_itable);
1285
1286	return retval;
1287}
1288
1289static errcode_t ext2fs_calculate_summary_stats(ext2_filsys fs)
1290{
1291	blk_t		blk;
1292	ext2_ino_t	ino;
1293	unsigned int	group = 0;
1294	unsigned int	count = 0;
1295	int		total_free = 0;
1296	int		group_free = 0;
1297
1298	/*
1299	 * First calculate the block statistics
1300	 */
1301	for (blk = fs->super->s_first_data_block;
1302	     blk < fs->super->s_blocks_count; blk++) {
1303		if (!ext2fs_fast_test_block_bitmap(fs->block_map, blk)) {
1304			group_free++;
1305			total_free++;
1306		}
1307		count++;
1308		if ((count == fs->super->s_blocks_per_group) ||
1309		    (blk == fs->super->s_blocks_count-1)) {
1310			fs->group_desc[group++].bg_free_blocks_count =
1311				group_free;
1312			count = 0;
1313			group_free = 0;
1314		}
1315	}
1316	fs->super->s_free_blocks_count = total_free;
1317
1318	/*
1319	 * Next, calculate the inode statistics
1320	 */
1321	group_free = 0;
1322	total_free = 0;
1323	count = 0;
1324	group = 0;
1325
1326	/* Protect loop from wrap-around if s_inodes_count maxed */
1327	for (ino = 1; ino <= fs->super->s_inodes_count && ino > 0; ino++) {
1328		if (!ext2fs_fast_test_inode_bitmap(fs->inode_map, ino)) {
1329			group_free++;
1330			total_free++;
1331		}
1332		count++;
1333		if ((count == fs->super->s_inodes_per_group) ||
1334		    (ino == fs->super->s_inodes_count)) {
1335			fs->group_desc[group++].bg_free_inodes_count =
1336				group_free;
1337			count = 0;
1338			group_free = 0;
1339		}
1340	}
1341	fs->super->s_free_inodes_count = total_free;
1342	ext2fs_mark_super_dirty(fs);
1343	return 0;
1344}
1345
1346#define list_for_each_safe(pos, pnext, head) \
1347	for (pos = (head)->next, pnext = pos->next; pos != (head); \
1348	     pos = pnext, pnext = pos->next)
1349
1350static void free_blk_move_list(void)
1351{
1352	struct list_head *entry, *tmp;
1353	struct blk_move *bmv;
1354
1355	list_for_each_safe(entry, tmp, &blk_move_list) {
1356		bmv = list_entry(entry, struct blk_move, list);
1357		list_del(entry);
1358		ext2fs_free_mem(&bmv);
1359	}
1360	return;
1361}
1362
1363static int resize_inode(ext2_filsys fs, unsigned long new_size)
1364{
1365	errcode_t retval;
1366	int new_ino_blks_per_grp;
1367	ext2fs_block_bitmap bmap, metadata_bmap;
1368
1369	ext2fs_read_inode_bitmap(fs);
1370	ext2fs_read_block_bitmap(fs);
1371	INIT_LIST_HEAD(&blk_move_list);
1372
1373
1374	new_ino_blks_per_grp = ext2fs_div_ceil(
1375					EXT2_INODES_PER_GROUP(fs->super)*
1376					new_size,
1377					fs->blocksize);
1378
1379	/* We may change the file system.
1380	 * Mark the file system as invalid so that
1381	 * the user is prompted to run fsck.
1382	 */
1383	fs->super->s_state &= ~EXT2_VALID_FS;
1384
1385	retval = ext2fs_allocate_block_bitmap(fs, _("blocks to be moved"),
1386						&bmap);
1387	if (retval)
1388		return retval;
1389
1390	retval = ext2fs_allocate_block_bitmap(fs, _("blocks to be moved"),
1391						&metadata_bmap);
1392	if (retval)
1393		return retval;
1394
1395	retval = get_move_bitmaps(fs, new_ino_blks_per_grp, bmap,
1396				  metadata_bmap);
1397	if (retval)
1398		goto err_out;
1399
1400	retval = move_block(fs, bmap, metadata_bmap);
1401	if (retval)
1402		goto err_out;
1403
1404	retval = inode_scan_and_fix(fs, bmap);
1405	if (retval)
1406		goto err_out;
1407
1408	retval = group_desc_scan_and_fix(fs, bmap);
1409	if (retval)
1410		goto err_out;
1411
1412	retval = expand_inode_table(fs, new_size);
1413	if (retval)
1414		goto err_out;
1415
1416	ext2fs_calculate_summary_stats(fs);
1417
1418	fs->super->s_state |= EXT2_VALID_FS;
1419	/* mark super block and block bitmap as dirty */
1420	ext2fs_mark_super_dirty(fs);
1421	ext2fs_mark_bb_dirty(fs);
1422
1423err_out:
1424	free_blk_move_list();
1425	ext2fs_free_block_bitmap(bmap);
1426
1427	return retval;
1428}
1429
1430static int tune2fs_setup_tdb(const char *name, io_manager *io_ptr)
1431{
1432	errcode_t retval = 0;
1433	const char *tdb_dir;
1434	char tdb_file[PATH_MAX];
1435	char *dev_name, *tmp_name;
1436
1437#if 0 /* FIXME!! */
1438	/*
1439	 * Configuration via a conf file would be
1440	 * nice
1441	 */
1442	profile_get_string(profile, "scratch_files",
1443					"directory", 0, 0,
1444					&tdb_dir);
1445#endif
1446	tmp_name = strdup(name);
1447	dev_name = basename(tmp_name);
1448
1449	tdb_dir = getenv("E2FSPROGS_UNDO_DIR");
1450	if (!tdb_dir)
1451		tdb_dir = "/var/lib/e2fsprogs";
1452
1453	if (!strcmp(tdb_dir, "none") || (tdb_dir[0] == 0) ||
1454	    access(tdb_dir, W_OK))
1455		return 0;
1456
1457	sprintf(tdb_file, "%s/tune2fs-%s.e2undo", tdb_dir, dev_name);
1458
1459	if (!access(tdb_file, F_OK)) {
1460		if (unlink(tdb_file) < 0) {
1461			retval = errno;
1462			com_err(program_name, retval,
1463				_("while trying to delete %s"),
1464				tdb_file);
1465			return retval;
1466		}
1467	}
1468
1469	set_undo_io_backing_manager(*io_ptr);
1470	*io_ptr = undo_io_manager;
1471	set_undo_io_backup_file(tdb_file);
1472	printf(_("To undo the tune2fs operation please run "
1473		 "the command\n    e2undo %s %s\n\n"),
1474		 tdb_file, name);
1475	free(tmp_name);
1476	return retval;
1477}
1478
1479int main(int argc, char **argv)
1480{
1481	errcode_t retval;
1482	ext2_filsys fs;
1483	struct ext2_super_block *sb;
1484	io_manager io_ptr, io_ptr_orig = NULL;
1485
1486#ifdef ENABLE_NLS
1487	setlocale(LC_MESSAGES, "");
1488	setlocale(LC_CTYPE, "");
1489	bindtextdomain(NLS_CAT_NAME, LOCALEDIR);
1490	textdomain(NLS_CAT_NAME);
1491#endif
1492	if (argc && *argv)
1493		program_name = *argv;
1494	add_error_table(&et_ext2_error_table);
1495
1496	if (strcmp(get_progname(argv[0]), "findfs") == 0)
1497		do_findfs(argc, argv);
1498	if (strcmp(get_progname(argv[0]), "e2label") == 0)
1499		parse_e2label_options(argc, argv);
1500	else
1501		parse_tune2fs_options(argc, argv);
1502
1503#ifdef CONFIG_TESTIO_DEBUG
1504	if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_DEBUG")) {
1505		io_ptr = test_io_manager;
1506		test_io_backing_manager = unix_io_manager;
1507	} else
1508#endif
1509		io_ptr = unix_io_manager;
1510
1511retry_open:
1512	retval = ext2fs_open2(device_name, io_options, open_flag,
1513			      0, 0, io_ptr, &fs);
1514	if (retval) {
1515			com_err(program_name, retval,
1516				_("while trying to open %s"),
1517			device_name);
1518		fprintf(stderr,
1519			_("Couldn't find valid filesystem superblock.\n"));
1520		exit(1);
1521	}
1522
1523	if (I_flag && !io_ptr_orig) {
1524		/*
1525		 * Check the inode size is right so we can issue an
1526		 * error message and bail before setting up the tdb
1527		 * file.
1528		 */
1529		if (new_inode_size == EXT2_INODE_SIZE(fs->super)) {
1530			fprintf(stderr, _("The inode size is already %d\n"),
1531				new_inode_size);
1532			exit(1);
1533		}
1534		if (new_inode_size < EXT2_INODE_SIZE(fs->super)) {
1535			fprintf(stderr, _("Shrinking the inode size is "
1536					  "not supported\n"));
1537			exit(1);
1538		}
1539
1540		/*
1541		 * If inode resize is requested use the
1542		 * Undo I/O manager
1543		 */
1544		io_ptr_orig = io_ptr;
1545		retval = tune2fs_setup_tdb(device_name, &io_ptr);
1546		if (retval)
1547			exit(1);
1548		if (io_ptr != io_ptr_orig) {
1549			ext2fs_close(fs);
1550			goto retry_open;
1551		}
1552	}
1553
1554	sb = fs->super;
1555	fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
1556
1557	if (print_label) {
1558		/* For e2label emulation */
1559		printf("%.*s\n", (int) sizeof(sb->s_volume_name),
1560		       sb->s_volume_name);
1561		remove_error_table(&et_ext2_error_table);
1562		exit(0);
1563	}
1564
1565	retval = ext2fs_check_if_mounted(device_name, &mount_flags);
1566	if (retval) {
1567		com_err("ext2fs_check_if_mount", retval,
1568			_("while determining whether %s is mounted."),
1569			device_name);
1570		exit(1);
1571	}
1572	/* Normally we only need to write out the superblock */
1573	fs->flags |= EXT2_FLAG_SUPER_ONLY;
1574
1575	if (c_flag) {
1576		sb->s_max_mnt_count = max_mount_count;
1577		ext2fs_mark_super_dirty(fs);
1578		printf(_("Setting maximal mount count to %d\n"),
1579		       max_mount_count);
1580	}
1581	if (C_flag) {
1582		sb->s_mnt_count = mount_count;
1583		ext2fs_mark_super_dirty(fs);
1584		printf(_("Setting current mount count to %d\n"), mount_count);
1585	}
1586	if (e_flag) {
1587		sb->s_errors = errors;
1588		ext2fs_mark_super_dirty(fs);
1589		printf(_("Setting error behavior to %d\n"), errors);
1590	}
1591	if (g_flag) {
1592		sb->s_def_resgid = resgid;
1593		ext2fs_mark_super_dirty(fs);
1594		printf(_("Setting reserved blocks gid to %lu\n"), resgid);
1595	}
1596	if (i_flag) {
1597		sb->s_checkinterval = interval;
1598		ext2fs_mark_super_dirty(fs);
1599		printf(_("Setting interval between checks to %lu seconds\n"),
1600		       interval);
1601	}
1602	if (m_flag) {
1603		sb->s_r_blocks_count = (unsigned int) (reserved_ratio *
1604					sb->s_blocks_count / 100.0);
1605		ext2fs_mark_super_dirty(fs);
1606		printf(_("Setting reserved blocks percentage to %g%% "
1607			 "(%u blocks)\n"),
1608		       reserved_ratio, sb->s_r_blocks_count);
1609	}
1610	if (r_flag) {
1611		if (reserved_blocks >= sb->s_blocks_count/2) {
1612			com_err(program_name, 0,
1613				_("reserved blocks count is too big (%lu)"),
1614				reserved_blocks);
1615			exit(1);
1616		}
1617		sb->s_r_blocks_count = reserved_blocks;
1618		ext2fs_mark_super_dirty(fs);
1619		printf(_("Setting reserved blocks count to %lu\n"),
1620		       reserved_blocks);
1621	}
1622	if (s_flag == 1) {
1623		if (sb->s_feature_ro_compat &
1624		    EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER)
1625			fputs(_("\nThe filesystem already has sparse "
1626				"superblocks.\n"), stderr);
1627		else {
1628			sb->s_feature_ro_compat |=
1629				EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER;
1630			sb->s_state &= ~EXT2_VALID_FS;
1631			ext2fs_mark_super_dirty(fs);
1632			printf(_("\nSparse superblock flag set.  %s"),
1633			       _(please_fsck));
1634		}
1635	}
1636	if (s_flag == 0) {
1637		fputs(_("\nClearing the sparse superflag not supported.\n"),
1638		      stderr);
1639		exit(1);
1640	}
1641	if (T_flag) {
1642		sb->s_lastcheck = last_check_time;
1643		ext2fs_mark_super_dirty(fs);
1644		printf(_("Setting time filesystem last checked to %s\n"),
1645		       ctime(&last_check_time));
1646	}
1647	if (u_flag) {
1648		sb->s_def_resuid = resuid;
1649		ext2fs_mark_super_dirty(fs);
1650		printf(_("Setting reserved blocks uid to %lu\n"), resuid);
1651	}
1652	if (L_flag) {
1653		if (strlen(new_label) > sizeof(sb->s_volume_name))
1654			fputs(_("Warning: label too long, truncating.\n"),
1655			      stderr);
1656		memset(sb->s_volume_name, 0, sizeof(sb->s_volume_name));
1657		strncpy(sb->s_volume_name, new_label,
1658			sizeof(sb->s_volume_name));
1659		ext2fs_mark_super_dirty(fs);
1660	}
1661	if (M_flag) {
1662		memset(sb->s_last_mounted, 0, sizeof(sb->s_last_mounted));
1663		strncpy(sb->s_last_mounted, new_last_mounted,
1664			sizeof(sb->s_last_mounted));
1665		ext2fs_mark_super_dirty(fs);
1666	}
1667	if (mntopts_cmd)
1668		update_mntopts(fs, mntopts_cmd);
1669	if (features_cmd)
1670		update_feature_set(fs, features_cmd);
1671	if (extended_cmd)
1672		parse_extended_opts(fs, extended_cmd);
1673	if (journal_size || journal_device)
1674		add_journal(fs);
1675
1676	if (U_flag) {
1677		int set_csum = 0;
1678		dgrp_t i;
1679
1680		if (sb->s_feature_ro_compat &
1681		    EXT4_FEATURE_RO_COMPAT_GDT_CSUM) {
1682			/*
1683			 * Determine if the block group checksums are
1684			 * correct so we know whether or not to set
1685			 * them later on.
1686			 */
1687			for (i = 0; i < fs->group_desc_count; i++)
1688				if (!ext2fs_group_desc_csum_verify(fs, i))
1689					break;
1690			if (i >= fs->group_desc_count)
1691				set_csum = 1;
1692		}
1693		if ((strcasecmp(new_UUID, "null") == 0) ||
1694		    (strcasecmp(new_UUID, "clear") == 0)) {
1695			uuid_clear(sb->s_uuid);
1696		} else if (strcasecmp(new_UUID, "time") == 0) {
1697			uuid_generate_time(sb->s_uuid);
1698		} else if (strcasecmp(new_UUID, "random") == 0) {
1699			uuid_generate(sb->s_uuid);
1700		} else if (uuid_parse(new_UUID, sb->s_uuid)) {
1701			com_err(program_name, 0, _("Invalid UUID format\n"));
1702			exit(1);
1703		}
1704		if (set_csum) {
1705			for (i = 0; i < fs->group_desc_count; i++)
1706				ext2fs_group_desc_csum_set(fs, i);
1707			fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
1708		}
1709		ext2fs_mark_super_dirty(fs);
1710	}
1711	if (I_flag) {
1712		if (mount_flags & EXT2_MF_MOUNTED) {
1713			fputs(_("The inode size may only be "
1714				"changed when the filesystem is "
1715				"unmounted.\n"), stderr);
1716			exit(1);
1717		}
1718		if (fs->super->s_feature_incompat &
1719		    EXT4_FEATURE_INCOMPAT_FLEX_BG) {
1720			fputs(_("Changing the inode size not supported for "
1721				"filesystems with the flex_bg\n"
1722				"feature enabled.\n"),
1723			      stderr);
1724			exit(1);
1725		}
1726		/*
1727		 * We want to update group descriptor also
1728		 * with the new free inode count
1729		 */
1730		fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
1731		if (resize_inode(fs, new_inode_size)) {
1732			fputs(_("Error in resizing the inode size.\n"
1733				"Run e2undo to undo the "
1734				"file system changes. \n"), stderr);
1735		} else {
1736			printf(_("Setting inode size %lu\n"),
1737							new_inode_size);
1738		}
1739	}
1740
1741	if (l_flag)
1742		list_super(sb);
1743	if (stride_set) {
1744		sb->s_raid_stride = stride;
1745		ext2fs_mark_super_dirty(fs);
1746		printf(_("Setting stride size to %d\n"), stride);
1747	}
1748	if (stripe_width_set) {
1749		sb->s_raid_stripe_width = stripe_width;
1750		ext2fs_mark_super_dirty(fs);
1751		printf(_("Setting stripe width to %d\n"), stripe_width);
1752	}
1753	remove_error_table(&et_ext2_error_table);
1754	return (ext2fs_close(fs) ? 1 : 0);
1755}
1756