xref: /openbmc/linux/fs/f2fs/super.c (revision b62e71be2110d8b52bf5faf3c3ed7ca1a0c113a5)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * fs/f2fs/super.c
4  *
5  * Copyright (c) 2012 Samsung Electronics Co., Ltd.
6  *             http://www.samsung.com/
7  */
8 #include <linux/module.h>
9 #include <linux/init.h>
10 #include <linux/fs.h>
11 #include <linux/fs_context.h>
12 #include <linux/sched/mm.h>
13 #include <linux/statfs.h>
14 #include <linux/buffer_head.h>
15 #include <linux/kthread.h>
16 #include <linux/parser.h>
17 #include <linux/mount.h>
18 #include <linux/seq_file.h>
19 #include <linux/proc_fs.h>
20 #include <linux/random.h>
21 #include <linux/exportfs.h>
22 #include <linux/blkdev.h>
23 #include <linux/quotaops.h>
24 #include <linux/f2fs_fs.h>
25 #include <linux/sysfs.h>
26 #include <linux/quota.h>
27 #include <linux/unicode.h>
28 #include <linux/part_stat.h>
29 #include <linux/zstd.h>
30 #include <linux/lz4.h>
31 
32 #include "f2fs.h"
33 #include "node.h"
34 #include "segment.h"
35 #include "xattr.h"
36 #include "gc.h"
37 #include "iostat.h"
38 
39 #define CREATE_TRACE_POINTS
40 #include <trace/events/f2fs.h>
41 
42 static struct kmem_cache *f2fs_inode_cachep;
43 
44 #ifdef CONFIG_F2FS_FAULT_INJECTION
45 
46 const char *f2fs_fault_name[FAULT_MAX] = {
47 	[FAULT_KMALLOC]		= "kmalloc",
48 	[FAULT_KVMALLOC]	= "kvmalloc",
49 	[FAULT_PAGE_ALLOC]	= "page alloc",
50 	[FAULT_PAGE_GET]	= "page get",
51 	[FAULT_ALLOC_NID]	= "alloc nid",
52 	[FAULT_ORPHAN]		= "orphan",
53 	[FAULT_BLOCK]		= "no more block",
54 	[FAULT_DIR_DEPTH]	= "too big dir depth",
55 	[FAULT_EVICT_INODE]	= "evict_inode fail",
56 	[FAULT_TRUNCATE]	= "truncate fail",
57 	[FAULT_READ_IO]		= "read IO error",
58 	[FAULT_CHECKPOINT]	= "checkpoint error",
59 	[FAULT_DISCARD]		= "discard error",
60 	[FAULT_WRITE_IO]	= "write IO error",
61 	[FAULT_SLAB_ALLOC]	= "slab alloc",
62 	[FAULT_DQUOT_INIT]	= "dquot initialize",
63 	[FAULT_LOCK_OP]		= "lock_op",
64 	[FAULT_BLKADDR]		= "invalid blkaddr",
65 };
66 
67 void f2fs_build_fault_attr(struct f2fs_sb_info *sbi, unsigned int rate,
68 							unsigned int type)
69 {
70 	struct f2fs_fault_info *ffi = &F2FS_OPTION(sbi).fault_info;
71 
72 	if (rate) {
73 		atomic_set(&ffi->inject_ops, 0);
74 		ffi->inject_rate = rate;
75 	}
76 
77 	if (type)
78 		ffi->inject_type = type;
79 
80 	if (!rate && !type)
81 		memset(ffi, 0, sizeof(struct f2fs_fault_info));
82 }
83 #endif
84 
85 /* f2fs-wide shrinker description */
86 static struct shrinker f2fs_shrinker_info = {
87 	.scan_objects = f2fs_shrink_scan,
88 	.count_objects = f2fs_shrink_count,
89 	.seeks = DEFAULT_SEEKS,
90 };
91 
92 enum {
93 	Opt_gc_background,
94 	Opt_disable_roll_forward,
95 	Opt_norecovery,
96 	Opt_discard,
97 	Opt_nodiscard,
98 	Opt_noheap,
99 	Opt_heap,
100 	Opt_user_xattr,
101 	Opt_nouser_xattr,
102 	Opt_acl,
103 	Opt_noacl,
104 	Opt_active_logs,
105 	Opt_disable_ext_identify,
106 	Opt_inline_xattr,
107 	Opt_noinline_xattr,
108 	Opt_inline_xattr_size,
109 	Opt_inline_data,
110 	Opt_inline_dentry,
111 	Opt_noinline_dentry,
112 	Opt_flush_merge,
113 	Opt_noflush_merge,
114 	Opt_barrier,
115 	Opt_nobarrier,
116 	Opt_fastboot,
117 	Opt_extent_cache,
118 	Opt_noextent_cache,
119 	Opt_noinline_data,
120 	Opt_data_flush,
121 	Opt_reserve_root,
122 	Opt_resgid,
123 	Opt_resuid,
124 	Opt_mode,
125 	Opt_io_size_bits,
126 	Opt_fault_injection,
127 	Opt_fault_type,
128 	Opt_lazytime,
129 	Opt_nolazytime,
130 	Opt_quota,
131 	Opt_noquota,
132 	Opt_usrquota,
133 	Opt_grpquota,
134 	Opt_prjquota,
135 	Opt_usrjquota,
136 	Opt_grpjquota,
137 	Opt_prjjquota,
138 	Opt_offusrjquota,
139 	Opt_offgrpjquota,
140 	Opt_offprjjquota,
141 	Opt_jqfmt_vfsold,
142 	Opt_jqfmt_vfsv0,
143 	Opt_jqfmt_vfsv1,
144 	Opt_alloc,
145 	Opt_fsync,
146 	Opt_test_dummy_encryption,
147 	Opt_inlinecrypt,
148 	Opt_checkpoint_disable,
149 	Opt_checkpoint_disable_cap,
150 	Opt_checkpoint_disable_cap_perc,
151 	Opt_checkpoint_enable,
152 	Opt_checkpoint_merge,
153 	Opt_nocheckpoint_merge,
154 	Opt_compress_algorithm,
155 	Opt_compress_log_size,
156 	Opt_compress_extension,
157 	Opt_nocompress_extension,
158 	Opt_compress_chksum,
159 	Opt_compress_mode,
160 	Opt_compress_cache,
161 	Opt_atgc,
162 	Opt_gc_merge,
163 	Opt_nogc_merge,
164 	Opt_discard_unit,
165 	Opt_memory_mode,
166 	Opt_age_extent_cache,
167 	Opt_errors,
168 	Opt_err,
169 };
170 
171 static match_table_t f2fs_tokens = {
172 	{Opt_gc_background, "background_gc=%s"},
173 	{Opt_disable_roll_forward, "disable_roll_forward"},
174 	{Opt_norecovery, "norecovery"},
175 	{Opt_discard, "discard"},
176 	{Opt_nodiscard, "nodiscard"},
177 	{Opt_noheap, "no_heap"},
178 	{Opt_heap, "heap"},
179 	{Opt_user_xattr, "user_xattr"},
180 	{Opt_nouser_xattr, "nouser_xattr"},
181 	{Opt_acl, "acl"},
182 	{Opt_noacl, "noacl"},
183 	{Opt_active_logs, "active_logs=%u"},
184 	{Opt_disable_ext_identify, "disable_ext_identify"},
185 	{Opt_inline_xattr, "inline_xattr"},
186 	{Opt_noinline_xattr, "noinline_xattr"},
187 	{Opt_inline_xattr_size, "inline_xattr_size=%u"},
188 	{Opt_inline_data, "inline_data"},
189 	{Opt_inline_dentry, "inline_dentry"},
190 	{Opt_noinline_dentry, "noinline_dentry"},
191 	{Opt_flush_merge, "flush_merge"},
192 	{Opt_noflush_merge, "noflush_merge"},
193 	{Opt_barrier, "barrier"},
194 	{Opt_nobarrier, "nobarrier"},
195 	{Opt_fastboot, "fastboot"},
196 	{Opt_extent_cache, "extent_cache"},
197 	{Opt_noextent_cache, "noextent_cache"},
198 	{Opt_noinline_data, "noinline_data"},
199 	{Opt_data_flush, "data_flush"},
200 	{Opt_reserve_root, "reserve_root=%u"},
201 	{Opt_resgid, "resgid=%u"},
202 	{Opt_resuid, "resuid=%u"},
203 	{Opt_mode, "mode=%s"},
204 	{Opt_io_size_bits, "io_bits=%u"},
205 	{Opt_fault_injection, "fault_injection=%u"},
206 	{Opt_fault_type, "fault_type=%u"},
207 	{Opt_lazytime, "lazytime"},
208 	{Opt_nolazytime, "nolazytime"},
209 	{Opt_quota, "quota"},
210 	{Opt_noquota, "noquota"},
211 	{Opt_usrquota, "usrquota"},
212 	{Opt_grpquota, "grpquota"},
213 	{Opt_prjquota, "prjquota"},
214 	{Opt_usrjquota, "usrjquota=%s"},
215 	{Opt_grpjquota, "grpjquota=%s"},
216 	{Opt_prjjquota, "prjjquota=%s"},
217 	{Opt_offusrjquota, "usrjquota="},
218 	{Opt_offgrpjquota, "grpjquota="},
219 	{Opt_offprjjquota, "prjjquota="},
220 	{Opt_jqfmt_vfsold, "jqfmt=vfsold"},
221 	{Opt_jqfmt_vfsv0, "jqfmt=vfsv0"},
222 	{Opt_jqfmt_vfsv1, "jqfmt=vfsv1"},
223 	{Opt_alloc, "alloc_mode=%s"},
224 	{Opt_fsync, "fsync_mode=%s"},
225 	{Opt_test_dummy_encryption, "test_dummy_encryption=%s"},
226 	{Opt_test_dummy_encryption, "test_dummy_encryption"},
227 	{Opt_inlinecrypt, "inlinecrypt"},
228 	{Opt_checkpoint_disable, "checkpoint=disable"},
229 	{Opt_checkpoint_disable_cap, "checkpoint=disable:%u"},
230 	{Opt_checkpoint_disable_cap_perc, "checkpoint=disable:%u%%"},
231 	{Opt_checkpoint_enable, "checkpoint=enable"},
232 	{Opt_checkpoint_merge, "checkpoint_merge"},
233 	{Opt_nocheckpoint_merge, "nocheckpoint_merge"},
234 	{Opt_compress_algorithm, "compress_algorithm=%s"},
235 	{Opt_compress_log_size, "compress_log_size=%u"},
236 	{Opt_compress_extension, "compress_extension=%s"},
237 	{Opt_nocompress_extension, "nocompress_extension=%s"},
238 	{Opt_compress_chksum, "compress_chksum"},
239 	{Opt_compress_mode, "compress_mode=%s"},
240 	{Opt_compress_cache, "compress_cache"},
241 	{Opt_atgc, "atgc"},
242 	{Opt_gc_merge, "gc_merge"},
243 	{Opt_nogc_merge, "nogc_merge"},
244 	{Opt_discard_unit, "discard_unit=%s"},
245 	{Opt_memory_mode, "memory=%s"},
246 	{Opt_age_extent_cache, "age_extent_cache"},
247 	{Opt_errors, "errors=%s"},
248 	{Opt_err, NULL},
249 };
250 
251 void f2fs_printk(struct f2fs_sb_info *sbi, const char *fmt, ...)
252 {
253 	struct va_format vaf;
254 	va_list args;
255 	int level;
256 
257 	va_start(args, fmt);
258 
259 	level = printk_get_level(fmt);
260 	vaf.fmt = printk_skip_level(fmt);
261 	vaf.va = &args;
262 	printk("%c%cF2FS-fs (%s): %pV\n",
263 	       KERN_SOH_ASCII, level, sbi->sb->s_id, &vaf);
264 
265 	va_end(args);
266 }
267 
268 #if IS_ENABLED(CONFIG_UNICODE)
269 static const struct f2fs_sb_encodings {
270 	__u16 magic;
271 	char *name;
272 	unsigned int version;
273 } f2fs_sb_encoding_map[] = {
274 	{F2FS_ENC_UTF8_12_1, "utf8", UNICODE_AGE(12, 1, 0)},
275 };
276 
277 static const struct f2fs_sb_encodings *
278 f2fs_sb_read_encoding(const struct f2fs_super_block *sb)
279 {
280 	__u16 magic = le16_to_cpu(sb->s_encoding);
281 	int i;
282 
283 	for (i = 0; i < ARRAY_SIZE(f2fs_sb_encoding_map); i++)
284 		if (magic == f2fs_sb_encoding_map[i].magic)
285 			return &f2fs_sb_encoding_map[i];
286 
287 	return NULL;
288 }
289 
290 struct kmem_cache *f2fs_cf_name_slab;
291 static int __init f2fs_create_casefold_cache(void)
292 {
293 	f2fs_cf_name_slab = f2fs_kmem_cache_create("f2fs_casefolded_name",
294 							F2FS_NAME_LEN);
295 	return f2fs_cf_name_slab ? 0 : -ENOMEM;
296 }
297 
298 static void f2fs_destroy_casefold_cache(void)
299 {
300 	kmem_cache_destroy(f2fs_cf_name_slab);
301 }
302 #else
303 static int __init f2fs_create_casefold_cache(void) { return 0; }
304 static void f2fs_destroy_casefold_cache(void) { }
305 #endif
306 
307 static inline void limit_reserve_root(struct f2fs_sb_info *sbi)
308 {
309 	block_t limit = min((sbi->user_block_count >> 3),
310 			sbi->user_block_count - sbi->reserved_blocks);
311 
312 	/* limit is 12.5% */
313 	if (test_opt(sbi, RESERVE_ROOT) &&
314 			F2FS_OPTION(sbi).root_reserved_blocks > limit) {
315 		F2FS_OPTION(sbi).root_reserved_blocks = limit;
316 		f2fs_info(sbi, "Reduce reserved blocks for root = %u",
317 			  F2FS_OPTION(sbi).root_reserved_blocks);
318 	}
319 	if (!test_opt(sbi, RESERVE_ROOT) &&
320 		(!uid_eq(F2FS_OPTION(sbi).s_resuid,
321 				make_kuid(&init_user_ns, F2FS_DEF_RESUID)) ||
322 		!gid_eq(F2FS_OPTION(sbi).s_resgid,
323 				make_kgid(&init_user_ns, F2FS_DEF_RESGID))))
324 		f2fs_info(sbi, "Ignore s_resuid=%u, s_resgid=%u w/o reserve_root",
325 			  from_kuid_munged(&init_user_ns,
326 					   F2FS_OPTION(sbi).s_resuid),
327 			  from_kgid_munged(&init_user_ns,
328 					   F2FS_OPTION(sbi).s_resgid));
329 }
330 
331 static inline int adjust_reserved_segment(struct f2fs_sb_info *sbi)
332 {
333 	unsigned int sec_blks = sbi->blocks_per_seg * sbi->segs_per_sec;
334 	unsigned int avg_vblocks;
335 	unsigned int wanted_reserved_segments;
336 	block_t avail_user_block_count;
337 
338 	if (!F2FS_IO_ALIGNED(sbi))
339 		return 0;
340 
341 	/* average valid block count in section in worst case */
342 	avg_vblocks = sec_blks / F2FS_IO_SIZE(sbi);
343 
344 	/*
345 	 * we need enough free space when migrating one section in worst case
346 	 */
347 	wanted_reserved_segments = (F2FS_IO_SIZE(sbi) / avg_vblocks) *
348 						reserved_segments(sbi);
349 	wanted_reserved_segments -= reserved_segments(sbi);
350 
351 	avail_user_block_count = sbi->user_block_count -
352 				sbi->current_reserved_blocks -
353 				F2FS_OPTION(sbi).root_reserved_blocks;
354 
355 	if (wanted_reserved_segments * sbi->blocks_per_seg >
356 					avail_user_block_count) {
357 		f2fs_err(sbi, "IO align feature can't grab additional reserved segment: %u, available segments: %u",
358 			wanted_reserved_segments,
359 			avail_user_block_count >> sbi->log_blocks_per_seg);
360 		return -ENOSPC;
361 	}
362 
363 	SM_I(sbi)->additional_reserved_segments = wanted_reserved_segments;
364 
365 	f2fs_info(sbi, "IO align feature needs additional reserved segment: %u",
366 			 wanted_reserved_segments);
367 
368 	return 0;
369 }
370 
371 static inline void adjust_unusable_cap_perc(struct f2fs_sb_info *sbi)
372 {
373 	if (!F2FS_OPTION(sbi).unusable_cap_perc)
374 		return;
375 
376 	if (F2FS_OPTION(sbi).unusable_cap_perc == 100)
377 		F2FS_OPTION(sbi).unusable_cap = sbi->user_block_count;
378 	else
379 		F2FS_OPTION(sbi).unusable_cap = (sbi->user_block_count / 100) *
380 					F2FS_OPTION(sbi).unusable_cap_perc;
381 
382 	f2fs_info(sbi, "Adjust unusable cap for checkpoint=disable = %u / %u%%",
383 			F2FS_OPTION(sbi).unusable_cap,
384 			F2FS_OPTION(sbi).unusable_cap_perc);
385 }
386 
387 static void init_once(void *foo)
388 {
389 	struct f2fs_inode_info *fi = (struct f2fs_inode_info *) foo;
390 
391 	inode_init_once(&fi->vfs_inode);
392 }
393 
394 #ifdef CONFIG_QUOTA
395 static const char * const quotatypes[] = INITQFNAMES;
396 #define QTYPE2NAME(t) (quotatypes[t])
397 static int f2fs_set_qf_name(struct super_block *sb, int qtype,
398 							substring_t *args)
399 {
400 	struct f2fs_sb_info *sbi = F2FS_SB(sb);
401 	char *qname;
402 	int ret = -EINVAL;
403 
404 	if (sb_any_quota_loaded(sb) && !F2FS_OPTION(sbi).s_qf_names[qtype]) {
405 		f2fs_err(sbi, "Cannot change journaled quota options when quota turned on");
406 		return -EINVAL;
407 	}
408 	if (f2fs_sb_has_quota_ino(sbi)) {
409 		f2fs_info(sbi, "QUOTA feature is enabled, so ignore qf_name");
410 		return 0;
411 	}
412 
413 	qname = match_strdup(args);
414 	if (!qname) {
415 		f2fs_err(sbi, "Not enough memory for storing quotafile name");
416 		return -ENOMEM;
417 	}
418 	if (F2FS_OPTION(sbi).s_qf_names[qtype]) {
419 		if (strcmp(F2FS_OPTION(sbi).s_qf_names[qtype], qname) == 0)
420 			ret = 0;
421 		else
422 			f2fs_err(sbi, "%s quota file already specified",
423 				 QTYPE2NAME(qtype));
424 		goto errout;
425 	}
426 	if (strchr(qname, '/')) {
427 		f2fs_err(sbi, "quotafile must be on filesystem root");
428 		goto errout;
429 	}
430 	F2FS_OPTION(sbi).s_qf_names[qtype] = qname;
431 	set_opt(sbi, QUOTA);
432 	return 0;
433 errout:
434 	kfree(qname);
435 	return ret;
436 }
437 
438 static int f2fs_clear_qf_name(struct super_block *sb, int qtype)
439 {
440 	struct f2fs_sb_info *sbi = F2FS_SB(sb);
441 
442 	if (sb_any_quota_loaded(sb) && F2FS_OPTION(sbi).s_qf_names[qtype]) {
443 		f2fs_err(sbi, "Cannot change journaled quota options when quota turned on");
444 		return -EINVAL;
445 	}
446 	kfree(F2FS_OPTION(sbi).s_qf_names[qtype]);
447 	F2FS_OPTION(sbi).s_qf_names[qtype] = NULL;
448 	return 0;
449 }
450 
451 static int f2fs_check_quota_options(struct f2fs_sb_info *sbi)
452 {
453 	/*
454 	 * We do the test below only for project quotas. 'usrquota' and
455 	 * 'grpquota' mount options are allowed even without quota feature
456 	 * to support legacy quotas in quota files.
457 	 */
458 	if (test_opt(sbi, PRJQUOTA) && !f2fs_sb_has_project_quota(sbi)) {
459 		f2fs_err(sbi, "Project quota feature not enabled. Cannot enable project quota enforcement.");
460 		return -1;
461 	}
462 	if (F2FS_OPTION(sbi).s_qf_names[USRQUOTA] ||
463 			F2FS_OPTION(sbi).s_qf_names[GRPQUOTA] ||
464 			F2FS_OPTION(sbi).s_qf_names[PRJQUOTA]) {
465 		if (test_opt(sbi, USRQUOTA) &&
466 				F2FS_OPTION(sbi).s_qf_names[USRQUOTA])
467 			clear_opt(sbi, USRQUOTA);
468 
469 		if (test_opt(sbi, GRPQUOTA) &&
470 				F2FS_OPTION(sbi).s_qf_names[GRPQUOTA])
471 			clear_opt(sbi, GRPQUOTA);
472 
473 		if (test_opt(sbi, PRJQUOTA) &&
474 				F2FS_OPTION(sbi).s_qf_names[PRJQUOTA])
475 			clear_opt(sbi, PRJQUOTA);
476 
477 		if (test_opt(sbi, GRPQUOTA) || test_opt(sbi, USRQUOTA) ||
478 				test_opt(sbi, PRJQUOTA)) {
479 			f2fs_err(sbi, "old and new quota format mixing");
480 			return -1;
481 		}
482 
483 		if (!F2FS_OPTION(sbi).s_jquota_fmt) {
484 			f2fs_err(sbi, "journaled quota format not specified");
485 			return -1;
486 		}
487 	}
488 
489 	if (f2fs_sb_has_quota_ino(sbi) && F2FS_OPTION(sbi).s_jquota_fmt) {
490 		f2fs_info(sbi, "QUOTA feature is enabled, so ignore jquota_fmt");
491 		F2FS_OPTION(sbi).s_jquota_fmt = 0;
492 	}
493 	return 0;
494 }
495 #endif
496 
497 static int f2fs_set_test_dummy_encryption(struct super_block *sb,
498 					  const char *opt,
499 					  const substring_t *arg,
500 					  bool is_remount)
501 {
502 	struct f2fs_sb_info *sbi = F2FS_SB(sb);
503 	struct fs_parameter param = {
504 		.type = fs_value_is_string,
505 		.string = arg->from ? arg->from : "",
506 	};
507 	struct fscrypt_dummy_policy *policy =
508 		&F2FS_OPTION(sbi).dummy_enc_policy;
509 	int err;
510 
511 	if (!IS_ENABLED(CONFIG_FS_ENCRYPTION)) {
512 		f2fs_warn(sbi, "test_dummy_encryption option not supported");
513 		return -EINVAL;
514 	}
515 
516 	if (!f2fs_sb_has_encrypt(sbi)) {
517 		f2fs_err(sbi, "Encrypt feature is off");
518 		return -EINVAL;
519 	}
520 
521 	/*
522 	 * This mount option is just for testing, and it's not worthwhile to
523 	 * implement the extra complexity (e.g. RCU protection) that would be
524 	 * needed to allow it to be set or changed during remount.  We do allow
525 	 * it to be specified during remount, but only if there is no change.
526 	 */
527 	if (is_remount && !fscrypt_is_dummy_policy_set(policy)) {
528 		f2fs_warn(sbi, "Can't set test_dummy_encryption on remount");
529 		return -EINVAL;
530 	}
531 
532 	err = fscrypt_parse_test_dummy_encryption(&param, policy);
533 	if (err) {
534 		if (err == -EEXIST)
535 			f2fs_warn(sbi,
536 				  "Can't change test_dummy_encryption on remount");
537 		else if (err == -EINVAL)
538 			f2fs_warn(sbi, "Value of option \"%s\" is unrecognized",
539 				  opt);
540 		else
541 			f2fs_warn(sbi, "Error processing option \"%s\" [%d]",
542 				  opt, err);
543 		return -EINVAL;
544 	}
545 	f2fs_warn(sbi, "Test dummy encryption mode enabled");
546 	return 0;
547 }
548 
549 #ifdef CONFIG_F2FS_FS_COMPRESSION
550 /*
551  * 1. The same extension name cannot not appear in both compress and non-compress extension
552  * at the same time.
553  * 2. If the compress extension specifies all files, the types specified by the non-compress
554  * extension will be treated as special cases and will not be compressed.
555  * 3. Don't allow the non-compress extension specifies all files.
556  */
557 static int f2fs_test_compress_extension(struct f2fs_sb_info *sbi)
558 {
559 	unsigned char (*ext)[F2FS_EXTENSION_LEN];
560 	unsigned char (*noext)[F2FS_EXTENSION_LEN];
561 	int ext_cnt, noext_cnt, index = 0, no_index = 0;
562 
563 	ext = F2FS_OPTION(sbi).extensions;
564 	ext_cnt = F2FS_OPTION(sbi).compress_ext_cnt;
565 	noext = F2FS_OPTION(sbi).noextensions;
566 	noext_cnt = F2FS_OPTION(sbi).nocompress_ext_cnt;
567 
568 	if (!noext_cnt)
569 		return 0;
570 
571 	for (no_index = 0; no_index < noext_cnt; no_index++) {
572 		if (!strcasecmp("*", noext[no_index])) {
573 			f2fs_info(sbi, "Don't allow the nocompress extension specifies all files");
574 			return -EINVAL;
575 		}
576 		for (index = 0; index < ext_cnt; index++) {
577 			if (!strcasecmp(ext[index], noext[no_index])) {
578 				f2fs_info(sbi, "Don't allow the same extension %s appear in both compress and nocompress extension",
579 						ext[index]);
580 				return -EINVAL;
581 			}
582 		}
583 	}
584 	return 0;
585 }
586 
587 #ifdef CONFIG_F2FS_FS_LZ4
588 static int f2fs_set_lz4hc_level(struct f2fs_sb_info *sbi, const char *str)
589 {
590 #ifdef CONFIG_F2FS_FS_LZ4HC
591 	unsigned int level;
592 #endif
593 
594 	if (strlen(str) == 3) {
595 		F2FS_OPTION(sbi).compress_level = 0;
596 		return 0;
597 	}
598 
599 #ifdef CONFIG_F2FS_FS_LZ4HC
600 	str += 3;
601 
602 	if (str[0] != ':') {
603 		f2fs_info(sbi, "wrong format, e.g. <alg_name>:<compr_level>");
604 		return -EINVAL;
605 	}
606 	if (kstrtouint(str + 1, 10, &level))
607 		return -EINVAL;
608 
609 	if (level < LZ4HC_MIN_CLEVEL || level > LZ4HC_MAX_CLEVEL) {
610 		f2fs_info(sbi, "invalid lz4hc compress level: %d", level);
611 		return -EINVAL;
612 	}
613 
614 	F2FS_OPTION(sbi).compress_level = level;
615 	return 0;
616 #else
617 	f2fs_info(sbi, "kernel doesn't support lz4hc compression");
618 	return -EINVAL;
619 #endif
620 }
621 #endif
622 
623 #ifdef CONFIG_F2FS_FS_ZSTD
624 static int f2fs_set_zstd_level(struct f2fs_sb_info *sbi, const char *str)
625 {
626 	unsigned int level;
627 	int len = 4;
628 
629 	if (strlen(str) == len) {
630 		F2FS_OPTION(sbi).compress_level = 0;
631 		return 0;
632 	}
633 
634 	str += len;
635 
636 	if (str[0] != ':') {
637 		f2fs_info(sbi, "wrong format, e.g. <alg_name>:<compr_level>");
638 		return -EINVAL;
639 	}
640 	if (kstrtouint(str + 1, 10, &level))
641 		return -EINVAL;
642 
643 	if (!level || level > zstd_max_clevel()) {
644 		f2fs_info(sbi, "invalid zstd compress level: %d", level);
645 		return -EINVAL;
646 	}
647 
648 	F2FS_OPTION(sbi).compress_level = level;
649 	return 0;
650 }
651 #endif
652 #endif
653 
654 static int parse_options(struct super_block *sb, char *options, bool is_remount)
655 {
656 	struct f2fs_sb_info *sbi = F2FS_SB(sb);
657 	substring_t args[MAX_OPT_ARGS];
658 #ifdef CONFIG_F2FS_FS_COMPRESSION
659 	unsigned char (*ext)[F2FS_EXTENSION_LEN];
660 	unsigned char (*noext)[F2FS_EXTENSION_LEN];
661 	int ext_cnt, noext_cnt;
662 #endif
663 	char *p, *name;
664 	int arg = 0;
665 	kuid_t uid;
666 	kgid_t gid;
667 	int ret;
668 
669 	if (!options)
670 		goto default_check;
671 
672 	while ((p = strsep(&options, ",")) != NULL) {
673 		int token;
674 
675 		if (!*p)
676 			continue;
677 		/*
678 		 * Initialize args struct so we know whether arg was
679 		 * found; some options take optional arguments.
680 		 */
681 		args[0].to = args[0].from = NULL;
682 		token = match_token(p, f2fs_tokens, args);
683 
684 		switch (token) {
685 		case Opt_gc_background:
686 			name = match_strdup(&args[0]);
687 
688 			if (!name)
689 				return -ENOMEM;
690 			if (!strcmp(name, "on")) {
691 				F2FS_OPTION(sbi).bggc_mode = BGGC_MODE_ON;
692 			} else if (!strcmp(name, "off")) {
693 				F2FS_OPTION(sbi).bggc_mode = BGGC_MODE_OFF;
694 			} else if (!strcmp(name, "sync")) {
695 				F2FS_OPTION(sbi).bggc_mode = BGGC_MODE_SYNC;
696 			} else {
697 				kfree(name);
698 				return -EINVAL;
699 			}
700 			kfree(name);
701 			break;
702 		case Opt_disable_roll_forward:
703 			set_opt(sbi, DISABLE_ROLL_FORWARD);
704 			break;
705 		case Opt_norecovery:
706 			/* this option mounts f2fs with ro */
707 			set_opt(sbi, NORECOVERY);
708 			if (!f2fs_readonly(sb))
709 				return -EINVAL;
710 			break;
711 		case Opt_discard:
712 			if (!f2fs_hw_support_discard(sbi)) {
713 				f2fs_warn(sbi, "device does not support discard");
714 				break;
715 			}
716 			set_opt(sbi, DISCARD);
717 			break;
718 		case Opt_nodiscard:
719 			if (f2fs_hw_should_discard(sbi)) {
720 				f2fs_warn(sbi, "discard is required for zoned block devices");
721 				return -EINVAL;
722 			}
723 			clear_opt(sbi, DISCARD);
724 			break;
725 		case Opt_noheap:
726 			set_opt(sbi, NOHEAP);
727 			break;
728 		case Opt_heap:
729 			clear_opt(sbi, NOHEAP);
730 			break;
731 #ifdef CONFIG_F2FS_FS_XATTR
732 		case Opt_user_xattr:
733 			set_opt(sbi, XATTR_USER);
734 			break;
735 		case Opt_nouser_xattr:
736 			clear_opt(sbi, XATTR_USER);
737 			break;
738 		case Opt_inline_xattr:
739 			set_opt(sbi, INLINE_XATTR);
740 			break;
741 		case Opt_noinline_xattr:
742 			clear_opt(sbi, INLINE_XATTR);
743 			break;
744 		case Opt_inline_xattr_size:
745 			if (args->from && match_int(args, &arg))
746 				return -EINVAL;
747 			set_opt(sbi, INLINE_XATTR_SIZE);
748 			F2FS_OPTION(sbi).inline_xattr_size = arg;
749 			break;
750 #else
751 		case Opt_user_xattr:
752 			f2fs_info(sbi, "user_xattr options not supported");
753 			break;
754 		case Opt_nouser_xattr:
755 			f2fs_info(sbi, "nouser_xattr options not supported");
756 			break;
757 		case Opt_inline_xattr:
758 			f2fs_info(sbi, "inline_xattr options not supported");
759 			break;
760 		case Opt_noinline_xattr:
761 			f2fs_info(sbi, "noinline_xattr options not supported");
762 			break;
763 #endif
764 #ifdef CONFIG_F2FS_FS_POSIX_ACL
765 		case Opt_acl:
766 			set_opt(sbi, POSIX_ACL);
767 			break;
768 		case Opt_noacl:
769 			clear_opt(sbi, POSIX_ACL);
770 			break;
771 #else
772 		case Opt_acl:
773 			f2fs_info(sbi, "acl options not supported");
774 			break;
775 		case Opt_noacl:
776 			f2fs_info(sbi, "noacl options not supported");
777 			break;
778 #endif
779 		case Opt_active_logs:
780 			if (args->from && match_int(args, &arg))
781 				return -EINVAL;
782 			if (arg != 2 && arg != 4 &&
783 				arg != NR_CURSEG_PERSIST_TYPE)
784 				return -EINVAL;
785 			F2FS_OPTION(sbi).active_logs = arg;
786 			break;
787 		case Opt_disable_ext_identify:
788 			set_opt(sbi, DISABLE_EXT_IDENTIFY);
789 			break;
790 		case Opt_inline_data:
791 			set_opt(sbi, INLINE_DATA);
792 			break;
793 		case Opt_inline_dentry:
794 			set_opt(sbi, INLINE_DENTRY);
795 			break;
796 		case Opt_noinline_dentry:
797 			clear_opt(sbi, INLINE_DENTRY);
798 			break;
799 		case Opt_flush_merge:
800 			set_opt(sbi, FLUSH_MERGE);
801 			break;
802 		case Opt_noflush_merge:
803 			clear_opt(sbi, FLUSH_MERGE);
804 			break;
805 		case Opt_nobarrier:
806 			set_opt(sbi, NOBARRIER);
807 			break;
808 		case Opt_barrier:
809 			clear_opt(sbi, NOBARRIER);
810 			break;
811 		case Opt_fastboot:
812 			set_opt(sbi, FASTBOOT);
813 			break;
814 		case Opt_extent_cache:
815 			set_opt(sbi, READ_EXTENT_CACHE);
816 			break;
817 		case Opt_noextent_cache:
818 			clear_opt(sbi, READ_EXTENT_CACHE);
819 			break;
820 		case Opt_noinline_data:
821 			clear_opt(sbi, INLINE_DATA);
822 			break;
823 		case Opt_data_flush:
824 			set_opt(sbi, DATA_FLUSH);
825 			break;
826 		case Opt_reserve_root:
827 			if (args->from && match_int(args, &arg))
828 				return -EINVAL;
829 			if (test_opt(sbi, RESERVE_ROOT)) {
830 				f2fs_info(sbi, "Preserve previous reserve_root=%u",
831 					  F2FS_OPTION(sbi).root_reserved_blocks);
832 			} else {
833 				F2FS_OPTION(sbi).root_reserved_blocks = arg;
834 				set_opt(sbi, RESERVE_ROOT);
835 			}
836 			break;
837 		case Opt_resuid:
838 			if (args->from && match_int(args, &arg))
839 				return -EINVAL;
840 			uid = make_kuid(current_user_ns(), arg);
841 			if (!uid_valid(uid)) {
842 				f2fs_err(sbi, "Invalid uid value %d", arg);
843 				return -EINVAL;
844 			}
845 			F2FS_OPTION(sbi).s_resuid = uid;
846 			break;
847 		case Opt_resgid:
848 			if (args->from && match_int(args, &arg))
849 				return -EINVAL;
850 			gid = make_kgid(current_user_ns(), arg);
851 			if (!gid_valid(gid)) {
852 				f2fs_err(sbi, "Invalid gid value %d", arg);
853 				return -EINVAL;
854 			}
855 			F2FS_OPTION(sbi).s_resgid = gid;
856 			break;
857 		case Opt_mode:
858 			name = match_strdup(&args[0]);
859 
860 			if (!name)
861 				return -ENOMEM;
862 			if (!strcmp(name, "adaptive")) {
863 				if (f2fs_sb_has_blkzoned(sbi)) {
864 					f2fs_warn(sbi, "adaptive mode is not allowed with zoned block device feature");
865 					kfree(name);
866 					return -EINVAL;
867 				}
868 				F2FS_OPTION(sbi).fs_mode = FS_MODE_ADAPTIVE;
869 			} else if (!strcmp(name, "lfs")) {
870 				F2FS_OPTION(sbi).fs_mode = FS_MODE_LFS;
871 			} else if (!strcmp(name, "fragment:segment")) {
872 				F2FS_OPTION(sbi).fs_mode = FS_MODE_FRAGMENT_SEG;
873 			} else if (!strcmp(name, "fragment:block")) {
874 				F2FS_OPTION(sbi).fs_mode = FS_MODE_FRAGMENT_BLK;
875 			} else {
876 				kfree(name);
877 				return -EINVAL;
878 			}
879 			kfree(name);
880 			break;
881 		case Opt_io_size_bits:
882 			if (args->from && match_int(args, &arg))
883 				return -EINVAL;
884 			if (arg <= 0 || arg > __ilog2_u32(BIO_MAX_VECS)) {
885 				f2fs_warn(sbi, "Not support %ld, larger than %d",
886 					BIT(arg), BIO_MAX_VECS);
887 				return -EINVAL;
888 			}
889 			F2FS_OPTION(sbi).write_io_size_bits = arg;
890 			break;
891 #ifdef CONFIG_F2FS_FAULT_INJECTION
892 		case Opt_fault_injection:
893 			if (args->from && match_int(args, &arg))
894 				return -EINVAL;
895 			f2fs_build_fault_attr(sbi, arg, F2FS_ALL_FAULT_TYPE);
896 			set_opt(sbi, FAULT_INJECTION);
897 			break;
898 
899 		case Opt_fault_type:
900 			if (args->from && match_int(args, &arg))
901 				return -EINVAL;
902 			f2fs_build_fault_attr(sbi, 0, arg);
903 			set_opt(sbi, FAULT_INJECTION);
904 			break;
905 #else
906 		case Opt_fault_injection:
907 			f2fs_info(sbi, "fault_injection options not supported");
908 			break;
909 
910 		case Opt_fault_type:
911 			f2fs_info(sbi, "fault_type options not supported");
912 			break;
913 #endif
914 		case Opt_lazytime:
915 			sb->s_flags |= SB_LAZYTIME;
916 			break;
917 		case Opt_nolazytime:
918 			sb->s_flags &= ~SB_LAZYTIME;
919 			break;
920 #ifdef CONFIG_QUOTA
921 		case Opt_quota:
922 		case Opt_usrquota:
923 			set_opt(sbi, USRQUOTA);
924 			break;
925 		case Opt_grpquota:
926 			set_opt(sbi, GRPQUOTA);
927 			break;
928 		case Opt_prjquota:
929 			set_opt(sbi, PRJQUOTA);
930 			break;
931 		case Opt_usrjquota:
932 			ret = f2fs_set_qf_name(sb, USRQUOTA, &args[0]);
933 			if (ret)
934 				return ret;
935 			break;
936 		case Opt_grpjquota:
937 			ret = f2fs_set_qf_name(sb, GRPQUOTA, &args[0]);
938 			if (ret)
939 				return ret;
940 			break;
941 		case Opt_prjjquota:
942 			ret = f2fs_set_qf_name(sb, PRJQUOTA, &args[0]);
943 			if (ret)
944 				return ret;
945 			break;
946 		case Opt_offusrjquota:
947 			ret = f2fs_clear_qf_name(sb, USRQUOTA);
948 			if (ret)
949 				return ret;
950 			break;
951 		case Opt_offgrpjquota:
952 			ret = f2fs_clear_qf_name(sb, GRPQUOTA);
953 			if (ret)
954 				return ret;
955 			break;
956 		case Opt_offprjjquota:
957 			ret = f2fs_clear_qf_name(sb, PRJQUOTA);
958 			if (ret)
959 				return ret;
960 			break;
961 		case Opt_jqfmt_vfsold:
962 			F2FS_OPTION(sbi).s_jquota_fmt = QFMT_VFS_OLD;
963 			break;
964 		case Opt_jqfmt_vfsv0:
965 			F2FS_OPTION(sbi).s_jquota_fmt = QFMT_VFS_V0;
966 			break;
967 		case Opt_jqfmt_vfsv1:
968 			F2FS_OPTION(sbi).s_jquota_fmt = QFMT_VFS_V1;
969 			break;
970 		case Opt_noquota:
971 			clear_opt(sbi, QUOTA);
972 			clear_opt(sbi, USRQUOTA);
973 			clear_opt(sbi, GRPQUOTA);
974 			clear_opt(sbi, PRJQUOTA);
975 			break;
976 #else
977 		case Opt_quota:
978 		case Opt_usrquota:
979 		case Opt_grpquota:
980 		case Opt_prjquota:
981 		case Opt_usrjquota:
982 		case Opt_grpjquota:
983 		case Opt_prjjquota:
984 		case Opt_offusrjquota:
985 		case Opt_offgrpjquota:
986 		case Opt_offprjjquota:
987 		case Opt_jqfmt_vfsold:
988 		case Opt_jqfmt_vfsv0:
989 		case Opt_jqfmt_vfsv1:
990 		case Opt_noquota:
991 			f2fs_info(sbi, "quota operations not supported");
992 			break;
993 #endif
994 		case Opt_alloc:
995 			name = match_strdup(&args[0]);
996 			if (!name)
997 				return -ENOMEM;
998 
999 			if (!strcmp(name, "default")) {
1000 				F2FS_OPTION(sbi).alloc_mode = ALLOC_MODE_DEFAULT;
1001 			} else if (!strcmp(name, "reuse")) {
1002 				F2FS_OPTION(sbi).alloc_mode = ALLOC_MODE_REUSE;
1003 			} else {
1004 				kfree(name);
1005 				return -EINVAL;
1006 			}
1007 			kfree(name);
1008 			break;
1009 		case Opt_fsync:
1010 			name = match_strdup(&args[0]);
1011 			if (!name)
1012 				return -ENOMEM;
1013 			if (!strcmp(name, "posix")) {
1014 				F2FS_OPTION(sbi).fsync_mode = FSYNC_MODE_POSIX;
1015 			} else if (!strcmp(name, "strict")) {
1016 				F2FS_OPTION(sbi).fsync_mode = FSYNC_MODE_STRICT;
1017 			} else if (!strcmp(name, "nobarrier")) {
1018 				F2FS_OPTION(sbi).fsync_mode =
1019 							FSYNC_MODE_NOBARRIER;
1020 			} else {
1021 				kfree(name);
1022 				return -EINVAL;
1023 			}
1024 			kfree(name);
1025 			break;
1026 		case Opt_test_dummy_encryption:
1027 			ret = f2fs_set_test_dummy_encryption(sb, p, &args[0],
1028 							     is_remount);
1029 			if (ret)
1030 				return ret;
1031 			break;
1032 		case Opt_inlinecrypt:
1033 #ifdef CONFIG_FS_ENCRYPTION_INLINE_CRYPT
1034 			sb->s_flags |= SB_INLINECRYPT;
1035 #else
1036 			f2fs_info(sbi, "inline encryption not supported");
1037 #endif
1038 			break;
1039 		case Opt_checkpoint_disable_cap_perc:
1040 			if (args->from && match_int(args, &arg))
1041 				return -EINVAL;
1042 			if (arg < 0 || arg > 100)
1043 				return -EINVAL;
1044 			F2FS_OPTION(sbi).unusable_cap_perc = arg;
1045 			set_opt(sbi, DISABLE_CHECKPOINT);
1046 			break;
1047 		case Opt_checkpoint_disable_cap:
1048 			if (args->from && match_int(args, &arg))
1049 				return -EINVAL;
1050 			F2FS_OPTION(sbi).unusable_cap = arg;
1051 			set_opt(sbi, DISABLE_CHECKPOINT);
1052 			break;
1053 		case Opt_checkpoint_disable:
1054 			set_opt(sbi, DISABLE_CHECKPOINT);
1055 			break;
1056 		case Opt_checkpoint_enable:
1057 			clear_opt(sbi, DISABLE_CHECKPOINT);
1058 			break;
1059 		case Opt_checkpoint_merge:
1060 			set_opt(sbi, MERGE_CHECKPOINT);
1061 			break;
1062 		case Opt_nocheckpoint_merge:
1063 			clear_opt(sbi, MERGE_CHECKPOINT);
1064 			break;
1065 #ifdef CONFIG_F2FS_FS_COMPRESSION
1066 		case Opt_compress_algorithm:
1067 			if (!f2fs_sb_has_compression(sbi)) {
1068 				f2fs_info(sbi, "Image doesn't support compression");
1069 				break;
1070 			}
1071 			name = match_strdup(&args[0]);
1072 			if (!name)
1073 				return -ENOMEM;
1074 			if (!strcmp(name, "lzo")) {
1075 #ifdef CONFIG_F2FS_FS_LZO
1076 				F2FS_OPTION(sbi).compress_level = 0;
1077 				F2FS_OPTION(sbi).compress_algorithm =
1078 								COMPRESS_LZO;
1079 #else
1080 				f2fs_info(sbi, "kernel doesn't support lzo compression");
1081 #endif
1082 			} else if (!strncmp(name, "lz4", 3)) {
1083 #ifdef CONFIG_F2FS_FS_LZ4
1084 				ret = f2fs_set_lz4hc_level(sbi, name);
1085 				if (ret) {
1086 					kfree(name);
1087 					return -EINVAL;
1088 				}
1089 				F2FS_OPTION(sbi).compress_algorithm =
1090 								COMPRESS_LZ4;
1091 #else
1092 				f2fs_info(sbi, "kernel doesn't support lz4 compression");
1093 #endif
1094 			} else if (!strncmp(name, "zstd", 4)) {
1095 #ifdef CONFIG_F2FS_FS_ZSTD
1096 				ret = f2fs_set_zstd_level(sbi, name);
1097 				if (ret) {
1098 					kfree(name);
1099 					return -EINVAL;
1100 				}
1101 				F2FS_OPTION(sbi).compress_algorithm =
1102 								COMPRESS_ZSTD;
1103 #else
1104 				f2fs_info(sbi, "kernel doesn't support zstd compression");
1105 #endif
1106 			} else if (!strcmp(name, "lzo-rle")) {
1107 #ifdef CONFIG_F2FS_FS_LZORLE
1108 				F2FS_OPTION(sbi).compress_level = 0;
1109 				F2FS_OPTION(sbi).compress_algorithm =
1110 								COMPRESS_LZORLE;
1111 #else
1112 				f2fs_info(sbi, "kernel doesn't support lzorle compression");
1113 #endif
1114 			} else {
1115 				kfree(name);
1116 				return -EINVAL;
1117 			}
1118 			kfree(name);
1119 			break;
1120 		case Opt_compress_log_size:
1121 			if (!f2fs_sb_has_compression(sbi)) {
1122 				f2fs_info(sbi, "Image doesn't support compression");
1123 				break;
1124 			}
1125 			if (args->from && match_int(args, &arg))
1126 				return -EINVAL;
1127 			if (arg < MIN_COMPRESS_LOG_SIZE ||
1128 				arg > MAX_COMPRESS_LOG_SIZE) {
1129 				f2fs_err(sbi,
1130 					"Compress cluster log size is out of range");
1131 				return -EINVAL;
1132 			}
1133 			F2FS_OPTION(sbi).compress_log_size = arg;
1134 			break;
1135 		case Opt_compress_extension:
1136 			if (!f2fs_sb_has_compression(sbi)) {
1137 				f2fs_info(sbi, "Image doesn't support compression");
1138 				break;
1139 			}
1140 			name = match_strdup(&args[0]);
1141 			if (!name)
1142 				return -ENOMEM;
1143 
1144 			ext = F2FS_OPTION(sbi).extensions;
1145 			ext_cnt = F2FS_OPTION(sbi).compress_ext_cnt;
1146 
1147 			if (strlen(name) >= F2FS_EXTENSION_LEN ||
1148 				ext_cnt >= COMPRESS_EXT_NUM) {
1149 				f2fs_err(sbi,
1150 					"invalid extension length/number");
1151 				kfree(name);
1152 				return -EINVAL;
1153 			}
1154 
1155 			strcpy(ext[ext_cnt], name);
1156 			F2FS_OPTION(sbi).compress_ext_cnt++;
1157 			kfree(name);
1158 			break;
1159 		case Opt_nocompress_extension:
1160 			if (!f2fs_sb_has_compression(sbi)) {
1161 				f2fs_info(sbi, "Image doesn't support compression");
1162 				break;
1163 			}
1164 			name = match_strdup(&args[0]);
1165 			if (!name)
1166 				return -ENOMEM;
1167 
1168 			noext = F2FS_OPTION(sbi).noextensions;
1169 			noext_cnt = F2FS_OPTION(sbi).nocompress_ext_cnt;
1170 
1171 			if (strlen(name) >= F2FS_EXTENSION_LEN ||
1172 				noext_cnt >= COMPRESS_EXT_NUM) {
1173 				f2fs_err(sbi,
1174 					"invalid extension length/number");
1175 				kfree(name);
1176 				return -EINVAL;
1177 			}
1178 
1179 			strcpy(noext[noext_cnt], name);
1180 			F2FS_OPTION(sbi).nocompress_ext_cnt++;
1181 			kfree(name);
1182 			break;
1183 		case Opt_compress_chksum:
1184 			if (!f2fs_sb_has_compression(sbi)) {
1185 				f2fs_info(sbi, "Image doesn't support compression");
1186 				break;
1187 			}
1188 			F2FS_OPTION(sbi).compress_chksum = true;
1189 			break;
1190 		case Opt_compress_mode:
1191 			if (!f2fs_sb_has_compression(sbi)) {
1192 				f2fs_info(sbi, "Image doesn't support compression");
1193 				break;
1194 			}
1195 			name = match_strdup(&args[0]);
1196 			if (!name)
1197 				return -ENOMEM;
1198 			if (!strcmp(name, "fs")) {
1199 				F2FS_OPTION(sbi).compress_mode = COMPR_MODE_FS;
1200 			} else if (!strcmp(name, "user")) {
1201 				F2FS_OPTION(sbi).compress_mode = COMPR_MODE_USER;
1202 			} else {
1203 				kfree(name);
1204 				return -EINVAL;
1205 			}
1206 			kfree(name);
1207 			break;
1208 		case Opt_compress_cache:
1209 			if (!f2fs_sb_has_compression(sbi)) {
1210 				f2fs_info(sbi, "Image doesn't support compression");
1211 				break;
1212 			}
1213 			set_opt(sbi, COMPRESS_CACHE);
1214 			break;
1215 #else
1216 		case Opt_compress_algorithm:
1217 		case Opt_compress_log_size:
1218 		case Opt_compress_extension:
1219 		case Opt_nocompress_extension:
1220 		case Opt_compress_chksum:
1221 		case Opt_compress_mode:
1222 		case Opt_compress_cache:
1223 			f2fs_info(sbi, "compression options not supported");
1224 			break;
1225 #endif
1226 		case Opt_atgc:
1227 			set_opt(sbi, ATGC);
1228 			break;
1229 		case Opt_gc_merge:
1230 			set_opt(sbi, GC_MERGE);
1231 			break;
1232 		case Opt_nogc_merge:
1233 			clear_opt(sbi, GC_MERGE);
1234 			break;
1235 		case Opt_discard_unit:
1236 			name = match_strdup(&args[0]);
1237 			if (!name)
1238 				return -ENOMEM;
1239 			if (!strcmp(name, "block")) {
1240 				F2FS_OPTION(sbi).discard_unit =
1241 						DISCARD_UNIT_BLOCK;
1242 			} else if (!strcmp(name, "segment")) {
1243 				F2FS_OPTION(sbi).discard_unit =
1244 						DISCARD_UNIT_SEGMENT;
1245 			} else if (!strcmp(name, "section")) {
1246 				F2FS_OPTION(sbi).discard_unit =
1247 						DISCARD_UNIT_SECTION;
1248 			} else {
1249 				kfree(name);
1250 				return -EINVAL;
1251 			}
1252 			kfree(name);
1253 			break;
1254 		case Opt_memory_mode:
1255 			name = match_strdup(&args[0]);
1256 			if (!name)
1257 				return -ENOMEM;
1258 			if (!strcmp(name, "normal")) {
1259 				F2FS_OPTION(sbi).memory_mode =
1260 						MEMORY_MODE_NORMAL;
1261 			} else if (!strcmp(name, "low")) {
1262 				F2FS_OPTION(sbi).memory_mode =
1263 						MEMORY_MODE_LOW;
1264 			} else {
1265 				kfree(name);
1266 				return -EINVAL;
1267 			}
1268 			kfree(name);
1269 			break;
1270 		case Opt_age_extent_cache:
1271 			set_opt(sbi, AGE_EXTENT_CACHE);
1272 			break;
1273 		case Opt_errors:
1274 			name = match_strdup(&args[0]);
1275 			if (!name)
1276 				return -ENOMEM;
1277 			if (!strcmp(name, "remount-ro")) {
1278 				F2FS_OPTION(sbi).errors =
1279 						MOUNT_ERRORS_READONLY;
1280 			} else if (!strcmp(name, "continue")) {
1281 				F2FS_OPTION(sbi).errors =
1282 						MOUNT_ERRORS_CONTINUE;
1283 			} else if (!strcmp(name, "panic")) {
1284 				F2FS_OPTION(sbi).errors =
1285 						MOUNT_ERRORS_PANIC;
1286 			} else {
1287 				kfree(name);
1288 				return -EINVAL;
1289 			}
1290 			kfree(name);
1291 			break;
1292 		default:
1293 			f2fs_err(sbi, "Unrecognized mount option \"%s\" or missing value",
1294 				 p);
1295 			return -EINVAL;
1296 		}
1297 	}
1298 default_check:
1299 #ifdef CONFIG_QUOTA
1300 	if (f2fs_check_quota_options(sbi))
1301 		return -EINVAL;
1302 #else
1303 	if (f2fs_sb_has_quota_ino(sbi) && !f2fs_readonly(sbi->sb)) {
1304 		f2fs_info(sbi, "Filesystem with quota feature cannot be mounted RDWR without CONFIG_QUOTA");
1305 		return -EINVAL;
1306 	}
1307 	if (f2fs_sb_has_project_quota(sbi) && !f2fs_readonly(sbi->sb)) {
1308 		f2fs_err(sbi, "Filesystem with project quota feature cannot be mounted RDWR without CONFIG_QUOTA");
1309 		return -EINVAL;
1310 	}
1311 #endif
1312 #if !IS_ENABLED(CONFIG_UNICODE)
1313 	if (f2fs_sb_has_casefold(sbi)) {
1314 		f2fs_err(sbi,
1315 			"Filesystem with casefold feature cannot be mounted without CONFIG_UNICODE");
1316 		return -EINVAL;
1317 	}
1318 #endif
1319 	/*
1320 	 * The BLKZONED feature indicates that the drive was formatted with
1321 	 * zone alignment optimization. This is optional for host-aware
1322 	 * devices, but mandatory for host-managed zoned block devices.
1323 	 */
1324 	if (f2fs_sb_has_blkzoned(sbi)) {
1325 #ifdef CONFIG_BLK_DEV_ZONED
1326 		if (F2FS_OPTION(sbi).discard_unit !=
1327 						DISCARD_UNIT_SECTION) {
1328 			f2fs_info(sbi, "Zoned block device doesn't need small discard, set discard_unit=section by default");
1329 			F2FS_OPTION(sbi).discard_unit =
1330 					DISCARD_UNIT_SECTION;
1331 		}
1332 #else
1333 		f2fs_err(sbi, "Zoned block device support is not enabled");
1334 		return -EINVAL;
1335 #endif
1336 	}
1337 
1338 #ifdef CONFIG_F2FS_FS_COMPRESSION
1339 	if (f2fs_test_compress_extension(sbi)) {
1340 		f2fs_err(sbi, "invalid compress or nocompress extension");
1341 		return -EINVAL;
1342 	}
1343 #endif
1344 
1345 	if (F2FS_IO_SIZE_BITS(sbi) && !f2fs_lfs_mode(sbi)) {
1346 		f2fs_err(sbi, "Should set mode=lfs with %luKB-sized IO",
1347 			 F2FS_IO_SIZE_KB(sbi));
1348 		return -EINVAL;
1349 	}
1350 
1351 	if (test_opt(sbi, INLINE_XATTR_SIZE)) {
1352 		int min_size, max_size;
1353 
1354 		if (!f2fs_sb_has_extra_attr(sbi) ||
1355 			!f2fs_sb_has_flexible_inline_xattr(sbi)) {
1356 			f2fs_err(sbi, "extra_attr or flexible_inline_xattr feature is off");
1357 			return -EINVAL;
1358 		}
1359 		if (!test_opt(sbi, INLINE_XATTR)) {
1360 			f2fs_err(sbi, "inline_xattr_size option should be set with inline_xattr option");
1361 			return -EINVAL;
1362 		}
1363 
1364 		min_size = sizeof(struct f2fs_xattr_header) / sizeof(__le32);
1365 		max_size = MAX_INLINE_XATTR_SIZE;
1366 
1367 		if (F2FS_OPTION(sbi).inline_xattr_size < min_size ||
1368 				F2FS_OPTION(sbi).inline_xattr_size > max_size) {
1369 			f2fs_err(sbi, "inline xattr size is out of range: %d ~ %d",
1370 				 min_size, max_size);
1371 			return -EINVAL;
1372 		}
1373 	}
1374 
1375 	if (test_opt(sbi, DISABLE_CHECKPOINT) && f2fs_lfs_mode(sbi)) {
1376 		f2fs_err(sbi, "LFS is not compatible with checkpoint=disable");
1377 		return -EINVAL;
1378 	}
1379 
1380 	if (test_opt(sbi, ATGC) && f2fs_lfs_mode(sbi)) {
1381 		f2fs_err(sbi, "LFS is not compatible with ATGC");
1382 		return -EINVAL;
1383 	}
1384 
1385 	if (f2fs_is_readonly(sbi) && test_opt(sbi, FLUSH_MERGE)) {
1386 		f2fs_err(sbi, "FLUSH_MERGE not compatible with readonly mode");
1387 		return -EINVAL;
1388 	}
1389 
1390 	if (f2fs_sb_has_readonly(sbi) && !f2fs_readonly(sbi->sb)) {
1391 		f2fs_err(sbi, "Allow to mount readonly mode only");
1392 		return -EROFS;
1393 	}
1394 	return 0;
1395 }
1396 
1397 static struct inode *f2fs_alloc_inode(struct super_block *sb)
1398 {
1399 	struct f2fs_inode_info *fi;
1400 
1401 	if (time_to_inject(F2FS_SB(sb), FAULT_SLAB_ALLOC))
1402 		return NULL;
1403 
1404 	fi = alloc_inode_sb(sb, f2fs_inode_cachep, GFP_F2FS_ZERO);
1405 	if (!fi)
1406 		return NULL;
1407 
1408 	init_once((void *) fi);
1409 
1410 	/* Initialize f2fs-specific inode info */
1411 	atomic_set(&fi->dirty_pages, 0);
1412 	atomic_set(&fi->i_compr_blocks, 0);
1413 	init_f2fs_rwsem(&fi->i_sem);
1414 	spin_lock_init(&fi->i_size_lock);
1415 	INIT_LIST_HEAD(&fi->dirty_list);
1416 	INIT_LIST_HEAD(&fi->gdirty_list);
1417 	init_f2fs_rwsem(&fi->i_gc_rwsem[READ]);
1418 	init_f2fs_rwsem(&fi->i_gc_rwsem[WRITE]);
1419 	init_f2fs_rwsem(&fi->i_xattr_sem);
1420 
1421 	/* Will be used by directory only */
1422 	fi->i_dir_level = F2FS_SB(sb)->dir_level;
1423 
1424 	return &fi->vfs_inode;
1425 }
1426 
1427 static int f2fs_drop_inode(struct inode *inode)
1428 {
1429 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1430 	int ret;
1431 
1432 	/*
1433 	 * during filesystem shutdown, if checkpoint is disabled,
1434 	 * drop useless meta/node dirty pages.
1435 	 */
1436 	if (unlikely(is_sbi_flag_set(sbi, SBI_CP_DISABLED))) {
1437 		if (inode->i_ino == F2FS_NODE_INO(sbi) ||
1438 			inode->i_ino == F2FS_META_INO(sbi)) {
1439 			trace_f2fs_drop_inode(inode, 1);
1440 			return 1;
1441 		}
1442 	}
1443 
1444 	/*
1445 	 * This is to avoid a deadlock condition like below.
1446 	 * writeback_single_inode(inode)
1447 	 *  - f2fs_write_data_page
1448 	 *    - f2fs_gc -> iput -> evict
1449 	 *       - inode_wait_for_writeback(inode)
1450 	 */
1451 	if ((!inode_unhashed(inode) && inode->i_state & I_SYNC)) {
1452 		if (!inode->i_nlink && !is_bad_inode(inode)) {
1453 			/* to avoid evict_inode call simultaneously */
1454 			atomic_inc(&inode->i_count);
1455 			spin_unlock(&inode->i_lock);
1456 
1457 			/* should remain fi->extent_tree for writepage */
1458 			f2fs_destroy_extent_node(inode);
1459 
1460 			sb_start_intwrite(inode->i_sb);
1461 			f2fs_i_size_write(inode, 0);
1462 
1463 			f2fs_submit_merged_write_cond(F2FS_I_SB(inode),
1464 					inode, NULL, 0, DATA);
1465 			truncate_inode_pages_final(inode->i_mapping);
1466 
1467 			if (F2FS_HAS_BLOCKS(inode))
1468 				f2fs_truncate(inode);
1469 
1470 			sb_end_intwrite(inode->i_sb);
1471 
1472 			spin_lock(&inode->i_lock);
1473 			atomic_dec(&inode->i_count);
1474 		}
1475 		trace_f2fs_drop_inode(inode, 0);
1476 		return 0;
1477 	}
1478 	ret = generic_drop_inode(inode);
1479 	if (!ret)
1480 		ret = fscrypt_drop_inode(inode);
1481 	trace_f2fs_drop_inode(inode, ret);
1482 	return ret;
1483 }
1484 
1485 int f2fs_inode_dirtied(struct inode *inode, bool sync)
1486 {
1487 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1488 	int ret = 0;
1489 
1490 	spin_lock(&sbi->inode_lock[DIRTY_META]);
1491 	if (is_inode_flag_set(inode, FI_DIRTY_INODE)) {
1492 		ret = 1;
1493 	} else {
1494 		set_inode_flag(inode, FI_DIRTY_INODE);
1495 		stat_inc_dirty_inode(sbi, DIRTY_META);
1496 	}
1497 	if (sync && list_empty(&F2FS_I(inode)->gdirty_list)) {
1498 		list_add_tail(&F2FS_I(inode)->gdirty_list,
1499 				&sbi->inode_list[DIRTY_META]);
1500 		inc_page_count(sbi, F2FS_DIRTY_IMETA);
1501 	}
1502 	spin_unlock(&sbi->inode_lock[DIRTY_META]);
1503 	return ret;
1504 }
1505 
1506 void f2fs_inode_synced(struct inode *inode)
1507 {
1508 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1509 
1510 	spin_lock(&sbi->inode_lock[DIRTY_META]);
1511 	if (!is_inode_flag_set(inode, FI_DIRTY_INODE)) {
1512 		spin_unlock(&sbi->inode_lock[DIRTY_META]);
1513 		return;
1514 	}
1515 	if (!list_empty(&F2FS_I(inode)->gdirty_list)) {
1516 		list_del_init(&F2FS_I(inode)->gdirty_list);
1517 		dec_page_count(sbi, F2FS_DIRTY_IMETA);
1518 	}
1519 	clear_inode_flag(inode, FI_DIRTY_INODE);
1520 	clear_inode_flag(inode, FI_AUTO_RECOVER);
1521 	stat_dec_dirty_inode(F2FS_I_SB(inode), DIRTY_META);
1522 	spin_unlock(&sbi->inode_lock[DIRTY_META]);
1523 }
1524 
1525 /*
1526  * f2fs_dirty_inode() is called from __mark_inode_dirty()
1527  *
1528  * We should call set_dirty_inode to write the dirty inode through write_inode.
1529  */
1530 static void f2fs_dirty_inode(struct inode *inode, int flags)
1531 {
1532 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1533 
1534 	if (inode->i_ino == F2FS_NODE_INO(sbi) ||
1535 			inode->i_ino == F2FS_META_INO(sbi))
1536 		return;
1537 
1538 	if (is_inode_flag_set(inode, FI_AUTO_RECOVER))
1539 		clear_inode_flag(inode, FI_AUTO_RECOVER);
1540 
1541 	f2fs_inode_dirtied(inode, false);
1542 }
1543 
1544 static void f2fs_free_inode(struct inode *inode)
1545 {
1546 	fscrypt_free_inode(inode);
1547 	kmem_cache_free(f2fs_inode_cachep, F2FS_I(inode));
1548 }
1549 
1550 static void destroy_percpu_info(struct f2fs_sb_info *sbi)
1551 {
1552 	percpu_counter_destroy(&sbi->total_valid_inode_count);
1553 	percpu_counter_destroy(&sbi->rf_node_block_count);
1554 	percpu_counter_destroy(&sbi->alloc_valid_block_count);
1555 }
1556 
1557 static void destroy_device_list(struct f2fs_sb_info *sbi)
1558 {
1559 	int i;
1560 
1561 	for (i = 0; i < sbi->s_ndevs; i++) {
1562 		blkdev_put(FDEV(i).bdev, FMODE_EXCL);
1563 #ifdef CONFIG_BLK_DEV_ZONED
1564 		kvfree(FDEV(i).blkz_seq);
1565 #endif
1566 	}
1567 	kvfree(sbi->devs);
1568 }
1569 
1570 static void f2fs_put_super(struct super_block *sb)
1571 {
1572 	struct f2fs_sb_info *sbi = F2FS_SB(sb);
1573 	int i;
1574 	bool done;
1575 
1576 	/* unregister procfs/sysfs entries in advance to avoid race case */
1577 	f2fs_unregister_sysfs(sbi);
1578 
1579 	f2fs_quota_off_umount(sb);
1580 
1581 	/* prevent remaining shrinker jobs */
1582 	mutex_lock(&sbi->umount_mutex);
1583 
1584 	/*
1585 	 * flush all issued checkpoints and stop checkpoint issue thread.
1586 	 * after then, all checkpoints should be done by each process context.
1587 	 */
1588 	f2fs_stop_ckpt_thread(sbi);
1589 
1590 	/*
1591 	 * We don't need to do checkpoint when superblock is clean.
1592 	 * But, the previous checkpoint was not done by umount, it needs to do
1593 	 * clean checkpoint again.
1594 	 */
1595 	if ((is_sbi_flag_set(sbi, SBI_IS_DIRTY) ||
1596 			!is_set_ckpt_flags(sbi, CP_UMOUNT_FLAG))) {
1597 		struct cp_control cpc = {
1598 			.reason = CP_UMOUNT,
1599 		};
1600 		f2fs_write_checkpoint(sbi, &cpc);
1601 	}
1602 
1603 	/* be sure to wait for any on-going discard commands */
1604 	done = f2fs_issue_discard_timeout(sbi);
1605 	if (f2fs_realtime_discard_enable(sbi) && !sbi->discard_blks && done) {
1606 		struct cp_control cpc = {
1607 			.reason = CP_UMOUNT | CP_TRIMMED,
1608 		};
1609 		f2fs_write_checkpoint(sbi, &cpc);
1610 	}
1611 
1612 	/*
1613 	 * normally superblock is clean, so we need to release this.
1614 	 * In addition, EIO will skip do checkpoint, we need this as well.
1615 	 */
1616 	f2fs_release_ino_entry(sbi, true);
1617 
1618 	f2fs_leave_shrinker(sbi);
1619 	mutex_unlock(&sbi->umount_mutex);
1620 
1621 	/* our cp_error case, we can wait for any writeback page */
1622 	f2fs_flush_merged_writes(sbi);
1623 
1624 	f2fs_wait_on_all_pages(sbi, F2FS_WB_CP_DATA);
1625 
1626 	f2fs_bug_on(sbi, sbi->fsync_node_num);
1627 
1628 	f2fs_destroy_compress_inode(sbi);
1629 
1630 	iput(sbi->node_inode);
1631 	sbi->node_inode = NULL;
1632 
1633 	iput(sbi->meta_inode);
1634 	sbi->meta_inode = NULL;
1635 
1636 	/*
1637 	 * iput() can update stat information, if f2fs_write_checkpoint()
1638 	 * above failed with error.
1639 	 */
1640 	f2fs_destroy_stats(sbi);
1641 
1642 	/* destroy f2fs internal modules */
1643 	f2fs_destroy_node_manager(sbi);
1644 	f2fs_destroy_segment_manager(sbi);
1645 
1646 	/* flush s_error_work before sbi destroy */
1647 	flush_work(&sbi->s_error_work);
1648 
1649 	f2fs_destroy_post_read_wq(sbi);
1650 
1651 	kvfree(sbi->ckpt);
1652 
1653 	sb->s_fs_info = NULL;
1654 	if (sbi->s_chksum_driver)
1655 		crypto_free_shash(sbi->s_chksum_driver);
1656 	kfree(sbi->raw_super);
1657 
1658 	destroy_device_list(sbi);
1659 	f2fs_destroy_page_array_cache(sbi);
1660 	f2fs_destroy_xattr_caches(sbi);
1661 	mempool_destroy(sbi->write_io_dummy);
1662 #ifdef CONFIG_QUOTA
1663 	for (i = 0; i < MAXQUOTAS; i++)
1664 		kfree(F2FS_OPTION(sbi).s_qf_names[i]);
1665 #endif
1666 	fscrypt_free_dummy_policy(&F2FS_OPTION(sbi).dummy_enc_policy);
1667 	destroy_percpu_info(sbi);
1668 	f2fs_destroy_iostat(sbi);
1669 	for (i = 0; i < NR_PAGE_TYPE; i++)
1670 		kvfree(sbi->write_io[i]);
1671 #if IS_ENABLED(CONFIG_UNICODE)
1672 	utf8_unload(sb->s_encoding);
1673 #endif
1674 	kfree(sbi);
1675 }
1676 
1677 int f2fs_sync_fs(struct super_block *sb, int sync)
1678 {
1679 	struct f2fs_sb_info *sbi = F2FS_SB(sb);
1680 	int err = 0;
1681 
1682 	if (unlikely(f2fs_cp_error(sbi)))
1683 		return 0;
1684 	if (unlikely(is_sbi_flag_set(sbi, SBI_CP_DISABLED)))
1685 		return 0;
1686 
1687 	trace_f2fs_sync_fs(sb, sync);
1688 
1689 	if (unlikely(is_sbi_flag_set(sbi, SBI_POR_DOING)))
1690 		return -EAGAIN;
1691 
1692 	if (sync)
1693 		err = f2fs_issue_checkpoint(sbi);
1694 
1695 	return err;
1696 }
1697 
1698 static int f2fs_freeze(struct super_block *sb)
1699 {
1700 	if (f2fs_readonly(sb))
1701 		return 0;
1702 
1703 	/* IO error happened before */
1704 	if (unlikely(f2fs_cp_error(F2FS_SB(sb))))
1705 		return -EIO;
1706 
1707 	/* must be clean, since sync_filesystem() was already called */
1708 	if (is_sbi_flag_set(F2FS_SB(sb), SBI_IS_DIRTY))
1709 		return -EINVAL;
1710 
1711 	/* Let's flush checkpoints and stop the thread. */
1712 	f2fs_flush_ckpt_thread(F2FS_SB(sb));
1713 
1714 	/* to avoid deadlock on f2fs_evict_inode->SB_FREEZE_FS */
1715 	set_sbi_flag(F2FS_SB(sb), SBI_IS_FREEZING);
1716 	return 0;
1717 }
1718 
1719 static int f2fs_unfreeze(struct super_block *sb)
1720 {
1721 	clear_sbi_flag(F2FS_SB(sb), SBI_IS_FREEZING);
1722 	return 0;
1723 }
1724 
1725 #ifdef CONFIG_QUOTA
1726 static int f2fs_statfs_project(struct super_block *sb,
1727 				kprojid_t projid, struct kstatfs *buf)
1728 {
1729 	struct kqid qid;
1730 	struct dquot *dquot;
1731 	u64 limit;
1732 	u64 curblock;
1733 
1734 	qid = make_kqid_projid(projid);
1735 	dquot = dqget(sb, qid);
1736 	if (IS_ERR(dquot))
1737 		return PTR_ERR(dquot);
1738 	spin_lock(&dquot->dq_dqb_lock);
1739 
1740 	limit = min_not_zero(dquot->dq_dqb.dqb_bsoftlimit,
1741 					dquot->dq_dqb.dqb_bhardlimit);
1742 	if (limit)
1743 		limit >>= sb->s_blocksize_bits;
1744 
1745 	if (limit && buf->f_blocks > limit) {
1746 		curblock = (dquot->dq_dqb.dqb_curspace +
1747 			    dquot->dq_dqb.dqb_rsvspace) >> sb->s_blocksize_bits;
1748 		buf->f_blocks = limit;
1749 		buf->f_bfree = buf->f_bavail =
1750 			(buf->f_blocks > curblock) ?
1751 			 (buf->f_blocks - curblock) : 0;
1752 	}
1753 
1754 	limit = min_not_zero(dquot->dq_dqb.dqb_isoftlimit,
1755 					dquot->dq_dqb.dqb_ihardlimit);
1756 
1757 	if (limit && buf->f_files > limit) {
1758 		buf->f_files = limit;
1759 		buf->f_ffree =
1760 			(buf->f_files > dquot->dq_dqb.dqb_curinodes) ?
1761 			 (buf->f_files - dquot->dq_dqb.dqb_curinodes) : 0;
1762 	}
1763 
1764 	spin_unlock(&dquot->dq_dqb_lock);
1765 	dqput(dquot);
1766 	return 0;
1767 }
1768 #endif
1769 
1770 static int f2fs_statfs(struct dentry *dentry, struct kstatfs *buf)
1771 {
1772 	struct super_block *sb = dentry->d_sb;
1773 	struct f2fs_sb_info *sbi = F2FS_SB(sb);
1774 	u64 id = huge_encode_dev(sb->s_bdev->bd_dev);
1775 	block_t total_count, user_block_count, start_count;
1776 	u64 avail_node_count;
1777 	unsigned int total_valid_node_count;
1778 
1779 	total_count = le64_to_cpu(sbi->raw_super->block_count);
1780 	start_count = le32_to_cpu(sbi->raw_super->segment0_blkaddr);
1781 	buf->f_type = F2FS_SUPER_MAGIC;
1782 	buf->f_bsize = sbi->blocksize;
1783 
1784 	buf->f_blocks = total_count - start_count;
1785 
1786 	spin_lock(&sbi->stat_lock);
1787 
1788 	user_block_count = sbi->user_block_count;
1789 	total_valid_node_count = valid_node_count(sbi);
1790 	avail_node_count = sbi->total_node_count - F2FS_RESERVED_NODE_NUM;
1791 	buf->f_bfree = user_block_count - valid_user_blocks(sbi) -
1792 						sbi->current_reserved_blocks;
1793 
1794 	if (unlikely(buf->f_bfree <= sbi->unusable_block_count))
1795 		buf->f_bfree = 0;
1796 	else
1797 		buf->f_bfree -= sbi->unusable_block_count;
1798 	spin_unlock(&sbi->stat_lock);
1799 
1800 	if (buf->f_bfree > F2FS_OPTION(sbi).root_reserved_blocks)
1801 		buf->f_bavail = buf->f_bfree -
1802 				F2FS_OPTION(sbi).root_reserved_blocks;
1803 	else
1804 		buf->f_bavail = 0;
1805 
1806 	if (avail_node_count > user_block_count) {
1807 		buf->f_files = user_block_count;
1808 		buf->f_ffree = buf->f_bavail;
1809 	} else {
1810 		buf->f_files = avail_node_count;
1811 		buf->f_ffree = min(avail_node_count - total_valid_node_count,
1812 					buf->f_bavail);
1813 	}
1814 
1815 	buf->f_namelen = F2FS_NAME_LEN;
1816 	buf->f_fsid    = u64_to_fsid(id);
1817 
1818 #ifdef CONFIG_QUOTA
1819 	if (is_inode_flag_set(dentry->d_inode, FI_PROJ_INHERIT) &&
1820 			sb_has_quota_limits_enabled(sb, PRJQUOTA)) {
1821 		f2fs_statfs_project(sb, F2FS_I(dentry->d_inode)->i_projid, buf);
1822 	}
1823 #endif
1824 	return 0;
1825 }
1826 
1827 static inline void f2fs_show_quota_options(struct seq_file *seq,
1828 					   struct super_block *sb)
1829 {
1830 #ifdef CONFIG_QUOTA
1831 	struct f2fs_sb_info *sbi = F2FS_SB(sb);
1832 
1833 	if (F2FS_OPTION(sbi).s_jquota_fmt) {
1834 		char *fmtname = "";
1835 
1836 		switch (F2FS_OPTION(sbi).s_jquota_fmt) {
1837 		case QFMT_VFS_OLD:
1838 			fmtname = "vfsold";
1839 			break;
1840 		case QFMT_VFS_V0:
1841 			fmtname = "vfsv0";
1842 			break;
1843 		case QFMT_VFS_V1:
1844 			fmtname = "vfsv1";
1845 			break;
1846 		}
1847 		seq_printf(seq, ",jqfmt=%s", fmtname);
1848 	}
1849 
1850 	if (F2FS_OPTION(sbi).s_qf_names[USRQUOTA])
1851 		seq_show_option(seq, "usrjquota",
1852 			F2FS_OPTION(sbi).s_qf_names[USRQUOTA]);
1853 
1854 	if (F2FS_OPTION(sbi).s_qf_names[GRPQUOTA])
1855 		seq_show_option(seq, "grpjquota",
1856 			F2FS_OPTION(sbi).s_qf_names[GRPQUOTA]);
1857 
1858 	if (F2FS_OPTION(sbi).s_qf_names[PRJQUOTA])
1859 		seq_show_option(seq, "prjjquota",
1860 			F2FS_OPTION(sbi).s_qf_names[PRJQUOTA]);
1861 #endif
1862 }
1863 
1864 #ifdef CONFIG_F2FS_FS_COMPRESSION
1865 static inline void f2fs_show_compress_options(struct seq_file *seq,
1866 							struct super_block *sb)
1867 {
1868 	struct f2fs_sb_info *sbi = F2FS_SB(sb);
1869 	char *algtype = "";
1870 	int i;
1871 
1872 	if (!f2fs_sb_has_compression(sbi))
1873 		return;
1874 
1875 	switch (F2FS_OPTION(sbi).compress_algorithm) {
1876 	case COMPRESS_LZO:
1877 		algtype = "lzo";
1878 		break;
1879 	case COMPRESS_LZ4:
1880 		algtype = "lz4";
1881 		break;
1882 	case COMPRESS_ZSTD:
1883 		algtype = "zstd";
1884 		break;
1885 	case COMPRESS_LZORLE:
1886 		algtype = "lzo-rle";
1887 		break;
1888 	}
1889 	seq_printf(seq, ",compress_algorithm=%s", algtype);
1890 
1891 	if (F2FS_OPTION(sbi).compress_level)
1892 		seq_printf(seq, ":%d", F2FS_OPTION(sbi).compress_level);
1893 
1894 	seq_printf(seq, ",compress_log_size=%u",
1895 			F2FS_OPTION(sbi).compress_log_size);
1896 
1897 	for (i = 0; i < F2FS_OPTION(sbi).compress_ext_cnt; i++) {
1898 		seq_printf(seq, ",compress_extension=%s",
1899 			F2FS_OPTION(sbi).extensions[i]);
1900 	}
1901 
1902 	for (i = 0; i < F2FS_OPTION(sbi).nocompress_ext_cnt; i++) {
1903 		seq_printf(seq, ",nocompress_extension=%s",
1904 			F2FS_OPTION(sbi).noextensions[i]);
1905 	}
1906 
1907 	if (F2FS_OPTION(sbi).compress_chksum)
1908 		seq_puts(seq, ",compress_chksum");
1909 
1910 	if (F2FS_OPTION(sbi).compress_mode == COMPR_MODE_FS)
1911 		seq_printf(seq, ",compress_mode=%s", "fs");
1912 	else if (F2FS_OPTION(sbi).compress_mode == COMPR_MODE_USER)
1913 		seq_printf(seq, ",compress_mode=%s", "user");
1914 
1915 	if (test_opt(sbi, COMPRESS_CACHE))
1916 		seq_puts(seq, ",compress_cache");
1917 }
1918 #endif
1919 
1920 static int f2fs_show_options(struct seq_file *seq, struct dentry *root)
1921 {
1922 	struct f2fs_sb_info *sbi = F2FS_SB(root->d_sb);
1923 
1924 	if (F2FS_OPTION(sbi).bggc_mode == BGGC_MODE_SYNC)
1925 		seq_printf(seq, ",background_gc=%s", "sync");
1926 	else if (F2FS_OPTION(sbi).bggc_mode == BGGC_MODE_ON)
1927 		seq_printf(seq, ",background_gc=%s", "on");
1928 	else if (F2FS_OPTION(sbi).bggc_mode == BGGC_MODE_OFF)
1929 		seq_printf(seq, ",background_gc=%s", "off");
1930 
1931 	if (test_opt(sbi, GC_MERGE))
1932 		seq_puts(seq, ",gc_merge");
1933 	else
1934 		seq_puts(seq, ",nogc_merge");
1935 
1936 	if (test_opt(sbi, DISABLE_ROLL_FORWARD))
1937 		seq_puts(seq, ",disable_roll_forward");
1938 	if (test_opt(sbi, NORECOVERY))
1939 		seq_puts(seq, ",norecovery");
1940 	if (test_opt(sbi, DISCARD)) {
1941 		seq_puts(seq, ",discard");
1942 		if (F2FS_OPTION(sbi).discard_unit == DISCARD_UNIT_BLOCK)
1943 			seq_printf(seq, ",discard_unit=%s", "block");
1944 		else if (F2FS_OPTION(sbi).discard_unit == DISCARD_UNIT_SEGMENT)
1945 			seq_printf(seq, ",discard_unit=%s", "segment");
1946 		else if (F2FS_OPTION(sbi).discard_unit == DISCARD_UNIT_SECTION)
1947 			seq_printf(seq, ",discard_unit=%s", "section");
1948 	} else {
1949 		seq_puts(seq, ",nodiscard");
1950 	}
1951 	if (test_opt(sbi, NOHEAP))
1952 		seq_puts(seq, ",no_heap");
1953 	else
1954 		seq_puts(seq, ",heap");
1955 #ifdef CONFIG_F2FS_FS_XATTR
1956 	if (test_opt(sbi, XATTR_USER))
1957 		seq_puts(seq, ",user_xattr");
1958 	else
1959 		seq_puts(seq, ",nouser_xattr");
1960 	if (test_opt(sbi, INLINE_XATTR))
1961 		seq_puts(seq, ",inline_xattr");
1962 	else
1963 		seq_puts(seq, ",noinline_xattr");
1964 	if (test_opt(sbi, INLINE_XATTR_SIZE))
1965 		seq_printf(seq, ",inline_xattr_size=%u",
1966 					F2FS_OPTION(sbi).inline_xattr_size);
1967 #endif
1968 #ifdef CONFIG_F2FS_FS_POSIX_ACL
1969 	if (test_opt(sbi, POSIX_ACL))
1970 		seq_puts(seq, ",acl");
1971 	else
1972 		seq_puts(seq, ",noacl");
1973 #endif
1974 	if (test_opt(sbi, DISABLE_EXT_IDENTIFY))
1975 		seq_puts(seq, ",disable_ext_identify");
1976 	if (test_opt(sbi, INLINE_DATA))
1977 		seq_puts(seq, ",inline_data");
1978 	else
1979 		seq_puts(seq, ",noinline_data");
1980 	if (test_opt(sbi, INLINE_DENTRY))
1981 		seq_puts(seq, ",inline_dentry");
1982 	else
1983 		seq_puts(seq, ",noinline_dentry");
1984 	if (test_opt(sbi, FLUSH_MERGE))
1985 		seq_puts(seq, ",flush_merge");
1986 	else
1987 		seq_puts(seq, ",noflush_merge");
1988 	if (test_opt(sbi, NOBARRIER))
1989 		seq_puts(seq, ",nobarrier");
1990 	else
1991 		seq_puts(seq, ",barrier");
1992 	if (test_opt(sbi, FASTBOOT))
1993 		seq_puts(seq, ",fastboot");
1994 	if (test_opt(sbi, READ_EXTENT_CACHE))
1995 		seq_puts(seq, ",extent_cache");
1996 	else
1997 		seq_puts(seq, ",noextent_cache");
1998 	if (test_opt(sbi, AGE_EXTENT_CACHE))
1999 		seq_puts(seq, ",age_extent_cache");
2000 	if (test_opt(sbi, DATA_FLUSH))
2001 		seq_puts(seq, ",data_flush");
2002 
2003 	seq_puts(seq, ",mode=");
2004 	if (F2FS_OPTION(sbi).fs_mode == FS_MODE_ADAPTIVE)
2005 		seq_puts(seq, "adaptive");
2006 	else if (F2FS_OPTION(sbi).fs_mode == FS_MODE_LFS)
2007 		seq_puts(seq, "lfs");
2008 	else if (F2FS_OPTION(sbi).fs_mode == FS_MODE_FRAGMENT_SEG)
2009 		seq_puts(seq, "fragment:segment");
2010 	else if (F2FS_OPTION(sbi).fs_mode == FS_MODE_FRAGMENT_BLK)
2011 		seq_puts(seq, "fragment:block");
2012 	seq_printf(seq, ",active_logs=%u", F2FS_OPTION(sbi).active_logs);
2013 	if (test_opt(sbi, RESERVE_ROOT))
2014 		seq_printf(seq, ",reserve_root=%u,resuid=%u,resgid=%u",
2015 				F2FS_OPTION(sbi).root_reserved_blocks,
2016 				from_kuid_munged(&init_user_ns,
2017 					F2FS_OPTION(sbi).s_resuid),
2018 				from_kgid_munged(&init_user_ns,
2019 					F2FS_OPTION(sbi).s_resgid));
2020 	if (F2FS_IO_SIZE_BITS(sbi))
2021 		seq_printf(seq, ",io_bits=%u",
2022 				F2FS_OPTION(sbi).write_io_size_bits);
2023 #ifdef CONFIG_F2FS_FAULT_INJECTION
2024 	if (test_opt(sbi, FAULT_INJECTION)) {
2025 		seq_printf(seq, ",fault_injection=%u",
2026 				F2FS_OPTION(sbi).fault_info.inject_rate);
2027 		seq_printf(seq, ",fault_type=%u",
2028 				F2FS_OPTION(sbi).fault_info.inject_type);
2029 	}
2030 #endif
2031 #ifdef CONFIG_QUOTA
2032 	if (test_opt(sbi, QUOTA))
2033 		seq_puts(seq, ",quota");
2034 	if (test_opt(sbi, USRQUOTA))
2035 		seq_puts(seq, ",usrquota");
2036 	if (test_opt(sbi, GRPQUOTA))
2037 		seq_puts(seq, ",grpquota");
2038 	if (test_opt(sbi, PRJQUOTA))
2039 		seq_puts(seq, ",prjquota");
2040 #endif
2041 	f2fs_show_quota_options(seq, sbi->sb);
2042 
2043 	fscrypt_show_test_dummy_encryption(seq, ',', sbi->sb);
2044 
2045 	if (sbi->sb->s_flags & SB_INLINECRYPT)
2046 		seq_puts(seq, ",inlinecrypt");
2047 
2048 	if (F2FS_OPTION(sbi).alloc_mode == ALLOC_MODE_DEFAULT)
2049 		seq_printf(seq, ",alloc_mode=%s", "default");
2050 	else if (F2FS_OPTION(sbi).alloc_mode == ALLOC_MODE_REUSE)
2051 		seq_printf(seq, ",alloc_mode=%s", "reuse");
2052 
2053 	if (test_opt(sbi, DISABLE_CHECKPOINT))
2054 		seq_printf(seq, ",checkpoint=disable:%u",
2055 				F2FS_OPTION(sbi).unusable_cap);
2056 	if (test_opt(sbi, MERGE_CHECKPOINT))
2057 		seq_puts(seq, ",checkpoint_merge");
2058 	else
2059 		seq_puts(seq, ",nocheckpoint_merge");
2060 	if (F2FS_OPTION(sbi).fsync_mode == FSYNC_MODE_POSIX)
2061 		seq_printf(seq, ",fsync_mode=%s", "posix");
2062 	else if (F2FS_OPTION(sbi).fsync_mode == FSYNC_MODE_STRICT)
2063 		seq_printf(seq, ",fsync_mode=%s", "strict");
2064 	else if (F2FS_OPTION(sbi).fsync_mode == FSYNC_MODE_NOBARRIER)
2065 		seq_printf(seq, ",fsync_mode=%s", "nobarrier");
2066 
2067 #ifdef CONFIG_F2FS_FS_COMPRESSION
2068 	f2fs_show_compress_options(seq, sbi->sb);
2069 #endif
2070 
2071 	if (test_opt(sbi, ATGC))
2072 		seq_puts(seq, ",atgc");
2073 
2074 	if (F2FS_OPTION(sbi).memory_mode == MEMORY_MODE_NORMAL)
2075 		seq_printf(seq, ",memory=%s", "normal");
2076 	else if (F2FS_OPTION(sbi).memory_mode == MEMORY_MODE_LOW)
2077 		seq_printf(seq, ",memory=%s", "low");
2078 
2079 	if (F2FS_OPTION(sbi).errors == MOUNT_ERRORS_READONLY)
2080 		seq_printf(seq, ",errors=%s", "remount-ro");
2081 	else if (F2FS_OPTION(sbi).errors == MOUNT_ERRORS_CONTINUE)
2082 		seq_printf(seq, ",errors=%s", "continue");
2083 	else if (F2FS_OPTION(sbi).errors == MOUNT_ERRORS_PANIC)
2084 		seq_printf(seq, ",errors=%s", "panic");
2085 
2086 	return 0;
2087 }
2088 
2089 static void default_options(struct f2fs_sb_info *sbi)
2090 {
2091 	/* init some FS parameters */
2092 	if (f2fs_sb_has_readonly(sbi))
2093 		F2FS_OPTION(sbi).active_logs = NR_CURSEG_RO_TYPE;
2094 	else
2095 		F2FS_OPTION(sbi).active_logs = NR_CURSEG_PERSIST_TYPE;
2096 
2097 	F2FS_OPTION(sbi).inline_xattr_size = DEFAULT_INLINE_XATTR_ADDRS;
2098 	if (le32_to_cpu(F2FS_RAW_SUPER(sbi)->segment_count_main) <=
2099 							SMALL_VOLUME_SEGMENTS)
2100 		F2FS_OPTION(sbi).alloc_mode = ALLOC_MODE_REUSE;
2101 	else
2102 		F2FS_OPTION(sbi).alloc_mode = ALLOC_MODE_DEFAULT;
2103 	F2FS_OPTION(sbi).fsync_mode = FSYNC_MODE_POSIX;
2104 	F2FS_OPTION(sbi).s_resuid = make_kuid(&init_user_ns, F2FS_DEF_RESUID);
2105 	F2FS_OPTION(sbi).s_resgid = make_kgid(&init_user_ns, F2FS_DEF_RESGID);
2106 	if (f2fs_sb_has_compression(sbi)) {
2107 		F2FS_OPTION(sbi).compress_algorithm = COMPRESS_LZ4;
2108 		F2FS_OPTION(sbi).compress_log_size = MIN_COMPRESS_LOG_SIZE;
2109 		F2FS_OPTION(sbi).compress_ext_cnt = 0;
2110 		F2FS_OPTION(sbi).compress_mode = COMPR_MODE_FS;
2111 	}
2112 	F2FS_OPTION(sbi).bggc_mode = BGGC_MODE_ON;
2113 	F2FS_OPTION(sbi).memory_mode = MEMORY_MODE_NORMAL;
2114 	F2FS_OPTION(sbi).errors = MOUNT_ERRORS_CONTINUE;
2115 
2116 	sbi->sb->s_flags &= ~SB_INLINECRYPT;
2117 
2118 	set_opt(sbi, INLINE_XATTR);
2119 	set_opt(sbi, INLINE_DATA);
2120 	set_opt(sbi, INLINE_DENTRY);
2121 	set_opt(sbi, READ_EXTENT_CACHE);
2122 	set_opt(sbi, NOHEAP);
2123 	clear_opt(sbi, DISABLE_CHECKPOINT);
2124 	set_opt(sbi, MERGE_CHECKPOINT);
2125 	F2FS_OPTION(sbi).unusable_cap = 0;
2126 	sbi->sb->s_flags |= SB_LAZYTIME;
2127 	if (!f2fs_is_readonly(sbi))
2128 		set_opt(sbi, FLUSH_MERGE);
2129 	if (f2fs_hw_support_discard(sbi) || f2fs_hw_should_discard(sbi))
2130 		set_opt(sbi, DISCARD);
2131 	if (f2fs_sb_has_blkzoned(sbi)) {
2132 		F2FS_OPTION(sbi).fs_mode = FS_MODE_LFS;
2133 		F2FS_OPTION(sbi).discard_unit = DISCARD_UNIT_SECTION;
2134 	} else {
2135 		F2FS_OPTION(sbi).fs_mode = FS_MODE_ADAPTIVE;
2136 		F2FS_OPTION(sbi).discard_unit = DISCARD_UNIT_BLOCK;
2137 	}
2138 
2139 #ifdef CONFIG_F2FS_FS_XATTR
2140 	set_opt(sbi, XATTR_USER);
2141 #endif
2142 #ifdef CONFIG_F2FS_FS_POSIX_ACL
2143 	set_opt(sbi, POSIX_ACL);
2144 #endif
2145 
2146 	f2fs_build_fault_attr(sbi, 0, 0);
2147 }
2148 
2149 #ifdef CONFIG_QUOTA
2150 static int f2fs_enable_quotas(struct super_block *sb);
2151 #endif
2152 
2153 static int f2fs_disable_checkpoint(struct f2fs_sb_info *sbi)
2154 {
2155 	unsigned int s_flags = sbi->sb->s_flags;
2156 	struct cp_control cpc;
2157 	unsigned int gc_mode = sbi->gc_mode;
2158 	int err = 0;
2159 	int ret;
2160 	block_t unusable;
2161 
2162 	if (s_flags & SB_RDONLY) {
2163 		f2fs_err(sbi, "checkpoint=disable on readonly fs");
2164 		return -EINVAL;
2165 	}
2166 	sbi->sb->s_flags |= SB_ACTIVE;
2167 
2168 	/* check if we need more GC first */
2169 	unusable = f2fs_get_unusable_blocks(sbi);
2170 	if (!f2fs_disable_cp_again(sbi, unusable))
2171 		goto skip_gc;
2172 
2173 	f2fs_update_time(sbi, DISABLE_TIME);
2174 
2175 	sbi->gc_mode = GC_URGENT_HIGH;
2176 
2177 	while (!f2fs_time_over(sbi, DISABLE_TIME)) {
2178 		struct f2fs_gc_control gc_control = {
2179 			.victim_segno = NULL_SEGNO,
2180 			.init_gc_type = FG_GC,
2181 			.should_migrate_blocks = false,
2182 			.err_gc_skipped = true,
2183 			.nr_free_secs = 1 };
2184 
2185 		f2fs_down_write(&sbi->gc_lock);
2186 		err = f2fs_gc(sbi, &gc_control);
2187 		if (err == -ENODATA) {
2188 			err = 0;
2189 			break;
2190 		}
2191 		if (err && err != -EAGAIN)
2192 			break;
2193 	}
2194 
2195 	ret = sync_filesystem(sbi->sb);
2196 	if (ret || err) {
2197 		err = ret ? ret : err;
2198 		goto restore_flag;
2199 	}
2200 
2201 	unusable = f2fs_get_unusable_blocks(sbi);
2202 	if (f2fs_disable_cp_again(sbi, unusable)) {
2203 		err = -EAGAIN;
2204 		goto restore_flag;
2205 	}
2206 
2207 skip_gc:
2208 	f2fs_down_write(&sbi->gc_lock);
2209 	cpc.reason = CP_PAUSE;
2210 	set_sbi_flag(sbi, SBI_CP_DISABLED);
2211 	err = f2fs_write_checkpoint(sbi, &cpc);
2212 	if (err)
2213 		goto out_unlock;
2214 
2215 	spin_lock(&sbi->stat_lock);
2216 	sbi->unusable_block_count = unusable;
2217 	spin_unlock(&sbi->stat_lock);
2218 
2219 out_unlock:
2220 	f2fs_up_write(&sbi->gc_lock);
2221 restore_flag:
2222 	sbi->gc_mode = gc_mode;
2223 	sbi->sb->s_flags = s_flags;	/* Restore SB_RDONLY status */
2224 	return err;
2225 }
2226 
2227 static void f2fs_enable_checkpoint(struct f2fs_sb_info *sbi)
2228 {
2229 	int retry = DEFAULT_RETRY_IO_COUNT;
2230 
2231 	/* we should flush all the data to keep data consistency */
2232 	do {
2233 		sync_inodes_sb(sbi->sb);
2234 		f2fs_io_schedule_timeout(DEFAULT_IO_TIMEOUT);
2235 	} while (get_pages(sbi, F2FS_DIRTY_DATA) && retry--);
2236 
2237 	if (unlikely(retry < 0))
2238 		f2fs_warn(sbi, "checkpoint=enable has some unwritten data.");
2239 
2240 	f2fs_down_write(&sbi->gc_lock);
2241 	f2fs_dirty_to_prefree(sbi);
2242 
2243 	clear_sbi_flag(sbi, SBI_CP_DISABLED);
2244 	set_sbi_flag(sbi, SBI_IS_DIRTY);
2245 	f2fs_up_write(&sbi->gc_lock);
2246 
2247 	f2fs_sync_fs(sbi->sb, 1);
2248 
2249 	/* Let's ensure there's no pending checkpoint anymore */
2250 	f2fs_flush_ckpt_thread(sbi);
2251 }
2252 
2253 static int f2fs_remount(struct super_block *sb, int *flags, char *data)
2254 {
2255 	struct f2fs_sb_info *sbi = F2FS_SB(sb);
2256 	struct f2fs_mount_info org_mount_opt;
2257 	unsigned long old_sb_flags;
2258 	int err;
2259 	bool need_restart_gc = false, need_stop_gc = false;
2260 	bool need_restart_ckpt = false, need_stop_ckpt = false;
2261 	bool need_restart_flush = false, need_stop_flush = false;
2262 	bool need_restart_discard = false, need_stop_discard = false;
2263 	bool no_read_extent_cache = !test_opt(sbi, READ_EXTENT_CACHE);
2264 	bool no_age_extent_cache = !test_opt(sbi, AGE_EXTENT_CACHE);
2265 	bool enable_checkpoint = !test_opt(sbi, DISABLE_CHECKPOINT);
2266 	bool no_io_align = !F2FS_IO_ALIGNED(sbi);
2267 	bool no_atgc = !test_opt(sbi, ATGC);
2268 	bool no_discard = !test_opt(sbi, DISCARD);
2269 	bool no_compress_cache = !test_opt(sbi, COMPRESS_CACHE);
2270 	bool block_unit_discard = f2fs_block_unit_discard(sbi);
2271 #ifdef CONFIG_QUOTA
2272 	int i, j;
2273 #endif
2274 
2275 	/*
2276 	 * Save the old mount options in case we
2277 	 * need to restore them.
2278 	 */
2279 	org_mount_opt = sbi->mount_opt;
2280 	old_sb_flags = sb->s_flags;
2281 
2282 #ifdef CONFIG_QUOTA
2283 	org_mount_opt.s_jquota_fmt = F2FS_OPTION(sbi).s_jquota_fmt;
2284 	for (i = 0; i < MAXQUOTAS; i++) {
2285 		if (F2FS_OPTION(sbi).s_qf_names[i]) {
2286 			org_mount_opt.s_qf_names[i] =
2287 				kstrdup(F2FS_OPTION(sbi).s_qf_names[i],
2288 				GFP_KERNEL);
2289 			if (!org_mount_opt.s_qf_names[i]) {
2290 				for (j = 0; j < i; j++)
2291 					kfree(org_mount_opt.s_qf_names[j]);
2292 				return -ENOMEM;
2293 			}
2294 		} else {
2295 			org_mount_opt.s_qf_names[i] = NULL;
2296 		}
2297 	}
2298 #endif
2299 
2300 	/* recover superblocks we couldn't write due to previous RO mount */
2301 	if (!(*flags & SB_RDONLY) && is_sbi_flag_set(sbi, SBI_NEED_SB_WRITE)) {
2302 		err = f2fs_commit_super(sbi, false);
2303 		f2fs_info(sbi, "Try to recover all the superblocks, ret: %d",
2304 			  err);
2305 		if (!err)
2306 			clear_sbi_flag(sbi, SBI_NEED_SB_WRITE);
2307 	}
2308 
2309 	default_options(sbi);
2310 
2311 	/* parse mount options */
2312 	err = parse_options(sb, data, true);
2313 	if (err)
2314 		goto restore_opts;
2315 
2316 	/* flush outstanding errors before changing fs state */
2317 	flush_work(&sbi->s_error_work);
2318 
2319 	/*
2320 	 * Previous and new state of filesystem is RO,
2321 	 * so skip checking GC and FLUSH_MERGE conditions.
2322 	 */
2323 	if (f2fs_readonly(sb) && (*flags & SB_RDONLY))
2324 		goto skip;
2325 
2326 	if (f2fs_dev_is_readonly(sbi) && !(*flags & SB_RDONLY)) {
2327 		err = -EROFS;
2328 		goto restore_opts;
2329 	}
2330 
2331 #ifdef CONFIG_QUOTA
2332 	if (!f2fs_readonly(sb) && (*flags & SB_RDONLY)) {
2333 		err = dquot_suspend(sb, -1);
2334 		if (err < 0)
2335 			goto restore_opts;
2336 	} else if (f2fs_readonly(sb) && !(*flags & SB_RDONLY)) {
2337 		/* dquot_resume needs RW */
2338 		sb->s_flags &= ~SB_RDONLY;
2339 		if (sb_any_quota_suspended(sb)) {
2340 			dquot_resume(sb, -1);
2341 		} else if (f2fs_sb_has_quota_ino(sbi)) {
2342 			err = f2fs_enable_quotas(sb);
2343 			if (err)
2344 				goto restore_opts;
2345 		}
2346 	}
2347 #endif
2348 	if (f2fs_lfs_mode(sbi) && !IS_F2FS_IPU_DISABLE(sbi)) {
2349 		err = -EINVAL;
2350 		f2fs_warn(sbi, "LFS is not compatible with IPU");
2351 		goto restore_opts;
2352 	}
2353 
2354 	/* disallow enable atgc dynamically */
2355 	if (no_atgc == !!test_opt(sbi, ATGC)) {
2356 		err = -EINVAL;
2357 		f2fs_warn(sbi, "switch atgc option is not allowed");
2358 		goto restore_opts;
2359 	}
2360 
2361 	/* disallow enable/disable extent_cache dynamically */
2362 	if (no_read_extent_cache == !!test_opt(sbi, READ_EXTENT_CACHE)) {
2363 		err = -EINVAL;
2364 		f2fs_warn(sbi, "switch extent_cache option is not allowed");
2365 		goto restore_opts;
2366 	}
2367 	/* disallow enable/disable age extent_cache dynamically */
2368 	if (no_age_extent_cache == !!test_opt(sbi, AGE_EXTENT_CACHE)) {
2369 		err = -EINVAL;
2370 		f2fs_warn(sbi, "switch age_extent_cache option is not allowed");
2371 		goto restore_opts;
2372 	}
2373 
2374 	if (no_io_align == !!F2FS_IO_ALIGNED(sbi)) {
2375 		err = -EINVAL;
2376 		f2fs_warn(sbi, "switch io_bits option is not allowed");
2377 		goto restore_opts;
2378 	}
2379 
2380 	if (no_compress_cache == !!test_opt(sbi, COMPRESS_CACHE)) {
2381 		err = -EINVAL;
2382 		f2fs_warn(sbi, "switch compress_cache option is not allowed");
2383 		goto restore_opts;
2384 	}
2385 
2386 	if (block_unit_discard != f2fs_block_unit_discard(sbi)) {
2387 		err = -EINVAL;
2388 		f2fs_warn(sbi, "switch discard_unit option is not allowed");
2389 		goto restore_opts;
2390 	}
2391 
2392 	if ((*flags & SB_RDONLY) && test_opt(sbi, DISABLE_CHECKPOINT)) {
2393 		err = -EINVAL;
2394 		f2fs_warn(sbi, "disabling checkpoint not compatible with read-only");
2395 		goto restore_opts;
2396 	}
2397 
2398 	/*
2399 	 * We stop the GC thread if FS is mounted as RO
2400 	 * or if background_gc = off is passed in mount
2401 	 * option. Also sync the filesystem.
2402 	 */
2403 	if ((*flags & SB_RDONLY) ||
2404 			(F2FS_OPTION(sbi).bggc_mode == BGGC_MODE_OFF &&
2405 			!test_opt(sbi, GC_MERGE))) {
2406 		if (sbi->gc_thread) {
2407 			f2fs_stop_gc_thread(sbi);
2408 			need_restart_gc = true;
2409 		}
2410 	} else if (!sbi->gc_thread) {
2411 		err = f2fs_start_gc_thread(sbi);
2412 		if (err)
2413 			goto restore_opts;
2414 		need_stop_gc = true;
2415 	}
2416 
2417 	if (*flags & SB_RDONLY) {
2418 		sync_inodes_sb(sb);
2419 
2420 		set_sbi_flag(sbi, SBI_IS_DIRTY);
2421 		set_sbi_flag(sbi, SBI_IS_CLOSE);
2422 		f2fs_sync_fs(sb, 1);
2423 		clear_sbi_flag(sbi, SBI_IS_CLOSE);
2424 	}
2425 
2426 	if ((*flags & SB_RDONLY) || test_opt(sbi, DISABLE_CHECKPOINT) ||
2427 			!test_opt(sbi, MERGE_CHECKPOINT)) {
2428 		f2fs_stop_ckpt_thread(sbi);
2429 		need_restart_ckpt = true;
2430 	} else {
2431 		/* Flush if the prevous checkpoint, if exists. */
2432 		f2fs_flush_ckpt_thread(sbi);
2433 
2434 		err = f2fs_start_ckpt_thread(sbi);
2435 		if (err) {
2436 			f2fs_err(sbi,
2437 			    "Failed to start F2FS issue_checkpoint_thread (%d)",
2438 			    err);
2439 			goto restore_gc;
2440 		}
2441 		need_stop_ckpt = true;
2442 	}
2443 
2444 	/*
2445 	 * We stop issue flush thread if FS is mounted as RO
2446 	 * or if flush_merge is not passed in mount option.
2447 	 */
2448 	if ((*flags & SB_RDONLY) || !test_opt(sbi, FLUSH_MERGE)) {
2449 		clear_opt(sbi, FLUSH_MERGE);
2450 		f2fs_destroy_flush_cmd_control(sbi, false);
2451 		need_restart_flush = true;
2452 	} else {
2453 		err = f2fs_create_flush_cmd_control(sbi);
2454 		if (err)
2455 			goto restore_ckpt;
2456 		need_stop_flush = true;
2457 	}
2458 
2459 	if (no_discard == !!test_opt(sbi, DISCARD)) {
2460 		if (test_opt(sbi, DISCARD)) {
2461 			err = f2fs_start_discard_thread(sbi);
2462 			if (err)
2463 				goto restore_flush;
2464 			need_stop_discard = true;
2465 		} else {
2466 			f2fs_stop_discard_thread(sbi);
2467 			f2fs_issue_discard_timeout(sbi);
2468 			need_restart_discard = true;
2469 		}
2470 	}
2471 
2472 	if (enable_checkpoint == !!test_opt(sbi, DISABLE_CHECKPOINT)) {
2473 		if (test_opt(sbi, DISABLE_CHECKPOINT)) {
2474 			err = f2fs_disable_checkpoint(sbi);
2475 			if (err)
2476 				goto restore_discard;
2477 		} else {
2478 			f2fs_enable_checkpoint(sbi);
2479 		}
2480 	}
2481 
2482 skip:
2483 #ifdef CONFIG_QUOTA
2484 	/* Release old quota file names */
2485 	for (i = 0; i < MAXQUOTAS; i++)
2486 		kfree(org_mount_opt.s_qf_names[i]);
2487 #endif
2488 	/* Update the POSIXACL Flag */
2489 	sb->s_flags = (sb->s_flags & ~SB_POSIXACL) |
2490 		(test_opt(sbi, POSIX_ACL) ? SB_POSIXACL : 0);
2491 
2492 	limit_reserve_root(sbi);
2493 	adjust_unusable_cap_perc(sbi);
2494 	*flags = (*flags & ~SB_LAZYTIME) | (sb->s_flags & SB_LAZYTIME);
2495 	return 0;
2496 restore_discard:
2497 	if (need_restart_discard) {
2498 		if (f2fs_start_discard_thread(sbi))
2499 			f2fs_warn(sbi, "discard has been stopped");
2500 	} else if (need_stop_discard) {
2501 		f2fs_stop_discard_thread(sbi);
2502 	}
2503 restore_flush:
2504 	if (need_restart_flush) {
2505 		if (f2fs_create_flush_cmd_control(sbi))
2506 			f2fs_warn(sbi, "background flush thread has stopped");
2507 	} else if (need_stop_flush) {
2508 		clear_opt(sbi, FLUSH_MERGE);
2509 		f2fs_destroy_flush_cmd_control(sbi, false);
2510 	}
2511 restore_ckpt:
2512 	if (need_restart_ckpt) {
2513 		if (f2fs_start_ckpt_thread(sbi))
2514 			f2fs_warn(sbi, "background ckpt thread has stopped");
2515 	} else if (need_stop_ckpt) {
2516 		f2fs_stop_ckpt_thread(sbi);
2517 	}
2518 restore_gc:
2519 	if (need_restart_gc) {
2520 		if (f2fs_start_gc_thread(sbi))
2521 			f2fs_warn(sbi, "background gc thread has stopped");
2522 	} else if (need_stop_gc) {
2523 		f2fs_stop_gc_thread(sbi);
2524 	}
2525 restore_opts:
2526 #ifdef CONFIG_QUOTA
2527 	F2FS_OPTION(sbi).s_jquota_fmt = org_mount_opt.s_jquota_fmt;
2528 	for (i = 0; i < MAXQUOTAS; i++) {
2529 		kfree(F2FS_OPTION(sbi).s_qf_names[i]);
2530 		F2FS_OPTION(sbi).s_qf_names[i] = org_mount_opt.s_qf_names[i];
2531 	}
2532 #endif
2533 	sbi->mount_opt = org_mount_opt;
2534 	sb->s_flags = old_sb_flags;
2535 	return err;
2536 }
2537 
2538 #ifdef CONFIG_QUOTA
2539 static bool f2fs_need_recovery(struct f2fs_sb_info *sbi)
2540 {
2541 	/* need to recovery orphan */
2542 	if (is_set_ckpt_flags(sbi, CP_ORPHAN_PRESENT_FLAG))
2543 		return true;
2544 	/* need to recovery data */
2545 	if (test_opt(sbi, DISABLE_ROLL_FORWARD))
2546 		return false;
2547 	if (test_opt(sbi, NORECOVERY))
2548 		return false;
2549 	return !is_set_ckpt_flags(sbi, CP_UMOUNT_FLAG);
2550 }
2551 
2552 static bool f2fs_recover_quota_begin(struct f2fs_sb_info *sbi)
2553 {
2554 	bool readonly = f2fs_readonly(sbi->sb);
2555 
2556 	if (!f2fs_need_recovery(sbi))
2557 		return false;
2558 
2559 	/* it doesn't need to check f2fs_sb_has_readonly() */
2560 	if (f2fs_hw_is_readonly(sbi))
2561 		return false;
2562 
2563 	if (readonly) {
2564 		sbi->sb->s_flags &= ~SB_RDONLY;
2565 		set_sbi_flag(sbi, SBI_IS_WRITABLE);
2566 	}
2567 
2568 	/*
2569 	 * Turn on quotas which were not enabled for read-only mounts if
2570 	 * filesystem has quota feature, so that they are updated correctly.
2571 	 */
2572 	return f2fs_enable_quota_files(sbi, readonly);
2573 }
2574 
2575 static void f2fs_recover_quota_end(struct f2fs_sb_info *sbi,
2576 						bool quota_enabled)
2577 {
2578 	if (quota_enabled)
2579 		f2fs_quota_off_umount(sbi->sb);
2580 
2581 	if (is_sbi_flag_set(sbi, SBI_IS_WRITABLE)) {
2582 		clear_sbi_flag(sbi, SBI_IS_WRITABLE);
2583 		sbi->sb->s_flags |= SB_RDONLY;
2584 	}
2585 }
2586 
2587 /* Read data from quotafile */
2588 static ssize_t f2fs_quota_read(struct super_block *sb, int type, char *data,
2589 			       size_t len, loff_t off)
2590 {
2591 	struct inode *inode = sb_dqopt(sb)->files[type];
2592 	struct address_space *mapping = inode->i_mapping;
2593 	block_t blkidx = F2FS_BYTES_TO_BLK(off);
2594 	int offset = off & (sb->s_blocksize - 1);
2595 	int tocopy;
2596 	size_t toread;
2597 	loff_t i_size = i_size_read(inode);
2598 	struct page *page;
2599 
2600 	if (off > i_size)
2601 		return 0;
2602 
2603 	if (off + len > i_size)
2604 		len = i_size - off;
2605 	toread = len;
2606 	while (toread > 0) {
2607 		tocopy = min_t(unsigned long, sb->s_blocksize - offset, toread);
2608 repeat:
2609 		page = read_cache_page_gfp(mapping, blkidx, GFP_NOFS);
2610 		if (IS_ERR(page)) {
2611 			if (PTR_ERR(page) == -ENOMEM) {
2612 				memalloc_retry_wait(GFP_NOFS);
2613 				goto repeat;
2614 			}
2615 			set_sbi_flag(F2FS_SB(sb), SBI_QUOTA_NEED_REPAIR);
2616 			return PTR_ERR(page);
2617 		}
2618 
2619 		lock_page(page);
2620 
2621 		if (unlikely(page->mapping != mapping)) {
2622 			f2fs_put_page(page, 1);
2623 			goto repeat;
2624 		}
2625 		if (unlikely(!PageUptodate(page))) {
2626 			f2fs_put_page(page, 1);
2627 			set_sbi_flag(F2FS_SB(sb), SBI_QUOTA_NEED_REPAIR);
2628 			return -EIO;
2629 		}
2630 
2631 		memcpy_from_page(data, page, offset, tocopy);
2632 		f2fs_put_page(page, 1);
2633 
2634 		offset = 0;
2635 		toread -= tocopy;
2636 		data += tocopy;
2637 		blkidx++;
2638 	}
2639 	return len;
2640 }
2641 
2642 /* Write to quotafile */
2643 static ssize_t f2fs_quota_write(struct super_block *sb, int type,
2644 				const char *data, size_t len, loff_t off)
2645 {
2646 	struct inode *inode = sb_dqopt(sb)->files[type];
2647 	struct address_space *mapping = inode->i_mapping;
2648 	const struct address_space_operations *a_ops = mapping->a_ops;
2649 	int offset = off & (sb->s_blocksize - 1);
2650 	size_t towrite = len;
2651 	struct page *page;
2652 	void *fsdata = NULL;
2653 	int err = 0;
2654 	int tocopy;
2655 
2656 	while (towrite > 0) {
2657 		tocopy = min_t(unsigned long, sb->s_blocksize - offset,
2658 								towrite);
2659 retry:
2660 		err = a_ops->write_begin(NULL, mapping, off, tocopy,
2661 							&page, &fsdata);
2662 		if (unlikely(err)) {
2663 			if (err == -ENOMEM) {
2664 				f2fs_io_schedule_timeout(DEFAULT_IO_TIMEOUT);
2665 				goto retry;
2666 			}
2667 			set_sbi_flag(F2FS_SB(sb), SBI_QUOTA_NEED_REPAIR);
2668 			break;
2669 		}
2670 
2671 		memcpy_to_page(page, offset, data, tocopy);
2672 
2673 		a_ops->write_end(NULL, mapping, off, tocopy, tocopy,
2674 						page, fsdata);
2675 		offset = 0;
2676 		towrite -= tocopy;
2677 		off += tocopy;
2678 		data += tocopy;
2679 		cond_resched();
2680 	}
2681 
2682 	if (len == towrite)
2683 		return err;
2684 	inode->i_mtime = inode->i_ctime = current_time(inode);
2685 	f2fs_mark_inode_dirty_sync(inode, false);
2686 	return len - towrite;
2687 }
2688 
2689 int f2fs_dquot_initialize(struct inode *inode)
2690 {
2691 	if (time_to_inject(F2FS_I_SB(inode), FAULT_DQUOT_INIT))
2692 		return -ESRCH;
2693 
2694 	return dquot_initialize(inode);
2695 }
2696 
2697 static struct dquot **f2fs_get_dquots(struct inode *inode)
2698 {
2699 	return F2FS_I(inode)->i_dquot;
2700 }
2701 
2702 static qsize_t *f2fs_get_reserved_space(struct inode *inode)
2703 {
2704 	return &F2FS_I(inode)->i_reserved_quota;
2705 }
2706 
2707 static int f2fs_quota_on_mount(struct f2fs_sb_info *sbi, int type)
2708 {
2709 	if (is_set_ckpt_flags(sbi, CP_QUOTA_NEED_FSCK_FLAG)) {
2710 		f2fs_err(sbi, "quota sysfile may be corrupted, skip loading it");
2711 		return 0;
2712 	}
2713 
2714 	return dquot_quota_on_mount(sbi->sb, F2FS_OPTION(sbi).s_qf_names[type],
2715 					F2FS_OPTION(sbi).s_jquota_fmt, type);
2716 }
2717 
2718 int f2fs_enable_quota_files(struct f2fs_sb_info *sbi, bool rdonly)
2719 {
2720 	int enabled = 0;
2721 	int i, err;
2722 
2723 	if (f2fs_sb_has_quota_ino(sbi) && rdonly) {
2724 		err = f2fs_enable_quotas(sbi->sb);
2725 		if (err) {
2726 			f2fs_err(sbi, "Cannot turn on quota_ino: %d", err);
2727 			return 0;
2728 		}
2729 		return 1;
2730 	}
2731 
2732 	for (i = 0; i < MAXQUOTAS; i++) {
2733 		if (F2FS_OPTION(sbi).s_qf_names[i]) {
2734 			err = f2fs_quota_on_mount(sbi, i);
2735 			if (!err) {
2736 				enabled = 1;
2737 				continue;
2738 			}
2739 			f2fs_err(sbi, "Cannot turn on quotas: %d on %d",
2740 				 err, i);
2741 		}
2742 	}
2743 	return enabled;
2744 }
2745 
2746 static int f2fs_quota_enable(struct super_block *sb, int type, int format_id,
2747 			     unsigned int flags)
2748 {
2749 	struct inode *qf_inode;
2750 	unsigned long qf_inum;
2751 	int err;
2752 
2753 	BUG_ON(!f2fs_sb_has_quota_ino(F2FS_SB(sb)));
2754 
2755 	qf_inum = f2fs_qf_ino(sb, type);
2756 	if (!qf_inum)
2757 		return -EPERM;
2758 
2759 	qf_inode = f2fs_iget(sb, qf_inum);
2760 	if (IS_ERR(qf_inode)) {
2761 		f2fs_err(F2FS_SB(sb), "Bad quota inode %u:%lu", type, qf_inum);
2762 		return PTR_ERR(qf_inode);
2763 	}
2764 
2765 	/* Don't account quota for quota files to avoid recursion */
2766 	qf_inode->i_flags |= S_NOQUOTA;
2767 	err = dquot_load_quota_inode(qf_inode, type, format_id, flags);
2768 	iput(qf_inode);
2769 	return err;
2770 }
2771 
2772 static int f2fs_enable_quotas(struct super_block *sb)
2773 {
2774 	struct f2fs_sb_info *sbi = F2FS_SB(sb);
2775 	int type, err = 0;
2776 	unsigned long qf_inum;
2777 	bool quota_mopt[MAXQUOTAS] = {
2778 		test_opt(sbi, USRQUOTA),
2779 		test_opt(sbi, GRPQUOTA),
2780 		test_opt(sbi, PRJQUOTA),
2781 	};
2782 
2783 	if (is_set_ckpt_flags(F2FS_SB(sb), CP_QUOTA_NEED_FSCK_FLAG)) {
2784 		f2fs_err(sbi, "quota file may be corrupted, skip loading it");
2785 		return 0;
2786 	}
2787 
2788 	sb_dqopt(sb)->flags |= DQUOT_QUOTA_SYS_FILE;
2789 
2790 	for (type = 0; type < MAXQUOTAS; type++) {
2791 		qf_inum = f2fs_qf_ino(sb, type);
2792 		if (qf_inum) {
2793 			err = f2fs_quota_enable(sb, type, QFMT_VFS_V1,
2794 				DQUOT_USAGE_ENABLED |
2795 				(quota_mopt[type] ? DQUOT_LIMITS_ENABLED : 0));
2796 			if (err) {
2797 				f2fs_err(sbi, "Failed to enable quota tracking (type=%d, err=%d). Please run fsck to fix.",
2798 					 type, err);
2799 				for (type--; type >= 0; type--)
2800 					dquot_quota_off(sb, type);
2801 				set_sbi_flag(F2FS_SB(sb),
2802 						SBI_QUOTA_NEED_REPAIR);
2803 				return err;
2804 			}
2805 		}
2806 	}
2807 	return 0;
2808 }
2809 
2810 static int f2fs_quota_sync_file(struct f2fs_sb_info *sbi, int type)
2811 {
2812 	struct quota_info *dqopt = sb_dqopt(sbi->sb);
2813 	struct address_space *mapping = dqopt->files[type]->i_mapping;
2814 	int ret = 0;
2815 
2816 	ret = dquot_writeback_dquots(sbi->sb, type);
2817 	if (ret)
2818 		goto out;
2819 
2820 	ret = filemap_fdatawrite(mapping);
2821 	if (ret)
2822 		goto out;
2823 
2824 	/* if we are using journalled quota */
2825 	if (is_journalled_quota(sbi))
2826 		goto out;
2827 
2828 	ret = filemap_fdatawait(mapping);
2829 
2830 	truncate_inode_pages(&dqopt->files[type]->i_data, 0);
2831 out:
2832 	if (ret)
2833 		set_sbi_flag(sbi, SBI_QUOTA_NEED_REPAIR);
2834 	return ret;
2835 }
2836 
2837 int f2fs_quota_sync(struct super_block *sb, int type)
2838 {
2839 	struct f2fs_sb_info *sbi = F2FS_SB(sb);
2840 	struct quota_info *dqopt = sb_dqopt(sb);
2841 	int cnt;
2842 	int ret = 0;
2843 
2844 	/*
2845 	 * Now when everything is written we can discard the pagecache so
2846 	 * that userspace sees the changes.
2847 	 */
2848 	for (cnt = 0; cnt < MAXQUOTAS; cnt++) {
2849 
2850 		if (type != -1 && cnt != type)
2851 			continue;
2852 
2853 		if (!sb_has_quota_active(sb, cnt))
2854 			continue;
2855 
2856 		if (!f2fs_sb_has_quota_ino(sbi))
2857 			inode_lock(dqopt->files[cnt]);
2858 
2859 		/*
2860 		 * do_quotactl
2861 		 *  f2fs_quota_sync
2862 		 *  f2fs_down_read(quota_sem)
2863 		 *  dquot_writeback_dquots()
2864 		 *  f2fs_dquot_commit
2865 		 *			      block_operation
2866 		 *			      f2fs_down_read(quota_sem)
2867 		 */
2868 		f2fs_lock_op(sbi);
2869 		f2fs_down_read(&sbi->quota_sem);
2870 
2871 		ret = f2fs_quota_sync_file(sbi, cnt);
2872 
2873 		f2fs_up_read(&sbi->quota_sem);
2874 		f2fs_unlock_op(sbi);
2875 
2876 		if (!f2fs_sb_has_quota_ino(sbi))
2877 			inode_unlock(dqopt->files[cnt]);
2878 
2879 		if (ret)
2880 			break;
2881 	}
2882 	return ret;
2883 }
2884 
2885 static int f2fs_quota_on(struct super_block *sb, int type, int format_id,
2886 							const struct path *path)
2887 {
2888 	struct inode *inode;
2889 	int err;
2890 
2891 	/* if quota sysfile exists, deny enabling quota with specific file */
2892 	if (f2fs_sb_has_quota_ino(F2FS_SB(sb))) {
2893 		f2fs_err(F2FS_SB(sb), "quota sysfile already exists");
2894 		return -EBUSY;
2895 	}
2896 
2897 	err = f2fs_quota_sync(sb, type);
2898 	if (err)
2899 		return err;
2900 
2901 	err = dquot_quota_on(sb, type, format_id, path);
2902 	if (err)
2903 		return err;
2904 
2905 	inode = d_inode(path->dentry);
2906 
2907 	inode_lock(inode);
2908 	F2FS_I(inode)->i_flags |= F2FS_NOATIME_FL | F2FS_IMMUTABLE_FL;
2909 	f2fs_set_inode_flags(inode);
2910 	inode_unlock(inode);
2911 	f2fs_mark_inode_dirty_sync(inode, false);
2912 
2913 	return 0;
2914 }
2915 
2916 static int __f2fs_quota_off(struct super_block *sb, int type)
2917 {
2918 	struct inode *inode = sb_dqopt(sb)->files[type];
2919 	int err;
2920 
2921 	if (!inode || !igrab(inode))
2922 		return dquot_quota_off(sb, type);
2923 
2924 	err = f2fs_quota_sync(sb, type);
2925 	if (err)
2926 		goto out_put;
2927 
2928 	err = dquot_quota_off(sb, type);
2929 	if (err || f2fs_sb_has_quota_ino(F2FS_SB(sb)))
2930 		goto out_put;
2931 
2932 	inode_lock(inode);
2933 	F2FS_I(inode)->i_flags &= ~(F2FS_NOATIME_FL | F2FS_IMMUTABLE_FL);
2934 	f2fs_set_inode_flags(inode);
2935 	inode_unlock(inode);
2936 	f2fs_mark_inode_dirty_sync(inode, false);
2937 out_put:
2938 	iput(inode);
2939 	return err;
2940 }
2941 
2942 static int f2fs_quota_off(struct super_block *sb, int type)
2943 {
2944 	struct f2fs_sb_info *sbi = F2FS_SB(sb);
2945 	int err;
2946 
2947 	err = __f2fs_quota_off(sb, type);
2948 
2949 	/*
2950 	 * quotactl can shutdown journalled quota, result in inconsistence
2951 	 * between quota record and fs data by following updates, tag the
2952 	 * flag to let fsck be aware of it.
2953 	 */
2954 	if (is_journalled_quota(sbi))
2955 		set_sbi_flag(sbi, SBI_QUOTA_NEED_REPAIR);
2956 	return err;
2957 }
2958 
2959 void f2fs_quota_off_umount(struct super_block *sb)
2960 {
2961 	int type;
2962 	int err;
2963 
2964 	for (type = 0; type < MAXQUOTAS; type++) {
2965 		err = __f2fs_quota_off(sb, type);
2966 		if (err) {
2967 			int ret = dquot_quota_off(sb, type);
2968 
2969 			f2fs_err(F2FS_SB(sb), "Fail to turn off disk quota (type: %d, err: %d, ret:%d), Please run fsck to fix it.",
2970 				 type, err, ret);
2971 			set_sbi_flag(F2FS_SB(sb), SBI_QUOTA_NEED_REPAIR);
2972 		}
2973 	}
2974 	/*
2975 	 * In case of checkpoint=disable, we must flush quota blocks.
2976 	 * This can cause NULL exception for node_inode in end_io, since
2977 	 * put_super already dropped it.
2978 	 */
2979 	sync_filesystem(sb);
2980 }
2981 
2982 static void f2fs_truncate_quota_inode_pages(struct super_block *sb)
2983 {
2984 	struct quota_info *dqopt = sb_dqopt(sb);
2985 	int type;
2986 
2987 	for (type = 0; type < MAXQUOTAS; type++) {
2988 		if (!dqopt->files[type])
2989 			continue;
2990 		f2fs_inode_synced(dqopt->files[type]);
2991 	}
2992 }
2993 
2994 static int f2fs_dquot_commit(struct dquot *dquot)
2995 {
2996 	struct f2fs_sb_info *sbi = F2FS_SB(dquot->dq_sb);
2997 	int ret;
2998 
2999 	f2fs_down_read_nested(&sbi->quota_sem, SINGLE_DEPTH_NESTING);
3000 	ret = dquot_commit(dquot);
3001 	if (ret < 0)
3002 		set_sbi_flag(sbi, SBI_QUOTA_NEED_REPAIR);
3003 	f2fs_up_read(&sbi->quota_sem);
3004 	return ret;
3005 }
3006 
3007 static int f2fs_dquot_acquire(struct dquot *dquot)
3008 {
3009 	struct f2fs_sb_info *sbi = F2FS_SB(dquot->dq_sb);
3010 	int ret;
3011 
3012 	f2fs_down_read(&sbi->quota_sem);
3013 	ret = dquot_acquire(dquot);
3014 	if (ret < 0)
3015 		set_sbi_flag(sbi, SBI_QUOTA_NEED_REPAIR);
3016 	f2fs_up_read(&sbi->quota_sem);
3017 	return ret;
3018 }
3019 
3020 static int f2fs_dquot_release(struct dquot *dquot)
3021 {
3022 	struct f2fs_sb_info *sbi = F2FS_SB(dquot->dq_sb);
3023 	int ret = dquot_release(dquot);
3024 
3025 	if (ret < 0)
3026 		set_sbi_flag(sbi, SBI_QUOTA_NEED_REPAIR);
3027 	return ret;
3028 }
3029 
3030 static int f2fs_dquot_mark_dquot_dirty(struct dquot *dquot)
3031 {
3032 	struct super_block *sb = dquot->dq_sb;
3033 	struct f2fs_sb_info *sbi = F2FS_SB(sb);
3034 	int ret = dquot_mark_dquot_dirty(dquot);
3035 
3036 	/* if we are using journalled quota */
3037 	if (is_journalled_quota(sbi))
3038 		set_sbi_flag(sbi, SBI_QUOTA_NEED_FLUSH);
3039 
3040 	return ret;
3041 }
3042 
3043 static int f2fs_dquot_commit_info(struct super_block *sb, int type)
3044 {
3045 	struct f2fs_sb_info *sbi = F2FS_SB(sb);
3046 	int ret = dquot_commit_info(sb, type);
3047 
3048 	if (ret < 0)
3049 		set_sbi_flag(sbi, SBI_QUOTA_NEED_REPAIR);
3050 	return ret;
3051 }
3052 
3053 static int f2fs_get_projid(struct inode *inode, kprojid_t *projid)
3054 {
3055 	*projid = F2FS_I(inode)->i_projid;
3056 	return 0;
3057 }
3058 
3059 static const struct dquot_operations f2fs_quota_operations = {
3060 	.get_reserved_space = f2fs_get_reserved_space,
3061 	.write_dquot	= f2fs_dquot_commit,
3062 	.acquire_dquot	= f2fs_dquot_acquire,
3063 	.release_dquot	= f2fs_dquot_release,
3064 	.mark_dirty	= f2fs_dquot_mark_dquot_dirty,
3065 	.write_info	= f2fs_dquot_commit_info,
3066 	.alloc_dquot	= dquot_alloc,
3067 	.destroy_dquot	= dquot_destroy,
3068 	.get_projid	= f2fs_get_projid,
3069 	.get_next_id	= dquot_get_next_id,
3070 };
3071 
3072 static const struct quotactl_ops f2fs_quotactl_ops = {
3073 	.quota_on	= f2fs_quota_on,
3074 	.quota_off	= f2fs_quota_off,
3075 	.quota_sync	= f2fs_quota_sync,
3076 	.get_state	= dquot_get_state,
3077 	.set_info	= dquot_set_dqinfo,
3078 	.get_dqblk	= dquot_get_dqblk,
3079 	.set_dqblk	= dquot_set_dqblk,
3080 	.get_nextdqblk	= dquot_get_next_dqblk,
3081 };
3082 #else
3083 int f2fs_dquot_initialize(struct inode *inode)
3084 {
3085 	return 0;
3086 }
3087 
3088 int f2fs_quota_sync(struct super_block *sb, int type)
3089 {
3090 	return 0;
3091 }
3092 
3093 void f2fs_quota_off_umount(struct super_block *sb)
3094 {
3095 }
3096 #endif
3097 
3098 static const struct super_operations f2fs_sops = {
3099 	.alloc_inode	= f2fs_alloc_inode,
3100 	.free_inode	= f2fs_free_inode,
3101 	.drop_inode	= f2fs_drop_inode,
3102 	.write_inode	= f2fs_write_inode,
3103 	.dirty_inode	= f2fs_dirty_inode,
3104 	.show_options	= f2fs_show_options,
3105 #ifdef CONFIG_QUOTA
3106 	.quota_read	= f2fs_quota_read,
3107 	.quota_write	= f2fs_quota_write,
3108 	.get_dquots	= f2fs_get_dquots,
3109 #endif
3110 	.evict_inode	= f2fs_evict_inode,
3111 	.put_super	= f2fs_put_super,
3112 	.sync_fs	= f2fs_sync_fs,
3113 	.freeze_fs	= f2fs_freeze,
3114 	.unfreeze_fs	= f2fs_unfreeze,
3115 	.statfs		= f2fs_statfs,
3116 	.remount_fs	= f2fs_remount,
3117 };
3118 
3119 #ifdef CONFIG_FS_ENCRYPTION
3120 static int f2fs_get_context(struct inode *inode, void *ctx, size_t len)
3121 {
3122 	return f2fs_getxattr(inode, F2FS_XATTR_INDEX_ENCRYPTION,
3123 				F2FS_XATTR_NAME_ENCRYPTION_CONTEXT,
3124 				ctx, len, NULL);
3125 }
3126 
3127 static int f2fs_set_context(struct inode *inode, const void *ctx, size_t len,
3128 							void *fs_data)
3129 {
3130 	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
3131 
3132 	/*
3133 	 * Encrypting the root directory is not allowed because fsck
3134 	 * expects lost+found directory to exist and remain unencrypted
3135 	 * if LOST_FOUND feature is enabled.
3136 	 *
3137 	 */
3138 	if (f2fs_sb_has_lost_found(sbi) &&
3139 			inode->i_ino == F2FS_ROOT_INO(sbi))
3140 		return -EPERM;
3141 
3142 	return f2fs_setxattr(inode, F2FS_XATTR_INDEX_ENCRYPTION,
3143 				F2FS_XATTR_NAME_ENCRYPTION_CONTEXT,
3144 				ctx, len, fs_data, XATTR_CREATE);
3145 }
3146 
3147 static const union fscrypt_policy *f2fs_get_dummy_policy(struct super_block *sb)
3148 {
3149 	return F2FS_OPTION(F2FS_SB(sb)).dummy_enc_policy.policy;
3150 }
3151 
3152 static bool f2fs_has_stable_inodes(struct super_block *sb)
3153 {
3154 	return true;
3155 }
3156 
3157 static void f2fs_get_ino_and_lblk_bits(struct super_block *sb,
3158 				       int *ino_bits_ret, int *lblk_bits_ret)
3159 {
3160 	*ino_bits_ret = 8 * sizeof(nid_t);
3161 	*lblk_bits_ret = 8 * sizeof(block_t);
3162 }
3163 
3164 static struct block_device **f2fs_get_devices(struct super_block *sb,
3165 					      unsigned int *num_devs)
3166 {
3167 	struct f2fs_sb_info *sbi = F2FS_SB(sb);
3168 	struct block_device **devs;
3169 	int i;
3170 
3171 	if (!f2fs_is_multi_device(sbi))
3172 		return NULL;
3173 
3174 	devs = kmalloc_array(sbi->s_ndevs, sizeof(*devs), GFP_KERNEL);
3175 	if (!devs)
3176 		return ERR_PTR(-ENOMEM);
3177 
3178 	for (i = 0; i < sbi->s_ndevs; i++)
3179 		devs[i] = FDEV(i).bdev;
3180 	*num_devs = sbi->s_ndevs;
3181 	return devs;
3182 }
3183 
3184 static const struct fscrypt_operations f2fs_cryptops = {
3185 	.key_prefix		= "f2fs:",
3186 	.get_context		= f2fs_get_context,
3187 	.set_context		= f2fs_set_context,
3188 	.get_dummy_policy	= f2fs_get_dummy_policy,
3189 	.empty_dir		= f2fs_empty_dir,
3190 	.has_stable_inodes	= f2fs_has_stable_inodes,
3191 	.get_ino_and_lblk_bits	= f2fs_get_ino_and_lblk_bits,
3192 	.get_devices		= f2fs_get_devices,
3193 };
3194 #endif
3195 
3196 static struct inode *f2fs_nfs_get_inode(struct super_block *sb,
3197 		u64 ino, u32 generation)
3198 {
3199 	struct f2fs_sb_info *sbi = F2FS_SB(sb);
3200 	struct inode *inode;
3201 
3202 	if (f2fs_check_nid_range(sbi, ino))
3203 		return ERR_PTR(-ESTALE);
3204 
3205 	/*
3206 	 * f2fs_iget isn't quite right if the inode is currently unallocated!
3207 	 * However f2fs_iget currently does appropriate checks to handle stale
3208 	 * inodes so everything is OK.
3209 	 */
3210 	inode = f2fs_iget(sb, ino);
3211 	if (IS_ERR(inode))
3212 		return ERR_CAST(inode);
3213 	if (unlikely(generation && inode->i_generation != generation)) {
3214 		/* we didn't find the right inode.. */
3215 		iput(inode);
3216 		return ERR_PTR(-ESTALE);
3217 	}
3218 	return inode;
3219 }
3220 
3221 static struct dentry *f2fs_fh_to_dentry(struct super_block *sb, struct fid *fid,
3222 		int fh_len, int fh_type)
3223 {
3224 	return generic_fh_to_dentry(sb, fid, fh_len, fh_type,
3225 				    f2fs_nfs_get_inode);
3226 }
3227 
3228 static struct dentry *f2fs_fh_to_parent(struct super_block *sb, struct fid *fid,
3229 		int fh_len, int fh_type)
3230 {
3231 	return generic_fh_to_parent(sb, fid, fh_len, fh_type,
3232 				    f2fs_nfs_get_inode);
3233 }
3234 
3235 static const struct export_operations f2fs_export_ops = {
3236 	.fh_to_dentry = f2fs_fh_to_dentry,
3237 	.fh_to_parent = f2fs_fh_to_parent,
3238 	.get_parent = f2fs_get_parent,
3239 };
3240 
3241 loff_t max_file_blocks(struct inode *inode)
3242 {
3243 	loff_t result = 0;
3244 	loff_t leaf_count;
3245 
3246 	/*
3247 	 * note: previously, result is equal to (DEF_ADDRS_PER_INODE -
3248 	 * DEFAULT_INLINE_XATTR_ADDRS), but now f2fs try to reserve more
3249 	 * space in inode.i_addr, it will be more safe to reassign
3250 	 * result as zero.
3251 	 */
3252 
3253 	if (inode && f2fs_compressed_file(inode))
3254 		leaf_count = ADDRS_PER_BLOCK(inode);
3255 	else
3256 		leaf_count = DEF_ADDRS_PER_BLOCK;
3257 
3258 	/* two direct node blocks */
3259 	result += (leaf_count * 2);
3260 
3261 	/* two indirect node blocks */
3262 	leaf_count *= NIDS_PER_BLOCK;
3263 	result += (leaf_count * 2);
3264 
3265 	/* one double indirect node block */
3266 	leaf_count *= NIDS_PER_BLOCK;
3267 	result += leaf_count;
3268 
3269 	return result;
3270 }
3271 
3272 static int __f2fs_commit_super(struct buffer_head *bh,
3273 			struct f2fs_super_block *super)
3274 {
3275 	lock_buffer(bh);
3276 	if (super)
3277 		memcpy(bh->b_data + F2FS_SUPER_OFFSET, super, sizeof(*super));
3278 	set_buffer_dirty(bh);
3279 	unlock_buffer(bh);
3280 
3281 	/* it's rare case, we can do fua all the time */
3282 	return __sync_dirty_buffer(bh, REQ_SYNC | REQ_PREFLUSH | REQ_FUA);
3283 }
3284 
3285 static inline bool sanity_check_area_boundary(struct f2fs_sb_info *sbi,
3286 					struct buffer_head *bh)
3287 {
3288 	struct f2fs_super_block *raw_super = (struct f2fs_super_block *)
3289 					(bh->b_data + F2FS_SUPER_OFFSET);
3290 	struct super_block *sb = sbi->sb;
3291 	u32 segment0_blkaddr = le32_to_cpu(raw_super->segment0_blkaddr);
3292 	u32 cp_blkaddr = le32_to_cpu(raw_super->cp_blkaddr);
3293 	u32 sit_blkaddr = le32_to_cpu(raw_super->sit_blkaddr);
3294 	u32 nat_blkaddr = le32_to_cpu(raw_super->nat_blkaddr);
3295 	u32 ssa_blkaddr = le32_to_cpu(raw_super->ssa_blkaddr);
3296 	u32 main_blkaddr = le32_to_cpu(raw_super->main_blkaddr);
3297 	u32 segment_count_ckpt = le32_to_cpu(raw_super->segment_count_ckpt);
3298 	u32 segment_count_sit = le32_to_cpu(raw_super->segment_count_sit);
3299 	u32 segment_count_nat = le32_to_cpu(raw_super->segment_count_nat);
3300 	u32 segment_count_ssa = le32_to_cpu(raw_super->segment_count_ssa);
3301 	u32 segment_count_main = le32_to_cpu(raw_super->segment_count_main);
3302 	u32 segment_count = le32_to_cpu(raw_super->segment_count);
3303 	u32 log_blocks_per_seg = le32_to_cpu(raw_super->log_blocks_per_seg);
3304 	u64 main_end_blkaddr = main_blkaddr +
3305 				(segment_count_main << log_blocks_per_seg);
3306 	u64 seg_end_blkaddr = segment0_blkaddr +
3307 				(segment_count << log_blocks_per_seg);
3308 
3309 	if (segment0_blkaddr != cp_blkaddr) {
3310 		f2fs_info(sbi, "Mismatch start address, segment0(%u) cp_blkaddr(%u)",
3311 			  segment0_blkaddr, cp_blkaddr);
3312 		return true;
3313 	}
3314 
3315 	if (cp_blkaddr + (segment_count_ckpt << log_blocks_per_seg) !=
3316 							sit_blkaddr) {
3317 		f2fs_info(sbi, "Wrong CP boundary, start(%u) end(%u) blocks(%u)",
3318 			  cp_blkaddr, sit_blkaddr,
3319 			  segment_count_ckpt << log_blocks_per_seg);
3320 		return true;
3321 	}
3322 
3323 	if (sit_blkaddr + (segment_count_sit << log_blocks_per_seg) !=
3324 							nat_blkaddr) {
3325 		f2fs_info(sbi, "Wrong SIT boundary, start(%u) end(%u) blocks(%u)",
3326 			  sit_blkaddr, nat_blkaddr,
3327 			  segment_count_sit << log_blocks_per_seg);
3328 		return true;
3329 	}
3330 
3331 	if (nat_blkaddr + (segment_count_nat << log_blocks_per_seg) !=
3332 							ssa_blkaddr) {
3333 		f2fs_info(sbi, "Wrong NAT boundary, start(%u) end(%u) blocks(%u)",
3334 			  nat_blkaddr, ssa_blkaddr,
3335 			  segment_count_nat << log_blocks_per_seg);
3336 		return true;
3337 	}
3338 
3339 	if (ssa_blkaddr + (segment_count_ssa << log_blocks_per_seg) !=
3340 							main_blkaddr) {
3341 		f2fs_info(sbi, "Wrong SSA boundary, start(%u) end(%u) blocks(%u)",
3342 			  ssa_blkaddr, main_blkaddr,
3343 			  segment_count_ssa << log_blocks_per_seg);
3344 		return true;
3345 	}
3346 
3347 	if (main_end_blkaddr > seg_end_blkaddr) {
3348 		f2fs_info(sbi, "Wrong MAIN_AREA boundary, start(%u) end(%llu) block(%u)",
3349 			  main_blkaddr, seg_end_blkaddr,
3350 			  segment_count_main << log_blocks_per_seg);
3351 		return true;
3352 	} else if (main_end_blkaddr < seg_end_blkaddr) {
3353 		int err = 0;
3354 		char *res;
3355 
3356 		/* fix in-memory information all the time */
3357 		raw_super->segment_count = cpu_to_le32((main_end_blkaddr -
3358 				segment0_blkaddr) >> log_blocks_per_seg);
3359 
3360 		if (f2fs_readonly(sb) || f2fs_hw_is_readonly(sbi)) {
3361 			set_sbi_flag(sbi, SBI_NEED_SB_WRITE);
3362 			res = "internally";
3363 		} else {
3364 			err = __f2fs_commit_super(bh, NULL);
3365 			res = err ? "failed" : "done";
3366 		}
3367 		f2fs_info(sbi, "Fix alignment : %s, start(%u) end(%llu) block(%u)",
3368 			  res, main_blkaddr, seg_end_blkaddr,
3369 			  segment_count_main << log_blocks_per_seg);
3370 		if (err)
3371 			return true;
3372 	}
3373 	return false;
3374 }
3375 
3376 static int sanity_check_raw_super(struct f2fs_sb_info *sbi,
3377 				struct buffer_head *bh)
3378 {
3379 	block_t segment_count, segs_per_sec, secs_per_zone, segment_count_main;
3380 	block_t total_sections, blocks_per_seg;
3381 	struct f2fs_super_block *raw_super = (struct f2fs_super_block *)
3382 					(bh->b_data + F2FS_SUPER_OFFSET);
3383 	size_t crc_offset = 0;
3384 	__u32 crc = 0;
3385 
3386 	if (le32_to_cpu(raw_super->magic) != F2FS_SUPER_MAGIC) {
3387 		f2fs_info(sbi, "Magic Mismatch, valid(0x%x) - read(0x%x)",
3388 			  F2FS_SUPER_MAGIC, le32_to_cpu(raw_super->magic));
3389 		return -EINVAL;
3390 	}
3391 
3392 	/* Check checksum_offset and crc in superblock */
3393 	if (__F2FS_HAS_FEATURE(raw_super, F2FS_FEATURE_SB_CHKSUM)) {
3394 		crc_offset = le32_to_cpu(raw_super->checksum_offset);
3395 		if (crc_offset !=
3396 			offsetof(struct f2fs_super_block, crc)) {
3397 			f2fs_info(sbi, "Invalid SB checksum offset: %zu",
3398 				  crc_offset);
3399 			return -EFSCORRUPTED;
3400 		}
3401 		crc = le32_to_cpu(raw_super->crc);
3402 		if (!f2fs_crc_valid(sbi, crc, raw_super, crc_offset)) {
3403 			f2fs_info(sbi, "Invalid SB checksum value: %u", crc);
3404 			return -EFSCORRUPTED;
3405 		}
3406 	}
3407 
3408 	/* Currently, support only 4KB block size */
3409 	if (le32_to_cpu(raw_super->log_blocksize) != F2FS_BLKSIZE_BITS) {
3410 		f2fs_info(sbi, "Invalid log_blocksize (%u), supports only %u",
3411 			  le32_to_cpu(raw_super->log_blocksize),
3412 			  F2FS_BLKSIZE_BITS);
3413 		return -EFSCORRUPTED;
3414 	}
3415 
3416 	/* check log blocks per segment */
3417 	if (le32_to_cpu(raw_super->log_blocks_per_seg) != 9) {
3418 		f2fs_info(sbi, "Invalid log blocks per segment (%u)",
3419 			  le32_to_cpu(raw_super->log_blocks_per_seg));
3420 		return -EFSCORRUPTED;
3421 	}
3422 
3423 	/* Currently, support 512/1024/2048/4096 bytes sector size */
3424 	if (le32_to_cpu(raw_super->log_sectorsize) >
3425 				F2FS_MAX_LOG_SECTOR_SIZE ||
3426 		le32_to_cpu(raw_super->log_sectorsize) <
3427 				F2FS_MIN_LOG_SECTOR_SIZE) {
3428 		f2fs_info(sbi, "Invalid log sectorsize (%u)",
3429 			  le32_to_cpu(raw_super->log_sectorsize));
3430 		return -EFSCORRUPTED;
3431 	}
3432 	if (le32_to_cpu(raw_super->log_sectors_per_block) +
3433 		le32_to_cpu(raw_super->log_sectorsize) !=
3434 			F2FS_MAX_LOG_SECTOR_SIZE) {
3435 		f2fs_info(sbi, "Invalid log sectors per block(%u) log sectorsize(%u)",
3436 			  le32_to_cpu(raw_super->log_sectors_per_block),
3437 			  le32_to_cpu(raw_super->log_sectorsize));
3438 		return -EFSCORRUPTED;
3439 	}
3440 
3441 	segment_count = le32_to_cpu(raw_super->segment_count);
3442 	segment_count_main = le32_to_cpu(raw_super->segment_count_main);
3443 	segs_per_sec = le32_to_cpu(raw_super->segs_per_sec);
3444 	secs_per_zone = le32_to_cpu(raw_super->secs_per_zone);
3445 	total_sections = le32_to_cpu(raw_super->section_count);
3446 
3447 	/* blocks_per_seg should be 512, given the above check */
3448 	blocks_per_seg = BIT(le32_to_cpu(raw_super->log_blocks_per_seg));
3449 
3450 	if (segment_count > F2FS_MAX_SEGMENT ||
3451 				segment_count < F2FS_MIN_SEGMENTS) {
3452 		f2fs_info(sbi, "Invalid segment count (%u)", segment_count);
3453 		return -EFSCORRUPTED;
3454 	}
3455 
3456 	if (total_sections > segment_count_main || total_sections < 1 ||
3457 			segs_per_sec > segment_count || !segs_per_sec) {
3458 		f2fs_info(sbi, "Invalid segment/section count (%u, %u x %u)",
3459 			  segment_count, total_sections, segs_per_sec);
3460 		return -EFSCORRUPTED;
3461 	}
3462 
3463 	if (segment_count_main != total_sections * segs_per_sec) {
3464 		f2fs_info(sbi, "Invalid segment/section count (%u != %u * %u)",
3465 			  segment_count_main, total_sections, segs_per_sec);
3466 		return -EFSCORRUPTED;
3467 	}
3468 
3469 	if ((segment_count / segs_per_sec) < total_sections) {
3470 		f2fs_info(sbi, "Small segment_count (%u < %u * %u)",
3471 			  segment_count, segs_per_sec, total_sections);
3472 		return -EFSCORRUPTED;
3473 	}
3474 
3475 	if (segment_count > (le64_to_cpu(raw_super->block_count) >> 9)) {
3476 		f2fs_info(sbi, "Wrong segment_count / block_count (%u > %llu)",
3477 			  segment_count, le64_to_cpu(raw_super->block_count));
3478 		return -EFSCORRUPTED;
3479 	}
3480 
3481 	if (RDEV(0).path[0]) {
3482 		block_t dev_seg_count = le32_to_cpu(RDEV(0).total_segments);
3483 		int i = 1;
3484 
3485 		while (i < MAX_DEVICES && RDEV(i).path[0]) {
3486 			dev_seg_count += le32_to_cpu(RDEV(i).total_segments);
3487 			i++;
3488 		}
3489 		if (segment_count != dev_seg_count) {
3490 			f2fs_info(sbi, "Segment count (%u) mismatch with total segments from devices (%u)",
3491 					segment_count, dev_seg_count);
3492 			return -EFSCORRUPTED;
3493 		}
3494 	} else {
3495 		if (__F2FS_HAS_FEATURE(raw_super, F2FS_FEATURE_BLKZONED) &&
3496 					!bdev_is_zoned(sbi->sb->s_bdev)) {
3497 			f2fs_info(sbi, "Zoned block device path is missing");
3498 			return -EFSCORRUPTED;
3499 		}
3500 	}
3501 
3502 	if (secs_per_zone > total_sections || !secs_per_zone) {
3503 		f2fs_info(sbi, "Wrong secs_per_zone / total_sections (%u, %u)",
3504 			  secs_per_zone, total_sections);
3505 		return -EFSCORRUPTED;
3506 	}
3507 	if (le32_to_cpu(raw_super->extension_count) > F2FS_MAX_EXTENSION ||
3508 			raw_super->hot_ext_count > F2FS_MAX_EXTENSION ||
3509 			(le32_to_cpu(raw_super->extension_count) +
3510 			raw_super->hot_ext_count) > F2FS_MAX_EXTENSION) {
3511 		f2fs_info(sbi, "Corrupted extension count (%u + %u > %u)",
3512 			  le32_to_cpu(raw_super->extension_count),
3513 			  raw_super->hot_ext_count,
3514 			  F2FS_MAX_EXTENSION);
3515 		return -EFSCORRUPTED;
3516 	}
3517 
3518 	if (le32_to_cpu(raw_super->cp_payload) >=
3519 				(blocks_per_seg - F2FS_CP_PACKS -
3520 				NR_CURSEG_PERSIST_TYPE)) {
3521 		f2fs_info(sbi, "Insane cp_payload (%u >= %u)",
3522 			  le32_to_cpu(raw_super->cp_payload),
3523 			  blocks_per_seg - F2FS_CP_PACKS -
3524 			  NR_CURSEG_PERSIST_TYPE);
3525 		return -EFSCORRUPTED;
3526 	}
3527 
3528 	/* check reserved ino info */
3529 	if (le32_to_cpu(raw_super->node_ino) != 1 ||
3530 		le32_to_cpu(raw_super->meta_ino) != 2 ||
3531 		le32_to_cpu(raw_super->root_ino) != 3) {
3532 		f2fs_info(sbi, "Invalid Fs Meta Ino: node(%u) meta(%u) root(%u)",
3533 			  le32_to_cpu(raw_super->node_ino),
3534 			  le32_to_cpu(raw_super->meta_ino),
3535 			  le32_to_cpu(raw_super->root_ino));
3536 		return -EFSCORRUPTED;
3537 	}
3538 
3539 	/* check CP/SIT/NAT/SSA/MAIN_AREA area boundary */
3540 	if (sanity_check_area_boundary(sbi, bh))
3541 		return -EFSCORRUPTED;
3542 
3543 	return 0;
3544 }
3545 
3546 int f2fs_sanity_check_ckpt(struct f2fs_sb_info *sbi)
3547 {
3548 	unsigned int total, fsmeta;
3549 	struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi);
3550 	struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
3551 	unsigned int ovp_segments, reserved_segments;
3552 	unsigned int main_segs, blocks_per_seg;
3553 	unsigned int sit_segs, nat_segs;
3554 	unsigned int sit_bitmap_size, nat_bitmap_size;
3555 	unsigned int log_blocks_per_seg;
3556 	unsigned int segment_count_main;
3557 	unsigned int cp_pack_start_sum, cp_payload;
3558 	block_t user_block_count, valid_user_blocks;
3559 	block_t avail_node_count, valid_node_count;
3560 	unsigned int nat_blocks, nat_bits_bytes, nat_bits_blocks;
3561 	int i, j;
3562 
3563 	total = le32_to_cpu(raw_super->segment_count);
3564 	fsmeta = le32_to_cpu(raw_super->segment_count_ckpt);
3565 	sit_segs = le32_to_cpu(raw_super->segment_count_sit);
3566 	fsmeta += sit_segs;
3567 	nat_segs = le32_to_cpu(raw_super->segment_count_nat);
3568 	fsmeta += nat_segs;
3569 	fsmeta += le32_to_cpu(ckpt->rsvd_segment_count);
3570 	fsmeta += le32_to_cpu(raw_super->segment_count_ssa);
3571 
3572 	if (unlikely(fsmeta >= total))
3573 		return 1;
3574 
3575 	ovp_segments = le32_to_cpu(ckpt->overprov_segment_count);
3576 	reserved_segments = le32_to_cpu(ckpt->rsvd_segment_count);
3577 
3578 	if (!f2fs_sb_has_readonly(sbi) &&
3579 			unlikely(fsmeta < F2FS_MIN_META_SEGMENTS ||
3580 			ovp_segments == 0 || reserved_segments == 0)) {
3581 		f2fs_err(sbi, "Wrong layout: check mkfs.f2fs version");
3582 		return 1;
3583 	}
3584 	user_block_count = le64_to_cpu(ckpt->user_block_count);
3585 	segment_count_main = le32_to_cpu(raw_super->segment_count_main) +
3586 			(f2fs_sb_has_readonly(sbi) ? 1 : 0);
3587 	log_blocks_per_seg = le32_to_cpu(raw_super->log_blocks_per_seg);
3588 	if (!user_block_count || user_block_count >=
3589 			segment_count_main << log_blocks_per_seg) {
3590 		f2fs_err(sbi, "Wrong user_block_count: %u",
3591 			 user_block_count);
3592 		return 1;
3593 	}
3594 
3595 	valid_user_blocks = le64_to_cpu(ckpt->valid_block_count);
3596 	if (valid_user_blocks > user_block_count) {
3597 		f2fs_err(sbi, "Wrong valid_user_blocks: %u, user_block_count: %u",
3598 			 valid_user_blocks, user_block_count);
3599 		return 1;
3600 	}
3601 
3602 	valid_node_count = le32_to_cpu(ckpt->valid_node_count);
3603 	avail_node_count = sbi->total_node_count - F2FS_RESERVED_NODE_NUM;
3604 	if (valid_node_count > avail_node_count) {
3605 		f2fs_err(sbi, "Wrong valid_node_count: %u, avail_node_count: %u",
3606 			 valid_node_count, avail_node_count);
3607 		return 1;
3608 	}
3609 
3610 	main_segs = le32_to_cpu(raw_super->segment_count_main);
3611 	blocks_per_seg = sbi->blocks_per_seg;
3612 
3613 	for (i = 0; i < NR_CURSEG_NODE_TYPE; i++) {
3614 		if (le32_to_cpu(ckpt->cur_node_segno[i]) >= main_segs ||
3615 			le16_to_cpu(ckpt->cur_node_blkoff[i]) >= blocks_per_seg)
3616 			return 1;
3617 
3618 		if (f2fs_sb_has_readonly(sbi))
3619 			goto check_data;
3620 
3621 		for (j = i + 1; j < NR_CURSEG_NODE_TYPE; j++) {
3622 			if (le32_to_cpu(ckpt->cur_node_segno[i]) ==
3623 				le32_to_cpu(ckpt->cur_node_segno[j])) {
3624 				f2fs_err(sbi, "Node segment (%u, %u) has the same segno: %u",
3625 					 i, j,
3626 					 le32_to_cpu(ckpt->cur_node_segno[i]));
3627 				return 1;
3628 			}
3629 		}
3630 	}
3631 check_data:
3632 	for (i = 0; i < NR_CURSEG_DATA_TYPE; i++) {
3633 		if (le32_to_cpu(ckpt->cur_data_segno[i]) >= main_segs ||
3634 			le16_to_cpu(ckpt->cur_data_blkoff[i]) >= blocks_per_seg)
3635 			return 1;
3636 
3637 		if (f2fs_sb_has_readonly(sbi))
3638 			goto skip_cross;
3639 
3640 		for (j = i + 1; j < NR_CURSEG_DATA_TYPE; j++) {
3641 			if (le32_to_cpu(ckpt->cur_data_segno[i]) ==
3642 				le32_to_cpu(ckpt->cur_data_segno[j])) {
3643 				f2fs_err(sbi, "Data segment (%u, %u) has the same segno: %u",
3644 					 i, j,
3645 					 le32_to_cpu(ckpt->cur_data_segno[i]));
3646 				return 1;
3647 			}
3648 		}
3649 	}
3650 	for (i = 0; i < NR_CURSEG_NODE_TYPE; i++) {
3651 		for (j = 0; j < NR_CURSEG_DATA_TYPE; j++) {
3652 			if (le32_to_cpu(ckpt->cur_node_segno[i]) ==
3653 				le32_to_cpu(ckpt->cur_data_segno[j])) {
3654 				f2fs_err(sbi, "Node segment (%u) and Data segment (%u) has the same segno: %u",
3655 					 i, j,
3656 					 le32_to_cpu(ckpt->cur_node_segno[i]));
3657 				return 1;
3658 			}
3659 		}
3660 	}
3661 skip_cross:
3662 	sit_bitmap_size = le32_to_cpu(ckpt->sit_ver_bitmap_bytesize);
3663 	nat_bitmap_size = le32_to_cpu(ckpt->nat_ver_bitmap_bytesize);
3664 
3665 	if (sit_bitmap_size != ((sit_segs / 2) << log_blocks_per_seg) / 8 ||
3666 		nat_bitmap_size != ((nat_segs / 2) << log_blocks_per_seg) / 8) {
3667 		f2fs_err(sbi, "Wrong bitmap size: sit: %u, nat:%u",
3668 			 sit_bitmap_size, nat_bitmap_size);
3669 		return 1;
3670 	}
3671 
3672 	cp_pack_start_sum = __start_sum_addr(sbi);
3673 	cp_payload = __cp_payload(sbi);
3674 	if (cp_pack_start_sum < cp_payload + 1 ||
3675 		cp_pack_start_sum > blocks_per_seg - 1 -
3676 			NR_CURSEG_PERSIST_TYPE) {
3677 		f2fs_err(sbi, "Wrong cp_pack_start_sum: %u",
3678 			 cp_pack_start_sum);
3679 		return 1;
3680 	}
3681 
3682 	if (__is_set_ckpt_flags(ckpt, CP_LARGE_NAT_BITMAP_FLAG) &&
3683 		le32_to_cpu(ckpt->checksum_offset) != CP_MIN_CHKSUM_OFFSET) {
3684 		f2fs_warn(sbi, "using deprecated layout of large_nat_bitmap, "
3685 			  "please run fsck v1.13.0 or higher to repair, chksum_offset: %u, "
3686 			  "fixed with patch: \"f2fs-tools: relocate chksum_offset for large_nat_bitmap feature\"",
3687 			  le32_to_cpu(ckpt->checksum_offset));
3688 		return 1;
3689 	}
3690 
3691 	nat_blocks = nat_segs << log_blocks_per_seg;
3692 	nat_bits_bytes = nat_blocks / BITS_PER_BYTE;
3693 	nat_bits_blocks = F2FS_BLK_ALIGN((nat_bits_bytes << 1) + 8);
3694 	if (__is_set_ckpt_flags(ckpt, CP_NAT_BITS_FLAG) &&
3695 		(cp_payload + F2FS_CP_PACKS +
3696 		NR_CURSEG_PERSIST_TYPE + nat_bits_blocks >= blocks_per_seg)) {
3697 		f2fs_warn(sbi, "Insane cp_payload: %u, nat_bits_blocks: %u)",
3698 			  cp_payload, nat_bits_blocks);
3699 		return 1;
3700 	}
3701 
3702 	if (unlikely(f2fs_cp_error(sbi))) {
3703 		f2fs_err(sbi, "A bug case: need to run fsck");
3704 		return 1;
3705 	}
3706 	return 0;
3707 }
3708 
3709 static void init_sb_info(struct f2fs_sb_info *sbi)
3710 {
3711 	struct f2fs_super_block *raw_super = sbi->raw_super;
3712 	int i;
3713 
3714 	sbi->log_sectors_per_block =
3715 		le32_to_cpu(raw_super->log_sectors_per_block);
3716 	sbi->log_blocksize = le32_to_cpu(raw_super->log_blocksize);
3717 	sbi->blocksize = BIT(sbi->log_blocksize);
3718 	sbi->log_blocks_per_seg = le32_to_cpu(raw_super->log_blocks_per_seg);
3719 	sbi->blocks_per_seg = BIT(sbi->log_blocks_per_seg);
3720 	sbi->segs_per_sec = le32_to_cpu(raw_super->segs_per_sec);
3721 	sbi->secs_per_zone = le32_to_cpu(raw_super->secs_per_zone);
3722 	sbi->total_sections = le32_to_cpu(raw_super->section_count);
3723 	sbi->total_node_count =
3724 		(le32_to_cpu(raw_super->segment_count_nat) / 2)
3725 			* sbi->blocks_per_seg * NAT_ENTRY_PER_BLOCK;
3726 	F2FS_ROOT_INO(sbi) = le32_to_cpu(raw_super->root_ino);
3727 	F2FS_NODE_INO(sbi) = le32_to_cpu(raw_super->node_ino);
3728 	F2FS_META_INO(sbi) = le32_to_cpu(raw_super->meta_ino);
3729 	sbi->cur_victim_sec = NULL_SECNO;
3730 	sbi->gc_mode = GC_NORMAL;
3731 	sbi->next_victim_seg[BG_GC] = NULL_SEGNO;
3732 	sbi->next_victim_seg[FG_GC] = NULL_SEGNO;
3733 	sbi->max_victim_search = DEF_MAX_VICTIM_SEARCH;
3734 	sbi->migration_granularity = sbi->segs_per_sec;
3735 	sbi->seq_file_ra_mul = MIN_RA_MUL;
3736 	sbi->max_fragment_chunk = DEF_FRAGMENT_SIZE;
3737 	sbi->max_fragment_hole = DEF_FRAGMENT_SIZE;
3738 	spin_lock_init(&sbi->gc_remaining_trials_lock);
3739 	atomic64_set(&sbi->current_atomic_write, 0);
3740 
3741 	sbi->dir_level = DEF_DIR_LEVEL;
3742 	sbi->interval_time[CP_TIME] = DEF_CP_INTERVAL;
3743 	sbi->interval_time[REQ_TIME] = DEF_IDLE_INTERVAL;
3744 	sbi->interval_time[DISCARD_TIME] = DEF_IDLE_INTERVAL;
3745 	sbi->interval_time[GC_TIME] = DEF_IDLE_INTERVAL;
3746 	sbi->interval_time[DISABLE_TIME] = DEF_DISABLE_INTERVAL;
3747 	sbi->interval_time[UMOUNT_DISCARD_TIMEOUT] =
3748 				DEF_UMOUNT_DISCARD_TIMEOUT;
3749 	clear_sbi_flag(sbi, SBI_NEED_FSCK);
3750 
3751 	for (i = 0; i < NR_COUNT_TYPE; i++)
3752 		atomic_set(&sbi->nr_pages[i], 0);
3753 
3754 	for (i = 0; i < META; i++)
3755 		atomic_set(&sbi->wb_sync_req[i], 0);
3756 
3757 	INIT_LIST_HEAD(&sbi->s_list);
3758 	mutex_init(&sbi->umount_mutex);
3759 	init_f2fs_rwsem(&sbi->io_order_lock);
3760 	spin_lock_init(&sbi->cp_lock);
3761 
3762 	sbi->dirty_device = 0;
3763 	spin_lock_init(&sbi->dev_lock);
3764 
3765 	init_f2fs_rwsem(&sbi->sb_lock);
3766 	init_f2fs_rwsem(&sbi->pin_sem);
3767 }
3768 
3769 static int init_percpu_info(struct f2fs_sb_info *sbi)
3770 {
3771 	int err;
3772 
3773 	err = percpu_counter_init(&sbi->alloc_valid_block_count, 0, GFP_KERNEL);
3774 	if (err)
3775 		return err;
3776 
3777 	err = percpu_counter_init(&sbi->rf_node_block_count, 0, GFP_KERNEL);
3778 	if (err)
3779 		goto err_valid_block;
3780 
3781 	err = percpu_counter_init(&sbi->total_valid_inode_count, 0,
3782 								GFP_KERNEL);
3783 	if (err)
3784 		goto err_node_block;
3785 	return 0;
3786 
3787 err_node_block:
3788 	percpu_counter_destroy(&sbi->rf_node_block_count);
3789 err_valid_block:
3790 	percpu_counter_destroy(&sbi->alloc_valid_block_count);
3791 	return err;
3792 }
3793 
3794 #ifdef CONFIG_BLK_DEV_ZONED
3795 
3796 struct f2fs_report_zones_args {
3797 	struct f2fs_sb_info *sbi;
3798 	struct f2fs_dev_info *dev;
3799 };
3800 
3801 static int f2fs_report_zone_cb(struct blk_zone *zone, unsigned int idx,
3802 			      void *data)
3803 {
3804 	struct f2fs_report_zones_args *rz_args = data;
3805 	block_t unusable_blocks = (zone->len - zone->capacity) >>
3806 					F2FS_LOG_SECTORS_PER_BLOCK;
3807 
3808 	if (zone->type == BLK_ZONE_TYPE_CONVENTIONAL)
3809 		return 0;
3810 
3811 	set_bit(idx, rz_args->dev->blkz_seq);
3812 	if (!rz_args->sbi->unusable_blocks_per_sec) {
3813 		rz_args->sbi->unusable_blocks_per_sec = unusable_blocks;
3814 		return 0;
3815 	}
3816 	if (rz_args->sbi->unusable_blocks_per_sec != unusable_blocks) {
3817 		f2fs_err(rz_args->sbi, "F2FS supports single zone capacity\n");
3818 		return -EINVAL;
3819 	}
3820 	return 0;
3821 }
3822 
3823 static int init_blkz_info(struct f2fs_sb_info *sbi, int devi)
3824 {
3825 	struct block_device *bdev = FDEV(devi).bdev;
3826 	sector_t nr_sectors = bdev_nr_sectors(bdev);
3827 	struct f2fs_report_zones_args rep_zone_arg;
3828 	u64 zone_sectors;
3829 	int ret;
3830 
3831 	if (!f2fs_sb_has_blkzoned(sbi))
3832 		return 0;
3833 
3834 	zone_sectors = bdev_zone_sectors(bdev);
3835 	if (!is_power_of_2(zone_sectors)) {
3836 		f2fs_err(sbi, "F2FS does not support non power of 2 zone sizes\n");
3837 		return -EINVAL;
3838 	}
3839 
3840 	if (sbi->blocks_per_blkz && sbi->blocks_per_blkz !=
3841 				SECTOR_TO_BLOCK(zone_sectors))
3842 		return -EINVAL;
3843 	sbi->blocks_per_blkz = SECTOR_TO_BLOCK(zone_sectors);
3844 	FDEV(devi).nr_blkz = div_u64(SECTOR_TO_BLOCK(nr_sectors),
3845 					sbi->blocks_per_blkz);
3846 	if (nr_sectors & (zone_sectors - 1))
3847 		FDEV(devi).nr_blkz++;
3848 
3849 	FDEV(devi).blkz_seq = f2fs_kvzalloc(sbi,
3850 					BITS_TO_LONGS(FDEV(devi).nr_blkz)
3851 					* sizeof(unsigned long),
3852 					GFP_KERNEL);
3853 	if (!FDEV(devi).blkz_seq)
3854 		return -ENOMEM;
3855 
3856 	rep_zone_arg.sbi = sbi;
3857 	rep_zone_arg.dev = &FDEV(devi);
3858 
3859 	ret = blkdev_report_zones(bdev, 0, BLK_ALL_ZONES, f2fs_report_zone_cb,
3860 				  &rep_zone_arg);
3861 	if (ret < 0)
3862 		return ret;
3863 	return 0;
3864 }
3865 #endif
3866 
3867 /*
3868  * Read f2fs raw super block.
3869  * Because we have two copies of super block, so read both of them
3870  * to get the first valid one. If any one of them is broken, we pass
3871  * them recovery flag back to the caller.
3872  */
3873 static int read_raw_super_block(struct f2fs_sb_info *sbi,
3874 			struct f2fs_super_block **raw_super,
3875 			int *valid_super_block, int *recovery)
3876 {
3877 	struct super_block *sb = sbi->sb;
3878 	int block;
3879 	struct buffer_head *bh;
3880 	struct f2fs_super_block *super;
3881 	int err = 0;
3882 
3883 	super = kzalloc(sizeof(struct f2fs_super_block), GFP_KERNEL);
3884 	if (!super)
3885 		return -ENOMEM;
3886 
3887 	for (block = 0; block < 2; block++) {
3888 		bh = sb_bread(sb, block);
3889 		if (!bh) {
3890 			f2fs_err(sbi, "Unable to read %dth superblock",
3891 				 block + 1);
3892 			err = -EIO;
3893 			*recovery = 1;
3894 			continue;
3895 		}
3896 
3897 		/* sanity checking of raw super */
3898 		err = sanity_check_raw_super(sbi, bh);
3899 		if (err) {
3900 			f2fs_err(sbi, "Can't find valid F2FS filesystem in %dth superblock",
3901 				 block + 1);
3902 			brelse(bh);
3903 			*recovery = 1;
3904 			continue;
3905 		}
3906 
3907 		if (!*raw_super) {
3908 			memcpy(super, bh->b_data + F2FS_SUPER_OFFSET,
3909 							sizeof(*super));
3910 			*valid_super_block = block;
3911 			*raw_super = super;
3912 		}
3913 		brelse(bh);
3914 	}
3915 
3916 	/* No valid superblock */
3917 	if (!*raw_super)
3918 		kfree(super);
3919 	else
3920 		err = 0;
3921 
3922 	return err;
3923 }
3924 
3925 int f2fs_commit_super(struct f2fs_sb_info *sbi, bool recover)
3926 {
3927 	struct buffer_head *bh;
3928 	__u32 crc = 0;
3929 	int err;
3930 
3931 	if ((recover && f2fs_readonly(sbi->sb)) ||
3932 				f2fs_hw_is_readonly(sbi)) {
3933 		set_sbi_flag(sbi, SBI_NEED_SB_WRITE);
3934 		return -EROFS;
3935 	}
3936 
3937 	/* we should update superblock crc here */
3938 	if (!recover && f2fs_sb_has_sb_chksum(sbi)) {
3939 		crc = f2fs_crc32(sbi, F2FS_RAW_SUPER(sbi),
3940 				offsetof(struct f2fs_super_block, crc));
3941 		F2FS_RAW_SUPER(sbi)->crc = cpu_to_le32(crc);
3942 	}
3943 
3944 	/* write back-up superblock first */
3945 	bh = sb_bread(sbi->sb, sbi->valid_super_block ? 0 : 1);
3946 	if (!bh)
3947 		return -EIO;
3948 	err = __f2fs_commit_super(bh, F2FS_RAW_SUPER(sbi));
3949 	brelse(bh);
3950 
3951 	/* if we are in recovery path, skip writing valid superblock */
3952 	if (recover || err)
3953 		return err;
3954 
3955 	/* write current valid superblock */
3956 	bh = sb_bread(sbi->sb, sbi->valid_super_block);
3957 	if (!bh)
3958 		return -EIO;
3959 	err = __f2fs_commit_super(bh, F2FS_RAW_SUPER(sbi));
3960 	brelse(bh);
3961 	return err;
3962 }
3963 
3964 static void save_stop_reason(struct f2fs_sb_info *sbi, unsigned char reason)
3965 {
3966 	unsigned long flags;
3967 
3968 	spin_lock_irqsave(&sbi->error_lock, flags);
3969 	if (sbi->stop_reason[reason] < GENMASK(BITS_PER_BYTE - 1, 0))
3970 		sbi->stop_reason[reason]++;
3971 	spin_unlock_irqrestore(&sbi->error_lock, flags);
3972 }
3973 
3974 static void f2fs_record_stop_reason(struct f2fs_sb_info *sbi)
3975 {
3976 	struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi);
3977 	unsigned long flags;
3978 	int err;
3979 
3980 	f2fs_down_write(&sbi->sb_lock);
3981 
3982 	spin_lock_irqsave(&sbi->error_lock, flags);
3983 	memcpy(raw_super->s_stop_reason, sbi->stop_reason, MAX_STOP_REASON);
3984 	spin_unlock_irqrestore(&sbi->error_lock, flags);
3985 
3986 	err = f2fs_commit_super(sbi, false);
3987 
3988 	f2fs_up_write(&sbi->sb_lock);
3989 	if (err)
3990 		f2fs_err(sbi, "f2fs_commit_super fails to record err:%d", err);
3991 }
3992 
3993 void f2fs_save_errors(struct f2fs_sb_info *sbi, unsigned char flag)
3994 {
3995 	unsigned long flags;
3996 
3997 	spin_lock_irqsave(&sbi->error_lock, flags);
3998 	if (!test_bit(flag, (unsigned long *)sbi->errors)) {
3999 		set_bit(flag, (unsigned long *)sbi->errors);
4000 		sbi->error_dirty = true;
4001 	}
4002 	spin_unlock_irqrestore(&sbi->error_lock, flags);
4003 }
4004 
4005 static bool f2fs_update_errors(struct f2fs_sb_info *sbi)
4006 {
4007 	unsigned long flags;
4008 	bool need_update = false;
4009 
4010 	spin_lock_irqsave(&sbi->error_lock, flags);
4011 	if (sbi->error_dirty) {
4012 		memcpy(F2FS_RAW_SUPER(sbi)->s_errors, sbi->errors,
4013 							MAX_F2FS_ERRORS);
4014 		sbi->error_dirty = false;
4015 		need_update = true;
4016 	}
4017 	spin_unlock_irqrestore(&sbi->error_lock, flags);
4018 
4019 	return need_update;
4020 }
4021 
4022 void f2fs_handle_error(struct f2fs_sb_info *sbi, unsigned char error)
4023 {
4024 	int err;
4025 
4026 	f2fs_save_errors(sbi, error);
4027 
4028 	f2fs_down_write(&sbi->sb_lock);
4029 
4030 	if (!f2fs_update_errors(sbi))
4031 		goto out_unlock;
4032 
4033 	err = f2fs_commit_super(sbi, false);
4034 	if (err)
4035 		f2fs_err(sbi, "f2fs_commit_super fails to record errors:%u, err:%d",
4036 								error, err);
4037 out_unlock:
4038 	f2fs_up_write(&sbi->sb_lock);
4039 }
4040 
4041 static bool system_going_down(void)
4042 {
4043 	return system_state == SYSTEM_HALT || system_state == SYSTEM_POWER_OFF
4044 		|| system_state == SYSTEM_RESTART;
4045 }
4046 
4047 void f2fs_handle_critical_error(struct f2fs_sb_info *sbi, unsigned char reason,
4048 							bool irq_context)
4049 {
4050 	struct super_block *sb = sbi->sb;
4051 	bool shutdown = reason == STOP_CP_REASON_SHUTDOWN;
4052 	bool continue_fs = !shutdown &&
4053 			F2FS_OPTION(sbi).errors == MOUNT_ERRORS_CONTINUE;
4054 
4055 	set_ckpt_flags(sbi, CP_ERROR_FLAG);
4056 
4057 	if (!f2fs_hw_is_readonly(sbi)) {
4058 		save_stop_reason(sbi, reason);
4059 
4060 		if (irq_context && !shutdown)
4061 			schedule_work(&sbi->s_error_work);
4062 		else
4063 			f2fs_record_stop_reason(sbi);
4064 	}
4065 
4066 	/*
4067 	 * We force ERRORS_RO behavior when system is rebooting. Otherwise we
4068 	 * could panic during 'reboot -f' as the underlying device got already
4069 	 * disabled.
4070 	 */
4071 	if (F2FS_OPTION(sbi).errors == MOUNT_ERRORS_PANIC &&
4072 				!shutdown && !system_going_down() &&
4073 				!is_sbi_flag_set(sbi, SBI_IS_SHUTDOWN))
4074 		panic("F2FS-fs (device %s): panic forced after error\n",
4075 							sb->s_id);
4076 
4077 	if (shutdown)
4078 		set_sbi_flag(sbi, SBI_IS_SHUTDOWN);
4079 
4080 	/* continue filesystem operators if errors=continue */
4081 	if (continue_fs || f2fs_readonly(sb))
4082 		return;
4083 
4084 	f2fs_warn(sbi, "Remounting filesystem read-only");
4085 	/*
4086 	 * Make sure updated value of ->s_mount_flags will be visible before
4087 	 * ->s_flags update
4088 	 */
4089 	smp_wmb();
4090 	sb->s_flags |= SB_RDONLY;
4091 }
4092 
4093 static void f2fs_record_error_work(struct work_struct *work)
4094 {
4095 	struct f2fs_sb_info *sbi = container_of(work,
4096 					struct f2fs_sb_info, s_error_work);
4097 
4098 	f2fs_record_stop_reason(sbi);
4099 }
4100 
4101 static int f2fs_scan_devices(struct f2fs_sb_info *sbi)
4102 {
4103 	struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi);
4104 	unsigned int max_devices = MAX_DEVICES;
4105 	unsigned int logical_blksize;
4106 	int i;
4107 
4108 	/* Initialize single device information */
4109 	if (!RDEV(0).path[0]) {
4110 		if (!bdev_is_zoned(sbi->sb->s_bdev))
4111 			return 0;
4112 		max_devices = 1;
4113 	}
4114 
4115 	/*
4116 	 * Initialize multiple devices information, or single
4117 	 * zoned block device information.
4118 	 */
4119 	sbi->devs = f2fs_kzalloc(sbi,
4120 				 array_size(max_devices,
4121 					    sizeof(struct f2fs_dev_info)),
4122 				 GFP_KERNEL);
4123 	if (!sbi->devs)
4124 		return -ENOMEM;
4125 
4126 	logical_blksize = bdev_logical_block_size(sbi->sb->s_bdev);
4127 	sbi->aligned_blksize = true;
4128 
4129 	for (i = 0; i < max_devices; i++) {
4130 
4131 		if (i > 0 && !RDEV(i).path[0])
4132 			break;
4133 
4134 		if (max_devices == 1) {
4135 			/* Single zoned block device mount */
4136 			FDEV(0).bdev =
4137 				blkdev_get_by_dev(sbi->sb->s_bdev->bd_dev,
4138 					sbi->sb->s_mode, sbi->sb->s_type);
4139 		} else {
4140 			/* Multi-device mount */
4141 			memcpy(FDEV(i).path, RDEV(i).path, MAX_PATH_LEN);
4142 			FDEV(i).total_segments =
4143 				le32_to_cpu(RDEV(i).total_segments);
4144 			if (i == 0) {
4145 				FDEV(i).start_blk = 0;
4146 				FDEV(i).end_blk = FDEV(i).start_blk +
4147 				    (FDEV(i).total_segments <<
4148 				    sbi->log_blocks_per_seg) - 1 +
4149 				    le32_to_cpu(raw_super->segment0_blkaddr);
4150 			} else {
4151 				FDEV(i).start_blk = FDEV(i - 1).end_blk + 1;
4152 				FDEV(i).end_blk = FDEV(i).start_blk +
4153 					(FDEV(i).total_segments <<
4154 					sbi->log_blocks_per_seg) - 1;
4155 			}
4156 			FDEV(i).bdev = blkdev_get_by_path(FDEV(i).path,
4157 					sbi->sb->s_mode, sbi->sb->s_type);
4158 		}
4159 		if (IS_ERR(FDEV(i).bdev))
4160 			return PTR_ERR(FDEV(i).bdev);
4161 
4162 		/* to release errored devices */
4163 		sbi->s_ndevs = i + 1;
4164 
4165 		if (logical_blksize != bdev_logical_block_size(FDEV(i).bdev))
4166 			sbi->aligned_blksize = false;
4167 
4168 #ifdef CONFIG_BLK_DEV_ZONED
4169 		if (bdev_zoned_model(FDEV(i).bdev) == BLK_ZONED_HM &&
4170 				!f2fs_sb_has_blkzoned(sbi)) {
4171 			f2fs_err(sbi, "Zoned block device feature not enabled");
4172 			return -EINVAL;
4173 		}
4174 		if (bdev_zoned_model(FDEV(i).bdev) != BLK_ZONED_NONE) {
4175 			if (init_blkz_info(sbi, i)) {
4176 				f2fs_err(sbi, "Failed to initialize F2FS blkzone information");
4177 				return -EINVAL;
4178 			}
4179 			if (max_devices == 1)
4180 				break;
4181 			f2fs_info(sbi, "Mount Device [%2d]: %20s, %8u, %8x - %8x (zone: %s)",
4182 				  i, FDEV(i).path,
4183 				  FDEV(i).total_segments,
4184 				  FDEV(i).start_blk, FDEV(i).end_blk,
4185 				  bdev_zoned_model(FDEV(i).bdev) == BLK_ZONED_HA ?
4186 				  "Host-aware" : "Host-managed");
4187 			continue;
4188 		}
4189 #endif
4190 		f2fs_info(sbi, "Mount Device [%2d]: %20s, %8u, %8x - %8x",
4191 			  i, FDEV(i).path,
4192 			  FDEV(i).total_segments,
4193 			  FDEV(i).start_blk, FDEV(i).end_blk);
4194 	}
4195 	f2fs_info(sbi,
4196 		  "IO Block Size: %8ld KB", F2FS_IO_SIZE_KB(sbi));
4197 	return 0;
4198 }
4199 
4200 static int f2fs_setup_casefold(struct f2fs_sb_info *sbi)
4201 {
4202 #if IS_ENABLED(CONFIG_UNICODE)
4203 	if (f2fs_sb_has_casefold(sbi) && !sbi->sb->s_encoding) {
4204 		const struct f2fs_sb_encodings *encoding_info;
4205 		struct unicode_map *encoding;
4206 		__u16 encoding_flags;
4207 
4208 		encoding_info = f2fs_sb_read_encoding(sbi->raw_super);
4209 		if (!encoding_info) {
4210 			f2fs_err(sbi,
4211 				 "Encoding requested by superblock is unknown");
4212 			return -EINVAL;
4213 		}
4214 
4215 		encoding_flags = le16_to_cpu(sbi->raw_super->s_encoding_flags);
4216 		encoding = utf8_load(encoding_info->version);
4217 		if (IS_ERR(encoding)) {
4218 			f2fs_err(sbi,
4219 				 "can't mount with superblock charset: %s-%u.%u.%u "
4220 				 "not supported by the kernel. flags: 0x%x.",
4221 				 encoding_info->name,
4222 				 unicode_major(encoding_info->version),
4223 				 unicode_minor(encoding_info->version),
4224 				 unicode_rev(encoding_info->version),
4225 				 encoding_flags);
4226 			return PTR_ERR(encoding);
4227 		}
4228 		f2fs_info(sbi, "Using encoding defined by superblock: "
4229 			 "%s-%u.%u.%u with flags 0x%hx", encoding_info->name,
4230 			 unicode_major(encoding_info->version),
4231 			 unicode_minor(encoding_info->version),
4232 			 unicode_rev(encoding_info->version),
4233 			 encoding_flags);
4234 
4235 		sbi->sb->s_encoding = encoding;
4236 		sbi->sb->s_encoding_flags = encoding_flags;
4237 	}
4238 #else
4239 	if (f2fs_sb_has_casefold(sbi)) {
4240 		f2fs_err(sbi, "Filesystem with casefold feature cannot be mounted without CONFIG_UNICODE");
4241 		return -EINVAL;
4242 	}
4243 #endif
4244 	return 0;
4245 }
4246 
4247 static void f2fs_tuning_parameters(struct f2fs_sb_info *sbi)
4248 {
4249 	/* adjust parameters according to the volume size */
4250 	if (MAIN_SEGS(sbi) <= SMALL_VOLUME_SEGMENTS) {
4251 		if (f2fs_block_unit_discard(sbi))
4252 			SM_I(sbi)->dcc_info->discard_granularity =
4253 						MIN_DISCARD_GRANULARITY;
4254 		if (!f2fs_lfs_mode(sbi))
4255 			SM_I(sbi)->ipu_policy = BIT(F2FS_IPU_FORCE) |
4256 						BIT(F2FS_IPU_HONOR_OPU_WRITE);
4257 	}
4258 
4259 	sbi->readdir_ra = true;
4260 }
4261 
4262 static int f2fs_fill_super(struct super_block *sb, void *data, int silent)
4263 {
4264 	struct f2fs_sb_info *sbi;
4265 	struct f2fs_super_block *raw_super;
4266 	struct inode *root;
4267 	int err;
4268 	bool skip_recovery = false, need_fsck = false;
4269 	char *options = NULL;
4270 	int recovery, i, valid_super_block;
4271 	struct curseg_info *seg_i;
4272 	int retry_cnt = 1;
4273 #ifdef CONFIG_QUOTA
4274 	bool quota_enabled = false;
4275 #endif
4276 
4277 try_onemore:
4278 	err = -EINVAL;
4279 	raw_super = NULL;
4280 	valid_super_block = -1;
4281 	recovery = 0;
4282 
4283 	/* allocate memory for f2fs-specific super block info */
4284 	sbi = kzalloc(sizeof(struct f2fs_sb_info), GFP_KERNEL);
4285 	if (!sbi)
4286 		return -ENOMEM;
4287 
4288 	sbi->sb = sb;
4289 
4290 	/* initialize locks within allocated memory */
4291 	init_f2fs_rwsem(&sbi->gc_lock);
4292 	mutex_init(&sbi->writepages);
4293 	init_f2fs_rwsem(&sbi->cp_global_sem);
4294 	init_f2fs_rwsem(&sbi->node_write);
4295 	init_f2fs_rwsem(&sbi->node_change);
4296 	spin_lock_init(&sbi->stat_lock);
4297 	init_f2fs_rwsem(&sbi->cp_rwsem);
4298 	init_f2fs_rwsem(&sbi->quota_sem);
4299 	init_waitqueue_head(&sbi->cp_wait);
4300 	spin_lock_init(&sbi->error_lock);
4301 
4302 	for (i = 0; i < NR_INODE_TYPE; i++) {
4303 		INIT_LIST_HEAD(&sbi->inode_list[i]);
4304 		spin_lock_init(&sbi->inode_lock[i]);
4305 	}
4306 	mutex_init(&sbi->flush_lock);
4307 
4308 	/* Load the checksum driver */
4309 	sbi->s_chksum_driver = crypto_alloc_shash("crc32", 0, 0);
4310 	if (IS_ERR(sbi->s_chksum_driver)) {
4311 		f2fs_err(sbi, "Cannot load crc32 driver.");
4312 		err = PTR_ERR(sbi->s_chksum_driver);
4313 		sbi->s_chksum_driver = NULL;
4314 		goto free_sbi;
4315 	}
4316 
4317 	/* set a block size */
4318 	if (unlikely(!sb_set_blocksize(sb, F2FS_BLKSIZE))) {
4319 		f2fs_err(sbi, "unable to set blocksize");
4320 		goto free_sbi;
4321 	}
4322 
4323 	err = read_raw_super_block(sbi, &raw_super, &valid_super_block,
4324 								&recovery);
4325 	if (err)
4326 		goto free_sbi;
4327 
4328 	sb->s_fs_info = sbi;
4329 	sbi->raw_super = raw_super;
4330 
4331 	INIT_WORK(&sbi->s_error_work, f2fs_record_error_work);
4332 	memcpy(sbi->errors, raw_super->s_errors, MAX_F2FS_ERRORS);
4333 	memcpy(sbi->stop_reason, raw_super->s_stop_reason, MAX_STOP_REASON);
4334 
4335 	/* precompute checksum seed for metadata */
4336 	if (f2fs_sb_has_inode_chksum(sbi))
4337 		sbi->s_chksum_seed = f2fs_chksum(sbi, ~0, raw_super->uuid,
4338 						sizeof(raw_super->uuid));
4339 
4340 	default_options(sbi);
4341 	/* parse mount options */
4342 	options = kstrdup((const char *)data, GFP_KERNEL);
4343 	if (data && !options) {
4344 		err = -ENOMEM;
4345 		goto free_sb_buf;
4346 	}
4347 
4348 	err = parse_options(sb, options, false);
4349 	if (err)
4350 		goto free_options;
4351 
4352 	sb->s_maxbytes = max_file_blocks(NULL) <<
4353 				le32_to_cpu(raw_super->log_blocksize);
4354 	sb->s_max_links = F2FS_LINK_MAX;
4355 
4356 	err = f2fs_setup_casefold(sbi);
4357 	if (err)
4358 		goto free_options;
4359 
4360 #ifdef CONFIG_QUOTA
4361 	sb->dq_op = &f2fs_quota_operations;
4362 	sb->s_qcop = &f2fs_quotactl_ops;
4363 	sb->s_quota_types = QTYPE_MASK_USR | QTYPE_MASK_GRP | QTYPE_MASK_PRJ;
4364 
4365 	if (f2fs_sb_has_quota_ino(sbi)) {
4366 		for (i = 0; i < MAXQUOTAS; i++) {
4367 			if (f2fs_qf_ino(sbi->sb, i))
4368 				sbi->nquota_files++;
4369 		}
4370 	}
4371 #endif
4372 
4373 	sb->s_op = &f2fs_sops;
4374 #ifdef CONFIG_FS_ENCRYPTION
4375 	sb->s_cop = &f2fs_cryptops;
4376 #endif
4377 #ifdef CONFIG_FS_VERITY
4378 	sb->s_vop = &f2fs_verityops;
4379 #endif
4380 	sb->s_xattr = f2fs_xattr_handlers;
4381 	sb->s_export_op = &f2fs_export_ops;
4382 	sb->s_magic = F2FS_SUPER_MAGIC;
4383 	sb->s_time_gran = 1;
4384 	sb->s_flags = (sb->s_flags & ~SB_POSIXACL) |
4385 		(test_opt(sbi, POSIX_ACL) ? SB_POSIXACL : 0);
4386 	memcpy(&sb->s_uuid, raw_super->uuid, sizeof(raw_super->uuid));
4387 	sb->s_iflags |= SB_I_CGROUPWB;
4388 
4389 	/* init f2fs-specific super block info */
4390 	sbi->valid_super_block = valid_super_block;
4391 
4392 	/* disallow all the data/node/meta page writes */
4393 	set_sbi_flag(sbi, SBI_POR_DOING);
4394 
4395 	err = f2fs_init_write_merge_io(sbi);
4396 	if (err)
4397 		goto free_bio_info;
4398 
4399 	init_sb_info(sbi);
4400 
4401 	err = f2fs_init_iostat(sbi);
4402 	if (err)
4403 		goto free_bio_info;
4404 
4405 	err = init_percpu_info(sbi);
4406 	if (err)
4407 		goto free_iostat;
4408 
4409 	if (F2FS_IO_ALIGNED(sbi)) {
4410 		sbi->write_io_dummy =
4411 			mempool_create_page_pool(2 * (F2FS_IO_SIZE(sbi) - 1), 0);
4412 		if (!sbi->write_io_dummy) {
4413 			err = -ENOMEM;
4414 			goto free_percpu;
4415 		}
4416 	}
4417 
4418 	/* init per sbi slab cache */
4419 	err = f2fs_init_xattr_caches(sbi);
4420 	if (err)
4421 		goto free_io_dummy;
4422 	err = f2fs_init_page_array_cache(sbi);
4423 	if (err)
4424 		goto free_xattr_cache;
4425 
4426 	/* get an inode for meta space */
4427 	sbi->meta_inode = f2fs_iget(sb, F2FS_META_INO(sbi));
4428 	if (IS_ERR(sbi->meta_inode)) {
4429 		f2fs_err(sbi, "Failed to read F2FS meta data inode");
4430 		err = PTR_ERR(sbi->meta_inode);
4431 		goto free_page_array_cache;
4432 	}
4433 
4434 	err = f2fs_get_valid_checkpoint(sbi);
4435 	if (err) {
4436 		f2fs_err(sbi, "Failed to get valid F2FS checkpoint");
4437 		goto free_meta_inode;
4438 	}
4439 
4440 	if (__is_set_ckpt_flags(F2FS_CKPT(sbi), CP_QUOTA_NEED_FSCK_FLAG))
4441 		set_sbi_flag(sbi, SBI_QUOTA_NEED_REPAIR);
4442 	if (__is_set_ckpt_flags(F2FS_CKPT(sbi), CP_DISABLED_QUICK_FLAG)) {
4443 		set_sbi_flag(sbi, SBI_CP_DISABLED_QUICK);
4444 		sbi->interval_time[DISABLE_TIME] = DEF_DISABLE_QUICK_INTERVAL;
4445 	}
4446 
4447 	if (__is_set_ckpt_flags(F2FS_CKPT(sbi), CP_FSCK_FLAG))
4448 		set_sbi_flag(sbi, SBI_NEED_FSCK);
4449 
4450 	/* Initialize device list */
4451 	err = f2fs_scan_devices(sbi);
4452 	if (err) {
4453 		f2fs_err(sbi, "Failed to find devices");
4454 		goto free_devices;
4455 	}
4456 
4457 	err = f2fs_init_post_read_wq(sbi);
4458 	if (err) {
4459 		f2fs_err(sbi, "Failed to initialize post read workqueue");
4460 		goto free_devices;
4461 	}
4462 
4463 	sbi->total_valid_node_count =
4464 				le32_to_cpu(sbi->ckpt->valid_node_count);
4465 	percpu_counter_set(&sbi->total_valid_inode_count,
4466 				le32_to_cpu(sbi->ckpt->valid_inode_count));
4467 	sbi->user_block_count = le64_to_cpu(sbi->ckpt->user_block_count);
4468 	sbi->total_valid_block_count =
4469 				le64_to_cpu(sbi->ckpt->valid_block_count);
4470 	sbi->last_valid_block_count = sbi->total_valid_block_count;
4471 	sbi->reserved_blocks = 0;
4472 	sbi->current_reserved_blocks = 0;
4473 	limit_reserve_root(sbi);
4474 	adjust_unusable_cap_perc(sbi);
4475 
4476 	f2fs_init_extent_cache_info(sbi);
4477 
4478 	f2fs_init_ino_entry_info(sbi);
4479 
4480 	f2fs_init_fsync_node_info(sbi);
4481 
4482 	/* setup checkpoint request control and start checkpoint issue thread */
4483 	f2fs_init_ckpt_req_control(sbi);
4484 	if (!f2fs_readonly(sb) && !test_opt(sbi, DISABLE_CHECKPOINT) &&
4485 			test_opt(sbi, MERGE_CHECKPOINT)) {
4486 		err = f2fs_start_ckpt_thread(sbi);
4487 		if (err) {
4488 			f2fs_err(sbi,
4489 			    "Failed to start F2FS issue_checkpoint_thread (%d)",
4490 			    err);
4491 			goto stop_ckpt_thread;
4492 		}
4493 	}
4494 
4495 	/* setup f2fs internal modules */
4496 	err = f2fs_build_segment_manager(sbi);
4497 	if (err) {
4498 		f2fs_err(sbi, "Failed to initialize F2FS segment manager (%d)",
4499 			 err);
4500 		goto free_sm;
4501 	}
4502 	err = f2fs_build_node_manager(sbi);
4503 	if (err) {
4504 		f2fs_err(sbi, "Failed to initialize F2FS node manager (%d)",
4505 			 err);
4506 		goto free_nm;
4507 	}
4508 
4509 	err = adjust_reserved_segment(sbi);
4510 	if (err)
4511 		goto free_nm;
4512 
4513 	/* For write statistics */
4514 	sbi->sectors_written_start = f2fs_get_sectors_written(sbi);
4515 
4516 	/* Read accumulated write IO statistics if exists */
4517 	seg_i = CURSEG_I(sbi, CURSEG_HOT_NODE);
4518 	if (__exist_node_summaries(sbi))
4519 		sbi->kbytes_written =
4520 			le64_to_cpu(seg_i->journal->info.kbytes_written);
4521 
4522 	f2fs_build_gc_manager(sbi);
4523 
4524 	err = f2fs_build_stats(sbi);
4525 	if (err)
4526 		goto free_nm;
4527 
4528 	/* get an inode for node space */
4529 	sbi->node_inode = f2fs_iget(sb, F2FS_NODE_INO(sbi));
4530 	if (IS_ERR(sbi->node_inode)) {
4531 		f2fs_err(sbi, "Failed to read node inode");
4532 		err = PTR_ERR(sbi->node_inode);
4533 		goto free_stats;
4534 	}
4535 
4536 	/* read root inode and dentry */
4537 	root = f2fs_iget(sb, F2FS_ROOT_INO(sbi));
4538 	if (IS_ERR(root)) {
4539 		f2fs_err(sbi, "Failed to read root inode");
4540 		err = PTR_ERR(root);
4541 		goto free_node_inode;
4542 	}
4543 	if (!S_ISDIR(root->i_mode) || !root->i_blocks ||
4544 			!root->i_size || !root->i_nlink) {
4545 		iput(root);
4546 		err = -EINVAL;
4547 		goto free_node_inode;
4548 	}
4549 
4550 	sb->s_root = d_make_root(root); /* allocate root dentry */
4551 	if (!sb->s_root) {
4552 		err = -ENOMEM;
4553 		goto free_node_inode;
4554 	}
4555 
4556 	err = f2fs_init_compress_inode(sbi);
4557 	if (err)
4558 		goto free_root_inode;
4559 
4560 	err = f2fs_register_sysfs(sbi);
4561 	if (err)
4562 		goto free_compress_inode;
4563 
4564 #ifdef CONFIG_QUOTA
4565 	/* Enable quota usage during mount */
4566 	if (f2fs_sb_has_quota_ino(sbi) && !f2fs_readonly(sb)) {
4567 		err = f2fs_enable_quotas(sb);
4568 		if (err)
4569 			f2fs_err(sbi, "Cannot turn on quotas: error %d", err);
4570 	}
4571 
4572 	quota_enabled = f2fs_recover_quota_begin(sbi);
4573 #endif
4574 	/* if there are any orphan inodes, free them */
4575 	err = f2fs_recover_orphan_inodes(sbi);
4576 	if (err)
4577 		goto free_meta;
4578 
4579 	if (unlikely(is_set_ckpt_flags(sbi, CP_DISABLED_FLAG)))
4580 		goto reset_checkpoint;
4581 
4582 	/* recover fsynced data */
4583 	if (!test_opt(sbi, DISABLE_ROLL_FORWARD) &&
4584 			!test_opt(sbi, NORECOVERY)) {
4585 		/*
4586 		 * mount should be failed, when device has readonly mode, and
4587 		 * previous checkpoint was not done by clean system shutdown.
4588 		 */
4589 		if (f2fs_hw_is_readonly(sbi)) {
4590 			if (!is_set_ckpt_flags(sbi, CP_UMOUNT_FLAG)) {
4591 				err = f2fs_recover_fsync_data(sbi, true);
4592 				if (err > 0) {
4593 					err = -EROFS;
4594 					f2fs_err(sbi, "Need to recover fsync data, but "
4595 						"write access unavailable, please try "
4596 						"mount w/ disable_roll_forward or norecovery");
4597 				}
4598 				if (err < 0)
4599 					goto free_meta;
4600 			}
4601 			f2fs_info(sbi, "write access unavailable, skipping recovery");
4602 			goto reset_checkpoint;
4603 		}
4604 
4605 		if (need_fsck)
4606 			set_sbi_flag(sbi, SBI_NEED_FSCK);
4607 
4608 		if (skip_recovery)
4609 			goto reset_checkpoint;
4610 
4611 		err = f2fs_recover_fsync_data(sbi, false);
4612 		if (err < 0) {
4613 			if (err != -ENOMEM)
4614 				skip_recovery = true;
4615 			need_fsck = true;
4616 			f2fs_err(sbi, "Cannot recover all fsync data errno=%d",
4617 				 err);
4618 			goto free_meta;
4619 		}
4620 	} else {
4621 		err = f2fs_recover_fsync_data(sbi, true);
4622 
4623 		if (!f2fs_readonly(sb) && err > 0) {
4624 			err = -EINVAL;
4625 			f2fs_err(sbi, "Need to recover fsync data");
4626 			goto free_meta;
4627 		}
4628 	}
4629 
4630 #ifdef CONFIG_QUOTA
4631 	f2fs_recover_quota_end(sbi, quota_enabled);
4632 #endif
4633 
4634 	/*
4635 	 * If the f2fs is not readonly and fsync data recovery succeeds,
4636 	 * check zoned block devices' write pointer consistency.
4637 	 */
4638 	if (!err && !f2fs_readonly(sb) && f2fs_sb_has_blkzoned(sbi)) {
4639 		err = f2fs_check_write_pointer(sbi);
4640 		if (err)
4641 			goto free_meta;
4642 	}
4643 
4644 reset_checkpoint:
4645 	f2fs_init_inmem_curseg(sbi);
4646 
4647 	/* f2fs_recover_fsync_data() cleared this already */
4648 	clear_sbi_flag(sbi, SBI_POR_DOING);
4649 
4650 	if (test_opt(sbi, DISABLE_CHECKPOINT)) {
4651 		err = f2fs_disable_checkpoint(sbi);
4652 		if (err)
4653 			goto sync_free_meta;
4654 	} else if (is_set_ckpt_flags(sbi, CP_DISABLED_FLAG)) {
4655 		f2fs_enable_checkpoint(sbi);
4656 	}
4657 
4658 	/*
4659 	 * If filesystem is not mounted as read-only then
4660 	 * do start the gc_thread.
4661 	 */
4662 	if ((F2FS_OPTION(sbi).bggc_mode != BGGC_MODE_OFF ||
4663 		test_opt(sbi, GC_MERGE)) && !f2fs_readonly(sb)) {
4664 		/* After POR, we can run background GC thread.*/
4665 		err = f2fs_start_gc_thread(sbi);
4666 		if (err)
4667 			goto sync_free_meta;
4668 	}
4669 	kvfree(options);
4670 
4671 	/* recover broken superblock */
4672 	if (recovery) {
4673 		err = f2fs_commit_super(sbi, true);
4674 		f2fs_info(sbi, "Try to recover %dth superblock, ret: %d",
4675 			  sbi->valid_super_block ? 1 : 2, err);
4676 	}
4677 
4678 	f2fs_join_shrinker(sbi);
4679 
4680 	f2fs_tuning_parameters(sbi);
4681 
4682 	f2fs_notice(sbi, "Mounted with checkpoint version = %llx",
4683 		    cur_cp_version(F2FS_CKPT(sbi)));
4684 	f2fs_update_time(sbi, CP_TIME);
4685 	f2fs_update_time(sbi, REQ_TIME);
4686 	clear_sbi_flag(sbi, SBI_CP_DISABLED_QUICK);
4687 	return 0;
4688 
4689 sync_free_meta:
4690 	/* safe to flush all the data */
4691 	sync_filesystem(sbi->sb);
4692 	retry_cnt = 0;
4693 
4694 free_meta:
4695 #ifdef CONFIG_QUOTA
4696 	f2fs_truncate_quota_inode_pages(sb);
4697 	if (f2fs_sb_has_quota_ino(sbi) && !f2fs_readonly(sb))
4698 		f2fs_quota_off_umount(sbi->sb);
4699 #endif
4700 	/*
4701 	 * Some dirty meta pages can be produced by f2fs_recover_orphan_inodes()
4702 	 * failed by EIO. Then, iput(node_inode) can trigger balance_fs_bg()
4703 	 * followed by f2fs_write_checkpoint() through f2fs_write_node_pages(), which
4704 	 * falls into an infinite loop in f2fs_sync_meta_pages().
4705 	 */
4706 	truncate_inode_pages_final(META_MAPPING(sbi));
4707 	/* evict some inodes being cached by GC */
4708 	evict_inodes(sb);
4709 	f2fs_unregister_sysfs(sbi);
4710 free_compress_inode:
4711 	f2fs_destroy_compress_inode(sbi);
4712 free_root_inode:
4713 	dput(sb->s_root);
4714 	sb->s_root = NULL;
4715 free_node_inode:
4716 	f2fs_release_ino_entry(sbi, true);
4717 	truncate_inode_pages_final(NODE_MAPPING(sbi));
4718 	iput(sbi->node_inode);
4719 	sbi->node_inode = NULL;
4720 free_stats:
4721 	f2fs_destroy_stats(sbi);
4722 free_nm:
4723 	/* stop discard thread before destroying node manager */
4724 	f2fs_stop_discard_thread(sbi);
4725 	f2fs_destroy_node_manager(sbi);
4726 free_sm:
4727 	f2fs_destroy_segment_manager(sbi);
4728 stop_ckpt_thread:
4729 	f2fs_stop_ckpt_thread(sbi);
4730 	/* flush s_error_work before sbi destroy */
4731 	flush_work(&sbi->s_error_work);
4732 	f2fs_destroy_post_read_wq(sbi);
4733 free_devices:
4734 	destroy_device_list(sbi);
4735 	kvfree(sbi->ckpt);
4736 free_meta_inode:
4737 	make_bad_inode(sbi->meta_inode);
4738 	iput(sbi->meta_inode);
4739 	sbi->meta_inode = NULL;
4740 free_page_array_cache:
4741 	f2fs_destroy_page_array_cache(sbi);
4742 free_xattr_cache:
4743 	f2fs_destroy_xattr_caches(sbi);
4744 free_io_dummy:
4745 	mempool_destroy(sbi->write_io_dummy);
4746 free_percpu:
4747 	destroy_percpu_info(sbi);
4748 free_iostat:
4749 	f2fs_destroy_iostat(sbi);
4750 free_bio_info:
4751 	for (i = 0; i < NR_PAGE_TYPE; i++)
4752 		kvfree(sbi->write_io[i]);
4753 
4754 #if IS_ENABLED(CONFIG_UNICODE)
4755 	utf8_unload(sb->s_encoding);
4756 	sb->s_encoding = NULL;
4757 #endif
4758 free_options:
4759 #ifdef CONFIG_QUOTA
4760 	for (i = 0; i < MAXQUOTAS; i++)
4761 		kfree(F2FS_OPTION(sbi).s_qf_names[i]);
4762 #endif
4763 	fscrypt_free_dummy_policy(&F2FS_OPTION(sbi).dummy_enc_policy);
4764 	kvfree(options);
4765 free_sb_buf:
4766 	kfree(raw_super);
4767 free_sbi:
4768 	if (sbi->s_chksum_driver)
4769 		crypto_free_shash(sbi->s_chksum_driver);
4770 	kfree(sbi);
4771 
4772 	/* give only one another chance */
4773 	if (retry_cnt > 0 && skip_recovery) {
4774 		retry_cnt--;
4775 		shrink_dcache_sb(sb);
4776 		goto try_onemore;
4777 	}
4778 	return err;
4779 }
4780 
4781 static struct dentry *f2fs_mount(struct file_system_type *fs_type, int flags,
4782 			const char *dev_name, void *data)
4783 {
4784 	return mount_bdev(fs_type, flags, dev_name, data, f2fs_fill_super);
4785 }
4786 
4787 static void kill_f2fs_super(struct super_block *sb)
4788 {
4789 	if (sb->s_root) {
4790 		struct f2fs_sb_info *sbi = F2FS_SB(sb);
4791 
4792 		set_sbi_flag(sbi, SBI_IS_CLOSE);
4793 		f2fs_stop_gc_thread(sbi);
4794 		f2fs_stop_discard_thread(sbi);
4795 
4796 #ifdef CONFIG_F2FS_FS_COMPRESSION
4797 		/*
4798 		 * latter evict_inode() can bypass checking and invalidating
4799 		 * compress inode cache.
4800 		 */
4801 		if (test_opt(sbi, COMPRESS_CACHE))
4802 			truncate_inode_pages_final(COMPRESS_MAPPING(sbi));
4803 #endif
4804 
4805 		if (is_sbi_flag_set(sbi, SBI_IS_DIRTY) ||
4806 				!is_set_ckpt_flags(sbi, CP_UMOUNT_FLAG)) {
4807 			struct cp_control cpc = {
4808 				.reason = CP_UMOUNT,
4809 			};
4810 			f2fs_write_checkpoint(sbi, &cpc);
4811 		}
4812 
4813 		if (is_sbi_flag_set(sbi, SBI_IS_RECOVERED) && f2fs_readonly(sb))
4814 			sb->s_flags &= ~SB_RDONLY;
4815 	}
4816 	kill_block_super(sb);
4817 }
4818 
4819 static struct file_system_type f2fs_fs_type = {
4820 	.owner		= THIS_MODULE,
4821 	.name		= "f2fs",
4822 	.mount		= f2fs_mount,
4823 	.kill_sb	= kill_f2fs_super,
4824 	.fs_flags	= FS_REQUIRES_DEV | FS_ALLOW_IDMAP,
4825 };
4826 MODULE_ALIAS_FS("f2fs");
4827 
4828 static int __init init_inodecache(void)
4829 {
4830 	f2fs_inode_cachep = kmem_cache_create("f2fs_inode_cache",
4831 			sizeof(struct f2fs_inode_info), 0,
4832 			SLAB_RECLAIM_ACCOUNT|SLAB_ACCOUNT, NULL);
4833 	return f2fs_inode_cachep ? 0 : -ENOMEM;
4834 }
4835 
4836 static void destroy_inodecache(void)
4837 {
4838 	/*
4839 	 * Make sure all delayed rcu free inodes are flushed before we
4840 	 * destroy cache.
4841 	 */
4842 	rcu_barrier();
4843 	kmem_cache_destroy(f2fs_inode_cachep);
4844 }
4845 
4846 static int __init init_f2fs_fs(void)
4847 {
4848 	int err;
4849 
4850 	if (PAGE_SIZE != F2FS_BLKSIZE) {
4851 		printk("F2FS not supported on PAGE_SIZE(%lu) != %d\n",
4852 				PAGE_SIZE, F2FS_BLKSIZE);
4853 		return -EINVAL;
4854 	}
4855 
4856 	err = init_inodecache();
4857 	if (err)
4858 		goto fail;
4859 	err = f2fs_create_node_manager_caches();
4860 	if (err)
4861 		goto free_inodecache;
4862 	err = f2fs_create_segment_manager_caches();
4863 	if (err)
4864 		goto free_node_manager_caches;
4865 	err = f2fs_create_checkpoint_caches();
4866 	if (err)
4867 		goto free_segment_manager_caches;
4868 	err = f2fs_create_recovery_cache();
4869 	if (err)
4870 		goto free_checkpoint_caches;
4871 	err = f2fs_create_extent_cache();
4872 	if (err)
4873 		goto free_recovery_cache;
4874 	err = f2fs_create_garbage_collection_cache();
4875 	if (err)
4876 		goto free_extent_cache;
4877 	err = f2fs_init_sysfs();
4878 	if (err)
4879 		goto free_garbage_collection_cache;
4880 	err = register_shrinker(&f2fs_shrinker_info, "f2fs-shrinker");
4881 	if (err)
4882 		goto free_sysfs;
4883 	err = register_filesystem(&f2fs_fs_type);
4884 	if (err)
4885 		goto free_shrinker;
4886 	f2fs_create_root_stats();
4887 	err = f2fs_init_post_read_processing();
4888 	if (err)
4889 		goto free_root_stats;
4890 	err = f2fs_init_iostat_processing();
4891 	if (err)
4892 		goto free_post_read;
4893 	err = f2fs_init_bio_entry_cache();
4894 	if (err)
4895 		goto free_iostat;
4896 	err = f2fs_init_bioset();
4897 	if (err)
4898 		goto free_bio_entry_cache;
4899 	err = f2fs_init_compress_mempool();
4900 	if (err)
4901 		goto free_bioset;
4902 	err = f2fs_init_compress_cache();
4903 	if (err)
4904 		goto free_compress_mempool;
4905 	err = f2fs_create_casefold_cache();
4906 	if (err)
4907 		goto free_compress_cache;
4908 	return 0;
4909 free_compress_cache:
4910 	f2fs_destroy_compress_cache();
4911 free_compress_mempool:
4912 	f2fs_destroy_compress_mempool();
4913 free_bioset:
4914 	f2fs_destroy_bioset();
4915 free_bio_entry_cache:
4916 	f2fs_destroy_bio_entry_cache();
4917 free_iostat:
4918 	f2fs_destroy_iostat_processing();
4919 free_post_read:
4920 	f2fs_destroy_post_read_processing();
4921 free_root_stats:
4922 	f2fs_destroy_root_stats();
4923 	unregister_filesystem(&f2fs_fs_type);
4924 free_shrinker:
4925 	unregister_shrinker(&f2fs_shrinker_info);
4926 free_sysfs:
4927 	f2fs_exit_sysfs();
4928 free_garbage_collection_cache:
4929 	f2fs_destroy_garbage_collection_cache();
4930 free_extent_cache:
4931 	f2fs_destroy_extent_cache();
4932 free_recovery_cache:
4933 	f2fs_destroy_recovery_cache();
4934 free_checkpoint_caches:
4935 	f2fs_destroy_checkpoint_caches();
4936 free_segment_manager_caches:
4937 	f2fs_destroy_segment_manager_caches();
4938 free_node_manager_caches:
4939 	f2fs_destroy_node_manager_caches();
4940 free_inodecache:
4941 	destroy_inodecache();
4942 fail:
4943 	return err;
4944 }
4945 
4946 static void __exit exit_f2fs_fs(void)
4947 {
4948 	f2fs_destroy_casefold_cache();
4949 	f2fs_destroy_compress_cache();
4950 	f2fs_destroy_compress_mempool();
4951 	f2fs_destroy_bioset();
4952 	f2fs_destroy_bio_entry_cache();
4953 	f2fs_destroy_iostat_processing();
4954 	f2fs_destroy_post_read_processing();
4955 	f2fs_destroy_root_stats();
4956 	unregister_filesystem(&f2fs_fs_type);
4957 	unregister_shrinker(&f2fs_shrinker_info);
4958 	f2fs_exit_sysfs();
4959 	f2fs_destroy_garbage_collection_cache();
4960 	f2fs_destroy_extent_cache();
4961 	f2fs_destroy_recovery_cache();
4962 	f2fs_destroy_checkpoint_caches();
4963 	f2fs_destroy_segment_manager_caches();
4964 	f2fs_destroy_node_manager_caches();
4965 	destroy_inodecache();
4966 }
4967 
4968 module_init(init_f2fs_fs)
4969 module_exit(exit_f2fs_fs)
4970 
4971 MODULE_AUTHOR("Samsung Electronics's Praesto Team");
4972 MODULE_DESCRIPTION("Flash Friendly File System");
4973 MODULE_LICENSE("GPL");
4974 MODULE_SOFTDEP("pre: crc32");
4975 
4976