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