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