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