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