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