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