Whamcloud - gitweb
Merge branch 'maint' into next
[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 if (strcmp(token, "mount-options")) {
986                         if (!arg) {
987                                 r_usage++;
988                                 continue;
989                         }
990                         if (strlen(arg) >= sizeof(fs->super->s_mount_opts)) {
991                                 fprintf(stderr,
992                                         "Extended mount options too long\n");
993                                 continue;
994                         }
995                         strcpy(fs->super->s_mount_opts, arg);
996                         ext2fs_mark_super_dirty(fs);
997                 } else
998                         r_usage++;
999         }
1000         if (r_usage) {
1001                 fprintf(stderr, _("\nBad options specified.\n\n"
1002                         "Extended options are separated by commas, "
1003                         "and may take an argument which\n"
1004                         "\tis set off by an equals ('=') sign.\n\n"
1005                         "Valid extended options are:\n"
1006                         "\tstride=<RAID per-disk chunk size in blocks>\n"
1007                         "\tstripe_width=<RAID stride*data disks in blocks>\n"
1008                         "\thash_alg=<hash algorithm>\n"
1009                         "\ttest_fs\n"
1010                         "\t^test_fs\n"));
1011                 free(buf);
1012                 exit(1);
1013         }
1014         free(buf);
1015 }
1016
1017 /*
1018  * Fill in the block bitmap bmap with the information regarding the
1019  * blocks to be moved
1020  */
1021 static int get_move_bitmaps(ext2_filsys fs, int new_ino_blks_per_grp,
1022                             ext2fs_block_bitmap bmap)
1023 {
1024         dgrp_t i;
1025         int retval;
1026         ext2_badblocks_list bb_list = 0;
1027         blk64_t j, needed_blocks = 0;
1028         blk64_t start_blk, end_blk;
1029
1030         retval = ext2fs_read_bb_inode(fs, &bb_list);
1031         if (retval)
1032                 return retval;
1033
1034         for (i = 0; i < fs->group_desc_count; i++) {
1035                 start_blk = ext2fs_inode_table_loc(fs, i) +
1036                                         fs->inode_blocks_per_group;
1037
1038                 end_blk = ext2fs_inode_table_loc(fs, i) +
1039                                         new_ino_blks_per_grp;
1040
1041                 for (j = start_blk; j < end_blk; j++) {
1042                         if (ext2fs_test_block_bitmap2(fs->block_map, j)) {
1043                                 /*
1044                                  * IF the block is a bad block we fail
1045                                  */
1046                                 if (ext2fs_badblocks_list_test(bb_list, j)) {
1047                                         ext2fs_badblocks_list_free(bb_list);
1048                                         return ENOSPC;
1049                                 }
1050
1051                                 ext2fs_mark_block_bitmap2(bmap, j);
1052                         } else {
1053                                 /*
1054                                  * We are going to use this block for
1055                                  * inode table. So mark them used.
1056                                  */
1057                                 ext2fs_mark_block_bitmap2(fs->block_map, j);
1058                         }
1059                 }
1060                 needed_blocks += end_blk - start_blk;
1061         }
1062
1063         ext2fs_badblocks_list_free(bb_list);
1064         if (needed_blocks > ext2fs_free_blocks_count(fs->super))
1065                 return ENOSPC;
1066
1067         return 0;
1068 }
1069
1070 static int ext2fs_is_meta_block(ext2_filsys fs, blk_t blk)
1071 {
1072         dgrp_t group;
1073         group = ext2fs_group_of_blk(fs, blk);
1074         if (ext2fs_block_bitmap_loc(fs, group) == blk)
1075                 return 1;
1076         if (ext2fs_inode_bitmap_loc(fs, group) == blk)
1077                 return 1;
1078         return 0;
1079 }
1080
1081 static int ext2fs_is_block_in_group(ext2_filsys fs, dgrp_t group, blk_t blk)
1082 {
1083         blk_t start_blk, end_blk;
1084         start_blk = fs->super->s_first_data_block +
1085                         EXT2_BLOCKS_PER_GROUP(fs->super) * group;
1086         /*
1087          * We cannot get new block beyond end_blk for for the last block group
1088          * so we can check with EXT2_BLOCKS_PER_GROUP even for last block group
1089          */
1090         end_blk   = start_blk + EXT2_BLOCKS_PER_GROUP(fs->super);
1091         if (blk >= start_blk && blk <= end_blk)
1092                 return 1;
1093         return 0;
1094 }
1095
1096 static int move_block(ext2_filsys fs, ext2fs_block_bitmap bmap)
1097 {
1098
1099         char *buf;
1100         dgrp_t group;
1101         errcode_t retval;
1102         int meta_data = 0;
1103         blk64_t blk, new_blk, goal;
1104         struct blk_move *bmv;
1105
1106         retval = ext2fs_get_mem(fs->blocksize, &buf);
1107         if (retval)
1108                 return retval;
1109
1110         for (new_blk = blk = fs->super->s_first_data_block;
1111              blk < ext2fs_blocks_count(fs->super); blk++) {
1112                 if (!ext2fs_test_block_bitmap2(bmap, blk))
1113                         continue;
1114
1115                 if (ext2fs_is_meta_block(fs, blk)) {
1116                         /*
1117                          * If the block is mapping a fs meta data block
1118                          * like group desc/block bitmap/inode bitmap. We
1119                          * should find a block in the same group and fix
1120                          * the respective fs metadata pointers. Otherwise
1121                          * fail
1122                          */
1123                         group = ext2fs_group_of_blk(fs, blk);
1124                         goal = ext2fs_group_first_block2(fs, group);
1125                         meta_data = 1;
1126
1127                 } else {
1128                         goal = new_blk;
1129                 }
1130                 retval = ext2fs_new_block2(fs, goal, NULL, &new_blk);
1131                 if (retval)
1132                         goto err_out;
1133
1134                 /* new fs meta data block should be in the same group */
1135                 if (meta_data && !ext2fs_is_block_in_group(fs, group, new_blk)) {
1136                         retval = ENOSPC;
1137                         goto err_out;
1138                 }
1139
1140                 /* Mark this block as allocated */
1141                 ext2fs_mark_block_bitmap2(fs->block_map, new_blk);
1142
1143                 /* Add it to block move list */
1144                 retval = ext2fs_get_mem(sizeof(struct blk_move), &bmv);
1145                 if (retval)
1146                         goto err_out;
1147
1148                 bmv->old_loc = blk;
1149                 bmv->new_loc = new_blk;
1150
1151                 list_add(&(bmv->list), &blk_move_list);
1152
1153                 retval = io_channel_read_blk64(fs->io, blk, 1, buf);
1154                 if (retval)
1155                         goto err_out;
1156
1157                 retval = io_channel_write_blk64(fs->io, new_blk, 1, buf);
1158                 if (retval)
1159                         goto err_out;
1160         }
1161
1162 err_out:
1163         ext2fs_free_mem(&buf);
1164         return retval;
1165 }
1166
1167 static blk64_t translate_block(blk64_t blk)
1168 {
1169         struct list_head *entry;
1170         struct blk_move *bmv;
1171
1172         list_for_each(entry, &blk_move_list) {
1173                 bmv = list_entry(entry, struct blk_move, list);
1174                 if (bmv->old_loc == blk)
1175                         return bmv->new_loc;
1176         }
1177
1178         return 0;
1179 }
1180
1181 static int process_block(ext2_filsys fs EXT2FS_ATTR((unused)),
1182                          blk64_t *block_nr,
1183                          e2_blkcnt_t blockcnt EXT2FS_ATTR((unused)),
1184                          blk64_t ref_block EXT2FS_ATTR((unused)),
1185                          int ref_offset EXT2FS_ATTR((unused)),
1186                          void *priv_data)
1187 {
1188         int ret = 0;
1189         blk64_t new_blk;
1190         ext2fs_block_bitmap bmap = (ext2fs_block_bitmap) priv_data;
1191
1192         if (!ext2fs_test_block_bitmap2(bmap, *block_nr))
1193                 return 0;
1194         new_blk = translate_block(*block_nr);
1195         if (new_blk) {
1196                 *block_nr = new_blk;
1197                 /*
1198                  * This will force the ext2fs_write_inode in the iterator
1199                  */
1200                 ret |= BLOCK_CHANGED;
1201         }
1202
1203         return ret;
1204 }
1205
1206 static int inode_scan_and_fix(ext2_filsys fs, ext2fs_block_bitmap bmap)
1207 {
1208         errcode_t retval = 0;
1209         ext2_ino_t ino;
1210         blk64_t blk;
1211         char *block_buf = 0;
1212         struct ext2_inode inode;
1213         ext2_inode_scan scan = NULL;
1214
1215         retval = ext2fs_get_mem(fs->blocksize * 3, &block_buf);
1216         if (retval)
1217                 return retval;
1218
1219         retval = ext2fs_open_inode_scan(fs, 0, &scan);
1220         if (retval)
1221                 goto err_out;
1222
1223         while (1) {
1224                 retval = ext2fs_get_next_inode(scan, &ino, &inode);
1225                 if (retval)
1226                         goto err_out;
1227
1228                 if (!ino)
1229                         break;
1230
1231                 if (inode.i_links_count == 0)
1232                         continue; /* inode not in use */
1233
1234                 /* FIXME!!
1235                  * If we end up modifying the journal inode
1236                  * the sb->s_jnl_blocks will differ. But a
1237                  * subsequent e2fsck fixes that.
1238                  * Do we need to fix this ??
1239                  */
1240
1241                 if (ext2fs_file_acl_block(&inode) &&
1242                     ext2fs_test_block_bitmap2(bmap,
1243                                               ext2fs_file_acl_block(&inode))) {
1244                         blk = translate_block(ext2fs_file_acl_block(&inode));
1245                         if (!blk)
1246                                 continue;
1247
1248                         ext2fs_file_acl_block_set(&inode, blk);
1249
1250                         /*
1251                          * Write the inode to disk so that inode table
1252                          * resizing can work
1253                          */
1254                         retval = ext2fs_write_inode(fs, ino, &inode);
1255                         if (retval)
1256                                 goto err_out;
1257                 }
1258
1259                 if (!ext2fs_inode_has_valid_blocks(&inode))
1260                         continue;
1261
1262                 retval = ext2fs_block_iterate3(fs, ino, 0, block_buf,
1263                                                process_block, bmap);
1264                 if (retval)
1265                         goto err_out;
1266
1267         }
1268
1269 err_out:
1270         ext2fs_free_mem(&block_buf);
1271
1272         return retval;
1273 }
1274
1275 /*
1276  * We need to scan for inode and block bitmaps that may need to be
1277  * moved.  This can take place if the filesystem was formatted for
1278  * RAID arrays using the mke2fs's extended option "stride".
1279  */
1280 static int group_desc_scan_and_fix(ext2_filsys fs, ext2fs_block_bitmap bmap)
1281 {
1282         dgrp_t i;
1283         blk_t blk, new_blk;
1284
1285         for (i = 0; i < fs->group_desc_count; i++) {
1286                 blk = ext2fs_block_bitmap_loc(fs, i);
1287                 if (ext2fs_test_block_bitmap2(bmap, blk)) {
1288                         new_blk = translate_block(blk);
1289                         if (!new_blk)
1290                                 continue;
1291                         ext2fs_block_bitmap_loc_set(fs, i, new_blk);
1292                 }
1293
1294                 blk = ext2fs_inode_bitmap_loc(fs, i);
1295                 if (ext2fs_test_block_bitmap2(bmap, blk)) {
1296                         new_blk = translate_block(blk);
1297                         if (!new_blk)
1298                                 continue;
1299                         ext2fs_inode_bitmap_loc_set(fs, i, new_blk);
1300                 }
1301         }
1302         return 0;
1303 }
1304
1305 static int expand_inode_table(ext2_filsys fs, unsigned long new_ino_size)
1306 {
1307         dgrp_t i;
1308         blk64_t blk;
1309         errcode_t retval;
1310         int new_ino_blks_per_grp;
1311         unsigned int j;
1312         char *old_itable = NULL, *new_itable = NULL;
1313         char *tmp_old_itable = NULL, *tmp_new_itable = NULL;
1314         unsigned long old_ino_size;
1315         int old_itable_size, new_itable_size;
1316
1317         old_itable_size = fs->inode_blocks_per_group * fs->blocksize;
1318         old_ino_size = EXT2_INODE_SIZE(fs->super);
1319
1320         new_ino_blks_per_grp = ext2fs_div_ceil(
1321                                         EXT2_INODES_PER_GROUP(fs->super) *
1322                                         new_ino_size,
1323                                         fs->blocksize);
1324
1325         new_itable_size = new_ino_blks_per_grp * fs->blocksize;
1326
1327         retval = ext2fs_get_mem(old_itable_size, &old_itable);
1328         if (retval)
1329                 return retval;
1330
1331         retval = ext2fs_get_mem(new_itable_size, &new_itable);
1332         if (retval)
1333                 goto err_out;
1334
1335         tmp_old_itable = old_itable;
1336         tmp_new_itable = new_itable;
1337
1338         for (i = 0; i < fs->group_desc_count; i++) {
1339                 blk = ext2fs_inode_table_loc(fs, i);
1340                 retval = io_channel_read_blk64(fs->io, blk,
1341                                 fs->inode_blocks_per_group, old_itable);
1342                 if (retval)
1343                         goto err_out;
1344
1345                 for (j = 0; j < EXT2_INODES_PER_GROUP(fs->super); j++) {
1346                         memcpy(new_itable, old_itable, old_ino_size);
1347
1348                         memset(new_itable+old_ino_size, 0,
1349                                         new_ino_size - old_ino_size);
1350
1351                         new_itable += new_ino_size;
1352                         old_itable += old_ino_size;
1353                 }
1354
1355                 /* reset the pointer */
1356                 old_itable = tmp_old_itable;
1357                 new_itable = tmp_new_itable;
1358
1359                 retval = io_channel_write_blk64(fs->io, blk,
1360                                         new_ino_blks_per_grp, new_itable);
1361                 if (retval)
1362                         goto err_out;
1363         }
1364
1365         /* Update the meta data */
1366         fs->inode_blocks_per_group = new_ino_blks_per_grp;
1367         fs->super->s_inode_size = new_ino_size;
1368
1369 err_out:
1370         if (old_itable)
1371                 ext2fs_free_mem(&old_itable);
1372
1373         if (new_itable)
1374                 ext2fs_free_mem(&new_itable);
1375
1376         return retval;
1377 }
1378
1379 static errcode_t ext2fs_calculate_summary_stats(ext2_filsys fs)
1380 {
1381         blk64_t         blk;
1382         ext2_ino_t      ino;
1383         unsigned int    group = 0;
1384         unsigned int    count = 0;
1385         int             total_free = 0;
1386         int             group_free = 0;
1387
1388         /*
1389          * First calculate the block statistics
1390          */
1391         for (blk = fs->super->s_first_data_block;
1392              blk < ext2fs_blocks_count(fs->super); blk++) {
1393                 if (!ext2fs_fast_test_block_bitmap2(fs->block_map, blk)) {
1394                         group_free++;
1395                         total_free++;
1396                 }
1397                 count++;
1398                 if ((count == fs->super->s_blocks_per_group) ||
1399                     (blk == ext2fs_blocks_count(fs->super)-1)) {
1400                         ext2fs_bg_free_blocks_count_set(fs, group++,
1401                                                         group_free);
1402                         count = 0;
1403                         group_free = 0;
1404                 }
1405         }
1406         ext2fs_free_blocks_count_set(fs->super, total_free);
1407
1408         /*
1409          * Next, calculate the inode statistics
1410          */
1411         group_free = 0;
1412         total_free = 0;
1413         count = 0;
1414         group = 0;
1415
1416         /* Protect loop from wrap-around if s_inodes_count maxed */
1417         for (ino = 1; ino <= fs->super->s_inodes_count && ino > 0; ino++) {
1418                 if (!ext2fs_fast_test_inode_bitmap2(fs->inode_map, ino)) {
1419                         group_free++;
1420                         total_free++;
1421                 }
1422                 count++;
1423                 if ((count == fs->super->s_inodes_per_group) ||
1424                     (ino == fs->super->s_inodes_count)) {
1425                         ext2fs_bg_free_inodes_count_set(fs, group++,
1426                                                         group_free);
1427                         count = 0;
1428                         group_free = 0;
1429                 }
1430         }
1431         fs->super->s_free_inodes_count = total_free;
1432         ext2fs_mark_super_dirty(fs);
1433         return 0;
1434 }
1435
1436 #define list_for_each_safe(pos, pnext, head) \
1437         for (pos = (head)->next, pnext = pos->next; pos != (head); \
1438              pos = pnext, pnext = pos->next)
1439
1440 static void free_blk_move_list(void)
1441 {
1442         struct list_head *entry, *tmp;
1443         struct blk_move *bmv;
1444
1445         list_for_each_safe(entry, tmp, &blk_move_list) {
1446                 bmv = list_entry(entry, struct blk_move, list);
1447                 list_del(entry);
1448                 ext2fs_free_mem(&bmv);
1449         }
1450         return;
1451 }
1452
1453 static int resize_inode(ext2_filsys fs, unsigned long new_size)
1454 {
1455         errcode_t retval;
1456         int new_ino_blks_per_grp;
1457         ext2fs_block_bitmap bmap;
1458
1459         ext2fs_read_inode_bitmap(fs);
1460         ext2fs_read_block_bitmap(fs);
1461         INIT_LIST_HEAD(&blk_move_list);
1462
1463
1464         new_ino_blks_per_grp = ext2fs_div_ceil(
1465                                         EXT2_INODES_PER_GROUP(fs->super)*
1466                                         new_size,
1467                                         fs->blocksize);
1468
1469         /* We may change the file system.
1470          * Mark the file system as invalid so that
1471          * the user is prompted to run fsck.
1472          */
1473         fs->super->s_state &= ~EXT2_VALID_FS;
1474
1475         retval = ext2fs_allocate_block_bitmap(fs, _("blocks to be moved"),
1476                                                 &bmap);
1477         if (retval) {
1478                 fputs(_("Failed to allocate block bitmap when "
1479                                 "increasing inode size\n"), stderr);
1480                 return retval;
1481         }
1482         retval = get_move_bitmaps(fs, new_ino_blks_per_grp, bmap);
1483         if (retval) {
1484                 fputs(_("Not enough space to increase inode size \n"), stderr);
1485                 goto err_out;
1486         }
1487         retval = move_block(fs, bmap);
1488         if (retval) {
1489                 fputs(_("Failed to relocate blocks during inode resize \n"),
1490                       stderr);
1491                 goto err_out;
1492         }
1493         retval = inode_scan_and_fix(fs, bmap);
1494         if (retval)
1495                 goto err_out_undo;
1496
1497         retval = group_desc_scan_and_fix(fs, bmap);
1498         if (retval)
1499                 goto err_out_undo;
1500
1501         retval = expand_inode_table(fs, new_size);
1502         if (retval)
1503                 goto err_out_undo;
1504
1505         ext2fs_calculate_summary_stats(fs);
1506
1507         fs->super->s_state |= EXT2_VALID_FS;
1508         /* mark super block and block bitmap as dirty */
1509         ext2fs_mark_super_dirty(fs);
1510         ext2fs_mark_bb_dirty(fs);
1511
1512 err_out:
1513         free_blk_move_list();
1514         ext2fs_free_block_bitmap(bmap);
1515
1516         return retval;
1517
1518 err_out_undo:
1519         free_blk_move_list();
1520         ext2fs_free_block_bitmap(bmap);
1521         fputs(_("Error in resizing the inode size.\n"
1522                         "Run e2undo to undo the "
1523                         "file system changes. \n"), stderr);
1524
1525         return retval;
1526 }
1527
1528 static int tune2fs_setup_tdb(const char *name, io_manager *io_ptr)
1529 {
1530         errcode_t retval = 0;
1531         const char *tdb_dir;
1532         char *tdb_file;
1533         char *dev_name, *tmp_name;
1534
1535 #if 0 /* FIXME!! */
1536         /*
1537          * Configuration via a conf file would be
1538          * nice
1539          */
1540         profile_get_string(profile, "scratch_files",
1541                                         "directory", 0, 0,
1542                                         &tdb_dir);
1543 #endif
1544         tmp_name = strdup(name);
1545         if (!tmp_name) {
1546         alloc_fn_fail:
1547                 com_err(program_name, ENOMEM, 
1548                         _("Couldn't allocate memory for tdb filename\n"));
1549                 return ENOMEM;
1550         }
1551         dev_name = basename(tmp_name);
1552
1553         tdb_dir = getenv("E2FSPROGS_UNDO_DIR");
1554         if (!tdb_dir)
1555                 tdb_dir = "/var/lib/e2fsprogs";
1556
1557         if (!strcmp(tdb_dir, "none") || (tdb_dir[0] == 0) ||
1558             access(tdb_dir, W_OK))
1559                 return 0;
1560
1561         tdb_file = malloc(strlen(tdb_dir) + 9 + strlen(dev_name) + 7 + 1);
1562         if (!tdb_file)
1563                 goto alloc_fn_fail;
1564         sprintf(tdb_file, "%s/tune2fs-%s.e2undo", tdb_dir, dev_name);
1565
1566         if (!access(tdb_file, F_OK)) {
1567                 if (unlink(tdb_file) < 0) {
1568                         retval = errno;
1569                         com_err(program_name, retval,
1570                                 _("while trying to delete %s"),
1571                                 tdb_file);
1572                         free(tdb_file);
1573                         return retval;
1574                 }
1575         }
1576
1577         set_undo_io_backing_manager(*io_ptr);
1578         *io_ptr = undo_io_manager;
1579         set_undo_io_backup_file(tdb_file);
1580         printf(_("To undo the tune2fs operation please run "
1581                  "the command\n    e2undo %s %s\n\n"),
1582                  tdb_file, name);
1583         free(tdb_file);
1584         free(tmp_name);
1585         return retval;
1586 }
1587
1588 int main(int argc, char **argv)
1589 {
1590         errcode_t retval;
1591         ext2_filsys fs;
1592         struct ext2_super_block *sb;
1593         io_manager io_ptr, io_ptr_orig = NULL;
1594
1595 #ifdef ENABLE_NLS
1596         setlocale(LC_MESSAGES, "");
1597         setlocale(LC_CTYPE, "");
1598         bindtextdomain(NLS_CAT_NAME, LOCALEDIR);
1599         textdomain(NLS_CAT_NAME);
1600 #endif
1601         if (argc && *argv)
1602                 program_name = *argv;
1603         add_error_table(&et_ext2_error_table);
1604
1605 #ifdef CONFIG_BUILD_FINDFS
1606         if (strcmp(get_progname(argv[0]), "findfs") == 0)
1607                 do_findfs(argc, argv);
1608 #endif
1609         if (strcmp(get_progname(argv[0]), "e2label") == 0)
1610                 parse_e2label_options(argc, argv);
1611         else
1612                 parse_tune2fs_options(argc, argv);
1613
1614 #ifdef CONFIG_TESTIO_DEBUG
1615         if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_DEBUG")) {
1616                 io_ptr = test_io_manager;
1617                 test_io_backing_manager = unix_io_manager;
1618         } else
1619 #endif
1620                 io_ptr = unix_io_manager;
1621
1622 retry_open:
1623         retval = ext2fs_open2(device_name, io_options, open_flag,
1624                               0, 0, io_ptr, &fs);
1625         if (retval) {
1626                         com_err(program_name, retval,
1627                                 _("while trying to open %s"),
1628                         device_name);
1629                 fprintf(stderr,
1630                         _("Couldn't find valid filesystem superblock.\n"));
1631                 exit(1);
1632         }
1633
1634         if (I_flag && !io_ptr_orig) {
1635                 /*
1636                  * Check the inode size is right so we can issue an
1637                  * error message and bail before setting up the tdb
1638                  * file.
1639                  */
1640                 if (new_inode_size == EXT2_INODE_SIZE(fs->super)) {
1641                         fprintf(stderr, _("The inode size is already %lu\n"),
1642                                 new_inode_size);
1643                         exit(1);
1644                 }
1645                 if (new_inode_size < EXT2_INODE_SIZE(fs->super)) {
1646                         fprintf(stderr, _("Shrinking the inode size is "
1647                                           "not supported\n"));
1648                         exit(1);
1649                 }
1650
1651                 /*
1652                  * If inode resize is requested use the
1653                  * Undo I/O manager
1654                  */
1655                 io_ptr_orig = io_ptr;
1656                 retval = tune2fs_setup_tdb(device_name, &io_ptr);
1657                 if (retval)
1658                         exit(1);
1659                 if (io_ptr != io_ptr_orig) {
1660                         ext2fs_close(fs);
1661                         goto retry_open;
1662                 }
1663         }
1664
1665         sb = fs->super;
1666         fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
1667
1668         if (print_label) {
1669                 /* For e2label emulation */
1670                 printf("%.*s\n", (int) sizeof(sb->s_volume_name),
1671                        sb->s_volume_name);
1672                 remove_error_table(&et_ext2_error_table);
1673                 exit(0);
1674         }
1675
1676         retval = ext2fs_check_if_mounted(device_name, &mount_flags);
1677         if (retval) {
1678                 com_err("ext2fs_check_if_mount", retval,
1679                         _("while determining whether %s is mounted."),
1680                         device_name);
1681                 exit(1);
1682         }
1683         /* Normally we only need to write out the superblock */
1684         fs->flags |= EXT2_FLAG_SUPER_ONLY;
1685
1686         if (c_flag) {
1687                 sb->s_max_mnt_count = max_mount_count;
1688                 ext2fs_mark_super_dirty(fs);
1689                 printf(_("Setting maximal mount count to %d\n"),
1690                        max_mount_count);
1691         }
1692         if (C_flag) {
1693                 sb->s_mnt_count = mount_count;
1694                 ext2fs_mark_super_dirty(fs);
1695                 printf(_("Setting current mount count to %d\n"), mount_count);
1696         }
1697         if (e_flag) {
1698                 sb->s_errors = errors;
1699                 ext2fs_mark_super_dirty(fs);
1700                 printf(_("Setting error behavior to %d\n"), errors);
1701         }
1702         if (g_flag) {
1703                 sb->s_def_resgid = resgid;
1704                 ext2fs_mark_super_dirty(fs);
1705                 printf(_("Setting reserved blocks gid to %lu\n"), resgid);
1706         }
1707         if (i_flag) {
1708                 if (interval >= (1ULL << 32)) {
1709                         com_err(program_name, 0,
1710                                 _("interval between checks is too big (%lu)"),
1711                                 interval);
1712                         exit(1);
1713                 }
1714                 sb->s_checkinterval = interval;
1715                 ext2fs_mark_super_dirty(fs);
1716                 printf(_("Setting interval between checks to %lu seconds\n"),
1717                        interval);
1718         }
1719         if (m_flag) {
1720                 ext2fs_r_blocks_count_set(sb, reserved_ratio *
1721                                           ext2fs_blocks_count(sb) / 100.0);
1722                 ext2fs_mark_super_dirty(fs);
1723                 printf (_("Setting reserved blocks percentage to %g%% (%llu blocks)\n"),
1724                         reserved_ratio, ext2fs_r_blocks_count(sb));
1725         }
1726         if (r_flag) {
1727                 if (reserved_blocks > ext2fs_blocks_count(sb)/2) {
1728                         com_err(program_name, 0,
1729                                 _("reserved blocks count is too big (%llu)"),
1730                                 reserved_blocks);
1731                         exit(1);
1732                 }
1733                 ext2fs_r_blocks_count_set(sb, reserved_blocks);
1734                 ext2fs_mark_super_dirty(fs);
1735                 printf(_("Setting reserved blocks count to %llu\n"),
1736                        reserved_blocks);
1737         }
1738         if (s_flag == 1) {
1739                 if (sb->s_feature_ro_compat &
1740                     EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER)
1741                         fputs(_("\nThe filesystem already has sparse "
1742                                 "superblocks.\n"), stderr);
1743                 else {
1744                         sb->s_feature_ro_compat |=
1745                                 EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER;
1746                         sb->s_state &= ~EXT2_VALID_FS;
1747                         ext2fs_mark_super_dirty(fs);
1748                         printf(_("\nSparse superblock flag set.  %s"),
1749                                _(please_fsck));
1750                 }
1751         }
1752         if (s_flag == 0) {
1753                 fputs(_("\nClearing the sparse superflag not supported.\n"),
1754                       stderr);
1755                 exit(1);
1756         }
1757         if (T_flag) {
1758                 sb->s_lastcheck = last_check_time;
1759                 ext2fs_mark_super_dirty(fs);
1760                 printf(_("Setting time filesystem last checked to %s\n"),
1761                        ctime(&last_check_time));
1762         }
1763         if (u_flag) {
1764                 sb->s_def_resuid = resuid;
1765                 ext2fs_mark_super_dirty(fs);
1766                 printf(_("Setting reserved blocks uid to %lu\n"), resuid);
1767         }
1768         if (L_flag) {
1769                 if (strlen(new_label) > sizeof(sb->s_volume_name))
1770                         fputs(_("Warning: label too long, truncating.\n"),
1771                               stderr);
1772                 memset(sb->s_volume_name, 0, sizeof(sb->s_volume_name));
1773                 strncpy(sb->s_volume_name, new_label,
1774                         sizeof(sb->s_volume_name));
1775                 ext2fs_mark_super_dirty(fs);
1776         }
1777         if (M_flag) {
1778                 memset(sb->s_last_mounted, 0, sizeof(sb->s_last_mounted));
1779                 strncpy(sb->s_last_mounted, new_last_mounted,
1780                         sizeof(sb->s_last_mounted));
1781                 ext2fs_mark_super_dirty(fs);
1782         }
1783         if (mntopts_cmd)
1784                 update_mntopts(fs, mntopts_cmd);
1785         if (features_cmd)
1786                 update_feature_set(fs, features_cmd);
1787         if (extended_cmd)
1788                 parse_extended_opts(fs, extended_cmd);
1789         if (journal_size || journal_device)
1790                 add_journal(fs);
1791
1792         if (U_flag) {
1793                 int set_csum = 0;
1794                 dgrp_t i;
1795
1796                 if (sb->s_feature_ro_compat &
1797                     EXT4_FEATURE_RO_COMPAT_GDT_CSUM) {
1798                         /*
1799                          * Determine if the block group checksums are
1800                          * correct so we know whether or not to set
1801                          * them later on.
1802                          */
1803                         for (i = 0; i < fs->group_desc_count; i++)
1804                                 if (!ext2fs_group_desc_csum_verify(fs, i))
1805                                         break;
1806                         if (i >= fs->group_desc_count)
1807                                 set_csum = 1;
1808                 }
1809                 if ((strcasecmp(new_UUID, "null") == 0) ||
1810                     (strcasecmp(new_UUID, "clear") == 0)) {
1811                         uuid_clear(sb->s_uuid);
1812                 } else if (strcasecmp(new_UUID, "time") == 0) {
1813                         uuid_generate_time(sb->s_uuid);
1814                 } else if (strcasecmp(new_UUID, "random") == 0) {
1815                         uuid_generate(sb->s_uuid);
1816                 } else if (uuid_parse(new_UUID, sb->s_uuid)) {
1817                         com_err(program_name, 0, _("Invalid UUID format\n"));
1818                         exit(1);
1819                 }
1820                 if (set_csum) {
1821                         for (i = 0; i < fs->group_desc_count; i++)
1822                                 ext2fs_group_desc_csum_set(fs, i);
1823                         fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
1824                 }
1825                 ext2fs_mark_super_dirty(fs);
1826         }
1827         if (I_flag) {
1828                 if (mount_flags & EXT2_MF_MOUNTED) {
1829                         fputs(_("The inode size may only be "
1830                                 "changed when the filesystem is "
1831                                 "unmounted.\n"), stderr);
1832                         exit(1);
1833                 }
1834                 if (fs->super->s_feature_incompat &
1835                     EXT4_FEATURE_INCOMPAT_FLEX_BG) {
1836                         fputs(_("Changing the inode size not supported for "
1837                                 "filesystems with the flex_bg\n"
1838                                 "feature enabled.\n"),
1839                               stderr);
1840                         exit(1);
1841                 }
1842                 /*
1843                  * We want to update group descriptor also
1844                  * with the new free inode count
1845                  */
1846                 fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
1847                 if (resize_inode(fs, new_inode_size) == 0) {
1848                         printf(_("Setting inode size %lu\n"),
1849                                                         new_inode_size);
1850                 }
1851         }
1852
1853         if (l_flag)
1854                 list_super(sb);
1855         if (stride_set) {
1856                 sb->s_raid_stride = stride;
1857                 ext2fs_mark_super_dirty(fs);
1858                 printf(_("Setting stride size to %d\n"), stride);
1859         }
1860         if (stripe_width_set) {
1861                 sb->s_raid_stripe_width = stripe_width;
1862                 ext2fs_mark_super_dirty(fs);
1863                 printf(_("Setting stripe width to %d\n"), stripe_width);
1864         }
1865         free(device_name);
1866         remove_error_table(&et_ext2_error_table);
1867         return (ext2fs_close(fs) ? 1 : 0);
1868 }