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