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