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