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