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