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