ext4: fix bdev write error check failed when mount fs with ro
[linux-2.6-microblaze.git] / fs / ext4 / super.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  linux/fs/ext4/super.c
4  *
5  * Copyright (C) 1992, 1993, 1994, 1995
6  * Remy Card (card@masi.ibp.fr)
7  * Laboratoire MASI - Institut Blaise Pascal
8  * Universite Pierre et Marie Curie (Paris VI)
9  *
10  *  from
11  *
12  *  linux/fs/minix/inode.c
13  *
14  *  Copyright (C) 1991, 1992  Linus Torvalds
15  *
16  *  Big-endian to little-endian byte-swapping/bitmaps by
17  *        David S. Miller (davem@caip.rutgers.edu), 1995
18  */
19
20 #include <linux/module.h>
21 #include <linux/string.h>
22 #include <linux/fs.h>
23 #include <linux/time.h>
24 #include <linux/vmalloc.h>
25 #include <linux/slab.h>
26 #include <linux/init.h>
27 #include <linux/blkdev.h>
28 #include <linux/backing-dev.h>
29 #include <linux/parser.h>
30 #include <linux/buffer_head.h>
31 #include <linux/exportfs.h>
32 #include <linux/vfs.h>
33 #include <linux/random.h>
34 #include <linux/mount.h>
35 #include <linux/namei.h>
36 #include <linux/quotaops.h>
37 #include <linux/seq_file.h>
38 #include <linux/ctype.h>
39 #include <linux/log2.h>
40 #include <linux/crc16.h>
41 #include <linux/dax.h>
42 #include <linux/cleancache.h>
43 #include <linux/uaccess.h>
44 #include <linux/iversion.h>
45 #include <linux/unicode.h>
46 #include <linux/part_stat.h>
47 #include <linux/kthread.h>
48 #include <linux/freezer.h>
49
50 #include "ext4.h"
51 #include "ext4_extents.h"       /* Needed for trace points definition */
52 #include "ext4_jbd2.h"
53 #include "xattr.h"
54 #include "acl.h"
55 #include "mballoc.h"
56 #include "fsmap.h"
57
58 #define CREATE_TRACE_POINTS
59 #include <trace/events/ext4.h>
60
61 static struct ext4_lazy_init *ext4_li_info;
62 static struct mutex ext4_li_mtx;
63 static struct ratelimit_state ext4_mount_msg_ratelimit;
64
65 static int ext4_load_journal(struct super_block *, struct ext4_super_block *,
66                              unsigned long journal_devnum);
67 static int ext4_show_options(struct seq_file *seq, struct dentry *root);
68 static int ext4_commit_super(struct super_block *sb, int sync);
69 static int ext4_mark_recovery_complete(struct super_block *sb,
70                                         struct ext4_super_block *es);
71 static int ext4_clear_journal_err(struct super_block *sb,
72                                   struct ext4_super_block *es);
73 static int ext4_sync_fs(struct super_block *sb, int wait);
74 static int ext4_remount(struct super_block *sb, int *flags, char *data);
75 static int ext4_statfs(struct dentry *dentry, struct kstatfs *buf);
76 static int ext4_unfreeze(struct super_block *sb);
77 static int ext4_freeze(struct super_block *sb);
78 static struct dentry *ext4_mount(struct file_system_type *fs_type, int flags,
79                        const char *dev_name, void *data);
80 static inline int ext2_feature_set_ok(struct super_block *sb);
81 static inline int ext3_feature_set_ok(struct super_block *sb);
82 static int ext4_feature_set_ok(struct super_block *sb, int readonly);
83 static void ext4_destroy_lazyinit_thread(void);
84 static void ext4_unregister_li_request(struct super_block *sb);
85 static void ext4_clear_request_list(void);
86 static struct inode *ext4_get_journal_inode(struct super_block *sb,
87                                             unsigned int journal_inum);
88
89 /*
90  * Lock ordering
91  *
92  * Note the difference between i_mmap_sem (EXT4_I(inode)->i_mmap_sem) and
93  * i_mmap_rwsem (inode->i_mmap_rwsem)!
94  *
95  * page fault path:
96  * mmap_lock -> sb_start_pagefault -> i_mmap_sem (r) -> transaction start ->
97  *   page lock -> i_data_sem (rw)
98  *
99  * buffered write path:
100  * sb_start_write -> i_mutex -> mmap_lock
101  * sb_start_write -> i_mutex -> transaction start -> page lock ->
102  *   i_data_sem (rw)
103  *
104  * truncate:
105  * sb_start_write -> i_mutex -> i_mmap_sem (w) -> i_mmap_rwsem (w) -> page lock
106  * sb_start_write -> i_mutex -> i_mmap_sem (w) -> transaction start ->
107  *   i_data_sem (rw)
108  *
109  * direct IO:
110  * sb_start_write -> i_mutex -> mmap_lock
111  * sb_start_write -> i_mutex -> transaction start -> i_data_sem (rw)
112  *
113  * writepages:
114  * transaction start -> page lock(s) -> i_data_sem (rw)
115  */
116
117 #if !defined(CONFIG_EXT2_FS) && !defined(CONFIG_EXT2_FS_MODULE) && defined(CONFIG_EXT4_USE_FOR_EXT2)
118 static struct file_system_type ext2_fs_type = {
119         .owner          = THIS_MODULE,
120         .name           = "ext2",
121         .mount          = ext4_mount,
122         .kill_sb        = kill_block_super,
123         .fs_flags       = FS_REQUIRES_DEV,
124 };
125 MODULE_ALIAS_FS("ext2");
126 MODULE_ALIAS("ext2");
127 #define IS_EXT2_SB(sb) ((sb)->s_bdev->bd_holder == &ext2_fs_type)
128 #else
129 #define IS_EXT2_SB(sb) (0)
130 #endif
131
132
133 static struct file_system_type ext3_fs_type = {
134         .owner          = THIS_MODULE,
135         .name           = "ext3",
136         .mount          = ext4_mount,
137         .kill_sb        = kill_block_super,
138         .fs_flags       = FS_REQUIRES_DEV,
139 };
140 MODULE_ALIAS_FS("ext3");
141 MODULE_ALIAS("ext3");
142 #define IS_EXT3_SB(sb) ((sb)->s_bdev->bd_holder == &ext3_fs_type)
143
144 /*
145  * This works like sb_bread() except it uses ERR_PTR for error
146  * returns.  Currently with sb_bread it's impossible to distinguish
147  * between ENOMEM and EIO situations (since both result in a NULL
148  * return.
149  */
150 struct buffer_head *
151 ext4_sb_bread(struct super_block *sb, sector_t block, int op_flags)
152 {
153         struct buffer_head *bh = sb_getblk(sb, block);
154
155         if (bh == NULL)
156                 return ERR_PTR(-ENOMEM);
157         if (ext4_buffer_uptodate(bh))
158                 return bh;
159         ll_rw_block(REQ_OP_READ, REQ_META | op_flags, 1, &bh);
160         wait_on_buffer(bh);
161         if (buffer_uptodate(bh))
162                 return bh;
163         put_bh(bh);
164         return ERR_PTR(-EIO);
165 }
166
167 static int ext4_verify_csum_type(struct super_block *sb,
168                                  struct ext4_super_block *es)
169 {
170         if (!ext4_has_feature_metadata_csum(sb))
171                 return 1;
172
173         return es->s_checksum_type == EXT4_CRC32C_CHKSUM;
174 }
175
176 static __le32 ext4_superblock_csum(struct super_block *sb,
177                                    struct ext4_super_block *es)
178 {
179         struct ext4_sb_info *sbi = EXT4_SB(sb);
180         int offset = offsetof(struct ext4_super_block, s_checksum);
181         __u32 csum;
182
183         csum = ext4_chksum(sbi, ~0, (char *)es, offset);
184
185         return cpu_to_le32(csum);
186 }
187
188 static int ext4_superblock_csum_verify(struct super_block *sb,
189                                        struct ext4_super_block *es)
190 {
191         if (!ext4_has_metadata_csum(sb))
192                 return 1;
193
194         return es->s_checksum == ext4_superblock_csum(sb, es);
195 }
196
197 void ext4_superblock_csum_set(struct super_block *sb)
198 {
199         struct ext4_super_block *es = EXT4_SB(sb)->s_es;
200
201         if (!ext4_has_metadata_csum(sb))
202                 return;
203
204         /*
205          * Locking the superblock prevents the scenario
206          * where:
207          *  1) a first thread pauses during checksum calculation.
208          *  2) a second thread updates the superblock, recalculates
209          *     the checksum, and updates s_checksum
210          *  3) the first thread resumes and finishes its checksum calculation
211          *     and updates s_checksum with a potentially stale or torn value.
212          */
213         lock_buffer(EXT4_SB(sb)->s_sbh);
214         es->s_checksum = ext4_superblock_csum(sb, es);
215         unlock_buffer(EXT4_SB(sb)->s_sbh);
216 }
217
218 ext4_fsblk_t ext4_block_bitmap(struct super_block *sb,
219                                struct ext4_group_desc *bg)
220 {
221         return le32_to_cpu(bg->bg_block_bitmap_lo) |
222                 (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
223                  (ext4_fsblk_t)le32_to_cpu(bg->bg_block_bitmap_hi) << 32 : 0);
224 }
225
226 ext4_fsblk_t ext4_inode_bitmap(struct super_block *sb,
227                                struct ext4_group_desc *bg)
228 {
229         return le32_to_cpu(bg->bg_inode_bitmap_lo) |
230                 (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
231                  (ext4_fsblk_t)le32_to_cpu(bg->bg_inode_bitmap_hi) << 32 : 0);
232 }
233
234 ext4_fsblk_t ext4_inode_table(struct super_block *sb,
235                               struct ext4_group_desc *bg)
236 {
237         return le32_to_cpu(bg->bg_inode_table_lo) |
238                 (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
239                  (ext4_fsblk_t)le32_to_cpu(bg->bg_inode_table_hi) << 32 : 0);
240 }
241
242 __u32 ext4_free_group_clusters(struct super_block *sb,
243                                struct ext4_group_desc *bg)
244 {
245         return le16_to_cpu(bg->bg_free_blocks_count_lo) |
246                 (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
247                  (__u32)le16_to_cpu(bg->bg_free_blocks_count_hi) << 16 : 0);
248 }
249
250 __u32 ext4_free_inodes_count(struct super_block *sb,
251                               struct ext4_group_desc *bg)
252 {
253         return le16_to_cpu(bg->bg_free_inodes_count_lo) |
254                 (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
255                  (__u32)le16_to_cpu(bg->bg_free_inodes_count_hi) << 16 : 0);
256 }
257
258 __u32 ext4_used_dirs_count(struct super_block *sb,
259                               struct ext4_group_desc *bg)
260 {
261         return le16_to_cpu(bg->bg_used_dirs_count_lo) |
262                 (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
263                  (__u32)le16_to_cpu(bg->bg_used_dirs_count_hi) << 16 : 0);
264 }
265
266 __u32 ext4_itable_unused_count(struct super_block *sb,
267                               struct ext4_group_desc *bg)
268 {
269         return le16_to_cpu(bg->bg_itable_unused_lo) |
270                 (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
271                  (__u32)le16_to_cpu(bg->bg_itable_unused_hi) << 16 : 0);
272 }
273
274 void ext4_block_bitmap_set(struct super_block *sb,
275                            struct ext4_group_desc *bg, ext4_fsblk_t blk)
276 {
277         bg->bg_block_bitmap_lo = cpu_to_le32((u32)blk);
278         if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
279                 bg->bg_block_bitmap_hi = cpu_to_le32(blk >> 32);
280 }
281
282 void ext4_inode_bitmap_set(struct super_block *sb,
283                            struct ext4_group_desc *bg, ext4_fsblk_t blk)
284 {
285         bg->bg_inode_bitmap_lo  = cpu_to_le32((u32)blk);
286         if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
287                 bg->bg_inode_bitmap_hi = cpu_to_le32(blk >> 32);
288 }
289
290 void ext4_inode_table_set(struct super_block *sb,
291                           struct ext4_group_desc *bg, ext4_fsblk_t blk)
292 {
293         bg->bg_inode_table_lo = cpu_to_le32((u32)blk);
294         if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
295                 bg->bg_inode_table_hi = cpu_to_le32(blk >> 32);
296 }
297
298 void ext4_free_group_clusters_set(struct super_block *sb,
299                                   struct ext4_group_desc *bg, __u32 count)
300 {
301         bg->bg_free_blocks_count_lo = cpu_to_le16((__u16)count);
302         if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
303                 bg->bg_free_blocks_count_hi = cpu_to_le16(count >> 16);
304 }
305
306 void ext4_free_inodes_set(struct super_block *sb,
307                           struct ext4_group_desc *bg, __u32 count)
308 {
309         bg->bg_free_inodes_count_lo = cpu_to_le16((__u16)count);
310         if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
311                 bg->bg_free_inodes_count_hi = cpu_to_le16(count >> 16);
312 }
313
314 void ext4_used_dirs_set(struct super_block *sb,
315                           struct ext4_group_desc *bg, __u32 count)
316 {
317         bg->bg_used_dirs_count_lo = cpu_to_le16((__u16)count);
318         if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
319                 bg->bg_used_dirs_count_hi = cpu_to_le16(count >> 16);
320 }
321
322 void ext4_itable_unused_set(struct super_block *sb,
323                           struct ext4_group_desc *bg, __u32 count)
324 {
325         bg->bg_itable_unused_lo = cpu_to_le16((__u16)count);
326         if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
327                 bg->bg_itable_unused_hi = cpu_to_le16(count >> 16);
328 }
329
330 static void __ext4_update_tstamp(__le32 *lo, __u8 *hi)
331 {
332         time64_t now = ktime_get_real_seconds();
333
334         now = clamp_val(now, 0, (1ull << 40) - 1);
335
336         *lo = cpu_to_le32(lower_32_bits(now));
337         *hi = upper_32_bits(now);
338 }
339
340 static time64_t __ext4_get_tstamp(__le32 *lo, __u8 *hi)
341 {
342         return ((time64_t)(*hi) << 32) + le32_to_cpu(*lo);
343 }
344 #define ext4_update_tstamp(es, tstamp) \
345         __ext4_update_tstamp(&(es)->tstamp, &(es)->tstamp ## _hi)
346 #define ext4_get_tstamp(es, tstamp) \
347         __ext4_get_tstamp(&(es)->tstamp, &(es)->tstamp ## _hi)
348
349 static void __save_error_info(struct super_block *sb, int error,
350                               __u32 ino, __u64 block,
351                               const char *func, unsigned int line)
352 {
353         struct ext4_super_block *es = EXT4_SB(sb)->s_es;
354         int err;
355
356         EXT4_SB(sb)->s_mount_state |= EXT4_ERROR_FS;
357         if (bdev_read_only(sb->s_bdev))
358                 return;
359         es->s_state |= cpu_to_le16(EXT4_ERROR_FS);
360         ext4_update_tstamp(es, s_last_error_time);
361         strncpy(es->s_last_error_func, func, sizeof(es->s_last_error_func));
362         es->s_last_error_line = cpu_to_le32(line);
363         es->s_last_error_ino = cpu_to_le32(ino);
364         es->s_last_error_block = cpu_to_le64(block);
365         switch (error) {
366         case EIO:
367                 err = EXT4_ERR_EIO;
368                 break;
369         case ENOMEM:
370                 err = EXT4_ERR_ENOMEM;
371                 break;
372         case EFSBADCRC:
373                 err = EXT4_ERR_EFSBADCRC;
374                 break;
375         case 0:
376         case EFSCORRUPTED:
377                 err = EXT4_ERR_EFSCORRUPTED;
378                 break;
379         case ENOSPC:
380                 err = EXT4_ERR_ENOSPC;
381                 break;
382         case ENOKEY:
383                 err = EXT4_ERR_ENOKEY;
384                 break;
385         case EROFS:
386                 err = EXT4_ERR_EROFS;
387                 break;
388         case EFBIG:
389                 err = EXT4_ERR_EFBIG;
390                 break;
391         case EEXIST:
392                 err = EXT4_ERR_EEXIST;
393                 break;
394         case ERANGE:
395                 err = EXT4_ERR_ERANGE;
396                 break;
397         case EOVERFLOW:
398                 err = EXT4_ERR_EOVERFLOW;
399                 break;
400         case EBUSY:
401                 err = EXT4_ERR_EBUSY;
402                 break;
403         case ENOTDIR:
404                 err = EXT4_ERR_ENOTDIR;
405                 break;
406         case ENOTEMPTY:
407                 err = EXT4_ERR_ENOTEMPTY;
408                 break;
409         case ESHUTDOWN:
410                 err = EXT4_ERR_ESHUTDOWN;
411                 break;
412         case EFAULT:
413                 err = EXT4_ERR_EFAULT;
414                 break;
415         default:
416                 err = EXT4_ERR_UNKNOWN;
417         }
418         es->s_last_error_errcode = err;
419         if (!es->s_first_error_time) {
420                 es->s_first_error_time = es->s_last_error_time;
421                 es->s_first_error_time_hi = es->s_last_error_time_hi;
422                 strncpy(es->s_first_error_func, func,
423                         sizeof(es->s_first_error_func));
424                 es->s_first_error_line = cpu_to_le32(line);
425                 es->s_first_error_ino = es->s_last_error_ino;
426                 es->s_first_error_block = es->s_last_error_block;
427                 es->s_first_error_errcode = es->s_last_error_errcode;
428         }
429         /*
430          * Start the daily error reporting function if it hasn't been
431          * started already
432          */
433         if (!es->s_error_count)
434                 mod_timer(&EXT4_SB(sb)->s_err_report, jiffies + 24*60*60*HZ);
435         le32_add_cpu(&es->s_error_count, 1);
436 }
437
438 static void save_error_info(struct super_block *sb, int error,
439                             __u32 ino, __u64 block,
440                             const char *func, unsigned int line)
441 {
442         __save_error_info(sb, error, ino, block, func, line);
443         if (!bdev_read_only(sb->s_bdev))
444                 ext4_commit_super(sb, 1);
445 }
446
447 /*
448  * The del_gendisk() function uninitializes the disk-specific data
449  * structures, including the bdi structure, without telling anyone
450  * else.  Once this happens, any attempt to call mark_buffer_dirty()
451  * (for example, by ext4_commit_super), will cause a kernel OOPS.
452  * This is a kludge to prevent these oops until we can put in a proper
453  * hook in del_gendisk() to inform the VFS and file system layers.
454  */
455 static int block_device_ejected(struct super_block *sb)
456 {
457         struct inode *bd_inode = sb->s_bdev->bd_inode;
458         struct backing_dev_info *bdi = inode_to_bdi(bd_inode);
459
460         return bdi->dev == NULL;
461 }
462
463 static void ext4_journal_commit_callback(journal_t *journal, transaction_t *txn)
464 {
465         struct super_block              *sb = journal->j_private;
466         struct ext4_sb_info             *sbi = EXT4_SB(sb);
467         int                             error = is_journal_aborted(journal);
468         struct ext4_journal_cb_entry    *jce;
469
470         BUG_ON(txn->t_state == T_FINISHED);
471
472         ext4_process_freed_data(sb, txn->t_tid);
473
474         spin_lock(&sbi->s_md_lock);
475         while (!list_empty(&txn->t_private_list)) {
476                 jce = list_entry(txn->t_private_list.next,
477                                  struct ext4_journal_cb_entry, jce_list);
478                 list_del_init(&jce->jce_list);
479                 spin_unlock(&sbi->s_md_lock);
480                 jce->jce_func(sb, jce, error);
481                 spin_lock(&sbi->s_md_lock);
482         }
483         spin_unlock(&sbi->s_md_lock);
484 }
485
486 static bool system_going_down(void)
487 {
488         return system_state == SYSTEM_HALT || system_state == SYSTEM_POWER_OFF
489                 || system_state == SYSTEM_RESTART;
490 }
491
492 /* Deal with the reporting of failure conditions on a filesystem such as
493  * inconsistencies detected or read IO failures.
494  *
495  * On ext2, we can store the error state of the filesystem in the
496  * superblock.  That is not possible on ext4, because we may have other
497  * write ordering constraints on the superblock which prevent us from
498  * writing it out straight away; and given that the journal is about to
499  * be aborted, we can't rely on the current, or future, transactions to
500  * write out the superblock safely.
501  *
502  * We'll just use the jbd2_journal_abort() error code to record an error in
503  * the journal instead.  On recovery, the journal will complain about
504  * that error until we've noted it down and cleared it.
505  */
506
507 static void ext4_handle_error(struct super_block *sb)
508 {
509         if (test_opt(sb, WARN_ON_ERROR))
510                 WARN_ON_ONCE(1);
511
512         if (sb_rdonly(sb))
513                 return;
514
515         if (!test_opt(sb, ERRORS_CONT)) {
516                 journal_t *journal = EXT4_SB(sb)->s_journal;
517
518                 EXT4_SB(sb)->s_mount_flags |= EXT4_MF_FS_ABORTED;
519                 if (journal)
520                         jbd2_journal_abort(journal, -EIO);
521         }
522         /*
523          * We force ERRORS_RO behavior when system is rebooting. Otherwise we
524          * could panic during 'reboot -f' as the underlying device got already
525          * disabled.
526          */
527         if (test_opt(sb, ERRORS_RO) || system_going_down()) {
528                 ext4_msg(sb, KERN_CRIT, "Remounting filesystem read-only");
529                 /*
530                  * Make sure updated value of ->s_mount_flags will be visible
531                  * before ->s_flags update
532                  */
533                 smp_wmb();
534                 sb->s_flags |= SB_RDONLY;
535         } else if (test_opt(sb, ERRORS_PANIC)) {
536                 panic("EXT4-fs (device %s): panic forced after error\n",
537                         sb->s_id);
538         }
539 }
540
541 #define ext4_error_ratelimit(sb)                                        \
542                 ___ratelimit(&(EXT4_SB(sb)->s_err_ratelimit_state),     \
543                              "EXT4-fs error")
544
545 void __ext4_error(struct super_block *sb, const char *function,
546                   unsigned int line, int error, __u64 block,
547                   const char *fmt, ...)
548 {
549         struct va_format vaf;
550         va_list args;
551
552         if (unlikely(ext4_forced_shutdown(EXT4_SB(sb))))
553                 return;
554
555         trace_ext4_error(sb, function, line);
556         if (ext4_error_ratelimit(sb)) {
557                 va_start(args, fmt);
558                 vaf.fmt = fmt;
559                 vaf.va = &args;
560                 printk(KERN_CRIT
561                        "EXT4-fs error (device %s): %s:%d: comm %s: %pV\n",
562                        sb->s_id, function, line, current->comm, &vaf);
563                 va_end(args);
564         }
565         save_error_info(sb, error, 0, block, function, line);
566         ext4_handle_error(sb);
567 }
568
569 void __ext4_error_inode(struct inode *inode, const char *function,
570                         unsigned int line, ext4_fsblk_t block, int error,
571                         const char *fmt, ...)
572 {
573         va_list args;
574         struct va_format vaf;
575
576         if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
577                 return;
578
579         trace_ext4_error(inode->i_sb, function, line);
580         if (ext4_error_ratelimit(inode->i_sb)) {
581                 va_start(args, fmt);
582                 vaf.fmt = fmt;
583                 vaf.va = &args;
584                 if (block)
585                         printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: "
586                                "inode #%lu: block %llu: comm %s: %pV\n",
587                                inode->i_sb->s_id, function, line, inode->i_ino,
588                                block, current->comm, &vaf);
589                 else
590                         printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: "
591                                "inode #%lu: comm %s: %pV\n",
592                                inode->i_sb->s_id, function, line, inode->i_ino,
593                                current->comm, &vaf);
594                 va_end(args);
595         }
596         save_error_info(inode->i_sb, error, inode->i_ino, block,
597                         function, line);
598         ext4_handle_error(inode->i_sb);
599 }
600
601 void __ext4_error_file(struct file *file, const char *function,
602                        unsigned int line, ext4_fsblk_t block,
603                        const char *fmt, ...)
604 {
605         va_list args;
606         struct va_format vaf;
607         struct inode *inode = file_inode(file);
608         char pathname[80], *path;
609
610         if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
611                 return;
612
613         trace_ext4_error(inode->i_sb, function, line);
614         if (ext4_error_ratelimit(inode->i_sb)) {
615                 path = file_path(file, pathname, sizeof(pathname));
616                 if (IS_ERR(path))
617                         path = "(unknown)";
618                 va_start(args, fmt);
619                 vaf.fmt = fmt;
620                 vaf.va = &args;
621                 if (block)
622                         printk(KERN_CRIT
623                                "EXT4-fs error (device %s): %s:%d: inode #%lu: "
624                                "block %llu: comm %s: path %s: %pV\n",
625                                inode->i_sb->s_id, function, line, inode->i_ino,
626                                block, current->comm, path, &vaf);
627                 else
628                         printk(KERN_CRIT
629                                "EXT4-fs error (device %s): %s:%d: inode #%lu: "
630                                "comm %s: path %s: %pV\n",
631                                inode->i_sb->s_id, function, line, inode->i_ino,
632                                current->comm, path, &vaf);
633                 va_end(args);
634         }
635         save_error_info(inode->i_sb, EFSCORRUPTED, inode->i_ino, block,
636                         function, line);
637         ext4_handle_error(inode->i_sb);
638 }
639
640 const char *ext4_decode_error(struct super_block *sb, int errno,
641                               char nbuf[16])
642 {
643         char *errstr = NULL;
644
645         switch (errno) {
646         case -EFSCORRUPTED:
647                 errstr = "Corrupt filesystem";
648                 break;
649         case -EFSBADCRC:
650                 errstr = "Filesystem failed CRC";
651                 break;
652         case -EIO:
653                 errstr = "IO failure";
654                 break;
655         case -ENOMEM:
656                 errstr = "Out of memory";
657                 break;
658         case -EROFS:
659                 if (!sb || (EXT4_SB(sb)->s_journal &&
660                             EXT4_SB(sb)->s_journal->j_flags & JBD2_ABORT))
661                         errstr = "Journal has aborted";
662                 else
663                         errstr = "Readonly filesystem";
664                 break;
665         default:
666                 /* If the caller passed in an extra buffer for unknown
667                  * errors, textualise them now.  Else we just return
668                  * NULL. */
669                 if (nbuf) {
670                         /* Check for truncated error codes... */
671                         if (snprintf(nbuf, 16, "error %d", -errno) >= 0)
672                                 errstr = nbuf;
673                 }
674                 break;
675         }
676
677         return errstr;
678 }
679
680 /* __ext4_std_error decodes expected errors from journaling functions
681  * automatically and invokes the appropriate error response.  */
682
683 void __ext4_std_error(struct super_block *sb, const char *function,
684                       unsigned int line, int errno)
685 {
686         char nbuf[16];
687         const char *errstr;
688
689         if (unlikely(ext4_forced_shutdown(EXT4_SB(sb))))
690                 return;
691
692         /* Special case: if the error is EROFS, and we're not already
693          * inside a transaction, then there's really no point in logging
694          * an error. */
695         if (errno == -EROFS && journal_current_handle() == NULL && sb_rdonly(sb))
696                 return;
697
698         if (ext4_error_ratelimit(sb)) {
699                 errstr = ext4_decode_error(sb, errno, nbuf);
700                 printk(KERN_CRIT "EXT4-fs error (device %s) in %s:%d: %s\n",
701                        sb->s_id, function, line, errstr);
702         }
703
704         save_error_info(sb, -errno, 0, 0, function, line);
705         ext4_handle_error(sb);
706 }
707
708 /*
709  * ext4_abort is a much stronger failure handler than ext4_error.  The
710  * abort function may be used to deal with unrecoverable failures such
711  * as journal IO errors or ENOMEM at a critical moment in log management.
712  *
713  * We unconditionally force the filesystem into an ABORT|READONLY state,
714  * unless the error response on the fs has been set to panic in which
715  * case we take the easy way out and panic immediately.
716  */
717
718 void __ext4_abort(struct super_block *sb, const char *function,
719                   unsigned int line, int error, const char *fmt, ...)
720 {
721         struct va_format vaf;
722         va_list args;
723
724         if (unlikely(ext4_forced_shutdown(EXT4_SB(sb))))
725                 return;
726
727         save_error_info(sb, error, 0, 0, function, line);
728         va_start(args, fmt);
729         vaf.fmt = fmt;
730         vaf.va = &args;
731         printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: %pV\n",
732                sb->s_id, function, line, &vaf);
733         va_end(args);
734
735         if (sb_rdonly(sb) == 0) {
736                 EXT4_SB(sb)->s_mount_flags |= EXT4_MF_FS_ABORTED;
737                 if (EXT4_SB(sb)->s_journal)
738                         jbd2_journal_abort(EXT4_SB(sb)->s_journal, -EIO);
739
740                 ext4_msg(sb, KERN_CRIT, "Remounting filesystem read-only");
741                 /*
742                  * Make sure updated value of ->s_mount_flags will be visible
743                  * before ->s_flags update
744                  */
745                 smp_wmb();
746                 sb->s_flags |= SB_RDONLY;
747         }
748         if (test_opt(sb, ERRORS_PANIC) && !system_going_down())
749                 panic("EXT4-fs panic from previous error\n");
750 }
751
752 void __ext4_msg(struct super_block *sb,
753                 const char *prefix, const char *fmt, ...)
754 {
755         struct va_format vaf;
756         va_list args;
757
758         atomic_inc(&EXT4_SB(sb)->s_msg_count);
759         if (!___ratelimit(&(EXT4_SB(sb)->s_msg_ratelimit_state), "EXT4-fs"))
760                 return;
761
762         va_start(args, fmt);
763         vaf.fmt = fmt;
764         vaf.va = &args;
765         printk("%sEXT4-fs (%s): %pV\n", prefix, sb->s_id, &vaf);
766         va_end(args);
767 }
768
769 static int ext4_warning_ratelimit(struct super_block *sb)
770 {
771         atomic_inc(&EXT4_SB(sb)->s_warning_count);
772         return ___ratelimit(&(EXT4_SB(sb)->s_warning_ratelimit_state),
773                             "EXT4-fs warning");
774 }
775
776 void __ext4_warning(struct super_block *sb, const char *function,
777                     unsigned int line, const char *fmt, ...)
778 {
779         struct va_format vaf;
780         va_list args;
781
782         if (!ext4_warning_ratelimit(sb))
783                 return;
784
785         va_start(args, fmt);
786         vaf.fmt = fmt;
787         vaf.va = &args;
788         printk(KERN_WARNING "EXT4-fs warning (device %s): %s:%d: %pV\n",
789                sb->s_id, function, line, &vaf);
790         va_end(args);
791 }
792
793 void __ext4_warning_inode(const struct inode *inode, const char *function,
794                           unsigned int line, const char *fmt, ...)
795 {
796         struct va_format vaf;
797         va_list args;
798
799         if (!ext4_warning_ratelimit(inode->i_sb))
800                 return;
801
802         va_start(args, fmt);
803         vaf.fmt = fmt;
804         vaf.va = &args;
805         printk(KERN_WARNING "EXT4-fs warning (device %s): %s:%d: "
806                "inode #%lu: comm %s: %pV\n", inode->i_sb->s_id,
807                function, line, inode->i_ino, current->comm, &vaf);
808         va_end(args);
809 }
810
811 void __ext4_grp_locked_error(const char *function, unsigned int line,
812                              struct super_block *sb, ext4_group_t grp,
813                              unsigned long ino, ext4_fsblk_t block,
814                              const char *fmt, ...)
815 __releases(bitlock)
816 __acquires(bitlock)
817 {
818         struct va_format vaf;
819         va_list args;
820
821         if (unlikely(ext4_forced_shutdown(EXT4_SB(sb))))
822                 return;
823
824         trace_ext4_error(sb, function, line);
825         __save_error_info(sb, EFSCORRUPTED, ino, block, function, line);
826
827         if (ext4_error_ratelimit(sb)) {
828                 va_start(args, fmt);
829                 vaf.fmt = fmt;
830                 vaf.va = &args;
831                 printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: group %u, ",
832                        sb->s_id, function, line, grp);
833                 if (ino)
834                         printk(KERN_CONT "inode %lu: ", ino);
835                 if (block)
836                         printk(KERN_CONT "block %llu:",
837                                (unsigned long long) block);
838                 printk(KERN_CONT "%pV\n", &vaf);
839                 va_end(args);
840         }
841
842         if (test_opt(sb, WARN_ON_ERROR))
843                 WARN_ON_ONCE(1);
844
845         if (test_opt(sb, ERRORS_CONT)) {
846                 ext4_commit_super(sb, 0);
847                 return;
848         }
849
850         ext4_unlock_group(sb, grp);
851         ext4_commit_super(sb, 1);
852         ext4_handle_error(sb);
853         /*
854          * We only get here in the ERRORS_RO case; relocking the group
855          * may be dangerous, but nothing bad will happen since the
856          * filesystem will have already been marked read/only and the
857          * journal has been aborted.  We return 1 as a hint to callers
858          * who might what to use the return value from
859          * ext4_grp_locked_error() to distinguish between the
860          * ERRORS_CONT and ERRORS_RO case, and perhaps return more
861          * aggressively from the ext4 function in question, with a
862          * more appropriate error code.
863          */
864         ext4_lock_group(sb, grp);
865         return;
866 }
867
868 void ext4_mark_group_bitmap_corrupted(struct super_block *sb,
869                                      ext4_group_t group,
870                                      unsigned int flags)
871 {
872         struct ext4_sb_info *sbi = EXT4_SB(sb);
873         struct ext4_group_info *grp = ext4_get_group_info(sb, group);
874         struct ext4_group_desc *gdp = ext4_get_group_desc(sb, group, NULL);
875         int ret;
876
877         if (flags & EXT4_GROUP_INFO_BBITMAP_CORRUPT) {
878                 ret = ext4_test_and_set_bit(EXT4_GROUP_INFO_BBITMAP_CORRUPT_BIT,
879                                             &grp->bb_state);
880                 if (!ret)
881                         percpu_counter_sub(&sbi->s_freeclusters_counter,
882                                            grp->bb_free);
883         }
884
885         if (flags & EXT4_GROUP_INFO_IBITMAP_CORRUPT) {
886                 ret = ext4_test_and_set_bit(EXT4_GROUP_INFO_IBITMAP_CORRUPT_BIT,
887                                             &grp->bb_state);
888                 if (!ret && gdp) {
889                         int count;
890
891                         count = ext4_free_inodes_count(sb, gdp);
892                         percpu_counter_sub(&sbi->s_freeinodes_counter,
893                                            count);
894                 }
895         }
896 }
897
898 void ext4_update_dynamic_rev(struct super_block *sb)
899 {
900         struct ext4_super_block *es = EXT4_SB(sb)->s_es;
901
902         if (le32_to_cpu(es->s_rev_level) > EXT4_GOOD_OLD_REV)
903                 return;
904
905         ext4_warning(sb,
906                      "updating to rev %d because of new feature flag, "
907                      "running e2fsck is recommended",
908                      EXT4_DYNAMIC_REV);
909
910         es->s_first_ino = cpu_to_le32(EXT4_GOOD_OLD_FIRST_INO);
911         es->s_inode_size = cpu_to_le16(EXT4_GOOD_OLD_INODE_SIZE);
912         es->s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV);
913         /* leave es->s_feature_*compat flags alone */
914         /* es->s_uuid will be set by e2fsck if empty */
915
916         /*
917          * The rest of the superblock fields should be zero, and if not it
918          * means they are likely already in use, so leave them alone.  We
919          * can leave it up to e2fsck to clean up any inconsistencies there.
920          */
921 }
922
923 /*
924  * Open the external journal device
925  */
926 static struct block_device *ext4_blkdev_get(dev_t dev, struct super_block *sb)
927 {
928         struct block_device *bdev;
929
930         bdev = blkdev_get_by_dev(dev, FMODE_READ|FMODE_WRITE|FMODE_EXCL, sb);
931         if (IS_ERR(bdev))
932                 goto fail;
933         return bdev;
934
935 fail:
936         ext4_msg(sb, KERN_ERR,
937                  "failed to open journal device unknown-block(%u,%u) %ld",
938                  MAJOR(dev), MINOR(dev), PTR_ERR(bdev));
939         return NULL;
940 }
941
942 /*
943  * Release the journal device
944  */
945 static void ext4_blkdev_put(struct block_device *bdev)
946 {
947         blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
948 }
949
950 static void ext4_blkdev_remove(struct ext4_sb_info *sbi)
951 {
952         struct block_device *bdev;
953         bdev = sbi->s_journal_bdev;
954         if (bdev) {
955                 ext4_blkdev_put(bdev);
956                 sbi->s_journal_bdev = NULL;
957         }
958 }
959
960 static inline struct inode *orphan_list_entry(struct list_head *l)
961 {
962         return &list_entry(l, struct ext4_inode_info, i_orphan)->vfs_inode;
963 }
964
965 static void dump_orphan_list(struct super_block *sb, struct ext4_sb_info *sbi)
966 {
967         struct list_head *l;
968
969         ext4_msg(sb, KERN_ERR, "sb orphan head is %d",
970                  le32_to_cpu(sbi->s_es->s_last_orphan));
971
972         printk(KERN_ERR "sb_info orphan list:\n");
973         list_for_each(l, &sbi->s_orphan) {
974                 struct inode *inode = orphan_list_entry(l);
975                 printk(KERN_ERR "  "
976                        "inode %s:%lu at %p: mode %o, nlink %d, next %d\n",
977                        inode->i_sb->s_id, inode->i_ino, inode,
978                        inode->i_mode, inode->i_nlink,
979                        NEXT_ORPHAN(inode));
980         }
981 }
982
983 #ifdef CONFIG_QUOTA
984 static int ext4_quota_off(struct super_block *sb, int type);
985
986 static inline void ext4_quota_off_umount(struct super_block *sb)
987 {
988         int type;
989
990         /* Use our quota_off function to clear inode flags etc. */
991         for (type = 0; type < EXT4_MAXQUOTAS; type++)
992                 ext4_quota_off(sb, type);
993 }
994
995 /*
996  * This is a helper function which is used in the mount/remount
997  * codepaths (which holds s_umount) to fetch the quota file name.
998  */
999 static inline char *get_qf_name(struct super_block *sb,
1000                                 struct ext4_sb_info *sbi,
1001                                 int type)
1002 {
1003         return rcu_dereference_protected(sbi->s_qf_names[type],
1004                                          lockdep_is_held(&sb->s_umount));
1005 }
1006 #else
1007 static inline void ext4_quota_off_umount(struct super_block *sb)
1008 {
1009 }
1010 #endif
1011
1012 static void ext4_put_super(struct super_block *sb)
1013 {
1014         struct ext4_sb_info *sbi = EXT4_SB(sb);
1015         struct ext4_super_block *es = sbi->s_es;
1016         struct buffer_head **group_desc;
1017         struct flex_groups **flex_groups;
1018         int aborted = 0;
1019         int i, err;
1020
1021         ext4_unregister_li_request(sb);
1022         ext4_quota_off_umount(sb);
1023
1024         destroy_workqueue(sbi->rsv_conversion_wq);
1025
1026         /*
1027          * Unregister sysfs before destroying jbd2 journal.
1028          * Since we could still access attr_journal_task attribute via sysfs
1029          * path which could have sbi->s_journal->j_task as NULL
1030          */
1031         ext4_unregister_sysfs(sb);
1032
1033         if (sbi->s_journal) {
1034                 aborted = is_journal_aborted(sbi->s_journal);
1035                 err = jbd2_journal_destroy(sbi->s_journal);
1036                 sbi->s_journal = NULL;
1037                 if ((err < 0) && !aborted) {
1038                         ext4_abort(sb, -err, "Couldn't clean up the journal");
1039                 }
1040         }
1041
1042         ext4_es_unregister_shrinker(sbi);
1043         del_timer_sync(&sbi->s_err_report);
1044         ext4_release_system_zone(sb);
1045         ext4_mb_release(sb);
1046         ext4_ext_release(sb);
1047
1048         if (!sb_rdonly(sb) && !aborted) {
1049                 ext4_clear_feature_journal_needs_recovery(sb);
1050                 es->s_state = cpu_to_le16(sbi->s_mount_state);
1051         }
1052         if (!sb_rdonly(sb))
1053                 ext4_commit_super(sb, 1);
1054
1055         rcu_read_lock();
1056         group_desc = rcu_dereference(sbi->s_group_desc);
1057         for (i = 0; i < sbi->s_gdb_count; i++)
1058                 brelse(group_desc[i]);
1059         kvfree(group_desc);
1060         flex_groups = rcu_dereference(sbi->s_flex_groups);
1061         if (flex_groups) {
1062                 for (i = 0; i < sbi->s_flex_groups_allocated; i++)
1063                         kvfree(flex_groups[i]);
1064                 kvfree(flex_groups);
1065         }
1066         rcu_read_unlock();
1067         percpu_counter_destroy(&sbi->s_freeclusters_counter);
1068         percpu_counter_destroy(&sbi->s_freeinodes_counter);
1069         percpu_counter_destroy(&sbi->s_dirs_counter);
1070         percpu_counter_destroy(&sbi->s_dirtyclusters_counter);
1071         percpu_free_rwsem(&sbi->s_writepages_rwsem);
1072 #ifdef CONFIG_QUOTA
1073         for (i = 0; i < EXT4_MAXQUOTAS; i++)
1074                 kfree(get_qf_name(sb, sbi, i));
1075 #endif
1076
1077         /* Debugging code just in case the in-memory inode orphan list
1078          * isn't empty.  The on-disk one can be non-empty if we've
1079          * detected an error and taken the fs readonly, but the
1080          * in-memory list had better be clean by this point. */
1081         if (!list_empty(&sbi->s_orphan))
1082                 dump_orphan_list(sb, sbi);
1083         J_ASSERT(list_empty(&sbi->s_orphan));
1084
1085         sync_blockdev(sb->s_bdev);
1086         invalidate_bdev(sb->s_bdev);
1087         if (sbi->s_journal_bdev && sbi->s_journal_bdev != sb->s_bdev) {
1088                 /*
1089                  * Invalidate the journal device's buffers.  We don't want them
1090                  * floating about in memory - the physical journal device may
1091                  * hotswapped, and it breaks the `ro-after' testing code.
1092                  */
1093                 sync_blockdev(sbi->s_journal_bdev);
1094                 invalidate_bdev(sbi->s_journal_bdev);
1095                 ext4_blkdev_remove(sbi);
1096         }
1097
1098         ext4_xattr_destroy_cache(sbi->s_ea_inode_cache);
1099         sbi->s_ea_inode_cache = NULL;
1100
1101         ext4_xattr_destroy_cache(sbi->s_ea_block_cache);
1102         sbi->s_ea_block_cache = NULL;
1103
1104         if (sbi->s_mmp_tsk)
1105                 kthread_stop(sbi->s_mmp_tsk);
1106         brelse(sbi->s_sbh);
1107         sb->s_fs_info = NULL;
1108         /*
1109          * Now that we are completely done shutting down the
1110          * superblock, we need to actually destroy the kobject.
1111          */
1112         kobject_put(&sbi->s_kobj);
1113         wait_for_completion(&sbi->s_kobj_unregister);
1114         if (sbi->s_chksum_driver)
1115                 crypto_free_shash(sbi->s_chksum_driver);
1116         kfree(sbi->s_blockgroup_lock);
1117         fs_put_dax(sbi->s_daxdev);
1118         fscrypt_free_dummy_context(&sbi->s_dummy_enc_ctx);
1119 #ifdef CONFIG_UNICODE
1120         utf8_unload(sbi->s_encoding);
1121 #endif
1122         kfree(sbi);
1123 }
1124
1125 static struct kmem_cache *ext4_inode_cachep;
1126
1127 /*
1128  * Called inside transaction, so use GFP_NOFS
1129  */
1130 static struct inode *ext4_alloc_inode(struct super_block *sb)
1131 {
1132         struct ext4_inode_info *ei;
1133
1134         ei = kmem_cache_alloc(ext4_inode_cachep, GFP_NOFS);
1135         if (!ei)
1136                 return NULL;
1137
1138         inode_set_iversion(&ei->vfs_inode, 1);
1139         spin_lock_init(&ei->i_raw_lock);
1140         INIT_LIST_HEAD(&ei->i_prealloc_list);
1141         atomic_set(&ei->i_prealloc_active, 0);
1142         spin_lock_init(&ei->i_prealloc_lock);
1143         ext4_es_init_tree(&ei->i_es_tree);
1144         rwlock_init(&ei->i_es_lock);
1145         INIT_LIST_HEAD(&ei->i_es_list);
1146         ei->i_es_all_nr = 0;
1147         ei->i_es_shk_nr = 0;
1148         ei->i_es_shrink_lblk = 0;
1149         ei->i_reserved_data_blocks = 0;
1150         spin_lock_init(&(ei->i_block_reservation_lock));
1151         ext4_init_pending_tree(&ei->i_pending_tree);
1152 #ifdef CONFIG_QUOTA
1153         ei->i_reserved_quota = 0;
1154         memset(&ei->i_dquot, 0, sizeof(ei->i_dquot));
1155 #endif
1156         ei->jinode = NULL;
1157         INIT_LIST_HEAD(&ei->i_rsv_conversion_list);
1158         spin_lock_init(&ei->i_completed_io_lock);
1159         ei->i_sync_tid = 0;
1160         ei->i_datasync_tid = 0;
1161         atomic_set(&ei->i_unwritten, 0);
1162         INIT_WORK(&ei->i_rsv_conversion_work, ext4_end_io_rsv_work);
1163         return &ei->vfs_inode;
1164 }
1165
1166 static int ext4_drop_inode(struct inode *inode)
1167 {
1168         int drop = generic_drop_inode(inode);
1169
1170         if (!drop)
1171                 drop = fscrypt_drop_inode(inode);
1172
1173         trace_ext4_drop_inode(inode, drop);
1174         return drop;
1175 }
1176
1177 static void ext4_free_in_core_inode(struct inode *inode)
1178 {
1179         fscrypt_free_inode(inode);
1180         kmem_cache_free(ext4_inode_cachep, EXT4_I(inode));
1181 }
1182
1183 static void ext4_destroy_inode(struct inode *inode)
1184 {
1185         if (!list_empty(&(EXT4_I(inode)->i_orphan))) {
1186                 ext4_msg(inode->i_sb, KERN_ERR,
1187                          "Inode %lu (%p): orphan list check failed!",
1188                          inode->i_ino, EXT4_I(inode));
1189                 print_hex_dump(KERN_INFO, "", DUMP_PREFIX_ADDRESS, 16, 4,
1190                                 EXT4_I(inode), sizeof(struct ext4_inode_info),
1191                                 true);
1192                 dump_stack();
1193         }
1194 }
1195
1196 static void init_once(void *foo)
1197 {
1198         struct ext4_inode_info *ei = (struct ext4_inode_info *) foo;
1199
1200         INIT_LIST_HEAD(&ei->i_orphan);
1201         init_rwsem(&ei->xattr_sem);
1202         init_rwsem(&ei->i_data_sem);
1203         init_rwsem(&ei->i_mmap_sem);
1204         inode_init_once(&ei->vfs_inode);
1205 }
1206
1207 static int __init init_inodecache(void)
1208 {
1209         ext4_inode_cachep = kmem_cache_create_usercopy("ext4_inode_cache",
1210                                 sizeof(struct ext4_inode_info), 0,
1211                                 (SLAB_RECLAIM_ACCOUNT|SLAB_MEM_SPREAD|
1212                                         SLAB_ACCOUNT),
1213                                 offsetof(struct ext4_inode_info, i_data),
1214                                 sizeof_field(struct ext4_inode_info, i_data),
1215                                 init_once);
1216         if (ext4_inode_cachep == NULL)
1217                 return -ENOMEM;
1218         return 0;
1219 }
1220
1221 static void destroy_inodecache(void)
1222 {
1223         /*
1224          * Make sure all delayed rcu free inodes are flushed before we
1225          * destroy cache.
1226          */
1227         rcu_barrier();
1228         kmem_cache_destroy(ext4_inode_cachep);
1229 }
1230
1231 void ext4_clear_inode(struct inode *inode)
1232 {
1233         invalidate_inode_buffers(inode);
1234         clear_inode(inode);
1235         ext4_discard_preallocations(inode, 0);
1236         ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS);
1237         dquot_drop(inode);
1238         if (EXT4_I(inode)->jinode) {
1239                 jbd2_journal_release_jbd_inode(EXT4_JOURNAL(inode),
1240                                                EXT4_I(inode)->jinode);
1241                 jbd2_free_inode(EXT4_I(inode)->jinode);
1242                 EXT4_I(inode)->jinode = NULL;
1243         }
1244         fscrypt_put_encryption_info(inode);
1245         fsverity_cleanup_inode(inode);
1246 }
1247
1248 static struct inode *ext4_nfs_get_inode(struct super_block *sb,
1249                                         u64 ino, u32 generation)
1250 {
1251         struct inode *inode;
1252
1253         /*
1254          * Currently we don't know the generation for parent directory, so
1255          * a generation of 0 means "accept any"
1256          */
1257         inode = ext4_iget(sb, ino, EXT4_IGET_HANDLE);
1258         if (IS_ERR(inode))
1259                 return ERR_CAST(inode);
1260         if (generation && inode->i_generation != generation) {
1261                 iput(inode);
1262                 return ERR_PTR(-ESTALE);
1263         }
1264
1265         return inode;
1266 }
1267
1268 static struct dentry *ext4_fh_to_dentry(struct super_block *sb, struct fid *fid,
1269                                         int fh_len, int fh_type)
1270 {
1271         return generic_fh_to_dentry(sb, fid, fh_len, fh_type,
1272                                     ext4_nfs_get_inode);
1273 }
1274
1275 static struct dentry *ext4_fh_to_parent(struct super_block *sb, struct fid *fid,
1276                                         int fh_len, int fh_type)
1277 {
1278         return generic_fh_to_parent(sb, fid, fh_len, fh_type,
1279                                     ext4_nfs_get_inode);
1280 }
1281
1282 static int ext4_nfs_commit_metadata(struct inode *inode)
1283 {
1284         struct writeback_control wbc = {
1285                 .sync_mode = WB_SYNC_ALL
1286         };
1287
1288         trace_ext4_nfs_commit_metadata(inode);
1289         return ext4_write_inode(inode, &wbc);
1290 }
1291
1292 /*
1293  * Try to release metadata pages (indirect blocks, directories) which are
1294  * mapped via the block device.  Since these pages could have journal heads
1295  * which would prevent try_to_free_buffers() from freeing them, we must use
1296  * jbd2 layer's try_to_free_buffers() function to release them.
1297  */
1298 static int bdev_try_to_free_page(struct super_block *sb, struct page *page,
1299                                  gfp_t wait)
1300 {
1301         journal_t *journal = EXT4_SB(sb)->s_journal;
1302
1303         WARN_ON(PageChecked(page));
1304         if (!page_has_buffers(page))
1305                 return 0;
1306         if (journal)
1307                 return jbd2_journal_try_to_free_buffers(journal, page);
1308
1309         return try_to_free_buffers(page);
1310 }
1311
1312 #ifdef CONFIG_FS_ENCRYPTION
1313 static int ext4_get_context(struct inode *inode, void *ctx, size_t len)
1314 {
1315         return ext4_xattr_get(inode, EXT4_XATTR_INDEX_ENCRYPTION,
1316                                  EXT4_XATTR_NAME_ENCRYPTION_CONTEXT, ctx, len);
1317 }
1318
1319 static int ext4_set_context(struct inode *inode, const void *ctx, size_t len,
1320                                                         void *fs_data)
1321 {
1322         handle_t *handle = fs_data;
1323         int res, res2, credits, retries = 0;
1324
1325         /*
1326          * Encrypting the root directory is not allowed because e2fsck expects
1327          * lost+found to exist and be unencrypted, and encrypting the root
1328          * directory would imply encrypting the lost+found directory as well as
1329          * the filename "lost+found" itself.
1330          */
1331         if (inode->i_ino == EXT4_ROOT_INO)
1332                 return -EPERM;
1333
1334         if (WARN_ON_ONCE(IS_DAX(inode) && i_size_read(inode)))
1335                 return -EINVAL;
1336
1337         if (ext4_test_inode_flag(inode, EXT4_INODE_DAX))
1338                 return -EOPNOTSUPP;
1339
1340         res = ext4_convert_inline_data(inode);
1341         if (res)
1342                 return res;
1343
1344         /*
1345          * If a journal handle was specified, then the encryption context is
1346          * being set on a new inode via inheritance and is part of a larger
1347          * transaction to create the inode.  Otherwise the encryption context is
1348          * being set on an existing inode in its own transaction.  Only in the
1349          * latter case should the "retry on ENOSPC" logic be used.
1350          */
1351
1352         if (handle) {
1353                 res = ext4_xattr_set_handle(handle, inode,
1354                                             EXT4_XATTR_INDEX_ENCRYPTION,
1355                                             EXT4_XATTR_NAME_ENCRYPTION_CONTEXT,
1356                                             ctx, len, 0);
1357                 if (!res) {
1358                         ext4_set_inode_flag(inode, EXT4_INODE_ENCRYPT);
1359                         ext4_clear_inode_state(inode,
1360                                         EXT4_STATE_MAY_INLINE_DATA);
1361                         /*
1362                          * Update inode->i_flags - S_ENCRYPTED will be enabled,
1363                          * S_DAX may be disabled
1364                          */
1365                         ext4_set_inode_flags(inode, false);
1366                 }
1367                 return res;
1368         }
1369
1370         res = dquot_initialize(inode);
1371         if (res)
1372                 return res;
1373 retry:
1374         res = ext4_xattr_set_credits(inode, len, false /* is_create */,
1375                                      &credits);
1376         if (res)
1377                 return res;
1378
1379         handle = ext4_journal_start(inode, EXT4_HT_MISC, credits);
1380         if (IS_ERR(handle))
1381                 return PTR_ERR(handle);
1382
1383         res = ext4_xattr_set_handle(handle, inode, EXT4_XATTR_INDEX_ENCRYPTION,
1384                                     EXT4_XATTR_NAME_ENCRYPTION_CONTEXT,
1385                                     ctx, len, 0);
1386         if (!res) {
1387                 ext4_set_inode_flag(inode, EXT4_INODE_ENCRYPT);
1388                 /*
1389                  * Update inode->i_flags - S_ENCRYPTED will be enabled,
1390                  * S_DAX may be disabled
1391                  */
1392                 ext4_set_inode_flags(inode, false);
1393                 res = ext4_mark_inode_dirty(handle, inode);
1394                 if (res)
1395                         EXT4_ERROR_INODE(inode, "Failed to mark inode dirty");
1396         }
1397         res2 = ext4_journal_stop(handle);
1398
1399         if (res == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
1400                 goto retry;
1401         if (!res)
1402                 res = res2;
1403         return res;
1404 }
1405
1406 static const union fscrypt_context *
1407 ext4_get_dummy_context(struct super_block *sb)
1408 {
1409         return EXT4_SB(sb)->s_dummy_enc_ctx.ctx;
1410 }
1411
1412 static bool ext4_has_stable_inodes(struct super_block *sb)
1413 {
1414         return ext4_has_feature_stable_inodes(sb);
1415 }
1416
1417 static void ext4_get_ino_and_lblk_bits(struct super_block *sb,
1418                                        int *ino_bits_ret, int *lblk_bits_ret)
1419 {
1420         *ino_bits_ret = 8 * sizeof(EXT4_SB(sb)->s_es->s_inodes_count);
1421         *lblk_bits_ret = 8 * sizeof(ext4_lblk_t);
1422 }
1423
1424 static const struct fscrypt_operations ext4_cryptops = {
1425         .key_prefix             = "ext4:",
1426         .get_context            = ext4_get_context,
1427         .set_context            = ext4_set_context,
1428         .get_dummy_context      = ext4_get_dummy_context,
1429         .empty_dir              = ext4_empty_dir,
1430         .max_namelen            = EXT4_NAME_LEN,
1431         .has_stable_inodes      = ext4_has_stable_inodes,
1432         .get_ino_and_lblk_bits  = ext4_get_ino_and_lblk_bits,
1433 };
1434 #endif
1435
1436 #ifdef CONFIG_QUOTA
1437 static const char * const quotatypes[] = INITQFNAMES;
1438 #define QTYPE2NAME(t) (quotatypes[t])
1439
1440 static int ext4_write_dquot(struct dquot *dquot);
1441 static int ext4_acquire_dquot(struct dquot *dquot);
1442 static int ext4_release_dquot(struct dquot *dquot);
1443 static int ext4_mark_dquot_dirty(struct dquot *dquot);
1444 static int ext4_write_info(struct super_block *sb, int type);
1445 static int ext4_quota_on(struct super_block *sb, int type, int format_id,
1446                          const struct path *path);
1447 static int ext4_quota_on_mount(struct super_block *sb, int type);
1448 static ssize_t ext4_quota_read(struct super_block *sb, int type, char *data,
1449                                size_t len, loff_t off);
1450 static ssize_t ext4_quota_write(struct super_block *sb, int type,
1451                                 const char *data, size_t len, loff_t off);
1452 static int ext4_quota_enable(struct super_block *sb, int type, int format_id,
1453                              unsigned int flags);
1454 static int ext4_enable_quotas(struct super_block *sb);
1455
1456 static struct dquot **ext4_get_dquots(struct inode *inode)
1457 {
1458         return EXT4_I(inode)->i_dquot;
1459 }
1460
1461 static const struct dquot_operations ext4_quota_operations = {
1462         .get_reserved_space     = ext4_get_reserved_space,
1463         .write_dquot            = ext4_write_dquot,
1464         .acquire_dquot          = ext4_acquire_dquot,
1465         .release_dquot          = ext4_release_dquot,
1466         .mark_dirty             = ext4_mark_dquot_dirty,
1467         .write_info             = ext4_write_info,
1468         .alloc_dquot            = dquot_alloc,
1469         .destroy_dquot          = dquot_destroy,
1470         .get_projid             = ext4_get_projid,
1471         .get_inode_usage        = ext4_get_inode_usage,
1472         .get_next_id            = dquot_get_next_id,
1473 };
1474
1475 static const struct quotactl_ops ext4_qctl_operations = {
1476         .quota_on       = ext4_quota_on,
1477         .quota_off      = ext4_quota_off,
1478         .quota_sync     = dquot_quota_sync,
1479         .get_state      = dquot_get_state,
1480         .set_info       = dquot_set_dqinfo,
1481         .get_dqblk      = dquot_get_dqblk,
1482         .set_dqblk      = dquot_set_dqblk,
1483         .get_nextdqblk  = dquot_get_next_dqblk,
1484 };
1485 #endif
1486
1487 static const struct super_operations ext4_sops = {
1488         .alloc_inode    = ext4_alloc_inode,
1489         .free_inode     = ext4_free_in_core_inode,
1490         .destroy_inode  = ext4_destroy_inode,
1491         .write_inode    = ext4_write_inode,
1492         .dirty_inode    = ext4_dirty_inode,
1493         .drop_inode     = ext4_drop_inode,
1494         .evict_inode    = ext4_evict_inode,
1495         .put_super      = ext4_put_super,
1496         .sync_fs        = ext4_sync_fs,
1497         .freeze_fs      = ext4_freeze,
1498         .unfreeze_fs    = ext4_unfreeze,
1499         .statfs         = ext4_statfs,
1500         .remount_fs     = ext4_remount,
1501         .show_options   = ext4_show_options,
1502 #ifdef CONFIG_QUOTA
1503         .quota_read     = ext4_quota_read,
1504         .quota_write    = ext4_quota_write,
1505         .get_dquots     = ext4_get_dquots,
1506 #endif
1507         .bdev_try_to_free_page = bdev_try_to_free_page,
1508 };
1509
1510 static const struct export_operations ext4_export_ops = {
1511         .fh_to_dentry = ext4_fh_to_dentry,
1512         .fh_to_parent = ext4_fh_to_parent,
1513         .get_parent = ext4_get_parent,
1514         .commit_metadata = ext4_nfs_commit_metadata,
1515 };
1516
1517 enum {
1518         Opt_bsd_df, Opt_minix_df, Opt_grpid, Opt_nogrpid,
1519         Opt_resgid, Opt_resuid, Opt_sb, Opt_err_cont, Opt_err_panic, Opt_err_ro,
1520         Opt_nouid32, Opt_debug, Opt_removed,
1521         Opt_user_xattr, Opt_nouser_xattr, Opt_acl, Opt_noacl,
1522         Opt_auto_da_alloc, Opt_noauto_da_alloc, Opt_noload,
1523         Opt_commit, Opt_min_batch_time, Opt_max_batch_time, Opt_journal_dev,
1524         Opt_journal_path, Opt_journal_checksum, Opt_journal_async_commit,
1525         Opt_abort, Opt_data_journal, Opt_data_ordered, Opt_data_writeback,
1526         Opt_data_err_abort, Opt_data_err_ignore, Opt_test_dummy_encryption,
1527         Opt_inlinecrypt,
1528         Opt_usrjquota, Opt_grpjquota, Opt_offusrjquota, Opt_offgrpjquota,
1529         Opt_jqfmt_vfsold, Opt_jqfmt_vfsv0, Opt_jqfmt_vfsv1, Opt_quota,
1530         Opt_noquota, Opt_barrier, Opt_nobarrier, Opt_err,
1531         Opt_usrquota, Opt_grpquota, Opt_prjquota, Opt_i_version,
1532         Opt_dax, Opt_dax_always, Opt_dax_inode, Opt_dax_never,
1533         Opt_stripe, Opt_delalloc, Opt_nodelalloc, Opt_warn_on_error,
1534         Opt_nowarn_on_error, Opt_mblk_io_submit,
1535         Opt_lazytime, Opt_nolazytime, Opt_debug_want_extra_isize,
1536         Opt_nomblk_io_submit, Opt_block_validity, Opt_noblock_validity,
1537         Opt_inode_readahead_blks, Opt_journal_ioprio,
1538         Opt_dioread_nolock, Opt_dioread_lock,
1539         Opt_discard, Opt_nodiscard, Opt_init_itable, Opt_noinit_itable,
1540         Opt_max_dir_size_kb, Opt_nojournal_checksum, Opt_nombcache,
1541         Opt_prefetch_block_bitmaps,
1542 };
1543
1544 static const match_table_t tokens = {
1545         {Opt_bsd_df, "bsddf"},
1546         {Opt_minix_df, "minixdf"},
1547         {Opt_grpid, "grpid"},
1548         {Opt_grpid, "bsdgroups"},
1549         {Opt_nogrpid, "nogrpid"},
1550         {Opt_nogrpid, "sysvgroups"},
1551         {Opt_resgid, "resgid=%u"},
1552         {Opt_resuid, "resuid=%u"},
1553         {Opt_sb, "sb=%u"},
1554         {Opt_err_cont, "errors=continue"},
1555         {Opt_err_panic, "errors=panic"},
1556         {Opt_err_ro, "errors=remount-ro"},
1557         {Opt_nouid32, "nouid32"},
1558         {Opt_debug, "debug"},
1559         {Opt_removed, "oldalloc"},
1560         {Opt_removed, "orlov"},
1561         {Opt_user_xattr, "user_xattr"},
1562         {Opt_nouser_xattr, "nouser_xattr"},
1563         {Opt_acl, "acl"},
1564         {Opt_noacl, "noacl"},
1565         {Opt_noload, "norecovery"},
1566         {Opt_noload, "noload"},
1567         {Opt_removed, "nobh"},
1568         {Opt_removed, "bh"},
1569         {Opt_commit, "commit=%u"},
1570         {Opt_min_batch_time, "min_batch_time=%u"},
1571         {Opt_max_batch_time, "max_batch_time=%u"},
1572         {Opt_journal_dev, "journal_dev=%u"},
1573         {Opt_journal_path, "journal_path=%s"},
1574         {Opt_journal_checksum, "journal_checksum"},
1575         {Opt_nojournal_checksum, "nojournal_checksum"},
1576         {Opt_journal_async_commit, "journal_async_commit"},
1577         {Opt_abort, "abort"},
1578         {Opt_data_journal, "data=journal"},
1579         {Opt_data_ordered, "data=ordered"},
1580         {Opt_data_writeback, "data=writeback"},
1581         {Opt_data_err_abort, "data_err=abort"},
1582         {Opt_data_err_ignore, "data_err=ignore"},
1583         {Opt_offusrjquota, "usrjquota="},
1584         {Opt_usrjquota, "usrjquota=%s"},
1585         {Opt_offgrpjquota, "grpjquota="},
1586         {Opt_grpjquota, "grpjquota=%s"},
1587         {Opt_jqfmt_vfsold, "jqfmt=vfsold"},
1588         {Opt_jqfmt_vfsv0, "jqfmt=vfsv0"},
1589         {Opt_jqfmt_vfsv1, "jqfmt=vfsv1"},
1590         {Opt_grpquota, "grpquota"},
1591         {Opt_noquota, "noquota"},
1592         {Opt_quota, "quota"},
1593         {Opt_usrquota, "usrquota"},
1594         {Opt_prjquota, "prjquota"},
1595         {Opt_barrier, "barrier=%u"},
1596         {Opt_barrier, "barrier"},
1597         {Opt_nobarrier, "nobarrier"},
1598         {Opt_i_version, "i_version"},
1599         {Opt_dax, "dax"},
1600         {Opt_dax_always, "dax=always"},
1601         {Opt_dax_inode, "dax=inode"},
1602         {Opt_dax_never, "dax=never"},
1603         {Opt_stripe, "stripe=%u"},
1604         {Opt_delalloc, "delalloc"},
1605         {Opt_warn_on_error, "warn_on_error"},
1606         {Opt_nowarn_on_error, "nowarn_on_error"},
1607         {Opt_lazytime, "lazytime"},
1608         {Opt_nolazytime, "nolazytime"},
1609         {Opt_debug_want_extra_isize, "debug_want_extra_isize=%u"},
1610         {Opt_nodelalloc, "nodelalloc"},
1611         {Opt_removed, "mblk_io_submit"},
1612         {Opt_removed, "nomblk_io_submit"},
1613         {Opt_block_validity, "block_validity"},
1614         {Opt_noblock_validity, "noblock_validity"},
1615         {Opt_inode_readahead_blks, "inode_readahead_blks=%u"},
1616         {Opt_journal_ioprio, "journal_ioprio=%u"},
1617         {Opt_auto_da_alloc, "auto_da_alloc=%u"},
1618         {Opt_auto_da_alloc, "auto_da_alloc"},
1619         {Opt_noauto_da_alloc, "noauto_da_alloc"},
1620         {Opt_dioread_nolock, "dioread_nolock"},
1621         {Opt_dioread_lock, "nodioread_nolock"},
1622         {Opt_dioread_lock, "dioread_lock"},
1623         {Opt_discard, "discard"},
1624         {Opt_nodiscard, "nodiscard"},
1625         {Opt_init_itable, "init_itable=%u"},
1626         {Opt_init_itable, "init_itable"},
1627         {Opt_noinit_itable, "noinit_itable"},
1628         {Opt_max_dir_size_kb, "max_dir_size_kb=%u"},
1629         {Opt_test_dummy_encryption, "test_dummy_encryption=%s"},
1630         {Opt_test_dummy_encryption, "test_dummy_encryption"},
1631         {Opt_inlinecrypt, "inlinecrypt"},
1632         {Opt_nombcache, "nombcache"},
1633         {Opt_nombcache, "no_mbcache"},  /* for backward compatibility */
1634         {Opt_prefetch_block_bitmaps, "prefetch_block_bitmaps"},
1635         {Opt_removed, "check=none"},    /* mount option from ext2/3 */
1636         {Opt_removed, "nocheck"},       /* mount option from ext2/3 */
1637         {Opt_removed, "reservation"},   /* mount option from ext2/3 */
1638         {Opt_removed, "noreservation"}, /* mount option from ext2/3 */
1639         {Opt_removed, "journal=%u"},    /* mount option from ext2/3 */
1640         {Opt_err, NULL},
1641 };
1642
1643 static ext4_fsblk_t get_sb_block(void **data)
1644 {
1645         ext4_fsblk_t    sb_block;
1646         char            *options = (char *) *data;
1647
1648         if (!options || strncmp(options, "sb=", 3) != 0)
1649                 return 1;       /* Default location */
1650
1651         options += 3;
1652         /* TODO: use simple_strtoll with >32bit ext4 */
1653         sb_block = simple_strtoul(options, &options, 0);
1654         if (*options && *options != ',') {
1655                 printk(KERN_ERR "EXT4-fs: Invalid sb specification: %s\n",
1656                        (char *) *data);
1657                 return 1;
1658         }
1659         if (*options == ',')
1660                 options++;
1661         *data = (void *) options;
1662
1663         return sb_block;
1664 }
1665
1666 #define DEFAULT_JOURNAL_IOPRIO (IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 3))
1667 static const char deprecated_msg[] =
1668         "Mount option \"%s\" will be removed by %s\n"
1669         "Contact linux-ext4@vger.kernel.org if you think we should keep it.\n";
1670
1671 #ifdef CONFIG_QUOTA
1672 static int set_qf_name(struct super_block *sb, int qtype, substring_t *args)
1673 {
1674         struct ext4_sb_info *sbi = EXT4_SB(sb);
1675         char *qname, *old_qname = get_qf_name(sb, sbi, qtype);
1676         int ret = -1;
1677
1678         if (sb_any_quota_loaded(sb) && !old_qname) {
1679                 ext4_msg(sb, KERN_ERR,
1680                         "Cannot change journaled "
1681                         "quota options when quota turned on");
1682                 return -1;
1683         }
1684         if (ext4_has_feature_quota(sb)) {
1685                 ext4_msg(sb, KERN_INFO, "Journaled quota options "
1686                          "ignored when QUOTA feature is enabled");
1687                 return 1;
1688         }
1689         qname = match_strdup(args);
1690         if (!qname) {
1691                 ext4_msg(sb, KERN_ERR,
1692                         "Not enough memory for storing quotafile name");
1693                 return -1;
1694         }
1695         if (old_qname) {
1696                 if (strcmp(old_qname, qname) == 0)
1697                         ret = 1;
1698                 else
1699                         ext4_msg(sb, KERN_ERR,
1700                                  "%s quota file already specified",
1701                                  QTYPE2NAME(qtype));
1702                 goto errout;
1703         }
1704         if (strchr(qname, '/')) {
1705                 ext4_msg(sb, KERN_ERR,
1706                         "quotafile must be on filesystem root");
1707                 goto errout;
1708         }
1709         rcu_assign_pointer(sbi->s_qf_names[qtype], qname);
1710         set_opt(sb, QUOTA);
1711         return 1;
1712 errout:
1713         kfree(qname);
1714         return ret;
1715 }
1716
1717 static int clear_qf_name(struct super_block *sb, int qtype)
1718 {
1719
1720         struct ext4_sb_info *sbi = EXT4_SB(sb);
1721         char *old_qname = get_qf_name(sb, sbi, qtype);
1722
1723         if (sb_any_quota_loaded(sb) && old_qname) {
1724                 ext4_msg(sb, KERN_ERR, "Cannot change journaled quota options"
1725                         " when quota turned on");
1726                 return -1;
1727         }
1728         rcu_assign_pointer(sbi->s_qf_names[qtype], NULL);
1729         synchronize_rcu();
1730         kfree(old_qname);
1731         return 1;
1732 }
1733 #endif
1734
1735 #define MOPT_SET        0x0001
1736 #define MOPT_CLEAR      0x0002
1737 #define MOPT_NOSUPPORT  0x0004
1738 #define MOPT_EXPLICIT   0x0008
1739 #define MOPT_CLEAR_ERR  0x0010
1740 #define MOPT_GTE0       0x0020
1741 #ifdef CONFIG_QUOTA
1742 #define MOPT_Q          0
1743 #define MOPT_QFMT       0x0040
1744 #else
1745 #define MOPT_Q          MOPT_NOSUPPORT
1746 #define MOPT_QFMT       MOPT_NOSUPPORT
1747 #endif
1748 #define MOPT_DATAJ      0x0080
1749 #define MOPT_NO_EXT2    0x0100
1750 #define MOPT_NO_EXT3    0x0200
1751 #define MOPT_EXT4_ONLY  (MOPT_NO_EXT2 | MOPT_NO_EXT3)
1752 #define MOPT_STRING     0x0400
1753 #define MOPT_SKIP       0x0800
1754
1755 static const struct mount_opts {
1756         int     token;
1757         int     mount_opt;
1758         int     flags;
1759 } ext4_mount_opts[] = {
1760         {Opt_minix_df, EXT4_MOUNT_MINIX_DF, MOPT_SET},
1761         {Opt_bsd_df, EXT4_MOUNT_MINIX_DF, MOPT_CLEAR},
1762         {Opt_grpid, EXT4_MOUNT_GRPID, MOPT_SET},
1763         {Opt_nogrpid, EXT4_MOUNT_GRPID, MOPT_CLEAR},
1764         {Opt_block_validity, EXT4_MOUNT_BLOCK_VALIDITY, MOPT_SET},
1765         {Opt_noblock_validity, EXT4_MOUNT_BLOCK_VALIDITY, MOPT_CLEAR},
1766         {Opt_dioread_nolock, EXT4_MOUNT_DIOREAD_NOLOCK,
1767          MOPT_EXT4_ONLY | MOPT_SET},
1768         {Opt_dioread_lock, EXT4_MOUNT_DIOREAD_NOLOCK,
1769          MOPT_EXT4_ONLY | MOPT_CLEAR},
1770         {Opt_discard, EXT4_MOUNT_DISCARD, MOPT_SET},
1771         {Opt_nodiscard, EXT4_MOUNT_DISCARD, MOPT_CLEAR},
1772         {Opt_delalloc, EXT4_MOUNT_DELALLOC,
1773          MOPT_EXT4_ONLY | MOPT_SET | MOPT_EXPLICIT},
1774         {Opt_nodelalloc, EXT4_MOUNT_DELALLOC,
1775          MOPT_EXT4_ONLY | MOPT_CLEAR},
1776         {Opt_warn_on_error, EXT4_MOUNT_WARN_ON_ERROR, MOPT_SET},
1777         {Opt_nowarn_on_error, EXT4_MOUNT_WARN_ON_ERROR, MOPT_CLEAR},
1778         {Opt_nojournal_checksum, EXT4_MOUNT_JOURNAL_CHECKSUM,
1779          MOPT_EXT4_ONLY | MOPT_CLEAR},
1780         {Opt_journal_checksum, EXT4_MOUNT_JOURNAL_CHECKSUM,
1781          MOPT_EXT4_ONLY | MOPT_SET | MOPT_EXPLICIT},
1782         {Opt_journal_async_commit, (EXT4_MOUNT_JOURNAL_ASYNC_COMMIT |
1783                                     EXT4_MOUNT_JOURNAL_CHECKSUM),
1784          MOPT_EXT4_ONLY | MOPT_SET | MOPT_EXPLICIT},
1785         {Opt_noload, EXT4_MOUNT_NOLOAD, MOPT_NO_EXT2 | MOPT_SET},
1786         {Opt_err_panic, EXT4_MOUNT_ERRORS_PANIC, MOPT_SET | MOPT_CLEAR_ERR},
1787         {Opt_err_ro, EXT4_MOUNT_ERRORS_RO, MOPT_SET | MOPT_CLEAR_ERR},
1788         {Opt_err_cont, EXT4_MOUNT_ERRORS_CONT, MOPT_SET | MOPT_CLEAR_ERR},
1789         {Opt_data_err_abort, EXT4_MOUNT_DATA_ERR_ABORT,
1790          MOPT_NO_EXT2},
1791         {Opt_data_err_ignore, EXT4_MOUNT_DATA_ERR_ABORT,
1792          MOPT_NO_EXT2},
1793         {Opt_barrier, EXT4_MOUNT_BARRIER, MOPT_SET},
1794         {Opt_nobarrier, EXT4_MOUNT_BARRIER, MOPT_CLEAR},
1795         {Opt_noauto_da_alloc, EXT4_MOUNT_NO_AUTO_DA_ALLOC, MOPT_SET},
1796         {Opt_auto_da_alloc, EXT4_MOUNT_NO_AUTO_DA_ALLOC, MOPT_CLEAR},
1797         {Opt_noinit_itable, EXT4_MOUNT_INIT_INODE_TABLE, MOPT_CLEAR},
1798         {Opt_commit, 0, MOPT_GTE0},
1799         {Opt_max_batch_time, 0, MOPT_GTE0},
1800         {Opt_min_batch_time, 0, MOPT_GTE0},
1801         {Opt_inode_readahead_blks, 0, MOPT_GTE0},
1802         {Opt_init_itable, 0, MOPT_GTE0},
1803         {Opt_dax, EXT4_MOUNT_DAX_ALWAYS, MOPT_SET | MOPT_SKIP},
1804         {Opt_dax_always, EXT4_MOUNT_DAX_ALWAYS,
1805                 MOPT_EXT4_ONLY | MOPT_SET | MOPT_SKIP},
1806         {Opt_dax_inode, EXT4_MOUNT2_DAX_INODE,
1807                 MOPT_EXT4_ONLY | MOPT_SET | MOPT_SKIP},
1808         {Opt_dax_never, EXT4_MOUNT2_DAX_NEVER,
1809                 MOPT_EXT4_ONLY | MOPT_SET | MOPT_SKIP},
1810         {Opt_stripe, 0, MOPT_GTE0},
1811         {Opt_resuid, 0, MOPT_GTE0},
1812         {Opt_resgid, 0, MOPT_GTE0},
1813         {Opt_journal_dev, 0, MOPT_NO_EXT2 | MOPT_GTE0},
1814         {Opt_journal_path, 0, MOPT_NO_EXT2 | MOPT_STRING},
1815         {Opt_journal_ioprio, 0, MOPT_NO_EXT2 | MOPT_GTE0},
1816         {Opt_data_journal, EXT4_MOUNT_JOURNAL_DATA, MOPT_NO_EXT2 | MOPT_DATAJ},
1817         {Opt_data_ordered, EXT4_MOUNT_ORDERED_DATA, MOPT_NO_EXT2 | MOPT_DATAJ},
1818         {Opt_data_writeback, EXT4_MOUNT_WRITEBACK_DATA,
1819          MOPT_NO_EXT2 | MOPT_DATAJ},
1820         {Opt_user_xattr, EXT4_MOUNT_XATTR_USER, MOPT_SET},
1821         {Opt_nouser_xattr, EXT4_MOUNT_XATTR_USER, MOPT_CLEAR},
1822 #ifdef CONFIG_EXT4_FS_POSIX_ACL
1823         {Opt_acl, EXT4_MOUNT_POSIX_ACL, MOPT_SET},
1824         {Opt_noacl, EXT4_MOUNT_POSIX_ACL, MOPT_CLEAR},
1825 #else
1826         {Opt_acl, 0, MOPT_NOSUPPORT},
1827         {Opt_noacl, 0, MOPT_NOSUPPORT},
1828 #endif
1829         {Opt_nouid32, EXT4_MOUNT_NO_UID32, MOPT_SET},
1830         {Opt_debug, EXT4_MOUNT_DEBUG, MOPT_SET},
1831         {Opt_debug_want_extra_isize, 0, MOPT_GTE0},
1832         {Opt_quota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_USRQUOTA, MOPT_SET | MOPT_Q},
1833         {Opt_usrquota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_USRQUOTA,
1834                                                         MOPT_SET | MOPT_Q},
1835         {Opt_grpquota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_GRPQUOTA,
1836                                                         MOPT_SET | MOPT_Q},
1837         {Opt_prjquota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_PRJQUOTA,
1838                                                         MOPT_SET | MOPT_Q},
1839         {Opt_noquota, (EXT4_MOUNT_QUOTA | EXT4_MOUNT_USRQUOTA |
1840                        EXT4_MOUNT_GRPQUOTA | EXT4_MOUNT_PRJQUOTA),
1841                                                         MOPT_CLEAR | MOPT_Q},
1842         {Opt_usrjquota, 0, MOPT_Q},
1843         {Opt_grpjquota, 0, MOPT_Q},
1844         {Opt_offusrjquota, 0, MOPT_Q},
1845         {Opt_offgrpjquota, 0, MOPT_Q},
1846         {Opt_jqfmt_vfsold, QFMT_VFS_OLD, MOPT_QFMT},
1847         {Opt_jqfmt_vfsv0, QFMT_VFS_V0, MOPT_QFMT},
1848         {Opt_jqfmt_vfsv1, QFMT_VFS_V1, MOPT_QFMT},
1849         {Opt_max_dir_size_kb, 0, MOPT_GTE0},
1850         {Opt_test_dummy_encryption, 0, MOPT_STRING},
1851         {Opt_nombcache, EXT4_MOUNT_NO_MBCACHE, MOPT_SET},
1852         {Opt_prefetch_block_bitmaps, EXT4_MOUNT_PREFETCH_BLOCK_BITMAPS,
1853          MOPT_SET},
1854         {Opt_err, 0, 0}
1855 };
1856
1857 #ifdef CONFIG_UNICODE
1858 static const struct ext4_sb_encodings {
1859         __u16 magic;
1860         char *name;
1861         char *version;
1862 } ext4_sb_encoding_map[] = {
1863         {EXT4_ENC_UTF8_12_1, "utf8", "12.1.0"},
1864 };
1865
1866 static int ext4_sb_read_encoding(const struct ext4_super_block *es,
1867                                  const struct ext4_sb_encodings **encoding,
1868                                  __u16 *flags)
1869 {
1870         __u16 magic = le16_to_cpu(es->s_encoding);
1871         int i;
1872
1873         for (i = 0; i < ARRAY_SIZE(ext4_sb_encoding_map); i++)
1874                 if (magic == ext4_sb_encoding_map[i].magic)
1875                         break;
1876
1877         if (i >= ARRAY_SIZE(ext4_sb_encoding_map))
1878                 return -EINVAL;
1879
1880         *encoding = &ext4_sb_encoding_map[i];
1881         *flags = le16_to_cpu(es->s_encoding_flags);
1882
1883         return 0;
1884 }
1885 #endif
1886
1887 static int ext4_set_test_dummy_encryption(struct super_block *sb,
1888                                           const char *opt,
1889                                           const substring_t *arg,
1890                                           bool is_remount)
1891 {
1892 #ifdef CONFIG_FS_ENCRYPTION
1893         struct ext4_sb_info *sbi = EXT4_SB(sb);
1894         int err;
1895
1896         /*
1897          * This mount option is just for testing, and it's not worthwhile to
1898          * implement the extra complexity (e.g. RCU protection) that would be
1899          * needed to allow it to be set or changed during remount.  We do allow
1900          * it to be specified during remount, but only if there is no change.
1901          */
1902         if (is_remount && !sbi->s_dummy_enc_ctx.ctx) {
1903                 ext4_msg(sb, KERN_WARNING,
1904                          "Can't set test_dummy_encryption on remount");
1905                 return -1;
1906         }
1907         err = fscrypt_set_test_dummy_encryption(sb, arg, &sbi->s_dummy_enc_ctx);
1908         if (err) {
1909                 if (err == -EEXIST)
1910                         ext4_msg(sb, KERN_WARNING,
1911                                  "Can't change test_dummy_encryption on remount");
1912                 else if (err == -EINVAL)
1913                         ext4_msg(sb, KERN_WARNING,
1914                                  "Value of option \"%s\" is unrecognized", opt);
1915                 else
1916                         ext4_msg(sb, KERN_WARNING,
1917                                  "Error processing option \"%s\" [%d]",
1918                                  opt, err);
1919                 return -1;
1920         }
1921         ext4_msg(sb, KERN_WARNING, "Test dummy encryption mode enabled");
1922 #else
1923         ext4_msg(sb, KERN_WARNING,
1924                  "Test dummy encryption mount option ignored");
1925 #endif
1926         return 1;
1927 }
1928
1929 static int handle_mount_opt(struct super_block *sb, char *opt, int token,
1930                             substring_t *args, unsigned long *journal_devnum,
1931                             unsigned int *journal_ioprio, int is_remount)
1932 {
1933         struct ext4_sb_info *sbi = EXT4_SB(sb);
1934         const struct mount_opts *m;
1935         kuid_t uid;
1936         kgid_t gid;
1937         int arg = 0;
1938
1939 #ifdef CONFIG_QUOTA
1940         if (token == Opt_usrjquota)
1941                 return set_qf_name(sb, USRQUOTA, &args[0]);
1942         else if (token == Opt_grpjquota)
1943                 return set_qf_name(sb, GRPQUOTA, &args[0]);
1944         else if (token == Opt_offusrjquota)
1945                 return clear_qf_name(sb, USRQUOTA);
1946         else if (token == Opt_offgrpjquota)
1947                 return clear_qf_name(sb, GRPQUOTA);
1948 #endif
1949         switch (token) {
1950         case Opt_noacl:
1951         case Opt_nouser_xattr:
1952                 ext4_msg(sb, KERN_WARNING, deprecated_msg, opt, "3.5");
1953                 break;
1954         case Opt_sb:
1955                 return 1;       /* handled by get_sb_block() */
1956         case Opt_removed:
1957                 ext4_msg(sb, KERN_WARNING, "Ignoring removed %s option", opt);
1958                 return 1;
1959         case Opt_abort:
1960                 sbi->s_mount_flags |= EXT4_MF_FS_ABORTED;
1961                 return 1;
1962         case Opt_i_version:
1963                 sb->s_flags |= SB_I_VERSION;
1964                 return 1;
1965         case Opt_lazytime:
1966                 sb->s_flags |= SB_LAZYTIME;
1967                 return 1;
1968         case Opt_nolazytime:
1969                 sb->s_flags &= ~SB_LAZYTIME;
1970                 return 1;
1971         case Opt_inlinecrypt:
1972 #ifdef CONFIG_FS_ENCRYPTION_INLINE_CRYPT
1973                 sb->s_flags |= SB_INLINECRYPT;
1974 #else
1975                 ext4_msg(sb, KERN_ERR, "inline encryption not supported");
1976 #endif
1977                 return 1;
1978         }
1979
1980         for (m = ext4_mount_opts; m->token != Opt_err; m++)
1981                 if (token == m->token)
1982                         break;
1983
1984         if (m->token == Opt_err) {
1985                 ext4_msg(sb, KERN_ERR, "Unrecognized mount option \"%s\" "
1986                          "or missing value", opt);
1987                 return -1;
1988         }
1989
1990         if ((m->flags & MOPT_NO_EXT2) && IS_EXT2_SB(sb)) {
1991                 ext4_msg(sb, KERN_ERR,
1992                          "Mount option \"%s\" incompatible with ext2", opt);
1993                 return -1;
1994         }
1995         if ((m->flags & MOPT_NO_EXT3) && IS_EXT3_SB(sb)) {
1996                 ext4_msg(sb, KERN_ERR,
1997                          "Mount option \"%s\" incompatible with ext3", opt);
1998                 return -1;
1999         }
2000
2001         if (args->from && !(m->flags & MOPT_STRING) && match_int(args, &arg))
2002                 return -1;
2003         if (args->from && (m->flags & MOPT_GTE0) && (arg < 0))
2004                 return -1;
2005         if (m->flags & MOPT_EXPLICIT) {
2006                 if (m->mount_opt & EXT4_MOUNT_DELALLOC) {
2007                         set_opt2(sb, EXPLICIT_DELALLOC);
2008                 } else if (m->mount_opt & EXT4_MOUNT_JOURNAL_CHECKSUM) {
2009                         set_opt2(sb, EXPLICIT_JOURNAL_CHECKSUM);
2010                 } else
2011                         return -1;
2012         }
2013         if (m->flags & MOPT_CLEAR_ERR)
2014                 clear_opt(sb, ERRORS_MASK);
2015         if (token == Opt_noquota && sb_any_quota_loaded(sb)) {
2016                 ext4_msg(sb, KERN_ERR, "Cannot change quota "
2017                          "options when quota turned on");
2018                 return -1;
2019         }
2020
2021         if (m->flags & MOPT_NOSUPPORT) {
2022                 ext4_msg(sb, KERN_ERR, "%s option not supported", opt);
2023         } else if (token == Opt_commit) {
2024                 if (arg == 0)
2025                         arg = JBD2_DEFAULT_MAX_COMMIT_AGE;
2026                 else if (arg > INT_MAX / HZ) {
2027                         ext4_msg(sb, KERN_ERR,
2028                                  "Invalid commit interval %d, "
2029                                  "must be smaller than %d",
2030                                  arg, INT_MAX / HZ);
2031                         return -1;
2032                 }
2033                 sbi->s_commit_interval = HZ * arg;
2034         } else if (token == Opt_debug_want_extra_isize) {
2035                 if ((arg & 1) ||
2036                     (arg < 4) ||
2037                     (arg > (sbi->s_inode_size - EXT4_GOOD_OLD_INODE_SIZE))) {
2038                         ext4_msg(sb, KERN_ERR,
2039                                  "Invalid want_extra_isize %d", arg);
2040                         return -1;
2041                 }
2042                 sbi->s_want_extra_isize = arg;
2043         } else if (token == Opt_max_batch_time) {
2044                 sbi->s_max_batch_time = arg;
2045         } else if (token == Opt_min_batch_time) {
2046                 sbi->s_min_batch_time = arg;
2047         } else if (token == Opt_inode_readahead_blks) {
2048                 if (arg && (arg > (1 << 30) || !is_power_of_2(arg))) {
2049                         ext4_msg(sb, KERN_ERR,
2050                                  "EXT4-fs: inode_readahead_blks must be "
2051                                  "0 or a power of 2 smaller than 2^31");
2052                         return -1;
2053                 }
2054                 sbi->s_inode_readahead_blks = arg;
2055         } else if (token == Opt_init_itable) {
2056                 set_opt(sb, INIT_INODE_TABLE);
2057                 if (!args->from)
2058                         arg = EXT4_DEF_LI_WAIT_MULT;
2059                 sbi->s_li_wait_mult = arg;
2060         } else if (token == Opt_max_dir_size_kb) {
2061                 sbi->s_max_dir_size_kb = arg;
2062         } else if (token == Opt_stripe) {
2063                 sbi->s_stripe = arg;
2064         } else if (token == Opt_resuid) {
2065                 uid = make_kuid(current_user_ns(), arg);
2066                 if (!uid_valid(uid)) {
2067                         ext4_msg(sb, KERN_ERR, "Invalid uid value %d", arg);
2068                         return -1;
2069                 }
2070                 sbi->s_resuid = uid;
2071         } else if (token == Opt_resgid) {
2072                 gid = make_kgid(current_user_ns(), arg);
2073                 if (!gid_valid(gid)) {
2074                         ext4_msg(sb, KERN_ERR, "Invalid gid value %d", arg);
2075                         return -1;
2076                 }
2077                 sbi->s_resgid = gid;
2078         } else if (token == Opt_journal_dev) {
2079                 if (is_remount) {
2080                         ext4_msg(sb, KERN_ERR,
2081                                  "Cannot specify journal on remount");
2082                         return -1;
2083                 }
2084                 *journal_devnum = arg;
2085         } else if (token == Opt_journal_path) {
2086                 char *journal_path;
2087                 struct inode *journal_inode;
2088                 struct path path;
2089                 int error;
2090
2091                 if (is_remount) {
2092                         ext4_msg(sb, KERN_ERR,
2093                                  "Cannot specify journal on remount");
2094                         return -1;
2095                 }
2096                 journal_path = match_strdup(&args[0]);
2097                 if (!journal_path) {
2098                         ext4_msg(sb, KERN_ERR, "error: could not dup "
2099                                 "journal device string");
2100                         return -1;
2101                 }
2102
2103                 error = kern_path(journal_path, LOOKUP_FOLLOW, &path);
2104                 if (error) {
2105                         ext4_msg(sb, KERN_ERR, "error: could not find "
2106                                 "journal device path: error %d", error);
2107                         kfree(journal_path);
2108                         return -1;
2109                 }
2110
2111                 journal_inode = d_inode(path.dentry);
2112                 if (!S_ISBLK(journal_inode->i_mode)) {
2113                         ext4_msg(sb, KERN_ERR, "error: journal path %s "
2114                                 "is not a block device", journal_path);
2115                         path_put(&path);
2116                         kfree(journal_path);
2117                         return -1;
2118                 }
2119
2120                 *journal_devnum = new_encode_dev(journal_inode->i_rdev);
2121                 path_put(&path);
2122                 kfree(journal_path);
2123         } else if (token == Opt_journal_ioprio) {
2124                 if (arg > 7) {
2125                         ext4_msg(sb, KERN_ERR, "Invalid journal IO priority"
2126                                  " (must be 0-7)");
2127                         return -1;
2128                 }
2129                 *journal_ioprio =
2130                         IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, arg);
2131         } else if (token == Opt_test_dummy_encryption) {
2132                 return ext4_set_test_dummy_encryption(sb, opt, &args[0],
2133                                                       is_remount);
2134         } else if (m->flags & MOPT_DATAJ) {
2135                 if (is_remount) {
2136                         if (!sbi->s_journal)
2137                                 ext4_msg(sb, KERN_WARNING, "Remounting file system with no journal so ignoring journalled data option");
2138                         else if (test_opt(sb, DATA_FLAGS) != m->mount_opt) {
2139                                 ext4_msg(sb, KERN_ERR,
2140                                          "Cannot change data mode on remount");
2141                                 return -1;
2142                         }
2143                 } else {
2144                         clear_opt(sb, DATA_FLAGS);
2145                         sbi->s_mount_opt |= m->mount_opt;
2146                 }
2147 #ifdef CONFIG_QUOTA
2148         } else if (m->flags & MOPT_QFMT) {
2149                 if (sb_any_quota_loaded(sb) &&
2150                     sbi->s_jquota_fmt != m->mount_opt) {
2151                         ext4_msg(sb, KERN_ERR, "Cannot change journaled "
2152                                  "quota options when quota turned on");
2153                         return -1;
2154                 }
2155                 if (ext4_has_feature_quota(sb)) {
2156                         ext4_msg(sb, KERN_INFO,
2157                                  "Quota format mount options ignored "
2158                                  "when QUOTA feature is enabled");
2159                         return 1;
2160                 }
2161                 sbi->s_jquota_fmt = m->mount_opt;
2162 #endif
2163         } else if (token == Opt_dax || token == Opt_dax_always ||
2164                    token == Opt_dax_inode || token == Opt_dax_never) {
2165 #ifdef CONFIG_FS_DAX
2166                 switch (token) {
2167                 case Opt_dax:
2168                 case Opt_dax_always:
2169                         if (is_remount &&
2170                             (!(sbi->s_mount_opt & EXT4_MOUNT_DAX_ALWAYS) ||
2171                              (sbi->s_mount_opt2 & EXT4_MOUNT2_DAX_NEVER))) {
2172                         fail_dax_change_remount:
2173                                 ext4_msg(sb, KERN_ERR, "can't change "
2174                                          "dax mount option while remounting");
2175                                 return -1;
2176                         }
2177                         if (is_remount &&
2178                             (test_opt(sb, DATA_FLAGS) ==
2179                              EXT4_MOUNT_JOURNAL_DATA)) {
2180                                     ext4_msg(sb, KERN_ERR, "can't mount with "
2181                                              "both data=journal and dax");
2182                                     return -1;
2183                         }
2184                         ext4_msg(sb, KERN_WARNING,
2185                                 "DAX enabled. Warning: EXPERIMENTAL, use at your own risk");
2186                         sbi->s_mount_opt |= EXT4_MOUNT_DAX_ALWAYS;
2187                         sbi->s_mount_opt2 &= ~EXT4_MOUNT2_DAX_NEVER;
2188                         break;
2189                 case Opt_dax_never:
2190                         if (is_remount &&
2191                             (!(sbi->s_mount_opt2 & EXT4_MOUNT2_DAX_NEVER) ||
2192                              (sbi->s_mount_opt & EXT4_MOUNT_DAX_ALWAYS)))
2193                                 goto fail_dax_change_remount;
2194                         sbi->s_mount_opt2 |= EXT4_MOUNT2_DAX_NEVER;
2195                         sbi->s_mount_opt &= ~EXT4_MOUNT_DAX_ALWAYS;
2196                         break;
2197                 case Opt_dax_inode:
2198                         if (is_remount &&
2199                             ((sbi->s_mount_opt & EXT4_MOUNT_DAX_ALWAYS) ||
2200                              (sbi->s_mount_opt2 & EXT4_MOUNT2_DAX_NEVER) ||
2201                              !(sbi->s_mount_opt2 & EXT4_MOUNT2_DAX_INODE)))
2202                                 goto fail_dax_change_remount;
2203                         sbi->s_mount_opt &= ~EXT4_MOUNT_DAX_ALWAYS;
2204                         sbi->s_mount_opt2 &= ~EXT4_MOUNT2_DAX_NEVER;
2205                         /* Strictly for printing options */
2206                         sbi->s_mount_opt2 |= EXT4_MOUNT2_DAX_INODE;
2207                         break;
2208                 }
2209 #else
2210                 ext4_msg(sb, KERN_INFO, "dax option not supported");
2211                 sbi->s_mount_opt2 |= EXT4_MOUNT2_DAX_NEVER;
2212                 sbi->s_mount_opt &= ~EXT4_MOUNT_DAX_ALWAYS;
2213                 return -1;
2214 #endif
2215         } else if (token == Opt_data_err_abort) {
2216                 sbi->s_mount_opt |= m->mount_opt;
2217         } else if (token == Opt_data_err_ignore) {
2218                 sbi->s_mount_opt &= ~m->mount_opt;
2219         } else {
2220                 if (!args->from)
2221                         arg = 1;
2222                 if (m->flags & MOPT_CLEAR)
2223                         arg = !arg;
2224                 else if (unlikely(!(m->flags & MOPT_SET))) {
2225                         ext4_msg(sb, KERN_WARNING,
2226                                  "buggy handling of option %s", opt);
2227                         WARN_ON(1);
2228                         return -1;
2229                 }
2230                 if (arg != 0)
2231                         sbi->s_mount_opt |= m->mount_opt;
2232                 else
2233                         sbi->s_mount_opt &= ~m->mount_opt;
2234         }
2235         return 1;
2236 }
2237
2238 static int parse_options(char *options, struct super_block *sb,
2239                          unsigned long *journal_devnum,
2240                          unsigned int *journal_ioprio,
2241                          int is_remount)
2242 {
2243         struct ext4_sb_info __maybe_unused *sbi = EXT4_SB(sb);
2244         char *p, __maybe_unused *usr_qf_name, __maybe_unused *grp_qf_name;
2245         substring_t args[MAX_OPT_ARGS];
2246         int token;
2247
2248         if (!options)
2249                 return 1;
2250
2251         while ((p = strsep(&options, ",")) != NULL) {
2252                 if (!*p)
2253                         continue;
2254                 /*
2255                  * Initialize args struct so we know whether arg was
2256                  * found; some options take optional arguments.
2257                  */
2258                 args[0].to = args[0].from = NULL;
2259                 token = match_token(p, tokens, args);
2260                 if (handle_mount_opt(sb, p, token, args, journal_devnum,
2261                                      journal_ioprio, is_remount) < 0)
2262                         return 0;
2263         }
2264 #ifdef CONFIG_QUOTA
2265         /*
2266          * We do the test below only for project quotas. 'usrquota' and
2267          * 'grpquota' mount options are allowed even without quota feature
2268          * to support legacy quotas in quota files.
2269          */
2270         if (test_opt(sb, PRJQUOTA) && !ext4_has_feature_project(sb)) {
2271                 ext4_msg(sb, KERN_ERR, "Project quota feature not enabled. "
2272                          "Cannot enable project quota enforcement.");
2273                 return 0;
2274         }
2275         usr_qf_name = get_qf_name(sb, sbi, USRQUOTA);
2276         grp_qf_name = get_qf_name(sb, sbi, GRPQUOTA);
2277         if (usr_qf_name || grp_qf_name) {
2278                 if (test_opt(sb, USRQUOTA) && usr_qf_name)
2279                         clear_opt(sb, USRQUOTA);
2280
2281                 if (test_opt(sb, GRPQUOTA) && grp_qf_name)
2282                         clear_opt(sb, GRPQUOTA);
2283
2284                 if (test_opt(sb, GRPQUOTA) || test_opt(sb, USRQUOTA)) {
2285                         ext4_msg(sb, KERN_ERR, "old and new quota "
2286                                         "format mixing");
2287                         return 0;
2288                 }
2289
2290                 if (!sbi->s_jquota_fmt) {
2291                         ext4_msg(sb, KERN_ERR, "journaled quota format "
2292                                         "not specified");
2293                         return 0;
2294                 }
2295         }
2296 #endif
2297         if (test_opt(sb, DIOREAD_NOLOCK)) {
2298                 int blocksize =
2299                         BLOCK_SIZE << le32_to_cpu(sbi->s_es->s_log_block_size);
2300                 if (blocksize < PAGE_SIZE)
2301                         ext4_msg(sb, KERN_WARNING, "Warning: mounting with an "
2302                                  "experimental mount option 'dioread_nolock' "
2303                                  "for blocksize < PAGE_SIZE");
2304         }
2305         return 1;
2306 }
2307
2308 static inline void ext4_show_quota_options(struct seq_file *seq,
2309                                            struct super_block *sb)
2310 {
2311 #if defined(CONFIG_QUOTA)
2312         struct ext4_sb_info *sbi = EXT4_SB(sb);
2313         char *usr_qf_name, *grp_qf_name;
2314
2315         if (sbi->s_jquota_fmt) {
2316                 char *fmtname = "";
2317
2318                 switch (sbi->s_jquota_fmt) {
2319                 case QFMT_VFS_OLD:
2320                         fmtname = "vfsold";
2321                         break;
2322                 case QFMT_VFS_V0:
2323                         fmtname = "vfsv0";
2324                         break;
2325                 case QFMT_VFS_V1:
2326                         fmtname = "vfsv1";
2327                         break;
2328                 }
2329                 seq_printf(seq, ",jqfmt=%s", fmtname);
2330         }
2331
2332         rcu_read_lock();
2333         usr_qf_name = rcu_dereference(sbi->s_qf_names[USRQUOTA]);
2334         grp_qf_name = rcu_dereference(sbi->s_qf_names[GRPQUOTA]);
2335         if (usr_qf_name)
2336                 seq_show_option(seq, "usrjquota", usr_qf_name);
2337         if (grp_qf_name)
2338                 seq_show_option(seq, "grpjquota", grp_qf_name);
2339         rcu_read_unlock();
2340 #endif
2341 }
2342
2343 static const char *token2str(int token)
2344 {
2345         const struct match_token *t;
2346
2347         for (t = tokens; t->token != Opt_err; t++)
2348                 if (t->token == token && !strchr(t->pattern, '='))
2349                         break;
2350         return t->pattern;
2351 }
2352
2353 /*
2354  * Show an option if
2355  *  - it's set to a non-default value OR
2356  *  - if the per-sb default is different from the global default
2357  */
2358 static int _ext4_show_options(struct seq_file *seq, struct super_block *sb,
2359                               int nodefs)
2360 {
2361         struct ext4_sb_info *sbi = EXT4_SB(sb);
2362         struct ext4_super_block *es = sbi->s_es;
2363         int def_errors, def_mount_opt = sbi->s_def_mount_opt;
2364         const struct mount_opts *m;
2365         char sep = nodefs ? '\n' : ',';
2366
2367 #define SEQ_OPTS_PUTS(str) seq_printf(seq, "%c" str, sep)
2368 #define SEQ_OPTS_PRINT(str, arg) seq_printf(seq, "%c" str, sep, arg)
2369
2370         if (sbi->s_sb_block != 1)
2371                 SEQ_OPTS_PRINT("sb=%llu", sbi->s_sb_block);
2372
2373         for (m = ext4_mount_opts; m->token != Opt_err; m++) {
2374                 int want_set = m->flags & MOPT_SET;
2375                 if (((m->flags & (MOPT_SET|MOPT_CLEAR)) == 0) ||
2376                     (m->flags & MOPT_CLEAR_ERR) || m->flags & MOPT_SKIP)
2377                         continue;
2378                 if (!nodefs && !(m->mount_opt & (sbi->s_mount_opt ^ def_mount_opt)))
2379                         continue; /* skip if same as the default */
2380                 if ((want_set &&
2381                      (sbi->s_mount_opt & m->mount_opt) != m->mount_opt) ||
2382                     (!want_set && (sbi->s_mount_opt & m->mount_opt)))
2383                         continue; /* select Opt_noFoo vs Opt_Foo */
2384                 SEQ_OPTS_PRINT("%s", token2str(m->token));
2385         }
2386
2387         if (nodefs || !uid_eq(sbi->s_resuid, make_kuid(&init_user_ns, EXT4_DEF_RESUID)) ||
2388             le16_to_cpu(es->s_def_resuid) != EXT4_DEF_RESUID)
2389                 SEQ_OPTS_PRINT("resuid=%u",
2390                                 from_kuid_munged(&init_user_ns, sbi->s_resuid));
2391         if (nodefs || !gid_eq(sbi->s_resgid, make_kgid(&init_user_ns, EXT4_DEF_RESGID)) ||
2392             le16_to_cpu(es->s_def_resgid) != EXT4_DEF_RESGID)
2393                 SEQ_OPTS_PRINT("resgid=%u",
2394                                 from_kgid_munged(&init_user_ns, sbi->s_resgid));
2395         def_errors = nodefs ? -1 : le16_to_cpu(es->s_errors);
2396         if (test_opt(sb, ERRORS_RO) && def_errors != EXT4_ERRORS_RO)
2397                 SEQ_OPTS_PUTS("errors=remount-ro");
2398         if (test_opt(sb, ERRORS_CONT) && def_errors != EXT4_ERRORS_CONTINUE)
2399                 SEQ_OPTS_PUTS("errors=continue");
2400         if (test_opt(sb, ERRORS_PANIC) && def_errors != EXT4_ERRORS_PANIC)
2401                 SEQ_OPTS_PUTS("errors=panic");
2402         if (nodefs || sbi->s_commit_interval != JBD2_DEFAULT_MAX_COMMIT_AGE*HZ)
2403                 SEQ_OPTS_PRINT("commit=%lu", sbi->s_commit_interval / HZ);
2404         if (nodefs || sbi->s_min_batch_time != EXT4_DEF_MIN_BATCH_TIME)
2405                 SEQ_OPTS_PRINT("min_batch_time=%u", sbi->s_min_batch_time);
2406         if (nodefs || sbi->s_max_batch_time != EXT4_DEF_MAX_BATCH_TIME)
2407                 SEQ_OPTS_PRINT("max_batch_time=%u", sbi->s_max_batch_time);
2408         if (sb->s_flags & SB_I_VERSION)
2409                 SEQ_OPTS_PUTS("i_version");
2410         if (nodefs || sbi->s_stripe)
2411                 SEQ_OPTS_PRINT("stripe=%lu", sbi->s_stripe);
2412         if (nodefs || EXT4_MOUNT_DATA_FLAGS &
2413                         (sbi->s_mount_opt ^ def_mount_opt)) {
2414                 if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA)
2415                         SEQ_OPTS_PUTS("data=journal");
2416                 else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA)
2417                         SEQ_OPTS_PUTS("data=ordered");
2418                 else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_WRITEBACK_DATA)
2419                         SEQ_OPTS_PUTS("data=writeback");
2420         }
2421         if (nodefs ||
2422             sbi->s_inode_readahead_blks != EXT4_DEF_INODE_READAHEAD_BLKS)
2423                 SEQ_OPTS_PRINT("inode_readahead_blks=%u",
2424                                sbi->s_inode_readahead_blks);
2425
2426         if (test_opt(sb, INIT_INODE_TABLE) && (nodefs ||
2427                        (sbi->s_li_wait_mult != EXT4_DEF_LI_WAIT_MULT)))
2428                 SEQ_OPTS_PRINT("init_itable=%u", sbi->s_li_wait_mult);
2429         if (nodefs || sbi->s_max_dir_size_kb)
2430                 SEQ_OPTS_PRINT("max_dir_size_kb=%u", sbi->s_max_dir_size_kb);
2431         if (test_opt(sb, DATA_ERR_ABORT))
2432                 SEQ_OPTS_PUTS("data_err=abort");
2433
2434         fscrypt_show_test_dummy_encryption(seq, sep, sb);
2435
2436         if (sb->s_flags & SB_INLINECRYPT)
2437                 SEQ_OPTS_PUTS("inlinecrypt");
2438
2439         if (test_opt(sb, DAX_ALWAYS)) {
2440                 if (IS_EXT2_SB(sb))
2441                         SEQ_OPTS_PUTS("dax");
2442                 else
2443                         SEQ_OPTS_PUTS("dax=always");
2444         } else if (test_opt2(sb, DAX_NEVER)) {
2445                 SEQ_OPTS_PUTS("dax=never");
2446         } else if (test_opt2(sb, DAX_INODE)) {
2447                 SEQ_OPTS_PUTS("dax=inode");
2448         }
2449
2450         ext4_show_quota_options(seq, sb);
2451         return 0;
2452 }
2453
2454 static int ext4_show_options(struct seq_file *seq, struct dentry *root)
2455 {
2456         return _ext4_show_options(seq, root->d_sb, 0);
2457 }
2458
2459 int ext4_seq_options_show(struct seq_file *seq, void *offset)
2460 {
2461         struct super_block *sb = seq->private;
2462         int rc;
2463
2464         seq_puts(seq, sb_rdonly(sb) ? "ro" : "rw");
2465         rc = _ext4_show_options(seq, sb, 1);
2466         seq_puts(seq, "\n");
2467         return rc;
2468 }
2469
2470 static int ext4_setup_super(struct super_block *sb, struct ext4_super_block *es,
2471                             int read_only)
2472 {
2473         struct ext4_sb_info *sbi = EXT4_SB(sb);
2474         int err = 0;
2475
2476         if (le32_to_cpu(es->s_rev_level) > EXT4_MAX_SUPP_REV) {
2477                 ext4_msg(sb, KERN_ERR, "revision level too high, "
2478                          "forcing read-only mode");
2479                 err = -EROFS;
2480                 goto done;
2481         }
2482         if (read_only)
2483                 goto done;
2484         if (!(sbi->s_mount_state & EXT4_VALID_FS))
2485                 ext4_msg(sb, KERN_WARNING, "warning: mounting unchecked fs, "
2486                          "running e2fsck is recommended");
2487         else if (sbi->s_mount_state & EXT4_ERROR_FS)
2488                 ext4_msg(sb, KERN_WARNING,
2489                          "warning: mounting fs with errors, "
2490                          "running e2fsck is recommended");
2491         else if ((__s16) le16_to_cpu(es->s_max_mnt_count) > 0 &&
2492                  le16_to_cpu(es->s_mnt_count) >=
2493                  (unsigned short) (__s16) le16_to_cpu(es->s_max_mnt_count))
2494                 ext4_msg(sb, KERN_WARNING,
2495                          "warning: maximal mount count reached, "
2496                          "running e2fsck is recommended");
2497         else if (le32_to_cpu(es->s_checkinterval) &&
2498                  (ext4_get_tstamp(es, s_lastcheck) +
2499                   le32_to_cpu(es->s_checkinterval) <= ktime_get_real_seconds()))
2500                 ext4_msg(sb, KERN_WARNING,
2501                          "warning: checktime reached, "
2502                          "running e2fsck is recommended");
2503         if (!sbi->s_journal)
2504                 es->s_state &= cpu_to_le16(~EXT4_VALID_FS);
2505         if (!(__s16) le16_to_cpu(es->s_max_mnt_count))
2506                 es->s_max_mnt_count = cpu_to_le16(EXT4_DFL_MAX_MNT_COUNT);
2507         le16_add_cpu(&es->s_mnt_count, 1);
2508         ext4_update_tstamp(es, s_mtime);
2509         if (sbi->s_journal)
2510                 ext4_set_feature_journal_needs_recovery(sb);
2511
2512         err = ext4_commit_super(sb, 1);
2513 done:
2514         if (test_opt(sb, DEBUG))
2515                 printk(KERN_INFO "[EXT4 FS bs=%lu, gc=%u, "
2516                                 "bpg=%lu, ipg=%lu, mo=%04x, mo2=%04x]\n",
2517                         sb->s_blocksize,
2518                         sbi->s_groups_count,
2519                         EXT4_BLOCKS_PER_GROUP(sb),
2520                         EXT4_INODES_PER_GROUP(sb),
2521                         sbi->s_mount_opt, sbi->s_mount_opt2);
2522
2523         cleancache_init_fs(sb);
2524         return err;
2525 }
2526
2527 int ext4_alloc_flex_bg_array(struct super_block *sb, ext4_group_t ngroup)
2528 {
2529         struct ext4_sb_info *sbi = EXT4_SB(sb);
2530         struct flex_groups **old_groups, **new_groups;
2531         int size, i, j;
2532
2533         if (!sbi->s_log_groups_per_flex)
2534                 return 0;
2535
2536         size = ext4_flex_group(sbi, ngroup - 1) + 1;
2537         if (size <= sbi->s_flex_groups_allocated)
2538                 return 0;
2539
2540         new_groups = kvzalloc(roundup_pow_of_two(size *
2541                               sizeof(*sbi->s_flex_groups)), GFP_KERNEL);
2542         if (!new_groups) {
2543                 ext4_msg(sb, KERN_ERR,
2544                          "not enough memory for %d flex group pointers", size);
2545                 return -ENOMEM;
2546         }
2547         for (i = sbi->s_flex_groups_allocated; i < size; i++) {
2548                 new_groups[i] = kvzalloc(roundup_pow_of_two(
2549                                          sizeof(struct flex_groups)),
2550                                          GFP_KERNEL);
2551                 if (!new_groups[i]) {
2552                         for (j = sbi->s_flex_groups_allocated; j < i; j++)
2553                                 kvfree(new_groups[j]);
2554                         kvfree(new_groups);
2555                         ext4_msg(sb, KERN_ERR,
2556                                  "not enough memory for %d flex groups", size);
2557                         return -ENOMEM;
2558                 }
2559         }
2560         rcu_read_lock();
2561         old_groups = rcu_dereference(sbi->s_flex_groups);
2562         if (old_groups)
2563                 memcpy(new_groups, old_groups,
2564                        (sbi->s_flex_groups_allocated *
2565                         sizeof(struct flex_groups *)));
2566         rcu_read_unlock();
2567         rcu_assign_pointer(sbi->s_flex_groups, new_groups);
2568         sbi->s_flex_groups_allocated = size;
2569         if (old_groups)
2570                 ext4_kvfree_array_rcu(old_groups);
2571         return 0;
2572 }
2573
2574 static int ext4_fill_flex_info(struct super_block *sb)
2575 {
2576         struct ext4_sb_info *sbi = EXT4_SB(sb);
2577         struct ext4_group_desc *gdp = NULL;
2578         struct flex_groups *fg;
2579         ext4_group_t flex_group;
2580         int i, err;
2581
2582         sbi->s_log_groups_per_flex = sbi->s_es->s_log_groups_per_flex;
2583         if (sbi->s_log_groups_per_flex < 1 || sbi->s_log_groups_per_flex > 31) {
2584                 sbi->s_log_groups_per_flex = 0;
2585                 return 1;
2586         }
2587
2588         err = ext4_alloc_flex_bg_array(sb, sbi->s_groups_count);
2589         if (err)
2590                 goto failed;
2591
2592         for (i = 0; i < sbi->s_groups_count; i++) {
2593                 gdp = ext4_get_group_desc(sb, i, NULL);
2594
2595                 flex_group = ext4_flex_group(sbi, i);
2596                 fg = sbi_array_rcu_deref(sbi, s_flex_groups, flex_group);
2597                 atomic_add(ext4_free_inodes_count(sb, gdp), &fg->free_inodes);
2598                 atomic64_add(ext4_free_group_clusters(sb, gdp),
2599                              &fg->free_clusters);
2600                 atomic_add(ext4_used_dirs_count(sb, gdp), &fg->used_dirs);
2601         }
2602
2603         return 1;
2604 failed:
2605         return 0;
2606 }
2607
2608 static __le16 ext4_group_desc_csum(struct super_block *sb, __u32 block_group,
2609                                    struct ext4_group_desc *gdp)
2610 {
2611         int offset = offsetof(struct ext4_group_desc, bg_checksum);
2612         __u16 crc = 0;
2613         __le32 le_group = cpu_to_le32(block_group);
2614         struct ext4_sb_info *sbi = EXT4_SB(sb);
2615
2616         if (ext4_has_metadata_csum(sbi->s_sb)) {
2617                 /* Use new metadata_csum algorithm */
2618                 __u32 csum32;
2619                 __u16 dummy_csum = 0;
2620
2621                 csum32 = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&le_group,
2622                                      sizeof(le_group));
2623                 csum32 = ext4_chksum(sbi, csum32, (__u8 *)gdp, offset);
2624                 csum32 = ext4_chksum(sbi, csum32, (__u8 *)&dummy_csum,
2625                                      sizeof(dummy_csum));
2626                 offset += sizeof(dummy_csum);
2627                 if (offset < sbi->s_desc_size)
2628                         csum32 = ext4_chksum(sbi, csum32, (__u8 *)gdp + offset,
2629                                              sbi->s_desc_size - offset);
2630
2631                 crc = csum32 & 0xFFFF;
2632                 goto out;
2633         }
2634
2635         /* old crc16 code */
2636         if (!ext4_has_feature_gdt_csum(sb))
2637                 return 0;
2638
2639         crc = crc16(~0, sbi->s_es->s_uuid, sizeof(sbi->s_es->s_uuid));
2640         crc = crc16(crc, (__u8 *)&le_group, sizeof(le_group));
2641         crc = crc16(crc, (__u8 *)gdp, offset);
2642         offset += sizeof(gdp->bg_checksum); /* skip checksum */
2643         /* for checksum of struct ext4_group_desc do the rest...*/
2644         if (ext4_has_feature_64bit(sb) &&
2645             offset < le16_to_cpu(sbi->s_es->s_desc_size))
2646                 crc = crc16(crc, (__u8 *)gdp + offset,
2647                             le16_to_cpu(sbi->s_es->s_desc_size) -
2648                                 offset);
2649
2650 out:
2651         return cpu_to_le16(crc);
2652 }
2653
2654 int ext4_group_desc_csum_verify(struct super_block *sb, __u32 block_group,
2655                                 struct ext4_group_desc *gdp)
2656 {
2657         if (ext4_has_group_desc_csum(sb) &&
2658             (gdp->bg_checksum != ext4_group_desc_csum(sb, block_group, gdp)))
2659                 return 0;
2660
2661         return 1;
2662 }
2663
2664 void ext4_group_desc_csum_set(struct super_block *sb, __u32 block_group,
2665                               struct ext4_group_desc *gdp)
2666 {
2667         if (!ext4_has_group_desc_csum(sb))
2668                 return;
2669         gdp->bg_checksum = ext4_group_desc_csum(sb, block_group, gdp);
2670 }
2671
2672 /* Called at mount-time, super-block is locked */
2673 static int ext4_check_descriptors(struct super_block *sb,
2674                                   ext4_fsblk_t sb_block,
2675                                   ext4_group_t *first_not_zeroed)
2676 {
2677         struct ext4_sb_info *sbi = EXT4_SB(sb);
2678         ext4_fsblk_t first_block = le32_to_cpu(sbi->s_es->s_first_data_block);
2679         ext4_fsblk_t last_block;
2680         ext4_fsblk_t last_bg_block = sb_block + ext4_bg_num_gdb(sb, 0);
2681         ext4_fsblk_t block_bitmap;
2682         ext4_fsblk_t inode_bitmap;
2683         ext4_fsblk_t inode_table;
2684         int flexbg_flag = 0;
2685         ext4_group_t i, grp = sbi->s_groups_count;
2686
2687         if (ext4_has_feature_flex_bg(sb))
2688                 flexbg_flag = 1;
2689
2690         ext4_debug("Checking group descriptors");
2691
2692         for (i = 0; i < sbi->s_groups_count; i++) {
2693                 struct ext4_group_desc *gdp = ext4_get_group_desc(sb, i, NULL);
2694
2695                 if (i == sbi->s_groups_count - 1 || flexbg_flag)
2696                         last_block = ext4_blocks_count(sbi->s_es) - 1;
2697                 else
2698                         last_block = first_block +
2699                                 (EXT4_BLOCKS_PER_GROUP(sb) - 1);
2700
2701                 if ((grp == sbi->s_groups_count) &&
2702                    !(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED)))
2703                         grp = i;
2704
2705                 block_bitmap = ext4_block_bitmap(sb, gdp);
2706                 if (block_bitmap == sb_block) {
2707                         ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2708                                  "Block bitmap for group %u overlaps "
2709                                  "superblock", i);
2710                         if (!sb_rdonly(sb))
2711                                 return 0;
2712                 }
2713                 if (block_bitmap >= sb_block + 1 &&
2714                     block_bitmap <= last_bg_block) {
2715                         ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2716                                  "Block bitmap for group %u overlaps "
2717                                  "block group descriptors", i);
2718                         if (!sb_rdonly(sb))
2719                                 return 0;
2720                 }
2721                 if (block_bitmap < first_block || block_bitmap > last_block) {
2722                         ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2723                                "Block bitmap for group %u not in group "
2724                                "(block %llu)!", i, block_bitmap);
2725                         return 0;
2726                 }
2727                 inode_bitmap = ext4_inode_bitmap(sb, gdp);
2728                 if (inode_bitmap == sb_block) {
2729                         ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2730                                  "Inode bitmap for group %u overlaps "
2731                                  "superblock", i);
2732                         if (!sb_rdonly(sb))
2733                                 return 0;
2734                 }
2735                 if (inode_bitmap >= sb_block + 1 &&
2736                     inode_bitmap <= last_bg_block) {
2737                         ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2738                                  "Inode bitmap for group %u overlaps "
2739                                  "block group descriptors", i);
2740                         if (!sb_rdonly(sb))
2741                                 return 0;
2742                 }
2743                 if (inode_bitmap < first_block || inode_bitmap > last_block) {
2744                         ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2745                                "Inode bitmap for group %u not in group "
2746                                "(block %llu)!", i, inode_bitmap);
2747                         return 0;
2748                 }
2749                 inode_table = ext4_inode_table(sb, gdp);
2750                 if (inode_table == sb_block) {
2751                         ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2752                                  "Inode table for group %u overlaps "
2753                                  "superblock", i);
2754                         if (!sb_rdonly(sb))
2755                                 return 0;
2756                 }
2757                 if (inode_table >= sb_block + 1 &&
2758                     inode_table <= last_bg_block) {
2759                         ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2760                                  "Inode table for group %u overlaps "
2761                                  "block group descriptors", i);
2762                         if (!sb_rdonly(sb))
2763                                 return 0;
2764                 }
2765                 if (inode_table < first_block ||
2766                     inode_table + sbi->s_itb_per_group - 1 > last_block) {
2767                         ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2768                                "Inode table for group %u not in group "
2769                                "(block %llu)!", i, inode_table);
2770                         return 0;
2771                 }
2772                 ext4_lock_group(sb, i);
2773                 if (!ext4_group_desc_csum_verify(sb, i, gdp)) {
2774                         ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
2775                                  "Checksum for group %u failed (%u!=%u)",
2776                                  i, le16_to_cpu(ext4_group_desc_csum(sb, i,
2777                                      gdp)), le16_to_cpu(gdp->bg_checksum));
2778                         if (!sb_rdonly(sb)) {
2779                                 ext4_unlock_group(sb, i);
2780                                 return 0;
2781                         }
2782                 }
2783                 ext4_unlock_group(sb, i);
2784                 if (!flexbg_flag)
2785                         first_block += EXT4_BLOCKS_PER_GROUP(sb);
2786         }
2787         if (NULL != first_not_zeroed)
2788                 *first_not_zeroed = grp;
2789         return 1;
2790 }
2791
2792 /* ext4_orphan_cleanup() walks a singly-linked list of inodes (starting at
2793  * the superblock) which were deleted from all directories, but held open by
2794  * a process at the time of a crash.  We walk the list and try to delete these
2795  * inodes at recovery time (only with a read-write filesystem).
2796  *
2797  * In order to keep the orphan inode chain consistent during traversal (in
2798  * case of crash during recovery), we link each inode into the superblock
2799  * orphan list_head and handle it the same way as an inode deletion during
2800  * normal operation (which journals the operations for us).
2801  *
2802  * We only do an iget() and an iput() on each inode, which is very safe if we
2803  * accidentally point at an in-use or already deleted inode.  The worst that
2804  * can happen in this case is that we get a "bit already cleared" message from
2805  * ext4_free_inode().  The only reason we would point at a wrong inode is if
2806  * e2fsck was run on this filesystem, and it must have already done the orphan
2807  * inode cleanup for us, so we can safely abort without any further action.
2808  */
2809 static void ext4_orphan_cleanup(struct super_block *sb,
2810                                 struct ext4_super_block *es)
2811 {
2812         unsigned int s_flags = sb->s_flags;
2813         int ret, nr_orphans = 0, nr_truncates = 0;
2814 #ifdef CONFIG_QUOTA
2815         int quota_update = 0;
2816         int i;
2817 #endif
2818         if (!es->s_last_orphan) {
2819                 jbd_debug(4, "no orphan inodes to clean up\n");
2820                 return;
2821         }
2822
2823         if (bdev_read_only(sb->s_bdev)) {
2824                 ext4_msg(sb, KERN_ERR, "write access "
2825                         "unavailable, skipping orphan cleanup");
2826                 return;
2827         }
2828
2829         /* Check if feature set would not allow a r/w mount */
2830         if (!ext4_feature_set_ok(sb, 0)) {
2831                 ext4_msg(sb, KERN_INFO, "Skipping orphan cleanup due to "
2832                          "unknown ROCOMPAT features");
2833                 return;
2834         }
2835
2836         if (EXT4_SB(sb)->s_mount_state & EXT4_ERROR_FS) {
2837                 /* don't clear list on RO mount w/ errors */
2838                 if (es->s_last_orphan && !(s_flags & SB_RDONLY)) {
2839                         ext4_msg(sb, KERN_INFO, "Errors on filesystem, "
2840                                   "clearing orphan list.\n");
2841                         es->s_last_orphan = 0;
2842                 }
2843                 jbd_debug(1, "Skipping orphan recovery on fs with errors.\n");
2844                 return;
2845         }
2846
2847         if (s_flags & SB_RDONLY) {
2848                 ext4_msg(sb, KERN_INFO, "orphan cleanup on readonly fs");
2849                 sb->s_flags &= ~SB_RDONLY;
2850         }
2851 #ifdef CONFIG_QUOTA
2852         /* Needed for iput() to work correctly and not trash data */
2853         sb->s_flags |= SB_ACTIVE;
2854
2855         /*
2856          * Turn on quotas which were not enabled for read-only mounts if
2857          * filesystem has quota feature, so that they are updated correctly.
2858          */
2859         if (ext4_has_feature_quota(sb) && (s_flags & SB_RDONLY)) {
2860                 int ret = ext4_enable_quotas(sb);
2861
2862                 if (!ret)
2863                         quota_update = 1;
2864                 else
2865                         ext4_msg(sb, KERN_ERR,
2866                                 "Cannot turn on quotas: error %d", ret);
2867         }
2868
2869         /* Turn on journaled quotas used for old sytle */
2870         for (i = 0; i < EXT4_MAXQUOTAS; i++) {
2871                 if (EXT4_SB(sb)->s_qf_names[i]) {
2872                         int ret = ext4_quota_on_mount(sb, i);
2873
2874                         if (!ret)
2875                                 quota_update = 1;
2876                         else
2877                                 ext4_msg(sb, KERN_ERR,
2878                                         "Cannot turn on journaled "
2879                                         "quota: type %d: error %d", i, ret);
2880                 }
2881         }
2882 #endif
2883
2884         while (es->s_last_orphan) {
2885                 struct inode *inode;
2886
2887                 /*
2888                  * We may have encountered an error during cleanup; if
2889                  * so, skip the rest.
2890                  */
2891                 if (EXT4_SB(sb)->s_mount_state & EXT4_ERROR_FS) {
2892                         jbd_debug(1, "Skipping orphan recovery on fs with errors.\n");
2893                         es->s_last_orphan = 0;
2894                         break;
2895                 }
2896
2897                 inode = ext4_orphan_get(sb, le32_to_cpu(es->s_last_orphan));
2898                 if (IS_ERR(inode)) {
2899                         es->s_last_orphan = 0;
2900                         break;
2901                 }
2902
2903                 list_add(&EXT4_I(inode)->i_orphan, &EXT4_SB(sb)->s_orphan);
2904                 dquot_initialize(inode);
2905                 if (inode->i_nlink) {
2906                         if (test_opt(sb, DEBUG))
2907                                 ext4_msg(sb, KERN_DEBUG,
2908                                         "%s: truncating inode %lu to %lld bytes",
2909                                         __func__, inode->i_ino, inode->i_size);
2910                         jbd_debug(2, "truncating inode %lu to %lld bytes\n",
2911                                   inode->i_ino, inode->i_size);
2912                         inode_lock(inode);
2913                         truncate_inode_pages(inode->i_mapping, inode->i_size);
2914                         ret = ext4_truncate(inode);
2915                         if (ret)
2916                                 ext4_std_error(inode->i_sb, ret);
2917                         inode_unlock(inode);
2918                         nr_truncates++;
2919                 } else {
2920                         if (test_opt(sb, DEBUG))
2921                                 ext4_msg(sb, KERN_DEBUG,
2922                                         "%s: deleting unreferenced inode %lu",
2923                                         __func__, inode->i_ino);
2924                         jbd_debug(2, "deleting unreferenced inode %lu\n",
2925                                   inode->i_ino);
2926                         nr_orphans++;
2927                 }
2928                 iput(inode);  /* The delete magic happens here! */
2929         }
2930
2931 #define PLURAL(x) (x), ((x) == 1) ? "" : "s"
2932
2933         if (nr_orphans)
2934                 ext4_msg(sb, KERN_INFO, "%d orphan inode%s deleted",
2935                        PLURAL(nr_orphans));
2936         if (nr_truncates)
2937                 ext4_msg(sb, KERN_INFO, "%d truncate%s cleaned up",
2938                        PLURAL(nr_truncates));
2939 #ifdef CONFIG_QUOTA
2940         /* Turn off quotas if they were enabled for orphan cleanup */
2941         if (quota_update) {
2942                 for (i = 0; i < EXT4_MAXQUOTAS; i++) {
2943                         if (sb_dqopt(sb)->files[i])
2944                                 dquot_quota_off(sb, i);
2945                 }
2946         }
2947 #endif
2948         sb->s_flags = s_flags; /* Restore SB_RDONLY status */
2949 }
2950
2951 /*
2952  * Maximal extent format file size.
2953  * Resulting logical blkno at s_maxbytes must fit in our on-disk
2954  * extent format containers, within a sector_t, and within i_blocks
2955  * in the vfs.  ext4 inode has 48 bits of i_block in fsblock units,
2956  * so that won't be a limiting factor.
2957  *
2958  * However there is other limiting factor. We do store extents in the form
2959  * of starting block and length, hence the resulting length of the extent
2960  * covering maximum file size must fit into on-disk format containers as
2961  * well. Given that length is always by 1 unit bigger than max unit (because
2962  * we count 0 as well) we have to lower the s_maxbytes by one fs block.
2963  *
2964  * Note, this does *not* consider any metadata overhead for vfs i_blocks.
2965  */
2966 static loff_t ext4_max_size(int blkbits, int has_huge_files)
2967 {
2968         loff_t res;
2969         loff_t upper_limit = MAX_LFS_FILESIZE;
2970
2971         BUILD_BUG_ON(sizeof(blkcnt_t) < sizeof(u64));
2972
2973         if (!has_huge_files) {
2974                 upper_limit = (1LL << 32) - 1;
2975
2976                 /* total blocks in file system block size */
2977                 upper_limit >>= (blkbits - 9);
2978                 upper_limit <<= blkbits;
2979         }
2980
2981         /*
2982          * 32-bit extent-start container, ee_block. We lower the maxbytes
2983          * by one fs block, so ee_len can cover the extent of maximum file
2984          * size
2985          */
2986         res = (1LL << 32) - 1;
2987         res <<= blkbits;
2988
2989         /* Sanity check against vm- & vfs- imposed limits */
2990         if (res > upper_limit)
2991                 res = upper_limit;
2992
2993         return res;
2994 }
2995
2996 /*
2997  * Maximal bitmap file size.  There is a direct, and {,double-,triple-}indirect
2998  * block limit, and also a limit of (2^48 - 1) 512-byte sectors in i_blocks.
2999  * We need to be 1 filesystem block less than the 2^48 sector limit.
3000  */
3001 static loff_t ext4_max_bitmap_size(int bits, int has_huge_files)
3002 {
3003         loff_t res = EXT4_NDIR_BLOCKS;
3004         int meta_blocks;
3005         loff_t upper_limit;
3006         /* This is calculated to be the largest file size for a dense, block
3007          * mapped file such that the file's total number of 512-byte sectors,
3008          * including data and all indirect blocks, does not exceed (2^48 - 1).
3009          *
3010          * __u32 i_blocks_lo and _u16 i_blocks_high represent the total
3011          * number of 512-byte sectors of the file.
3012          */
3013
3014         if (!has_huge_files) {
3015                 /*
3016                  * !has_huge_files or implies that the inode i_block field
3017                  * represents total file blocks in 2^32 512-byte sectors ==
3018                  * size of vfs inode i_blocks * 8
3019                  */
3020                 upper_limit = (1LL << 32) - 1;
3021
3022                 /* total blocks in file system block size */
3023                 upper_limit >>= (bits - 9);
3024
3025         } else {
3026                 /*
3027                  * We use 48 bit ext4_inode i_blocks
3028                  * With EXT4_HUGE_FILE_FL set the i_blocks
3029                  * represent total number of blocks in
3030                  * file system block size
3031                  */
3032                 upper_limit = (1LL << 48) - 1;
3033
3034         }
3035
3036         /* indirect blocks */
3037         meta_blocks = 1;
3038         /* double indirect blocks */
3039         meta_blocks += 1 + (1LL << (bits-2));
3040         /* tripple indirect blocks */
3041         meta_blocks += 1 + (1LL << (bits-2)) + (1LL << (2*(bits-2)));
3042
3043         upper_limit -= meta_blocks;
3044         upper_limit <<= bits;
3045
3046         res += 1LL << (bits-2);
3047         res += 1LL << (2*(bits-2));
3048         res += 1LL << (3*(bits-2));
3049         res <<= bits;
3050         if (res > upper_limit)
3051                 res = upper_limit;
3052
3053         if (res > MAX_LFS_FILESIZE)
3054                 res = MAX_LFS_FILESIZE;
3055
3056         return res;
3057 }
3058
3059 static ext4_fsblk_t descriptor_loc(struct super_block *sb,
3060                                    ext4_fsblk_t logical_sb_block, int nr)
3061 {
3062         struct ext4_sb_info *sbi = EXT4_SB(sb);
3063         ext4_group_t bg, first_meta_bg;
3064         int has_super = 0;
3065
3066         first_meta_bg = le32_to_cpu(sbi->s_es->s_first_meta_bg);
3067
3068         if (!ext4_has_feature_meta_bg(sb) || nr < first_meta_bg)
3069                 return logical_sb_block + nr + 1;
3070         bg = sbi->s_desc_per_block * nr;
3071         if (ext4_bg_has_super(sb, bg))
3072                 has_super = 1;
3073
3074         /*
3075          * If we have a meta_bg fs with 1k blocks, group 0's GDT is at
3076          * block 2, not 1.  If s_first_data_block == 0 (bigalloc is enabled
3077          * on modern mke2fs or blksize > 1k on older mke2fs) then we must
3078          * compensate.
3079          */
3080         if (sb->s_blocksize == 1024 && nr == 0 &&
3081             le32_to_cpu(sbi->s_es->s_first_data_block) == 0)
3082                 has_super++;
3083
3084         return (has_super + ext4_group_first_block_no(sb, bg));
3085 }
3086
3087 /**
3088  * ext4_get_stripe_size: Get the stripe size.
3089  * @sbi: In memory super block info
3090  *
3091  * If we have specified it via mount option, then
3092  * use the mount option value. If the value specified at mount time is
3093  * greater than the blocks per group use the super block value.
3094  * If the super block value is greater than blocks per group return 0.
3095  * Allocator needs it be less than blocks per group.
3096  *
3097  */
3098 static unsigned long ext4_get_stripe_size(struct ext4_sb_info *sbi)
3099 {
3100         unsigned long stride = le16_to_cpu(sbi->s_es->s_raid_stride);
3101         unsigned long stripe_width =
3102                         le32_to_cpu(sbi->s_es->s_raid_stripe_width);
3103         int ret;
3104
3105         if (sbi->s_stripe && sbi->s_stripe <= sbi->s_blocks_per_group)
3106                 ret = sbi->s_stripe;
3107         else if (stripe_width && stripe_width <= sbi->s_blocks_per_group)
3108                 ret = stripe_width;
3109         else if (stride && stride <= sbi->s_blocks_per_group)
3110                 ret = stride;
3111         else
3112                 ret = 0;
3113
3114         /*
3115          * If the stripe width is 1, this makes no sense and
3116          * we set it to 0 to turn off stripe handling code.
3117          */
3118         if (ret <= 1)
3119                 ret = 0;
3120
3121         return ret;
3122 }
3123
3124 /*
3125  * Check whether this filesystem can be mounted based on
3126  * the features present and the RDONLY/RDWR mount requested.
3127  * Returns 1 if this filesystem can be mounted as requested,
3128  * 0 if it cannot be.
3129  */
3130 static int ext4_feature_set_ok(struct super_block *sb, int readonly)
3131 {
3132         if (ext4_has_unknown_ext4_incompat_features(sb)) {
3133                 ext4_msg(sb, KERN_ERR,
3134                         "Couldn't mount because of "
3135                         "unsupported optional features (%x)",
3136                         (le32_to_cpu(EXT4_SB(sb)->s_es->s_feature_incompat) &
3137                         ~EXT4_FEATURE_INCOMPAT_SUPP));
3138                 return 0;
3139         }
3140
3141 #ifndef CONFIG_UNICODE
3142         if (ext4_has_feature_casefold(sb)) {
3143                 ext4_msg(sb, KERN_ERR,
3144                          "Filesystem with casefold feature cannot be "
3145                          "mounted without CONFIG_UNICODE");
3146                 return 0;
3147         }
3148 #endif
3149
3150         if (readonly)
3151                 return 1;
3152
3153         if (ext4_has_feature_readonly(sb)) {
3154                 ext4_msg(sb, KERN_INFO, "filesystem is read-only");
3155                 sb->s_flags |= SB_RDONLY;
3156                 return 1;
3157         }
3158
3159         /* Check that feature set is OK for a read-write mount */
3160         if (ext4_has_unknown_ext4_ro_compat_features(sb)) {
3161                 ext4_msg(sb, KERN_ERR, "couldn't mount RDWR because of "
3162                          "unsupported optional features (%x)",
3163                          (le32_to_cpu(EXT4_SB(sb)->s_es->s_feature_ro_compat) &
3164                                 ~EXT4_FEATURE_RO_COMPAT_SUPP));
3165                 return 0;
3166         }
3167         if (ext4_has_feature_bigalloc(sb) && !ext4_has_feature_extents(sb)) {
3168                 ext4_msg(sb, KERN_ERR,
3169                          "Can't support bigalloc feature without "
3170                          "extents feature\n");
3171                 return 0;
3172         }
3173
3174 #if !IS_ENABLED(CONFIG_QUOTA) || !IS_ENABLED(CONFIG_QFMT_V2)
3175         if (!readonly && (ext4_has_feature_quota(sb) ||
3176                           ext4_has_feature_project(sb))) {
3177                 ext4_msg(sb, KERN_ERR,
3178                          "The kernel was not built with CONFIG_QUOTA and CONFIG_QFMT_V2");
3179                 return 0;
3180         }
3181 #endif  /* CONFIG_QUOTA */
3182         return 1;
3183 }
3184
3185 /*
3186  * This function is called once a day if we have errors logged
3187  * on the file system
3188  */
3189 static void print_daily_error_info(struct timer_list *t)
3190 {
3191         struct ext4_sb_info *sbi = from_timer(sbi, t, s_err_report);
3192         struct super_block *sb = sbi->s_sb;
3193         struct ext4_super_block *es = sbi->s_es;
3194
3195         if (es->s_error_count)
3196                 /* fsck newer than v1.41.13 is needed to clean this condition. */
3197                 ext4_msg(sb, KERN_NOTICE, "error count since last fsck: %u",
3198                          le32_to_cpu(es->s_error_count));
3199         if (es->s_first_error_time) {
3200                 printk(KERN_NOTICE "EXT4-fs (%s): initial error at time %llu: %.*s:%d",
3201                        sb->s_id,
3202                        ext4_get_tstamp(es, s_first_error_time),
3203                        (int) sizeof(es->s_first_error_func),
3204                        es->s_first_error_func,
3205                        le32_to_cpu(es->s_first_error_line));
3206                 if (es->s_first_error_ino)
3207                         printk(KERN_CONT ": inode %u",
3208                                le32_to_cpu(es->s_first_error_ino));
3209                 if (es->s_first_error_block)
3210                         printk(KERN_CONT ": block %llu", (unsigned long long)
3211                                le64_to_cpu(es->s_first_error_block));
3212                 printk(KERN_CONT "\n");
3213         }
3214         if (es->s_last_error_time) {
3215                 printk(KERN_NOTICE "EXT4-fs (%s): last error at time %llu: %.*s:%d",
3216                        sb->s_id,
3217                        ext4_get_tstamp(es, s_last_error_time),
3218                        (int) sizeof(es->s_last_error_func),
3219                        es->s_last_error_func,
3220                        le32_to_cpu(es->s_last_error_line));
3221                 if (es->s_last_error_ino)
3222                         printk(KERN_CONT ": inode %u",
3223                                le32_to_cpu(es->s_last_error_ino));
3224                 if (es->s_last_error_block)
3225                         printk(KERN_CONT ": block %llu", (unsigned long long)
3226                                le64_to_cpu(es->s_last_error_block));
3227                 printk(KERN_CONT "\n");
3228         }
3229         mod_timer(&sbi->s_err_report, jiffies + 24*60*60*HZ);  /* Once a day */
3230 }
3231
3232 /* Find next suitable group and run ext4_init_inode_table */
3233 static int ext4_run_li_request(struct ext4_li_request *elr)
3234 {
3235         struct ext4_group_desc *gdp = NULL;
3236         struct super_block *sb = elr->lr_super;
3237         ext4_group_t ngroups = EXT4_SB(sb)->s_groups_count;
3238         ext4_group_t group = elr->lr_next_group;
3239         unsigned long timeout = 0;
3240         unsigned int prefetch_ios = 0;
3241         int ret = 0;
3242
3243         if (elr->lr_mode == EXT4_LI_MODE_PREFETCH_BBITMAP) {
3244                 elr->lr_next_group = ext4_mb_prefetch(sb, group,
3245                                 EXT4_SB(sb)->s_mb_prefetch, &prefetch_ios);
3246                 if (prefetch_ios)
3247                         ext4_mb_prefetch_fini(sb, elr->lr_next_group,
3248                                               prefetch_ios);
3249                 trace_ext4_prefetch_bitmaps(sb, group, elr->lr_next_group,
3250                                             prefetch_ios);
3251                 if (group >= elr->lr_next_group) {
3252                         ret = 1;
3253                         if (elr->lr_first_not_zeroed != ngroups &&
3254                             !sb_rdonly(sb) && test_opt(sb, INIT_INODE_TABLE)) {
3255                                 elr->lr_next_group = elr->lr_first_not_zeroed;
3256                                 elr->lr_mode = EXT4_LI_MODE_ITABLE;
3257                                 ret = 0;
3258                         }
3259                 }
3260                 return ret;
3261         }
3262
3263         for (; group < ngroups; group++) {
3264                 gdp = ext4_get_group_desc(sb, group, NULL);
3265                 if (!gdp) {
3266                         ret = 1;
3267                         break;
3268                 }
3269
3270                 if (!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED)))
3271                         break;
3272         }
3273
3274         if (group >= ngroups)
3275                 ret = 1;
3276
3277         if (!ret) {
3278                 timeout = jiffies;
3279                 ret = ext4_init_inode_table(sb, group,
3280                                             elr->lr_timeout ? 0 : 1);
3281                 trace_ext4_lazy_itable_init(sb, group);
3282                 if (elr->lr_timeout == 0) {
3283                         timeout = (jiffies - timeout) *
3284                                 EXT4_SB(elr->lr_super)->s_li_wait_mult;
3285                         elr->lr_timeout = timeout;
3286                 }
3287                 elr->lr_next_sched = jiffies + elr->lr_timeout;
3288                 elr->lr_next_group = group + 1;
3289         }
3290         return ret;
3291 }
3292
3293 /*
3294  * Remove lr_request from the list_request and free the
3295  * request structure. Should be called with li_list_mtx held
3296  */
3297 static void ext4_remove_li_request(struct ext4_li_request *elr)
3298 {
3299         if (!elr)
3300                 return;
3301
3302         list_del(&elr->lr_request);
3303         EXT4_SB(elr->lr_super)->s_li_request = NULL;
3304         kfree(elr);
3305 }
3306
3307 static void ext4_unregister_li_request(struct super_block *sb)
3308 {
3309         mutex_lock(&ext4_li_mtx);
3310         if (!ext4_li_info) {
3311                 mutex_unlock(&ext4_li_mtx);
3312                 return;
3313         }
3314
3315         mutex_lock(&ext4_li_info->li_list_mtx);
3316         ext4_remove_li_request(EXT4_SB(sb)->s_li_request);
3317         mutex_unlock(&ext4_li_info->li_list_mtx);
3318         mutex_unlock(&ext4_li_mtx);
3319 }
3320
3321 static struct task_struct *ext4_lazyinit_task;
3322
3323 /*
3324  * This is the function where ext4lazyinit thread lives. It walks
3325  * through the request list searching for next scheduled filesystem.
3326  * When such a fs is found, run the lazy initialization request
3327  * (ext4_rn_li_request) and keep track of the time spend in this
3328  * function. Based on that time we compute next schedule time of
3329  * the request. When walking through the list is complete, compute
3330  * next waking time and put itself into sleep.
3331  */
3332 static int ext4_lazyinit_thread(void *arg)
3333 {
3334         struct ext4_lazy_init *eli = (struct ext4_lazy_init *)arg;
3335         struct list_head *pos, *n;
3336         struct ext4_li_request *elr;
3337         unsigned long next_wakeup, cur;
3338
3339         BUG_ON(NULL == eli);
3340
3341 cont_thread:
3342         while (true) {
3343                 next_wakeup = MAX_JIFFY_OFFSET;
3344
3345                 mutex_lock(&eli->li_list_mtx);
3346                 if (list_empty(&eli->li_request_list)) {
3347                         mutex_unlock(&eli->li_list_mtx);
3348                         goto exit_thread;
3349                 }
3350                 list_for_each_safe(pos, n, &eli->li_request_list) {
3351                         int err = 0;
3352                         int progress = 0;
3353                         elr = list_entry(pos, struct ext4_li_request,
3354                                          lr_request);
3355
3356                         if (time_before(jiffies, elr->lr_next_sched)) {
3357                                 if (time_before(elr->lr_next_sched, next_wakeup))
3358                                         next_wakeup = elr->lr_next_sched;
3359                                 continue;
3360                         }
3361                         if (down_read_trylock(&elr->lr_super->s_umount)) {
3362                                 if (sb_start_write_trylock(elr->lr_super)) {
3363                                         progress = 1;
3364                                         /*
3365                                          * We hold sb->s_umount, sb can not
3366                                          * be removed from the list, it is
3367                                          * now safe to drop li_list_mtx
3368                                          */
3369                                         mutex_unlock(&eli->li_list_mtx);
3370                                         err = ext4_run_li_request(elr);
3371                                         sb_end_write(elr->lr_super);
3372                                         mutex_lock(&eli->li_list_mtx);
3373                                         n = pos->next;
3374                                 }
3375                                 up_read((&elr->lr_super->s_umount));
3376                         }
3377                         /* error, remove the lazy_init job */
3378                         if (err) {
3379                                 ext4_remove_li_request(elr);
3380                                 continue;
3381                         }
3382                         if (!progress) {
3383                                 elr->lr_next_sched = jiffies +
3384                                         (prandom_u32()
3385                                          % (EXT4_DEF_LI_MAX_START_DELAY * HZ));
3386                         }
3387                         if (time_before(elr->lr_next_sched, next_wakeup))
3388                                 next_wakeup = elr->lr_next_sched;
3389                 }
3390                 mutex_unlock(&eli->li_list_mtx);
3391
3392                 try_to_freeze();
3393
3394                 cur = jiffies;
3395                 if ((time_after_eq(cur, next_wakeup)) ||
3396                     (MAX_JIFFY_OFFSET == next_wakeup)) {
3397                         cond_resched();
3398                         continue;
3399                 }
3400
3401                 schedule_timeout_interruptible(next_wakeup - cur);
3402
3403                 if (kthread_should_stop()) {
3404                         ext4_clear_request_list();
3405                         goto exit_thread;
3406                 }
3407         }
3408
3409 exit_thread:
3410         /*
3411          * It looks like the request list is empty, but we need
3412          * to check it under the li_list_mtx lock, to prevent any
3413          * additions into it, and of course we should lock ext4_li_mtx
3414          * to atomically free the list and ext4_li_info, because at
3415          * this point another ext4 filesystem could be registering
3416          * new one.
3417          */
3418         mutex_lock(&ext4_li_mtx);
3419         mutex_lock(&eli->li_list_mtx);
3420         if (!list_empty(&eli->li_request_list)) {
3421                 mutex_unlock(&eli->li_list_mtx);
3422                 mutex_unlock(&ext4_li_mtx);
3423                 goto cont_thread;
3424         }
3425         mutex_unlock(&eli->li_list_mtx);
3426         kfree(ext4_li_info);
3427         ext4_li_info = NULL;
3428         mutex_unlock(&ext4_li_mtx);
3429
3430         return 0;
3431 }
3432
3433 static void ext4_clear_request_list(void)
3434 {
3435         struct list_head *pos, *n;
3436         struct ext4_li_request *elr;
3437
3438         mutex_lock(&ext4_li_info->li_list_mtx);
3439         list_for_each_safe(pos, n, &ext4_li_info->li_request_list) {
3440                 elr = list_entry(pos, struct ext4_li_request,
3441                                  lr_request);
3442                 ext4_remove_li_request(elr);
3443         }
3444         mutex_unlock(&ext4_li_info->li_list_mtx);
3445 }
3446
3447 static int ext4_run_lazyinit_thread(void)
3448 {
3449         ext4_lazyinit_task = kthread_run(ext4_lazyinit_thread,
3450                                          ext4_li_info, "ext4lazyinit");
3451         if (IS_ERR(ext4_lazyinit_task)) {
3452                 int err = PTR_ERR(ext4_lazyinit_task);
3453                 ext4_clear_request_list();
3454                 kfree(ext4_li_info);
3455                 ext4_li_info = NULL;
3456                 printk(KERN_CRIT "EXT4-fs: error %d creating inode table "
3457                                  "initialization thread\n",
3458                                  err);
3459                 return err;
3460         }
3461         ext4_li_info->li_state |= EXT4_LAZYINIT_RUNNING;
3462         return 0;
3463 }
3464
3465 /*
3466  * Check whether it make sense to run itable init. thread or not.
3467  * If there is at least one uninitialized inode table, return
3468  * corresponding group number, else the loop goes through all
3469  * groups and return total number of groups.
3470  */
3471 static ext4_group_t ext4_has_uninit_itable(struct super_block *sb)
3472 {
3473         ext4_group_t group, ngroups = EXT4_SB(sb)->s_groups_count;
3474         struct ext4_group_desc *gdp = NULL;
3475
3476         if (!ext4_has_group_desc_csum(sb))
3477                 return ngroups;
3478
3479         for (group = 0; group < ngroups; group++) {
3480                 gdp = ext4_get_group_desc(sb, group, NULL);
3481                 if (!gdp)
3482                         continue;
3483
3484                 if (!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED)))
3485                         break;
3486         }
3487
3488         return group;
3489 }
3490
3491 static int ext4_li_info_new(void)
3492 {
3493         struct ext4_lazy_init *eli = NULL;
3494
3495         eli = kzalloc(sizeof(*eli), GFP_KERNEL);
3496         if (!eli)
3497                 return -ENOMEM;
3498
3499         INIT_LIST_HEAD(&eli->li_request_list);
3500         mutex_init(&eli->li_list_mtx);
3501
3502         eli->li_state |= EXT4_LAZYINIT_QUIT;
3503
3504         ext4_li_info = eli;
3505
3506         return 0;
3507 }
3508
3509 static struct ext4_li_request *ext4_li_request_new(struct super_block *sb,
3510                                             ext4_group_t start)
3511 {
3512         struct ext4_li_request *elr;
3513
3514         elr = kzalloc(sizeof(*elr), GFP_KERNEL);
3515         if (!elr)
3516                 return NULL;
3517
3518         elr->lr_super = sb;
3519         elr->lr_first_not_zeroed = start;
3520         if (test_opt(sb, PREFETCH_BLOCK_BITMAPS))
3521                 elr->lr_mode = EXT4_LI_MODE_PREFETCH_BBITMAP;
3522         else {
3523                 elr->lr_mode = EXT4_LI_MODE_ITABLE;
3524                 elr->lr_next_group = start;
3525         }
3526
3527         /*
3528          * Randomize first schedule time of the request to
3529          * spread the inode table initialization requests
3530          * better.
3531          */
3532         elr->lr_next_sched = jiffies + (prandom_u32() %
3533                                 (EXT4_DEF_LI_MAX_START_DELAY * HZ));
3534         return elr;
3535 }
3536
3537 int ext4_register_li_request(struct super_block *sb,
3538                              ext4_group_t first_not_zeroed)
3539 {
3540         struct ext4_sb_info *sbi = EXT4_SB(sb);
3541         struct ext4_li_request *elr = NULL;
3542         ext4_group_t ngroups = sbi->s_groups_count;
3543         int ret = 0;
3544
3545         mutex_lock(&ext4_li_mtx);
3546         if (sbi->s_li_request != NULL) {
3547                 /*
3548                  * Reset timeout so it can be computed again, because
3549                  * s_li_wait_mult might have changed.
3550                  */
3551                 sbi->s_li_request->lr_timeout = 0;
3552                 goto out;
3553         }
3554
3555         if (!test_opt(sb, PREFETCH_BLOCK_BITMAPS) &&
3556             (first_not_zeroed == ngroups || sb_rdonly(sb) ||
3557              !test_opt(sb, INIT_INODE_TABLE)))
3558                 goto out;
3559
3560         elr = ext4_li_request_new(sb, first_not_zeroed);
3561         if (!elr) {
3562                 ret = -ENOMEM;
3563                 goto out;
3564         }
3565
3566         if (NULL == ext4_li_info) {
3567                 ret = ext4_li_info_new();
3568                 if (ret)
3569                         goto out;
3570         }
3571
3572         mutex_lock(&ext4_li_info->li_list_mtx);
3573         list_add(&elr->lr_request, &ext4_li_info->li_request_list);
3574         mutex_unlock(&ext4_li_info->li_list_mtx);
3575
3576         sbi->s_li_request = elr;
3577         /*
3578          * set elr to NULL here since it has been inserted to
3579          * the request_list and the removal and free of it is
3580          * handled by ext4_clear_request_list from now on.
3581          */
3582         elr = NULL;
3583
3584         if (!(ext4_li_info->li_state & EXT4_LAZYINIT_RUNNING)) {
3585                 ret = ext4_run_lazyinit_thread();
3586                 if (ret)
3587                         goto out;
3588         }
3589 out:
3590         mutex_unlock(&ext4_li_mtx);
3591         if (ret)
3592                 kfree(elr);
3593         return ret;
3594 }
3595
3596 /*
3597  * We do not need to lock anything since this is called on
3598  * module unload.
3599  */
3600 static void ext4_destroy_lazyinit_thread(void)
3601 {
3602         /*
3603          * If thread exited earlier
3604          * there's nothing to be done.
3605          */
3606         if (!ext4_li_info || !ext4_lazyinit_task)
3607                 return;
3608
3609         kthread_stop(ext4_lazyinit_task);
3610 }
3611
3612 static int set_journal_csum_feature_set(struct super_block *sb)
3613 {
3614         int ret = 1;
3615         int compat, incompat;
3616         struct ext4_sb_info *sbi = EXT4_SB(sb);
3617
3618         if (ext4_has_metadata_csum(sb)) {
3619                 /* journal checksum v3 */
3620                 compat = 0;
3621                 incompat = JBD2_FEATURE_INCOMPAT_CSUM_V3;
3622         } else {
3623                 /* journal checksum v1 */
3624                 compat = JBD2_FEATURE_COMPAT_CHECKSUM;
3625                 incompat = 0;
3626         }
3627
3628         jbd2_journal_clear_features(sbi->s_journal,
3629                         JBD2_FEATURE_COMPAT_CHECKSUM, 0,
3630                         JBD2_FEATURE_INCOMPAT_CSUM_V3 |
3631                         JBD2_FEATURE_INCOMPAT_CSUM_V2);
3632         if (test_opt(sb, JOURNAL_ASYNC_COMMIT)) {
3633                 ret = jbd2_journal_set_features(sbi->s_journal,
3634                                 compat, 0,
3635                                 JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT |
3636                                 incompat);
3637         } else if (test_opt(sb, JOURNAL_CHECKSUM)) {
3638                 ret = jbd2_journal_set_features(sbi->s_journal,
3639                                 compat, 0,
3640                                 incompat);
3641                 jbd2_journal_clear_features(sbi->s_journal, 0, 0,
3642                                 JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT);
3643         } else {
3644                 jbd2_journal_clear_features(sbi->s_journal, 0, 0,
3645                                 JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT);
3646         }
3647
3648         return ret;
3649 }
3650
3651 /*
3652  * Note: calculating the overhead so we can be compatible with
3653  * historical BSD practice is quite difficult in the face of
3654  * clusters/bigalloc.  This is because multiple metadata blocks from
3655  * different block group can end up in the same allocation cluster.
3656  * Calculating the exact overhead in the face of clustered allocation
3657  * requires either O(all block bitmaps) in memory or O(number of block
3658  * groups**2) in time.  We will still calculate the superblock for
3659  * older file systems --- and if we come across with a bigalloc file
3660  * system with zero in s_overhead_clusters the estimate will be close to
3661  * correct especially for very large cluster sizes --- but for newer
3662  * file systems, it's better to calculate this figure once at mkfs
3663  * time, and store it in the superblock.  If the superblock value is
3664  * present (even for non-bigalloc file systems), we will use it.
3665  */
3666 static int count_overhead(struct super_block *sb, ext4_group_t grp,
3667                           char *buf)
3668 {
3669         struct ext4_sb_info     *sbi = EXT4_SB(sb);
3670         struct ext4_group_desc  *gdp;
3671         ext4_fsblk_t            first_block, last_block, b;
3672         ext4_group_t            i, ngroups = ext4_get_groups_count(sb);
3673         int                     s, j, count = 0;
3674
3675         if (!ext4_has_feature_bigalloc(sb))
3676                 return (ext4_bg_has_super(sb, grp) + ext4_bg_num_gdb(sb, grp) +
3677                         sbi->s_itb_per_group + 2);
3678
3679         first_block = le32_to_cpu(sbi->s_es->s_first_data_block) +
3680                 (grp * EXT4_BLOCKS_PER_GROUP(sb));
3681         last_block = first_block + EXT4_BLOCKS_PER_GROUP(sb) - 1;
3682         for (i = 0; i < ngroups; i++) {
3683                 gdp = ext4_get_group_desc(sb, i, NULL);
3684                 b = ext4_block_bitmap(sb, gdp);
3685                 if (b >= first_block && b <= last_block) {
3686                         ext4_set_bit(EXT4_B2C(sbi, b - first_block), buf);
3687                         count++;
3688                 }
3689                 b = ext4_inode_bitmap(sb, gdp);
3690                 if (b >= first_block && b <= last_block) {
3691                         ext4_set_bit(EXT4_B2C(sbi, b - first_block), buf);
3692                         count++;
3693                 }
3694                 b = ext4_inode_table(sb, gdp);
3695                 if (b >= first_block && b + sbi->s_itb_per_group <= last_block)
3696                         for (j = 0; j < sbi->s_itb_per_group; j++, b++) {
3697                                 int c = EXT4_B2C(sbi, b - first_block);
3698                                 ext4_set_bit(c, buf);
3699                                 count++;
3700                         }
3701                 if (i != grp)
3702                         continue;
3703                 s = 0;
3704                 if (ext4_bg_has_super(sb, grp)) {
3705                         ext4_set_bit(s++, buf);
3706                         count++;
3707                 }
3708                 j = ext4_bg_num_gdb(sb, grp);
3709                 if (s + j > EXT4_BLOCKS_PER_GROUP(sb)) {
3710                         ext4_error(sb, "Invalid number of block group "
3711                                    "descriptor blocks: %d", j);
3712                         j = EXT4_BLOCKS_PER_GROUP(sb) - s;
3713                 }
3714                 count += j;
3715                 for (; j > 0; j--)
3716                         ext4_set_bit(EXT4_B2C(sbi, s++), buf);
3717         }
3718         if (!count)
3719                 return 0;
3720         return EXT4_CLUSTERS_PER_GROUP(sb) -
3721                 ext4_count_free(buf, EXT4_CLUSTERS_PER_GROUP(sb) / 8);
3722 }
3723
3724 /*
3725  * Compute the overhead and stash it in sbi->s_overhead
3726  */
3727 int ext4_calculate_overhead(struct super_block *sb)
3728 {
3729         struct ext4_sb_info *sbi = EXT4_SB(sb);
3730         struct ext4_super_block *es = sbi->s_es;
3731         struct inode *j_inode;
3732         unsigned int j_blocks, j_inum = le32_to_cpu(es->s_journal_inum);
3733         ext4_group_t i, ngroups = ext4_get_groups_count(sb);
3734         ext4_fsblk_t overhead = 0;
3735         char *buf = (char *) get_zeroed_page(GFP_NOFS);
3736
3737         if (!buf)
3738                 return -ENOMEM;
3739
3740         /*
3741          * Compute the overhead (FS structures).  This is constant
3742          * for a given filesystem unless the number of block groups
3743          * changes so we cache the previous value until it does.
3744          */
3745
3746         /*
3747          * All of the blocks before first_data_block are overhead
3748          */
3749         overhead = EXT4_B2C(sbi, le32_to_cpu(es->s_first_data_block));
3750
3751         /*
3752          * Add the overhead found in each block group
3753          */
3754         for (i = 0; i < ngroups; i++) {
3755                 int blks;
3756
3757                 blks = count_overhead(sb, i, buf);
3758                 overhead += blks;
3759                 if (blks)
3760                         memset(buf, 0, PAGE_SIZE);
3761                 cond_resched();
3762         }
3763
3764         /*
3765          * Add the internal journal blocks whether the journal has been
3766          * loaded or not
3767          */
3768         if (sbi->s_journal && !sbi->s_journal_bdev)
3769                 overhead += EXT4_NUM_B2C(sbi, sbi->s_journal->j_maxlen);
3770         else if (ext4_has_feature_journal(sb) && !sbi->s_journal && j_inum) {
3771                 /* j_inum for internal journal is non-zero */
3772                 j_inode = ext4_get_journal_inode(sb, j_inum);
3773                 if (j_inode) {
3774                         j_blocks = j_inode->i_size >> sb->s_blocksize_bits;
3775                         overhead += EXT4_NUM_B2C(sbi, j_blocks);
3776                         iput(j_inode);
3777                 } else {
3778                         ext4_msg(sb, KERN_ERR, "can't get journal size");
3779                 }
3780         }
3781         sbi->s_overhead = overhead;
3782         smp_wmb();
3783         free_page((unsigned long) buf);
3784         return 0;
3785 }
3786
3787 static void ext4_set_resv_clusters(struct super_block *sb)
3788 {
3789         ext4_fsblk_t resv_clusters;
3790         struct ext4_sb_info *sbi = EXT4_SB(sb);
3791
3792         /*
3793          * There's no need to reserve anything when we aren't using extents.
3794          * The space estimates are exact, there are no unwritten extents,
3795          * hole punching doesn't need new metadata... This is needed especially
3796          * to keep ext2/3 backward compatibility.
3797          */
3798         if (!ext4_has_feature_extents(sb))
3799                 return;
3800         /*
3801          * By default we reserve 2% or 4096 clusters, whichever is smaller.
3802          * This should cover the situations where we can not afford to run
3803          * out of space like for example punch hole, or converting
3804          * unwritten extents in delalloc path. In most cases such
3805          * allocation would require 1, or 2 blocks, higher numbers are
3806          * very rare.
3807          */
3808         resv_clusters = (ext4_blocks_count(sbi->s_es) >>
3809                          sbi->s_cluster_bits);
3810
3811         do_div(resv_clusters, 50);
3812         resv_clusters = min_t(ext4_fsblk_t, resv_clusters, 4096);
3813
3814         atomic64_set(&sbi->s_resv_clusters, resv_clusters);
3815 }
3816
3817 static int ext4_fill_super(struct super_block *sb, void *data, int silent)
3818 {
3819         struct dax_device *dax_dev = fs_dax_get_by_bdev(sb->s_bdev);
3820         char *orig_data = kstrdup(data, GFP_KERNEL);
3821         struct buffer_head *bh, **group_desc;
3822         struct ext4_super_block *es = NULL;
3823         struct ext4_sb_info *sbi = kzalloc(sizeof(*sbi), GFP_KERNEL);
3824         struct flex_groups **flex_groups;
3825         ext4_fsblk_t block;
3826         ext4_fsblk_t sb_block = get_sb_block(&data);
3827         ext4_fsblk_t logical_sb_block;
3828         unsigned long offset = 0;
3829         unsigned long journal_devnum = 0;
3830         unsigned long def_mount_opts;
3831         struct inode *root;
3832         const char *descr;
3833         int ret = -ENOMEM;
3834         int blocksize, clustersize;
3835         unsigned int db_count;
3836         unsigned int i;
3837         int needs_recovery, has_huge_files;
3838         __u64 blocks_count;
3839         int err = 0;
3840         unsigned int journal_ioprio = DEFAULT_JOURNAL_IOPRIO;
3841         ext4_group_t first_not_zeroed;
3842
3843         if ((data && !orig_data) || !sbi)
3844                 goto out_free_base;
3845
3846         sbi->s_daxdev = dax_dev;
3847         sbi->s_blockgroup_lock =
3848                 kzalloc(sizeof(struct blockgroup_lock), GFP_KERNEL);
3849         if (!sbi->s_blockgroup_lock)
3850                 goto out_free_base;
3851
3852         sb->s_fs_info = sbi;
3853         sbi->s_sb = sb;
3854         sbi->s_inode_readahead_blks = EXT4_DEF_INODE_READAHEAD_BLKS;
3855         sbi->s_sb_block = sb_block;
3856         if (sb->s_bdev->bd_part)
3857                 sbi->s_sectors_written_start =
3858                         part_stat_read(sb->s_bdev->bd_part, sectors[STAT_WRITE]);
3859
3860         /* Cleanup superblock name */
3861         strreplace(sb->s_id, '/', '!');
3862
3863         /* -EINVAL is default */
3864         ret = -EINVAL;
3865         blocksize = sb_min_blocksize(sb, EXT4_MIN_BLOCK_SIZE);
3866         if (!blocksize) {
3867                 ext4_msg(sb, KERN_ERR, "unable to set blocksize");
3868                 goto out_fail;
3869         }
3870
3871         /*
3872          * The ext4 superblock will not be buffer aligned for other than 1kB
3873          * block sizes.  We need to calculate the offset from buffer start.
3874          */
3875         if (blocksize != EXT4_MIN_BLOCK_SIZE) {
3876                 logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE;
3877                 offset = do_div(logical_sb_block, blocksize);
3878         } else {
3879                 logical_sb_block = sb_block;
3880         }
3881
3882         if (!(bh = sb_bread_unmovable(sb, logical_sb_block))) {
3883                 ext4_msg(sb, KERN_ERR, "unable to read superblock");
3884                 goto out_fail;
3885         }
3886         /*
3887          * Note: s_es must be initialized as soon as possible because
3888          *       some ext4 macro-instructions depend on its value
3889          */
3890         es = (struct ext4_super_block *) (bh->b_data + offset);
3891         sbi->s_es = es;
3892         sb->s_magic = le16_to_cpu(es->s_magic);
3893         if (sb->s_magic != EXT4_SUPER_MAGIC)
3894                 goto cantfind_ext4;
3895         sbi->s_kbytes_written = le64_to_cpu(es->s_kbytes_written);
3896
3897         /* Warn if metadata_csum and gdt_csum are both set. */
3898         if (ext4_has_feature_metadata_csum(sb) &&
3899             ext4_has_feature_gdt_csum(sb))
3900                 ext4_warning(sb, "metadata_csum and uninit_bg are "
3901                              "redundant flags; please run fsck.");
3902
3903         /* Check for a known checksum algorithm */
3904         if (!ext4_verify_csum_type(sb, es)) {
3905                 ext4_msg(sb, KERN_ERR, "VFS: Found ext4 filesystem with "
3906                          "unknown checksum algorithm.");
3907                 silent = 1;
3908                 goto cantfind_ext4;
3909         }
3910
3911         /* Load the checksum driver */
3912         sbi->s_chksum_driver = crypto_alloc_shash("crc32c", 0, 0);
3913         if (IS_ERR(sbi->s_chksum_driver)) {
3914                 ext4_msg(sb, KERN_ERR, "Cannot load crc32c driver.");
3915                 ret = PTR_ERR(sbi->s_chksum_driver);
3916                 sbi->s_chksum_driver = NULL;
3917                 goto failed_mount;
3918         }
3919
3920         /* Check superblock checksum */
3921         if (!ext4_superblock_csum_verify(sb, es)) {
3922                 ext4_msg(sb, KERN_ERR, "VFS: Found ext4 filesystem with "
3923                          "invalid superblock checksum.  Run e2fsck?");
3924                 silent = 1;
3925                 ret = -EFSBADCRC;
3926                 goto cantfind_ext4;
3927         }
3928
3929         /* Precompute checksum seed for all metadata */
3930         if (ext4_has_feature_csum_seed(sb))
3931                 sbi->s_csum_seed = le32_to_cpu(es->s_checksum_seed);
3932         else if (ext4_has_metadata_csum(sb) || ext4_has_feature_ea_inode(sb))
3933                 sbi->s_csum_seed = ext4_chksum(sbi, ~0, es->s_uuid,
3934                                                sizeof(es->s_uuid));
3935
3936         /* Set defaults before we parse the mount options */
3937         def_mount_opts = le32_to_cpu(es->s_default_mount_opts);
3938         set_opt(sb, INIT_INODE_TABLE);
3939         if (def_mount_opts & EXT4_DEFM_DEBUG)
3940                 set_opt(sb, DEBUG);
3941         if (def_mount_opts & EXT4_DEFM_BSDGROUPS)
3942                 set_opt(sb, GRPID);
3943         if (def_mount_opts & EXT4_DEFM_UID16)
3944                 set_opt(sb, NO_UID32);
3945         /* xattr user namespace & acls are now defaulted on */
3946         set_opt(sb, XATTR_USER);
3947 #ifdef CONFIG_EXT4_FS_POSIX_ACL
3948         set_opt(sb, POSIX_ACL);
3949 #endif
3950         /* don't forget to enable journal_csum when metadata_csum is enabled. */
3951         if (ext4_has_metadata_csum(sb))
3952                 set_opt(sb, JOURNAL_CHECKSUM);
3953
3954         if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_DATA)
3955                 set_opt(sb, JOURNAL_DATA);
3956         else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_ORDERED)
3957                 set_opt(sb, ORDERED_DATA);
3958         else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_WBACK)
3959                 set_opt(sb, WRITEBACK_DATA);
3960
3961         if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_PANIC)
3962                 set_opt(sb, ERRORS_PANIC);
3963         else if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_CONTINUE)
3964                 set_opt(sb, ERRORS_CONT);
3965         else
3966                 set_opt(sb, ERRORS_RO);
3967         /* block_validity enabled by default; disable with noblock_validity */
3968         set_opt(sb, BLOCK_VALIDITY);
3969         if (def_mount_opts & EXT4_DEFM_DISCARD)
3970                 set_opt(sb, DISCARD);
3971
3972         sbi->s_resuid = make_kuid(&init_user_ns, le16_to_cpu(es->s_def_resuid));
3973         sbi->s_resgid = make_kgid(&init_user_ns, le16_to_cpu(es->s_def_resgid));
3974         sbi->s_commit_interval = JBD2_DEFAULT_MAX_COMMIT_AGE * HZ;
3975         sbi->s_min_batch_time = EXT4_DEF_MIN_BATCH_TIME;
3976         sbi->s_max_batch_time = EXT4_DEF_MAX_BATCH_TIME;
3977
3978         if ((def_mount_opts & EXT4_DEFM_NOBARRIER) == 0)
3979                 set_opt(sb, BARRIER);
3980
3981         /*
3982          * enable delayed allocation by default
3983          * Use -o nodelalloc to turn it off
3984          */
3985         if (!IS_EXT3_SB(sb) && !IS_EXT2_SB(sb) &&
3986             ((def_mount_opts & EXT4_DEFM_NODELALLOC) == 0))
3987                 set_opt(sb, DELALLOC);
3988
3989         /*
3990          * set default s_li_wait_mult for lazyinit, for the case there is
3991          * no mount option specified.
3992          */
3993         sbi->s_li_wait_mult = EXT4_DEF_LI_WAIT_MULT;
3994
3995         blocksize = BLOCK_SIZE << le32_to_cpu(es->s_log_block_size);
3996
3997         if (blocksize == PAGE_SIZE)
3998                 set_opt(sb, DIOREAD_NOLOCK);
3999
4000         if (blocksize < EXT4_MIN_BLOCK_SIZE ||
4001             blocksize > EXT4_MAX_BLOCK_SIZE) {
4002                 ext4_msg(sb, KERN_ERR,
4003                        "Unsupported filesystem blocksize %d (%d log_block_size)",
4004                          blocksize, le32_to_cpu(es->s_log_block_size));
4005                 goto failed_mount;
4006         }
4007
4008         if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV) {
4009                 sbi->s_inode_size = EXT4_GOOD_OLD_INODE_SIZE;
4010                 sbi->s_first_ino = EXT4_GOOD_OLD_FIRST_INO;
4011         } else {
4012                 sbi->s_inode_size = le16_to_cpu(es->s_inode_size);
4013                 sbi->s_first_ino = le32_to_cpu(es->s_first_ino);
4014                 if (sbi->s_first_ino < EXT4_GOOD_OLD_FIRST_INO) {
4015                         ext4_msg(sb, KERN_ERR, "invalid first ino: %u",
4016                                  sbi->s_first_ino);
4017                         goto failed_mount;
4018                 }
4019                 if ((sbi->s_inode_size < EXT4_GOOD_OLD_INODE_SIZE) ||
4020                     (!is_power_of_2(sbi->s_inode_size)) ||
4021                     (sbi->s_inode_size > blocksize)) {
4022                         ext4_msg(sb, KERN_ERR,
4023                                "unsupported inode size: %d",
4024                                sbi->s_inode_size);
4025                         ext4_msg(sb, KERN_ERR, "blocksize: %d", blocksize);
4026                         goto failed_mount;
4027                 }
4028                 /*
4029                  * i_atime_extra is the last extra field available for
4030                  * [acm]times in struct ext4_inode. Checking for that
4031                  * field should suffice to ensure we have extra space
4032                  * for all three.
4033                  */
4034                 if (sbi->s_inode_size >= offsetof(struct ext4_inode, i_atime_extra) +
4035                         sizeof(((struct ext4_inode *)0)->i_atime_extra)) {
4036                         sb->s_time_gran = 1;
4037                         sb->s_time_max = EXT4_EXTRA_TIMESTAMP_MAX;
4038                 } else {
4039                         sb->s_time_gran = NSEC_PER_SEC;
4040                         sb->s_time_max = EXT4_NON_EXTRA_TIMESTAMP_MAX;
4041                 }
4042                 sb->s_time_min = EXT4_TIMESTAMP_MIN;
4043         }
4044         if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE) {
4045                 sbi->s_want_extra_isize = sizeof(struct ext4_inode) -
4046                         EXT4_GOOD_OLD_INODE_SIZE;
4047                 if (ext4_has_feature_extra_isize(sb)) {
4048                         unsigned v, max = (sbi->s_inode_size -
4049                                            EXT4_GOOD_OLD_INODE_SIZE);
4050
4051                         v = le16_to_cpu(es->s_want_extra_isize);
4052                         if (v > max) {
4053                                 ext4_msg(sb, KERN_ERR,
4054                                          "bad s_want_extra_isize: %d", v);
4055                                 goto failed_mount;
4056                         }
4057                         if (sbi->s_want_extra_isize < v)
4058                                 sbi->s_want_extra_isize = v;
4059
4060                         v = le16_to_cpu(es->s_min_extra_isize);
4061                         if (v > max) {
4062                                 ext4_msg(sb, KERN_ERR,
4063                                          "bad s_min_extra_isize: %d", v);
4064                                 goto failed_mount;
4065                         }
4066                         if (sbi->s_want_extra_isize < v)
4067                                 sbi->s_want_extra_isize = v;
4068                 }
4069         }
4070
4071         if (sbi->s_es->s_mount_opts[0]) {
4072                 char *s_mount_opts = kstrndup(sbi->s_es->s_mount_opts,
4073                                               sizeof(sbi->s_es->s_mount_opts),
4074                                               GFP_KERNEL);
4075                 if (!s_mount_opts)
4076                         goto failed_mount;
4077                 if (!parse_options(s_mount_opts, sb, &journal_devnum,
4078                                    &journal_ioprio, 0)) {
4079                         ext4_msg(sb, KERN_WARNING,
4080                                  "failed to parse options in superblock: %s",
4081                                  s_mount_opts);
4082                 }
4083                 kfree(s_mount_opts);
4084         }
4085         sbi->s_def_mount_opt = sbi->s_mount_opt;
4086         if (!parse_options((char *) data, sb, &journal_devnum,
4087                            &journal_ioprio, 0))
4088                 goto failed_mount;
4089
4090 #ifdef CONFIG_UNICODE
4091         if (ext4_has_feature_casefold(sb) && !sbi->s_encoding) {
4092                 const struct ext4_sb_encodings *encoding_info;
4093                 struct unicode_map *encoding;
4094                 __u16 encoding_flags;
4095
4096                 if (ext4_has_feature_encrypt(sb)) {
4097                         ext4_msg(sb, KERN_ERR,
4098                                  "Can't mount with encoding and encryption");
4099                         goto failed_mount;
4100                 }
4101
4102                 if (ext4_sb_read_encoding(es, &encoding_info,
4103                                           &encoding_flags)) {
4104                         ext4_msg(sb, KERN_ERR,
4105                                  "Encoding requested by superblock is unknown");
4106                         goto failed_mount;
4107                 }
4108
4109                 encoding = utf8_load(encoding_info->version);
4110                 if (IS_ERR(encoding)) {
4111                         ext4_msg(sb, KERN_ERR,
4112                                  "can't mount with superblock charset: %s-%s "
4113                                  "not supported by the kernel. flags: 0x%x.",
4114                                  encoding_info->name, encoding_info->version,
4115                                  encoding_flags);
4116                         goto failed_mount;
4117                 }
4118                 ext4_msg(sb, KERN_INFO,"Using encoding defined by superblock: "
4119                          "%s-%s with flags 0x%hx", encoding_info->name,
4120                          encoding_info->version?:"\b", encoding_flags);
4121
4122                 sbi->s_encoding = encoding;
4123                 sbi->s_encoding_flags = encoding_flags;
4124         }
4125 #endif
4126
4127         if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) {
4128                 printk_once(KERN_WARNING "EXT4-fs: Warning: mounting with data=journal disables delayed allocation, dioread_nolock, and O_DIRECT support!\n");
4129                 /* can't mount with both data=journal and dioread_nolock. */
4130                 clear_opt(sb, DIOREAD_NOLOCK);
4131                 if (test_opt2(sb, EXPLICIT_DELALLOC)) {
4132                         ext4_msg(sb, KERN_ERR, "can't mount with "
4133                                  "both data=journal and delalloc");
4134                         goto failed_mount;
4135                 }
4136                 if (test_opt(sb, DAX_ALWAYS)) {
4137                         ext4_msg(sb, KERN_ERR, "can't mount with "
4138                                  "both data=journal and dax");
4139                         goto failed_mount;
4140                 }
4141                 if (ext4_has_feature_encrypt(sb)) {
4142                         ext4_msg(sb, KERN_WARNING,
4143                                  "encrypted files will use data=ordered "
4144                                  "instead of data journaling mode");
4145                 }
4146                 if (test_opt(sb, DELALLOC))
4147                         clear_opt(sb, DELALLOC);
4148         } else {
4149                 sb->s_iflags |= SB_I_CGROUPWB;
4150         }
4151
4152         sb->s_flags = (sb->s_flags & ~SB_POSIXACL) |
4153                 (test_opt(sb, POSIX_ACL) ? SB_POSIXACL : 0);
4154
4155         if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV &&
4156             (ext4_has_compat_features(sb) ||
4157              ext4_has_ro_compat_features(sb) ||
4158              ext4_has_incompat_features(sb)))
4159                 ext4_msg(sb, KERN_WARNING,
4160                        "feature flags set on rev 0 fs, "
4161                        "running e2fsck is recommended");
4162
4163         if (es->s_creator_os == cpu_to_le32(EXT4_OS_HURD)) {
4164                 set_opt2(sb, HURD_COMPAT);
4165                 if (ext4_has_feature_64bit(sb)) {
4166                         ext4_msg(sb, KERN_ERR,
4167                                  "The Hurd can't support 64-bit file systems");
4168                         goto failed_mount;
4169                 }
4170
4171                 /*
4172                  * ea_inode feature uses l_i_version field which is not
4173                  * available in HURD_COMPAT mode.
4174                  */
4175                 if (ext4_has_feature_ea_inode(sb)) {
4176                         ext4_msg(sb, KERN_ERR,
4177                                  "ea_inode feature is not supported for Hurd");
4178                         goto failed_mount;
4179                 }
4180         }
4181
4182         if (IS_EXT2_SB(sb)) {
4183                 if (ext2_feature_set_ok(sb))
4184                         ext4_msg(sb, KERN_INFO, "mounting ext2 file system "
4185                                  "using the ext4 subsystem");
4186                 else {
4187                         /*
4188                          * If we're probing be silent, if this looks like
4189                          * it's actually an ext[34] filesystem.
4190                          */
4191                         if (silent && ext4_feature_set_ok(sb, sb_rdonly(sb)))
4192                                 goto failed_mount;
4193                         ext4_msg(sb, KERN_ERR, "couldn't mount as ext2 due "
4194                                  "to feature incompatibilities");
4195                         goto failed_mount;
4196                 }
4197         }
4198
4199         if (IS_EXT3_SB(sb)) {
4200                 if (ext3_feature_set_ok(sb))
4201                         ext4_msg(sb, KERN_INFO, "mounting ext3 file system "
4202                                  "using the ext4 subsystem");
4203                 else {
4204                         /*
4205                          * If we're probing be silent, if this looks like
4206                          * it's actually an ext4 filesystem.
4207                          */
4208                         if (silent && ext4_feature_set_ok(sb, sb_rdonly(sb)))
4209                                 goto failed_mount;
4210                         ext4_msg(sb, KERN_ERR, "couldn't mount as ext3 due "
4211                                  "to feature incompatibilities");
4212                         goto failed_mount;
4213                 }
4214         }
4215
4216         /*
4217          * Check feature flags regardless of the revision level, since we
4218          * previously didn't change the revision level when setting the flags,
4219          * so there is a chance incompat flags are set on a rev 0 filesystem.
4220          */
4221         if (!ext4_feature_set_ok(sb, (sb_rdonly(sb))))
4222                 goto failed_mount;
4223
4224         if (le32_to_cpu(es->s_log_block_size) >
4225             (EXT4_MAX_BLOCK_LOG_SIZE - EXT4_MIN_BLOCK_LOG_SIZE)) {
4226                 ext4_msg(sb, KERN_ERR,
4227                          "Invalid log block size: %u",
4228                          le32_to_cpu(es->s_log_block_size));
4229                 goto failed_mount;
4230         }
4231         if (le32_to_cpu(es->s_log_cluster_size) >
4232             (EXT4_MAX_CLUSTER_LOG_SIZE - EXT4_MIN_BLOCK_LOG_SIZE)) {
4233                 ext4_msg(sb, KERN_ERR,
4234                          "Invalid log cluster size: %u",
4235                          le32_to_cpu(es->s_log_cluster_size));
4236                 goto failed_mount;
4237         }
4238
4239         if (le16_to_cpu(sbi->s_es->s_reserved_gdt_blocks) > (blocksize / 4)) {
4240                 ext4_msg(sb, KERN_ERR,
4241                          "Number of reserved GDT blocks insanely large: %d",
4242                          le16_to_cpu(sbi->s_es->s_reserved_gdt_blocks));
4243                 goto failed_mount;
4244         }
4245
4246         if (bdev_dax_supported(sb->s_bdev, blocksize))
4247                 set_bit(EXT4_FLAGS_BDEV_IS_DAX, &sbi->s_ext4_flags);
4248
4249         if (sbi->s_mount_opt & EXT4_MOUNT_DAX_ALWAYS) {
4250                 if (ext4_has_feature_inline_data(sb)) {
4251                         ext4_msg(sb, KERN_ERR, "Cannot use DAX on a filesystem"
4252                                         " that may contain inline data");
4253                         goto failed_mount;
4254                 }
4255                 if (!test_bit(EXT4_FLAGS_BDEV_IS_DAX, &sbi->s_ext4_flags)) {
4256                         ext4_msg(sb, KERN_ERR,
4257                                 "DAX unsupported by block device.");
4258                         goto failed_mount;
4259                 }
4260         }
4261
4262         if (ext4_has_feature_encrypt(sb) && es->s_encryption_level) {
4263                 ext4_msg(sb, KERN_ERR, "Unsupported encryption level %d",
4264                          es->s_encryption_level);
4265                 goto failed_mount;
4266         }
4267
4268         if (sb->s_blocksize != blocksize) {
4269                 /* Validate the filesystem blocksize */
4270                 if (!sb_set_blocksize(sb, blocksize)) {
4271                         ext4_msg(sb, KERN_ERR, "bad block size %d",
4272                                         blocksize);
4273                         goto failed_mount;
4274                 }
4275
4276                 brelse(bh);
4277                 logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE;
4278                 offset = do_div(logical_sb_block, blocksize);
4279                 bh = sb_bread_unmovable(sb, logical_sb_block);
4280                 if (!bh) {
4281                         ext4_msg(sb, KERN_ERR,
4282                                "Can't read superblock on 2nd try");
4283                         goto failed_mount;
4284                 }
4285                 es = (struct ext4_super_block *)(bh->b_data + offset);
4286                 sbi->s_es = es;
4287                 if (es->s_magic != cpu_to_le16(EXT4_SUPER_MAGIC)) {
4288                         ext4_msg(sb, KERN_ERR,
4289                                "Magic mismatch, very weird!");
4290                         goto failed_mount;
4291                 }
4292         }
4293
4294         has_huge_files = ext4_has_feature_huge_file(sb);
4295         sbi->s_bitmap_maxbytes = ext4_max_bitmap_size(sb->s_blocksize_bits,
4296                                                       has_huge_files);
4297         sb->s_maxbytes = ext4_max_size(sb->s_blocksize_bits, has_huge_files);
4298
4299         sbi->s_desc_size = le16_to_cpu(es->s_desc_size);
4300         if (ext4_has_feature_64bit(sb)) {
4301                 if (sbi->s_desc_size < EXT4_MIN_DESC_SIZE_64BIT ||
4302                     sbi->s_desc_size > EXT4_MAX_DESC_SIZE ||
4303                     !is_power_of_2(sbi->s_desc_size)) {
4304                         ext4_msg(sb, KERN_ERR,
4305                                "unsupported descriptor size %lu",
4306                                sbi->s_desc_size);
4307                         goto failed_mount;
4308                 }
4309         } else
4310                 sbi->s_desc_size = EXT4_MIN_DESC_SIZE;
4311
4312         sbi->s_blocks_per_group = le32_to_cpu(es->s_blocks_per_group);
4313         sbi->s_inodes_per_group = le32_to_cpu(es->s_inodes_per_group);
4314
4315         sbi->s_inodes_per_block = blocksize / EXT4_INODE_SIZE(sb);
4316         if (sbi->s_inodes_per_block == 0)
4317                 goto cantfind_ext4;
4318         if (sbi->s_inodes_per_group < sbi->s_inodes_per_block ||
4319             sbi->s_inodes_per_group > blocksize * 8) {
4320                 ext4_msg(sb, KERN_ERR, "invalid inodes per group: %lu\n",
4321                          sbi->s_inodes_per_group);
4322                 goto failed_mount;
4323         }
4324         sbi->s_itb_per_group = sbi->s_inodes_per_group /
4325                                         sbi->s_inodes_per_block;
4326         sbi->s_desc_per_block = blocksize / EXT4_DESC_SIZE(sb);
4327         sbi->s_sbh = bh;
4328         sbi->s_mount_state = le16_to_cpu(es->s_state);
4329         sbi->s_addr_per_block_bits = ilog2(EXT4_ADDR_PER_BLOCK(sb));
4330         sbi->s_desc_per_block_bits = ilog2(EXT4_DESC_PER_BLOCK(sb));
4331
4332         for (i = 0; i < 4; i++)
4333                 sbi->s_hash_seed[i] = le32_to_cpu(es->s_hash_seed[i]);
4334         sbi->s_def_hash_version = es->s_def_hash_version;
4335         if (ext4_has_feature_dir_index(sb)) {
4336                 i = le32_to_cpu(es->s_flags);
4337                 if (i & EXT2_FLAGS_UNSIGNED_HASH)
4338                         sbi->s_hash_unsigned = 3;
4339                 else if ((i & EXT2_FLAGS_SIGNED_HASH) == 0) {
4340 #ifdef __CHAR_UNSIGNED__
4341                         if (!sb_rdonly(sb))
4342                                 es->s_flags |=
4343                                         cpu_to_le32(EXT2_FLAGS_UNSIGNED_HASH);
4344                         sbi->s_hash_unsigned = 3;
4345 #else
4346                         if (!sb_rdonly(sb))
4347                                 es->s_flags |=
4348                                         cpu_to_le32(EXT2_FLAGS_SIGNED_HASH);
4349 #endif
4350                 }
4351         }
4352
4353         /* Handle clustersize */
4354         clustersize = BLOCK_SIZE << le32_to_cpu(es->s_log_cluster_size);
4355         if (ext4_has_feature_bigalloc(sb)) {
4356                 if (clustersize < blocksize) {
4357                         ext4_msg(sb, KERN_ERR,
4358                                  "cluster size (%d) smaller than "
4359                                  "block size (%d)", clustersize, blocksize);
4360                         goto failed_mount;
4361                 }
4362                 sbi->s_cluster_bits = le32_to_cpu(es->s_log_cluster_size) -
4363                         le32_to_cpu(es->s_log_block_size);
4364                 sbi->s_clusters_per_group =
4365                         le32_to_cpu(es->s_clusters_per_group);
4366                 if (sbi->s_clusters_per_group > blocksize * 8) {
4367                         ext4_msg(sb, KERN_ERR,
4368                                  "#clusters per group too big: %lu",
4369                                  sbi->s_clusters_per_group);
4370                         goto failed_mount;
4371                 }
4372                 if (sbi->s_blocks_per_group !=
4373                     (sbi->s_clusters_per_group * (clustersize / blocksize))) {
4374                         ext4_msg(sb, KERN_ERR, "blocks per group (%lu) and "
4375                                  "clusters per group (%lu) inconsistent",
4376                                  sbi->s_blocks_per_group,
4377                                  sbi->s_clusters_per_group);
4378                         goto failed_mount;
4379                 }
4380         } else {
4381                 if (clustersize != blocksize) {
4382                         ext4_msg(sb, KERN_ERR,
4383                                  "fragment/cluster size (%d) != "
4384                                  "block size (%d)", clustersize, blocksize);
4385                         goto failed_mount;
4386                 }
4387                 if (sbi->s_blocks_per_group > blocksize * 8) {
4388                         ext4_msg(sb, KERN_ERR,
4389                                  "#blocks per group too big: %lu",
4390                                  sbi->s_blocks_per_group);
4391                         goto failed_mount;
4392                 }
4393                 sbi->s_clusters_per_group = sbi->s_blocks_per_group;
4394                 sbi->s_cluster_bits = 0;
4395         }
4396         sbi->s_cluster_ratio = clustersize / blocksize;
4397
4398         /* Do we have standard group size of clustersize * 8 blocks ? */
4399         if (sbi->s_blocks_per_group == clustersize << 3)
4400                 set_opt2(sb, STD_GROUP_SIZE);
4401
4402         /*
4403          * Test whether we have more sectors than will fit in sector_t,
4404          * and whether the max offset is addressable by the page cache.
4405          */
4406         err = generic_check_addressable(sb->s_blocksize_bits,
4407                                         ext4_blocks_count(es));
4408         if (err) {
4409                 ext4_msg(sb, KERN_ERR, "filesystem"
4410                          " too large to mount safely on this system");
4411                 goto failed_mount;
4412         }
4413
4414         if (EXT4_BLOCKS_PER_GROUP(sb) == 0)
4415                 goto cantfind_ext4;
4416
4417         /* check blocks count against device size */
4418         blocks_count = sb->s_bdev->bd_inode->i_size >> sb->s_blocksize_bits;
4419         if (blocks_count && ext4_blocks_count(es) > blocks_count) {
4420                 ext4_msg(sb, KERN_WARNING, "bad geometry: block count %llu "
4421                        "exceeds size of device (%llu blocks)",
4422                        ext4_blocks_count(es), blocks_count);
4423                 goto failed_mount;
4424         }
4425
4426         /*
4427          * It makes no sense for the first data block to be beyond the end
4428          * of the filesystem.
4429          */
4430         if (le32_to_cpu(es->s_first_data_block) >= ext4_blocks_count(es)) {
4431                 ext4_msg(sb, KERN_WARNING, "bad geometry: first data "
4432                          "block %u is beyond end of filesystem (%llu)",
4433                          le32_to_cpu(es->s_first_data_block),
4434                          ext4_blocks_count(es));
4435                 goto failed_mount;
4436         }
4437         if ((es->s_first_data_block == 0) && (es->s_log_block_size == 0) &&
4438             (sbi->s_cluster_ratio == 1)) {
4439                 ext4_msg(sb, KERN_WARNING, "bad geometry: first data "
4440                          "block is 0 with a 1k block and cluster size");
4441                 goto failed_mount;
4442         }
4443
4444         blocks_count = (ext4_blocks_count(es) -
4445                         le32_to_cpu(es->s_first_data_block) +
4446                         EXT4_BLOCKS_PER_GROUP(sb) - 1);
4447         do_div(blocks_count, EXT4_BLOCKS_PER_GROUP(sb));
4448         if (blocks_count > ((uint64_t)1<<32) - EXT4_DESC_PER_BLOCK(sb)) {
4449                 ext4_msg(sb, KERN_WARNING, "groups count too large: %llu "
4450                        "(block count %llu, first data block %u, "
4451                        "blocks per group %lu)", blocks_count,
4452                        ext4_blocks_count(es),
4453                        le32_to_cpu(es->s_first_data_block),
4454                        EXT4_BLOCKS_PER_GROUP(sb));
4455                 goto failed_mount;
4456         }
4457         sbi->s_groups_count = blocks_count;
4458         sbi->s_blockfile_groups = min_t(ext4_group_t, sbi->s_groups_count,
4459                         (EXT4_MAX_BLOCK_FILE_PHYS / EXT4_BLOCKS_PER_GROUP(sb)));
4460         if (((u64)sbi->s_groups_count * sbi->s_inodes_per_group) !=
4461             le32_to_cpu(es->s_inodes_count)) {
4462                 ext4_msg(sb, KERN_ERR, "inodes count not valid: %u vs %llu",
4463                          le32_to_cpu(es->s_inodes_count),
4464                          ((u64)sbi->s_groups_count * sbi->s_inodes_per_group));
4465                 ret = -EINVAL;
4466                 goto failed_mount;
4467         }
4468         db_count = (sbi->s_groups_count + EXT4_DESC_PER_BLOCK(sb) - 1) /
4469                    EXT4_DESC_PER_BLOCK(sb);
4470         if (ext4_has_feature_meta_bg(sb)) {
4471                 if (le32_to_cpu(es->s_first_meta_bg) > db_count) {
4472                         ext4_msg(sb, KERN_WARNING,
4473                                  "first meta block group too large: %u "
4474                                  "(group descriptor block count %u)",
4475                                  le32_to_cpu(es->s_first_meta_bg), db_count);
4476                         goto failed_mount;
4477                 }
4478         }
4479         rcu_assign_pointer(sbi->s_group_desc,
4480                            kvmalloc_array(db_count,
4481                                           sizeof(struct buffer_head *),
4482                                           GFP_KERNEL));
4483         if (sbi->s_group_desc == NULL) {
4484                 ext4_msg(sb, KERN_ERR, "not enough memory");
4485                 ret = -ENOMEM;
4486                 goto failed_mount;
4487         }
4488
4489         bgl_lock_init(sbi->s_blockgroup_lock);
4490
4491         /* Pre-read the descriptors into the buffer cache */
4492         for (i = 0; i < db_count; i++) {
4493                 block = descriptor_loc(sb, logical_sb_block, i);
4494                 sb_breadahead_unmovable(sb, block);
4495         }
4496
4497         for (i = 0; i < db_count; i++) {
4498                 struct buffer_head *bh;
4499
4500                 block = descriptor_loc(sb, logical_sb_block, i);
4501                 bh = sb_bread_unmovable(sb, block);
4502                 if (!bh) {
4503                         ext4_msg(sb, KERN_ERR,
4504                                "can't read group descriptor %d", i);
4505                         db_count = i;
4506                         goto failed_mount2;
4507                 }
4508                 rcu_read_lock();
4509                 rcu_dereference(sbi->s_group_desc)[i] = bh;
4510                 rcu_read_unlock();
4511         }
4512         sbi->s_gdb_count = db_count;
4513         if (!ext4_check_descriptors(sb, logical_sb_block, &first_not_zeroed)) {
4514                 ext4_msg(sb, KERN_ERR, "group descriptors corrupted!");
4515                 ret = -EFSCORRUPTED;
4516                 goto failed_mount2;
4517         }
4518
4519         timer_setup(&sbi->s_err_report, print_daily_error_info, 0);
4520
4521         /* Register extent status tree shrinker */
4522         if (ext4_es_register_shrinker(sbi))
4523                 goto failed_mount3;
4524
4525         sbi->s_stripe = ext4_get_stripe_size(sbi);
4526         sbi->s_extent_max_zeroout_kb = 32;
4527
4528         /*
4529          * set up enough so that it can read an inode
4530          */
4531         sb->s_op = &ext4_sops;
4532         sb->s_export_op = &ext4_export_ops;
4533         sb->s_xattr = ext4_xattr_handlers;
4534 #ifdef CONFIG_FS_ENCRYPTION
4535         sb->s_cop = &ext4_cryptops;
4536 #endif
4537 #ifdef CONFIG_FS_VERITY
4538         sb->s_vop = &ext4_verityops;
4539 #endif
4540 #ifdef CONFIG_QUOTA
4541         sb->dq_op = &ext4_quota_operations;
4542         if (ext4_has_feature_quota(sb))
4543                 sb->s_qcop = &dquot_quotactl_sysfile_ops;
4544         else
4545                 sb->s_qcop = &ext4_qctl_operations;
4546         sb->s_quota_types = QTYPE_MASK_USR | QTYPE_MASK_GRP | QTYPE_MASK_PRJ;
4547 #endif
4548         memcpy(&sb->s_uuid, es->s_uuid, sizeof(es->s_uuid));
4549
4550         INIT_LIST_HEAD(&sbi->s_orphan); /* unlinked but open files */
4551         mutex_init(&sbi->s_orphan_lock);
4552
4553         sb->s_root = NULL;
4554
4555         needs_recovery = (es->s_last_orphan != 0 ||
4556                           ext4_has_feature_journal_needs_recovery(sb));
4557
4558         if (ext4_has_feature_mmp(sb) && !sb_rdonly(sb))
4559                 if (ext4_multi_mount_protect(sb, le64_to_cpu(es->s_mmp_block)))
4560                         goto failed_mount3a;
4561
4562         /*
4563          * The first inode we look at is the journal inode.  Don't try
4564          * root first: it may be modified in the journal!
4565          */
4566         if (!test_opt(sb, NOLOAD) && ext4_has_feature_journal(sb)) {
4567                 err = ext4_load_journal(sb, es, journal_devnum);
4568                 if (err)
4569                         goto failed_mount3a;
4570         } else if (test_opt(sb, NOLOAD) && !sb_rdonly(sb) &&
4571                    ext4_has_feature_journal_needs_recovery(sb)) {
4572                 ext4_msg(sb, KERN_ERR, "required journal recovery "
4573                        "suppressed and not mounted read-only");
4574                 goto failed_mount_wq;
4575         } else {
4576                 /* Nojournal mode, all journal mount options are illegal */
4577                 if (test_opt2(sb, EXPLICIT_JOURNAL_CHECKSUM)) {
4578                         ext4_msg(sb, KERN_ERR, "can't mount with "
4579                                  "journal_checksum, fs mounted w/o journal");
4580                         goto failed_mount_wq;
4581                 }
4582                 if (test_opt(sb, JOURNAL_ASYNC_COMMIT)) {
4583                         ext4_msg(sb, KERN_ERR, "can't mount with "
4584                                  "journal_async_commit, fs mounted w/o journal");
4585                         goto failed_mount_wq;
4586                 }
4587                 if (sbi->s_commit_interval != JBD2_DEFAULT_MAX_COMMIT_AGE*HZ) {
4588                         ext4_msg(sb, KERN_ERR, "can't mount with "
4589                                  "commit=%lu, fs mounted w/o journal",
4590                                  sbi->s_commit_interval / HZ);
4591                         goto failed_mount_wq;
4592                 }
4593                 if (EXT4_MOUNT_DATA_FLAGS &
4594                     (sbi->s_mount_opt ^ sbi->s_def_mount_opt)) {
4595                         ext4_msg(sb, KERN_ERR, "can't mount with "
4596                                  "data=, fs mounted w/o journal");
4597                         goto failed_mount_wq;
4598                 }
4599                 sbi->s_def_mount_opt &= ~EXT4_MOUNT_JOURNAL_CHECKSUM;
4600                 clear_opt(sb, JOURNAL_CHECKSUM);
4601                 clear_opt(sb, DATA_FLAGS);
4602                 sbi->s_journal = NULL;
4603                 needs_recovery = 0;
4604                 goto no_journal;
4605         }
4606
4607         if (ext4_has_feature_64bit(sb) &&
4608             !jbd2_journal_set_features(EXT4_SB(sb)->s_journal, 0, 0,
4609                                        JBD2_FEATURE_INCOMPAT_64BIT)) {
4610                 ext4_msg(sb, KERN_ERR, "Failed to set 64-bit journal feature");
4611                 goto failed_mount_wq;
4612         }
4613
4614         if (!set_journal_csum_feature_set(sb)) {
4615                 ext4_msg(sb, KERN_ERR, "Failed to set journal checksum "
4616                          "feature set");
4617                 goto failed_mount_wq;
4618         }
4619
4620         /* We have now updated the journal if required, so we can
4621          * validate the data journaling mode. */
4622         switch (test_opt(sb, DATA_FLAGS)) {
4623         case 0:
4624                 /* No mode set, assume a default based on the journal
4625                  * capabilities: ORDERED_DATA if the journal can
4626                  * cope, else JOURNAL_DATA
4627                  */
4628                 if (jbd2_journal_check_available_features
4629                     (sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)) {
4630                         set_opt(sb, ORDERED_DATA);
4631                         sbi->s_def_mount_opt |= EXT4_MOUNT_ORDERED_DATA;
4632                 } else {
4633                         set_opt(sb, JOURNAL_DATA);
4634                         sbi->s_def_mount_opt |= EXT4_MOUNT_JOURNAL_DATA;
4635                 }
4636                 break;
4637
4638         case EXT4_MOUNT_ORDERED_DATA:
4639         case EXT4_MOUNT_WRITEBACK_DATA:
4640                 if (!jbd2_journal_check_available_features
4641                     (sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)) {
4642                         ext4_msg(sb, KERN_ERR, "Journal does not support "
4643                                "requested data journaling mode");
4644                         goto failed_mount_wq;
4645                 }
4646         default:
4647                 break;
4648         }
4649
4650         if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA &&
4651             test_opt(sb, JOURNAL_ASYNC_COMMIT)) {
4652                 ext4_msg(sb, KERN_ERR, "can't mount with "
4653                         "journal_async_commit in data=ordered mode");
4654                 goto failed_mount_wq;
4655         }
4656
4657         set_task_ioprio(sbi->s_journal->j_task, journal_ioprio);
4658
4659         sbi->s_journal->j_commit_callback = ext4_journal_commit_callback;
4660
4661 no_journal:
4662         if (!test_opt(sb, NO_MBCACHE)) {
4663                 sbi->s_ea_block_cache = ext4_xattr_create_cache();
4664                 if (!sbi->s_ea_block_cache) {
4665                         ext4_msg(sb, KERN_ERR,
4666                                  "Failed to create ea_block_cache");
4667                         goto failed_mount_wq;
4668                 }
4669
4670                 if (ext4_has_feature_ea_inode(sb)) {
4671                         sbi->s_ea_inode_cache = ext4_xattr_create_cache();
4672                         if (!sbi->s_ea_inode_cache) {
4673                                 ext4_msg(sb, KERN_ERR,
4674                                          "Failed to create ea_inode_cache");
4675                                 goto failed_mount_wq;
4676                         }
4677                 }
4678         }
4679
4680         if (ext4_has_feature_verity(sb) && blocksize != PAGE_SIZE) {
4681                 ext4_msg(sb, KERN_ERR, "Unsupported blocksize for fs-verity");
4682                 goto failed_mount_wq;
4683         }
4684
4685         if (DUMMY_ENCRYPTION_ENABLED(sbi) && !sb_rdonly(sb) &&
4686             !ext4_has_feature_encrypt(sb)) {
4687                 ext4_set_feature_encrypt(sb);
4688                 ext4_commit_super(sb, 1);
4689         }
4690
4691         /*
4692          * Get the # of file system overhead blocks from the
4693          * superblock if present.
4694          */
4695         if (es->s_overhead_clusters)
4696                 sbi->s_overhead = le32_to_cpu(es->s_overhead_clusters);
4697         else {
4698                 err = ext4_calculate_overhead(sb);
4699                 if (err)
4700                         goto failed_mount_wq;
4701         }
4702
4703         /*
4704          * The maximum number of concurrent works can be high and
4705          * concurrency isn't really necessary.  Limit it to 1.
4706          */
4707         EXT4_SB(sb)->rsv_conversion_wq =
4708                 alloc_workqueue("ext4-rsv-conversion", WQ_MEM_RECLAIM | WQ_UNBOUND, 1);
4709         if (!EXT4_SB(sb)->rsv_conversion_wq) {
4710                 printk(KERN_ERR "EXT4-fs: failed to create workqueue\n");
4711                 ret = -ENOMEM;
4712                 goto failed_mount4;
4713         }
4714
4715         /*
4716          * The jbd2_journal_load will have done any necessary log recovery,
4717          * so we can safely mount the rest of the filesystem now.
4718          */
4719
4720         root = ext4_iget(sb, EXT4_ROOT_INO, EXT4_IGET_SPECIAL);
4721         if (IS_ERR(root)) {
4722                 ext4_msg(sb, KERN_ERR, "get root inode failed");
4723                 ret = PTR_ERR(root);
4724                 root = NULL;
4725                 goto failed_mount4;
4726         }
4727         if (!S_ISDIR(root->i_mode) || !root->i_blocks || !root->i_size) {
4728                 ext4_msg(sb, KERN_ERR, "corrupt root inode, run e2fsck");
4729                 iput(root);
4730                 goto failed_mount4;
4731         }
4732
4733 #ifdef CONFIG_UNICODE
4734         if (sbi->s_encoding)
4735                 sb->s_d_op = &ext4_dentry_ops;
4736 #endif
4737
4738         sb->s_root = d_make_root(root);
4739         if (!sb->s_root) {
4740                 ext4_msg(sb, KERN_ERR, "get root dentry failed");
4741                 ret = -ENOMEM;
4742                 goto failed_mount4;
4743         }
4744
4745         ret = ext4_setup_super(sb, es, sb_rdonly(sb));
4746         if (ret == -EROFS) {
4747                 sb->s_flags |= SB_RDONLY;
4748                 ret = 0;
4749         } else if (ret)
4750                 goto failed_mount4a;
4751
4752         ext4_set_resv_clusters(sb);
4753
4754         if (test_opt(sb, BLOCK_VALIDITY)) {
4755                 err = ext4_setup_system_zone(sb);
4756                 if (err) {
4757                         ext4_msg(sb, KERN_ERR, "failed to initialize system "
4758                                  "zone (%d)", err);
4759                         goto failed_mount4a;
4760                 }
4761         }
4762
4763         ext4_ext_init(sb);
4764         err = ext4_mb_init(sb);
4765         if (err) {
4766                 ext4_msg(sb, KERN_ERR, "failed to initialize mballoc (%d)",
4767                          err);
4768                 goto failed_mount5;
4769         }
4770
4771         block = ext4_count_free_clusters(sb);
4772         ext4_free_blocks_count_set(sbi->s_es, 
4773                                    EXT4_C2B(sbi, block));
4774         ext4_superblock_csum_set(sb);
4775         err = percpu_counter_init(&sbi->s_freeclusters_counter, block,
4776                                   GFP_KERNEL);
4777         if (!err) {
4778                 unsigned long freei = ext4_count_free_inodes(sb);
4779                 sbi->s_es->s_free_inodes_count = cpu_to_le32(freei);
4780                 ext4_superblock_csum_set(sb);
4781                 err = percpu_counter_init(&sbi->s_freeinodes_counter, freei,
4782                                           GFP_KERNEL);
4783         }
4784         if (!err)
4785                 err = percpu_counter_init(&sbi->s_dirs_counter,
4786                                           ext4_count_dirs(sb), GFP_KERNEL);
4787         if (!err)
4788                 err = percpu_counter_init(&sbi->s_dirtyclusters_counter, 0,
4789                                           GFP_KERNEL);
4790         if (!err)
4791                 err = percpu_init_rwsem(&sbi->s_writepages_rwsem);
4792
4793         if (err) {
4794                 ext4_msg(sb, KERN_ERR, "insufficient memory");
4795                 goto failed_mount6;
4796         }
4797
4798         if (ext4_has_feature_flex_bg(sb))
4799                 if (!ext4_fill_flex_info(sb)) {
4800                         ext4_msg(sb, KERN_ERR,
4801                                "unable to initialize "
4802                                "flex_bg meta info!");
4803                         goto failed_mount6;
4804                 }
4805
4806         err = ext4_register_li_request(sb, first_not_zeroed);
4807         if (err)
4808                 goto failed_mount6;
4809
4810         err = ext4_register_sysfs(sb);
4811         if (err)
4812                 goto failed_mount7;
4813
4814 #ifdef CONFIG_QUOTA
4815         /* Enable quota usage during mount. */
4816         if (ext4_has_feature_quota(sb) && !sb_rdonly(sb)) {
4817                 err = ext4_enable_quotas(sb);
4818                 if (err)
4819                         goto failed_mount8;
4820         }
4821 #endif  /* CONFIG_QUOTA */
4822
4823         /*
4824          * Save the original bdev mapping's wb_err value which could be
4825          * used to detect the metadata async write error.
4826          */
4827         spin_lock_init(&sbi->s_bdev_wb_lock);
4828         errseq_check_and_advance(&sb->s_bdev->bd_inode->i_mapping->wb_err,
4829                                  &sbi->s_bdev_wb_err);
4830         sb->s_bdev->bd_super = sb;
4831         EXT4_SB(sb)->s_mount_state |= EXT4_ORPHAN_FS;
4832         ext4_orphan_cleanup(sb, es);
4833         EXT4_SB(sb)->s_mount_state &= ~EXT4_ORPHAN_FS;
4834         if (needs_recovery) {
4835                 ext4_msg(sb, KERN_INFO, "recovery complete");
4836                 err = ext4_mark_recovery_complete(sb, es);
4837                 if (err)
4838                         goto failed_mount8;
4839         }
4840         if (EXT4_SB(sb)->s_journal) {
4841                 if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA)
4842                         descr = " journalled data mode";
4843                 else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA)
4844                         descr = " ordered data mode";
4845                 else
4846                         descr = " writeback data mode";
4847         } else
4848                 descr = "out journal";
4849
4850         if (test_opt(sb, DISCARD)) {
4851                 struct request_queue *q = bdev_get_queue(sb->s_bdev);
4852                 if (!blk_queue_discard(q))
4853                         ext4_msg(sb, KERN_WARNING,
4854                                  "mounting with \"discard\" option, but "
4855                                  "the device does not support discard");
4856         }
4857
4858         if (___ratelimit(&ext4_mount_msg_ratelimit, "EXT4-fs mount"))
4859                 ext4_msg(sb, KERN_INFO, "mounted filesystem with%s. "
4860                          "Opts: %.*s%s%s", descr,
4861                          (int) sizeof(sbi->s_es->s_mount_opts),
4862                          sbi->s_es->s_mount_opts,
4863                          *sbi->s_es->s_mount_opts ? "; " : "", orig_data);
4864
4865         if (es->s_error_count)
4866                 mod_timer(&sbi->s_err_report, jiffies + 300*HZ); /* 5 minutes */
4867
4868         /* Enable message ratelimiting. Default is 10 messages per 5 secs. */
4869         ratelimit_state_init(&sbi->s_err_ratelimit_state, 5 * HZ, 10);
4870         ratelimit_state_init(&sbi->s_warning_ratelimit_state, 5 * HZ, 10);
4871         ratelimit_state_init(&sbi->s_msg_ratelimit_state, 5 * HZ, 10);
4872         atomic_set(&sbi->s_warning_count, 0);
4873         atomic_set(&sbi->s_msg_count, 0);
4874
4875         kfree(orig_data);
4876         return 0;
4877
4878 cantfind_ext4:
4879         if (!silent)
4880                 ext4_msg(sb, KERN_ERR, "VFS: Can't find ext4 filesystem");
4881         goto failed_mount;
4882
4883 failed_mount8:
4884         ext4_unregister_sysfs(sb);
4885         kobject_put(&sbi->s_kobj);
4886 failed_mount7:
4887         ext4_unregister_li_request(sb);
4888 failed_mount6:
4889         ext4_mb_release(sb);
4890         rcu_read_lock();
4891         flex_groups = rcu_dereference(sbi->s_flex_groups);
4892         if (flex_groups) {
4893                 for (i = 0; i < sbi->s_flex_groups_allocated; i++)
4894                         kvfree(flex_groups[i]);
4895                 kvfree(flex_groups);
4896         }
4897         rcu_read_unlock();
4898         percpu_counter_destroy(&sbi->s_freeclusters_counter);
4899         percpu_counter_destroy(&sbi->s_freeinodes_counter);
4900         percpu_counter_destroy(&sbi->s_dirs_counter);
4901         percpu_counter_destroy(&sbi->s_dirtyclusters_counter);
4902         percpu_free_rwsem(&sbi->s_writepages_rwsem);
4903 failed_mount5:
4904         ext4_ext_release(sb);
4905         ext4_release_system_zone(sb);
4906 failed_mount4a:
4907         dput(sb->s_root);
4908         sb->s_root = NULL;
4909 failed_mount4:
4910         ext4_msg(sb, KERN_ERR, "mount failed");
4911         if (EXT4_SB(sb)->rsv_conversion_wq)
4912                 destroy_workqueue(EXT4_SB(sb)->rsv_conversion_wq);
4913 failed_mount_wq:
4914         ext4_xattr_destroy_cache(sbi->s_ea_inode_cache);
4915         sbi->s_ea_inode_cache = NULL;
4916
4917         ext4_xattr_destroy_cache(sbi->s_ea_block_cache);
4918         sbi->s_ea_block_cache = NULL;
4919
4920         if (sbi->s_journal) {
4921                 jbd2_journal_destroy(sbi->s_journal);
4922                 sbi->s_journal = NULL;
4923         }
4924 failed_mount3a:
4925         ext4_es_unregister_shrinker(sbi);
4926 failed_mount3:
4927         del_timer_sync(&sbi->s_err_report);
4928         if (sbi->s_mmp_tsk)
4929                 kthread_stop(sbi->s_mmp_tsk);
4930 failed_mount2:
4931         rcu_read_lock();
4932         group_desc = rcu_dereference(sbi->s_group_desc);
4933         for (i = 0; i < db_count; i++)
4934                 brelse(group_desc[i]);
4935         kvfree(group_desc);
4936         rcu_read_unlock();
4937 failed_mount:
4938         if (sbi->s_chksum_driver)
4939                 crypto_free_shash(sbi->s_chksum_driver);
4940
4941 #ifdef CONFIG_UNICODE
4942         utf8_unload(sbi->s_encoding);
4943 #endif
4944
4945 #ifdef CONFIG_QUOTA
4946         for (i = 0; i < EXT4_MAXQUOTAS; i++)
4947                 kfree(get_qf_name(sb, sbi, i));
4948 #endif
4949         fscrypt_free_dummy_context(&sbi->s_dummy_enc_ctx);
4950         ext4_blkdev_remove(sbi);
4951         brelse(bh);
4952 out_fail:
4953         sb->s_fs_info = NULL;
4954         kfree(sbi->s_blockgroup_lock);
4955 out_free_base:
4956         kfree(sbi);
4957         kfree(orig_data);
4958         fs_put_dax(dax_dev);
4959         return err ? err : ret;
4960 }
4961
4962 /*
4963  * Setup any per-fs journal parameters now.  We'll do this both on
4964  * initial mount, once the journal has been initialised but before we've
4965  * done any recovery; and again on any subsequent remount.
4966  */
4967 static void ext4_init_journal_params(struct super_block *sb, journal_t *journal)
4968 {
4969         struct ext4_sb_info *sbi = EXT4_SB(sb);
4970
4971         journal->j_commit_interval = sbi->s_commit_interval;
4972         journal->j_min_batch_time = sbi->s_min_batch_time;
4973         journal->j_max_batch_time = sbi->s_max_batch_time;
4974
4975         write_lock(&journal->j_state_lock);
4976         if (test_opt(sb, BARRIER))
4977                 journal->j_flags |= JBD2_BARRIER;
4978         else
4979                 journal->j_flags &= ~JBD2_BARRIER;
4980         if (test_opt(sb, DATA_ERR_ABORT))
4981                 journal->j_flags |= JBD2_ABORT_ON_SYNCDATA_ERR;
4982         else
4983                 journal->j_flags &= ~JBD2_ABORT_ON_SYNCDATA_ERR;
4984         write_unlock(&journal->j_state_lock);
4985 }
4986
4987 static struct inode *ext4_get_journal_inode(struct super_block *sb,
4988                                              unsigned int journal_inum)
4989 {
4990         struct inode *journal_inode;
4991
4992         /*
4993          * Test for the existence of a valid inode on disk.  Bad things
4994          * happen if we iget() an unused inode, as the subsequent iput()
4995          * will try to delete it.
4996          */
4997         journal_inode = ext4_iget(sb, journal_inum, EXT4_IGET_SPECIAL);
4998         if (IS_ERR(journal_inode)) {
4999                 ext4_msg(sb, KERN_ERR, "no journal found");
5000                 return NULL;
5001         }
5002         if (!journal_inode->i_nlink) {
5003                 make_bad_inode(journal_inode);
5004                 iput(journal_inode);
5005                 ext4_msg(sb, KERN_ERR, "journal inode is deleted");
5006                 return NULL;
5007         }
5008
5009         jbd_debug(2, "Journal inode found at %p: %lld bytes\n",
5010                   journal_inode, journal_inode->i_size);
5011         if (!S_ISREG(journal_inode->i_mode)) {
5012                 ext4_msg(sb, KERN_ERR, "invalid journal inode");
5013                 iput(journal_inode);
5014                 return NULL;
5015         }
5016         return journal_inode;
5017 }
5018
5019 static journal_t *ext4_get_journal(struct super_block *sb,
5020                                    unsigned int journal_inum)
5021 {
5022         struct inode *journal_inode;
5023         journal_t *journal;
5024
5025         if (WARN_ON_ONCE(!ext4_has_feature_journal(sb)))
5026                 return NULL;
5027
5028         journal_inode = ext4_get_journal_inode(sb, journal_inum);
5029         if (!journal_inode)
5030                 return NULL;
5031
5032         journal = jbd2_journal_init_inode(journal_inode);
5033         if (!journal) {
5034                 ext4_msg(sb, KERN_ERR, "Could not load journal inode");
5035                 iput(journal_inode);
5036                 return NULL;
5037         }
5038         journal->j_private = sb;
5039         ext4_init_journal_params(sb, journal);
5040         return journal;
5041 }
5042
5043 static journal_t *ext4_get_dev_journal(struct super_block *sb,
5044                                        dev_t j_dev)
5045 {
5046         struct buffer_head *bh;
5047         journal_t *journal;
5048         ext4_fsblk_t start;
5049         ext4_fsblk_t len;
5050         int hblock, blocksize;
5051         ext4_fsblk_t sb_block;
5052         unsigned long offset;
5053         struct ext4_super_block *es;
5054         struct block_device *bdev;
5055
5056         if (WARN_ON_ONCE(!ext4_has_feature_journal(sb)))
5057                 return NULL;
5058
5059         bdev = ext4_blkdev_get(j_dev, sb);
5060         if (bdev == NULL)
5061                 return NULL;
5062
5063         blocksize = sb->s_blocksize;
5064         hblock = bdev_logical_block_size(bdev);
5065         if (blocksize < hblock) {
5066                 ext4_msg(sb, KERN_ERR,
5067                         "blocksize too small for journal device");
5068                 goto out_bdev;
5069         }
5070
5071         sb_block = EXT4_MIN_BLOCK_SIZE / blocksize;
5072         offset = EXT4_MIN_BLOCK_SIZE % blocksize;
5073         set_blocksize(bdev, blocksize);
5074         if (!(bh = __bread(bdev, sb_block, blocksize))) {
5075                 ext4_msg(sb, KERN_ERR, "couldn't read superblock of "
5076                        "external journal");
5077                 goto out_bdev;
5078         }
5079
5080         es = (struct ext4_super_block *) (bh->b_data + offset);
5081         if ((le16_to_cpu(es->s_magic) != EXT4_SUPER_MAGIC) ||
5082             !(le32_to_cpu(es->s_feature_incompat) &
5083               EXT4_FEATURE_INCOMPAT_JOURNAL_DEV)) {
5084                 ext4_msg(sb, KERN_ERR, "external journal has "
5085                                         "bad superblock");
5086                 brelse(bh);
5087                 goto out_bdev;
5088         }
5089
5090         if ((le32_to_cpu(es->s_feature_ro_compat) &
5091              EXT4_FEATURE_RO_COMPAT_METADATA_CSUM) &&
5092             es->s_checksum != ext4_superblock_csum(sb, es)) {
5093                 ext4_msg(sb, KERN_ERR, "external journal has "
5094                                        "corrupt superblock");
5095                 brelse(bh);
5096                 goto out_bdev;
5097         }
5098
5099         if (memcmp(EXT4_SB(sb)->s_es->s_journal_uuid, es->s_uuid, 16)) {
5100                 ext4_msg(sb, KERN_ERR, "journal UUID does not match");
5101                 brelse(bh);
5102                 goto out_bdev;
5103         }
5104
5105         len = ext4_blocks_count(es);
5106         start = sb_block + 1;
5107         brelse(bh);     /* we're done with the superblock */
5108
5109         journal = jbd2_journal_init_dev(bdev, sb->s_bdev,
5110                                         start, len, blocksize);
5111         if (!journal) {
5112                 ext4_msg(sb, KERN_ERR, "failed to create device journal");
5113                 goto out_bdev;
5114         }
5115         journal->j_private = sb;
5116         ll_rw_block(REQ_OP_READ, REQ_META | REQ_PRIO, 1, &journal->j_sb_buffer);
5117         wait_on_buffer(journal->j_sb_buffer);
5118         if (!buffer_uptodate(journal->j_sb_buffer)) {
5119                 ext4_msg(sb, KERN_ERR, "I/O error on journal device");
5120                 goto out_journal;
5121         }
5122         if (be32_to_cpu(journal->j_superblock->s_nr_users) != 1) {
5123                 ext4_msg(sb, KERN_ERR, "External journal has more than one "
5124                                         "user (unsupported) - %d",
5125                         be32_to_cpu(journal->j_superblock->s_nr_users));
5126                 goto out_journal;
5127         }
5128         EXT4_SB(sb)->s_journal_bdev = bdev;
5129         ext4_init_journal_params(sb, journal);
5130         return journal;
5131
5132 out_journal:
5133         jbd2_journal_destroy(journal);
5134 out_bdev:
5135         ext4_blkdev_put(bdev);
5136         return NULL;
5137 }
5138
5139 static int ext4_load_journal(struct super_block *sb,
5140                              struct ext4_super_block *es,
5141                              unsigned long journal_devnum)
5142 {
5143         journal_t *journal;
5144         unsigned int journal_inum = le32_to_cpu(es->s_journal_inum);
5145         dev_t journal_dev;
5146         int err = 0;
5147         int really_read_only;
5148         int journal_dev_ro;
5149
5150         if (WARN_ON_ONCE(!ext4_has_feature_journal(sb)))
5151                 return -EFSCORRUPTED;
5152
5153         if (journal_devnum &&
5154             journal_devnum != le32_to_cpu(es->s_journal_dev)) {
5155                 ext4_msg(sb, KERN_INFO, "external journal device major/minor "
5156                         "numbers have changed");
5157                 journal_dev = new_decode_dev(journal_devnum);
5158         } else
5159                 journal_dev = new_decode_dev(le32_to_cpu(es->s_journal_dev));
5160
5161         if (journal_inum && journal_dev) {
5162                 ext4_msg(sb, KERN_ERR,
5163                          "filesystem has both journal inode and journal device!");
5164                 return -EINVAL;
5165         }
5166
5167         if (journal_inum) {
5168                 journal = ext4_get_journal(sb, journal_inum);
5169                 if (!journal)
5170                         return -EINVAL;
5171         } else {
5172                 journal = ext4_get_dev_journal(sb, journal_dev);
5173                 if (!journal)
5174                         return -EINVAL;
5175         }
5176
5177         journal_dev_ro = bdev_read_only(journal->j_dev);
5178         really_read_only = bdev_read_only(sb->s_bdev) | journal_dev_ro;
5179
5180         if (journal_dev_ro && !sb_rdonly(sb)) {
5181                 ext4_msg(sb, KERN_ERR,
5182                          "journal device read-only, try mounting with '-o ro'");
5183                 err = -EROFS;
5184                 goto err_out;
5185         }
5186
5187         /*
5188          * Are we loading a blank journal or performing recovery after a
5189          * crash?  For recovery, we need to check in advance whether we
5190          * can get read-write access to the device.
5191          */
5192         if (ext4_has_feature_journal_needs_recovery(sb)) {
5193                 if (sb_rdonly(sb)) {
5194                         ext4_msg(sb, KERN_INFO, "INFO: recovery "
5195                                         "required on readonly filesystem");
5196                         if (really_read_only) {
5197                                 ext4_msg(sb, KERN_ERR, "write access "
5198                                         "unavailable, cannot proceed "
5199                                         "(try mounting with noload)");
5200                                 err = -EROFS;
5201                                 goto err_out;
5202                         }
5203                         ext4_msg(sb, KERN_INFO, "write access will "
5204                                "be enabled during recovery");
5205                 }
5206         }
5207
5208         if (!(journal->j_flags & JBD2_BARRIER))
5209                 ext4_msg(sb, KERN_INFO, "barriers disabled");
5210
5211         if (!ext4_has_feature_journal_needs_recovery(sb))
5212                 err = jbd2_journal_wipe(journal, !really_read_only);
5213         if (!err) {
5214                 char *save = kmalloc(EXT4_S_ERR_LEN, GFP_KERNEL);
5215                 if (save)
5216                         memcpy(save, ((char *) es) +
5217                                EXT4_S_ERR_START, EXT4_S_ERR_LEN);
5218                 err = jbd2_journal_load(journal);
5219                 if (save)
5220                         memcpy(((char *) es) + EXT4_S_ERR_START,
5221                                save, EXT4_S_ERR_LEN);
5222                 kfree(save);
5223         }
5224
5225         if (err) {
5226                 ext4_msg(sb, KERN_ERR, "error loading journal");
5227                 goto err_out;
5228         }
5229
5230         EXT4_SB(sb)->s_journal = journal;
5231         err = ext4_clear_journal_err(sb, es);
5232         if (err) {
5233                 EXT4_SB(sb)->s_journal = NULL;
5234                 jbd2_journal_destroy(journal);
5235                 return err;
5236         }
5237
5238         if (!really_read_only && journal_devnum &&
5239             journal_devnum != le32_to_cpu(es->s_journal_dev)) {
5240                 es->s_journal_dev = cpu_to_le32(journal_devnum);
5241
5242                 /* Make sure we flush the recovery flag to disk. */
5243                 ext4_commit_super(sb, 1);
5244         }
5245
5246         return 0;
5247
5248 err_out:
5249         jbd2_journal_destroy(journal);
5250         return err;
5251 }
5252
5253 static int ext4_commit_super(struct super_block *sb, int sync)
5254 {
5255         struct ext4_super_block *es = EXT4_SB(sb)->s_es;
5256         struct buffer_head *sbh = EXT4_SB(sb)->s_sbh;
5257         int error = 0;
5258
5259         if (!sbh || block_device_ejected(sb))
5260                 return error;
5261
5262         /*
5263          * If the file system is mounted read-only, don't update the
5264          * superblock write time.  This avoids updating the superblock
5265          * write time when we are mounting the root file system
5266          * read/only but we need to replay the journal; at that point,
5267          * for people who are east of GMT and who make their clock
5268          * tick in localtime for Windows bug-for-bug compatibility,
5269          * the clock is set in the future, and this will cause e2fsck
5270          * to complain and force a full file system check.
5271          */
5272         if (!(sb->s_flags & SB_RDONLY))
5273                 ext4_update_tstamp(es, s_wtime);
5274         if (sb->s_bdev->bd_part)
5275                 es->s_kbytes_written =
5276                         cpu_to_le64(EXT4_SB(sb)->s_kbytes_written +
5277                             ((part_stat_read(sb->s_bdev->bd_part,
5278                                              sectors[STAT_WRITE]) -
5279                               EXT4_SB(sb)->s_sectors_written_start) >> 1));
5280         else
5281                 es->s_kbytes_written =
5282                         cpu_to_le64(EXT4_SB(sb)->s_kbytes_written);
5283         if (percpu_counter_initialized(&EXT4_SB(sb)->s_freeclusters_counter))
5284                 ext4_free_blocks_count_set(es,
5285                         EXT4_C2B(EXT4_SB(sb), percpu_counter_sum_positive(
5286                                 &EXT4_SB(sb)->s_freeclusters_counter)));
5287         if (percpu_counter_initialized(&EXT4_SB(sb)->s_freeinodes_counter))
5288                 es->s_free_inodes_count =
5289                         cpu_to_le32(percpu_counter_sum_positive(
5290                                 &EXT4_SB(sb)->s_freeinodes_counter));
5291         BUFFER_TRACE(sbh, "marking dirty");
5292         ext4_superblock_csum_set(sb);
5293         if (sync)
5294                 lock_buffer(sbh);
5295         if (buffer_write_io_error(sbh) || !buffer_uptodate(sbh)) {
5296                 /*
5297                  * Oh, dear.  A previous attempt to write the
5298                  * superblock failed.  This could happen because the
5299                  * USB device was yanked out.  Or it could happen to
5300                  * be a transient write error and maybe the block will
5301                  * be remapped.  Nothing we can do but to retry the
5302                  * write and hope for the best.
5303                  */
5304                 ext4_msg(sb, KERN_ERR, "previous I/O error to "
5305                        "superblock detected");
5306                 clear_buffer_write_io_error(sbh);
5307                 set_buffer_uptodate(sbh);
5308         }
5309         mark_buffer_dirty(sbh);
5310         if (sync) {
5311                 unlock_buffer(sbh);
5312                 error = __sync_dirty_buffer(sbh,
5313                         REQ_SYNC | (test_opt(sb, BARRIER) ? REQ_FUA : 0));
5314                 if (buffer_write_io_error(sbh)) {
5315                         ext4_msg(sb, KERN_ERR, "I/O error while writing "
5316                                "superblock");
5317                         clear_buffer_write_io_error(sbh);
5318                         set_buffer_uptodate(sbh);
5319                 }
5320         }
5321         return error;
5322 }
5323
5324 /*
5325  * Have we just finished recovery?  If so, and if we are mounting (or
5326  * remounting) the filesystem readonly, then we will end up with a
5327  * consistent fs on disk.  Record that fact.
5328  */
5329 static int ext4_mark_recovery_complete(struct super_block *sb,
5330                                        struct ext4_super_block *es)
5331 {
5332         int err;
5333         journal_t *journal = EXT4_SB(sb)->s_journal;
5334
5335         if (!ext4_has_feature_journal(sb)) {
5336                 if (journal != NULL) {
5337                         ext4_error(sb, "Journal got removed while the fs was "
5338                                    "mounted!");
5339                         return -EFSCORRUPTED;
5340                 }
5341                 return 0;
5342         }
5343         jbd2_journal_lock_updates(journal);
5344         err = jbd2_journal_flush(journal);
5345         if (err < 0)
5346                 goto out;
5347
5348         if (ext4_has_feature_journal_needs_recovery(sb) && sb_rdonly(sb)) {
5349                 ext4_clear_feature_journal_needs_recovery(sb);
5350                 ext4_commit_super(sb, 1);
5351         }
5352 out:
5353         jbd2_journal_unlock_updates(journal);
5354         return err;
5355 }
5356
5357 /*
5358  * If we are mounting (or read-write remounting) a filesystem whose journal
5359  * has recorded an error from a previous lifetime, move that error to the
5360  * main filesystem now.
5361  */
5362 static int ext4_clear_journal_err(struct super_block *sb,
5363                                    struct ext4_super_block *es)
5364 {
5365         journal_t *journal;
5366         int j_errno;
5367         const char *errstr;
5368
5369         if (!ext4_has_feature_journal(sb)) {
5370                 ext4_error(sb, "Journal got removed while the fs was mounted!");
5371                 return -EFSCORRUPTED;
5372         }
5373
5374         journal = EXT4_SB(sb)->s_journal;
5375
5376         /*
5377          * Now check for any error status which may have been recorded in the
5378          * journal by a prior ext4_error() or ext4_abort()
5379          */
5380
5381         j_errno = jbd2_journal_errno(journal);
5382         if (j_errno) {
5383                 char nbuf[16];
5384
5385                 errstr = ext4_decode_error(sb, j_errno, nbuf);
5386                 ext4_warning(sb, "Filesystem error recorded "
5387                              "from previous mount: %s", errstr);
5388                 ext4_warning(sb, "Marking fs in need of filesystem check.");
5389
5390                 EXT4_SB(sb)->s_mount_state |= EXT4_ERROR_FS;
5391                 es->s_state |= cpu_to_le16(EXT4_ERROR_FS);
5392                 ext4_commit_super(sb, 1);
5393
5394                 jbd2_journal_clear_err(journal);
5395                 jbd2_journal_update_sb_errno(journal);
5396         }
5397         return 0;
5398 }
5399
5400 /*
5401  * Force the running and committing transactions to commit,
5402  * and wait on the commit.
5403  */
5404 int ext4_force_commit(struct super_block *sb)
5405 {
5406         journal_t *journal;
5407
5408         if (sb_rdonly(sb))
5409                 return 0;
5410
5411         journal = EXT4_SB(sb)->s_journal;
5412         return ext4_journal_force_commit(journal);
5413 }
5414
5415 static int ext4_sync_fs(struct super_block *sb, int wait)
5416 {
5417         int ret = 0;
5418         tid_t target;
5419         bool needs_barrier = false;
5420         struct ext4_sb_info *sbi = EXT4_SB(sb);
5421
5422         if (unlikely(ext4_forced_shutdown(sbi)))
5423                 return 0;
5424
5425         trace_ext4_sync_fs(sb, wait);
5426         flush_workqueue(sbi->rsv_conversion_wq);
5427         /*
5428          * Writeback quota in non-journalled quota case - journalled quota has
5429          * no dirty dquots
5430          */
5431         dquot_writeback_dquots(sb, -1);
5432         /*
5433          * Data writeback is possible w/o journal transaction, so barrier must
5434          * being sent at the end of the function. But we can skip it if
5435          * transaction_commit will do it for us.
5436          */
5437         if (sbi->s_journal) {
5438                 target = jbd2_get_latest_transaction(sbi->s_journal);
5439                 if (wait && sbi->s_journal->j_flags & JBD2_BARRIER &&
5440                     !jbd2_trans_will_send_data_barrier(sbi->s_journal, target))
5441                         needs_barrier = true;
5442
5443                 if (jbd2_journal_start_commit(sbi->s_journal, &target)) {
5444                         if (wait)
5445                                 ret = jbd2_log_wait_commit(sbi->s_journal,
5446                                                            target);
5447                 }
5448         } else if (wait && test_opt(sb, BARRIER))
5449                 needs_barrier = true;
5450         if (needs_barrier) {
5451                 int err;
5452                 err = blkdev_issue_flush(sb->s_bdev, GFP_KERNEL);
5453                 if (!ret)
5454                         ret = err;
5455         }
5456
5457         return ret;
5458 }
5459
5460 /*
5461  * LVM calls this function before a (read-only) snapshot is created.  This
5462  * gives us a chance to flush the journal completely and mark the fs clean.
5463  *
5464  * Note that only this function cannot bring a filesystem to be in a clean
5465  * state independently. It relies on upper layer to stop all data & metadata
5466  * modifications.
5467  */
5468 static int ext4_freeze(struct super_block *sb)
5469 {
5470         int error = 0;
5471         journal_t *journal;
5472
5473         if (sb_rdonly(sb))
5474                 return 0;
5475
5476         journal = EXT4_SB(sb)->s_journal;
5477
5478         if (journal) {
5479                 /* Now we set up the journal barrier. */
5480                 jbd2_journal_lock_updates(journal);
5481
5482                 /*
5483                  * Don't clear the needs_recovery flag if we failed to
5484                  * flush the journal.
5485                  */
5486                 error = jbd2_journal_flush(journal);
5487                 if (error < 0)
5488                         goto out;
5489
5490                 /* Journal blocked and flushed, clear needs_recovery flag. */
5491                 ext4_clear_feature_journal_needs_recovery(sb);
5492         }
5493
5494         error = ext4_commit_super(sb, 1);
5495 out:
5496         if (journal)
5497                 /* we rely on upper layer to stop further updates */
5498                 jbd2_journal_unlock_updates(journal);
5499         return error;
5500 }
5501
5502 /*
5503  * Called by LVM after the snapshot is done.  We need to reset the RECOVER
5504  * flag here, even though the filesystem is not technically dirty yet.
5505  */
5506 static int ext4_unfreeze(struct super_block *sb)
5507 {
5508         if (sb_rdonly(sb) || ext4_forced_shutdown(EXT4_SB(sb)))
5509                 return 0;
5510
5511         if (EXT4_SB(sb)->s_journal) {
5512                 /* Reset the needs_recovery flag before the fs is unlocked. */
5513                 ext4_set_feature_journal_needs_recovery(sb);
5514         }
5515
5516         ext4_commit_super(sb, 1);
5517         return 0;
5518 }
5519
5520 /*
5521  * Structure to save mount options for ext4_remount's benefit
5522  */
5523 struct ext4_mount_options {
5524         unsigned long s_mount_opt;
5525         unsigned long s_mount_opt2;
5526         kuid_t s_resuid;
5527         kgid_t s_resgid;
5528         unsigned long s_commit_interval;
5529         u32 s_min_batch_time, s_max_batch_time;
5530 #ifdef CONFIG_QUOTA
5531         int s_jquota_fmt;
5532         char *s_qf_names[EXT4_MAXQUOTAS];
5533 #endif
5534 };
5535
5536 static int ext4_remount(struct super_block *sb, int *flags, char *data)
5537 {
5538         struct ext4_super_block *es;
5539         struct ext4_sb_info *sbi = EXT4_SB(sb);
5540         unsigned long old_sb_flags, vfs_flags;
5541         struct ext4_mount_options old_opts;
5542         int enable_quota = 0;
5543         ext4_group_t g;
5544         unsigned int journal_ioprio = DEFAULT_JOURNAL_IOPRIO;
5545         int err = 0;
5546 #ifdef CONFIG_QUOTA
5547         int i, j;
5548         char *to_free[EXT4_MAXQUOTAS];
5549 #endif
5550         char *orig_data = kstrdup(data, GFP_KERNEL);
5551
5552         if (data && !orig_data)
5553                 return -ENOMEM;
5554
5555         /* Store the original options */
5556         old_sb_flags = sb->s_flags;
5557         old_opts.s_mount_opt = sbi->s_mount_opt;
5558         old_opts.s_mount_opt2 = sbi->s_mount_opt2;
5559         old_opts.s_resuid = sbi->s_resuid;
5560         old_opts.s_resgid = sbi->s_resgid;
5561         old_opts.s_commit_interval = sbi->s_commit_interval;
5562         old_opts.s_min_batch_time = sbi->s_min_batch_time;
5563         old_opts.s_max_batch_time = sbi->s_max_batch_time;
5564 #ifdef CONFIG_QUOTA
5565         old_opts.s_jquota_fmt = sbi->s_jquota_fmt;
5566         for (i = 0; i < EXT4_MAXQUOTAS; i++)
5567                 if (sbi->s_qf_names[i]) {
5568                         char *qf_name = get_qf_name(sb, sbi, i);
5569
5570                         old_opts.s_qf_names[i] = kstrdup(qf_name, GFP_KERNEL);
5571                         if (!old_opts.s_qf_names[i]) {
5572                                 for (j = 0; j < i; j++)
5573                                         kfree(old_opts.s_qf_names[j]);
5574                                 kfree(orig_data);
5575                                 return -ENOMEM;
5576                         }
5577                 } else
5578                         old_opts.s_qf_names[i] = NULL;
5579 #endif
5580         if (sbi->s_journal && sbi->s_journal->j_task->io_context)
5581                 journal_ioprio = sbi->s_journal->j_task->io_context->ioprio;
5582
5583         /*
5584          * Some options can be enabled by ext4 and/or by VFS mount flag
5585          * either way we need to make sure it matches in both *flags and
5586          * s_flags. Copy those selected flags from *flags to s_flags
5587          */
5588         vfs_flags = SB_LAZYTIME | SB_I_VERSION;
5589         sb->s_flags = (sb->s_flags & ~vfs_flags) | (*flags & vfs_flags);
5590
5591         if (!parse_options(data, sb, NULL, &journal_ioprio, 1)) {
5592                 err = -EINVAL;
5593                 goto restore_opts;
5594         }
5595
5596         if ((old_opts.s_mount_opt & EXT4_MOUNT_JOURNAL_CHECKSUM) ^
5597             test_opt(sb, JOURNAL_CHECKSUM)) {
5598                 ext4_msg(sb, KERN_ERR, "changing journal_checksum "
5599                          "during remount not supported; ignoring");
5600                 sbi->s_mount_opt ^= EXT4_MOUNT_JOURNAL_CHECKSUM;
5601         }
5602
5603         if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) {
5604                 if (test_opt2(sb, EXPLICIT_DELALLOC)) {
5605                         ext4_msg(sb, KERN_ERR, "can't mount with "
5606                                  "both data=journal and delalloc");
5607                         err = -EINVAL;
5608                         goto restore_opts;
5609                 }
5610                 if (test_opt(sb, DIOREAD_NOLOCK)) {
5611                         ext4_msg(sb, KERN_ERR, "can't mount with "
5612                                  "both data=journal and dioread_nolock");
5613                         err = -EINVAL;
5614                         goto restore_opts;
5615                 }
5616         } else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA) {
5617                 if (test_opt(sb, JOURNAL_ASYNC_COMMIT)) {
5618                         ext4_msg(sb, KERN_ERR, "can't mount with "
5619                                 "journal_async_commit in data=ordered mode");
5620                         err = -EINVAL;
5621                         goto restore_opts;
5622                 }
5623         }
5624
5625         if ((sbi->s_mount_opt ^ old_opts.s_mount_opt) & EXT4_MOUNT_NO_MBCACHE) {
5626                 ext4_msg(sb, KERN_ERR, "can't enable nombcache during remount");
5627                 err = -EINVAL;
5628                 goto restore_opts;
5629         }
5630
5631         if (sbi->s_mount_flags & EXT4_MF_FS_ABORTED)
5632                 ext4_abort(sb, EXT4_ERR_ESHUTDOWN, "Abort forced by user");
5633
5634         sb->s_flags = (sb->s_flags & ~SB_POSIXACL) |
5635                 (test_opt(sb, POSIX_ACL) ? SB_POSIXACL : 0);
5636
5637         es = sbi->s_es;
5638
5639         if (sbi->s_journal) {
5640                 ext4_init_journal_params(sb, sbi->s_journal);
5641                 set_task_ioprio(sbi->s_journal->j_task, journal_ioprio);
5642         }
5643
5644         if ((bool)(*flags & SB_RDONLY) != sb_rdonly(sb)) {
5645                 if (sbi->s_mount_flags & EXT4_MF_FS_ABORTED) {
5646                         err = -EROFS;
5647                         goto restore_opts;
5648                 }
5649
5650                 if (*flags & SB_RDONLY) {
5651                         err = sync_filesystem(sb);
5652                         if (err < 0)
5653                                 goto restore_opts;
5654                         err = dquot_suspend(sb, -1);
5655                         if (err < 0)
5656                                 goto restore_opts;
5657
5658                         /*
5659                          * First of all, the unconditional stuff we have to do
5660                          * to disable replay of the journal when we next remount
5661                          */
5662                         sb->s_flags |= SB_RDONLY;
5663
5664                         /*
5665                          * OK, test if we are remounting a valid rw partition
5666                          * readonly, and if so set the rdonly flag and then
5667                          * mark the partition as valid again.
5668                          */
5669                         if (!(es->s_state & cpu_to_le16(EXT4_VALID_FS)) &&
5670                             (sbi->s_mount_state & EXT4_VALID_FS))
5671                                 es->s_state = cpu_to_le16(sbi->s_mount_state);
5672
5673                         if (sbi->s_journal) {
5674                                 /*
5675                                  * We let remount-ro finish even if marking fs
5676                                  * as clean failed...
5677                                  */
5678                                 ext4_mark_recovery_complete(sb, es);
5679                         }
5680                         if (sbi->s_mmp_tsk)
5681                                 kthread_stop(sbi->s_mmp_tsk);
5682                 } else {
5683                         /* Make sure we can mount this feature set readwrite */
5684                         if (ext4_has_feature_readonly(sb) ||
5685                             !ext4_feature_set_ok(sb, 0)) {
5686                                 err = -EROFS;
5687                                 goto restore_opts;
5688                         }
5689                         /*
5690                          * Make sure the group descriptor checksums
5691                          * are sane.  If they aren't, refuse to remount r/w.
5692                          */
5693                         for (g = 0; g < sbi->s_groups_count; g++) {
5694                                 struct ext4_group_desc *gdp =
5695                                         ext4_get_group_desc(sb, g, NULL);
5696
5697                                 if (!ext4_group_desc_csum_verify(sb, g, gdp)) {
5698                                         ext4_msg(sb, KERN_ERR,
5699                "ext4_remount: Checksum for group %u failed (%u!=%u)",
5700                 g, le16_to_cpu(ext4_group_desc_csum(sb, g, gdp)),
5701                                                le16_to_cpu(gdp->bg_checksum));
5702                                         err = -EFSBADCRC;
5703                                         goto restore_opts;
5704                                 }
5705                         }
5706
5707                         /*
5708                          * If we have an unprocessed orphan list hanging
5709                          * around from a previously readonly bdev mount,
5710                          * require a full umount/remount for now.
5711                          */
5712                         if (es->s_last_orphan) {
5713                                 ext4_msg(sb, KERN_WARNING, "Couldn't "
5714                                        "remount RDWR because of unprocessed "
5715                                        "orphan inode list.  Please "
5716                                        "umount/remount instead");
5717                                 err = -EINVAL;
5718                                 goto restore_opts;
5719                         }
5720
5721                         /*
5722                          * Mounting a RDONLY partition read-write, so reread
5723                          * and store the current valid flag.  (It may have
5724                          * been changed by e2fsck since we originally mounted
5725                          * the partition.)
5726                          */
5727                         if (sbi->s_journal) {
5728                                 err = ext4_clear_journal_err(sb, es);
5729                                 if (err)
5730                                         goto restore_opts;
5731                         }
5732                         sbi->s_mount_state = le16_to_cpu(es->s_state);
5733
5734                         err = ext4_setup_super(sb, es, 0);
5735                         if (err)
5736                                 goto restore_opts;
5737
5738                         sb->s_flags &= ~SB_RDONLY;
5739                         if (ext4_has_feature_mmp(sb))
5740                                 if (ext4_multi_mount_protect(sb,
5741                                                 le64_to_cpu(es->s_mmp_block))) {
5742                                         err = -EROFS;
5743                                         goto restore_opts;
5744                                 }
5745                         enable_quota = 1;
5746                 }
5747         }
5748
5749         /*
5750          * Reinitialize lazy itable initialization thread based on
5751          * current settings
5752          */
5753         if (sb_rdonly(sb) || !test_opt(sb, INIT_INODE_TABLE))
5754                 ext4_unregister_li_request(sb);
5755         else {
5756                 ext4_group_t first_not_zeroed;
5757                 first_not_zeroed = ext4_has_uninit_itable(sb);
5758                 ext4_register_li_request(sb, first_not_zeroed);
5759         }
5760
5761         /*
5762          * Handle creation of system zone data early because it can fail.
5763          * Releasing of existing data is done when we are sure remount will
5764          * succeed.
5765          */
5766         if (test_opt(sb, BLOCK_VALIDITY) && !sbi->s_system_blks) {
5767                 err = ext4_setup_system_zone(sb);
5768                 if (err)
5769                         goto restore_opts;
5770         }
5771
5772         if (sbi->s_journal == NULL && !(old_sb_flags & SB_RDONLY)) {
5773                 err = ext4_commit_super(sb, 1);
5774                 if (err)
5775                         goto restore_opts;
5776         }
5777
5778 #ifdef CONFIG_QUOTA
5779         /* Release old quota file names */
5780         for (i = 0; i < EXT4_MAXQUOTAS; i++)
5781                 kfree(old_opts.s_qf_names[i]);
5782         if (enable_quota) {
5783                 if (sb_any_quota_suspended(sb))
5784                         dquot_resume(sb, -1);
5785                 else if (ext4_has_feature_quota(sb)) {
5786                         err = ext4_enable_quotas(sb);
5787                         if (err)
5788                                 goto restore_opts;
5789                 }
5790         }
5791 #endif
5792         if (!test_opt(sb, BLOCK_VALIDITY) && sbi->s_system_blks)
5793                 ext4_release_system_zone(sb);
5794
5795         /*
5796          * Some options can be enabled by ext4 and/or by VFS mount flag
5797          * either way we need to make sure it matches in both *flags and
5798          * s_flags. Copy those selected flags from s_flags to *flags
5799          */
5800         *flags = (*flags & ~vfs_flags) | (sb->s_flags & vfs_flags);
5801
5802         ext4_msg(sb, KERN_INFO, "re-mounted. Opts: %s", orig_data);
5803         kfree(orig_data);
5804         return 0;
5805
5806 restore_opts:
5807         sb->s_flags = old_sb_flags;
5808         sbi->s_mount_opt = old_opts.s_mount_opt;
5809         sbi->s_mount_opt2 = old_opts.s_mount_opt2;
5810         sbi->s_resuid = old_opts.s_resuid;
5811         sbi->s_resgid = old_opts.s_resgid;
5812         sbi->s_commit_interval = old_opts.s_commit_interval;
5813         sbi->s_min_batch_time = old_opts.s_min_batch_time;
5814         sbi->s_max_batch_time = old_opts.s_max_batch_time;
5815         if (!test_opt(sb, BLOCK_VALIDITY) && sbi->s_system_blks)
5816                 ext4_release_system_zone(sb);
5817 #ifdef CONFIG_QUOTA
5818         sbi->s_jquota_fmt = old_opts.s_jquota_fmt;
5819         for (i = 0; i < EXT4_MAXQUOTAS; i++) {
5820                 to_free[i] = get_qf_name(sb, sbi, i);
5821                 rcu_assign_pointer(sbi->s_qf_names[i], old_opts.s_qf_names[i]);
5822         }
5823         synchronize_rcu();
5824         for (i = 0; i < EXT4_MAXQUOTAS; i++)
5825                 kfree(to_free[i]);
5826 #endif
5827         kfree(orig_data);
5828         return err;
5829 }
5830
5831 #ifdef CONFIG_QUOTA
5832 static int ext4_statfs_project(struct super_block *sb,
5833                                kprojid_t projid, struct kstatfs *buf)
5834 {
5835         struct kqid qid;
5836         struct dquot *dquot;
5837         u64 limit;
5838         u64 curblock;
5839
5840         qid = make_kqid_projid(projid);
5841         dquot = dqget(sb, qid);
5842         if (IS_ERR(dquot))
5843                 return PTR_ERR(dquot);
5844         spin_lock(&dquot->dq_dqb_lock);
5845
5846         limit = min_not_zero(dquot->dq_dqb.dqb_bsoftlimit,
5847                              dquot->dq_dqb.dqb_bhardlimit);
5848         limit >>= sb->s_blocksize_bits;
5849
5850         if (limit && buf->f_blocks > limit) {
5851                 curblock = (dquot->dq_dqb.dqb_curspace +
5852                             dquot->dq_dqb.dqb_rsvspace) >> sb->s_blocksize_bits;
5853                 buf->f_blocks = limit;
5854                 buf->f_bfree = buf->f_bavail =
5855                         (buf->f_blocks > curblock) ?
5856                          (buf->f_blocks - curblock) : 0;
5857         }
5858
5859         limit = min_not_zero(dquot->dq_dqb.dqb_isoftlimit,
5860                              dquot->dq_dqb.dqb_ihardlimit);
5861         if (limit && buf->f_files > limit) {
5862                 buf->f_files = limit;
5863                 buf->f_ffree =
5864                         (buf->f_files > dquot->dq_dqb.dqb_curinodes) ?
5865                          (buf->f_files - dquot->dq_dqb.dqb_curinodes) : 0;
5866         }
5867
5868         spin_unlock(&dquot->dq_dqb_lock);
5869         dqput(dquot);
5870         return 0;
5871 }
5872 #endif
5873
5874 static int ext4_statfs(struct dentry *dentry, struct kstatfs *buf)
5875 {
5876         struct super_block *sb = dentry->d_sb;
5877         struct ext4_sb_info *sbi = EXT4_SB(sb);
5878         struct ext4_super_block *es = sbi->s_es;
5879         ext4_fsblk_t overhead = 0, resv_blocks;
5880         u64 fsid;
5881         s64 bfree;
5882         resv_blocks = EXT4_C2B(sbi, atomic64_read(&sbi->s_resv_clusters));
5883
5884         if (!test_opt(sb, MINIX_DF))
5885                 overhead = sbi->s_overhead;
5886
5887         buf->f_type = EXT4_SUPER_MAGIC;
5888         buf->f_bsize = sb->s_blocksize;
5889         buf->f_blocks = ext4_blocks_count(es) - EXT4_C2B(sbi, overhead);
5890         bfree = percpu_counter_sum_positive(&sbi->s_freeclusters_counter) -
5891                 percpu_counter_sum_positive(&sbi->s_dirtyclusters_counter);
5892         /* prevent underflow in case that few free space is available */
5893         buf->f_bfree = EXT4_C2B(sbi, max_t(s64, bfree, 0));
5894         buf->f_bavail = buf->f_bfree -
5895                         (ext4_r_blocks_count(es) + resv_blocks);
5896         if (buf->f_bfree < (ext4_r_blocks_count(es) + resv_blocks))
5897                 buf->f_bavail = 0;
5898         buf->f_files = le32_to_cpu(es->s_inodes_count);
5899         buf->f_ffree = percpu_counter_sum_positive(&sbi->s_freeinodes_counter);
5900         buf->f_namelen = EXT4_NAME_LEN;
5901         fsid = le64_to_cpup((void *)es->s_uuid) ^
5902                le64_to_cpup((void *)es->s_uuid + sizeof(u64));
5903         buf->f_fsid.val[0] = fsid & 0xFFFFFFFFUL;
5904         buf->f_fsid.val[1] = (fsid >> 32) & 0xFFFFFFFFUL;
5905
5906 #ifdef CONFIG_QUOTA
5907         if (ext4_test_inode_flag(dentry->d_inode, EXT4_INODE_PROJINHERIT) &&
5908             sb_has_quota_limits_enabled(sb, PRJQUOTA))
5909                 ext4_statfs_project(sb, EXT4_I(dentry->d_inode)->i_projid, buf);
5910 #endif
5911         return 0;
5912 }
5913
5914
5915 #ifdef CONFIG_QUOTA
5916
5917 /*
5918  * Helper functions so that transaction is started before we acquire dqio_sem
5919  * to keep correct lock ordering of transaction > dqio_sem
5920  */
5921 static inline struct inode *dquot_to_inode(struct dquot *dquot)
5922 {
5923         return sb_dqopt(dquot->dq_sb)->files[dquot->dq_id.type];
5924 }
5925
5926 static int ext4_write_dquot(struct dquot *dquot)
5927 {
5928         int ret, err;
5929         handle_t *handle;
5930         struct inode *inode;
5931
5932         inode = dquot_to_inode(dquot);
5933         handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
5934                                     EXT4_QUOTA_TRANS_BLOCKS(dquot->dq_sb));
5935         if (IS_ERR(handle))
5936                 return PTR_ERR(handle);
5937         ret = dquot_commit(dquot);
5938         err = ext4_journal_stop(handle);
5939         if (!ret)
5940                 ret = err;
5941         return ret;
5942 }
5943
5944 static int ext4_acquire_dquot(struct dquot *dquot)
5945 {
5946         int ret, err;
5947         handle_t *handle;
5948
5949         handle = ext4_journal_start(dquot_to_inode(dquot), EXT4_HT_QUOTA,
5950                                     EXT4_QUOTA_INIT_BLOCKS(dquot->dq_sb));
5951         if (IS_ERR(handle))
5952                 return PTR_ERR(handle);
5953         ret = dquot_acquire(dquot);
5954         err = ext4_journal_stop(handle);
5955         if (!ret)
5956                 ret = err;
5957         return ret;
5958 }
5959
5960 static int ext4_release_dquot(struct dquot *dquot)
5961 {
5962         int ret, err;
5963         handle_t *handle;
5964
5965         handle = ext4_journal_start(dquot_to_inode(dquot), EXT4_HT_QUOTA,
5966                                     EXT4_QUOTA_DEL_BLOCKS(dquot->dq_sb));
5967         if (IS_ERR(handle)) {
5968                 /* Release dquot anyway to avoid endless cycle in dqput() */
5969                 dquot_release(dquot);
5970                 return PTR_ERR(handle);
5971         }
5972         ret = dquot_release(dquot);
5973         err = ext4_journal_stop(handle);
5974         if (!ret)
5975                 ret = err;
5976         return ret;
5977 }
5978
5979 static int ext4_mark_dquot_dirty(struct dquot *dquot)
5980 {
5981         struct super_block *sb = dquot->dq_sb;
5982         struct ext4_sb_info *sbi = EXT4_SB(sb);
5983
5984         /* Are we journaling quotas? */
5985         if (ext4_has_feature_quota(sb) ||
5986             sbi->s_qf_names[USRQUOTA] || sbi->s_qf_names[GRPQUOTA]) {
5987                 dquot_mark_dquot_dirty(dquot);
5988                 return ext4_write_dquot(dquot);
5989         } else {
5990                 return dquot_mark_dquot_dirty(dquot);
5991         }
5992 }
5993
5994 static int ext4_write_info(struct super_block *sb, int type)
5995 {
5996         int ret, err;
5997         handle_t *handle;
5998
5999         /* Data block + inode block */
6000         handle = ext4_journal_start(d_inode(sb->s_root), EXT4_HT_QUOTA, 2);
6001         if (IS_ERR(handle))
6002                 return PTR_ERR(handle);
6003         ret = dquot_commit_info(sb, type);
6004         err = ext4_journal_stop(handle);
6005         if (!ret)
6006                 ret = err;
6007         return ret;
6008 }
6009
6010 /*
6011  * Turn on quotas during mount time - we need to find
6012  * the quota file and such...
6013  */
6014 static int ext4_quota_on_mount(struct super_block *sb, int type)
6015 {
6016         return dquot_quota_on_mount(sb, get_qf_name(sb, EXT4_SB(sb), type),
6017                                         EXT4_SB(sb)->s_jquota_fmt, type);
6018 }
6019
6020 static void lockdep_set_quota_inode(struct inode *inode, int subclass)
6021 {
6022         struct ext4_inode_info *ei = EXT4_I(inode);
6023
6024         /* The first argument of lockdep_set_subclass has to be
6025          * *exactly* the same as the argument to init_rwsem() --- in
6026          * this case, in init_once() --- or lockdep gets unhappy
6027          * because the name of the lock is set using the
6028          * stringification of the argument to init_rwsem().
6029          */
6030         (void) ei;      /* shut up clang warning if !CONFIG_LOCKDEP */
6031         lockdep_set_subclass(&ei->i_data_sem, subclass);
6032 }
6033
6034 /*
6035  * Standard function to be called on quota_on
6036  */
6037 static int ext4_quota_on(struct super_block *sb, int type, int format_id,
6038                          const struct path *path)
6039 {
6040         int err;
6041
6042         if (!test_opt(sb, QUOTA))
6043                 return -EINVAL;
6044
6045         /* Quotafile not on the same filesystem? */
6046         if (path->dentry->d_sb != sb)
6047                 return -EXDEV;
6048         /* Journaling quota? */
6049         if (EXT4_SB(sb)->s_qf_names[type]) {
6050                 /* Quotafile not in fs root? */
6051                 if (path->dentry->d_parent != sb->s_root)
6052                         ext4_msg(sb, KERN_WARNING,
6053                                 "Quota file not on filesystem root. "
6054                                 "Journaled quota will not work");
6055                 sb_dqopt(sb)->flags |= DQUOT_NOLIST_DIRTY;
6056         } else {
6057                 /*
6058                  * Clear the flag just in case mount options changed since
6059                  * last time.
6060                  */
6061                 sb_dqopt(sb)->flags &= ~DQUOT_NOLIST_DIRTY;
6062         }
6063
6064         /*
6065          * When we journal data on quota file, we have to flush journal to see
6066          * all updates to the file when we bypass pagecache...
6067          */
6068         if (EXT4_SB(sb)->s_journal &&
6069             ext4_should_journal_data(d_inode(path->dentry))) {
6070                 /*
6071                  * We don't need to lock updates but journal_flush() could
6072                  * otherwise be livelocked...
6073                  */
6074                 jbd2_journal_lock_updates(EXT4_SB(sb)->s_journal);
6075                 err = jbd2_journal_flush(EXT4_SB(sb)->s_journal);
6076                 jbd2_journal_unlock_updates(EXT4_SB(sb)->s_journal);
6077                 if (err)
6078                         return err;
6079         }
6080
6081         lockdep_set_quota_inode(path->dentry->d_inode, I_DATA_SEM_QUOTA);
6082         err = dquot_quota_on(sb, type, format_id, path);
6083         if (err) {
6084                 lockdep_set_quota_inode(path->dentry->d_inode,
6085                                              I_DATA_SEM_NORMAL);
6086         } else {
6087                 struct inode *inode = d_inode(path->dentry);
6088                 handle_t *handle;
6089
6090                 /*
6091                  * Set inode flags to prevent userspace from messing with quota
6092                  * files. If this fails, we return success anyway since quotas
6093                  * are already enabled and this is not a hard failure.
6094                  */
6095                 inode_lock(inode);
6096                 handle = ext4_journal_start(inode, EXT4_HT_QUOTA, 1);
6097                 if (IS_ERR(handle))
6098                         goto unlock_inode;
6099                 EXT4_I(inode)->i_flags |= EXT4_NOATIME_FL | EXT4_IMMUTABLE_FL;
6100                 inode_set_flags(inode, S_NOATIME | S_IMMUTABLE,
6101                                 S_NOATIME | S_IMMUTABLE);
6102                 err = ext4_mark_inode_dirty(handle, inode);
6103                 ext4_journal_stop(handle);
6104         unlock_inode:
6105                 inode_unlock(inode);
6106         }
6107         return err;
6108 }
6109
6110 static int ext4_quota_enable(struct super_block *sb, int type, int format_id,
6111                              unsigned int flags)
6112 {
6113         int err;
6114         struct inode *qf_inode;
6115         unsigned long qf_inums[EXT4_MAXQUOTAS] = {
6116                 le32_to_cpu(EXT4_SB(sb)->s_es->s_usr_quota_inum),
6117                 le32_to_cpu(EXT4_SB(sb)->s_es->s_grp_quota_inum),
6118                 le32_to_cpu(EXT4_SB(sb)->s_es->s_prj_quota_inum)
6119         };
6120
6121         BUG_ON(!ext4_has_feature_quota(sb));
6122
6123         if (!qf_inums[type])
6124                 return -EPERM;
6125
6126         qf_inode = ext4_iget(sb, qf_inums[type], EXT4_IGET_SPECIAL);
6127         if (IS_ERR(qf_inode)) {
6128                 ext4_error(sb, "Bad quota inode # %lu", qf_inums[type]);
6129                 return PTR_ERR(qf_inode);
6130         }
6131
6132         /* Don't account quota for quota files to avoid recursion */
6133         qf_inode->i_flags |= S_NOQUOTA;
6134         lockdep_set_quota_inode(qf_inode, I_DATA_SEM_QUOTA);
6135         err = dquot_load_quota_inode(qf_inode, type, format_id, flags);
6136         if (err)
6137                 lockdep_set_quota_inode(qf_inode, I_DATA_SEM_NORMAL);
6138         iput(qf_inode);
6139
6140         return err;
6141 }
6142
6143 /* Enable usage tracking for all quota types. */
6144 static int ext4_enable_quotas(struct super_block *sb)
6145 {
6146         int type, err = 0;
6147         unsigned long qf_inums[EXT4_MAXQUOTAS] = {
6148                 le32_to_cpu(EXT4_SB(sb)->s_es->s_usr_quota_inum),
6149                 le32_to_cpu(EXT4_SB(sb)->s_es->s_grp_quota_inum),
6150                 le32_to_cpu(EXT4_SB(sb)->s_es->s_prj_quota_inum)
6151         };
6152         bool quota_mopt[EXT4_MAXQUOTAS] = {
6153                 test_opt(sb, USRQUOTA),
6154                 test_opt(sb, GRPQUOTA),
6155                 test_opt(sb, PRJQUOTA),
6156         };
6157
6158         sb_dqopt(sb)->flags |= DQUOT_QUOTA_SYS_FILE | DQUOT_NOLIST_DIRTY;
6159         for (type = 0; type < EXT4_MAXQUOTAS; type++) {
6160                 if (qf_inums[type]) {
6161                         err = ext4_quota_enable(sb, type, QFMT_VFS_V1,
6162                                 DQUOT_USAGE_ENABLED |
6163                                 (quota_mopt[type] ? DQUOT_LIMITS_ENABLED : 0));
6164                         if (err) {
6165                                 ext4_warning(sb,
6166                                         "Failed to enable quota tracking "
6167                                         "(type=%d, err=%d). Please run "
6168                                         "e2fsck to fix.", type, err);
6169                                 for (type--; type >= 0; type--)
6170                                         dquot_quota_off(sb, type);
6171
6172                                 return err;
6173                         }
6174                 }
6175         }
6176         return 0;
6177 }
6178
6179 static int ext4_quota_off(struct super_block *sb, int type)
6180 {
6181         struct inode *inode = sb_dqopt(sb)->files[type];
6182         handle_t *handle;
6183         int err;
6184
6185         /* Force all delayed allocation blocks to be allocated.
6186          * Caller already holds s_umount sem */
6187         if (test_opt(sb, DELALLOC))
6188                 sync_filesystem(sb);
6189
6190         if (!inode || !igrab(inode))
6191                 goto out;
6192
6193         err = dquot_quota_off(sb, type);
6194         if (err || ext4_has_feature_quota(sb))
6195                 goto out_put;
6196
6197         inode_lock(inode);
6198         /*
6199          * Update modification times of quota files when userspace can
6200          * start looking at them. If we fail, we return success anyway since
6201          * this is not a hard failure and quotas are already disabled.
6202          */
6203         handle = ext4_journal_start(inode, EXT4_HT_QUOTA, 1);
6204         if (IS_ERR(handle)) {
6205                 err = PTR_ERR(handle);
6206                 goto out_unlock;
6207         }
6208         EXT4_I(inode)->i_flags &= ~(EXT4_NOATIME_FL | EXT4_IMMUTABLE_FL);
6209         inode_set_flags(inode, 0, S_NOATIME | S_IMMUTABLE);
6210         inode->i_mtime = inode->i_ctime = current_time(inode);
6211         err = ext4_mark_inode_dirty(handle, inode);
6212         ext4_journal_stop(handle);
6213 out_unlock:
6214         inode_unlock(inode);
6215 out_put:
6216         lockdep_set_quota_inode(inode, I_DATA_SEM_NORMAL);
6217         iput(inode);
6218         return err;
6219 out:
6220         return dquot_quota_off(sb, type);
6221 }
6222
6223 /* Read data from quotafile - avoid pagecache and such because we cannot afford
6224  * acquiring the locks... As quota files are never truncated and quota code
6225  * itself serializes the operations (and no one else should touch the files)
6226  * we don't have to be afraid of races */
6227 static ssize_t ext4_quota_read(struct super_block *sb, int type, char *data,
6228                                size_t len, loff_t off)
6229 {
6230         struct inode *inode = sb_dqopt(sb)->files[type];
6231         ext4_lblk_t blk = off >> EXT4_BLOCK_SIZE_BITS(sb);
6232         int offset = off & (sb->s_blocksize - 1);
6233         int tocopy;
6234         size_t toread;
6235         struct buffer_head *bh;
6236         loff_t i_size = i_size_read(inode);
6237
6238         if (off > i_size)
6239                 return 0;
6240         if (off+len > i_size)
6241                 len = i_size-off;
6242         toread = len;
6243         while (toread > 0) {
6244                 tocopy = sb->s_blocksize - offset < toread ?
6245                                 sb->s_blocksize - offset : toread;
6246                 bh = ext4_bread(NULL, inode, blk, 0);
6247                 if (IS_ERR(bh))
6248                         return PTR_ERR(bh);
6249                 if (!bh)        /* A hole? */
6250                         memset(data, 0, tocopy);
6251                 else
6252                         memcpy(data, bh->b_data+offset, tocopy);
6253                 brelse(bh);
6254                 offset = 0;
6255                 toread -= tocopy;
6256                 data += tocopy;
6257                 blk++;
6258         }
6259         return len;
6260 }
6261
6262 /* Write to quotafile (we know the transaction is already started and has
6263  * enough credits) */
6264 static ssize_t ext4_quota_write(struct super_block *sb, int type,
6265                                 const char *data, size_t len, loff_t off)
6266 {
6267         struct inode *inode = sb_dqopt(sb)->files[type];
6268         ext4_lblk_t blk = off >> EXT4_BLOCK_SIZE_BITS(sb);
6269         int err = 0, err2 = 0, offset = off & (sb->s_blocksize - 1);
6270         int retries = 0;
6271         struct buffer_head *bh;
6272         handle_t *handle = journal_current_handle();
6273
6274         if (EXT4_SB(sb)->s_journal && !handle) {
6275                 ext4_msg(sb, KERN_WARNING, "Quota write (off=%llu, len=%llu)"
6276                         " cancelled because transaction is not started",
6277                         (unsigned long long)off, (unsigned long long)len);
6278                 return -EIO;
6279         }
6280         /*
6281          * Since we account only one data block in transaction credits,
6282          * then it is impossible to cross a block boundary.
6283          */
6284         if (sb->s_blocksize - offset < len) {
6285                 ext4_msg(sb, KERN_WARNING, "Quota write (off=%llu, len=%llu)"
6286                         " cancelled because not block aligned",
6287                         (unsigned long long)off, (unsigned long long)len);
6288                 return -EIO;
6289         }
6290
6291         do {
6292                 bh = ext4_bread(handle, inode, blk,
6293                                 EXT4_GET_BLOCKS_CREATE |
6294                                 EXT4_GET_BLOCKS_METADATA_NOFAIL);
6295         } while (PTR_ERR(bh) == -ENOSPC &&
6296                  ext4_should_retry_alloc(inode->i_sb, &retries));
6297         if (IS_ERR(bh))
6298                 return PTR_ERR(bh);
6299         if (!bh)
6300                 goto out;
6301         BUFFER_TRACE(bh, "get write access");
6302         err = ext4_journal_get_write_access(handle, bh);
6303         if (err) {
6304                 brelse(bh);
6305                 return err;
6306         }
6307         lock_buffer(bh);
6308         memcpy(bh->b_data+offset, data, len);
6309         flush_dcache_page(bh->b_page);
6310         unlock_buffer(bh);
6311         err = ext4_handle_dirty_metadata(handle, NULL, bh);
6312         brelse(bh);
6313 out:
6314         if (inode->i_size < off + len) {
6315                 i_size_write(inode, off + len);
6316                 EXT4_I(inode)->i_disksize = inode->i_size;
6317                 err2 = ext4_mark_inode_dirty(handle, inode);
6318                 if (unlikely(err2 && !err))
6319                         err = err2;
6320         }
6321         return err ? err : len;
6322 }
6323 #endif
6324
6325 static struct dentry *ext4_mount(struct file_system_type *fs_type, int flags,
6326                        const char *dev_name, void *data)
6327 {
6328         return mount_bdev(fs_type, flags, dev_name, data, ext4_fill_super);
6329 }
6330
6331 #if !defined(CONFIG_EXT2_FS) && !defined(CONFIG_EXT2_FS_MODULE) && defined(CONFIG_EXT4_USE_FOR_EXT2)
6332 static inline void register_as_ext2(void)
6333 {
6334         int err = register_filesystem(&ext2_fs_type);
6335         if (err)
6336                 printk(KERN_WARNING
6337                        "EXT4-fs: Unable to register as ext2 (%d)\n", err);
6338 }
6339
6340 static inline void unregister_as_ext2(void)
6341 {
6342         unregister_filesystem(&ext2_fs_type);
6343 }
6344
6345 static inline int ext2_feature_set_ok(struct super_block *sb)
6346 {
6347         if (ext4_has_unknown_ext2_incompat_features(sb))
6348                 return 0;
6349         if (sb_rdonly(sb))
6350                 return 1;
6351         if (ext4_has_unknown_ext2_ro_compat_features(sb))
6352                 return 0;
6353         return 1;
6354 }
6355 #else
6356 static inline void register_as_ext2(void) { }
6357 static inline void unregister_as_ext2(void) { }
6358 static inline int ext2_feature_set_ok(struct super_block *sb) { return 0; }
6359 #endif
6360
6361 static inline void register_as_ext3(void)
6362 {
6363         int err = register_filesystem(&ext3_fs_type);
6364         if (err)
6365                 printk(KERN_WARNING
6366                        "EXT4-fs: Unable to register as ext3 (%d)\n", err);
6367 }
6368
6369 static inline void unregister_as_ext3(void)
6370 {
6371         unregister_filesystem(&ext3_fs_type);
6372 }
6373
6374 static inline int ext3_feature_set_ok(struct super_block *sb)
6375 {
6376         if (ext4_has_unknown_ext3_incompat_features(sb))
6377                 return 0;
6378         if (!ext4_has_feature_journal(sb))
6379                 return 0;
6380         if (sb_rdonly(sb))
6381                 return 1;
6382         if (ext4_has_unknown_ext3_ro_compat_features(sb))
6383                 return 0;
6384         return 1;
6385 }
6386
6387 static struct file_system_type ext4_fs_type = {
6388         .owner          = THIS_MODULE,
6389         .name           = "ext4",
6390         .mount          = ext4_mount,
6391         .kill_sb        = kill_block_super,
6392         .fs_flags       = FS_REQUIRES_DEV,
6393 };
6394 MODULE_ALIAS_FS("ext4");
6395
6396 /* Shared across all ext4 file systems */
6397 wait_queue_head_t ext4__ioend_wq[EXT4_WQ_HASH_SZ];
6398
6399 static int __init ext4_init_fs(void)
6400 {
6401         int i, err;
6402
6403         ratelimit_state_init(&ext4_mount_msg_ratelimit, 30 * HZ, 64);
6404         ext4_li_info = NULL;
6405         mutex_init(&ext4_li_mtx);
6406
6407         /* Build-time check for flags consistency */
6408         ext4_check_flag_values();
6409
6410         for (i = 0; i < EXT4_WQ_HASH_SZ; i++)
6411                 init_waitqueue_head(&ext4__ioend_wq[i]);
6412
6413         err = ext4_init_es();
6414         if (err)
6415                 return err;
6416
6417         err = ext4_init_pending();
6418         if (err)
6419                 goto out7;
6420
6421         err = ext4_init_post_read_processing();
6422         if (err)
6423                 goto out6;
6424
6425         err = ext4_init_pageio();
6426         if (err)
6427                 goto out5;
6428
6429         err = ext4_init_system_zone();
6430         if (err)
6431                 goto out4;
6432
6433         err = ext4_init_sysfs();
6434         if (err)
6435                 goto out3;
6436
6437         err = ext4_init_mballoc();
6438         if (err)
6439                 goto out2;
6440         err = init_inodecache();
6441         if (err)
6442                 goto out1;
6443         register_as_ext3();
6444         register_as_ext2();
6445         err = register_filesystem(&ext4_fs_type);
6446         if (err)
6447                 goto out;
6448
6449         return 0;
6450 out:
6451         unregister_as_ext2();
6452         unregister_as_ext3();
6453         destroy_inodecache();
6454 out1:
6455         ext4_exit_mballoc();
6456 out2:
6457         ext4_exit_sysfs();
6458 out3:
6459         ext4_exit_system_zone();
6460 out4:
6461         ext4_exit_pageio();
6462 out5:
6463         ext4_exit_post_read_processing();
6464 out6:
6465         ext4_exit_pending();
6466 out7:
6467         ext4_exit_es();
6468
6469         return err;
6470 }
6471
6472 static void __exit ext4_exit_fs(void)
6473 {
6474         ext4_destroy_lazyinit_thread();
6475         unregister_as_ext2();
6476         unregister_as_ext3();
6477         unregister_filesystem(&ext4_fs_type);
6478         destroy_inodecache();
6479         ext4_exit_mballoc();
6480         ext4_exit_sysfs();
6481         ext4_exit_system_zone();
6482         ext4_exit_pageio();
6483         ext4_exit_post_read_processing();
6484         ext4_exit_es();
6485         ext4_exit_pending();
6486 }
6487
6488 MODULE_AUTHOR("Remy Card, Stephen Tweedie, Andrew Morton, Andreas Dilger, Theodore Ts'o and others");
6489 MODULE_DESCRIPTION("Fourth Extended Filesystem");
6490 MODULE_LICENSE("GPL");
6491 MODULE_SOFTDEP("pre: crc32c");
6492 module_init(ext4_init_fs)
6493 module_exit(ext4_exit_fs)