Whamcloud - gitweb
misc: fix gcc -Wall nits
[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 "config.h"
31 #include <fcntl.h>
32 #include <grp.h>
33 #ifdef HAVE_GETOPT_H
34 #include <getopt.h>
35 #else
36 extern char *optarg;
37 extern int optind;
38 #endif
39 #include <pwd.h>
40 #include <stdio.h>
41 #ifdef HAVE_STDLIB_H
42 #include <stdlib.h>
43 #endif
44 #include <string.h>
45 #include <time.h>
46 #include <unistd.h>
47 #include <sys/types.h>
48 #include <libgen.h>
49 #include <limits.h>
50
51 #include "ext2fs/ext2_fs.h"
52 #include "ext2fs/ext2fs.h"
53 #include "et/com_err.h"
54 #include "uuid/uuid.h"
55 #include "e2p/e2p.h"
56 #include "jfs_user.h"
57 #include "util.h"
58 #include "blkid/blkid.h"
59 #include "quota/mkquota.h"
60
61 #include "../version.h"
62 #include "nls-enable.h"
63
64 #define QOPT_ENABLE     (1)
65 #define QOPT_DISABLE    (-1)
66
67 extern int ask_yn(const char *string, int def);
68
69 const char *program_name = "tune2fs";
70 char *device_name;
71 char *new_label, *new_last_mounted, *new_UUID;
72 char *io_options;
73 static int c_flag, C_flag, e_flag, f_flag, g_flag, i_flag, l_flag, L_flag;
74 static int m_flag, M_flag, Q_flag, r_flag, s_flag = -1, u_flag, U_flag, T_flag;
75 static int I_flag;
76 static int clear_mmp;
77 static time_t last_check_time;
78 static int print_label;
79 static int max_mount_count, mount_count, mount_flags;
80 static unsigned long interval;
81 static blk64_t reserved_blocks;
82 static double reserved_ratio;
83 static unsigned long resgid, resuid;
84 static unsigned short errors;
85 static int open_flag;
86 static char *features_cmd;
87 static char *mntopts_cmd;
88 static int stride, stripe_width;
89 static int stride_set, stripe_width_set;
90 static char *extended_cmd;
91 static unsigned long new_inode_size;
92 static char *ext_mount_opts;
93 static int usrquota, grpquota;
94 static int rewrite_checksums;
95
96 int journal_size, journal_flags;
97 char *journal_device;
98
99 static struct list_head blk_move_list;
100
101 struct blk_move {
102         struct list_head list;
103         blk64_t old_loc;
104         blk64_t new_loc;
105 };
106
107
108 static const char *please_fsck = N_("Please run e2fsck on the filesystem.\n");
109 static const char *please_dir_fsck =
110                 N_("Please run e2fsck -D on the filesystem.\n");
111
112 #ifdef CONFIG_BUILD_FINDFS
113 void do_findfs(int argc, char **argv);
114 #endif
115
116 static void usage(void)
117 {
118         fprintf(stderr,
119                 _("Usage: %s [-c max_mounts_count] [-e errors_behavior] "
120                   "[-g group]\n"
121                   "\t[-i interval[d|m|w]] [-j] [-J journal_options] [-l]\n"
122                   "\t[-m reserved_blocks_percent] "
123                   "[-o [^]mount_options[,...]] [-p mmp_update_interval]\n"
124                   "\t[-r reserved_blocks_count] [-u user] [-C mount_count] "
125                   "[-L volume_label]\n"
126                   "\t[-M last_mounted_dir] [-O [^]feature[,...]]\n"
127                   "\t[-E extended-option[,...]] [-T last_check_time] "
128                   "[-U UUID]\n\t[ -I new_inode_size ] device\n"), program_name);
129         exit(1);
130 }
131
132 static __u32 ok_features[3] = {
133         /* Compat */
134         EXT3_FEATURE_COMPAT_HAS_JOURNAL |
135                 EXT2_FEATURE_COMPAT_DIR_INDEX,
136         /* Incompat */
137         EXT2_FEATURE_INCOMPAT_FILETYPE |
138                 EXT3_FEATURE_INCOMPAT_EXTENTS |
139                 EXT4_FEATURE_INCOMPAT_FLEX_BG |
140                 EXT4_FEATURE_INCOMPAT_MMP,
141         /* R/O compat */
142         EXT2_FEATURE_RO_COMPAT_LARGE_FILE |
143                 EXT4_FEATURE_RO_COMPAT_HUGE_FILE|
144                 EXT4_FEATURE_RO_COMPAT_DIR_NLINK|
145                 EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE|
146                 EXT4_FEATURE_RO_COMPAT_GDT_CSUM |
147                 EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER |
148 #ifdef CONFIG_QUOTA
149                 EXT4_FEATURE_RO_COMPAT_QUOTA |
150 #endif
151                 EXT4_FEATURE_RO_COMPAT_METADATA_CSUM
152 };
153
154 static __u32 clear_ok_features[3] = {
155         /* Compat */
156         EXT3_FEATURE_COMPAT_HAS_JOURNAL |
157                 EXT2_FEATURE_COMPAT_RESIZE_INODE |
158                 EXT2_FEATURE_COMPAT_DIR_INDEX,
159         /* Incompat */
160         EXT2_FEATURE_INCOMPAT_FILETYPE |
161                 EXT4_FEATURE_INCOMPAT_FLEX_BG |
162                 EXT4_FEATURE_INCOMPAT_MMP,
163         /* R/O compat */
164         EXT2_FEATURE_RO_COMPAT_LARGE_FILE |
165                 EXT4_FEATURE_RO_COMPAT_HUGE_FILE|
166                 EXT4_FEATURE_RO_COMPAT_DIR_NLINK|
167                 EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE|
168                 EXT4_FEATURE_RO_COMPAT_GDT_CSUM |
169 #ifdef CONFIG_QUOTA
170                 EXT4_FEATURE_RO_COMPAT_QUOTA |
171 #endif
172                 EXT4_FEATURE_RO_COMPAT_METADATA_CSUM
173 };
174
175 /*
176  * Remove an external journal from the filesystem
177  */
178 static int remove_journal_device(ext2_filsys fs)
179 {
180         char            *journal_path;
181         ext2_filsys     jfs;
182         char            buf[1024];
183         journal_superblock_t    *jsb;
184         int             i, nr_users;
185         errcode_t       retval;
186         int             commit_remove_journal = 0;
187         io_manager      io_ptr;
188
189         if (f_flag)
190                 commit_remove_journal = 1; /* force removal even if error */
191
192         uuid_unparse(fs->super->s_journal_uuid, buf);
193         journal_path = blkid_get_devname(NULL, "UUID", buf);
194
195         if (!journal_path) {
196                 journal_path =
197                         ext2fs_find_block_device(fs->super->s_journal_dev);
198                 if (!journal_path)
199                         goto no_valid_journal;
200         }
201
202 #ifdef CONFIG_TESTIO_DEBUG
203         if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_BLOCK")) {
204                 io_ptr = test_io_manager;
205                 test_io_backing_manager = unix_io_manager;
206         } else
207 #endif
208                 io_ptr = unix_io_manager;
209         retval = ext2fs_open(journal_path, EXT2_FLAG_RW|
210                              EXT2_FLAG_JOURNAL_DEV_OK, 0,
211                              fs->blocksize, io_ptr, &jfs);
212         if (retval) {
213                 com_err(program_name, retval,
214                         _("while trying to open external journal"));
215                 goto no_valid_journal;
216         }
217         if (!(jfs->super->s_feature_incompat &
218               EXT3_FEATURE_INCOMPAT_JOURNAL_DEV)) {
219                 fprintf(stderr, _("%s is not a journal device.\n"),
220                         journal_path);
221                 goto no_valid_journal;
222         }
223
224         /* Get the journal superblock */
225         if ((retval = io_channel_read_blk64(jfs->io, 1, -1024, buf))) {
226                 com_err(program_name, retval,
227                         _("while reading journal superblock"));
228                 goto no_valid_journal;
229         }
230
231         jsb = (journal_superblock_t *) buf;
232         if ((jsb->s_header.h_magic != (unsigned)ntohl(JFS_MAGIC_NUMBER)) ||
233             (jsb->s_header.h_blocktype != (unsigned)ntohl(JFS_SUPERBLOCK_V2))) {
234                 fputs(_("Journal superblock not found!\n"), stderr);
235                 goto no_valid_journal;
236         }
237
238         /* Find the filesystem UUID */
239         nr_users = ntohl(jsb->s_nr_users);
240         for (i = 0; i < nr_users; i++) {
241                 if (memcmp(fs->super->s_uuid, &jsb->s_users[i * 16], 16) == 0)
242                         break;
243         }
244         if (i >= nr_users) {
245                 fputs(_("Filesystem's UUID not found on journal device.\n"),
246                       stderr);
247                 commit_remove_journal = 1;
248                 goto no_valid_journal;
249         }
250         nr_users--;
251         for (i = 0; i < nr_users; i++)
252                 memcpy(&jsb->s_users[i * 16], &jsb->s_users[(i + 1) * 16], 16);
253         jsb->s_nr_users = htonl(nr_users);
254
255         /* Write back the journal superblock */
256         if ((retval = io_channel_write_blk64(jfs->io, 1, -1024, buf))) {
257                 com_err(program_name, retval,
258                         "while writing journal superblock.");
259                 goto no_valid_journal;
260         }
261
262         commit_remove_journal = 1;
263
264 no_valid_journal:
265         if (commit_remove_journal == 0) {
266                 fputs(_("Cannot locate journal device. It was NOT removed\n"
267                         "Use -f option to remove missing journal device.\n"),
268                       stderr);
269                 return 1;
270         }
271         fs->super->s_journal_dev = 0;
272         uuid_clear(fs->super->s_journal_uuid);
273         ext2fs_mark_super_dirty(fs);
274         fputs(_("Journal removed\n"), stdout);
275         free(journal_path);
276
277         return 0;
278 }
279
280 /* Helper function for remove_journal_inode */
281 static int release_blocks_proc(ext2_filsys fs, blk64_t *blocknr,
282                                e2_blkcnt_t blockcnt EXT2FS_ATTR((unused)),
283                                blk64_t ref_block EXT2FS_ATTR((unused)),
284                                int ref_offset EXT2FS_ATTR((unused)),
285                                void *private EXT2FS_ATTR((unused)))
286 {
287         blk64_t block;
288         int     group;
289
290         block = *blocknr;
291         ext2fs_unmark_block_bitmap2(fs->block_map, block);
292         group = ext2fs_group_of_blk2(fs, block);
293         ext2fs_bg_free_blocks_count_set(fs, group, ext2fs_bg_free_blocks_count(fs, group) + 1);
294         ext2fs_group_desc_csum_set(fs, group);
295         ext2fs_free_blocks_count_add(fs->super, EXT2FS_CLUSTER_RATIO(fs));
296         return 0;
297 }
298
299 /*
300  * Remove the journal inode from the filesystem
301  */
302 static errcode_t remove_journal_inode(ext2_filsys fs)
303 {
304         struct ext2_inode       inode;
305         errcode_t               retval;
306         ino_t                   ino = fs->super->s_journal_inum;
307
308         retval = ext2fs_read_inode(fs, ino,  &inode);
309         if (retval) {
310                 com_err(program_name, retval,
311                         _("while reading journal inode"));
312                 return retval;
313         }
314         if (ino == EXT2_JOURNAL_INO) {
315                 retval = ext2fs_read_bitmaps(fs);
316                 if (retval) {
317                         com_err(program_name, retval,
318                                 _("while reading bitmaps"));
319                         return retval;
320                 }
321                 retval = ext2fs_block_iterate3(fs, ino,
322                                                BLOCK_FLAG_READ_ONLY, NULL,
323                                                release_blocks_proc, NULL);
324                 if (retval) {
325                         com_err(program_name, retval,
326                                 _("while clearing journal inode"));
327                         return retval;
328                 }
329                 memset(&inode, 0, sizeof(inode));
330                 ext2fs_mark_bb_dirty(fs);
331                 fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
332         } else
333                 inode.i_flags &= ~EXT2_IMMUTABLE_FL;
334         retval = ext2fs_write_inode(fs, ino, &inode);
335         if (retval) {
336                 com_err(program_name, retval,
337                         _("while writing journal inode"));
338                 return retval;
339         }
340         fs->super->s_journal_inum = 0;
341         ext2fs_mark_super_dirty(fs);
342
343         return 0;
344 }
345
346 /*
347  * Update the default mount options
348  */
349 static int update_mntopts(ext2_filsys fs, char *mntopts)
350 {
351         struct ext2_super_block *sb = fs->super;
352
353         if (e2p_edit_mntopts(mntopts, &sb->s_default_mount_opts, ~0)) {
354                 fprintf(stderr, _("Invalid mount option set: %s\n"),
355                         mntopts);
356                 return 1;
357         }
358         ext2fs_mark_super_dirty(fs);
359
360         return 0;
361 }
362
363 static int check_fsck_needed(ext2_filsys fs)
364 {
365         if (fs->super->s_state & EXT2_VALID_FS)
366                 return 0;
367         printf("\n%s\n", _(please_fsck));
368         if (mount_flags & EXT2_MF_READONLY)
369                 printf(_("(and reboot afterwards!)\n"));
370         return 1;
371 }
372
373 static void request_dir_fsck_afterwards(ext2_filsys fs)
374 {
375         static int requested;
376
377         if (requested++)
378                 return;
379         fs->super->s_state &= ~EXT2_VALID_FS;
380         printf("\n%s\n", _(please_dir_fsck));
381         if (mount_flags & EXT2_MF_READONLY)
382                 printf(_("(and reboot afterwards!)\n"));
383 }
384
385 static void request_fsck_afterwards(ext2_filsys fs)
386 {
387         static int requested = 0;
388
389         if (requested++)
390                 return;
391         fs->super->s_state &= ~EXT2_VALID_FS;
392         printf("\n%s\n", _(please_fsck));
393         if (mount_flags & EXT2_MF_READONLY)
394                 printf(_("(and reboot afterwards!)\n"));
395 }
396
397 /* Rewrite extents */
398 static errcode_t rewrite_extents(ext2_filsys fs, ext2_ino_t ino,
399                                  struct ext2_inode *inode)
400 {
401         ext2_extent_handle_t    handle;
402         struct ext2fs_extent    extent;
403         int                     op = EXT2_EXTENT_ROOT;
404         errcode_t               errcode;
405
406         if (!(inode->i_flags & EXT4_EXTENTS_FL))
407                 return 0;
408
409         errcode = ext2fs_extent_open(fs, ino, &handle);
410         if (errcode)
411                 return errcode;
412
413         while (1) {
414                 errcode = ext2fs_extent_get(handle, op, &extent);
415                 if (errcode)
416                         break;
417
418                 /* Root node is in the separately checksummed inode */
419                 if (op == EXT2_EXTENT_ROOT) {
420                         op = EXT2_EXTENT_NEXT;
421                         continue;
422                 }
423                 op = EXT2_EXTENT_NEXT;
424
425                 /* Only visit the first extent in each extent block */
426                 if (extent.e_flags & EXT2_EXTENT_FLAGS_SECOND_VISIT)
427                         continue;
428                 errcode = ext2fs_extent_replace(handle, 0, &extent);
429                 if (errcode)
430                         break;
431         }
432
433         /* Ok if we run off the end */
434         if (errcode == EXT2_ET_EXTENT_NO_NEXT)
435                 errcode = 0;
436         return errcode;
437 }
438
439 /*
440  * Rewrite directory blocks with checksums
441  */
442 struct rewrite_dir_context {
443         char *buf;
444         errcode_t errcode;
445         ext2_ino_t dir;
446         int is_htree;
447 };
448
449 static int rewrite_dir_block(ext2_filsys fs,
450                              blk64_t    *blocknr,
451                              e2_blkcnt_t blockcnt EXT2FS_ATTR((unused)),
452                              blk64_t    ref_block EXT2FS_ATTR((unused)),
453                              int        ref_offset EXT2FS_ATTR((unused)),
454                              void       *priv_data)
455 {
456         struct ext2_dx_countlimit *dcl = NULL;
457         struct rewrite_dir_context *ctx = priv_data;
458         int dcl_offset, changed = 0;
459
460         ctx->errcode = ext2fs_read_dir_block4(fs, *blocknr, ctx->buf, 0,
461                                               ctx->dir);
462         if (ctx->errcode)
463                 return BLOCK_ABORT;
464
465         /* if htree node... */
466         if (ctx->is_htree)
467                 ext2fs_get_dx_countlimit(fs, (struct ext2_dir_entry *)ctx->buf,
468                                          &dcl, &dcl_offset);
469         if (dcl) {
470                 if (!EXT2_HAS_RO_COMPAT_FEATURE(fs->super,
471                                 EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) {
472                         /* Ensure limit is the max size */
473                         int max_entries = (fs->blocksize - dcl_offset) /
474                                           sizeof(struct ext2_dx_entry);
475                         if (ext2fs_le16_to_cpu(dcl->limit) != max_entries) {
476                                 changed = 1;
477                                 dcl->limit = ext2fs_cpu_to_le16(max_entries);
478                         }
479                 } else {
480                         /* If htree block is full then rebuild the dir */
481                         if (ext2fs_le16_to_cpu(dcl->count) ==
482                             ext2fs_le16_to_cpu(dcl->limit)) {
483                                 request_dir_fsck_afterwards(fs);
484                                 return 0;
485                         }
486                         /*
487                          * Ensure dcl->limit is small enough to leave room for
488                          * the checksum tail.
489                          */
490                         int max_entries = (fs->blocksize - (dcl_offset +
491                                                 sizeof(struct ext2_dx_tail))) /
492                                           sizeof(struct ext2_dx_entry);
493                         if (ext2fs_le16_to_cpu(dcl->limit) != max_entries)
494                                 dcl->limit = ext2fs_cpu_to_le16(max_entries);
495                         /* Always rewrite checksum */
496                         changed = 1;
497                 }
498         } else {
499                 unsigned int rec_len, name_size;
500                 char *top = ctx->buf + fs->blocksize;
501                 struct ext2_dir_entry *de = (struct ext2_dir_entry *)ctx->buf;
502                 struct ext2_dir_entry *last_de = NULL, *penultimate_de = NULL;
503
504                 /* Find last and penultimate dirent */
505                 while ((char *)de < top) {
506                         penultimate_de = last_de;
507                         last_de = de;
508                         ctx->errcode = ext2fs_get_rec_len(fs, de, &rec_len);
509                         if (!ctx->errcode && !rec_len)
510                                 ctx->errcode = EXT2_ET_DIR_CORRUPTED;
511                         if (ctx->errcode)
512                                 return BLOCK_ABORT;
513                         de = (struct ext2_dir_entry *)(((char *)de) + rec_len);
514                 }
515                 ctx->errcode = ext2fs_get_rec_len(fs, last_de, &rec_len);
516                 if (ctx->errcode)
517                         return BLOCK_ABORT;
518                 name_size = last_de->name_len & 0xFF;
519
520                 if (!EXT2_HAS_RO_COMPAT_FEATURE(fs->super,
521                                 EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) {
522                         if (!penultimate_de)
523                                 return 0;
524                         if (last_de->inode ||
525                             name_size ||
526                             rec_len != sizeof(struct ext2_dir_entry_tail))
527                                 return 0;
528                         /*
529                          * The last dirent is unused and the right length to
530                          * have stored a checksum.  Erase it.
531                          */
532                         ctx->errcode = ext2fs_get_rec_len(fs, penultimate_de,
533                                                           &rec_len);
534                         if (!rec_len)
535                                 ctx->errcode = EXT2_ET_DIR_CORRUPTED;
536                         if (ctx->errcode)
537                                 return BLOCK_ABORT;
538                         ext2fs_set_rec_len(fs, rec_len +
539                                         sizeof(struct ext2_dir_entry_tail),
540                                         penultimate_de);
541                         changed = 1;
542                 } else {
543                         unsigned csum_size = sizeof(struct ext2_dir_entry_tail);
544                         struct ext2_dir_entry_tail *t;
545
546                         /*
547                          * If the last dirent looks like the tail, just update
548                          * the checksum.
549                          */
550                         if (!last_de->inode &&
551                             rec_len == csum_size) {
552                                 t = (struct ext2_dir_entry_tail *)last_de;
553                                 t->det_reserved_name_len =
554                                                 EXT2_DIR_NAME_LEN_CSUM;
555                                 changed = 1;
556                                 goto out;
557                         }
558                         if (name_size & 3)
559                                 name_size = (name_size & ~3) + 4;
560                         /* If there's not enough space for the tail, e2fsck */
561                         if (rec_len <= (8 + name_size + csum_size)) {
562                                 request_dir_fsck_afterwards(fs);
563                                 return 0;
564                         }
565                         /* Shorten that last de and insert the tail */
566                         ext2fs_set_rec_len(fs, rec_len - csum_size, last_de);
567                         t = EXT2_DIRENT_TAIL(ctx->buf, fs->blocksize);
568                         ext2fs_initialize_dirent_tail(fs, t);
569
570                         /* Always update checksum */
571                         changed = 1;
572                 }
573         }
574
575 out:
576         if (!changed)
577                 return 0;
578
579         ctx->errcode = ext2fs_write_dir_block4(fs, *blocknr, ctx->buf,
580                                                0, ctx->dir);
581         if (ctx->errcode)
582                 return BLOCK_ABORT;
583
584         return 0;
585 }
586
587 static errcode_t rewrite_directory(ext2_filsys fs, ext2_ino_t dir,
588                                    struct ext2_inode *inode)
589 {
590         errcode_t       retval;
591         struct rewrite_dir_context ctx;
592
593         retval = ext2fs_get_mem(fs->blocksize, &ctx.buf);
594         if (retval)
595                 return retval;
596
597         ctx.is_htree = (inode->i_flags & EXT2_INDEX_FL);
598         ctx.dir = dir;
599         ctx.errcode = 0;
600         retval = ext2fs_block_iterate3(fs, dir, BLOCK_FLAG_READ_ONLY |
601                                                 BLOCK_FLAG_DATA_ONLY,
602                                        0, rewrite_dir_block, &ctx);
603
604         ext2fs_free_mem(&ctx.buf);
605         if (retval)
606                 return retval;
607
608         return ctx.errcode;
609 }
610
611 /*
612  * Forcibly set checksums in all inodes.
613  */
614 static void rewrite_inodes(ext2_filsys fs)
615 {
616         int length = EXT2_INODE_SIZE(fs->super);
617         struct ext2_inode *inode;
618         char            *ea_buf;
619         ext2_inode_scan scan;
620         errcode_t       retval;
621         ext2_ino_t      ino;
622         blk64_t         file_acl_block;
623
624         if (fs->super->s_creator_os != EXT2_OS_LINUX)
625                 return;
626
627         retval = ext2fs_open_inode_scan(fs, 0, &scan);
628         if (retval) {
629                 com_err("set_csum", retval, "while opening inode scan");
630                 exit(1);
631         }
632
633         retval = ext2fs_get_mem(length, &inode);
634         if (retval) {
635                 com_err("set_csum", retval, "while allocating memory");
636                 exit(1);
637         }
638
639         retval = ext2fs_get_mem(fs->blocksize, &ea_buf);
640         if (retval) {
641                 com_err("set_csum", retval, "while allocating memory");
642                 exit(1);
643         }
644
645         do {
646                 retval = ext2fs_get_next_inode_full(scan, &ino, inode, length);
647                 if (retval) {
648                         com_err("set_csum", retval, "while getting next inode");
649                         exit(1);
650                 }
651                 if (!ino)
652                         break;
653
654                 retval = ext2fs_write_inode_full(fs, ino, inode, length);
655                 if (retval) {
656                         com_err("set_csum", retval, "while writing inode");
657                         exit(1);
658                 }
659
660                 retval = rewrite_extents(fs, ino, inode);
661                 if (retval) {
662                         com_err("rewrite_extents", retval,
663                                 "while rewriting extents");
664                         exit(1);
665                 }
666
667                 if (LINUX_S_ISDIR(inode->i_mode)) {
668                         retval = rewrite_directory(fs, ino, inode);
669                         if (retval) {
670                                 com_err("rewrite_directory", retval,
671                                         "while rewriting directories");
672                                 exit(1);
673                         }
674                 }
675
676                 file_acl_block = ext2fs_file_acl_block(fs, inode);
677                 if (!file_acl_block)
678                         continue;
679                 retval = ext2fs_read_ext_attr3(fs, file_acl_block, ea_buf, ino);
680                 if (retval) {
681                         com_err("rewrite_eablock", retval,
682                                 "while rewriting extended attribute");
683                         exit(1);
684                 }
685                 retval = ext2fs_write_ext_attr3(fs, file_acl_block, ea_buf,
686                                                 ino);
687                 if (retval) {
688                         com_err("rewrite_eablock", retval,
689                                 "while rewriting extended attribute");
690                         exit(1);
691                 }
692         } while (ino);
693
694         ext2fs_free_mem(&inode);
695         ext2fs_free_mem(&ea_buf);
696         ext2fs_close_inode_scan(scan);
697 }
698
699 static void rewrite_metadata_checksums(ext2_filsys fs)
700 {
701         dgrp_t i;
702
703         fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS;
704         ext2fs_init_csum_seed(fs);
705         for (i = 0; i < fs->group_desc_count; i++)
706                 ext2fs_group_desc_csum_set(fs, i);
707         rewrite_inodes(fs);
708         ext2fs_read_bitmaps(fs);
709         ext2fs_mark_ib_dirty(fs);
710         ext2fs_mark_bb_dirty(fs);
711         ext2fs_mmp_update2(fs, 1);
712         fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
713         fs->flags &= ~EXT2_FLAG_IGNORE_CSUM_ERRORS;
714         if (EXT2_HAS_RO_COMPAT_FEATURE(fs->super,
715                                        EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
716                 fs->super->s_checksum_type = EXT2_CRC32C_CHKSUM;
717         else
718                 fs->super->s_checksum_type = 0;
719         ext2fs_mark_super_dirty(fs);
720 }
721
722 static void enable_uninit_bg(ext2_filsys fs)
723 {
724         struct ext2_group_desc *gd;
725         dgrp_t i;
726
727         for (i = 0; i < fs->group_desc_count; i++) {
728                 gd = ext2fs_group_desc(fs, fs->group_desc, i);
729                 gd->bg_itable_unused = 0;
730                 gd->bg_flags = EXT2_BG_INODE_ZEROED;
731                 ext2fs_group_desc_csum_set(fs, i);
732         }
733         fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
734 }
735
736 static void disable_uninit_bg(ext2_filsys fs, __u32 csum_feature_flag)
737 {
738         struct ext2_group_desc *gd;
739         dgrp_t i;
740
741         /* Load bitmaps to ensure that the uninit ones get written out */
742         fs->super->s_feature_ro_compat |= csum_feature_flag;
743         ext2fs_read_bitmaps(fs);
744         ext2fs_mark_ib_dirty(fs);
745         ext2fs_mark_bb_dirty(fs);
746         fs->super->s_feature_ro_compat &= ~csum_feature_flag;
747
748         for (i = 0; i < fs->group_desc_count; i++) {
749                 gd = ext2fs_group_desc(fs, fs->group_desc, i);
750                 if ((gd->bg_flags & EXT2_BG_INODE_ZEROED) == 0) {
751                         /*
752                          * XXX what we really should do is zap
753                          * uninitialized inode tables instead.
754                          */
755                         request_fsck_afterwards(fs);
756                         break;
757                 }
758                 gd->bg_itable_unused = 0;
759                 gd->bg_flags = 0;
760                 ext2fs_group_desc_csum_set(fs, i);
761         }
762         fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
763 }
764
765 /*
766  * Update the feature set as provided by the user.
767  */
768 static int update_feature_set(ext2_filsys fs, char *features)
769 {
770         struct ext2_super_block *sb = fs->super;
771         __u32           old_features[3];
772         int             type_err;
773         unsigned int    mask_err;
774
775 #define FEATURE_ON(type, mask) (!(old_features[(type)] & (mask)) && \
776                                 ((&sb->s_feature_compat)[(type)] & (mask)))
777 #define FEATURE_OFF(type, mask) ((old_features[(type)] & (mask)) && \
778                                  !((&sb->s_feature_compat)[(type)] & (mask)))
779 #define FEATURE_CHANGED(type, mask) ((mask) & \
780                      (old_features[(type)] ^ (&sb->s_feature_compat)[(type)]))
781
782         old_features[E2P_FEATURE_COMPAT] = sb->s_feature_compat;
783         old_features[E2P_FEATURE_INCOMPAT] = sb->s_feature_incompat;
784         old_features[E2P_FEATURE_RO_INCOMPAT] = sb->s_feature_ro_compat;
785
786         if (e2p_edit_feature2(features, &sb->s_feature_compat,
787                               ok_features, clear_ok_features,
788                               &type_err, &mask_err)) {
789                 if (!mask_err)
790                         fprintf(stderr,
791                                 _("Invalid filesystem option set: %s\n"),
792                                 features);
793                 else if (type_err & E2P_FEATURE_NEGATE_FLAG)
794                         fprintf(stderr, _("Clearing filesystem feature '%s' "
795                                           "not supported.\n"),
796                                 e2p_feature2string(type_err &
797                                                    E2P_FEATURE_TYPE_MASK,
798                                                    mask_err));
799                 else
800                         fprintf(stderr, _("Setting filesystem feature '%s' "
801                                           "not supported.\n"),
802                                 e2p_feature2string(type_err, mask_err));
803                 return 1;
804         }
805
806         if (FEATURE_OFF(E2P_FEATURE_COMPAT, EXT3_FEATURE_COMPAT_HAS_JOURNAL)) {
807                 if ((mount_flags & EXT2_MF_MOUNTED) &&
808                     !(mount_flags & EXT2_MF_READONLY)) {
809                         fputs(_("The has_journal feature may only be "
810                                 "cleared when the filesystem is\n"
811                                 "unmounted or mounted "
812                                 "read-only.\n"), stderr);
813                         return 1;
814                 }
815                 if (sb->s_feature_incompat &
816                     EXT3_FEATURE_INCOMPAT_RECOVER) {
817                         fputs(_("The needs_recovery flag is set.  "
818                                 "Please run e2fsck before clearing\n"
819                                 "the has_journal flag.\n"), stderr);
820                         return 1;
821                 }
822                 if (sb->s_journal_inum) {
823                         if (remove_journal_inode(fs))
824                                 return 1;
825                 }
826                 if (sb->s_journal_dev) {
827                         if (remove_journal_device(fs))
828                                 return 1;
829                 }
830         }
831         if (FEATURE_ON(E2P_FEATURE_INCOMPAT, EXT4_FEATURE_INCOMPAT_MMP)) {
832                 int error;
833
834                 if ((mount_flags & EXT2_MF_MOUNTED) ||
835                     (mount_flags & EXT2_MF_READONLY)) {
836                         fputs(_("The multiple mount protection feature can't\n"
837                                 "be set if the filesystem is mounted or\n"
838                                 "read-only.\n"), stderr);
839                         return 1;
840                 }
841
842                 error = ext2fs_mmp_init(fs);
843                 if (error) {
844                         fputs(_("\nError while enabling multiple mount "
845                                 "protection feature."), stderr);
846                         return 1;
847                 }
848
849                 /*
850                  * We want to update group desc with the new free blocks count
851                  */
852                 fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
853
854                 printf(_("Multiple mount protection has been enabled "
855                          "with update interval %ds.\n"),
856                        sb->s_mmp_update_interval);
857         }
858
859         if (FEATURE_OFF(E2P_FEATURE_INCOMPAT, EXT4_FEATURE_INCOMPAT_MMP)) {
860                 int error;
861
862                 if (mount_flags & EXT2_MF_READONLY) {
863                         fputs(_("The multiple mount protection feature cannot\n"
864                                 "be disabled if the filesystem is readonly.\n"),
865                                 stderr);
866                         return 1;
867                 }
868
869                 error = ext2fs_read_bitmaps(fs);
870                 if (error) {
871                         fputs(_("Error while reading bitmaps\n"), stderr);
872                         return 1;
873                 }
874
875                 error = ext2fs_mmp_read(fs, sb->s_mmp_block, NULL);
876                 if (error) {
877                         struct mmp_struct *mmp_cmp = fs->mmp_cmp;
878
879                         if (error == EXT2_ET_MMP_MAGIC_INVALID)
880                                 printf(_("Magic number in MMP block does not "
881                                          "match. expected: %x, actual: %x\n"),
882                                          EXT4_MMP_MAGIC, mmp_cmp->mmp_magic);
883                         else
884                                 com_err(program_name, error,
885                                         _("while reading MMP block."));
886                         goto mmp_error;
887                 }
888
889                 /* We need to force out the group descriptors as well */
890                 fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
891                 ext2fs_block_alloc_stats(fs, sb->s_mmp_block, -1);
892 mmp_error:
893                 sb->s_mmp_block = 0;
894                 sb->s_mmp_update_interval = 0;
895         }
896
897         if (FEATURE_ON(E2P_FEATURE_COMPAT, EXT3_FEATURE_COMPAT_HAS_JOURNAL)) {
898                 /*
899                  * If adding a journal flag, let the create journal
900                  * code below handle setting the flag and creating the
901                  * journal.  We supply a default size if necessary.
902                  */
903                 if (!journal_size)
904                         journal_size = -1;
905                 sb->s_feature_compat &= ~EXT3_FEATURE_COMPAT_HAS_JOURNAL;
906         }
907
908         if (FEATURE_ON(E2P_FEATURE_COMPAT, EXT2_FEATURE_COMPAT_DIR_INDEX)) {
909                 if (!sb->s_def_hash_version)
910                         sb->s_def_hash_version = EXT2_HASH_HALF_MD4;
911                 if (uuid_is_null((unsigned char *) sb->s_hash_seed))
912                         uuid_generate((unsigned char *) sb->s_hash_seed);
913         }
914
915         if (FEATURE_OFF(E2P_FEATURE_INCOMPAT, EXT4_FEATURE_INCOMPAT_FLEX_BG)) {
916                 if (ext2fs_check_desc(fs)) {
917                         fputs(_("Clearing the flex_bg flag would "
918                                 "cause the the filesystem to be\n"
919                                 "inconsistent.\n"), stderr);
920                         return 1;
921                 }
922         }
923
924         if (FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
925                             EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
926                 if ((mount_flags & EXT2_MF_MOUNTED) &&
927                     !(mount_flags & EXT2_MF_READONLY)) {
928                         fputs(_("The huge_file feature may only be "
929                                 "cleared when the filesystem is\n"
930                                 "unmounted or mounted "
931                                 "read-only.\n"), stderr);
932                         return 1;
933                 }
934         }
935
936         if (FEATURE_ON(E2P_FEATURE_RO_INCOMPAT,
937                        EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) {
938                 if (check_fsck_needed(fs))
939                         exit(1);
940                 rewrite_checksums = 1;
941                 /* metadata_csum supersedes uninit_bg */
942                 fs->super->s_feature_ro_compat &=
943                         ~EXT4_FEATURE_RO_COMPAT_GDT_CSUM;
944
945                 /* if uninit_bg was previously off, rewrite group desc */
946                 if (!(old_features[E2P_FEATURE_RO_INCOMPAT] &
947                       EXT4_FEATURE_RO_COMPAT_GDT_CSUM))
948                         enable_uninit_bg(fs);
949
950                 /*
951                  * Since metadata_csum supersedes uninit_bg, pretend like
952                  * uninit_bg has been off all along.
953                  */
954                 old_features[E2P_FEATURE_RO_INCOMPAT] &=
955                         ~EXT4_FEATURE_RO_COMPAT_GDT_CSUM;
956         }
957
958         if (FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
959                         EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) {
960                 if (check_fsck_needed(fs))
961                         exit(1);
962                 rewrite_checksums = 1;
963                 /*
964                  * If we're turning off metadata_csum and not turning on
965                  * uninit_bg, rewrite group desc.
966                  */
967                 if (!(fs->super->s_feature_ro_compat &
968                       EXT4_FEATURE_RO_COMPAT_GDT_CSUM))
969                         disable_uninit_bg(fs,
970                                 EXT4_FEATURE_RO_COMPAT_METADATA_CSUM);
971                 else
972                         /*
973                          * metadata_csum previously provided uninit_bg, so if
974                          * we're also setting the uninit_bg feature bit,
975                          * pretend like it was previously enabled.  Checksums
976                          * will be rewritten with crc16 later.
977                          */
978                         old_features[E2P_FEATURE_RO_INCOMPAT] |=
979                                 EXT4_FEATURE_RO_COMPAT_GDT_CSUM;
980         }
981
982         if (FEATURE_ON(E2P_FEATURE_RO_INCOMPAT,
983                        EXT4_FEATURE_RO_COMPAT_GDT_CSUM)) {
984                 /* Do not enable uninit_bg when metadata_csum enabled */
985                 if (fs->super->s_feature_ro_compat &
986                     EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)
987                         fs->super->s_feature_ro_compat &=
988                                 ~EXT4_FEATURE_RO_COMPAT_GDT_CSUM;
989                 else
990                         enable_uninit_bg(fs);
991         }
992
993         if (FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
994                         EXT4_FEATURE_RO_COMPAT_GDT_CSUM))
995                 disable_uninit_bg(fs,
996                                 EXT4_FEATURE_RO_COMPAT_GDT_CSUM);
997
998         if (FEATURE_ON(E2P_FEATURE_RO_INCOMPAT,
999                                 EXT4_FEATURE_RO_COMPAT_QUOTA)) {
1000                 /*
1001                  * Set the Q_flag here and handle the quota options in the code
1002                  * below.
1003                  */
1004                 if (!Q_flag) {
1005                         Q_flag = 1;
1006                         /* Enable both user quota and group quota by default */
1007                         usrquota = QOPT_ENABLE;
1008                         grpquota = QOPT_ENABLE;
1009                 }
1010                 sb->s_feature_ro_compat &= ~EXT4_FEATURE_RO_COMPAT_QUOTA;
1011         }
1012
1013         if (FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
1014                                 EXT4_FEATURE_RO_COMPAT_QUOTA)) {
1015                 /*
1016                  * Set the Q_flag here and handle the quota options in the code
1017                  * below.
1018                  */
1019                 if (Q_flag)
1020                         fputs(_("\nWarning: '^quota' option overrides '-Q'"
1021                                 "arguments.\n"), stderr);
1022                 Q_flag = 1;
1023                 /* Disable both user quota and group quota by default */
1024                 usrquota = QOPT_DISABLE;
1025                 grpquota = QOPT_DISABLE;
1026         }
1027
1028         if (sb->s_rev_level == EXT2_GOOD_OLD_REV &&
1029             (sb->s_feature_compat || sb->s_feature_ro_compat ||
1030              sb->s_feature_incompat))
1031                 ext2fs_update_dynamic_rev(fs);
1032
1033         if (FEATURE_CHANGED(E2P_FEATURE_RO_INCOMPAT,
1034                             EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER) ||
1035             FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
1036                         EXT4_FEATURE_RO_COMPAT_HUGE_FILE) ||
1037             FEATURE_CHANGED(E2P_FEATURE_INCOMPAT,
1038                             EXT2_FEATURE_INCOMPAT_FILETYPE) ||
1039             FEATURE_CHANGED(E2P_FEATURE_COMPAT,
1040                             EXT2_FEATURE_COMPAT_RESIZE_INODE) ||
1041             FEATURE_OFF(E2P_FEATURE_RO_INCOMPAT,
1042                         EXT2_FEATURE_RO_COMPAT_LARGE_FILE))
1043                 request_fsck_afterwards(fs);
1044
1045         if ((old_features[E2P_FEATURE_COMPAT] != sb->s_feature_compat) ||
1046             (old_features[E2P_FEATURE_INCOMPAT] != sb->s_feature_incompat) ||
1047             (old_features[E2P_FEATURE_RO_INCOMPAT] != sb->s_feature_ro_compat))
1048                 ext2fs_mark_super_dirty(fs);
1049
1050         return 0;
1051 }
1052
1053 /*
1054  * Add a journal to the filesystem.
1055  */
1056 static int add_journal(ext2_filsys fs)
1057 {
1058         unsigned long journal_blocks;
1059         errcode_t       retval;
1060         ext2_filsys     jfs;
1061         io_manager      io_ptr;
1062
1063         if (fs->super->s_feature_compat &
1064             EXT3_FEATURE_COMPAT_HAS_JOURNAL) {
1065                 fputs(_("The filesystem already has a journal.\n"), stderr);
1066                 goto err;
1067         }
1068         if (journal_device) {
1069                 check_plausibility(journal_device);
1070                 check_mount(journal_device, 0, _("journal"));
1071 #ifdef CONFIG_TESTIO_DEBUG
1072                 if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_BLOCK")) {
1073                         io_ptr = test_io_manager;
1074                         test_io_backing_manager = unix_io_manager;
1075                 } else
1076 #endif
1077                         io_ptr = unix_io_manager;
1078                 retval = ext2fs_open(journal_device, EXT2_FLAG_RW|
1079                                      EXT2_FLAG_JOURNAL_DEV_OK, 0,
1080                                      fs->blocksize, io_ptr, &jfs);
1081                 if (retval) {
1082                         com_err(program_name, retval,
1083                                 _("\n\twhile trying to open journal on %s\n"),
1084                                 journal_device);
1085                         goto err;
1086                 }
1087                 printf(_("Creating journal on device %s: "),
1088                        journal_device);
1089                 fflush(stdout);
1090
1091                 retval = ext2fs_add_journal_device(fs, jfs);
1092                 ext2fs_close(jfs);
1093                 if (retval) {
1094                         com_err(program_name, retval,
1095                                 _("while adding filesystem to journal on %s"),
1096                                 journal_device);
1097                         goto err;
1098                 }
1099                 fputs(_("done\n"), stdout);
1100         } else if (journal_size) {
1101                 fputs(_("Creating journal inode: "), stdout);
1102                 fflush(stdout);
1103                 journal_blocks = figure_journal_size(journal_size, fs);
1104
1105                 retval = ext2fs_add_journal_inode(fs, journal_blocks,
1106                                                   journal_flags);
1107                 if (retval) {
1108                         fprintf(stderr, "\n");
1109                         com_err(program_name, retval,
1110                                 _("\n\twhile trying to create journal file"));
1111                         return retval;
1112                 } else
1113                         fputs(_("done\n"), stdout);
1114                 /*
1115                  * If the filesystem wasn't mounted, we need to force
1116                  * the block group descriptors out.
1117                  */
1118                 if ((mount_flags & EXT2_MF_MOUNTED) == 0)
1119                         fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
1120         }
1121         print_check_message(fs->super->s_max_mnt_count,
1122                             fs->super->s_checkinterval);
1123         return 0;
1124
1125 err:
1126         free(journal_device);
1127         return 1;
1128 }
1129
1130 static void handle_quota_options(ext2_filsys fs)
1131 {
1132         quota_ctx_t qctx;
1133         ext2_ino_t qf_ino;
1134
1135         if (!usrquota && !grpquota)
1136                 /* Nothing to do. */
1137                 return;
1138
1139         quota_init_context(&qctx, fs, -1);
1140
1141         if (usrquota == QOPT_ENABLE || grpquota == QOPT_ENABLE)
1142                 quota_compute_usage(qctx);
1143
1144         if (usrquota == QOPT_ENABLE && !fs->super->s_usr_quota_inum) {
1145                 if ((qf_ino = quota_file_exists(fs, USRQUOTA,
1146                                                 QFMT_VFS_V1)) > 0)
1147                         quota_update_limits(qctx, qf_ino, USRQUOTA);
1148                 quota_write_inode(qctx, USRQUOTA);
1149         } else if (usrquota == QOPT_DISABLE) {
1150                 quota_remove_inode(fs, USRQUOTA);
1151         }
1152
1153         if (grpquota == QOPT_ENABLE && !fs->super->s_grp_quota_inum) {
1154                 if ((qf_ino = quota_file_exists(fs, GRPQUOTA,
1155                                                 QFMT_VFS_V1)) > 0)
1156                         quota_update_limits(qctx, qf_ino, GRPQUOTA);
1157                 quota_write_inode(qctx, GRPQUOTA);
1158         } else if (grpquota == QOPT_DISABLE) {
1159                 quota_remove_inode(fs, GRPQUOTA);
1160         }
1161
1162         quota_release_context(&qctx);
1163
1164         if ((usrquota == QOPT_ENABLE) || (grpquota == QOPT_ENABLE)) {
1165                 fprintf(stderr, _("\nWarning: the quota feature is still "
1166                                   "under development\n"
1167                                   "See https://ext4.wiki.kernel.org/"
1168                                   "index.php/Quota for more information\n\n"));
1169                 fs->super->s_feature_ro_compat |= EXT4_FEATURE_RO_COMPAT_QUOTA;
1170                 ext2fs_mark_super_dirty(fs);
1171         } else if (!fs->super->s_usr_quota_inum &&
1172                    !fs->super->s_grp_quota_inum) {
1173                 fs->super->s_feature_ro_compat &= ~EXT4_FEATURE_RO_COMPAT_QUOTA;
1174                 ext2fs_mark_super_dirty(fs);
1175         }
1176
1177         return;
1178 }
1179
1180 static void parse_quota_opts(const char *opts)
1181 {
1182         char    *buf, *token, *next, *p;
1183         int     len;
1184
1185         len = strlen(opts);
1186         buf = malloc(len+1);
1187         if (!buf) {
1188                 fputs(_("Couldn't allocate memory to parse quota "
1189                         "options!\n"), stderr);
1190                 exit(1);
1191         }
1192         strcpy(buf, opts);
1193         for (token = buf; token && *token; token = next) {
1194                 p = strchr(token, ',');
1195                 next = 0;
1196                 if (p) {
1197                         *p = 0;
1198                         next = p+1;
1199                 }
1200
1201                 if (strcmp(token, "usrquota") == 0) {
1202                         usrquota = QOPT_ENABLE;
1203                 } else if (strcmp(token, "^usrquota") == 0) {
1204                         usrquota = QOPT_DISABLE;
1205                 } else if (strcmp(token, "grpquota") == 0) {
1206                         grpquota = QOPT_ENABLE;
1207                 } else if (strcmp(token, "^grpquota") == 0) {
1208                         grpquota = QOPT_DISABLE;
1209                 } else {
1210                         fputs(_("\nBad quota options specified.\n\n"
1211                                 "Following valid quota options are available "
1212                                 "(pass by separating with comma):\n"
1213                                 "\t[^]usrquota\n"
1214                                 "\t[^]grpquota\n"
1215                                 "\n\n"), stderr);
1216                         free(buf);
1217                         exit(1);
1218                 }
1219         }
1220         free(buf);
1221 }
1222
1223
1224
1225 static void parse_e2label_options(int argc, char ** argv)
1226 {
1227         if ((argc < 2) || (argc > 3)) {
1228                 fputs(_("Usage: e2label device [newlabel]\n"), stderr);
1229                 exit(1);
1230         }
1231         io_options = strchr(argv[1], '?');
1232         if (io_options)
1233                 *io_options++ = 0;
1234         device_name = blkid_get_devname(NULL, argv[1], NULL);
1235         if (!device_name) {
1236                 com_err("e2label", 0, _("Unable to resolve '%s'"),
1237                         argv[1]);
1238                 exit(1);
1239         }
1240         open_flag = EXT2_FLAG_JOURNAL_DEV_OK;
1241         if (argc == 3) {
1242                 open_flag |= EXT2_FLAG_RW;
1243                 L_flag = 1;
1244                 new_label = argv[2];
1245         } else
1246                 print_label++;
1247 }
1248
1249 static time_t parse_time(char *str)
1250 {
1251         struct  tm      ts;
1252
1253         if (strcmp(str, "now") == 0) {
1254                 return (time(0));
1255         }
1256         memset(&ts, 0, sizeof(ts));
1257 #ifdef HAVE_STRPTIME
1258         strptime(str, "%Y%m%d%H%M%S", &ts);
1259 #else
1260         sscanf(str, "%4d%2d%2d%2d%2d%2d", &ts.tm_year, &ts.tm_mon,
1261                &ts.tm_mday, &ts.tm_hour, &ts.tm_min, &ts.tm_sec);
1262         ts.tm_year -= 1900;
1263         ts.tm_mon -= 1;
1264         if (ts.tm_year < 0 || ts.tm_mon < 0 || ts.tm_mon > 11 ||
1265             ts.tm_mday < 0 || ts.tm_mday > 31 || ts.tm_hour > 23 ||
1266             ts.tm_min > 59 || ts.tm_sec > 61)
1267                 ts.tm_mday = 0;
1268 #endif
1269         if (ts.tm_mday == 0) {
1270                 com_err(program_name, 0,
1271                         _("Couldn't parse date/time specifier: %s"),
1272                         str);
1273                 usage();
1274         }
1275         ts.tm_isdst = -1;
1276         return (mktime(&ts));
1277 }
1278
1279 static void parse_tune2fs_options(int argc, char **argv)
1280 {
1281         int c;
1282         char *tmp;
1283         struct group *gr;
1284         struct passwd *pw;
1285
1286         open_flag = 0;
1287
1288         printf("tune2fs %s (%s)\n", E2FSPROGS_VERSION, E2FSPROGS_DATE);
1289         while ((c = getopt(argc, argv, "c:e:fg:i:jlm:o:r:s:u:C:E:I:J:L:M:O:Q:T:U:")) != EOF)
1290                 switch (c) {
1291                 case 'c':
1292                         max_mount_count = strtol(optarg, &tmp, 0);
1293                         if (*tmp || max_mount_count > 16000) {
1294                                 com_err(program_name, 0,
1295                                         _("bad mounts count - %s"),
1296                                         optarg);
1297                                 usage();
1298                         }
1299                         if (max_mount_count == 0)
1300                                 max_mount_count = -1;
1301                         c_flag = 1;
1302                         open_flag = EXT2_FLAG_RW;
1303                         break;
1304                 case 'C':
1305                         mount_count = strtoul(optarg, &tmp, 0);
1306                         if (*tmp || mount_count > 16000) {
1307                                 com_err(program_name, 0,
1308                                         _("bad mounts count - %s"),
1309                                         optarg);
1310                                 usage();
1311                         }
1312                         C_flag = 1;
1313                         open_flag = EXT2_FLAG_RW;
1314                         break;
1315                 case 'e':
1316                         if (strcmp(optarg, "continue") == 0)
1317                                 errors = EXT2_ERRORS_CONTINUE;
1318                         else if (strcmp(optarg, "remount-ro") == 0)
1319                                 errors = EXT2_ERRORS_RO;
1320                         else if (strcmp(optarg, "panic") == 0)
1321                                 errors = EXT2_ERRORS_PANIC;
1322                         else {
1323                                 com_err(program_name, 0,
1324                                         _("bad error behavior - %s"),
1325                                         optarg);
1326                                 usage();
1327                         }
1328                         e_flag = 1;
1329                         open_flag = EXT2_FLAG_RW;
1330                         break;
1331                 case 'E':
1332                         extended_cmd = optarg;
1333                         open_flag |= EXT2_FLAG_RW;
1334                         break;
1335                 case 'f': /* Force */
1336                         f_flag = 1;
1337                         break;
1338                 case 'g':
1339                         resgid = strtoul(optarg, &tmp, 0);
1340                         if (*tmp) {
1341                                 gr = getgrnam(optarg);
1342                                 if (gr == NULL)
1343                                         tmp = optarg;
1344                                 else {
1345                                         resgid = gr->gr_gid;
1346                                         *tmp = 0;
1347                                 }
1348                         }
1349                         if (*tmp) {
1350                                 com_err(program_name, 0,
1351                                         _("bad gid/group name - %s"),
1352                                         optarg);
1353                                 usage();
1354                         }
1355                         g_flag = 1;
1356                         open_flag = EXT2_FLAG_RW;
1357                         break;
1358                 case 'i':
1359                         interval = strtoul(optarg, &tmp, 0);
1360                         switch (*tmp) {
1361                         case 's':
1362                                 tmp++;
1363                                 break;
1364                         case '\0':
1365                         case 'd':
1366                         case 'D': /* days */
1367                                 interval *= 86400;
1368                                 if (*tmp != '\0')
1369                                         tmp++;
1370                                 break;
1371                         case 'm':
1372                         case 'M': /* months! */
1373                                 interval *= 86400 * 30;
1374                                 tmp++;
1375                                 break;
1376                         case 'w':
1377                         case 'W': /* weeks */
1378                                 interval *= 86400 * 7;
1379                                 tmp++;
1380                                 break;
1381                         }
1382                         if (*tmp) {
1383                                 com_err(program_name, 0,
1384                                         _("bad interval - %s"), optarg);
1385                                 usage();
1386                         }
1387                         i_flag = 1;
1388                         open_flag = EXT2_FLAG_RW;
1389                         break;
1390                 case 'j':
1391                         if (!journal_size)
1392                                 journal_size = -1;
1393                         open_flag = EXT2_FLAG_RW;
1394                         break;
1395                 case 'J':
1396                         parse_journal_opts(optarg);
1397                         open_flag = EXT2_FLAG_RW;
1398                         break;
1399                 case 'l':
1400                         l_flag = 1;
1401                         break;
1402                 case 'L':
1403                         new_label = optarg;
1404                         L_flag = 1;
1405                         open_flag |= EXT2_FLAG_RW |
1406                                 EXT2_FLAG_JOURNAL_DEV_OK;
1407                         break;
1408                 case 'm':
1409                         reserved_ratio = strtod(optarg, &tmp);
1410                         if (*tmp || reserved_ratio > 50 ||
1411                             reserved_ratio < 0) {
1412                                 com_err(program_name, 0,
1413                                         _("bad reserved block ratio - %s"),
1414                                         optarg);
1415                                 usage();
1416                         }
1417                         m_flag = 1;
1418                         open_flag = EXT2_FLAG_RW;
1419                         break;
1420                 case 'M':
1421                         new_last_mounted = optarg;
1422                         M_flag = 1;
1423                         open_flag = EXT2_FLAG_RW;
1424                         break;
1425                 case 'o':
1426                         if (mntopts_cmd) {
1427                                 com_err(program_name, 0,
1428                                         _("-o may only be specified once"));
1429                                 usage();
1430                         }
1431                         mntopts_cmd = optarg;
1432                         open_flag = EXT2_FLAG_RW;
1433                         break;
1434                 case 'O':
1435                         if (features_cmd) {
1436                                 com_err(program_name, 0,
1437                                         _("-O may only be specified once"));
1438                                 usage();
1439                         }
1440                         features_cmd = optarg;
1441                         open_flag = EXT2_FLAG_RW;
1442                         break;
1443                 case 'Q':
1444                         Q_flag = 1;
1445                         parse_quota_opts(optarg);
1446                         open_flag = EXT2_FLAG_RW;
1447                         break;
1448                 case 'r':
1449                         reserved_blocks = strtoul(optarg, &tmp, 0);
1450                         if (*tmp) {
1451                                 com_err(program_name, 0,
1452                                         _("bad reserved blocks count - %s"),
1453                                         optarg);
1454                                 usage();
1455                         }
1456                         r_flag = 1;
1457                         open_flag = EXT2_FLAG_RW;
1458                         break;
1459                 case 's': /* Deprecated */
1460                         s_flag = atoi(optarg);
1461                         open_flag = EXT2_FLAG_RW;
1462                         break;
1463                 case 'T':
1464                         T_flag = 1;
1465                         last_check_time = parse_time(optarg);
1466                         open_flag = EXT2_FLAG_RW;
1467                         break;
1468                 case 'u':
1469                                 resuid = strtoul(optarg, &tmp, 0);
1470                                 if (*tmp) {
1471                                         pw = getpwnam(optarg);
1472                                         if (pw == NULL)
1473                                                 tmp = optarg;
1474                                         else {
1475                                                 resuid = pw->pw_uid;
1476                                                 *tmp = 0;
1477                                         }
1478                                 }
1479                                 if (*tmp) {
1480                                         com_err(program_name, 0,
1481                                                 _("bad uid/user name - %s"),
1482                                                 optarg);
1483                                         usage();
1484                                 }
1485                                 u_flag = 1;
1486                                 open_flag = EXT2_FLAG_RW;
1487                                 break;
1488                 case 'U':
1489                         new_UUID = optarg;
1490                         U_flag = 1;
1491                         open_flag = EXT2_FLAG_RW |
1492                                 EXT2_FLAG_JOURNAL_DEV_OK;
1493                         break;
1494                 case 'I':
1495                         new_inode_size = strtoul(optarg, &tmp, 0);
1496                         if (*tmp) {
1497                                 com_err(program_name, 0,
1498                                         _("bad inode size - %s"),
1499                                         optarg);
1500                                 usage();
1501                         }
1502                         if (!((new_inode_size &
1503                                (new_inode_size - 1)) == 0)) {
1504                                 com_err(program_name, 0,
1505                                         _("Inode size must be a "
1506                                           "power of two- %s"),
1507                                         optarg);
1508                                 usage();
1509                         }
1510                         open_flag = EXT2_FLAG_RW;
1511                         I_flag = 1;
1512                         break;
1513                 default:
1514                         usage();
1515                 }
1516         if (optind < argc - 1 || optind == argc)
1517                 usage();
1518         if (!open_flag && !l_flag)
1519                 usage();
1520         io_options = strchr(argv[optind], '?');
1521         if (io_options)
1522                 *io_options++ = 0;
1523         device_name = blkid_get_devname(NULL, argv[optind], NULL);
1524         if (!device_name) {
1525                 com_err(program_name, 0, _("Unable to resolve '%s'"),
1526                         argv[optind]);
1527                 exit(1);
1528         }
1529 }
1530
1531 #ifdef CONFIG_BUILD_FINDFS
1532 void do_findfs(int argc, char **argv)
1533 {
1534         char    *dev;
1535
1536         if ((argc != 2) ||
1537             (strncmp(argv[1], "LABEL=", 6) && strncmp(argv[1], "UUID=", 5))) {
1538                 fprintf(stderr, "Usage: findfs LABEL=<label>|UUID=<uuid>\n");
1539                 exit(2);
1540         }
1541         dev = blkid_get_devname(NULL, argv[1], NULL);
1542         if (!dev) {
1543                 com_err("findfs", 0, _("Unable to resolve '%s'"),
1544                         argv[1]);
1545                 exit(1);
1546         }
1547         puts(dev);
1548         exit(0);
1549 }
1550 #endif
1551
1552 static int parse_extended_opts(ext2_filsys fs, const char *opts)
1553 {
1554         char    *buf, *token, *next, *p, *arg;
1555         int     len, hash_alg;
1556         int     r_usage = 0;
1557
1558         len = strlen(opts);
1559         buf = malloc(len+1);
1560         if (!buf) {
1561                 fprintf(stderr,
1562                         _("Couldn't allocate memory to parse options!\n"));
1563                 return 1;
1564         }
1565         strcpy(buf, opts);
1566         for (token = buf; token && *token; token = next) {
1567                 p = strchr(token, ',');
1568                 next = 0;
1569                 if (p) {
1570                         *p = 0;
1571                         next = p+1;
1572                 }
1573                 arg = strchr(token, '=');
1574                 if (arg) {
1575                         *arg = 0;
1576                         arg++;
1577                 }
1578                 if (strcmp(token, "clear-mmp") == 0 ||
1579                     strcmp(token, "clear_mmp") == 0) {
1580                         clear_mmp = 1;
1581                 } else if (strcmp(token, "mmp_update_interval") == 0) {
1582                         unsigned long intv;
1583                         if (!arg) {
1584                                 r_usage++;
1585                                 continue;
1586                         }
1587                         intv = strtoul(arg, &p, 0);
1588                         if (*p) {
1589                                 fprintf(stderr,
1590                                         _("Invalid mmp_update_interval: %s\n"),
1591                                         arg);
1592                                 r_usage++;
1593                                 continue;
1594                         }
1595                         if (intv == 0) {
1596                                 intv = EXT4_MMP_UPDATE_INTERVAL;
1597                         } else if (intv > EXT4_MMP_MAX_UPDATE_INTERVAL) {
1598                                 fprintf(stderr,
1599                                         _("mmp_update_interval too big: %lu\n"),
1600                                         intv);
1601                                 r_usage++;
1602                                 continue;
1603                         }
1604                         printf(P_("Setting multiple mount protection update "
1605                                   "interval to %lu second\n",
1606                                   "Setting multiple mount protection update "
1607                                   "interval to %lu seconds\n", intv),
1608                                intv);
1609                         fs->super->s_mmp_update_interval = intv;
1610                         ext2fs_mark_super_dirty(fs);
1611                 } else if (!strcmp(token, "test_fs")) {
1612                         fs->super->s_flags |= EXT2_FLAGS_TEST_FILESYS;
1613                         printf("Setting test filesystem flag\n");
1614                         ext2fs_mark_super_dirty(fs);
1615                 } else if (!strcmp(token, "^test_fs")) {
1616                         fs->super->s_flags &= ~EXT2_FLAGS_TEST_FILESYS;
1617                         printf("Clearing test filesystem flag\n");
1618                         ext2fs_mark_super_dirty(fs);
1619                 } else if (strcmp(token, "stride") == 0) {
1620                         if (!arg) {
1621                                 r_usage++;
1622                                 continue;
1623                         }
1624                         stride = strtoul(arg, &p, 0);
1625                         if (*p) {
1626                                 fprintf(stderr,
1627                                         _("Invalid RAID stride: %s\n"),
1628                                         arg);
1629                                 r_usage++;
1630                                 continue;
1631                         }
1632                         stride_set = 1;
1633                 } else if (strcmp(token, "stripe-width") == 0 ||
1634                            strcmp(token, "stripe_width") == 0) {
1635                         if (!arg) {
1636                                 r_usage++;
1637                                 continue;
1638                         }
1639                         stripe_width = strtoul(arg, &p, 0);
1640                         if (*p) {
1641                                 fprintf(stderr,
1642                                         _("Invalid RAID stripe-width: %s\n"),
1643                                         arg);
1644                                 r_usage++;
1645                                 continue;
1646                         }
1647                         stripe_width_set = 1;
1648                 } else if (strcmp(token, "hash_alg") == 0 ||
1649                            strcmp(token, "hash-alg") == 0) {
1650                         if (!arg) {
1651                                 r_usage++;
1652                                 continue;
1653                         }
1654                         hash_alg = e2p_string2hash(arg);
1655                         if (hash_alg < 0) {
1656                                 fprintf(stderr,
1657                                         _("Invalid hash algorithm: %s\n"),
1658                                         arg);
1659                                 r_usage++;
1660                                 continue;
1661                         }
1662                         fs->super->s_def_hash_version = hash_alg;
1663                         printf(_("Setting default hash algorithm "
1664                                  "to %s (%d)\n"),
1665                                arg, hash_alg);
1666                         ext2fs_mark_super_dirty(fs);
1667                 } else if (!strcmp(token, "mount_opts")) {
1668                         if (!arg) {
1669                                 r_usage++;
1670                                 continue;
1671                         }
1672                         if (strlen(arg) >= sizeof(fs->super->s_mount_opts)) {
1673                                 fprintf(stderr,
1674                                         "Extended mount options too long\n");
1675                                 continue;
1676                         }
1677                         ext_mount_opts = strdup(arg);
1678                 } else
1679                         r_usage++;
1680         }
1681         if (r_usage) {
1682                 fprintf(stderr, _("\nBad options specified.\n\n"
1683                         "Extended options are separated by commas, "
1684                         "and may take an argument which\n"
1685                         "\tis set off by an equals ('=') sign.\n\n"
1686                         "Valid extended options are:\n"
1687                         "\tclear_mmp\n"
1688                         "\thash_alg=<hash algorithm>\n"
1689                         "\tmount_opts=<extended default mount options>\n"
1690                         "\tstride=<RAID per-disk chunk size in blocks>\n"
1691                         "\tstripe_width=<RAID stride*data disks in blocks>\n"
1692                         "\ttest_fs\n"
1693                         "\t^test_fs\n"));
1694                 free(buf);
1695                 return 1;
1696         }
1697         free(buf);
1698
1699         return 0;
1700 }
1701
1702 /*
1703  * Fill in the block bitmap bmap with the information regarding the
1704  * blocks to be moved
1705  */
1706 static int get_move_bitmaps(ext2_filsys fs, int new_ino_blks_per_grp,
1707                             ext2fs_block_bitmap bmap)
1708 {
1709         dgrp_t i;
1710         int retval;
1711         ext2_badblocks_list bb_list = 0;
1712         blk64_t j, needed_blocks = 0;
1713         blk64_t start_blk, end_blk;
1714
1715         retval = ext2fs_read_bb_inode(fs, &bb_list);
1716         if (retval)
1717                 return retval;
1718
1719         for (i = 0; i < fs->group_desc_count; i++) {
1720                 start_blk = ext2fs_inode_table_loc(fs, i) +
1721                                         fs->inode_blocks_per_group;
1722
1723                 end_blk = ext2fs_inode_table_loc(fs, i) +
1724                                         new_ino_blks_per_grp;
1725
1726                 for (j = start_blk; j < end_blk; j++) {
1727                         if (ext2fs_test_block_bitmap2(fs->block_map, j)) {
1728                                 /*
1729                                  * IF the block is a bad block we fail
1730                                  */
1731                                 if (ext2fs_badblocks_list_test(bb_list, j)) {
1732                                         ext2fs_badblocks_list_free(bb_list);
1733                                         return ENOSPC;
1734                                 }
1735
1736                                 ext2fs_mark_block_bitmap2(bmap, j);
1737                         } else {
1738                                 /*
1739                                  * We are going to use this block for
1740                                  * inode table. So mark them used.
1741                                  */
1742                                 ext2fs_mark_block_bitmap2(fs->block_map, j);
1743                         }
1744                 }
1745                 needed_blocks += end_blk - start_blk;
1746         }
1747
1748         ext2fs_badblocks_list_free(bb_list);
1749         if (needed_blocks > ext2fs_free_blocks_count(fs->super))
1750                 return ENOSPC;
1751
1752         return 0;
1753 }
1754
1755 static int ext2fs_is_meta_block(ext2_filsys fs, blk_t blk)
1756 {
1757         dgrp_t group;
1758         group = ext2fs_group_of_blk(fs, blk);
1759         if (ext2fs_block_bitmap_loc(fs, group) == blk)
1760                 return 1;
1761         if (ext2fs_inode_bitmap_loc(fs, group) == blk)
1762                 return 1;
1763         return 0;
1764 }
1765
1766 static int ext2fs_is_block_in_group(ext2_filsys fs, dgrp_t group, blk_t blk)
1767 {
1768         blk_t start_blk, end_blk;
1769         start_blk = fs->super->s_first_data_block +
1770                         EXT2_BLOCKS_PER_GROUP(fs->super) * group;
1771         /*
1772          * We cannot get new block beyond end_blk for for the last block group
1773          * so we can check with EXT2_BLOCKS_PER_GROUP even for last block group
1774          */
1775         end_blk   = start_blk + EXT2_BLOCKS_PER_GROUP(fs->super);
1776         if (blk >= start_blk && blk <= end_blk)
1777                 return 1;
1778         return 0;
1779 }
1780
1781 static int move_block(ext2_filsys fs, ext2fs_block_bitmap bmap)
1782 {
1783
1784         char *buf;
1785         dgrp_t group = 0;
1786         errcode_t retval;
1787         int meta_data = 0;
1788         blk64_t blk, new_blk, goal;
1789         struct blk_move *bmv;
1790
1791         retval = ext2fs_get_mem(fs->blocksize, &buf);
1792         if (retval)
1793                 return retval;
1794
1795         for (new_blk = blk = fs->super->s_first_data_block;
1796              blk < ext2fs_blocks_count(fs->super); blk++) {
1797                 if (!ext2fs_test_block_bitmap2(bmap, blk))
1798                         continue;
1799
1800                 if (ext2fs_is_meta_block(fs, blk)) {
1801                         /*
1802                          * If the block is mapping a fs meta data block
1803                          * like group desc/block bitmap/inode bitmap. We
1804                          * should find a block in the same group and fix
1805                          * the respective fs metadata pointers. Otherwise
1806                          * fail
1807                          */
1808                         group = ext2fs_group_of_blk(fs, blk);
1809                         goal = ext2fs_group_first_block2(fs, group);
1810                         meta_data = 1;
1811
1812                 } else {
1813                         goal = new_blk;
1814                 }
1815                 retval = ext2fs_new_block2(fs, goal, NULL, &new_blk);
1816                 if (retval)
1817                         goto err_out;
1818
1819                 /* new fs meta data block should be in the same group */
1820                 if (meta_data && !ext2fs_is_block_in_group(fs, group, new_blk)) {
1821                         retval = ENOSPC;
1822                         goto err_out;
1823                 }
1824
1825                 /* Mark this block as allocated */
1826                 ext2fs_mark_block_bitmap2(fs->block_map, new_blk);
1827
1828                 /* Add it to block move list */
1829                 retval = ext2fs_get_mem(sizeof(struct blk_move), &bmv);
1830                 if (retval)
1831                         goto err_out;
1832
1833                 bmv->old_loc = blk;
1834                 bmv->new_loc = new_blk;
1835
1836                 list_add(&(bmv->list), &blk_move_list);
1837
1838                 retval = io_channel_read_blk64(fs->io, blk, 1, buf);
1839                 if (retval)
1840                         goto err_out;
1841
1842                 retval = io_channel_write_blk64(fs->io, new_blk, 1, buf);
1843                 if (retval)
1844                         goto err_out;
1845         }
1846
1847 err_out:
1848         ext2fs_free_mem(&buf);
1849         return retval;
1850 }
1851
1852 static blk64_t translate_block(blk64_t blk)
1853 {
1854         struct list_head *entry;
1855         struct blk_move *bmv;
1856
1857         list_for_each(entry, &blk_move_list) {
1858                 bmv = list_entry(entry, struct blk_move, list);
1859                 if (bmv->old_loc == blk)
1860                         return bmv->new_loc;
1861         }
1862
1863         return 0;
1864 }
1865
1866 static int process_block(ext2_filsys fs EXT2FS_ATTR((unused)),
1867                          blk64_t *block_nr,
1868                          e2_blkcnt_t blockcnt EXT2FS_ATTR((unused)),
1869                          blk64_t ref_block EXT2FS_ATTR((unused)),
1870                          int ref_offset EXT2FS_ATTR((unused)),
1871                          void *priv_data)
1872 {
1873         int ret = 0;
1874         blk64_t new_blk;
1875         ext2fs_block_bitmap bmap = (ext2fs_block_bitmap) priv_data;
1876
1877         if (!ext2fs_test_block_bitmap2(bmap, *block_nr))
1878                 return 0;
1879         new_blk = translate_block(*block_nr);
1880         if (new_blk) {
1881                 *block_nr = new_blk;
1882                 /*
1883                  * This will force the ext2fs_write_inode in the iterator
1884                  */
1885                 ret |= BLOCK_CHANGED;
1886         }
1887
1888         return ret;
1889 }
1890
1891 static int inode_scan_and_fix(ext2_filsys fs, ext2fs_block_bitmap bmap)
1892 {
1893         errcode_t retval = 0;
1894         ext2_ino_t ino;
1895         blk64_t blk;
1896         char *block_buf = 0;
1897         struct ext2_inode inode;
1898         ext2_inode_scan scan = NULL;
1899
1900         retval = ext2fs_get_mem(fs->blocksize * 3, &block_buf);
1901         if (retval)
1902                 return retval;
1903
1904         retval = ext2fs_open_inode_scan(fs, 0, &scan);
1905         if (retval)
1906                 goto err_out;
1907
1908         while (1) {
1909                 retval = ext2fs_get_next_inode(scan, &ino, &inode);
1910                 if (retval)
1911                         goto err_out;
1912
1913                 if (!ino)
1914                         break;
1915
1916                 if (inode.i_links_count == 0)
1917                         continue; /* inode not in use */
1918
1919                 /* FIXME!!
1920                  * If we end up modifying the journal inode
1921                  * the sb->s_jnl_blocks will differ. But a
1922                  * subsequent e2fsck fixes that.
1923                  * Do we need to fix this ??
1924                  */
1925
1926                 if (ext2fs_file_acl_block(fs, &inode) &&
1927                     ext2fs_test_block_bitmap2(bmap,
1928                                         ext2fs_file_acl_block(fs, &inode))) {
1929                         blk = translate_block(ext2fs_file_acl_block(fs,
1930                                                                     &inode));
1931                         if (!blk)
1932                                 continue;
1933
1934                         ext2fs_file_acl_block_set(fs, &inode, blk);
1935
1936                         /*
1937                          * Write the inode to disk so that inode table
1938                          * resizing can work
1939                          */
1940                         retval = ext2fs_write_inode(fs, ino, &inode);
1941                         if (retval)
1942                                 goto err_out;
1943                 }
1944
1945                 if (!ext2fs_inode_has_valid_blocks2(fs, &inode))
1946                         continue;
1947
1948                 retval = ext2fs_block_iterate3(fs, ino, 0, block_buf,
1949                                                process_block, bmap);
1950                 if (retval)
1951                         goto err_out;
1952
1953         }
1954
1955 err_out:
1956         ext2fs_free_mem(&block_buf);
1957
1958         return retval;
1959 }
1960
1961 /*
1962  * We need to scan for inode and block bitmaps that may need to be
1963  * moved.  This can take place if the filesystem was formatted for
1964  * RAID arrays using the mke2fs's extended option "stride".
1965  */
1966 static int group_desc_scan_and_fix(ext2_filsys fs, ext2fs_block_bitmap bmap)
1967 {
1968         dgrp_t i;
1969         blk_t blk, new_blk;
1970
1971         for (i = 0; i < fs->group_desc_count; i++) {
1972                 blk = ext2fs_block_bitmap_loc(fs, i);
1973                 if (ext2fs_test_block_bitmap2(bmap, blk)) {
1974                         new_blk = translate_block(blk);
1975                         if (!new_blk)
1976                                 continue;
1977                         ext2fs_block_bitmap_loc_set(fs, i, new_blk);
1978                 }
1979
1980                 blk = ext2fs_inode_bitmap_loc(fs, i);
1981                 if (ext2fs_test_block_bitmap2(bmap, blk)) {
1982                         new_blk = translate_block(blk);
1983                         if (!new_blk)
1984                                 continue;
1985                         ext2fs_inode_bitmap_loc_set(fs, i, new_blk);
1986                 }
1987         }
1988         return 0;
1989 }
1990
1991 static int expand_inode_table(ext2_filsys fs, unsigned long new_ino_size)
1992 {
1993         dgrp_t i;
1994         blk64_t blk;
1995         errcode_t retval;
1996         int new_ino_blks_per_grp;
1997         unsigned int j;
1998         char *old_itable = NULL, *new_itable = NULL;
1999         char *tmp_old_itable = NULL, *tmp_new_itable = NULL;
2000         unsigned long old_ino_size;
2001         int old_itable_size, new_itable_size;
2002
2003         old_itable_size = fs->inode_blocks_per_group * fs->blocksize;
2004         old_ino_size = EXT2_INODE_SIZE(fs->super);
2005
2006         new_ino_blks_per_grp = ext2fs_div_ceil(
2007                                         EXT2_INODES_PER_GROUP(fs->super) *
2008                                         new_ino_size,
2009                                         fs->blocksize);
2010
2011         new_itable_size = new_ino_blks_per_grp * fs->blocksize;
2012
2013         retval = ext2fs_get_mem(old_itable_size, &old_itable);
2014         if (retval)
2015                 return retval;
2016
2017         retval = ext2fs_get_mem(new_itable_size, &new_itable);
2018         if (retval)
2019                 goto err_out;
2020
2021         tmp_old_itable = old_itable;
2022         tmp_new_itable = new_itable;
2023
2024         for (i = 0; i < fs->group_desc_count; i++) {
2025                 blk = ext2fs_inode_table_loc(fs, i);
2026                 retval = io_channel_read_blk64(fs->io, blk,
2027                                 fs->inode_blocks_per_group, old_itable);
2028                 if (retval)
2029                         goto err_out;
2030
2031                 for (j = 0; j < EXT2_INODES_PER_GROUP(fs->super); j++) {
2032                         memcpy(new_itable, old_itable, old_ino_size);
2033
2034                         memset(new_itable+old_ino_size, 0,
2035                                         new_ino_size - old_ino_size);
2036
2037                         new_itable += new_ino_size;
2038                         old_itable += old_ino_size;
2039                 }
2040
2041                 /* reset the pointer */
2042                 old_itable = tmp_old_itable;
2043                 new_itable = tmp_new_itable;
2044
2045                 retval = io_channel_write_blk64(fs->io, blk,
2046                                         new_ino_blks_per_grp, new_itable);
2047                 if (retval)
2048                         goto err_out;
2049         }
2050
2051         /* Update the meta data */
2052         fs->inode_blocks_per_group = new_ino_blks_per_grp;
2053         fs->super->s_inode_size = new_ino_size;
2054
2055 err_out:
2056         if (old_itable)
2057                 ext2fs_free_mem(&old_itable);
2058
2059         if (new_itable)
2060                 ext2fs_free_mem(&new_itable);
2061
2062         return retval;
2063 }
2064
2065 static errcode_t ext2fs_calculate_summary_stats(ext2_filsys fs)
2066 {
2067         blk64_t         blk;
2068         ext2_ino_t      ino;
2069         unsigned int    group = 0;
2070         unsigned int    count = 0;
2071         int             total_free = 0;
2072         int             group_free = 0;
2073
2074         /*
2075          * First calculate the block statistics
2076          */
2077         for (blk = fs->super->s_first_data_block;
2078              blk < ext2fs_blocks_count(fs->super); blk++) {
2079                 if (!ext2fs_fast_test_block_bitmap2(fs->block_map, blk)) {
2080                         group_free++;
2081                         total_free++;
2082                 }
2083                 count++;
2084                 if ((count == fs->super->s_blocks_per_group) ||
2085                     (blk == ext2fs_blocks_count(fs->super)-1)) {
2086                         ext2fs_bg_free_blocks_count_set(fs, group++,
2087                                                         group_free);
2088                         count = 0;
2089                         group_free = 0;
2090                 }
2091         }
2092         total_free = EXT2FS_C2B(fs, total_free);
2093         ext2fs_free_blocks_count_set(fs->super, total_free);
2094
2095         /*
2096          * Next, calculate the inode statistics
2097          */
2098         group_free = 0;
2099         total_free = 0;
2100         count = 0;
2101         group = 0;
2102
2103         /* Protect loop from wrap-around if s_inodes_count maxed */
2104         for (ino = 1; ino <= fs->super->s_inodes_count && ino > 0; ino++) {
2105                 if (!ext2fs_fast_test_inode_bitmap2(fs->inode_map, ino)) {
2106                         group_free++;
2107                         total_free++;
2108                 }
2109                 count++;
2110                 if ((count == fs->super->s_inodes_per_group) ||
2111                     (ino == fs->super->s_inodes_count)) {
2112                         ext2fs_bg_free_inodes_count_set(fs, group++,
2113                                                         group_free);
2114                         count = 0;
2115                         group_free = 0;
2116                 }
2117         }
2118         fs->super->s_free_inodes_count = total_free;
2119         ext2fs_mark_super_dirty(fs);
2120         return 0;
2121 }
2122
2123 #define list_for_each_safe(pos, pnext, head) \
2124         for (pos = (head)->next, pnext = pos->next; pos != (head); \
2125              pos = pnext, pnext = pos->next)
2126
2127 static void free_blk_move_list(void)
2128 {
2129         struct list_head *entry, *tmp;
2130         struct blk_move *bmv;
2131
2132         list_for_each_safe(entry, tmp, &blk_move_list) {
2133                 bmv = list_entry(entry, struct blk_move, list);
2134                 list_del(entry);
2135                 ext2fs_free_mem(&bmv);
2136         }
2137         return;
2138 }
2139
2140 static int resize_inode(ext2_filsys fs, unsigned long new_size)
2141 {
2142         errcode_t retval;
2143         int new_ino_blks_per_grp;
2144         ext2fs_block_bitmap bmap;
2145
2146         retval = ext2fs_read_inode_bitmap(fs);
2147         if (retval) {
2148                 fputs(_("Failed to read inode bitmap\n"), stderr);
2149                 return retval;
2150         }
2151         retval = ext2fs_read_block_bitmap(fs);
2152         if (retval) {
2153                 fputs(_("Failed to read block bitmap\n"), stderr);
2154                 return retval;
2155         }
2156         INIT_LIST_HEAD(&blk_move_list);
2157
2158
2159         new_ino_blks_per_grp = ext2fs_div_ceil(
2160                                         EXT2_INODES_PER_GROUP(fs->super)*
2161                                         new_size,
2162                                         fs->blocksize);
2163
2164         /* We may change the file system.
2165          * Mark the file system as invalid so that
2166          * the user is prompted to run fsck.
2167          */
2168         fs->super->s_state &= ~EXT2_VALID_FS;
2169
2170         retval = ext2fs_allocate_block_bitmap(fs, _("blocks to be moved"),
2171                                                 &bmap);
2172         if (retval) {
2173                 fputs(_("Failed to allocate block bitmap when "
2174                                 "increasing inode size\n"), stderr);
2175                 return retval;
2176         }
2177         retval = get_move_bitmaps(fs, new_ino_blks_per_grp, bmap);
2178         if (retval) {
2179                 fputs(_("Not enough space to increase inode size \n"), stderr);
2180                 goto err_out;
2181         }
2182         retval = move_block(fs, bmap);
2183         if (retval) {
2184                 fputs(_("Failed to relocate blocks during inode resize \n"),
2185                       stderr);
2186                 goto err_out;
2187         }
2188         retval = inode_scan_and_fix(fs, bmap);
2189         if (retval)
2190                 goto err_out_undo;
2191
2192         retval = group_desc_scan_and_fix(fs, bmap);
2193         if (retval)
2194                 goto err_out_undo;
2195
2196         retval = expand_inode_table(fs, new_size);
2197         if (retval)
2198                 goto err_out_undo;
2199
2200         ext2fs_calculate_summary_stats(fs);
2201
2202         fs->super->s_state |= EXT2_VALID_FS;
2203         /* mark super block and block bitmap as dirty */
2204         ext2fs_mark_super_dirty(fs);
2205         ext2fs_mark_bb_dirty(fs);
2206
2207 err_out:
2208         free_blk_move_list();
2209         ext2fs_free_block_bitmap(bmap);
2210
2211         return retval;
2212
2213 err_out_undo:
2214         free_blk_move_list();
2215         ext2fs_free_block_bitmap(bmap);
2216         fputs(_("Error in resizing the inode size.\n"
2217                         "Run e2undo to undo the "
2218                         "file system changes. \n"), stderr);
2219
2220         return retval;
2221 }
2222
2223 static int tune2fs_setup_tdb(const char *name, io_manager *io_ptr)
2224 {
2225         errcode_t retval = 0;
2226         const char *tdb_dir;
2227         char *tdb_file;
2228         char *dev_name, *tmp_name;
2229
2230 #if 0 /* FIXME!! */
2231         /*
2232          * Configuration via a conf file would be
2233          * nice
2234          */
2235         profile_get_string(profile, "scratch_files",
2236                                         "directory", 0, 0,
2237                                         &tdb_dir);
2238 #endif
2239         tmp_name = strdup(name);
2240         if (!tmp_name) {
2241         alloc_fn_fail:
2242                 com_err(program_name, ENOMEM, 
2243                         _("Couldn't allocate memory for tdb filename\n"));
2244                 return ENOMEM;
2245         }
2246         dev_name = basename(tmp_name);
2247
2248         tdb_dir = getenv("E2FSPROGS_UNDO_DIR");
2249         if (!tdb_dir)
2250                 tdb_dir = "/var/lib/e2fsprogs";
2251
2252         if (!strcmp(tdb_dir, "none") || (tdb_dir[0] == 0) ||
2253             access(tdb_dir, W_OK))
2254                 return 0;
2255
2256         tdb_file = malloc(strlen(tdb_dir) + 9 + strlen(dev_name) + 7 + 1);
2257         if (!tdb_file)
2258                 goto alloc_fn_fail;
2259         sprintf(tdb_file, "%s/tune2fs-%s.e2undo", tdb_dir, dev_name);
2260
2261         if (!access(tdb_file, F_OK)) {
2262                 if (unlink(tdb_file) < 0) {
2263                         retval = errno;
2264                         com_err(program_name, retval,
2265                                 _("while trying to delete %s"),
2266                                 tdb_file);
2267                         free(tdb_file);
2268                         return retval;
2269                 }
2270         }
2271
2272         set_undo_io_backing_manager(*io_ptr);
2273         *io_ptr = undo_io_manager;
2274         set_undo_io_backup_file(tdb_file);
2275         printf(_("To undo the tune2fs operation please run "
2276                  "the command\n    e2undo %s %s\n\n"),
2277                  tdb_file, name);
2278         free(tdb_file);
2279         free(tmp_name);
2280         return retval;
2281 }
2282
2283 int main(int argc, char **argv)
2284 {
2285         errcode_t retval;
2286         ext2_filsys fs;
2287         struct ext2_super_block *sb;
2288         io_manager io_ptr, io_ptr_orig = NULL;
2289         int rc = 0;
2290
2291 #ifdef ENABLE_NLS
2292         setlocale(LC_MESSAGES, "");
2293         setlocale(LC_CTYPE, "");
2294         bindtextdomain(NLS_CAT_NAME, LOCALEDIR);
2295         textdomain(NLS_CAT_NAME);
2296         set_com_err_gettext(gettext);
2297 #endif
2298         if (argc && *argv)
2299                 program_name = *argv;
2300         add_error_table(&et_ext2_error_table);
2301
2302 #ifdef CONFIG_BUILD_FINDFS
2303         if (strcmp(get_progname(argv[0]), "findfs") == 0)
2304                 do_findfs(argc, argv);
2305 #endif
2306         if (strcmp(get_progname(argv[0]), "e2label") == 0)
2307                 parse_e2label_options(argc, argv);
2308         else
2309                 parse_tune2fs_options(argc, argv);
2310
2311 #ifdef CONFIG_TESTIO_DEBUG
2312         if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_DEBUG")) {
2313                 io_ptr = test_io_manager;
2314                 test_io_backing_manager = unix_io_manager;
2315         } else
2316 #endif
2317                 io_ptr = unix_io_manager;
2318
2319 retry_open:
2320         if ((open_flag & EXT2_FLAG_RW) == 0 || f_flag)
2321                 open_flag |= EXT2_FLAG_SKIP_MMP;
2322
2323         open_flag |= EXT2_FLAG_64BITS;
2324
2325         /* keep the filesystem struct around to dump MMP data */
2326         open_flag |= EXT2_FLAG_NOFREE_ON_ERROR;
2327
2328         retval = ext2fs_open2(device_name, io_options, open_flag,
2329                               0, 0, io_ptr, &fs);
2330         if (retval) {
2331                 com_err(program_name, retval,
2332                         _("while trying to open %s"),
2333                         device_name);
2334                 if (retval == EXT2_ET_MMP_FSCK_ON ||
2335                     retval == EXT2_ET_MMP_UNKNOWN_SEQ)
2336                         dump_mmp_msg(fs->mmp_buf,
2337                                      _("If you are sure the filesystem "
2338                                        "is not in use on any node, run:\n"
2339                                        "'tune2fs -f -E clear_mmp {device}'\n"));
2340                 else if (retval == EXT2_ET_MMP_FAILED)
2341                         dump_mmp_msg(fs->mmp_buf, NULL);
2342                 else if (retval == EXT2_ET_MMP_MAGIC_INVALID)
2343                         fprintf(stderr,
2344                                 _("MMP block magic is bad. Try to fix it by "
2345                                   "running:\n'e2fsck -f %s'\n"), device_name);
2346                 else if (retval != EXT2_ET_MMP_FAILED)
2347                         fprintf(stderr,
2348                              _("Couldn't find valid filesystem superblock.\n"));
2349
2350                 ext2fs_free(fs);
2351                 exit(1);
2352         }
2353         fs->default_bitmap_type = EXT2FS_BMAP64_RBTREE;
2354
2355         if (I_flag && !io_ptr_orig) {
2356                 /*
2357                  * Check the inode size is right so we can issue an
2358                  * error message and bail before setting up the tdb
2359                  * file.
2360                  */
2361                 if (new_inode_size == EXT2_INODE_SIZE(fs->super)) {
2362                         fprintf(stderr, _("The inode size is already %lu\n"),
2363                                 new_inode_size);
2364                         rc = 1;
2365                         goto closefs;
2366                 }
2367                 if (new_inode_size < EXT2_INODE_SIZE(fs->super)) {
2368                         fprintf(stderr, _("Shrinking the inode size is "
2369                                           "not supported\n"));
2370                         rc = 1;
2371                         goto closefs;
2372                 }
2373                 if (new_inode_size > fs->blocksize) {
2374                         fprintf(stderr, _("Invalid inode size %lu (max %d)\n"),
2375                                 new_inode_size, fs->blocksize);
2376                         rc = 1;
2377                         goto closefs;
2378                 }
2379
2380                 /*
2381                  * If inode resize is requested use the
2382                  * Undo I/O manager
2383                  */
2384                 io_ptr_orig = io_ptr;
2385                 retval = tune2fs_setup_tdb(device_name, &io_ptr);
2386                 if (retval) {
2387                         rc = 1;
2388                         goto closefs;
2389                 }
2390                 if (io_ptr != io_ptr_orig) {
2391                         ext2fs_close(fs);
2392                         goto retry_open;
2393                 }
2394         }
2395
2396         sb = fs->super;
2397         fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY;
2398
2399         if (print_label) {
2400                 /* For e2label emulation */
2401                 printf("%.*s\n", (int) sizeof(sb->s_volume_name),
2402                        sb->s_volume_name);
2403                 remove_error_table(&et_ext2_error_table);
2404                 goto closefs;
2405         }
2406
2407         retval = ext2fs_check_if_mounted(device_name, &mount_flags);
2408         if (retval) {
2409                 com_err("ext2fs_check_if_mount", retval,
2410                         _("while determining whether %s is mounted."),
2411                         device_name);
2412                 rc = 1;
2413                 goto closefs;
2414         }
2415         /* Normally we only need to write out the superblock */
2416         fs->flags |= EXT2_FLAG_SUPER_ONLY;
2417
2418         if (c_flag) {
2419                 sb->s_max_mnt_count = max_mount_count;
2420                 ext2fs_mark_super_dirty(fs);
2421                 printf(_("Setting maximal mount count to %d\n"),
2422                        max_mount_count);
2423         }
2424         if (C_flag) {
2425                 sb->s_mnt_count = mount_count;
2426                 ext2fs_mark_super_dirty(fs);
2427                 printf(_("Setting current mount count to %d\n"), mount_count);
2428         }
2429         if (e_flag) {
2430                 sb->s_errors = errors;
2431                 ext2fs_mark_super_dirty(fs);
2432                 printf(_("Setting error behavior to %d\n"), errors);
2433         }
2434         if (g_flag) {
2435                 sb->s_def_resgid = resgid;
2436                 ext2fs_mark_super_dirty(fs);
2437                 printf(_("Setting reserved blocks gid to %lu\n"), resgid);
2438         }
2439         if (i_flag) {
2440                 if (interval >= (1ULL << 32)) {
2441                         com_err(program_name, 0,
2442                                 _("interval between checks is too big (%lu)"),
2443                                 interval);
2444                         rc = 1;
2445                         goto closefs;
2446                 }
2447                 sb->s_checkinterval = interval;
2448                 ext2fs_mark_super_dirty(fs);
2449                 printf(_("Setting interval between checks to %lu seconds\n"),
2450                        interval);
2451         }
2452         if (m_flag) {
2453                 ext2fs_r_blocks_count_set(sb, reserved_ratio *
2454                                           ext2fs_blocks_count(sb) / 100.0);
2455                 ext2fs_mark_super_dirty(fs);
2456                 printf (_("Setting reserved blocks percentage to %g%% (%llu blocks)\n"),
2457                         reserved_ratio, ext2fs_r_blocks_count(sb));
2458         }
2459         if (r_flag) {
2460                 if (reserved_blocks > ext2fs_blocks_count(sb)/2) {
2461                         com_err(program_name, 0,
2462                                 _("reserved blocks count is too big (%llu)"),
2463                                 reserved_blocks);
2464                         rc = 1;
2465                         goto closefs;
2466                 }
2467                 ext2fs_r_blocks_count_set(sb, reserved_blocks);
2468                 ext2fs_mark_super_dirty(fs);
2469                 printf(_("Setting reserved blocks count to %llu\n"),
2470                        reserved_blocks);
2471         }
2472         if (s_flag == 1) {
2473                 if (sb->s_feature_ro_compat &
2474                     EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER)
2475                         fputs(_("\nThe filesystem already has sparse "
2476                                 "superblocks.\n"), stderr);
2477                 else {
2478                         sb->s_feature_ro_compat |=
2479                                 EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER;
2480                         sb->s_state &= ~EXT2_VALID_FS;
2481                         ext2fs_mark_super_dirty(fs);
2482                         printf(_("\nSparse superblock flag set.  %s"),
2483                                _(please_fsck));
2484                 }
2485         }
2486         if (s_flag == 0) {
2487                 fputs(_("\nClearing the sparse superflag not supported.\n"),
2488                       stderr);
2489                 rc = 1;
2490                 goto closefs;
2491         }
2492         if (T_flag) {
2493                 sb->s_lastcheck = last_check_time;
2494                 ext2fs_mark_super_dirty(fs);
2495                 printf(_("Setting time filesystem last checked to %s\n"),
2496                        ctime(&last_check_time));
2497         }
2498         if (u_flag) {
2499                 sb->s_def_resuid = resuid;
2500                 ext2fs_mark_super_dirty(fs);
2501                 printf(_("Setting reserved blocks uid to %lu\n"), resuid);
2502         }
2503         if (L_flag) {
2504                 if (strlen(new_label) > sizeof(sb->s_volume_name))
2505                         fputs(_("Warning: label too long, truncating.\n"),
2506                               stderr);
2507                 memset(sb->s_volume_name, 0, sizeof(sb->s_volume_name));
2508                 strncpy(sb->s_volume_name, new_label,
2509                         sizeof(sb->s_volume_name));
2510                 ext2fs_mark_super_dirty(fs);
2511         }
2512         if (M_flag) {
2513                 memset(sb->s_last_mounted, 0, sizeof(sb->s_last_mounted));
2514                 strncpy(sb->s_last_mounted, new_last_mounted,
2515                         sizeof(sb->s_last_mounted));
2516                 ext2fs_mark_super_dirty(fs);
2517         }
2518         if (mntopts_cmd) {
2519                 rc = update_mntopts(fs, mntopts_cmd);
2520                 if (rc)
2521                         goto closefs;
2522         }
2523         if (features_cmd) {
2524                 rc = update_feature_set(fs, features_cmd);
2525                 if (rc)
2526                         goto closefs;
2527         }
2528         if (extended_cmd) {
2529                 rc = parse_extended_opts(fs, extended_cmd);
2530                 if (rc)
2531                         goto closefs;
2532                 if (clear_mmp && !f_flag) {
2533                         fputs(_("Error in using clear_mmp. "
2534                                 "It must be used with -f\n"),
2535                               stderr);
2536                         goto closefs;
2537                 }
2538         }
2539         if (clear_mmp) {
2540                 rc = ext2fs_mmp_clear(fs);
2541                 goto closefs;
2542         }
2543         if (journal_size || journal_device) {
2544                 rc = add_journal(fs);
2545                 if (rc)
2546                         goto closefs;
2547         }
2548
2549         if (Q_flag) {
2550                 if (mount_flags & EXT2_MF_MOUNTED) {
2551                         fputs(_("The quota feature may only be changed when "
2552                                 "the filesystem is unmounted.\n"), stderr);
2553                         rc = 1;
2554                         goto closefs;
2555                 }
2556                 handle_quota_options(fs);
2557         }
2558
2559         if (U_flag) {
2560                 int set_csum = 0;
2561                 dgrp_t i;
2562
2563                 if (EXT2_HAS_RO_COMPAT_FEATURE(fs->super,
2564                                 EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) {
2565                         /*
2566                          * Changing the UUID requires rewriting all metadata,
2567                          * which can race with a mounted fs.  Don't allow that.
2568                          */
2569                         if (mount_flags & EXT2_MF_MOUNTED) {
2570                                 fputs(_("The UUID may only be "
2571                                         "changed when the filesystem is "
2572                                         "unmounted.\n"), stderr);
2573                                 exit(1);
2574                         }
2575
2576                         if (check_fsck_needed(fs))
2577                                 exit(1);
2578                 }
2579
2580                 if (ext2fs_has_group_desc_csum(fs)) {
2581                         /*
2582                          * Determine if the block group checksums are
2583                          * correct so we know whether or not to set
2584                          * them later on.
2585                          */
2586                         for (i = 0; i < fs->group_desc_count; i++)
2587                                 if (!ext2fs_group_desc_csum_verify(fs, i))
2588                                         break;
2589                         if (i >= fs->group_desc_count)
2590                                 set_csum = 1;
2591                 }
2592                 if ((strcasecmp(new_UUID, "null") == 0) ||
2593                     (strcasecmp(new_UUID, "clear") == 0)) {
2594                         uuid_clear(sb->s_uuid);
2595                 } else if (strcasecmp(new_UUID, "time") == 0) {
2596                         uuid_generate_time(sb->s_uuid);
2597                 } else if (strcasecmp(new_UUID, "random") == 0) {
2598                         uuid_generate(sb->s_uuid);
2599                 } else if (uuid_parse(new_UUID, sb->s_uuid)) {
2600                         com_err(program_name, 0, _("Invalid UUID format\n"));
2601                         rc = 1;
2602                         goto closefs;
2603                 }
2604                 ext2fs_init_csum_seed(fs);
2605                 if (set_csum) {
2606                         for (i = 0; i < fs->group_desc_count; i++)
2607                                 ext2fs_group_desc_csum_set(fs, i);
2608                         fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
2609                 }
2610                 ext2fs_mark_super_dirty(fs);
2611                 if (EXT2_HAS_RO_COMPAT_FEATURE(fs->super,
2612                                 EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
2613                         rewrite_checksums = 1;
2614         }
2615         if (rewrite_checksums)
2616                 rewrite_metadata_checksums(fs);
2617         if (I_flag) {
2618                 if (mount_flags & EXT2_MF_MOUNTED) {
2619                         fputs(_("The inode size may only be "
2620                                 "changed when the filesystem is "
2621                                 "unmounted.\n"), stderr);
2622                         rc = 1;
2623                         goto closefs;
2624                 }
2625                 if (fs->super->s_feature_incompat &
2626                     EXT4_FEATURE_INCOMPAT_FLEX_BG) {
2627                         fputs(_("Changing the inode size not supported for "
2628                                 "filesystems with the flex_bg\n"
2629                                 "feature enabled.\n"),
2630                               stderr);
2631                         rc = 1;
2632                         goto closefs;
2633                 }
2634                 /*
2635                  * We want to update group descriptor also
2636                  * with the new free inode count
2637                  */
2638                 fs->flags &= ~EXT2_FLAG_SUPER_ONLY;
2639                 if (resize_inode(fs, new_inode_size) == 0) {
2640                         printf(_("Setting inode size %lu\n"),
2641                                                         new_inode_size);
2642                 } else {
2643                         printf(_("Failed to change inode size\n"));
2644                         rc = 1;
2645                         goto closefs;
2646                 }
2647         }
2648
2649         if (l_flag)
2650                 list_super(sb);
2651         if (stride_set) {
2652                 sb->s_raid_stride = stride;
2653                 ext2fs_mark_super_dirty(fs);
2654                 printf(_("Setting stride size to %d\n"), stride);
2655         }
2656         if (stripe_width_set) {
2657                 sb->s_raid_stripe_width = stripe_width;
2658                 ext2fs_mark_super_dirty(fs);
2659                 printf(_("Setting stripe width to %d\n"), stripe_width);
2660         }
2661         if (ext_mount_opts) {
2662                 strncpy((char *)(fs->super->s_mount_opts), ext_mount_opts,
2663                         sizeof(fs->super->s_mount_opts));
2664                 fs->super->s_mount_opts[sizeof(fs->super->s_mount_opts)-1] = 0;
2665                 ext2fs_mark_super_dirty(fs);
2666                 printf(_("Setting extended default mount options to '%s'\n"),
2667                        ext_mount_opts);
2668                 free(ext_mount_opts);
2669         }
2670         free(device_name);
2671         remove_error_table(&et_ext2_error_table);
2672
2673 closefs:
2674         if (rc) {
2675                 ext2fs_mmp_stop(fs);
2676                 exit(1);
2677         }
2678
2679         return (ext2fs_close(fs) ? 1 : 0);
2680 }