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