Whamcloud - gitweb
e2fsck, tune2fs: Fix Hurd compilation problem due to lack of PATH_MAX
[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 void do_findfs(int argc, char **argv);
99
100 static 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
116 static __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
133 static __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  */
152 static 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
238 no_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 */
251 static 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  */
270 static 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  */
315 static 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  */
330 static 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  */
463 static 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
531 err:
532         free(journal_device);
533         exit(1);
534 }
535
536
537 static void parse_e2label_options(int argc, char ** argv)
538 {
539         if ((argc < 2) || (argc > 3)) {
540                 fputs(_("Usage: e2label device [newlabel]\n"), stderr);
541                 exit(1);
542         }
543         io_options = strchr(argv[1], '?');
544         if (io_options)
545                 *io_options++ = 0;
546         device_name = blkid_get_devname(NULL, argv[1], NULL);
547         if (!device_name) {
548                 com_err("e2label", 0, _("Unable to resolve '%s'"),
549                         argv[1]);
550                 exit(1);
551         }
552         open_flag = EXT2_FLAG_JOURNAL_DEV_OK;
553         if (argc == 3) {
554                 open_flag |= EXT2_FLAG_RW;
555                 L_flag = 1;
556                 new_label = argv[2];
557         } else
558                 print_label++;
559 }
560
561 static time_t parse_time(char *str)
562 {
563         struct  tm      ts;
564
565         if (strcmp(str, "now") == 0) {
566                 return (time(0));
567         }
568         memset(&ts, 0, sizeof(ts));
569 #ifdef HAVE_STRPTIME
570         strptime(str, "%Y%m%d%H%M%S", &ts);
571 #else
572         sscanf(str, "%4d%2d%2d%2d%2d%2d", &ts.tm_year, &ts.tm_mon,
573                &ts.tm_mday, &ts.tm_hour, &ts.tm_min, &ts.tm_sec);
574         ts.tm_year -= 1900;
575         ts.tm_mon -= 1;
576         if (ts.tm_year < 0 || ts.tm_mon < 0 || ts.tm_mon > 11 ||
577             ts.tm_mday < 0 || ts.tm_mday > 31 || ts.tm_hour > 23 ||
578             ts.tm_min > 59 || ts.tm_sec > 61)
579                 ts.tm_mday = 0;
580 #endif
581         if (ts.tm_mday == 0) {
582                 com_err(program_name, 0,
583                         _("Couldn't parse date/time specifier: %s"),
584                         str);
585                 usage();
586         }
587         ts.tm_isdst = -1;
588         return (mktime(&ts));
589 }
590
591 static void parse_tune2fs_options(int argc, char **argv)
592 {
593         int c;
594         char *tmp;
595         struct group *gr;
596         struct passwd *pw;
597
598         open_flag = 0;
599
600         printf("tune2fs %s (%s)\n", E2FSPROGS_VERSION, E2FSPROGS_DATE);
601         while ((c = getopt(argc, argv, "c:e:fg:i:jlm:o:r:s:u:C:E:I:J:L:M:O:T:U:")) != EOF)
602                 switch (c) {
603                 case 'c':
604                         max_mount_count = strtol(optarg, &tmp, 0);
605                         if (*tmp || max_mount_count > 16000) {
606                                 com_err(program_name, 0,
607                                         _("bad mounts count - %s"),
608                                         optarg);
609                                 usage();
610                         }
611                         if (max_mount_count == 0)
612                                 max_mount_count = -1;
613                         c_flag = 1;
614                         open_flag = EXT2_FLAG_RW;
615                         break;
616                 case 'C':
617                         mount_count = strtoul(optarg, &tmp, 0);
618                         if (*tmp || mount_count > 16000) {
619                                 com_err(program_name, 0,
620                                         _("bad mounts count - %s"),
621                                         optarg);
622                                 usage();
623                         }
624                         C_flag = 1;
625                         open_flag = EXT2_FLAG_RW;
626                         break;
627                 case 'e':
628                         if (strcmp(optarg, "continue") == 0)
629                                 errors = EXT2_ERRORS_CONTINUE;
630                         else if (strcmp(optarg, "remount-ro") == 0)
631                                 errors = EXT2_ERRORS_RO;
632                         else if (strcmp(optarg, "panic") == 0)
633                                 errors = EXT2_ERRORS_PANIC;
634                         else {
635                                 com_err(program_name, 0,
636                                         _("bad error behavior - %s"),
637                                         optarg);
638                                 usage();
639                         }
640                         e_flag = 1;
641                         open_flag = EXT2_FLAG_RW;
642                         break;
643                 case 'E':
644                         extended_cmd = optarg;
645                         open_flag |= EXT2_FLAG_RW;
646                         break;
647                 case 'f': /* Force */
648                         f_flag = 1;
649                         break;
650                 case 'g':
651                         resgid = strtoul(optarg, &tmp, 0);
652                         if (*tmp) {
653                                 gr = getgrnam(optarg);
654                                 if (gr == NULL)
655                                         tmp = optarg;
656                                 else {
657                                         resgid = gr->gr_gid;
658                                         *tmp = 0;
659                                 }
660                         }
661                         if (*tmp) {
662                                 com_err(program_name, 0,
663                                         _("bad gid/group name - %s"),
664                                         optarg);
665                                 usage();
666                         }
667                         g_flag = 1;
668                         open_flag = EXT2_FLAG_RW;
669                         break;
670                 case 'i':
671                         interval = strtoul(optarg, &tmp, 0);
672                         switch (*tmp) {
673                         case 's':
674                                 tmp++;
675                                 break;
676                         case '\0':
677                         case 'd':
678                         case 'D': /* days */
679                                 interval *= 86400;
680                                 if (*tmp != '\0')
681                                         tmp++;
682                                 break;
683                         case 'm':
684                         case 'M': /* months! */
685                                 interval *= 86400 * 30;
686                                 tmp++;
687                                 break;
688                         case 'w':
689                         case 'W': /* weeks */
690                                 interval *= 86400 * 7;
691                                 tmp++;
692                                 break;
693                         }
694                         if (*tmp) {
695                                 com_err(program_name, 0,
696                                         _("bad interval - %s"), optarg);
697                                 usage();
698                         }
699                         i_flag = 1;
700                         open_flag = EXT2_FLAG_RW;
701                         break;
702                 case 'j':
703                         if (!journal_size)
704                                 journal_size = -1;
705                         open_flag = EXT2_FLAG_RW;
706                         break;
707                 case 'J':
708                         parse_journal_opts(optarg);
709                         open_flag = EXT2_FLAG_RW;
710                         break;
711                 case 'l':
712                         l_flag = 1;
713                         break;
714                 case 'L':
715                         new_label = optarg;
716                         L_flag = 1;
717                         open_flag |= EXT2_FLAG_RW |
718                                 EXT2_FLAG_JOURNAL_DEV_OK;
719                         break;
720                 case 'm':
721                         reserved_ratio = strtod(optarg, &tmp);
722                         if (*tmp || reserved_ratio > 50 ||
723                             reserved_ratio < 0) {
724                                 com_err(program_name, 0,
725                                         _("bad reserved block ratio - %s"),
726                                         optarg);
727                                 usage();
728                         }
729                         m_flag = 1;
730                         open_flag = EXT2_FLAG_RW;
731                         break;
732                 case 'M':
733                         new_last_mounted = optarg;
734                         M_flag = 1;
735                         open_flag = EXT2_FLAG_RW;
736                         break;
737                 case 'o':
738                         if (mntopts_cmd) {
739                                 com_err(program_name, 0,
740                                         _("-o may only be specified once"));
741                                 usage();
742                         }
743                         mntopts_cmd = optarg;
744                         open_flag = EXT2_FLAG_RW;
745                         break;
746                         
747                 case 'O':
748                         if (features_cmd) {
749                                 com_err(program_name, 0,
750                                         _("-O may only be specified once"));
751                                 usage();
752                         }
753                         features_cmd = optarg;
754                         open_flag = EXT2_FLAG_RW;
755                         break;
756                 case 'r':
757                         reserved_blocks = strtoul(optarg, &tmp, 0);
758                         if (*tmp) {
759                                 com_err(program_name, 0,
760                                         _("bad reserved blocks count - %s"),
761                                         optarg);
762                                 usage();
763                         }
764                         r_flag = 1;
765                         open_flag = EXT2_FLAG_RW;
766                         break;
767                 case 's': /* Deprecated */
768                         s_flag = atoi(optarg);
769                         open_flag = EXT2_FLAG_RW;
770                         break;
771                 case 'T':
772                         T_flag = 1;
773                         last_check_time = parse_time(optarg);
774                         open_flag = EXT2_FLAG_RW;
775                         break;
776                 case 'u':
777                                 resuid = strtoul(optarg, &tmp, 0);
778                                 if (*tmp) {
779                                         pw = getpwnam(optarg);
780                                         if (pw == NULL)
781                                                 tmp = optarg;
782                                         else {
783                                                 resuid = pw->pw_uid;
784                                                 *tmp = 0;
785                                         }
786                                 }
787                                 if (*tmp) {
788                                         com_err(program_name, 0,
789                                                 _("bad uid/user name - %s"),
790                                                 optarg);
791                                         usage();
792                                 }
793                                 u_flag = 1;
794                                 open_flag = EXT2_FLAG_RW;
795                                 break;
796                 case 'U':
797                         new_UUID = optarg;
798                         U_flag = 1;
799                         open_flag = EXT2_FLAG_RW |
800                                 EXT2_FLAG_JOURNAL_DEV_OK;
801                         break;
802                 case 'I':
803                         new_inode_size = strtoul(optarg, &tmp, 0);
804                         if (*tmp) {
805                                 com_err(program_name, 0,
806                                         _("bad inode size - %s"),
807                                         optarg);
808                                 usage();
809                         }
810                         if (!((new_inode_size &
811                                (new_inode_size - 1)) == 0)) {
812                                 com_err(program_name, 0,
813                                         _("Inode size must be a "
814                                           "power of two- %s"),
815                                         optarg);
816                                 usage();
817                         }
818                         open_flag = EXT2_FLAG_RW;
819                         I_flag = 1;
820                         break;
821                 default:
822                         usage();
823                 }
824         if (optind < argc - 1 || optind == argc)
825                 usage();
826         if (!open_flag && !l_flag)
827                 usage();
828         io_options = strchr(argv[optind], '?');
829         if (io_options)
830                 *io_options++ = 0;
831         device_name = blkid_get_devname(NULL, argv[optind], NULL);
832         if (!device_name) {
833                 com_err("tune2fs", 0, _("Unable to resolve '%s'"),
834                         argv[optind]);
835                 exit(1);
836         }
837 }
838
839 void do_findfs(int argc, char **argv)
840 {
841         char    *dev;
842
843         if ((argc != 2) ||
844             (strncmp(argv[1], "LABEL=", 6) && strncmp(argv[1], "UUID=", 5))) {
845                 fprintf(stderr, "Usage: findfs LABEL=<label>|UUID=<uuid>\n");
846                 exit(2);
847         }
848         dev = blkid_get_devname(NULL, argv[1], NULL);
849         if (!dev) {
850                 com_err("findfs", 0, _("Unable to resolve '%s'"),
851                         argv[1]);
852                 exit(1);
853         }
854         puts(dev);
855         exit(0);
856 }
857
858 static void parse_extended_opts(ext2_filsys fs, const char *opts)
859 {
860         char    *buf, *token, *next, *p, *arg;
861         int     len, hash_alg;
862         int     r_usage = 0;
863
864         len = strlen(opts);
865         buf = malloc(len+1);
866         if (!buf) {
867                 fprintf(stderr,
868                         _("Couldn't allocate memory to parse options!\n"));
869                 exit(1);
870         }
871         strcpy(buf, opts);
872         for (token = buf; token && *token; token = next) {
873                 p = strchr(token, ',');
874                 next = 0;
875                 if (p) {
876                         *p = 0;
877                         next = p+1;
878                 }
879                 arg = strchr(token, '=');
880                 if (arg) {
881                         *arg = 0;
882                         arg++;
883                 }
884                 if (!strcmp(token, "test_fs")) {
885                         fs->super->s_flags |= EXT2_FLAGS_TEST_FILESYS;
886                         printf("Setting test filesystem flag\n");
887                         ext2fs_mark_super_dirty(fs);
888                 } else if (!strcmp(token, "^test_fs")) {
889                         fs->super->s_flags &= ~EXT2_FLAGS_TEST_FILESYS;
890                         printf("Clearing test filesystem flag\n");
891                         ext2fs_mark_super_dirty(fs);
892                 } else if (strcmp(token, "stride") == 0) {
893                         if (!arg) {
894                                 r_usage++;
895                                 continue;
896                         }
897                         stride = strtoul(arg, &p, 0);
898                         if (*p || (stride == 0)) {
899                                 fprintf(stderr,
900                                        _("Invalid RAID stride: %s\n"),
901                                         arg);
902                                 r_usage++;
903                                 continue;
904                         }
905                         stride_set = 1;
906                 } else if (strcmp(token, "stripe-width") == 0 ||
907                            strcmp(token, "stripe_width") == 0) {
908                         if (!arg) {
909                                 r_usage++;
910                                 continue;
911                         }
912                         stripe_width = strtoul(arg, &p, 0);
913                         if (*p || (stripe_width == 0)) {
914                                 fprintf(stderr,
915                                         _("Invalid RAID stripe-width: %s\n"),
916                                         arg);
917                                 r_usage++;
918                                 continue;
919                         }
920                         stripe_width_set = 1;
921                 } else if (strcmp(token, "hash_alg") == 0 ||
922                            strcmp(token, "hash-alg") == 0) {
923                         if (!arg) {
924                                 r_usage++;
925                                 continue;
926                         }
927                         hash_alg = e2p_string2hash(arg);
928                         if (hash_alg < 0) {
929                                 fprintf(stderr,
930                                         _("Invalid hash algorithm: %s\n"),
931                                         arg);
932                                 r_usage++;
933                                 continue;
934                         }
935                         fs->super->s_def_hash_version = hash_alg;
936                         printf(_("Setting default hash algorithm "
937                                  "to %s (%d)\n"),
938                                arg, hash_alg);
939                         ext2fs_mark_super_dirty(fs);
940                 } else
941                         r_usage++;
942         }
943         if (r_usage) {
944                 fprintf(stderr, _("\nBad options specified.\n\n"
945                         "Extended options are separated by commas, "
946                         "and may take an argument which\n"
947                         "\tis set off by an equals ('=') sign.\n\n"
948                         "Valid extended options are:\n"
949                         "\tstride=<RAID per-disk chunk size in blocks>\n"
950                         "\tstripe_width=<RAID stride*data disks in blocks>\n"
951                         "\thash_alg=<hash algorithm>\n"
952                         "\ttest_fs\n"
953                         "\t^test_fs\n"));
954                 free(buf);
955                 exit(1);
956         }
957         free(buf);
958 }
959
960 /*
961  * Fill in two bitmaps that we need to to control the inode resizing
962  * process.  The first is the set of blocks that must be moved, and
963  * the second is the set of blocks which are allocation bitmap blocks
964  * and must be treated specially.
965  */
966 static int get_move_bitmaps(ext2_filsys fs, int new_ino_blks_per_grp,
967                             ext2fs_block_bitmap bmap,
968                             ext2fs_block_bitmap metadata_bmap)
969 {
970         dgrp_t i;
971         blk_t j, needed_blocks = 0;
972         blk_t i_bmap, b_bmap;
973         blk_t start_blk, end_blk;
974         int num, k;
975
976         for (i = 0; i < fs->group_desc_count; i++) {
977                 b_bmap = fs->group_desc[i].bg_block_bitmap;
978                 ext2fs_mark_block_bitmap(metadata_bmap, b_bmap);
979                 i_bmap = fs->group_desc[i].bg_inode_bitmap;
980                 ext2fs_mark_block_bitmap(metadata_bmap, i_bmap);
981
982                 start_blk = fs->group_desc[i].bg_inode_table +
983                                         fs->inode_blocks_per_group;
984
985                 end_blk = fs->group_desc[i].bg_inode_table +
986                                         new_ino_blks_per_grp;
987
988                 num=0;
989                 for (j = start_blk; j < end_blk; j++) {
990                         if (ext2fs_test_block_bitmap(fs->block_map, j)) {
991                                 /* FIXME!!
992                                  * What happens if the block is marked
993                                  * as a bad block
994                                  */
995                                 ext2fs_mark_block_bitmap(bmap, j);
996                                 needed_blocks++;
997                         } else {
998                                 /*
999                                  * We are going to use this block for
1000                                  * inode table. So mark them used.
1001                                  */
1002                                 ext2fs_mark_block_bitmap(fs->block_map, j);
1003                         }
1004                         if ((j == i_bmap) || (j == b_bmap))
1005                                 num++;
1006                 }
1007                 if (num <= fs->group_desc[i].bg_free_blocks_count) 
1008                         continue;
1009         }
1010
1011         if (needed_blocks > fs->super->s_free_blocks_count)
1012                 return ENOSPC;
1013
1014         return 0;
1015 }
1016
1017 static int move_block(ext2_filsys fs, ext2fs_block_bitmap bmap,
1018                       ext2fs_block_bitmap metadata_bmap)
1019 {
1020         char *buf;
1021         errcode_t retval;
1022         blk_t blk, new_blk, goal;
1023         struct blk_move *bmv;
1024         dgrp_t          group;
1025
1026         retval = ext2fs_get_mem(fs->blocksize, &buf);
1027         if (retval)
1028                 return retval;
1029
1030         for (new_blk = blk = fs->super->s_first_data_block;
1031              blk < fs->super->s_blocks_count; blk++) {
1032                 if (!ext2fs_test_block_bitmap(bmap, blk))
1033                         continue;
1034
1035                 /*
1036                  * If the block is a bitmap block, find a new block in
1037                  * the same block group.
1038                  */
1039                 if (ext2fs_test_block_bitmap(metadata_bmap, blk)) {
1040                         group = ext2fs_group_of_blk(fs, blk);
1041                         goal = ext2fs_group_first_block(fs, group);
1042                 } else
1043                         goal = new_blk;
1044
1045                 retval = ext2fs_new_block(fs, goal, NULL, &new_blk);
1046                 if (retval)
1047                         goto err_out;
1048
1049                 /* Mark this block as allocated */
1050                 ext2fs_mark_block_bitmap(fs->block_map, new_blk);
1051
1052                 /* Add it to block move list */
1053                 retval = ext2fs_get_mem(sizeof(struct blk_move), &bmv);
1054                 if (retval)
1055                         goto err_out;
1056
1057                 bmv->old_loc = blk;
1058                 bmv->new_loc = new_blk;
1059
1060                 list_add(&(bmv->list), &blk_move_list);
1061
1062                 retval = io_channel_read_blk(fs->io, blk, 1, buf);
1063                 if (retval)
1064                         goto err_out;
1065
1066                 retval = io_channel_write_blk(fs->io, new_blk, 1, buf);
1067                 if (retval)
1068                         goto err_out;
1069         }
1070
1071 err_out:
1072         ext2fs_free_mem(&buf);
1073         return retval;
1074 }
1075
1076 static blk_t translate_block(blk_t blk)
1077 {
1078         struct list_head *entry;
1079         struct blk_move *bmv;
1080
1081         list_for_each(entry, &blk_move_list) {
1082                 bmv = list_entry(entry, struct blk_move, list);
1083                 if (bmv->old_loc == blk)
1084                         return bmv->new_loc;
1085         }
1086
1087         return 0;
1088 }
1089
1090 static int process_block(ext2_filsys fs EXT2FS_ATTR((unused)),
1091                          blk_t *block_nr,
1092                          e2_blkcnt_t blockcnt EXT2FS_ATTR((unused)),
1093                          blk_t ref_block EXT2FS_ATTR((unused)),
1094                          int ref_offset EXT2FS_ATTR((unused)),
1095                          void *priv_data)
1096 {
1097         int ret = 0;
1098         blk_t new_blk;
1099         ext2fs_block_bitmap bmap = (ext2fs_block_bitmap) priv_data;
1100
1101         if (!ext2fs_test_block_bitmap(bmap, *block_nr))
1102                 return 0;
1103         new_blk = translate_block(*block_nr);
1104         if (new_blk) {
1105                 *block_nr = new_blk;
1106                 /*
1107                  * This will force the ext2fs_write_inode in the iterator
1108                  */
1109                 ret |= BLOCK_CHANGED;
1110         }
1111
1112         return ret;
1113 }
1114
1115 static int inode_scan_and_fix(ext2_filsys fs, ext2fs_block_bitmap bmap)
1116 {
1117         errcode_t retval = 0;
1118         ext2_ino_t ino;
1119         blk_t blk;
1120         char *block_buf = 0;
1121         struct ext2_inode inode;
1122         ext2_inode_scan scan = NULL;
1123
1124         retval = ext2fs_get_mem(fs->blocksize * 3, &block_buf);
1125         if (retval)
1126                 return retval;
1127
1128         retval = ext2fs_open_inode_scan(fs, 0, &scan);
1129         if (retval)
1130                 goto err_out;
1131
1132         while (1) {
1133                 retval = ext2fs_get_next_inode(scan, &ino, &inode);
1134                 if (retval)
1135                         goto err_out;
1136
1137                 if (!ino)
1138                         break;
1139
1140                 if (inode.i_links_count == 0)
1141                         continue; /* inode not in use */
1142
1143                 /* FIXME!!
1144                  * If we end up modifying the journal inode
1145                  * the sb->s_jnl_blocks will differ. But a
1146                  * subsequent e2fsck fixes that.
1147                  * Do we need to fix this ??
1148                  */
1149
1150                 if (inode.i_file_acl &&
1151                     ext2fs_test_block_bitmap(bmap, inode.i_file_acl)) {
1152                         blk = translate_block(inode.i_file_acl);
1153                         if (!blk)
1154                                 continue;
1155
1156                         inode.i_file_acl = blk;
1157
1158                         /*
1159                          * Write the inode to disk so that inode table
1160                          * resizing can work
1161                          */
1162                         retval = ext2fs_write_inode(fs, ino, &inode);
1163                         if (retval)
1164                                 goto err_out;
1165                 }
1166
1167                 if (!ext2fs_inode_has_valid_blocks(&inode))
1168                         continue;
1169
1170                 retval = ext2fs_block_iterate2(fs, ino, 0, block_buf,
1171                                                process_block, bmap);
1172                 if (retval)
1173                         goto err_out;
1174
1175         }
1176
1177 err_out:
1178         ext2fs_free_mem(&block_buf);
1179
1180         return retval;
1181 }
1182
1183 /*
1184  * We need to scan for inode and block bitmaps that may need to be
1185  * moved.  This can take place if the filesystem was formatted for
1186  * RAID arrays using the mke2fs's extended option "stride".
1187  */
1188 static int group_desc_scan_and_fix(ext2_filsys fs, ext2fs_block_bitmap bmap)
1189 {
1190         dgrp_t i;
1191         blk_t blk, new_blk;
1192
1193         for (i = 0; i < fs->group_desc_count; i++) {
1194                 blk = fs->group_desc[i].bg_block_bitmap;
1195                 if (ext2fs_test_block_bitmap(bmap, blk)) {
1196                         new_blk = translate_block(blk);
1197                         if (!new_blk)
1198                                 continue;
1199                         fs->group_desc[i].bg_block_bitmap = new_blk;
1200                 }
1201
1202                 blk = fs->group_desc[i].bg_inode_bitmap;
1203                 if (ext2fs_test_block_bitmap(bmap, blk)) {
1204                         new_blk = translate_block(blk);
1205                         if (!new_blk)
1206                                 continue;
1207                         fs->group_desc[i].bg_inode_bitmap = new_blk;
1208                 }
1209         }
1210         return 0;
1211 }
1212
1213
1214 static int expand_inode_table(ext2_filsys fs, unsigned long new_ino_size)
1215 {
1216         dgrp_t i;
1217         blk_t blk;
1218         errcode_t retval;
1219         int new_ino_blks_per_grp;
1220         unsigned int j;
1221         char *old_itable = NULL, *new_itable = NULL;
1222         char *tmp_old_itable = NULL, *tmp_new_itable = NULL;
1223         unsigned long old_ino_size;
1224         int old_itable_size, new_itable_size;
1225
1226         old_itable_size = fs->inode_blocks_per_group * fs->blocksize;
1227         old_ino_size = EXT2_INODE_SIZE(fs->super);
1228
1229         new_ino_blks_per_grp = ext2fs_div_ceil(
1230                                         EXT2_INODES_PER_GROUP(fs->super) *
1231                                         new_ino_size,
1232                                         fs->blocksize);
1233
1234         new_itable_size = new_ino_blks_per_grp * fs->blocksize;
1235
1236         retval = ext2fs_get_mem(old_itable_size, &old_itable);
1237         if (retval)
1238                 return retval;
1239
1240         retval = ext2fs_get_mem(new_itable_size, &new_itable);
1241         if (retval)
1242                 goto err_out;
1243
1244         tmp_old_itable = old_itable;
1245         tmp_new_itable = new_itable;
1246
1247         for (i = 0; i < fs->group_desc_count; i++) {
1248                 blk = fs->group_desc[i].bg_inode_table;
1249                 retval = io_channel_read_blk(fs->io, blk,
1250                                 fs->inode_blocks_per_group, old_itable);
1251                 if (retval)
1252                         goto err_out;
1253
1254                 for (j = 0; j < EXT2_INODES_PER_GROUP(fs->super); j++) {
1255                         memcpy(new_itable, old_itable, old_ino_size);
1256
1257                         memset(new_itable+old_ino_size, 0,
1258                                         new_ino_size - old_ino_size);
1259
1260                         new_itable += new_ino_size;
1261                         old_itable += old_ino_size;
1262                 }
1263
1264                 /* reset the pointer */
1265                 old_itable = tmp_old_itable;
1266                 new_itable = tmp_new_itable;
1267
1268                 retval = io_channel_write_blk(fs->io, blk,
1269                                         new_ino_blks_per_grp, new_itable);
1270                 if (retval)
1271                         goto err_out;
1272         }
1273
1274         /* Update the meta data */
1275         fs->inode_blocks_per_group = new_ino_blks_per_grp;
1276         fs->super->s_inode_size = new_ino_size;
1277
1278 err_out:
1279         if (old_itable)
1280                 ext2fs_free_mem(&old_itable);
1281
1282         if (new_itable)
1283                 ext2fs_free_mem(&new_itable);
1284
1285         return retval;
1286 }
1287
1288 static errcode_t ext2fs_calculate_summary_stats(ext2_filsys fs)
1289 {
1290         blk_t           blk;
1291         ext2_ino_t      ino;
1292         unsigned int    group = 0;
1293         unsigned int    count = 0;
1294         int             total_free = 0;
1295         int             group_free = 0;
1296
1297         /*
1298          * First calculate the block statistics
1299          */
1300         for (blk = fs->super->s_first_data_block;
1301              blk < fs->super->s_blocks_count; blk++) {
1302                 if (!ext2fs_fast_test_block_bitmap(fs->block_map, blk)) {
1303                         group_free++;
1304                         total_free++;
1305                 }
1306                 count++;
1307                 if ((count == fs->super->s_blocks_per_group) ||
1308                     (blk == fs->super->s_blocks_count-1)) {
1309                         fs->group_desc[group++].bg_free_blocks_count =
1310                                 group_free;
1311                         count = 0;
1312                         group_free = 0;
1313                 }
1314         }
1315         fs->super->s_free_blocks_count = total_free;
1316
1317         /*
1318          * Next, calculate the inode statistics
1319          */
1320         group_free = 0;
1321         total_free = 0;
1322         count = 0;
1323         group = 0;
1324
1325         /* Protect loop from wrap-around if s_inodes_count maxed */
1326         for (ino = 1; ino <= fs->super->s_inodes_count && ino > 0; ino++) {
1327                 if (!ext2fs_fast_test_inode_bitmap(fs->inode_map, ino)) {
1328                         group_free++;
1329                         total_free++;
1330                 }
1331                 count++;
1332                 if ((count == fs->super->s_inodes_per_group) ||
1333                     (ino == fs->super->s_inodes_count)) {
1334                         fs->group_desc[group++].bg_free_inodes_count =
1335                                 group_free;
1336                         count = 0;
1337                         group_free = 0;
1338                 }
1339         }
1340         fs->super->s_free_inodes_count = total_free;
1341         ext2fs_mark_super_dirty(fs);
1342         return 0;
1343 }
1344
1345 #define list_for_each_safe(pos, pnext, head) \
1346         for (pos = (head)->next, pnext = pos->next; pos != (head); \
1347              pos = pnext, pnext = pos->next)
1348
1349 static void free_blk_move_list(void)
1350 {
1351         struct list_head *entry, *tmp;
1352         struct blk_move *bmv;
1353
1354         list_for_each_safe(entry, tmp, &blk_move_list) {
1355                 bmv = list_entry(entry, struct blk_move, list);
1356                 list_del(entry);
1357                 ext2fs_free_mem(&bmv);
1358         }
1359         return;
1360 }
1361
1362 static int resize_inode(ext2_filsys fs, unsigned long new_size)
1363 {
1364         errcode_t retval;
1365         int new_ino_blks_per_grp;
1366         ext2fs_block_bitmap bmap, metadata_bmap;
1367
1368         ext2fs_read_inode_bitmap(fs);
1369         ext2fs_read_block_bitmap(fs);
1370         INIT_LIST_HEAD(&blk_move_list);
1371
1372
1373         new_ino_blks_per_grp = ext2fs_div_ceil(
1374                                         EXT2_INODES_PER_GROUP(fs->super)*
1375                                         new_size,
1376                                         fs->blocksize);
1377
1378         /* We may change the file system.
1379          * Mark the file system as invalid so that
1380          * the user is prompted to run fsck.
1381          */
1382         fs->super->s_state &= ~EXT2_VALID_FS;
1383
1384         retval = ext2fs_allocate_block_bitmap(fs, _("blocks to be moved"),
1385                                                 &bmap);
1386         if (retval)
1387                 return retval;
1388
1389         retval = ext2fs_allocate_block_bitmap(fs, _("blocks to be moved"),
1390                                                 &metadata_bmap);
1391         if (retval)
1392                 return retval;
1393
1394         retval = get_move_bitmaps(fs, new_ino_blks_per_grp, bmap,
1395                                   metadata_bmap);
1396         if (retval)
1397                 goto err_out;
1398
1399         retval = move_block(fs, bmap, metadata_bmap);
1400         if (retval)
1401                 goto err_out;
1402
1403         retval = inode_scan_and_fix(fs, bmap);
1404         if (retval)
1405                 goto err_out;
1406
1407         retval = group_desc_scan_and_fix(fs, bmap);
1408         if (retval)
1409                 goto err_out;
1410
1411         retval = expand_inode_table(fs, new_size);
1412         if (retval)
1413                 goto err_out;
1414
1415         ext2fs_calculate_summary_stats(fs);
1416
1417         fs->super->s_state |= EXT2_VALID_FS;
1418         /* mark super block and block bitmap as dirty */
1419         ext2fs_mark_super_dirty(fs);
1420         ext2fs_mark_bb_dirty(fs);
1421
1422 err_out:
1423         free_blk_move_list();
1424         ext2fs_free_block_bitmap(bmap);
1425
1426         return retval;
1427 }
1428
1429 static int tune2fs_setup_tdb(const char *name, io_manager *io_ptr)
1430 {
1431         errcode_t retval = 0;
1432         const char *tdb_dir;
1433         char *tdb_file;
1434         char *dev_name, *tmp_name;
1435
1436 #if 0 /* FIXME!! */
1437         /*
1438          * Configuration via a conf file would be
1439          * nice
1440          */
1441         profile_get_string(profile, "scratch_files",
1442                                         "directory", 0, 0,
1443                                         &tdb_dir);
1444 #endif
1445         tmp_name = strdup(name);
1446         if (!tmp_name) {
1447         alloc_fn_fail:
1448                 com_err(program_name, ENOMEM, 
1449                         _("Couldn't allocate memory for tdb filename\n"));
1450                 return ENOMEM;
1451         }
1452         dev_name = basename(tmp_name);
1453
1454         tdb_dir = getenv("E2FSPROGS_UNDO_DIR");
1455         if (!tdb_dir)
1456                 tdb_dir = "/var/lib/e2fsprogs";
1457
1458         if (!strcmp(tdb_dir, "none") || (tdb_dir[0] == 0) ||
1459             access(tdb_dir, W_OK))
1460                 return 0;
1461
1462         tdb_file = malloc(strlen(tdb_dir) + 9 + strlen(dev_name) + 7 + 1);
1463         if (!tdb_file)
1464                 goto alloc_fn_fail;
1465         sprintf(tdb_file, "%s/tune2fs-%s.e2undo", tdb_dir, dev_name);
1466
1467         if (!access(tdb_file, F_OK)) {
1468                 if (unlink(tdb_file) < 0) {
1469                         retval = errno;
1470                         com_err(program_name, retval,
1471                                 _("while trying to delete %s"),
1472                                 tdb_file);
1473                         free(tdb_file);
1474                         return retval;
1475                 }
1476         }
1477
1478         set_undo_io_backing_manager(*io_ptr);
1479         *io_ptr = undo_io_manager;
1480         set_undo_io_backup_file(tdb_file);
1481         printf(_("To undo the tune2fs operation please run "
1482                  "the command\n    e2undo %s %s\n\n"),
1483                  tdb_file, name);
1484         free(tdb_file);
1485         free(tmp_name);
1486         return retval;
1487 }
1488
1489 int main(int argc, char **argv)
1490 {
1491         errcode_t retval;
1492         ext2_filsys fs;
1493         struct ext2_super_block *sb;
1494         io_manager io_ptr, io_ptr_orig = NULL;
1495
1496 #ifdef ENABLE_NLS
1497         setlocale(LC_MESSAGES, "");
1498         setlocale(LC_CTYPE, "");
1499         bindtextdomain(NLS_CAT_NAME, LOCALEDIR);
1500         textdomain(NLS_CAT_NAME);
1501 #endif
1502         if (argc && *argv)
1503                 program_name = *argv;
1504         add_error_table(&et_ext2_error_table);
1505
1506         if (strcmp(get_progname(argv[0]), "findfs") == 0)
1507                 do_findfs(argc, argv);
1508         if (strcmp(get_progname(argv[0]), "e2label") == 0)
1509                 parse_e2label_options(argc, argv);
1510         else
1511                 parse_tune2fs_options(argc, argv);
1512
1513 #ifdef CONFIG_TESTIO_DEBUG
1514         if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_DEBUG")) {
1515                 io_ptr = test_io_manager;
1516                 test_io_backing_manager = unix_io_manager;
1517         } else
1518 #endif
1519                 io_ptr = unix_io_manager;
1520
1521 retry_open:
1522         retval = ext2fs_open2(device_name, io_options, open_flag,
1523                               0, 0, io_ptr, &fs);
1524         if (retval) {
1525                         com_err(program_name, retval,
1526                                 _("while trying to open %s"),
1527                         device_name);
1528                 fprintf(stderr,
1529                         _("Couldn't find valid filesystem superblock.\n"));
1530                 exit(1);
1531         }
1532
1533         if (I_flag && !io_ptr_orig) {
1534                 /*
1535                  * Check the inode size is right so we can issue an
1536                  * error message and bail before setting up the tdb
1537                  * file.
1538                  */
1539                 if (new_inode_size == EXT2_INODE_SIZE(fs->super)) {
1540                         fprintf(stderr, _("The inode size is already %d\n"),
1541                                 new_inode_size);
1542                         exit(1);
1543                 }
1544                 if (new_inode_size < EXT2_INODE_SIZE(fs->super)) {
1545                         fprintf(stderr, _("Shrinking the inode size is "
1546                                           "not supported\n"));
1547                         exit(1);
1548                 }
1549
1550                 /*
1551                  * If inode resize is requested use the
1552                  * Undo I/O manager
1553                  */
1554                 io_ptr_orig = io_ptr;
1555                 retval = tune2fs_setup_tdb(device_name, &io_ptr);
1556                 if (retval)
1557                         exit(1);
1558                 if (io_ptr != io_ptr_orig) {
1559                         ext2fs_close(fs);
1560                         goto retry_open;
1561                 }
1562         }
1563
1564         sb = fs->super;
1565         fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
1566
1567         if (print_label) {
1568                 /* For e2label emulation */
1569                 printf("%.*s\n", (int) sizeof(sb->s_volume_name),
1570                        sb->s_volume_name);
1571                 remove_error_table(&et_ext2_error_table);
1572                 exit(0);
1573         }
1574
1575         retval = ext2fs_check_if_mounted(device_name, &mount_flags);
1576         if (retval) {
1577                 com_err("ext2fs_check_if_mount", retval,
1578                         _("while determining whether %s is mounted."),
1579                         device_name);
1580                 exit(1);
1581         }
1582         /* Normally we only need to write out the superblock */
1583         fs->flags |= EXT2_FLAG_SUPER_ONLY;
1584
1585         if (c_flag) {
1586                 sb->s_max_mnt_count = max_mount_count;
1587                 ext2fs_mark_super_dirty(fs);
1588                 printf(_("Setting maximal mount count to %d\n"),
1589                        max_mount_count);
1590         }
1591         if (C_flag) {
1592                 sb->s_mnt_count = mount_count;
1593                 ext2fs_mark_super_dirty(fs);
1594                 printf(_("Setting current mount count to %d\n"), mount_count);
1595         }
1596         if (e_flag) {
1597                 sb->s_errors = errors;
1598                 ext2fs_mark_super_dirty(fs);
1599                 printf(_("Setting error behavior to %d\n"), errors);
1600         }
1601         if (g_flag) {
1602                 sb->s_def_resgid = resgid;
1603                 ext2fs_mark_super_dirty(fs);
1604                 printf(_("Setting reserved blocks gid to %lu\n"), resgid);
1605         }
1606         if (i_flag) {
1607                 sb->s_checkinterval = interval;
1608                 ext2fs_mark_super_dirty(fs);
1609                 printf(_("Setting interval between checks to %lu seconds\n"),
1610                        interval);
1611         }
1612         if (m_flag) {
1613                 sb->s_r_blocks_count = (unsigned int) (reserved_ratio *
1614                                         sb->s_blocks_count / 100.0);
1615                 ext2fs_mark_super_dirty(fs);
1616                 printf(_("Setting reserved blocks percentage to %g%% "
1617                          "(%u blocks)\n"),
1618                        reserved_ratio, sb->s_r_blocks_count);
1619         }
1620         if (r_flag) {
1621                 if (reserved_blocks >= sb->s_blocks_count/2) {
1622                         com_err(program_name, 0,
1623                                 _("reserved blocks count is too big (%lu)"),
1624                                 reserved_blocks);
1625                         exit(1);
1626                 }
1627                 sb->s_r_blocks_count = reserved_blocks;
1628                 ext2fs_mark_super_dirty(fs);
1629                 printf(_("Setting reserved blocks count to %lu\n"),
1630                        reserved_blocks);
1631         }
1632         if (s_flag == 1) {
1633                 if (sb->s_feature_ro_compat &
1634                     EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER)
1635                         fputs(_("\nThe filesystem already has sparse "
1636                                 "superblocks.\n"), stderr);
1637                 else {
1638                         sb->s_feature_ro_compat |=
1639                                 EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER;
1640                         sb->s_state &= ~EXT2_VALID_FS;
1641                         ext2fs_mark_super_dirty(fs);
1642                         printf(_("\nSparse superblock flag set.  %s"),
1643                                _(please_fsck));
1644                 }
1645         }
1646         if (s_flag == 0) {
1647                 fputs(_("\nClearing the sparse superflag not supported.\n"),
1648                       stderr);
1649                 exit(1);
1650         }
1651         if (T_flag) {
1652                 sb->s_lastcheck = last_check_time;
1653                 ext2fs_mark_super_dirty(fs);
1654                 printf(_("Setting time filesystem last checked to %s\n"),
1655                        ctime(&last_check_time));
1656         }
1657         if (u_flag) {
1658                 sb->s_def_resuid = resuid;
1659                 ext2fs_mark_super_dirty(fs);
1660                 printf(_("Setting reserved blocks uid to %lu\n"), resuid);
1661         }
1662         if (L_flag) {
1663                 if (strlen(new_label) > sizeof(sb->s_volume_name))
1664                         fputs(_("Warning: label too long, truncating.\n"),
1665                               stderr);
1666                 memset(sb->s_volume_name, 0, sizeof(sb->s_volume_name));
1667                 strncpy(sb->s_volume_name, new_label,
1668                         sizeof(sb->s_volume_name));
1669                 ext2fs_mark_super_dirty(fs);
1670         }
1671         if (M_flag) {
1672                 memset(sb->s_last_mounted, 0, sizeof(sb->s_last_mounted));
1673                 strncpy(sb->s_last_mounted, new_last_mounted,
1674                         sizeof(sb->s_last_mounted));
1675                 ext2fs_mark_super_dirty(fs);
1676         }
1677         if (mntopts_cmd)
1678                 update_mntopts(fs, mntopts_cmd);
1679         if (features_cmd)
1680                 update_feature_set(fs, features_cmd);
1681         if (extended_cmd)
1682                 parse_extended_opts(fs, extended_cmd);
1683         if (journal_size || journal_device)
1684                 add_journal(fs);
1685
1686         if (U_flag) {
1687                 int set_csum = 0;
1688                 dgrp_t i;
1689
1690                 if (sb->s_feature_ro_compat &
1691                     EXT4_FEATURE_RO_COMPAT_GDT_CSUM) {
1692                         /*
1693                          * Determine if the block group checksums are
1694                          * correct so we know whether or not to set
1695                          * them later on.
1696                          */
1697                         for (i = 0; i < fs->group_desc_count; i++)
1698                                 if (!ext2fs_group_desc_csum_verify(fs, i))
1699                                         break;
1700                         if (i >= fs->group_desc_count)
1701                                 set_csum = 1;
1702                 }
1703                 if ((strcasecmp(new_UUID, "null") == 0) ||
1704                     (strcasecmp(new_UUID, "clear") == 0)) {
1705                         uuid_clear(sb->s_uuid);
1706                 } else if (strcasecmp(new_UUID, "time") == 0) {
1707                         uuid_generate_time(sb->s_uuid);
1708                 } else if (strcasecmp(new_UUID, "random") == 0) {
1709                         uuid_generate(sb->s_uuid);
1710                 } else if (uuid_parse(new_UUID, sb->s_uuid)) {
1711                         com_err(program_name, 0, _("Invalid UUID format\n"));
1712                         exit(1);
1713                 }
1714                 if (set_csum) {
1715                         for (i = 0; i < fs->group_desc_count; i++)
1716                                 ext2fs_group_desc_csum_set(fs, i);
1717                         fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
1718                 }
1719                 ext2fs_mark_super_dirty(fs);
1720         }
1721         if (I_flag) {
1722                 if (mount_flags & EXT2_MF_MOUNTED) {
1723                         fputs(_("The inode size may only be "
1724                                 "changed when the filesystem is "
1725                                 "unmounted.\n"), stderr);
1726                         exit(1);
1727                 }
1728                 if (fs->super->s_feature_incompat &
1729                     EXT4_FEATURE_INCOMPAT_FLEX_BG) {
1730                         fputs(_("Changing the inode size not supported for "
1731                                 "filesystems with the flex_bg\n"
1732                                 "feature enabled.\n"),
1733                               stderr);
1734                         exit(1);
1735                 }
1736                 /*
1737                  * We want to update group descriptor also
1738                  * with the new free inode count
1739                  */
1740                 fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
1741                 if (resize_inode(fs, new_inode_size)) {
1742                         fputs(_("Error in resizing the inode size.\n"
1743                                 "Run e2undo to undo the "
1744                                 "file system changes. \n"), stderr);
1745                 } else {
1746                         printf(_("Setting inode size %lu\n"),
1747                                                         new_inode_size);
1748                 }
1749         }
1750
1751         if (l_flag)
1752                 list_super(sb);
1753         if (stride_set) {
1754                 sb->s_raid_stride = stride;
1755                 ext2fs_mark_super_dirty(fs);
1756                 printf(_("Setting stride size to %d\n"), stride);
1757         }
1758         if (stripe_width_set) {
1759                 sb->s_raid_stripe_width = stripe_width;
1760                 ext2fs_mark_super_dirty(fs);
1761                 printf(_("Setting stripe width to %d\n"), stripe_width);
1762         }
1763         remove_error_table(&et_ext2_error_table);
1764         return (ext2fs_close(fs) ? 1 : 0);
1765 }