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