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