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