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