OSDN Git Service

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