GNU Linux-libre 5.4.257-gnu1
[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/statfs.h>
12 #include <linux/buffer_head.h>
13 #include <linux/backing-dev.h>
14 #include <linux/kthread.h>
15 #include <linux/parser.h>
16 #include <linux/mount.h>
17 #include <linux/seq_file.h>
18 #include <linux/proc_fs.h>
19 #include <linux/random.h>
20 #include <linux/exportfs.h>
21 #include <linux/blkdev.h>
22 #include <linux/quotaops.h>
23 #include <linux/f2fs_fs.h>
24 #include <linux/sysfs.h>
25 #include <linux/quota.h>
26 #include <linux/unicode.h>
27
28 #include "f2fs.h"
29 #include "node.h"
30 #include "segment.h"
31 #include "xattr.h"
32 #include "gc.h"
33 #include "trace.h"
34
35 #define CREATE_TRACE_POINTS
36 #include <trace/events/f2fs.h>
37
38 static struct kmem_cache *f2fs_inode_cachep;
39
40 #ifdef CONFIG_F2FS_FAULT_INJECTION
41
42 const char *f2fs_fault_name[FAULT_MAX] = {
43         [FAULT_KMALLOC]         = "kmalloc",
44         [FAULT_KVMALLOC]        = "kvmalloc",
45         [FAULT_PAGE_ALLOC]      = "page alloc",
46         [FAULT_PAGE_GET]        = "page get",
47         [FAULT_ALLOC_BIO]       = "alloc bio",
48         [FAULT_ALLOC_NID]       = "alloc nid",
49         [FAULT_ORPHAN]          = "orphan",
50         [FAULT_BLOCK]           = "no more block",
51         [FAULT_DIR_DEPTH]       = "too big dir depth",
52         [FAULT_EVICT_INODE]     = "evict_inode fail",
53         [FAULT_TRUNCATE]        = "truncate fail",
54         [FAULT_READ_IO]         = "read IO error",
55         [FAULT_CHECKPOINT]      = "checkpoint error",
56         [FAULT_DISCARD]         = "discard error",
57         [FAULT_WRITE_IO]        = "write IO error",
58 };
59
60 void f2fs_build_fault_attr(struct f2fs_sb_info *sbi, unsigned int rate,
61                                                         unsigned int type)
62 {
63         struct f2fs_fault_info *ffi = &F2FS_OPTION(sbi).fault_info;
64
65         if (rate) {
66                 atomic_set(&ffi->inject_ops, 0);
67                 ffi->inject_rate = rate;
68         }
69
70         if (type)
71                 ffi->inject_type = type;
72
73         if (!rate && !type)
74                 memset(ffi, 0, sizeof(struct f2fs_fault_info));
75 }
76 #endif
77
78 /* f2fs-wide shrinker description */
79 static struct shrinker f2fs_shrinker_info = {
80         .scan_objects = f2fs_shrink_scan,
81         .count_objects = f2fs_shrink_count,
82         .seeks = DEFAULT_SEEKS,
83 };
84
85 enum {
86         Opt_gc_background,
87         Opt_disable_roll_forward,
88         Opt_norecovery,
89         Opt_discard,
90         Opt_nodiscard,
91         Opt_noheap,
92         Opt_heap,
93         Opt_user_xattr,
94         Opt_nouser_xattr,
95         Opt_acl,
96         Opt_noacl,
97         Opt_active_logs,
98         Opt_disable_ext_identify,
99         Opt_inline_xattr,
100         Opt_noinline_xattr,
101         Opt_inline_xattr_size,
102         Opt_inline_data,
103         Opt_inline_dentry,
104         Opt_noinline_dentry,
105         Opt_flush_merge,
106         Opt_noflush_merge,
107         Opt_nobarrier,
108         Opt_fastboot,
109         Opt_extent_cache,
110         Opt_noextent_cache,
111         Opt_noinline_data,
112         Opt_data_flush,
113         Opt_reserve_root,
114         Opt_resgid,
115         Opt_resuid,
116         Opt_mode,
117         Opt_io_size_bits,
118         Opt_fault_injection,
119         Opt_fault_type,
120         Opt_lazytime,
121         Opt_nolazytime,
122         Opt_quota,
123         Opt_noquota,
124         Opt_usrquota,
125         Opt_grpquota,
126         Opt_prjquota,
127         Opt_usrjquota,
128         Opt_grpjquota,
129         Opt_prjjquota,
130         Opt_offusrjquota,
131         Opt_offgrpjquota,
132         Opt_offprjjquota,
133         Opt_jqfmt_vfsold,
134         Opt_jqfmt_vfsv0,
135         Opt_jqfmt_vfsv1,
136         Opt_whint,
137         Opt_alloc,
138         Opt_fsync,
139         Opt_test_dummy_encryption,
140         Opt_checkpoint_disable,
141         Opt_checkpoint_disable_cap,
142         Opt_checkpoint_disable_cap_perc,
143         Opt_checkpoint_enable,
144         Opt_err,
145 };
146
147 static match_table_t f2fs_tokens = {
148         {Opt_gc_background, "background_gc=%s"},
149         {Opt_disable_roll_forward, "disable_roll_forward"},
150         {Opt_norecovery, "norecovery"},
151         {Opt_discard, "discard"},
152         {Opt_nodiscard, "nodiscard"},
153         {Opt_noheap, "no_heap"},
154         {Opt_heap, "heap"},
155         {Opt_user_xattr, "user_xattr"},
156         {Opt_nouser_xattr, "nouser_xattr"},
157         {Opt_acl, "acl"},
158         {Opt_noacl, "noacl"},
159         {Opt_active_logs, "active_logs=%u"},
160         {Opt_disable_ext_identify, "disable_ext_identify"},
161         {Opt_inline_xattr, "inline_xattr"},
162         {Opt_noinline_xattr, "noinline_xattr"},
163         {Opt_inline_xattr_size, "inline_xattr_size=%u"},
164         {Opt_inline_data, "inline_data"},
165         {Opt_inline_dentry, "inline_dentry"},
166         {Opt_noinline_dentry, "noinline_dentry"},
167         {Opt_flush_merge, "flush_merge"},
168         {Opt_noflush_merge, "noflush_merge"},
169         {Opt_nobarrier, "nobarrier"},
170         {Opt_fastboot, "fastboot"},
171         {Opt_extent_cache, "extent_cache"},
172         {Opt_noextent_cache, "noextent_cache"},
173         {Opt_noinline_data, "noinline_data"},
174         {Opt_data_flush, "data_flush"},
175         {Opt_reserve_root, "reserve_root=%u"},
176         {Opt_resgid, "resgid=%u"},
177         {Opt_resuid, "resuid=%u"},
178         {Opt_mode, "mode=%s"},
179         {Opt_io_size_bits, "io_bits=%u"},
180         {Opt_fault_injection, "fault_injection=%u"},
181         {Opt_fault_type, "fault_type=%u"},
182         {Opt_lazytime, "lazytime"},
183         {Opt_nolazytime, "nolazytime"},
184         {Opt_quota, "quota"},
185         {Opt_noquota, "noquota"},
186         {Opt_usrquota, "usrquota"},
187         {Opt_grpquota, "grpquota"},
188         {Opt_prjquota, "prjquota"},
189         {Opt_usrjquota, "usrjquota=%s"},
190         {Opt_grpjquota, "grpjquota=%s"},
191         {Opt_prjjquota, "prjjquota=%s"},
192         {Opt_offusrjquota, "usrjquota="},
193         {Opt_offgrpjquota, "grpjquota="},
194         {Opt_offprjjquota, "prjjquota="},
195         {Opt_jqfmt_vfsold, "jqfmt=vfsold"},
196         {Opt_jqfmt_vfsv0, "jqfmt=vfsv0"},
197         {Opt_jqfmt_vfsv1, "jqfmt=vfsv1"},
198         {Opt_whint, "whint_mode=%s"},
199         {Opt_alloc, "alloc_mode=%s"},
200         {Opt_fsync, "fsync_mode=%s"},
201         {Opt_test_dummy_encryption, "test_dummy_encryption"},
202         {Opt_checkpoint_disable, "checkpoint=disable"},
203         {Opt_checkpoint_disable_cap, "checkpoint=disable:%u"},
204         {Opt_checkpoint_disable_cap_perc, "checkpoint=disable:%u%%"},
205         {Opt_checkpoint_enable, "checkpoint=enable"},
206         {Opt_err, NULL},
207 };
208
209 void f2fs_printk(struct f2fs_sb_info *sbi, const char *fmt, ...)
210 {
211         struct va_format vaf;
212         va_list args;
213         int level;
214
215         va_start(args, fmt);
216
217         level = printk_get_level(fmt);
218         vaf.fmt = printk_skip_level(fmt);
219         vaf.va = &args;
220         printk("%c%cF2FS-fs (%s): %pV\n",
221                KERN_SOH_ASCII, level, sbi->sb->s_id, &vaf);
222
223         va_end(args);
224 }
225
226 #ifdef CONFIG_UNICODE
227 static const struct f2fs_sb_encodings {
228         __u16 magic;
229         char *name;
230         char *version;
231 } f2fs_sb_encoding_map[] = {
232         {F2FS_ENC_UTF8_12_1, "utf8", "12.1.0"},
233 };
234
235 static int f2fs_sb_read_encoding(const struct f2fs_super_block *sb,
236                                  const struct f2fs_sb_encodings **encoding,
237                                  __u16 *flags)
238 {
239         __u16 magic = le16_to_cpu(sb->s_encoding);
240         int i;
241
242         for (i = 0; i < ARRAY_SIZE(f2fs_sb_encoding_map); i++)
243                 if (magic == f2fs_sb_encoding_map[i].magic)
244                         break;
245
246         if (i >= ARRAY_SIZE(f2fs_sb_encoding_map))
247                 return -EINVAL;
248
249         *encoding = &f2fs_sb_encoding_map[i];
250         *flags = le16_to_cpu(sb->s_encoding_flags);
251
252         return 0;
253 }
254 #endif
255
256 static inline void limit_reserve_root(struct f2fs_sb_info *sbi)
257 {
258         block_t limit = min((sbi->user_block_count >> 3),
259                         sbi->user_block_count - sbi->reserved_blocks);
260
261         /* limit is 12.5% */
262         if (test_opt(sbi, RESERVE_ROOT) &&
263                         F2FS_OPTION(sbi).root_reserved_blocks > limit) {
264                 F2FS_OPTION(sbi).root_reserved_blocks = limit;
265                 f2fs_info(sbi, "Reduce reserved blocks for root = %u",
266                           F2FS_OPTION(sbi).root_reserved_blocks);
267         }
268         if (!test_opt(sbi, RESERVE_ROOT) &&
269                 (!uid_eq(F2FS_OPTION(sbi).s_resuid,
270                                 make_kuid(&init_user_ns, F2FS_DEF_RESUID)) ||
271                 !gid_eq(F2FS_OPTION(sbi).s_resgid,
272                                 make_kgid(&init_user_ns, F2FS_DEF_RESGID))))
273                 f2fs_info(sbi, "Ignore s_resuid=%u, s_resgid=%u w/o reserve_root",
274                           from_kuid_munged(&init_user_ns,
275                                            F2FS_OPTION(sbi).s_resuid),
276                           from_kgid_munged(&init_user_ns,
277                                            F2FS_OPTION(sbi).s_resgid));
278 }
279
280 static inline int adjust_reserved_segment(struct f2fs_sb_info *sbi)
281 {
282         unsigned int sec_blks = sbi->blocks_per_seg * sbi->segs_per_sec;
283         unsigned int avg_vblocks;
284         unsigned int wanted_reserved_segments;
285         block_t avail_user_block_count;
286
287         if (!F2FS_IO_ALIGNED(sbi))
288                 return 0;
289
290         /* average valid block count in section in worst case */
291         avg_vblocks = sec_blks / F2FS_IO_SIZE(sbi);
292
293         /*
294          * we need enough free space when migrating one section in worst case
295          */
296         wanted_reserved_segments = (F2FS_IO_SIZE(sbi) / avg_vblocks) *
297                                                 reserved_segments(sbi);
298         wanted_reserved_segments -= reserved_segments(sbi);
299
300         avail_user_block_count = sbi->user_block_count -
301                                 sbi->current_reserved_blocks -
302                                 F2FS_OPTION(sbi).root_reserved_blocks;
303
304         if (wanted_reserved_segments * sbi->blocks_per_seg >
305                                         avail_user_block_count) {
306                 f2fs_err(sbi, "IO align feature can't grab additional reserved segment: %u, available segments: %u",
307                         wanted_reserved_segments,
308                         avail_user_block_count >> sbi->log_blocks_per_seg);
309                 return -ENOSPC;
310         }
311
312         SM_I(sbi)->additional_reserved_segments = wanted_reserved_segments;
313
314         f2fs_info(sbi, "IO align feature needs additional reserved segment: %u",
315                          wanted_reserved_segments);
316
317         return 0;
318 }
319
320 static inline void adjust_unusable_cap_perc(struct f2fs_sb_info *sbi)
321 {
322         if (!F2FS_OPTION(sbi).unusable_cap_perc)
323                 return;
324
325         if (F2FS_OPTION(sbi).unusable_cap_perc == 100)
326                 F2FS_OPTION(sbi).unusable_cap = sbi->user_block_count;
327         else
328                 F2FS_OPTION(sbi).unusable_cap = (sbi->user_block_count / 100) *
329                                         F2FS_OPTION(sbi).unusable_cap_perc;
330
331         f2fs_info(sbi, "Adjust unusable cap for checkpoint=disable = %u / %u%%",
332                         F2FS_OPTION(sbi).unusable_cap,
333                         F2FS_OPTION(sbi).unusable_cap_perc);
334 }
335
336 static void init_once(void *foo)
337 {
338         struct f2fs_inode_info *fi = (struct f2fs_inode_info *) foo;
339
340         inode_init_once(&fi->vfs_inode);
341 }
342
343 #ifdef CONFIG_QUOTA
344 static const char * const quotatypes[] = INITQFNAMES;
345 #define QTYPE2NAME(t) (quotatypes[t])
346 static int f2fs_set_qf_name(struct super_block *sb, int qtype,
347                                                         substring_t *args)
348 {
349         struct f2fs_sb_info *sbi = F2FS_SB(sb);
350         char *qname;
351         int ret = -EINVAL;
352
353         if (sb_any_quota_loaded(sb) && !F2FS_OPTION(sbi).s_qf_names[qtype]) {
354                 f2fs_err(sbi, "Cannot change journaled quota options when quota turned on");
355                 return -EINVAL;
356         }
357         if (f2fs_sb_has_quota_ino(sbi)) {
358                 f2fs_info(sbi, "QUOTA feature is enabled, so ignore qf_name");
359                 return 0;
360         }
361
362         qname = match_strdup(args);
363         if (!qname) {
364                 f2fs_err(sbi, "Not enough memory for storing quotafile name");
365                 return -ENOMEM;
366         }
367         if (F2FS_OPTION(sbi).s_qf_names[qtype]) {
368                 if (strcmp(F2FS_OPTION(sbi).s_qf_names[qtype], qname) == 0)
369                         ret = 0;
370                 else
371                         f2fs_err(sbi, "%s quota file already specified",
372                                  QTYPE2NAME(qtype));
373                 goto errout;
374         }
375         if (strchr(qname, '/')) {
376                 f2fs_err(sbi, "quotafile must be on filesystem root");
377                 goto errout;
378         }
379         F2FS_OPTION(sbi).s_qf_names[qtype] = qname;
380         set_opt(sbi, QUOTA);
381         return 0;
382 errout:
383         kvfree(qname);
384         return ret;
385 }
386
387 static int f2fs_clear_qf_name(struct super_block *sb, int qtype)
388 {
389         struct f2fs_sb_info *sbi = F2FS_SB(sb);
390
391         if (sb_any_quota_loaded(sb) && F2FS_OPTION(sbi).s_qf_names[qtype]) {
392                 f2fs_err(sbi, "Cannot change journaled quota options when quota turned on");
393                 return -EINVAL;
394         }
395         kvfree(F2FS_OPTION(sbi).s_qf_names[qtype]);
396         F2FS_OPTION(sbi).s_qf_names[qtype] = NULL;
397         return 0;
398 }
399
400 static int f2fs_check_quota_options(struct f2fs_sb_info *sbi)
401 {
402         /*
403          * We do the test below only for project quotas. 'usrquota' and
404          * 'grpquota' mount options are allowed even without quota feature
405          * to support legacy quotas in quota files.
406          */
407         if (test_opt(sbi, PRJQUOTA) && !f2fs_sb_has_project_quota(sbi)) {
408                 f2fs_err(sbi, "Project quota feature not enabled. Cannot enable project quota enforcement.");
409                 return -1;
410         }
411         if (F2FS_OPTION(sbi).s_qf_names[USRQUOTA] ||
412                         F2FS_OPTION(sbi).s_qf_names[GRPQUOTA] ||
413                         F2FS_OPTION(sbi).s_qf_names[PRJQUOTA]) {
414                 if (test_opt(sbi, USRQUOTA) &&
415                                 F2FS_OPTION(sbi).s_qf_names[USRQUOTA])
416                         clear_opt(sbi, USRQUOTA);
417
418                 if (test_opt(sbi, GRPQUOTA) &&
419                                 F2FS_OPTION(sbi).s_qf_names[GRPQUOTA])
420                         clear_opt(sbi, GRPQUOTA);
421
422                 if (test_opt(sbi, PRJQUOTA) &&
423                                 F2FS_OPTION(sbi).s_qf_names[PRJQUOTA])
424                         clear_opt(sbi, PRJQUOTA);
425
426                 if (test_opt(sbi, GRPQUOTA) || test_opt(sbi, USRQUOTA) ||
427                                 test_opt(sbi, PRJQUOTA)) {
428                         f2fs_err(sbi, "old and new quota format mixing");
429                         return -1;
430                 }
431
432                 if (!F2FS_OPTION(sbi).s_jquota_fmt) {
433                         f2fs_err(sbi, "journaled quota format not specified");
434                         return -1;
435                 }
436         }
437
438         if (f2fs_sb_has_quota_ino(sbi) && F2FS_OPTION(sbi).s_jquota_fmt) {
439                 f2fs_info(sbi, "QUOTA feature is enabled, so ignore jquota_fmt");
440                 F2FS_OPTION(sbi).s_jquota_fmt = 0;
441         }
442         return 0;
443 }
444 #endif
445
446 static int parse_options(struct super_block *sb, char *options)
447 {
448         struct f2fs_sb_info *sbi = F2FS_SB(sb);
449         substring_t args[MAX_OPT_ARGS];
450         char *p, *name;
451         int arg = 0;
452         kuid_t uid;
453         kgid_t gid;
454 #ifdef CONFIG_QUOTA
455         int ret;
456 #endif
457
458         if (!options)
459                 return 0;
460
461         while ((p = strsep(&options, ",")) != NULL) {
462                 int token;
463                 if (!*p)
464                         continue;
465                 /*
466                  * Initialize args struct so we know whether arg was
467                  * found; some options take optional arguments.
468                  */
469                 args[0].to = args[0].from = NULL;
470                 token = match_token(p, f2fs_tokens, args);
471
472                 switch (token) {
473                 case Opt_gc_background:
474                         name = match_strdup(&args[0]);
475
476                         if (!name)
477                                 return -ENOMEM;
478                         if (strlen(name) == 2 && !strncmp(name, "on", 2)) {
479                                 set_opt(sbi, BG_GC);
480                                 clear_opt(sbi, FORCE_FG_GC);
481                         } else if (strlen(name) == 3 && !strncmp(name, "off", 3)) {
482                                 clear_opt(sbi, BG_GC);
483                                 clear_opt(sbi, FORCE_FG_GC);
484                         } else if (strlen(name) == 4 && !strncmp(name, "sync", 4)) {
485                                 set_opt(sbi, BG_GC);
486                                 set_opt(sbi, FORCE_FG_GC);
487                         } else {
488                                 kvfree(name);
489                                 return -EINVAL;
490                         }
491                         kvfree(name);
492                         break;
493                 case Opt_disable_roll_forward:
494                         set_opt(sbi, DISABLE_ROLL_FORWARD);
495                         break;
496                 case Opt_norecovery:
497                         /* this option mounts f2fs with ro */
498                         set_opt(sbi, NORECOVERY);
499                         if (!f2fs_readonly(sb))
500                                 return -EINVAL;
501                         break;
502                 case Opt_discard:
503                         set_opt(sbi, DISCARD);
504                         break;
505                 case Opt_nodiscard:
506                         if (f2fs_sb_has_blkzoned(sbi)) {
507                                 f2fs_warn(sbi, "discard is required for zoned block devices");
508                                 return -EINVAL;
509                         }
510                         clear_opt(sbi, DISCARD);
511                         break;
512                 case Opt_noheap:
513                         set_opt(sbi, NOHEAP);
514                         break;
515                 case Opt_heap:
516                         clear_opt(sbi, NOHEAP);
517                         break;
518 #ifdef CONFIG_F2FS_FS_XATTR
519                 case Opt_user_xattr:
520                         set_opt(sbi, XATTR_USER);
521                         break;
522                 case Opt_nouser_xattr:
523                         clear_opt(sbi, XATTR_USER);
524                         break;
525                 case Opt_inline_xattr:
526                         set_opt(sbi, INLINE_XATTR);
527                         break;
528                 case Opt_noinline_xattr:
529                         clear_opt(sbi, INLINE_XATTR);
530                         break;
531                 case Opt_inline_xattr_size:
532                         if (args->from && match_int(args, &arg))
533                                 return -EINVAL;
534                         set_opt(sbi, INLINE_XATTR_SIZE);
535                         F2FS_OPTION(sbi).inline_xattr_size = arg;
536                         break;
537 #else
538                 case Opt_user_xattr:
539                         f2fs_info(sbi, "user_xattr options not supported");
540                         break;
541                 case Opt_nouser_xattr:
542                         f2fs_info(sbi, "nouser_xattr options not supported");
543                         break;
544                 case Opt_inline_xattr:
545                         f2fs_info(sbi, "inline_xattr options not supported");
546                         break;
547                 case Opt_noinline_xattr:
548                         f2fs_info(sbi, "noinline_xattr options not supported");
549                         break;
550 #endif
551 #ifdef CONFIG_F2FS_FS_POSIX_ACL
552                 case Opt_acl:
553                         set_opt(sbi, POSIX_ACL);
554                         break;
555                 case Opt_noacl:
556                         clear_opt(sbi, POSIX_ACL);
557                         break;
558 #else
559                 case Opt_acl:
560                         f2fs_info(sbi, "acl options not supported");
561                         break;
562                 case Opt_noacl:
563                         f2fs_info(sbi, "noacl options not supported");
564                         break;
565 #endif
566                 case Opt_active_logs:
567                         if (args->from && match_int(args, &arg))
568                                 return -EINVAL;
569                         if (arg != 2 && arg != 4 && arg != NR_CURSEG_TYPE)
570                                 return -EINVAL;
571                         F2FS_OPTION(sbi).active_logs = arg;
572                         break;
573                 case Opt_disable_ext_identify:
574                         set_opt(sbi, DISABLE_EXT_IDENTIFY);
575                         break;
576                 case Opt_inline_data:
577                         set_opt(sbi, INLINE_DATA);
578                         break;
579                 case Opt_inline_dentry:
580                         set_opt(sbi, INLINE_DENTRY);
581                         break;
582                 case Opt_noinline_dentry:
583                         clear_opt(sbi, INLINE_DENTRY);
584                         break;
585                 case Opt_flush_merge:
586                         set_opt(sbi, FLUSH_MERGE);
587                         break;
588                 case Opt_noflush_merge:
589                         clear_opt(sbi, FLUSH_MERGE);
590                         break;
591                 case Opt_nobarrier:
592                         set_opt(sbi, NOBARRIER);
593                         break;
594                 case Opt_fastboot:
595                         set_opt(sbi, FASTBOOT);
596                         break;
597                 case Opt_extent_cache:
598                         set_opt(sbi, EXTENT_CACHE);
599                         break;
600                 case Opt_noextent_cache:
601                         clear_opt(sbi, EXTENT_CACHE);
602                         break;
603                 case Opt_noinline_data:
604                         clear_opt(sbi, INLINE_DATA);
605                         break;
606                 case Opt_data_flush:
607                         set_opt(sbi, DATA_FLUSH);
608                         break;
609                 case Opt_reserve_root:
610                         if (args->from && match_int(args, &arg))
611                                 return -EINVAL;
612                         if (test_opt(sbi, RESERVE_ROOT)) {
613                                 f2fs_info(sbi, "Preserve previous reserve_root=%u",
614                                           F2FS_OPTION(sbi).root_reserved_blocks);
615                         } else {
616                                 F2FS_OPTION(sbi).root_reserved_blocks = arg;
617                                 set_opt(sbi, RESERVE_ROOT);
618                         }
619                         break;
620                 case Opt_resuid:
621                         if (args->from && match_int(args, &arg))
622                                 return -EINVAL;
623                         uid = make_kuid(current_user_ns(), arg);
624                         if (!uid_valid(uid)) {
625                                 f2fs_err(sbi, "Invalid uid value %d", arg);
626                                 return -EINVAL;
627                         }
628                         F2FS_OPTION(sbi).s_resuid = uid;
629                         break;
630                 case Opt_resgid:
631                         if (args->from && match_int(args, &arg))
632                                 return -EINVAL;
633                         gid = make_kgid(current_user_ns(), arg);
634                         if (!gid_valid(gid)) {
635                                 f2fs_err(sbi, "Invalid gid value %d", arg);
636                                 return -EINVAL;
637                         }
638                         F2FS_OPTION(sbi).s_resgid = gid;
639                         break;
640                 case Opt_mode:
641                         name = match_strdup(&args[0]);
642
643                         if (!name)
644                                 return -ENOMEM;
645                         if (strlen(name) == 8 &&
646                                         !strncmp(name, "adaptive", 8)) {
647                                 if (f2fs_sb_has_blkzoned(sbi)) {
648                                         f2fs_warn(sbi, "adaptive mode is not allowed with zoned block device feature");
649                                         kvfree(name);
650                                         return -EINVAL;
651                                 }
652                                 set_opt_mode(sbi, F2FS_MOUNT_ADAPTIVE);
653                         } else if (strlen(name) == 3 &&
654                                         !strncmp(name, "lfs", 3)) {
655                                 set_opt_mode(sbi, F2FS_MOUNT_LFS);
656                         } else {
657                                 kvfree(name);
658                                 return -EINVAL;
659                         }
660                         kvfree(name);
661                         break;
662                 case Opt_io_size_bits:
663                         if (args->from && match_int(args, &arg))
664                                 return -EINVAL;
665                         if (arg <= 0 || arg > __ilog2_u32(BIO_MAX_PAGES)) {
666                                 f2fs_warn(sbi, "Not support %d, larger than %d",
667                                           1 << arg, BIO_MAX_PAGES);
668                                 return -EINVAL;
669                         }
670                         F2FS_OPTION(sbi).write_io_size_bits = arg;
671                         break;
672 #ifdef CONFIG_F2FS_FAULT_INJECTION
673                 case Opt_fault_injection:
674                         if (args->from && match_int(args, &arg))
675                                 return -EINVAL;
676                         f2fs_build_fault_attr(sbi, arg, F2FS_ALL_FAULT_TYPE);
677                         set_opt(sbi, FAULT_INJECTION);
678                         break;
679
680                 case Opt_fault_type:
681                         if (args->from && match_int(args, &arg))
682                                 return -EINVAL;
683                         f2fs_build_fault_attr(sbi, 0, arg);
684                         set_opt(sbi, FAULT_INJECTION);
685                         break;
686 #else
687                 case Opt_fault_injection:
688                         f2fs_info(sbi, "fault_injection options not supported");
689                         break;
690
691                 case Opt_fault_type:
692                         f2fs_info(sbi, "fault_type options not supported");
693                         break;
694 #endif
695                 case Opt_lazytime:
696                         sb->s_flags |= SB_LAZYTIME;
697                         break;
698                 case Opt_nolazytime:
699                         sb->s_flags &= ~SB_LAZYTIME;
700                         break;
701 #ifdef CONFIG_QUOTA
702                 case Opt_quota:
703                 case Opt_usrquota:
704                         set_opt(sbi, USRQUOTA);
705                         break;
706                 case Opt_grpquota:
707                         set_opt(sbi, GRPQUOTA);
708                         break;
709                 case Opt_prjquota:
710                         set_opt(sbi, PRJQUOTA);
711                         break;
712                 case Opt_usrjquota:
713                         ret = f2fs_set_qf_name(sb, USRQUOTA, &args[0]);
714                         if (ret)
715                                 return ret;
716                         break;
717                 case Opt_grpjquota:
718                         ret = f2fs_set_qf_name(sb, GRPQUOTA, &args[0]);
719                         if (ret)
720                                 return ret;
721                         break;
722                 case Opt_prjjquota:
723                         ret = f2fs_set_qf_name(sb, PRJQUOTA, &args[0]);
724                         if (ret)
725                                 return ret;
726                         break;
727                 case Opt_offusrjquota:
728                         ret = f2fs_clear_qf_name(sb, USRQUOTA);
729                         if (ret)
730                                 return ret;
731                         break;
732                 case Opt_offgrpjquota:
733                         ret = f2fs_clear_qf_name(sb, GRPQUOTA);
734                         if (ret)
735                                 return ret;
736                         break;
737                 case Opt_offprjjquota:
738                         ret = f2fs_clear_qf_name(sb, PRJQUOTA);
739                         if (ret)
740                                 return ret;
741                         break;
742                 case Opt_jqfmt_vfsold:
743                         F2FS_OPTION(sbi).s_jquota_fmt = QFMT_VFS_OLD;
744                         break;
745                 case Opt_jqfmt_vfsv0:
746                         F2FS_OPTION(sbi).s_jquota_fmt = QFMT_VFS_V0;
747                         break;
748                 case Opt_jqfmt_vfsv1:
749                         F2FS_OPTION(sbi).s_jquota_fmt = QFMT_VFS_V1;
750                         break;
751                 case Opt_noquota:
752                         clear_opt(sbi, QUOTA);
753                         clear_opt(sbi, USRQUOTA);
754                         clear_opt(sbi, GRPQUOTA);
755                         clear_opt(sbi, PRJQUOTA);
756                         break;
757 #else
758                 case Opt_quota:
759                 case Opt_usrquota:
760                 case Opt_grpquota:
761                 case Opt_prjquota:
762                 case Opt_usrjquota:
763                 case Opt_grpjquota:
764                 case Opt_prjjquota:
765                 case Opt_offusrjquota:
766                 case Opt_offgrpjquota:
767                 case Opt_offprjjquota:
768                 case Opt_jqfmt_vfsold:
769                 case Opt_jqfmt_vfsv0:
770                 case Opt_jqfmt_vfsv1:
771                 case Opt_noquota:
772                         f2fs_info(sbi, "quota operations not supported");
773                         break;
774 #endif
775                 case Opt_whint:
776                         name = match_strdup(&args[0]);
777                         if (!name)
778                                 return -ENOMEM;
779                         if (strlen(name) == 10 &&
780                                         !strncmp(name, "user-based", 10)) {
781                                 F2FS_OPTION(sbi).whint_mode = WHINT_MODE_USER;
782                         } else if (strlen(name) == 3 &&
783                                         !strncmp(name, "off", 3)) {
784                                 F2FS_OPTION(sbi).whint_mode = WHINT_MODE_OFF;
785                         } else if (strlen(name) == 8 &&
786                                         !strncmp(name, "fs-based", 8)) {
787                                 F2FS_OPTION(sbi).whint_mode = WHINT_MODE_FS;
788                         } else {
789                                 kvfree(name);
790                                 return -EINVAL;
791                         }
792                         kvfree(name);
793                         break;
794                 case Opt_alloc:
795                         name = match_strdup(&args[0]);
796                         if (!name)
797                                 return -ENOMEM;
798
799                         if (strlen(name) == 7 &&
800                                         !strncmp(name, "default", 7)) {
801                                 F2FS_OPTION(sbi).alloc_mode = ALLOC_MODE_DEFAULT;
802                         } else if (strlen(name) == 5 &&
803                                         !strncmp(name, "reuse", 5)) {
804                                 F2FS_OPTION(sbi).alloc_mode = ALLOC_MODE_REUSE;
805                         } else {
806                                 kvfree(name);
807                                 return -EINVAL;
808                         }
809                         kvfree(name);
810                         break;
811                 case Opt_fsync:
812                         name = match_strdup(&args[0]);
813                         if (!name)
814                                 return -ENOMEM;
815                         if (strlen(name) == 5 &&
816                                         !strncmp(name, "posix", 5)) {
817                                 F2FS_OPTION(sbi).fsync_mode = FSYNC_MODE_POSIX;
818                         } else if (strlen(name) == 6 &&
819                                         !strncmp(name, "strict", 6)) {
820                                 F2FS_OPTION(sbi).fsync_mode = FSYNC_MODE_STRICT;
821                         } else if (strlen(name) == 9 &&
822                                         !strncmp(name, "nobarrier", 9)) {
823                                 F2FS_OPTION(sbi).fsync_mode =
824                                                         FSYNC_MODE_NOBARRIER;
825                         } else {
826                                 kvfree(name);
827                                 return -EINVAL;
828                         }
829                         kvfree(name);
830                         break;
831                 case Opt_test_dummy_encryption:
832 #ifdef CONFIG_FS_ENCRYPTION
833                         if (!f2fs_sb_has_encrypt(sbi)) {
834                                 f2fs_err(sbi, "Encrypt feature is off");
835                                 return -EINVAL;
836                         }
837
838                         F2FS_OPTION(sbi).test_dummy_encryption = true;
839                         f2fs_info(sbi, "Test dummy encryption mode enabled");
840 #else
841                         f2fs_info(sbi, "Test dummy encryption mount option ignored");
842 #endif
843                         break;
844                 case Opt_checkpoint_disable_cap_perc:
845                         if (args->from && match_int(args, &arg))
846                                 return -EINVAL;
847                         if (arg < 0 || arg > 100)
848                                 return -EINVAL;
849                         F2FS_OPTION(sbi).unusable_cap_perc = arg;
850                         set_opt(sbi, DISABLE_CHECKPOINT);
851                         break;
852                 case Opt_checkpoint_disable_cap:
853                         if (args->from && match_int(args, &arg))
854                                 return -EINVAL;
855                         F2FS_OPTION(sbi).unusable_cap = arg;
856                         set_opt(sbi, DISABLE_CHECKPOINT);
857                         break;
858                 case Opt_checkpoint_disable:
859                         set_opt(sbi, DISABLE_CHECKPOINT);
860                         break;
861                 case Opt_checkpoint_enable:
862                         clear_opt(sbi, DISABLE_CHECKPOINT);
863                         break;
864                 default:
865                         f2fs_err(sbi, "Unrecognized mount option \"%s\" or missing value",
866                                  p);
867                         return -EINVAL;
868                 }
869         }
870 #ifdef CONFIG_QUOTA
871         if (f2fs_check_quota_options(sbi))
872                 return -EINVAL;
873 #else
874         if (f2fs_sb_has_quota_ino(sbi) && !f2fs_readonly(sbi->sb)) {
875                 f2fs_info(sbi, "Filesystem with quota feature cannot be mounted RDWR without CONFIG_QUOTA");
876                 return -EINVAL;
877         }
878         if (f2fs_sb_has_project_quota(sbi) && !f2fs_readonly(sbi->sb)) {
879                 f2fs_err(sbi, "Filesystem with project quota feature cannot be mounted RDWR without CONFIG_QUOTA");
880                 return -EINVAL;
881         }
882 #endif
883 #ifndef CONFIG_UNICODE
884         if (f2fs_sb_has_casefold(sbi)) {
885                 f2fs_err(sbi,
886                         "Filesystem with casefold feature cannot be mounted without CONFIG_UNICODE");
887                 return -EINVAL;
888         }
889 #endif
890
891         if (F2FS_IO_SIZE_BITS(sbi) && !test_opt(sbi, LFS)) {
892                 f2fs_err(sbi, "Should set mode=lfs with %uKB-sized IO",
893                          F2FS_IO_SIZE_KB(sbi));
894                 return -EINVAL;
895         }
896
897         if (test_opt(sbi, INLINE_XATTR_SIZE)) {
898                 int min_size, max_size;
899
900                 if (!f2fs_sb_has_extra_attr(sbi) ||
901                         !f2fs_sb_has_flexible_inline_xattr(sbi)) {
902                         f2fs_err(sbi, "extra_attr or flexible_inline_xattr feature is off");
903                         return -EINVAL;
904                 }
905                 if (!test_opt(sbi, INLINE_XATTR)) {
906                         f2fs_err(sbi, "inline_xattr_size option should be set with inline_xattr option");
907                         return -EINVAL;
908                 }
909
910                 min_size = sizeof(struct f2fs_xattr_header) / sizeof(__le32);
911                 max_size = MAX_INLINE_XATTR_SIZE;
912
913                 if (F2FS_OPTION(sbi).inline_xattr_size < min_size ||
914                                 F2FS_OPTION(sbi).inline_xattr_size > max_size) {
915                         f2fs_err(sbi, "inline xattr size is out of range: %d ~ %d",
916                                  min_size, max_size);
917                         return -EINVAL;
918                 }
919         }
920
921         if (test_opt(sbi, DISABLE_CHECKPOINT) && test_opt(sbi, LFS)) {
922                 f2fs_err(sbi, "LFS not compatible with checkpoint=disable\n");
923                 return -EINVAL;
924         }
925
926         /* Not pass down write hints if the number of active logs is lesser
927          * than NR_CURSEG_TYPE.
928          */
929         if (F2FS_OPTION(sbi).active_logs != NR_CURSEG_TYPE)
930                 F2FS_OPTION(sbi).whint_mode = WHINT_MODE_OFF;
931         return 0;
932 }
933
934 static struct inode *f2fs_alloc_inode(struct super_block *sb)
935 {
936         struct f2fs_inode_info *fi;
937
938         fi = kmem_cache_alloc(f2fs_inode_cachep, GFP_F2FS_ZERO);
939         if (!fi)
940                 return NULL;
941
942         init_once((void *) fi);
943
944         /* Initialize f2fs-specific inode info */
945         atomic_set(&fi->dirty_pages, 0);
946         init_rwsem(&fi->i_sem);
947         INIT_LIST_HEAD(&fi->dirty_list);
948         INIT_LIST_HEAD(&fi->gdirty_list);
949         INIT_LIST_HEAD(&fi->inmem_ilist);
950         INIT_LIST_HEAD(&fi->inmem_pages);
951         mutex_init(&fi->inmem_lock);
952         init_rwsem(&fi->i_gc_rwsem[READ]);
953         init_rwsem(&fi->i_gc_rwsem[WRITE]);
954         init_rwsem(&fi->i_mmap_sem);
955         init_rwsem(&fi->i_xattr_sem);
956
957         /* Will be used by directory only */
958         fi->i_dir_level = F2FS_SB(sb)->dir_level;
959
960         return &fi->vfs_inode;
961 }
962
963 static int f2fs_drop_inode(struct inode *inode)
964 {
965         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
966         int ret;
967
968         /*
969          * during filesystem shutdown, if checkpoint is disabled,
970          * drop useless meta/node dirty pages.
971          */
972         if (unlikely(is_sbi_flag_set(sbi, SBI_CP_DISABLED))) {
973                 if (inode->i_ino == F2FS_NODE_INO(sbi) ||
974                         inode->i_ino == F2FS_META_INO(sbi)) {
975                         trace_f2fs_drop_inode(inode, 1);
976                         return 1;
977                 }
978         }
979
980         /*
981          * This is to avoid a deadlock condition like below.
982          * writeback_single_inode(inode)
983          *  - f2fs_write_data_page
984          *    - f2fs_gc -> iput -> evict
985          *       - inode_wait_for_writeback(inode)
986          */
987         if ((!inode_unhashed(inode) && inode->i_state & I_SYNC)) {
988                 if (!inode->i_nlink && !is_bad_inode(inode)) {
989                         /* to avoid evict_inode call simultaneously */
990                         atomic_inc(&inode->i_count);
991                         spin_unlock(&inode->i_lock);
992
993                         /* some remained atomic pages should discarded */
994                         if (f2fs_is_atomic_file(inode))
995                                 f2fs_drop_inmem_pages(inode);
996
997                         /* should remain fi->extent_tree for writepage */
998                         f2fs_destroy_extent_node(inode);
999
1000                         sb_start_intwrite(inode->i_sb);
1001                         f2fs_i_size_write(inode, 0);
1002
1003                         f2fs_submit_merged_write_cond(F2FS_I_SB(inode),
1004                                         inode, NULL, 0, DATA);
1005                         truncate_inode_pages_final(inode->i_mapping);
1006
1007                         if (F2FS_HAS_BLOCKS(inode))
1008                                 f2fs_truncate(inode);
1009
1010                         sb_end_intwrite(inode->i_sb);
1011
1012                         spin_lock(&inode->i_lock);
1013                         atomic_dec(&inode->i_count);
1014                 }
1015                 trace_f2fs_drop_inode(inode, 0);
1016                 return 0;
1017         }
1018         ret = generic_drop_inode(inode);
1019         if (!ret)
1020                 ret = fscrypt_drop_inode(inode);
1021         trace_f2fs_drop_inode(inode, ret);
1022         return ret;
1023 }
1024
1025 int f2fs_inode_dirtied(struct inode *inode, bool sync)
1026 {
1027         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1028         int ret = 0;
1029
1030         spin_lock(&sbi->inode_lock[DIRTY_META]);
1031         if (is_inode_flag_set(inode, FI_DIRTY_INODE)) {
1032                 ret = 1;
1033         } else {
1034                 set_inode_flag(inode, FI_DIRTY_INODE);
1035                 stat_inc_dirty_inode(sbi, DIRTY_META);
1036         }
1037         if (sync && list_empty(&F2FS_I(inode)->gdirty_list)) {
1038                 list_add_tail(&F2FS_I(inode)->gdirty_list,
1039                                 &sbi->inode_list[DIRTY_META]);
1040                 inc_page_count(sbi, F2FS_DIRTY_IMETA);
1041         }
1042         spin_unlock(&sbi->inode_lock[DIRTY_META]);
1043         return ret;
1044 }
1045
1046 void f2fs_inode_synced(struct inode *inode)
1047 {
1048         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1049
1050         spin_lock(&sbi->inode_lock[DIRTY_META]);
1051         if (!is_inode_flag_set(inode, FI_DIRTY_INODE)) {
1052                 spin_unlock(&sbi->inode_lock[DIRTY_META]);
1053                 return;
1054         }
1055         if (!list_empty(&F2FS_I(inode)->gdirty_list)) {
1056                 list_del_init(&F2FS_I(inode)->gdirty_list);
1057                 dec_page_count(sbi, F2FS_DIRTY_IMETA);
1058         }
1059         clear_inode_flag(inode, FI_DIRTY_INODE);
1060         clear_inode_flag(inode, FI_AUTO_RECOVER);
1061         stat_dec_dirty_inode(F2FS_I_SB(inode), DIRTY_META);
1062         spin_unlock(&sbi->inode_lock[DIRTY_META]);
1063 }
1064
1065 /*
1066  * f2fs_dirty_inode() is called from __mark_inode_dirty()
1067  *
1068  * We should call set_dirty_inode to write the dirty inode through write_inode.
1069  */
1070 static void f2fs_dirty_inode(struct inode *inode, int flags)
1071 {
1072         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1073
1074         if (inode->i_ino == F2FS_NODE_INO(sbi) ||
1075                         inode->i_ino == F2FS_META_INO(sbi))
1076                 return;
1077
1078         if (flags == I_DIRTY_TIME)
1079                 return;
1080
1081         if (is_inode_flag_set(inode, FI_AUTO_RECOVER))
1082                 clear_inode_flag(inode, FI_AUTO_RECOVER);
1083
1084         f2fs_inode_dirtied(inode, false);
1085 }
1086
1087 static void f2fs_free_inode(struct inode *inode)
1088 {
1089         fscrypt_free_inode(inode);
1090         kmem_cache_free(f2fs_inode_cachep, F2FS_I(inode));
1091 }
1092
1093 static void destroy_percpu_info(struct f2fs_sb_info *sbi)
1094 {
1095         percpu_counter_destroy(&sbi->alloc_valid_block_count);
1096         percpu_counter_destroy(&sbi->total_valid_inode_count);
1097 }
1098
1099 static void destroy_device_list(struct f2fs_sb_info *sbi)
1100 {
1101         int i;
1102
1103         for (i = 0; i < sbi->s_ndevs; i++) {
1104                 blkdev_put(FDEV(i).bdev, FMODE_EXCL);
1105 #ifdef CONFIG_BLK_DEV_ZONED
1106                 kvfree(FDEV(i).blkz_seq);
1107 #endif
1108         }
1109         kvfree(sbi->devs);
1110 }
1111
1112 static void f2fs_put_super(struct super_block *sb)
1113 {
1114         struct f2fs_sb_info *sbi = F2FS_SB(sb);
1115         int i;
1116         bool dropped;
1117
1118         /* unregister procfs/sysfs entries in advance to avoid race case */
1119         f2fs_unregister_sysfs(sbi);
1120
1121         f2fs_quota_off_umount(sb);
1122
1123         /* prevent remaining shrinker jobs */
1124         mutex_lock(&sbi->umount_mutex);
1125
1126         /*
1127          * We don't need to do checkpoint when superblock is clean.
1128          * But, the previous checkpoint was not done by umount, it needs to do
1129          * clean checkpoint again.
1130          */
1131         if ((is_sbi_flag_set(sbi, SBI_IS_DIRTY) ||
1132                         !is_set_ckpt_flags(sbi, CP_UMOUNT_FLAG))) {
1133                 struct cp_control cpc = {
1134                         .reason = CP_UMOUNT,
1135                 };
1136                 f2fs_write_checkpoint(sbi, &cpc);
1137         }
1138
1139         /* be sure to wait for any on-going discard commands */
1140         dropped = f2fs_issue_discard_timeout(sbi);
1141
1142         if ((f2fs_hw_support_discard(sbi) || f2fs_hw_should_discard(sbi)) &&
1143                                         !sbi->discard_blks && !dropped) {
1144                 struct cp_control cpc = {
1145                         .reason = CP_UMOUNT | CP_TRIMMED,
1146                 };
1147                 f2fs_write_checkpoint(sbi, &cpc);
1148         }
1149
1150         /*
1151          * normally superblock is clean, so we need to release this.
1152          * In addition, EIO will skip do checkpoint, we need this as well.
1153          */
1154         f2fs_release_ino_entry(sbi, true);
1155
1156         f2fs_leave_shrinker(sbi);
1157         mutex_unlock(&sbi->umount_mutex);
1158
1159         /* our cp_error case, we can wait for any writeback page */
1160         f2fs_flush_merged_writes(sbi);
1161
1162         f2fs_wait_on_all_pages(sbi, F2FS_WB_CP_DATA);
1163
1164         f2fs_bug_on(sbi, sbi->fsync_node_num);
1165
1166         iput(sbi->node_inode);
1167         sbi->node_inode = NULL;
1168
1169         iput(sbi->meta_inode);
1170         sbi->meta_inode = NULL;
1171
1172         /*
1173          * iput() can update stat information, if f2fs_write_checkpoint()
1174          * above failed with error.
1175          */
1176         f2fs_destroy_stats(sbi);
1177
1178         /* destroy f2fs internal modules */
1179         f2fs_destroy_node_manager(sbi);
1180         f2fs_destroy_segment_manager(sbi);
1181
1182         kvfree(sbi->ckpt);
1183
1184         sb->s_fs_info = NULL;
1185         if (sbi->s_chksum_driver)
1186                 crypto_free_shash(sbi->s_chksum_driver);
1187         kvfree(sbi->raw_super);
1188
1189         destroy_device_list(sbi);
1190         mempool_destroy(sbi->write_io_dummy);
1191 #ifdef CONFIG_QUOTA
1192         for (i = 0; i < MAXQUOTAS; i++)
1193                 kvfree(F2FS_OPTION(sbi).s_qf_names[i]);
1194 #endif
1195         destroy_percpu_info(sbi);
1196         for (i = 0; i < NR_PAGE_TYPE; i++)
1197                 kvfree(sbi->write_io[i]);
1198 #ifdef CONFIG_UNICODE
1199         utf8_unload(sbi->s_encoding);
1200 #endif
1201         kvfree(sbi);
1202 }
1203
1204 int f2fs_sync_fs(struct super_block *sb, int sync)
1205 {
1206         struct f2fs_sb_info *sbi = F2FS_SB(sb);
1207         int err = 0;
1208
1209         if (unlikely(f2fs_cp_error(sbi)))
1210                 return 0;
1211         if (unlikely(is_sbi_flag_set(sbi, SBI_CP_DISABLED)))
1212                 return 0;
1213
1214         trace_f2fs_sync_fs(sb, sync);
1215
1216         if (unlikely(is_sbi_flag_set(sbi, SBI_POR_DOING)))
1217                 return -EAGAIN;
1218
1219         if (sync) {
1220                 struct cp_control cpc;
1221
1222                 cpc.reason = __get_cp_reason(sbi);
1223
1224                 mutex_lock(&sbi->gc_mutex);
1225                 err = f2fs_write_checkpoint(sbi, &cpc);
1226                 mutex_unlock(&sbi->gc_mutex);
1227         }
1228         f2fs_trace_ios(NULL, 1);
1229
1230         return err;
1231 }
1232
1233 static int f2fs_freeze(struct super_block *sb)
1234 {
1235         if (f2fs_readonly(sb))
1236                 return 0;
1237
1238         /* IO error happened before */
1239         if (unlikely(f2fs_cp_error(F2FS_SB(sb))))
1240                 return -EIO;
1241
1242         /* must be clean, since sync_filesystem() was already called */
1243         if (is_sbi_flag_set(F2FS_SB(sb), SBI_IS_DIRTY))
1244                 return -EINVAL;
1245         return 0;
1246 }
1247
1248 static int f2fs_unfreeze(struct super_block *sb)
1249 {
1250         return 0;
1251 }
1252
1253 #ifdef CONFIG_QUOTA
1254 static int f2fs_statfs_project(struct super_block *sb,
1255                                 kprojid_t projid, struct kstatfs *buf)
1256 {
1257         struct kqid qid;
1258         struct dquot *dquot;
1259         u64 limit;
1260         u64 curblock;
1261
1262         qid = make_kqid_projid(projid);
1263         dquot = dqget(sb, qid);
1264         if (IS_ERR(dquot))
1265                 return PTR_ERR(dquot);
1266         spin_lock(&dquot->dq_dqb_lock);
1267
1268         limit = min_not_zero(dquot->dq_dqb.dqb_bsoftlimit,
1269                                         dquot->dq_dqb.dqb_bhardlimit);
1270         if (limit)
1271                 limit >>= sb->s_blocksize_bits;
1272
1273         if (limit && buf->f_blocks > limit) {
1274                 curblock = (dquot->dq_dqb.dqb_curspace +
1275                             dquot->dq_dqb.dqb_rsvspace) >> sb->s_blocksize_bits;
1276                 buf->f_blocks = limit;
1277                 buf->f_bfree = buf->f_bavail =
1278                         (buf->f_blocks > curblock) ?
1279                          (buf->f_blocks - curblock) : 0;
1280         }
1281
1282         limit = min_not_zero(dquot->dq_dqb.dqb_isoftlimit,
1283                                         dquot->dq_dqb.dqb_ihardlimit);
1284
1285         if (limit && buf->f_files > limit) {
1286                 buf->f_files = limit;
1287                 buf->f_ffree =
1288                         (buf->f_files > dquot->dq_dqb.dqb_curinodes) ?
1289                          (buf->f_files - dquot->dq_dqb.dqb_curinodes) : 0;
1290         }
1291
1292         spin_unlock(&dquot->dq_dqb_lock);
1293         dqput(dquot);
1294         return 0;
1295 }
1296 #endif
1297
1298 static int f2fs_statfs(struct dentry *dentry, struct kstatfs *buf)
1299 {
1300         struct super_block *sb = dentry->d_sb;
1301         struct f2fs_sb_info *sbi = F2FS_SB(sb);
1302         u64 id = huge_encode_dev(sb->s_bdev->bd_dev);
1303         block_t total_count, user_block_count, start_count;
1304         u64 avail_node_count;
1305
1306         total_count = le64_to_cpu(sbi->raw_super->block_count);
1307         user_block_count = sbi->user_block_count;
1308         start_count = le32_to_cpu(sbi->raw_super->segment0_blkaddr);
1309         buf->f_type = F2FS_SUPER_MAGIC;
1310         buf->f_bsize = sbi->blocksize;
1311
1312         buf->f_blocks = total_count - start_count;
1313         buf->f_bfree = user_block_count - valid_user_blocks(sbi) -
1314                                                 sbi->current_reserved_blocks;
1315
1316         spin_lock(&sbi->stat_lock);
1317         if (unlikely(buf->f_bfree <= sbi->unusable_block_count))
1318                 buf->f_bfree = 0;
1319         else
1320                 buf->f_bfree -= sbi->unusable_block_count;
1321         spin_unlock(&sbi->stat_lock);
1322
1323         if (buf->f_bfree > F2FS_OPTION(sbi).root_reserved_blocks)
1324                 buf->f_bavail = buf->f_bfree -
1325                                 F2FS_OPTION(sbi).root_reserved_blocks;
1326         else
1327                 buf->f_bavail = 0;
1328
1329         avail_node_count = sbi->total_node_count - F2FS_RESERVED_NODE_NUM;
1330
1331         if (avail_node_count > user_block_count) {
1332                 buf->f_files = user_block_count;
1333                 buf->f_ffree = buf->f_bavail;
1334         } else {
1335                 buf->f_files = avail_node_count;
1336                 buf->f_ffree = min(avail_node_count - valid_node_count(sbi),
1337                                         buf->f_bavail);
1338         }
1339
1340         buf->f_namelen = F2FS_NAME_LEN;
1341         buf->f_fsid.val[0] = (u32)id;
1342         buf->f_fsid.val[1] = (u32)(id >> 32);
1343
1344 #ifdef CONFIG_QUOTA
1345         if (is_inode_flag_set(dentry->d_inode, FI_PROJ_INHERIT) &&
1346                         sb_has_quota_limits_enabled(sb, PRJQUOTA)) {
1347                 f2fs_statfs_project(sb, F2FS_I(dentry->d_inode)->i_projid, buf);
1348         }
1349 #endif
1350         return 0;
1351 }
1352
1353 static inline void f2fs_show_quota_options(struct seq_file *seq,
1354                                            struct super_block *sb)
1355 {
1356 #ifdef CONFIG_QUOTA
1357         struct f2fs_sb_info *sbi = F2FS_SB(sb);
1358
1359         if (F2FS_OPTION(sbi).s_jquota_fmt) {
1360                 char *fmtname = "";
1361
1362                 switch (F2FS_OPTION(sbi).s_jquota_fmt) {
1363                 case QFMT_VFS_OLD:
1364                         fmtname = "vfsold";
1365                         break;
1366                 case QFMT_VFS_V0:
1367                         fmtname = "vfsv0";
1368                         break;
1369                 case QFMT_VFS_V1:
1370                         fmtname = "vfsv1";
1371                         break;
1372                 }
1373                 seq_printf(seq, ",jqfmt=%s", fmtname);
1374         }
1375
1376         if (F2FS_OPTION(sbi).s_qf_names[USRQUOTA])
1377                 seq_show_option(seq, "usrjquota",
1378                         F2FS_OPTION(sbi).s_qf_names[USRQUOTA]);
1379
1380         if (F2FS_OPTION(sbi).s_qf_names[GRPQUOTA])
1381                 seq_show_option(seq, "grpjquota",
1382                         F2FS_OPTION(sbi).s_qf_names[GRPQUOTA]);
1383
1384         if (F2FS_OPTION(sbi).s_qf_names[PRJQUOTA])
1385                 seq_show_option(seq, "prjjquota",
1386                         F2FS_OPTION(sbi).s_qf_names[PRJQUOTA]);
1387 #endif
1388 }
1389
1390 static int f2fs_show_options(struct seq_file *seq, struct dentry *root)
1391 {
1392         struct f2fs_sb_info *sbi = F2FS_SB(root->d_sb);
1393
1394         if (!f2fs_readonly(sbi->sb) && test_opt(sbi, BG_GC)) {
1395                 if (test_opt(sbi, FORCE_FG_GC))
1396                         seq_printf(seq, ",background_gc=%s", "sync");
1397                 else
1398                         seq_printf(seq, ",background_gc=%s", "on");
1399         } else {
1400                 seq_printf(seq, ",background_gc=%s", "off");
1401         }
1402         if (test_opt(sbi, DISABLE_ROLL_FORWARD))
1403                 seq_puts(seq, ",disable_roll_forward");
1404         if (test_opt(sbi, NORECOVERY))
1405                 seq_puts(seq, ",norecovery");
1406         if (test_opt(sbi, DISCARD))
1407                 seq_puts(seq, ",discard");
1408         else
1409                 seq_puts(seq, ",nodiscard");
1410         if (test_opt(sbi, NOHEAP))
1411                 seq_puts(seq, ",no_heap");
1412         else
1413                 seq_puts(seq, ",heap");
1414 #ifdef CONFIG_F2FS_FS_XATTR
1415         if (test_opt(sbi, XATTR_USER))
1416                 seq_puts(seq, ",user_xattr");
1417         else
1418                 seq_puts(seq, ",nouser_xattr");
1419         if (test_opt(sbi, INLINE_XATTR))
1420                 seq_puts(seq, ",inline_xattr");
1421         else
1422                 seq_puts(seq, ",noinline_xattr");
1423         if (test_opt(sbi, INLINE_XATTR_SIZE))
1424                 seq_printf(seq, ",inline_xattr_size=%u",
1425                                         F2FS_OPTION(sbi).inline_xattr_size);
1426 #endif
1427 #ifdef CONFIG_F2FS_FS_POSIX_ACL
1428         if (test_opt(sbi, POSIX_ACL))
1429                 seq_puts(seq, ",acl");
1430         else
1431                 seq_puts(seq, ",noacl");
1432 #endif
1433         if (test_opt(sbi, DISABLE_EXT_IDENTIFY))
1434                 seq_puts(seq, ",disable_ext_identify");
1435         if (test_opt(sbi, INLINE_DATA))
1436                 seq_puts(seq, ",inline_data");
1437         else
1438                 seq_puts(seq, ",noinline_data");
1439         if (test_opt(sbi, INLINE_DENTRY))
1440                 seq_puts(seq, ",inline_dentry");
1441         else
1442                 seq_puts(seq, ",noinline_dentry");
1443         if (!f2fs_readonly(sbi->sb) && test_opt(sbi, FLUSH_MERGE))
1444                 seq_puts(seq, ",flush_merge");
1445         if (test_opt(sbi, NOBARRIER))
1446                 seq_puts(seq, ",nobarrier");
1447         if (test_opt(sbi, FASTBOOT))
1448                 seq_puts(seq, ",fastboot");
1449         if (test_opt(sbi, EXTENT_CACHE))
1450                 seq_puts(seq, ",extent_cache");
1451         else
1452                 seq_puts(seq, ",noextent_cache");
1453         if (test_opt(sbi, DATA_FLUSH))
1454                 seq_puts(seq, ",data_flush");
1455
1456         seq_puts(seq, ",mode=");
1457         if (test_opt(sbi, ADAPTIVE))
1458                 seq_puts(seq, "adaptive");
1459         else if (test_opt(sbi, LFS))
1460                 seq_puts(seq, "lfs");
1461         seq_printf(seq, ",active_logs=%u", F2FS_OPTION(sbi).active_logs);
1462         if (test_opt(sbi, RESERVE_ROOT))
1463                 seq_printf(seq, ",reserve_root=%u,resuid=%u,resgid=%u",
1464                                 F2FS_OPTION(sbi).root_reserved_blocks,
1465                                 from_kuid_munged(&init_user_ns,
1466                                         F2FS_OPTION(sbi).s_resuid),
1467                                 from_kgid_munged(&init_user_ns,
1468                                         F2FS_OPTION(sbi).s_resgid));
1469         if (F2FS_IO_SIZE_BITS(sbi))
1470                 seq_printf(seq, ",io_bits=%u",
1471                                 F2FS_OPTION(sbi).write_io_size_bits);
1472 #ifdef CONFIG_F2FS_FAULT_INJECTION
1473         if (test_opt(sbi, FAULT_INJECTION)) {
1474                 seq_printf(seq, ",fault_injection=%u",
1475                                 F2FS_OPTION(sbi).fault_info.inject_rate);
1476                 seq_printf(seq, ",fault_type=%u",
1477                                 F2FS_OPTION(sbi).fault_info.inject_type);
1478         }
1479 #endif
1480 #ifdef CONFIG_QUOTA
1481         if (test_opt(sbi, QUOTA))
1482                 seq_puts(seq, ",quota");
1483         if (test_opt(sbi, USRQUOTA))
1484                 seq_puts(seq, ",usrquota");
1485         if (test_opt(sbi, GRPQUOTA))
1486                 seq_puts(seq, ",grpquota");
1487         if (test_opt(sbi, PRJQUOTA))
1488                 seq_puts(seq, ",prjquota");
1489 #endif
1490         f2fs_show_quota_options(seq, sbi->sb);
1491         if (F2FS_OPTION(sbi).whint_mode == WHINT_MODE_USER)
1492                 seq_printf(seq, ",whint_mode=%s", "user-based");
1493         else if (F2FS_OPTION(sbi).whint_mode == WHINT_MODE_FS)
1494                 seq_printf(seq, ",whint_mode=%s", "fs-based");
1495 #ifdef CONFIG_FS_ENCRYPTION
1496         if (F2FS_OPTION(sbi).test_dummy_encryption)
1497                 seq_puts(seq, ",test_dummy_encryption");
1498 #endif
1499
1500         if (F2FS_OPTION(sbi).alloc_mode == ALLOC_MODE_DEFAULT)
1501                 seq_printf(seq, ",alloc_mode=%s", "default");
1502         else if (F2FS_OPTION(sbi).alloc_mode == ALLOC_MODE_REUSE)
1503                 seq_printf(seq, ",alloc_mode=%s", "reuse");
1504
1505         if (test_opt(sbi, DISABLE_CHECKPOINT))
1506                 seq_printf(seq, ",checkpoint=disable:%u",
1507                                 F2FS_OPTION(sbi).unusable_cap);
1508         if (F2FS_OPTION(sbi).fsync_mode == FSYNC_MODE_POSIX)
1509                 seq_printf(seq, ",fsync_mode=%s", "posix");
1510         else if (F2FS_OPTION(sbi).fsync_mode == FSYNC_MODE_STRICT)
1511                 seq_printf(seq, ",fsync_mode=%s", "strict");
1512         else if (F2FS_OPTION(sbi).fsync_mode == FSYNC_MODE_NOBARRIER)
1513                 seq_printf(seq, ",fsync_mode=%s", "nobarrier");
1514         return 0;
1515 }
1516
1517 static void default_options(struct f2fs_sb_info *sbi)
1518 {
1519         /* init some FS parameters */
1520         F2FS_OPTION(sbi).active_logs = NR_CURSEG_TYPE;
1521         F2FS_OPTION(sbi).inline_xattr_size = DEFAULT_INLINE_XATTR_ADDRS;
1522         F2FS_OPTION(sbi).whint_mode = WHINT_MODE_OFF;
1523         F2FS_OPTION(sbi).alloc_mode = ALLOC_MODE_DEFAULT;
1524         F2FS_OPTION(sbi).fsync_mode = FSYNC_MODE_POSIX;
1525         F2FS_OPTION(sbi).test_dummy_encryption = false;
1526         F2FS_OPTION(sbi).s_resuid = make_kuid(&init_user_ns, F2FS_DEF_RESUID);
1527         F2FS_OPTION(sbi).s_resgid = make_kgid(&init_user_ns, F2FS_DEF_RESGID);
1528
1529         set_opt(sbi, BG_GC);
1530         set_opt(sbi, INLINE_XATTR);
1531         set_opt(sbi, INLINE_DATA);
1532         set_opt(sbi, INLINE_DENTRY);
1533         set_opt(sbi, EXTENT_CACHE);
1534         set_opt(sbi, NOHEAP);
1535         clear_opt(sbi, DISABLE_CHECKPOINT);
1536         F2FS_OPTION(sbi).unusable_cap = 0;
1537         sbi->sb->s_flags |= SB_LAZYTIME;
1538         set_opt(sbi, FLUSH_MERGE);
1539         set_opt(sbi, DISCARD);
1540         if (f2fs_sb_has_blkzoned(sbi))
1541                 set_opt_mode(sbi, F2FS_MOUNT_LFS);
1542         else
1543                 set_opt_mode(sbi, F2FS_MOUNT_ADAPTIVE);
1544
1545 #ifdef CONFIG_F2FS_FS_XATTR
1546         set_opt(sbi, XATTR_USER);
1547 #endif
1548 #ifdef CONFIG_F2FS_FS_POSIX_ACL
1549         set_opt(sbi, POSIX_ACL);
1550 #endif
1551
1552         f2fs_build_fault_attr(sbi, 0, 0);
1553 }
1554
1555 #ifdef CONFIG_QUOTA
1556 static int f2fs_enable_quotas(struct super_block *sb);
1557 #endif
1558
1559 static int f2fs_disable_checkpoint(struct f2fs_sb_info *sbi)
1560 {
1561         unsigned int s_flags = sbi->sb->s_flags;
1562         struct cp_control cpc;
1563         int err = 0;
1564         int ret;
1565         block_t unusable;
1566
1567         if (s_flags & SB_RDONLY) {
1568                 f2fs_err(sbi, "checkpoint=disable on readonly fs");
1569                 return -EINVAL;
1570         }
1571         sbi->sb->s_flags |= SB_ACTIVE;
1572
1573         f2fs_update_time(sbi, DISABLE_TIME);
1574
1575         while (!f2fs_time_over(sbi, DISABLE_TIME)) {
1576                 mutex_lock(&sbi->gc_mutex);
1577                 err = f2fs_gc(sbi, true, false, NULL_SEGNO);
1578                 if (err == -ENODATA) {
1579                         err = 0;
1580                         break;
1581                 }
1582                 if (err && err != -EAGAIN)
1583                         break;
1584         }
1585
1586         ret = sync_filesystem(sbi->sb);
1587         if (ret || err) {
1588                 err = ret ? ret: err;
1589                 goto restore_flag;
1590         }
1591
1592         unusable = f2fs_get_unusable_blocks(sbi);
1593         if (f2fs_disable_cp_again(sbi, unusable)) {
1594                 err = -EAGAIN;
1595                 goto restore_flag;
1596         }
1597
1598         mutex_lock(&sbi->gc_mutex);
1599         cpc.reason = CP_PAUSE;
1600         set_sbi_flag(sbi, SBI_CP_DISABLED);
1601         err = f2fs_write_checkpoint(sbi, &cpc);
1602         if (err)
1603                 goto out_unlock;
1604
1605         spin_lock(&sbi->stat_lock);
1606         sbi->unusable_block_count = unusable;
1607         spin_unlock(&sbi->stat_lock);
1608
1609 out_unlock:
1610         mutex_unlock(&sbi->gc_mutex);
1611 restore_flag:
1612         sbi->sb->s_flags = s_flags;     /* Restore MS_RDONLY status */
1613         return err;
1614 }
1615
1616 static void f2fs_enable_checkpoint(struct f2fs_sb_info *sbi)
1617 {
1618         mutex_lock(&sbi->gc_mutex);
1619         f2fs_dirty_to_prefree(sbi);
1620
1621         clear_sbi_flag(sbi, SBI_CP_DISABLED);
1622         set_sbi_flag(sbi, SBI_IS_DIRTY);
1623         mutex_unlock(&sbi->gc_mutex);
1624
1625         f2fs_sync_fs(sbi->sb, 1);
1626 }
1627
1628 static int f2fs_remount(struct super_block *sb, int *flags, char *data)
1629 {
1630         struct f2fs_sb_info *sbi = F2FS_SB(sb);
1631         struct f2fs_mount_info org_mount_opt;
1632         unsigned long old_sb_flags;
1633         int err;
1634         bool need_restart_gc = false;
1635         bool need_stop_gc = false;
1636         bool no_extent_cache = !test_opt(sbi, EXTENT_CACHE);
1637         bool disable_checkpoint = test_opt(sbi, DISABLE_CHECKPOINT);
1638         bool no_io_align = !F2FS_IO_ALIGNED(sbi);
1639         bool checkpoint_changed;
1640 #ifdef CONFIG_QUOTA
1641         int i, j;
1642 #endif
1643
1644         /*
1645          * Save the old mount options in case we
1646          * need to restore them.
1647          */
1648         org_mount_opt = sbi->mount_opt;
1649         old_sb_flags = sb->s_flags;
1650
1651 #ifdef CONFIG_QUOTA
1652         org_mount_opt.s_jquota_fmt = F2FS_OPTION(sbi).s_jquota_fmt;
1653         for (i = 0; i < MAXQUOTAS; i++) {
1654                 if (F2FS_OPTION(sbi).s_qf_names[i]) {
1655                         org_mount_opt.s_qf_names[i] =
1656                                 kstrdup(F2FS_OPTION(sbi).s_qf_names[i],
1657                                 GFP_KERNEL);
1658                         if (!org_mount_opt.s_qf_names[i]) {
1659                                 for (j = 0; j < i; j++)
1660                                         kvfree(org_mount_opt.s_qf_names[j]);
1661                                 return -ENOMEM;
1662                         }
1663                 } else {
1664                         org_mount_opt.s_qf_names[i] = NULL;
1665                 }
1666         }
1667 #endif
1668
1669         /* recover superblocks we couldn't write due to previous RO mount */
1670         if (!(*flags & SB_RDONLY) && is_sbi_flag_set(sbi, SBI_NEED_SB_WRITE)) {
1671                 err = f2fs_commit_super(sbi, false);
1672                 f2fs_info(sbi, "Try to recover all the superblocks, ret: %d",
1673                           err);
1674                 if (!err)
1675                         clear_sbi_flag(sbi, SBI_NEED_SB_WRITE);
1676         }
1677
1678         default_options(sbi);
1679
1680         /* parse mount options */
1681         err = parse_options(sb, data);
1682         if (err)
1683                 goto restore_opts;
1684         checkpoint_changed =
1685                         disable_checkpoint != test_opt(sbi, DISABLE_CHECKPOINT);
1686
1687         /*
1688          * Previous and new state of filesystem is RO,
1689          * so skip checking GC and FLUSH_MERGE conditions.
1690          */
1691         if (f2fs_readonly(sb) && (*flags & SB_RDONLY))
1692                 goto skip;
1693
1694 #ifdef CONFIG_QUOTA
1695         if (!f2fs_readonly(sb) && (*flags & SB_RDONLY)) {
1696                 err = dquot_suspend(sb, -1);
1697                 if (err < 0)
1698                         goto restore_opts;
1699         } else if (f2fs_readonly(sb) && !(*flags & SB_RDONLY)) {
1700                 /* dquot_resume needs RW */
1701                 sb->s_flags &= ~SB_RDONLY;
1702                 if (sb_any_quota_suspended(sb)) {
1703                         dquot_resume(sb, -1);
1704                 } else if (f2fs_sb_has_quota_ino(sbi)) {
1705                         err = f2fs_enable_quotas(sb);
1706                         if (err)
1707                                 goto restore_opts;
1708                 }
1709         }
1710 #endif
1711         /* disallow enable/disable extent_cache dynamically */
1712         if (no_extent_cache == !!test_opt(sbi, EXTENT_CACHE)) {
1713                 err = -EINVAL;
1714                 f2fs_warn(sbi, "switch extent_cache option is not allowed");
1715                 goto restore_opts;
1716         }
1717
1718         if (no_io_align == !!F2FS_IO_ALIGNED(sbi)) {
1719                 err = -EINVAL;
1720                 f2fs_warn(sbi, "switch io_bits option is not allowed");
1721                 goto restore_opts;
1722         }
1723
1724         if ((*flags & SB_RDONLY) && test_opt(sbi, DISABLE_CHECKPOINT)) {
1725                 err = -EINVAL;
1726                 f2fs_warn(sbi, "disabling checkpoint not compatible with read-only");
1727                 goto restore_opts;
1728         }
1729
1730         /*
1731          * We stop the GC thread if FS is mounted as RO
1732          * or if background_gc = off is passed in mount
1733          * option. Also sync the filesystem.
1734          */
1735         if ((*flags & SB_RDONLY) || !test_opt(sbi, BG_GC)) {
1736                 if (sbi->gc_thread) {
1737                         f2fs_stop_gc_thread(sbi);
1738                         need_restart_gc = true;
1739                 }
1740         } else if (!sbi->gc_thread) {
1741                 err = f2fs_start_gc_thread(sbi);
1742                 if (err)
1743                         goto restore_opts;
1744                 need_stop_gc = true;
1745         }
1746
1747         if (*flags & SB_RDONLY ||
1748                 F2FS_OPTION(sbi).whint_mode != org_mount_opt.whint_mode) {
1749                 writeback_inodes_sb(sb, WB_REASON_SYNC);
1750                 sync_inodes_sb(sb);
1751
1752                 set_sbi_flag(sbi, SBI_IS_DIRTY);
1753                 set_sbi_flag(sbi, SBI_IS_CLOSE);
1754                 f2fs_sync_fs(sb, 1);
1755                 clear_sbi_flag(sbi, SBI_IS_CLOSE);
1756         }
1757
1758         if (checkpoint_changed) {
1759                 if (test_opt(sbi, DISABLE_CHECKPOINT)) {
1760                         err = f2fs_disable_checkpoint(sbi);
1761                         if (err)
1762                                 goto restore_gc;
1763                 } else {
1764                         f2fs_enable_checkpoint(sbi);
1765                 }
1766         }
1767
1768         /*
1769          * We stop issue flush thread if FS is mounted as RO
1770          * or if flush_merge is not passed in mount option.
1771          */
1772         if ((*flags & SB_RDONLY) || !test_opt(sbi, FLUSH_MERGE)) {
1773                 clear_opt(sbi, FLUSH_MERGE);
1774                 f2fs_destroy_flush_cmd_control(sbi, false);
1775         } else {
1776                 err = f2fs_create_flush_cmd_control(sbi);
1777                 if (err)
1778                         goto restore_gc;
1779         }
1780 skip:
1781 #ifdef CONFIG_QUOTA
1782         /* Release old quota file names */
1783         for (i = 0; i < MAXQUOTAS; i++)
1784                 kvfree(org_mount_opt.s_qf_names[i]);
1785 #endif
1786         /* Update the POSIXACL Flag */
1787         sb->s_flags = (sb->s_flags & ~SB_POSIXACL) |
1788                 (test_opt(sbi, POSIX_ACL) ? SB_POSIXACL : 0);
1789
1790         limit_reserve_root(sbi);
1791         adjust_unusable_cap_perc(sbi);
1792         *flags = (*flags & ~SB_LAZYTIME) | (sb->s_flags & SB_LAZYTIME);
1793         return 0;
1794 restore_gc:
1795         if (need_restart_gc) {
1796                 if (f2fs_start_gc_thread(sbi))
1797                         f2fs_warn(sbi, "background gc thread has stopped");
1798         } else if (need_stop_gc) {
1799                 f2fs_stop_gc_thread(sbi);
1800         }
1801 restore_opts:
1802 #ifdef CONFIG_QUOTA
1803         F2FS_OPTION(sbi).s_jquota_fmt = org_mount_opt.s_jquota_fmt;
1804         for (i = 0; i < MAXQUOTAS; i++) {
1805                 kvfree(F2FS_OPTION(sbi).s_qf_names[i]);
1806                 F2FS_OPTION(sbi).s_qf_names[i] = org_mount_opt.s_qf_names[i];
1807         }
1808 #endif
1809         sbi->mount_opt = org_mount_opt;
1810         sb->s_flags = old_sb_flags;
1811         return err;
1812 }
1813
1814 #ifdef CONFIG_QUOTA
1815 /* Read data from quotafile */
1816 static ssize_t f2fs_quota_read(struct super_block *sb, int type, char *data,
1817                                size_t len, loff_t off)
1818 {
1819         struct inode *inode = sb_dqopt(sb)->files[type];
1820         struct address_space *mapping = inode->i_mapping;
1821         block_t blkidx = F2FS_BYTES_TO_BLK(off);
1822         int offset = off & (sb->s_blocksize - 1);
1823         int tocopy;
1824         size_t toread;
1825         loff_t i_size = i_size_read(inode);
1826         struct page *page;
1827
1828         if (off > i_size)
1829                 return 0;
1830
1831         if (off + len > i_size)
1832                 len = i_size - off;
1833         toread = len;
1834         while (toread > 0) {
1835                 tocopy = min_t(unsigned long, sb->s_blocksize - offset, toread);
1836 repeat:
1837                 page = read_cache_page_gfp(mapping, blkidx, GFP_NOFS);
1838                 if (IS_ERR(page)) {
1839                         if (PTR_ERR(page) == -ENOMEM) {
1840                                 congestion_wait(BLK_RW_ASYNC, HZ/50);
1841                                 goto repeat;
1842                         }
1843                         set_sbi_flag(F2FS_SB(sb), SBI_QUOTA_NEED_REPAIR);
1844                         return PTR_ERR(page);
1845                 }
1846
1847                 lock_page(page);
1848
1849                 if (unlikely(page->mapping != mapping)) {
1850                         f2fs_put_page(page, 1);
1851                         goto repeat;
1852                 }
1853                 if (unlikely(!PageUptodate(page))) {
1854                         f2fs_put_page(page, 1);
1855                         set_sbi_flag(F2FS_SB(sb), SBI_QUOTA_NEED_REPAIR);
1856                         return -EIO;
1857                 }
1858
1859                 memcpy_from_page(data, page, offset, tocopy);
1860                 f2fs_put_page(page, 1);
1861
1862                 offset = 0;
1863                 toread -= tocopy;
1864                 data += tocopy;
1865                 blkidx++;
1866         }
1867         return len;
1868 }
1869
1870 /* Write to quotafile */
1871 static ssize_t f2fs_quota_write(struct super_block *sb, int type,
1872                                 const char *data, size_t len, loff_t off)
1873 {
1874         struct inode *inode = sb_dqopt(sb)->files[type];
1875         struct address_space *mapping = inode->i_mapping;
1876         const struct address_space_operations *a_ops = mapping->a_ops;
1877         int offset = off & (sb->s_blocksize - 1);
1878         size_t towrite = len;
1879         struct page *page;
1880         void *fsdata = NULL;
1881         int err = 0;
1882         int tocopy;
1883
1884         while (towrite > 0) {
1885                 tocopy = min_t(unsigned long, sb->s_blocksize - offset,
1886                                                                 towrite);
1887 retry:
1888                 err = a_ops->write_begin(NULL, mapping, off, tocopy, 0,
1889                                                         &page, &fsdata);
1890                 if (unlikely(err)) {
1891                         if (err == -ENOMEM) {
1892                                 congestion_wait(BLK_RW_ASYNC, HZ/50);
1893                                 goto retry;
1894                         }
1895                         set_sbi_flag(F2FS_SB(sb), SBI_QUOTA_NEED_REPAIR);
1896                         break;
1897                 }
1898
1899                 memcpy_to_page(page, offset, data, tocopy);
1900
1901                 a_ops->write_end(NULL, mapping, off, tocopy, tocopy,
1902                                                 page, fsdata);
1903                 offset = 0;
1904                 towrite -= tocopy;
1905                 off += tocopy;
1906                 data += tocopy;
1907                 cond_resched();
1908         }
1909
1910         if (len == towrite)
1911                 return err;
1912         inode->i_mtime = inode->i_ctime = current_time(inode);
1913         f2fs_mark_inode_dirty_sync(inode, false);
1914         return len - towrite;
1915 }
1916
1917 static struct dquot **f2fs_get_dquots(struct inode *inode)
1918 {
1919         return F2FS_I(inode)->i_dquot;
1920 }
1921
1922 static qsize_t *f2fs_get_reserved_space(struct inode *inode)
1923 {
1924         return &F2FS_I(inode)->i_reserved_quota;
1925 }
1926
1927 static int f2fs_quota_on_mount(struct f2fs_sb_info *sbi, int type)
1928 {
1929         if (is_set_ckpt_flags(sbi, CP_QUOTA_NEED_FSCK_FLAG)) {
1930                 f2fs_err(sbi, "quota sysfile may be corrupted, skip loading it");
1931                 return 0;
1932         }
1933
1934         return dquot_quota_on_mount(sbi->sb, F2FS_OPTION(sbi).s_qf_names[type],
1935                                         F2FS_OPTION(sbi).s_jquota_fmt, type);
1936 }
1937
1938 int f2fs_enable_quota_files(struct f2fs_sb_info *sbi, bool rdonly)
1939 {
1940         int enabled = 0;
1941         int i, err;
1942
1943         if (f2fs_sb_has_quota_ino(sbi) && rdonly) {
1944                 err = f2fs_enable_quotas(sbi->sb);
1945                 if (err) {
1946                         f2fs_err(sbi, "Cannot turn on quota_ino: %d", err);
1947                         return 0;
1948                 }
1949                 return 1;
1950         }
1951
1952         for (i = 0; i < MAXQUOTAS; i++) {
1953                 if (F2FS_OPTION(sbi).s_qf_names[i]) {
1954                         err = f2fs_quota_on_mount(sbi, i);
1955                         if (!err) {
1956                                 enabled = 1;
1957                                 continue;
1958                         }
1959                         f2fs_err(sbi, "Cannot turn on quotas: %d on %d",
1960                                  err, i);
1961                 }
1962         }
1963         return enabled;
1964 }
1965
1966 static int f2fs_quota_enable(struct super_block *sb, int type, int format_id,
1967                              unsigned int flags)
1968 {
1969         struct inode *qf_inode;
1970         unsigned long qf_inum;
1971         int err;
1972
1973         BUG_ON(!f2fs_sb_has_quota_ino(F2FS_SB(sb)));
1974
1975         qf_inum = f2fs_qf_ino(sb, type);
1976         if (!qf_inum)
1977                 return -EPERM;
1978
1979         qf_inode = f2fs_iget(sb, qf_inum);
1980         if (IS_ERR(qf_inode)) {
1981                 f2fs_err(F2FS_SB(sb), "Bad quota inode %u:%lu", type, qf_inum);
1982                 return PTR_ERR(qf_inode);
1983         }
1984
1985         /* Don't account quota for quota files to avoid recursion */
1986         qf_inode->i_flags |= S_NOQUOTA;
1987         err = dquot_enable(qf_inode, type, format_id, flags);
1988         iput(qf_inode);
1989         return err;
1990 }
1991
1992 static int f2fs_enable_quotas(struct super_block *sb)
1993 {
1994         struct f2fs_sb_info *sbi = F2FS_SB(sb);
1995         int type, err = 0;
1996         unsigned long qf_inum;
1997         bool quota_mopt[MAXQUOTAS] = {
1998                 test_opt(sbi, USRQUOTA),
1999                 test_opt(sbi, GRPQUOTA),
2000                 test_opt(sbi, PRJQUOTA),
2001         };
2002
2003         if (is_set_ckpt_flags(F2FS_SB(sb), CP_QUOTA_NEED_FSCK_FLAG)) {
2004                 f2fs_err(sbi, "quota file may be corrupted, skip loading it");
2005                 return 0;
2006         }
2007
2008         sb_dqopt(sb)->flags |= DQUOT_QUOTA_SYS_FILE;
2009
2010         for (type = 0; type < MAXQUOTAS; type++) {
2011                 qf_inum = f2fs_qf_ino(sb, type);
2012                 if (qf_inum) {
2013                         err = f2fs_quota_enable(sb, type, QFMT_VFS_V1,
2014                                 DQUOT_USAGE_ENABLED |
2015                                 (quota_mopt[type] ? DQUOT_LIMITS_ENABLED : 0));
2016                         if (err) {
2017                                 f2fs_err(sbi, "Failed to enable quota tracking (type=%d, err=%d). Please run fsck to fix.",
2018                                          type, err);
2019                                 for (type--; type >= 0; type--)
2020                                         dquot_quota_off(sb, type);
2021                                 set_sbi_flag(F2FS_SB(sb),
2022                                                 SBI_QUOTA_NEED_REPAIR);
2023                                 return err;
2024                         }
2025                 }
2026         }
2027         return 0;
2028 }
2029
2030 static int f2fs_quota_sync_file(struct f2fs_sb_info *sbi, int type)
2031 {
2032         struct quota_info *dqopt = sb_dqopt(sbi->sb);
2033         struct address_space *mapping = dqopt->files[type]->i_mapping;
2034         int ret = 0;
2035
2036         ret = dquot_writeback_dquots(sbi->sb, type);
2037         if (ret)
2038                 goto out;
2039
2040         ret = filemap_fdatawrite(mapping);
2041         if (ret)
2042                 goto out;
2043
2044         /* if we are using journalled quota */
2045         if (is_journalled_quota(sbi))
2046                 goto out;
2047
2048         ret = filemap_fdatawait(mapping);
2049
2050         truncate_inode_pages(&dqopt->files[type]->i_data, 0);
2051 out:
2052         if (ret)
2053                 set_sbi_flag(sbi, SBI_QUOTA_NEED_REPAIR);
2054         return ret;
2055 }
2056
2057 int f2fs_quota_sync(struct super_block *sb, int type)
2058 {
2059         struct f2fs_sb_info *sbi = F2FS_SB(sb);
2060         struct quota_info *dqopt = sb_dqopt(sb);
2061         int cnt;
2062         int ret = 0;
2063
2064         /*
2065          * Now when everything is written we can discard the pagecache so
2066          * that userspace sees the changes.
2067          */
2068         for (cnt = 0; cnt < MAXQUOTAS; cnt++) {
2069
2070                 if (type != -1 && cnt != type)
2071                         continue;
2072
2073                 if (!sb_has_quota_active(sb, cnt))
2074                         continue;
2075
2076                 if (!f2fs_sb_has_quota_ino(sbi))
2077                         inode_lock(dqopt->files[cnt]);
2078
2079                 /*
2080                  * do_quotactl
2081                  *  f2fs_quota_sync
2082                  *  down_read(quota_sem)
2083                  *  dquot_writeback_dquots()
2084                  *  f2fs_dquot_commit
2085                  *                            block_operation
2086                  *                            down_read(quota_sem)
2087                  */
2088                 f2fs_lock_op(sbi);
2089                 down_read(&sbi->quota_sem);
2090
2091                 ret = f2fs_quota_sync_file(sbi, cnt);
2092
2093                 up_read(&sbi->quota_sem);
2094                 f2fs_unlock_op(sbi);
2095
2096                 if (!f2fs_sb_has_quota_ino(sbi))
2097                         inode_unlock(dqopt->files[cnt]);
2098
2099                 if (ret)
2100                         break;
2101         }
2102         return ret;
2103 }
2104
2105 static int f2fs_quota_on(struct super_block *sb, int type, int format_id,
2106                                                         const struct path *path)
2107 {
2108         struct inode *inode;
2109         int err;
2110
2111         /* if quota sysfile exists, deny enabling quota with specific file */
2112         if (f2fs_sb_has_quota_ino(F2FS_SB(sb))) {
2113                 f2fs_err(F2FS_SB(sb), "quota sysfile already exists");
2114                 return -EBUSY;
2115         }
2116
2117         err = f2fs_quota_sync(sb, type);
2118         if (err)
2119                 return err;
2120
2121         err = dquot_quota_on(sb, type, format_id, path);
2122         if (err)
2123                 return err;
2124
2125         inode = d_inode(path->dentry);
2126
2127         inode_lock(inode);
2128         F2FS_I(inode)->i_flags |= F2FS_NOATIME_FL | F2FS_IMMUTABLE_FL;
2129         f2fs_set_inode_flags(inode);
2130         inode_unlock(inode);
2131         f2fs_mark_inode_dirty_sync(inode, false);
2132
2133         return 0;
2134 }
2135
2136 static int __f2fs_quota_off(struct super_block *sb, int type)
2137 {
2138         struct inode *inode = sb_dqopt(sb)->files[type];
2139         int err;
2140
2141         if (!inode || !igrab(inode))
2142                 return dquot_quota_off(sb, type);
2143
2144         err = f2fs_quota_sync(sb, type);
2145         if (err)
2146                 goto out_put;
2147
2148         err = dquot_quota_off(sb, type);
2149         if (err || f2fs_sb_has_quota_ino(F2FS_SB(sb)))
2150                 goto out_put;
2151
2152         inode_lock(inode);
2153         F2FS_I(inode)->i_flags &= ~(F2FS_NOATIME_FL | F2FS_IMMUTABLE_FL);
2154         f2fs_set_inode_flags(inode);
2155         inode_unlock(inode);
2156         f2fs_mark_inode_dirty_sync(inode, false);
2157 out_put:
2158         iput(inode);
2159         return err;
2160 }
2161
2162 static int f2fs_quota_off(struct super_block *sb, int type)
2163 {
2164         struct f2fs_sb_info *sbi = F2FS_SB(sb);
2165         int err;
2166
2167         err = __f2fs_quota_off(sb, type);
2168
2169         /*
2170          * quotactl can shutdown journalled quota, result in inconsistence
2171          * between quota record and fs data by following updates, tag the
2172          * flag to let fsck be aware of it.
2173          */
2174         if (is_journalled_quota(sbi))
2175                 set_sbi_flag(sbi, SBI_QUOTA_NEED_REPAIR);
2176         return err;
2177 }
2178
2179 void f2fs_quota_off_umount(struct super_block *sb)
2180 {
2181         int type;
2182         int err;
2183
2184         for (type = 0; type < MAXQUOTAS; type++) {
2185                 err = __f2fs_quota_off(sb, type);
2186                 if (err) {
2187                         int ret = dquot_quota_off(sb, type);
2188
2189                         f2fs_err(F2FS_SB(sb), "Fail to turn off disk quota (type: %d, err: %d, ret:%d), Please run fsck to fix it.",
2190                                  type, err, ret);
2191                         set_sbi_flag(F2FS_SB(sb), SBI_QUOTA_NEED_REPAIR);
2192                 }
2193         }
2194         /*
2195          * In case of checkpoint=disable, we must flush quota blocks.
2196          * This can cause NULL exception for node_inode in end_io, since
2197          * put_super already dropped it.
2198          */
2199         sync_filesystem(sb);
2200 }
2201
2202 static void f2fs_truncate_quota_inode_pages(struct super_block *sb)
2203 {
2204         struct quota_info *dqopt = sb_dqopt(sb);
2205         int type;
2206
2207         for (type = 0; type < MAXQUOTAS; type++) {
2208                 if (!dqopt->files[type])
2209                         continue;
2210                 f2fs_inode_synced(dqopt->files[type]);
2211         }
2212 }
2213
2214 static int f2fs_dquot_commit(struct dquot *dquot)
2215 {
2216         struct f2fs_sb_info *sbi = F2FS_SB(dquot->dq_sb);
2217         int ret;
2218
2219         down_read(&sbi->quota_sem);
2220         ret = dquot_commit(dquot);
2221         if (ret < 0)
2222                 set_sbi_flag(sbi, SBI_QUOTA_NEED_REPAIR);
2223         up_read(&sbi->quota_sem);
2224         return ret;
2225 }
2226
2227 static int f2fs_dquot_acquire(struct dquot *dquot)
2228 {
2229         struct f2fs_sb_info *sbi = F2FS_SB(dquot->dq_sb);
2230         int ret;
2231
2232         down_read(&sbi->quota_sem);
2233         ret = dquot_acquire(dquot);
2234         if (ret < 0)
2235                 set_sbi_flag(sbi, SBI_QUOTA_NEED_REPAIR);
2236         up_read(&sbi->quota_sem);
2237         return ret;
2238 }
2239
2240 static int f2fs_dquot_release(struct dquot *dquot)
2241 {
2242         struct f2fs_sb_info *sbi = F2FS_SB(dquot->dq_sb);
2243         int ret;
2244
2245         down_read(&sbi->quota_sem);
2246         ret = dquot_release(dquot);
2247         if (ret < 0)
2248                 set_sbi_flag(sbi, SBI_QUOTA_NEED_REPAIR);
2249         up_read(&sbi->quota_sem);
2250         return ret;
2251 }
2252
2253 static int f2fs_dquot_mark_dquot_dirty(struct dquot *dquot)
2254 {
2255         struct super_block *sb = dquot->dq_sb;
2256         struct f2fs_sb_info *sbi = F2FS_SB(sb);
2257         int ret;
2258
2259         down_read(&sbi->quota_sem);
2260         ret = dquot_mark_dquot_dirty(dquot);
2261
2262         /* if we are using journalled quota */
2263         if (is_journalled_quota(sbi))
2264                 set_sbi_flag(sbi, SBI_QUOTA_NEED_FLUSH);
2265
2266         up_read(&sbi->quota_sem);
2267         return ret;
2268 }
2269
2270 static int f2fs_dquot_commit_info(struct super_block *sb, int type)
2271 {
2272         struct f2fs_sb_info *sbi = F2FS_SB(sb);
2273         int ret;
2274
2275         down_read(&sbi->quota_sem);
2276         ret = dquot_commit_info(sb, type);
2277         if (ret < 0)
2278                 set_sbi_flag(sbi, SBI_QUOTA_NEED_REPAIR);
2279         up_read(&sbi->quota_sem);
2280         return ret;
2281 }
2282
2283 static int f2fs_get_projid(struct inode *inode, kprojid_t *projid)
2284 {
2285         *projid = F2FS_I(inode)->i_projid;
2286         return 0;
2287 }
2288
2289 static const struct dquot_operations f2fs_quota_operations = {
2290         .get_reserved_space = f2fs_get_reserved_space,
2291         .write_dquot    = f2fs_dquot_commit,
2292         .acquire_dquot  = f2fs_dquot_acquire,
2293         .release_dquot  = f2fs_dquot_release,
2294         .mark_dirty     = f2fs_dquot_mark_dquot_dirty,
2295         .write_info     = f2fs_dquot_commit_info,
2296         .alloc_dquot    = dquot_alloc,
2297         .destroy_dquot  = dquot_destroy,
2298         .get_projid     = f2fs_get_projid,
2299         .get_next_id    = dquot_get_next_id,
2300 };
2301
2302 static const struct quotactl_ops f2fs_quotactl_ops = {
2303         .quota_on       = f2fs_quota_on,
2304         .quota_off      = f2fs_quota_off,
2305         .quota_sync     = f2fs_quota_sync,
2306         .get_state      = dquot_get_state,
2307         .set_info       = dquot_set_dqinfo,
2308         .get_dqblk      = dquot_get_dqblk,
2309         .set_dqblk      = dquot_set_dqblk,
2310         .get_nextdqblk  = dquot_get_next_dqblk,
2311 };
2312 #else
2313 int f2fs_quota_sync(struct super_block *sb, int type)
2314 {
2315         return 0;
2316 }
2317
2318 void f2fs_quota_off_umount(struct super_block *sb)
2319 {
2320 }
2321 #endif
2322
2323 static const struct super_operations f2fs_sops = {
2324         .alloc_inode    = f2fs_alloc_inode,
2325         .free_inode     = f2fs_free_inode,
2326         .drop_inode     = f2fs_drop_inode,
2327         .write_inode    = f2fs_write_inode,
2328         .dirty_inode    = f2fs_dirty_inode,
2329         .show_options   = f2fs_show_options,
2330 #ifdef CONFIG_QUOTA
2331         .quota_read     = f2fs_quota_read,
2332         .quota_write    = f2fs_quota_write,
2333         .get_dquots     = f2fs_get_dquots,
2334 #endif
2335         .evict_inode    = f2fs_evict_inode,
2336         .put_super      = f2fs_put_super,
2337         .sync_fs        = f2fs_sync_fs,
2338         .freeze_fs      = f2fs_freeze,
2339         .unfreeze_fs    = f2fs_unfreeze,
2340         .statfs         = f2fs_statfs,
2341         .remount_fs     = f2fs_remount,
2342 };
2343
2344 #ifdef CONFIG_FS_ENCRYPTION
2345 static int f2fs_get_context(struct inode *inode, void *ctx, size_t len)
2346 {
2347         return f2fs_getxattr(inode, F2FS_XATTR_INDEX_ENCRYPTION,
2348                                 F2FS_XATTR_NAME_ENCRYPTION_CONTEXT,
2349                                 ctx, len, NULL);
2350 }
2351
2352 static int f2fs_set_context(struct inode *inode, const void *ctx, size_t len,
2353                                                         void *fs_data)
2354 {
2355         struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
2356
2357         /*
2358          * Encrypting the root directory is not allowed because fsck
2359          * expects lost+found directory to exist and remain unencrypted
2360          * if LOST_FOUND feature is enabled.
2361          *
2362          */
2363         if (f2fs_sb_has_lost_found(sbi) &&
2364                         inode->i_ino == F2FS_ROOT_INO(sbi))
2365                 return -EPERM;
2366
2367         return f2fs_setxattr(inode, F2FS_XATTR_INDEX_ENCRYPTION,
2368                                 F2FS_XATTR_NAME_ENCRYPTION_CONTEXT,
2369                                 ctx, len, fs_data, XATTR_CREATE);
2370 }
2371
2372 static bool f2fs_dummy_context(struct inode *inode)
2373 {
2374         return DUMMY_ENCRYPTION_ENABLED(F2FS_I_SB(inode));
2375 }
2376
2377 static const struct fscrypt_operations f2fs_cryptops = {
2378         .key_prefix     = "f2fs:",
2379         .get_context    = f2fs_get_context,
2380         .set_context    = f2fs_set_context,
2381         .dummy_context  = f2fs_dummy_context,
2382         .empty_dir      = f2fs_empty_dir,
2383         .max_namelen    = F2FS_NAME_LEN,
2384 };
2385 #endif
2386
2387 static struct inode *f2fs_nfs_get_inode(struct super_block *sb,
2388                 u64 ino, u32 generation)
2389 {
2390         struct f2fs_sb_info *sbi = F2FS_SB(sb);
2391         struct inode *inode;
2392
2393         if (f2fs_check_nid_range(sbi, ino))
2394                 return ERR_PTR(-ESTALE);
2395
2396         /*
2397          * f2fs_iget isn't quite right if the inode is currently unallocated!
2398          * However f2fs_iget currently does appropriate checks to handle stale
2399          * inodes so everything is OK.
2400          */
2401         inode = f2fs_iget(sb, ino);
2402         if (IS_ERR(inode))
2403                 return ERR_CAST(inode);
2404         if (unlikely(generation && inode->i_generation != generation)) {
2405                 /* we didn't find the right inode.. */
2406                 iput(inode);
2407                 return ERR_PTR(-ESTALE);
2408         }
2409         return inode;
2410 }
2411
2412 static struct dentry *f2fs_fh_to_dentry(struct super_block *sb, struct fid *fid,
2413                 int fh_len, int fh_type)
2414 {
2415         return generic_fh_to_dentry(sb, fid, fh_len, fh_type,
2416                                     f2fs_nfs_get_inode);
2417 }
2418
2419 static struct dentry *f2fs_fh_to_parent(struct super_block *sb, struct fid *fid,
2420                 int fh_len, int fh_type)
2421 {
2422         return generic_fh_to_parent(sb, fid, fh_len, fh_type,
2423                                     f2fs_nfs_get_inode);
2424 }
2425
2426 static const struct export_operations f2fs_export_ops = {
2427         .fh_to_dentry = f2fs_fh_to_dentry,
2428         .fh_to_parent = f2fs_fh_to_parent,
2429         .get_parent = f2fs_get_parent,
2430 };
2431
2432 static loff_t max_file_blocks(void)
2433 {
2434         loff_t result = 0;
2435         loff_t leaf_count = DEF_ADDRS_PER_BLOCK;
2436
2437         /*
2438          * note: previously, result is equal to (DEF_ADDRS_PER_INODE -
2439          * DEFAULT_INLINE_XATTR_ADDRS), but now f2fs try to reserve more
2440          * space in inode.i_addr, it will be more safe to reassign
2441          * result as zero.
2442          */
2443
2444         /* two direct node blocks */
2445         result += (leaf_count * 2);
2446
2447         /* two indirect node blocks */
2448         leaf_count *= NIDS_PER_BLOCK;
2449         result += (leaf_count * 2);
2450
2451         /* one double indirect node block */
2452         leaf_count *= NIDS_PER_BLOCK;
2453         result += leaf_count;
2454
2455         return result;
2456 }
2457
2458 static int __f2fs_commit_super(struct buffer_head *bh,
2459                         struct f2fs_super_block *super)
2460 {
2461         lock_buffer(bh);
2462         if (super)
2463                 memcpy(bh->b_data + F2FS_SUPER_OFFSET, super, sizeof(*super));
2464         set_buffer_dirty(bh);
2465         unlock_buffer(bh);
2466
2467         /* it's rare case, we can do fua all the time */
2468         return __sync_dirty_buffer(bh, REQ_SYNC | REQ_PREFLUSH | REQ_FUA);
2469 }
2470
2471 static inline bool sanity_check_area_boundary(struct f2fs_sb_info *sbi,
2472                                         struct buffer_head *bh)
2473 {
2474         struct f2fs_super_block *raw_super = (struct f2fs_super_block *)
2475                                         (bh->b_data + F2FS_SUPER_OFFSET);
2476         struct super_block *sb = sbi->sb;
2477         u32 segment0_blkaddr = le32_to_cpu(raw_super->segment0_blkaddr);
2478         u32 cp_blkaddr = le32_to_cpu(raw_super->cp_blkaddr);
2479         u32 sit_blkaddr = le32_to_cpu(raw_super->sit_blkaddr);
2480         u32 nat_blkaddr = le32_to_cpu(raw_super->nat_blkaddr);
2481         u32 ssa_blkaddr = le32_to_cpu(raw_super->ssa_blkaddr);
2482         u32 main_blkaddr = le32_to_cpu(raw_super->main_blkaddr);
2483         u32 segment_count_ckpt = le32_to_cpu(raw_super->segment_count_ckpt);
2484         u32 segment_count_sit = le32_to_cpu(raw_super->segment_count_sit);
2485         u32 segment_count_nat = le32_to_cpu(raw_super->segment_count_nat);
2486         u32 segment_count_ssa = le32_to_cpu(raw_super->segment_count_ssa);
2487         u32 segment_count_main = le32_to_cpu(raw_super->segment_count_main);
2488         u32 segment_count = le32_to_cpu(raw_super->segment_count);
2489         u32 log_blocks_per_seg = le32_to_cpu(raw_super->log_blocks_per_seg);
2490         u64 main_end_blkaddr = main_blkaddr +
2491                                 (segment_count_main << log_blocks_per_seg);
2492         u64 seg_end_blkaddr = segment0_blkaddr +
2493                                 (segment_count << log_blocks_per_seg);
2494
2495         if (segment0_blkaddr != cp_blkaddr) {
2496                 f2fs_info(sbi, "Mismatch start address, segment0(%u) cp_blkaddr(%u)",
2497                           segment0_blkaddr, cp_blkaddr);
2498                 return true;
2499         }
2500
2501         if (cp_blkaddr + (segment_count_ckpt << log_blocks_per_seg) !=
2502                                                         sit_blkaddr) {
2503                 f2fs_info(sbi, "Wrong CP boundary, start(%u) end(%u) blocks(%u)",
2504                           cp_blkaddr, sit_blkaddr,
2505                           segment_count_ckpt << log_blocks_per_seg);
2506                 return true;
2507         }
2508
2509         if (sit_blkaddr + (segment_count_sit << log_blocks_per_seg) !=
2510                                                         nat_blkaddr) {
2511                 f2fs_info(sbi, "Wrong SIT boundary, start(%u) end(%u) blocks(%u)",
2512                           sit_blkaddr, nat_blkaddr,
2513                           segment_count_sit << log_blocks_per_seg);
2514                 return true;
2515         }
2516
2517         if (nat_blkaddr + (segment_count_nat << log_blocks_per_seg) !=
2518                                                         ssa_blkaddr) {
2519                 f2fs_info(sbi, "Wrong NAT boundary, start(%u) end(%u) blocks(%u)",
2520                           nat_blkaddr, ssa_blkaddr,
2521                           segment_count_nat << log_blocks_per_seg);
2522                 return true;
2523         }
2524
2525         if (ssa_blkaddr + (segment_count_ssa << log_blocks_per_seg) !=
2526                                                         main_blkaddr) {
2527                 f2fs_info(sbi, "Wrong SSA boundary, start(%u) end(%u) blocks(%u)",
2528                           ssa_blkaddr, main_blkaddr,
2529                           segment_count_ssa << log_blocks_per_seg);
2530                 return true;
2531         }
2532
2533         if (main_end_blkaddr > seg_end_blkaddr) {
2534                 f2fs_info(sbi, "Wrong MAIN_AREA boundary, start(%u) end(%u) block(%u)",
2535                           main_blkaddr,
2536                           segment0_blkaddr +
2537                           (segment_count << log_blocks_per_seg),
2538                           segment_count_main << log_blocks_per_seg);
2539                 return true;
2540         } else if (main_end_blkaddr < seg_end_blkaddr) {
2541                 int err = 0;
2542                 char *res;
2543
2544                 /* fix in-memory information all the time */
2545                 raw_super->segment_count = cpu_to_le32((main_end_blkaddr -
2546                                 segment0_blkaddr) >> log_blocks_per_seg);
2547
2548                 if (f2fs_readonly(sb) || bdev_read_only(sb->s_bdev)) {
2549                         set_sbi_flag(sbi, SBI_NEED_SB_WRITE);
2550                         res = "internally";
2551                 } else {
2552                         err = __f2fs_commit_super(bh, NULL);
2553                         res = err ? "failed" : "done";
2554                 }
2555                 f2fs_info(sbi, "Fix alignment : %s, start(%u) end(%u) block(%u)",
2556                           res, main_blkaddr,
2557                           segment0_blkaddr +
2558                           (segment_count << log_blocks_per_seg),
2559                           segment_count_main << log_blocks_per_seg);
2560                 if (err)
2561                         return true;
2562         }
2563         return false;
2564 }
2565
2566 static int sanity_check_raw_super(struct f2fs_sb_info *sbi,
2567                                 struct buffer_head *bh)
2568 {
2569         block_t segment_count, segs_per_sec, secs_per_zone;
2570         block_t total_sections, blocks_per_seg;
2571         struct f2fs_super_block *raw_super = (struct f2fs_super_block *)
2572                                         (bh->b_data + F2FS_SUPER_OFFSET);
2573         size_t crc_offset = 0;
2574         __u32 crc = 0;
2575
2576         if (le32_to_cpu(raw_super->magic) != F2FS_SUPER_MAGIC) {
2577                 f2fs_info(sbi, "Magic Mismatch, valid(0x%x) - read(0x%x)",
2578                           F2FS_SUPER_MAGIC, le32_to_cpu(raw_super->magic));
2579                 return -EINVAL;
2580         }
2581
2582         /* Check checksum_offset and crc in superblock */
2583         if (__F2FS_HAS_FEATURE(raw_super, F2FS_FEATURE_SB_CHKSUM)) {
2584                 crc_offset = le32_to_cpu(raw_super->checksum_offset);
2585                 if (crc_offset !=
2586                         offsetof(struct f2fs_super_block, crc)) {
2587                         f2fs_info(sbi, "Invalid SB checksum offset: %zu",
2588                                   crc_offset);
2589                         return -EFSCORRUPTED;
2590                 }
2591                 crc = le32_to_cpu(raw_super->crc);
2592                 if (!f2fs_crc_valid(sbi, crc, raw_super, crc_offset)) {
2593                         f2fs_info(sbi, "Invalid SB checksum value: %u", crc);
2594                         return -EFSCORRUPTED;
2595                 }
2596         }
2597
2598         /* Currently, support only 4KB page cache size */
2599         if (F2FS_BLKSIZE != PAGE_SIZE) {
2600                 f2fs_info(sbi, "Invalid page_cache_size (%lu), supports only 4KB",
2601                           PAGE_SIZE);
2602                 return -EFSCORRUPTED;
2603         }
2604
2605         /* Currently, support only 4KB block size */
2606         if (le32_to_cpu(raw_super->log_blocksize) != F2FS_BLKSIZE_BITS) {
2607                 f2fs_info(sbi, "Invalid log_blocksize (%u), supports only %u",
2608                           le32_to_cpu(raw_super->log_blocksize),
2609                           F2FS_BLKSIZE_BITS);
2610                 return -EFSCORRUPTED;
2611         }
2612
2613         /* check log blocks per segment */
2614         if (le32_to_cpu(raw_super->log_blocks_per_seg) != 9) {
2615                 f2fs_info(sbi, "Invalid log blocks per segment (%u)",
2616                           le32_to_cpu(raw_super->log_blocks_per_seg));
2617                 return -EFSCORRUPTED;
2618         }
2619
2620         /* Currently, support 512/1024/2048/4096 bytes sector size */
2621         if (le32_to_cpu(raw_super->log_sectorsize) >
2622                                 F2FS_MAX_LOG_SECTOR_SIZE ||
2623                 le32_to_cpu(raw_super->log_sectorsize) <
2624                                 F2FS_MIN_LOG_SECTOR_SIZE) {
2625                 f2fs_info(sbi, "Invalid log sectorsize (%u)",
2626                           le32_to_cpu(raw_super->log_sectorsize));
2627                 return -EFSCORRUPTED;
2628         }
2629         if (le32_to_cpu(raw_super->log_sectors_per_block) +
2630                 le32_to_cpu(raw_super->log_sectorsize) !=
2631                         F2FS_MAX_LOG_SECTOR_SIZE) {
2632                 f2fs_info(sbi, "Invalid log sectors per block(%u) log sectorsize(%u)",
2633                           le32_to_cpu(raw_super->log_sectors_per_block),
2634                           le32_to_cpu(raw_super->log_sectorsize));
2635                 return -EFSCORRUPTED;
2636         }
2637
2638         segment_count = le32_to_cpu(raw_super->segment_count);
2639         segs_per_sec = le32_to_cpu(raw_super->segs_per_sec);
2640         secs_per_zone = le32_to_cpu(raw_super->secs_per_zone);
2641         total_sections = le32_to_cpu(raw_super->section_count);
2642
2643         /* blocks_per_seg should be 512, given the above check */
2644         blocks_per_seg = 1 << le32_to_cpu(raw_super->log_blocks_per_seg);
2645
2646         if (segment_count > F2FS_MAX_SEGMENT ||
2647                                 segment_count < F2FS_MIN_SEGMENTS) {
2648                 f2fs_info(sbi, "Invalid segment count (%u)", segment_count);
2649                 return -EFSCORRUPTED;
2650         }
2651
2652         if (total_sections > segment_count ||
2653                         total_sections < F2FS_MIN_SEGMENTS ||
2654                         segs_per_sec > segment_count || !segs_per_sec) {
2655                 f2fs_info(sbi, "Invalid segment/section count (%u, %u x %u)",
2656                           segment_count, total_sections, segs_per_sec);
2657                 return -EFSCORRUPTED;
2658         }
2659
2660         if ((segment_count / segs_per_sec) < total_sections) {
2661                 f2fs_info(sbi, "Small segment_count (%u < %u * %u)",
2662                           segment_count, segs_per_sec, total_sections);
2663                 return -EFSCORRUPTED;
2664         }
2665
2666         if (segment_count > (le64_to_cpu(raw_super->block_count) >> 9)) {
2667                 f2fs_info(sbi, "Wrong segment_count / block_count (%u > %llu)",
2668                           segment_count, le64_to_cpu(raw_super->block_count));
2669                 return -EFSCORRUPTED;
2670         }
2671
2672         if (secs_per_zone > total_sections || !secs_per_zone) {
2673                 f2fs_info(sbi, "Wrong secs_per_zone / total_sections (%u, %u)",
2674                           secs_per_zone, total_sections);
2675                 return -EFSCORRUPTED;
2676         }
2677         if (le32_to_cpu(raw_super->extension_count) > F2FS_MAX_EXTENSION ||
2678                         raw_super->hot_ext_count > F2FS_MAX_EXTENSION ||
2679                         (le32_to_cpu(raw_super->extension_count) +
2680                         raw_super->hot_ext_count) > F2FS_MAX_EXTENSION) {
2681                 f2fs_info(sbi, "Corrupted extension count (%u + %u > %u)",
2682                           le32_to_cpu(raw_super->extension_count),
2683                           raw_super->hot_ext_count,
2684                           F2FS_MAX_EXTENSION);
2685                 return -EFSCORRUPTED;
2686         }
2687
2688         if (le32_to_cpu(raw_super->cp_payload) >
2689                                 (blocks_per_seg - F2FS_CP_PACKS)) {
2690                 f2fs_info(sbi, "Insane cp_payload (%u > %u)",
2691                           le32_to_cpu(raw_super->cp_payload),
2692                           blocks_per_seg - F2FS_CP_PACKS);
2693                 return -EFSCORRUPTED;
2694         }
2695
2696         /* check reserved ino info */
2697         if (le32_to_cpu(raw_super->node_ino) != 1 ||
2698                 le32_to_cpu(raw_super->meta_ino) != 2 ||
2699                 le32_to_cpu(raw_super->root_ino) != 3) {
2700                 f2fs_info(sbi, "Invalid Fs Meta Ino: node(%u) meta(%u) root(%u)",
2701                           le32_to_cpu(raw_super->node_ino),
2702                           le32_to_cpu(raw_super->meta_ino),
2703                           le32_to_cpu(raw_super->root_ino));
2704                 return -EFSCORRUPTED;
2705         }
2706
2707         /* check CP/SIT/NAT/SSA/MAIN_AREA area boundary */
2708         if (sanity_check_area_boundary(sbi, bh))
2709                 return -EFSCORRUPTED;
2710
2711         return 0;
2712 }
2713
2714 int f2fs_sanity_check_ckpt(struct f2fs_sb_info *sbi)
2715 {
2716         unsigned int total, fsmeta;
2717         struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi);
2718         struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
2719         unsigned int ovp_segments, reserved_segments;
2720         unsigned int main_segs, blocks_per_seg;
2721         unsigned int sit_segs, nat_segs;
2722         unsigned int sit_bitmap_size, nat_bitmap_size;
2723         unsigned int log_blocks_per_seg;
2724         unsigned int segment_count_main;
2725         unsigned int cp_pack_start_sum, cp_payload;
2726         block_t user_block_count, valid_user_blocks;
2727         block_t avail_node_count, valid_node_count;
2728         int i, j;
2729
2730         total = le32_to_cpu(raw_super->segment_count);
2731         fsmeta = le32_to_cpu(raw_super->segment_count_ckpt);
2732         sit_segs = le32_to_cpu(raw_super->segment_count_sit);
2733         fsmeta += sit_segs;
2734         nat_segs = le32_to_cpu(raw_super->segment_count_nat);
2735         fsmeta += nat_segs;
2736         fsmeta += le32_to_cpu(ckpt->rsvd_segment_count);
2737         fsmeta += le32_to_cpu(raw_super->segment_count_ssa);
2738
2739         if (unlikely(fsmeta >= total))
2740                 return 1;
2741
2742         ovp_segments = le32_to_cpu(ckpt->overprov_segment_count);
2743         reserved_segments = le32_to_cpu(ckpt->rsvd_segment_count);
2744
2745         if (unlikely(fsmeta < F2FS_MIN_SEGMENTS ||
2746                         ovp_segments == 0 || reserved_segments == 0)) {
2747                 f2fs_err(sbi, "Wrong layout: check mkfs.f2fs version");
2748                 return 1;
2749         }
2750
2751         user_block_count = le64_to_cpu(ckpt->user_block_count);
2752         segment_count_main = le32_to_cpu(raw_super->segment_count_main);
2753         log_blocks_per_seg = le32_to_cpu(raw_super->log_blocks_per_seg);
2754         if (!user_block_count || user_block_count >=
2755                         segment_count_main << log_blocks_per_seg) {
2756                 f2fs_err(sbi, "Wrong user_block_count: %u",
2757                          user_block_count);
2758                 return 1;
2759         }
2760
2761         valid_user_blocks = le64_to_cpu(ckpt->valid_block_count);
2762         if (valid_user_blocks > user_block_count) {
2763                 f2fs_err(sbi, "Wrong valid_user_blocks: %u, user_block_count: %u",
2764                          valid_user_blocks, user_block_count);
2765                 return 1;
2766         }
2767
2768         valid_node_count = le32_to_cpu(ckpt->valid_node_count);
2769         avail_node_count = sbi->total_node_count - F2FS_RESERVED_NODE_NUM;
2770         if (valid_node_count > avail_node_count) {
2771                 f2fs_err(sbi, "Wrong valid_node_count: %u, avail_node_count: %u",
2772                          valid_node_count, avail_node_count);
2773                 return 1;
2774         }
2775
2776         main_segs = le32_to_cpu(raw_super->segment_count_main);
2777         blocks_per_seg = sbi->blocks_per_seg;
2778
2779         for (i = 0; i < NR_CURSEG_NODE_TYPE; i++) {
2780                 if (le32_to_cpu(ckpt->cur_node_segno[i]) >= main_segs ||
2781                         le16_to_cpu(ckpt->cur_node_blkoff[i]) >= blocks_per_seg)
2782                         return 1;
2783                 for (j = i + 1; j < NR_CURSEG_NODE_TYPE; j++) {
2784                         if (le32_to_cpu(ckpt->cur_node_segno[i]) ==
2785                                 le32_to_cpu(ckpt->cur_node_segno[j])) {
2786                                 f2fs_err(sbi, "Node segment (%u, %u) has the same segno: %u",
2787                                          i, j,
2788                                          le32_to_cpu(ckpt->cur_node_segno[i]));
2789                                 return 1;
2790                         }
2791                 }
2792         }
2793         for (i = 0; i < NR_CURSEG_DATA_TYPE; i++) {
2794                 if (le32_to_cpu(ckpt->cur_data_segno[i]) >= main_segs ||
2795                         le16_to_cpu(ckpt->cur_data_blkoff[i]) >= blocks_per_seg)
2796                         return 1;
2797                 for (j = i + 1; j < NR_CURSEG_DATA_TYPE; j++) {
2798                         if (le32_to_cpu(ckpt->cur_data_segno[i]) ==
2799                                 le32_to_cpu(ckpt->cur_data_segno[j])) {
2800                                 f2fs_err(sbi, "Data segment (%u, %u) has the same segno: %u",
2801                                          i, j,
2802                                          le32_to_cpu(ckpt->cur_data_segno[i]));
2803                                 return 1;
2804                         }
2805                 }
2806         }
2807         for (i = 0; i < NR_CURSEG_NODE_TYPE; i++) {
2808                 for (j = 0; j < NR_CURSEG_DATA_TYPE; j++) {
2809                         if (le32_to_cpu(ckpt->cur_node_segno[i]) ==
2810                                 le32_to_cpu(ckpt->cur_data_segno[j])) {
2811                                 f2fs_err(sbi, "Node segment (%u) and Data segment (%u) has the same segno: %u",
2812                                          i, j,
2813                                          le32_to_cpu(ckpt->cur_node_segno[i]));
2814                                 return 1;
2815                         }
2816                 }
2817         }
2818
2819         sit_bitmap_size = le32_to_cpu(ckpt->sit_ver_bitmap_bytesize);
2820         nat_bitmap_size = le32_to_cpu(ckpt->nat_ver_bitmap_bytesize);
2821
2822         if (sit_bitmap_size != ((sit_segs / 2) << log_blocks_per_seg) / 8 ||
2823                 nat_bitmap_size != ((nat_segs / 2) << log_blocks_per_seg) / 8) {
2824                 f2fs_err(sbi, "Wrong bitmap size: sit: %u, nat:%u",
2825                          sit_bitmap_size, nat_bitmap_size);
2826                 return 1;
2827         }
2828
2829         cp_pack_start_sum = __start_sum_addr(sbi);
2830         cp_payload = __cp_payload(sbi);
2831         if (cp_pack_start_sum < cp_payload + 1 ||
2832                 cp_pack_start_sum > blocks_per_seg - 1 -
2833                         NR_CURSEG_TYPE) {
2834                 f2fs_err(sbi, "Wrong cp_pack_start_sum: %u",
2835                          cp_pack_start_sum);
2836                 return 1;
2837         }
2838
2839         if (__is_set_ckpt_flags(ckpt, CP_LARGE_NAT_BITMAP_FLAG) &&
2840                 le32_to_cpu(ckpt->checksum_offset) != CP_MIN_CHKSUM_OFFSET) {
2841                 f2fs_warn(sbi, "using deprecated layout of large_nat_bitmap, "
2842                           "please run fsck v1.13.0 or higher to repair, chksum_offset: %u, "
2843                           "fixed with patch: \"f2fs-tools: relocate chksum_offset for large_nat_bitmap feature\"",
2844                           le32_to_cpu(ckpt->checksum_offset));
2845                 return 1;
2846         }
2847
2848         if (unlikely(f2fs_cp_error(sbi))) {
2849                 f2fs_err(sbi, "A bug case: need to run fsck");
2850                 return 1;
2851         }
2852         return 0;
2853 }
2854
2855 static void init_sb_info(struct f2fs_sb_info *sbi)
2856 {
2857         struct f2fs_super_block *raw_super = sbi->raw_super;
2858         int i;
2859
2860         sbi->log_sectors_per_block =
2861                 le32_to_cpu(raw_super->log_sectors_per_block);
2862         sbi->log_blocksize = le32_to_cpu(raw_super->log_blocksize);
2863         sbi->blocksize = 1 << sbi->log_blocksize;
2864         sbi->log_blocks_per_seg = le32_to_cpu(raw_super->log_blocks_per_seg);
2865         sbi->blocks_per_seg = 1 << sbi->log_blocks_per_seg;
2866         sbi->segs_per_sec = le32_to_cpu(raw_super->segs_per_sec);
2867         sbi->secs_per_zone = le32_to_cpu(raw_super->secs_per_zone);
2868         sbi->total_sections = le32_to_cpu(raw_super->section_count);
2869         sbi->total_node_count =
2870                 (le32_to_cpu(raw_super->segment_count_nat) / 2)
2871                         * sbi->blocks_per_seg * NAT_ENTRY_PER_BLOCK;
2872         sbi->root_ino_num = le32_to_cpu(raw_super->root_ino);
2873         sbi->node_ino_num = le32_to_cpu(raw_super->node_ino);
2874         sbi->meta_ino_num = le32_to_cpu(raw_super->meta_ino);
2875         sbi->cur_victim_sec = NULL_SECNO;
2876         sbi->next_victim_seg[BG_GC] = NULL_SEGNO;
2877         sbi->next_victim_seg[FG_GC] = NULL_SEGNO;
2878         sbi->max_victim_search = DEF_MAX_VICTIM_SEARCH;
2879         sbi->migration_granularity = sbi->segs_per_sec;
2880
2881         sbi->dir_level = DEF_DIR_LEVEL;
2882         sbi->interval_time[CP_TIME] = DEF_CP_INTERVAL;
2883         sbi->interval_time[REQ_TIME] = DEF_IDLE_INTERVAL;
2884         sbi->interval_time[DISCARD_TIME] = DEF_IDLE_INTERVAL;
2885         sbi->interval_time[GC_TIME] = DEF_IDLE_INTERVAL;
2886         sbi->interval_time[DISABLE_TIME] = DEF_DISABLE_INTERVAL;
2887         sbi->interval_time[UMOUNT_DISCARD_TIMEOUT] =
2888                                 DEF_UMOUNT_DISCARD_TIMEOUT;
2889         clear_sbi_flag(sbi, SBI_NEED_FSCK);
2890
2891         for (i = 0; i < NR_COUNT_TYPE; i++)
2892                 atomic_set(&sbi->nr_pages[i], 0);
2893
2894         for (i = 0; i < META; i++)
2895                 atomic_set(&sbi->wb_sync_req[i], 0);
2896
2897         INIT_LIST_HEAD(&sbi->s_list);
2898         mutex_init(&sbi->umount_mutex);
2899         init_rwsem(&sbi->io_order_lock);
2900         spin_lock_init(&sbi->cp_lock);
2901
2902         sbi->dirty_device = 0;
2903         spin_lock_init(&sbi->dev_lock);
2904
2905         init_rwsem(&sbi->sb_lock);
2906 }
2907
2908 static int init_percpu_info(struct f2fs_sb_info *sbi)
2909 {
2910         int err;
2911
2912         err = percpu_counter_init(&sbi->alloc_valid_block_count, 0, GFP_KERNEL);
2913         if (err)
2914                 return err;
2915
2916         err = percpu_counter_init(&sbi->total_valid_inode_count, 0,
2917                                                                 GFP_KERNEL);
2918         if (err)
2919                 percpu_counter_destroy(&sbi->alloc_valid_block_count);
2920
2921         return err;
2922 }
2923
2924 #ifdef CONFIG_BLK_DEV_ZONED
2925 static int init_blkz_info(struct f2fs_sb_info *sbi, int devi)
2926 {
2927         struct block_device *bdev = FDEV(devi).bdev;
2928         sector_t nr_sectors = bdev->bd_part->nr_sects;
2929         sector_t sector = 0;
2930         struct blk_zone *zones;
2931         unsigned int i, nr_zones;
2932         unsigned int n = 0;
2933         int err = -EIO;
2934
2935         if (!f2fs_sb_has_blkzoned(sbi))
2936                 return 0;
2937
2938         if (sbi->blocks_per_blkz && sbi->blocks_per_blkz !=
2939                                 SECTOR_TO_BLOCK(bdev_zone_sectors(bdev)))
2940                 return -EINVAL;
2941         sbi->blocks_per_blkz = SECTOR_TO_BLOCK(bdev_zone_sectors(bdev));
2942         if (sbi->log_blocks_per_blkz && sbi->log_blocks_per_blkz !=
2943                                 __ilog2_u32(sbi->blocks_per_blkz))
2944                 return -EINVAL;
2945         sbi->log_blocks_per_blkz = __ilog2_u32(sbi->blocks_per_blkz);
2946         FDEV(devi).nr_blkz = SECTOR_TO_BLOCK(nr_sectors) >>
2947                                         sbi->log_blocks_per_blkz;
2948         if (nr_sectors & (bdev_zone_sectors(bdev) - 1))
2949                 FDEV(devi).nr_blkz++;
2950
2951         FDEV(devi).blkz_seq = f2fs_kvzalloc(sbi,
2952                                         BITS_TO_LONGS(FDEV(devi).nr_blkz)
2953                                         * sizeof(unsigned long),
2954                                         GFP_KERNEL);
2955         if (!FDEV(devi).blkz_seq)
2956                 return -ENOMEM;
2957
2958 #define F2FS_REPORT_NR_ZONES   4096
2959
2960         zones = f2fs_kzalloc(sbi,
2961                              array_size(F2FS_REPORT_NR_ZONES,
2962                                         sizeof(struct blk_zone)),
2963                              GFP_KERNEL);
2964         if (!zones)
2965                 return -ENOMEM;
2966
2967         /* Get block zones type */
2968         while (zones && sector < nr_sectors) {
2969
2970                 nr_zones = F2FS_REPORT_NR_ZONES;
2971                 err = blkdev_report_zones(bdev, sector, zones, &nr_zones);
2972                 if (err)
2973                         break;
2974                 if (!nr_zones) {
2975                         err = -EIO;
2976                         break;
2977                 }
2978
2979                 for (i = 0; i < nr_zones; i++) {
2980                         if (zones[i].type != BLK_ZONE_TYPE_CONVENTIONAL)
2981                                 set_bit(n, FDEV(devi).blkz_seq);
2982                         sector += zones[i].len;
2983                         n++;
2984                 }
2985         }
2986
2987         kvfree(zones);
2988
2989         return err;
2990 }
2991 #endif
2992
2993 /*
2994  * Read f2fs raw super block.
2995  * Because we have two copies of super block, so read both of them
2996  * to get the first valid one. If any one of them is broken, we pass
2997  * them recovery flag back to the caller.
2998  */
2999 static int read_raw_super_block(struct f2fs_sb_info *sbi,
3000                         struct f2fs_super_block **raw_super,
3001                         int *valid_super_block, int *recovery)
3002 {
3003         struct super_block *sb = sbi->sb;
3004         int block;
3005         struct buffer_head *bh;
3006         struct f2fs_super_block *super;
3007         int err = 0;
3008
3009         super = kzalloc(sizeof(struct f2fs_super_block), GFP_KERNEL);
3010         if (!super)
3011                 return -ENOMEM;
3012
3013         for (block = 0; block < 2; block++) {
3014                 bh = sb_bread(sb, block);
3015                 if (!bh) {
3016                         f2fs_err(sbi, "Unable to read %dth superblock",
3017                                  block + 1);
3018                         err = -EIO;
3019                         continue;
3020                 }
3021
3022                 /* sanity checking of raw super */
3023                 err = sanity_check_raw_super(sbi, bh);
3024                 if (err) {
3025                         f2fs_err(sbi, "Can't find valid F2FS filesystem in %dth superblock",
3026                                  block + 1);
3027                         brelse(bh);
3028                         continue;
3029                 }
3030
3031                 if (!*raw_super) {
3032                         memcpy(super, bh->b_data + F2FS_SUPER_OFFSET,
3033                                                         sizeof(*super));
3034                         *valid_super_block = block;
3035                         *raw_super = super;
3036                 }
3037                 brelse(bh);
3038         }
3039
3040         /* Fail to read any one of the superblocks*/
3041         if (err < 0)
3042                 *recovery = 1;
3043
3044         /* No valid superblock */
3045         if (!*raw_super)
3046                 kvfree(super);
3047         else
3048                 err = 0;
3049
3050         return err;
3051 }
3052
3053 int f2fs_commit_super(struct f2fs_sb_info *sbi, bool recover)
3054 {
3055         struct buffer_head *bh;
3056         __u32 crc = 0;
3057         int err;
3058
3059         if ((recover && f2fs_readonly(sbi->sb)) ||
3060                                 bdev_read_only(sbi->sb->s_bdev)) {
3061                 set_sbi_flag(sbi, SBI_NEED_SB_WRITE);
3062                 return -EROFS;
3063         }
3064
3065         /* we should update superblock crc here */
3066         if (!recover && f2fs_sb_has_sb_chksum(sbi)) {
3067                 crc = f2fs_crc32(sbi, F2FS_RAW_SUPER(sbi),
3068                                 offsetof(struct f2fs_super_block, crc));
3069                 F2FS_RAW_SUPER(sbi)->crc = cpu_to_le32(crc);
3070         }
3071
3072         /* write back-up superblock first */
3073         bh = sb_bread(sbi->sb, sbi->valid_super_block ? 0 : 1);
3074         if (!bh)
3075                 return -EIO;
3076         err = __f2fs_commit_super(bh, F2FS_RAW_SUPER(sbi));
3077         brelse(bh);
3078
3079         /* if we are in recovery path, skip writing valid superblock */
3080         if (recover || err)
3081                 return err;
3082
3083         /* write current valid superblock */
3084         bh = sb_bread(sbi->sb, sbi->valid_super_block);
3085         if (!bh)
3086                 return -EIO;
3087         err = __f2fs_commit_super(bh, F2FS_RAW_SUPER(sbi));
3088         brelse(bh);
3089         return err;
3090 }
3091
3092 static int f2fs_scan_devices(struct f2fs_sb_info *sbi)
3093 {
3094         struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi);
3095         unsigned int max_devices = MAX_DEVICES;
3096         int i;
3097
3098         /* Initialize single device information */
3099         if (!RDEV(0).path[0]) {
3100                 if (!bdev_is_zoned(sbi->sb->s_bdev))
3101                         return 0;
3102                 max_devices = 1;
3103         }
3104
3105         /*
3106          * Initialize multiple devices information, or single
3107          * zoned block device information.
3108          */
3109         sbi->devs = f2fs_kzalloc(sbi,
3110                                  array_size(max_devices,
3111                                             sizeof(struct f2fs_dev_info)),
3112                                  GFP_KERNEL);
3113         if (!sbi->devs)
3114                 return -ENOMEM;
3115
3116         for (i = 0; i < max_devices; i++) {
3117
3118                 if (i > 0 && !RDEV(i).path[0])
3119                         break;
3120
3121                 if (max_devices == 1) {
3122                         /* Single zoned block device mount */
3123                         FDEV(0).bdev =
3124                                 blkdev_get_by_dev(sbi->sb->s_bdev->bd_dev,
3125                                         sbi->sb->s_mode, sbi->sb->s_type);
3126                 } else {
3127                         /* Multi-device mount */
3128                         memcpy(FDEV(i).path, RDEV(i).path, MAX_PATH_LEN);
3129                         FDEV(i).total_segments =
3130                                 le32_to_cpu(RDEV(i).total_segments);
3131                         if (i == 0) {
3132                                 FDEV(i).start_blk = 0;
3133                                 FDEV(i).end_blk = FDEV(i).start_blk +
3134                                     (FDEV(i).total_segments <<
3135                                     sbi->log_blocks_per_seg) - 1 +
3136                                     le32_to_cpu(raw_super->segment0_blkaddr);
3137                         } else {
3138                                 FDEV(i).start_blk = FDEV(i - 1).end_blk + 1;
3139                                 FDEV(i).end_blk = FDEV(i).start_blk +
3140                                         (FDEV(i).total_segments <<
3141                                         sbi->log_blocks_per_seg) - 1;
3142                         }
3143                         FDEV(i).bdev = blkdev_get_by_path(FDEV(i).path,
3144                                         sbi->sb->s_mode, sbi->sb->s_type);
3145                 }
3146                 if (IS_ERR(FDEV(i).bdev))
3147                         return PTR_ERR(FDEV(i).bdev);
3148
3149                 /* to release errored devices */
3150                 sbi->s_ndevs = i + 1;
3151
3152 #ifdef CONFIG_BLK_DEV_ZONED
3153                 if (bdev_zoned_model(FDEV(i).bdev) == BLK_ZONED_HM &&
3154                                 !f2fs_sb_has_blkzoned(sbi)) {
3155                         f2fs_err(sbi, "Zoned block device feature not enabled\n");
3156                         return -EINVAL;
3157                 }
3158                 if (bdev_zoned_model(FDEV(i).bdev) != BLK_ZONED_NONE) {
3159                         if (init_blkz_info(sbi, i)) {
3160                                 f2fs_err(sbi, "Failed to initialize F2FS blkzone information");
3161                                 return -EINVAL;
3162                         }
3163                         if (max_devices == 1)
3164                                 break;
3165                         f2fs_info(sbi, "Mount Device [%2d]: %20s, %8u, %8x - %8x (zone: %s)",
3166                                   i, FDEV(i).path,
3167                                   FDEV(i).total_segments,
3168                                   FDEV(i).start_blk, FDEV(i).end_blk,
3169                                   bdev_zoned_model(FDEV(i).bdev) == BLK_ZONED_HA ?
3170                                   "Host-aware" : "Host-managed");
3171                         continue;
3172                 }
3173 #endif
3174                 f2fs_info(sbi, "Mount Device [%2d]: %20s, %8u, %8x - %8x",
3175                           i, FDEV(i).path,
3176                           FDEV(i).total_segments,
3177                           FDEV(i).start_blk, FDEV(i).end_blk);
3178         }
3179         f2fs_info(sbi,
3180                   "IO Block Size: %8d KB", F2FS_IO_SIZE_KB(sbi));
3181         return 0;
3182 }
3183
3184 static int f2fs_setup_casefold(struct f2fs_sb_info *sbi)
3185 {
3186 #ifdef CONFIG_UNICODE
3187         if (f2fs_sb_has_casefold(sbi) && !sbi->s_encoding) {
3188                 const struct f2fs_sb_encodings *encoding_info;
3189                 struct unicode_map *encoding;
3190                 __u16 encoding_flags;
3191
3192                 if (f2fs_sb_has_encrypt(sbi)) {
3193                         f2fs_err(sbi,
3194                                 "Can't mount with encoding and encryption");
3195                         return -EINVAL;
3196                 }
3197
3198                 if (f2fs_sb_read_encoding(sbi->raw_super, &encoding_info,
3199                                           &encoding_flags)) {
3200                         f2fs_err(sbi,
3201                                  "Encoding requested by superblock is unknown");
3202                         return -EINVAL;
3203                 }
3204
3205                 encoding = utf8_load(encoding_info->version);
3206                 if (IS_ERR(encoding)) {
3207                         f2fs_err(sbi,
3208                                  "can't mount with superblock charset: %s-%s "
3209                                  "not supported by the kernel. flags: 0x%x.",
3210                                  encoding_info->name, encoding_info->version,
3211                                  encoding_flags);
3212                         return PTR_ERR(encoding);
3213                 }
3214                 f2fs_info(sbi, "Using encoding defined by superblock: "
3215                          "%s-%s with flags 0x%hx", encoding_info->name,
3216                          encoding_info->version?:"\b", encoding_flags);
3217
3218                 sbi->s_encoding = encoding;
3219                 sbi->s_encoding_flags = encoding_flags;
3220                 sbi->sb->s_d_op = &f2fs_dentry_ops;
3221         }
3222 #else
3223         if (f2fs_sb_has_casefold(sbi)) {
3224                 f2fs_err(sbi, "Filesystem with casefold feature cannot be mounted without CONFIG_UNICODE");
3225                 return -EINVAL;
3226         }
3227 #endif
3228         return 0;
3229 }
3230
3231 static void f2fs_tuning_parameters(struct f2fs_sb_info *sbi)
3232 {
3233         struct f2fs_sm_info *sm_i = SM_I(sbi);
3234
3235         /* adjust parameters according to the volume size */
3236         if (sm_i->main_segments <= SMALL_VOLUME_SEGMENTS) {
3237                 F2FS_OPTION(sbi).alloc_mode = ALLOC_MODE_REUSE;
3238                 sm_i->dcc_info->discard_granularity = 1;
3239                 sm_i->ipu_policy = 1 << F2FS_IPU_FORCE;
3240         }
3241
3242         sbi->readdir_ra = 1;
3243 }
3244
3245 static int f2fs_fill_super(struct super_block *sb, void *data, int silent)
3246 {
3247         struct f2fs_sb_info *sbi;
3248         struct f2fs_super_block *raw_super;
3249         struct inode *root;
3250         int err;
3251         bool skip_recovery = false, need_fsck = false;
3252         char *options = NULL;
3253         int recovery, i, valid_super_block;
3254         struct curseg_info *seg_i;
3255         int retry_cnt = 1;
3256
3257 try_onemore:
3258         err = -EINVAL;
3259         raw_super = NULL;
3260         valid_super_block = -1;
3261         recovery = 0;
3262
3263         /* allocate memory for f2fs-specific super block info */
3264         sbi = kzalloc(sizeof(struct f2fs_sb_info), GFP_KERNEL);
3265         if (!sbi)
3266                 return -ENOMEM;
3267
3268         sbi->sb = sb;
3269
3270         /* Load the checksum driver */
3271         sbi->s_chksum_driver = crypto_alloc_shash("crc32", 0, 0);
3272         if (IS_ERR(sbi->s_chksum_driver)) {
3273                 f2fs_err(sbi, "Cannot load crc32 driver.");
3274                 err = PTR_ERR(sbi->s_chksum_driver);
3275                 sbi->s_chksum_driver = NULL;
3276                 goto free_sbi;
3277         }
3278
3279         /* set a block size */
3280         if (unlikely(!sb_set_blocksize(sb, F2FS_BLKSIZE))) {
3281                 f2fs_err(sbi, "unable to set blocksize");
3282                 goto free_sbi;
3283         }
3284
3285         err = read_raw_super_block(sbi, &raw_super, &valid_super_block,
3286                                                                 &recovery);
3287         if (err)
3288                 goto free_sbi;
3289
3290         sb->s_fs_info = sbi;
3291         sbi->raw_super = raw_super;
3292
3293         /* precompute checksum seed for metadata */
3294         if (f2fs_sb_has_inode_chksum(sbi))
3295                 sbi->s_chksum_seed = f2fs_chksum(sbi, ~0, raw_super->uuid,
3296                                                 sizeof(raw_super->uuid));
3297
3298         /*
3299          * The BLKZONED feature indicates that the drive was formatted with
3300          * zone alignment optimization. This is optional for host-aware
3301          * devices, but mandatory for host-managed zoned block devices.
3302          */
3303 #ifndef CONFIG_BLK_DEV_ZONED
3304         if (f2fs_sb_has_blkzoned(sbi)) {
3305                 f2fs_err(sbi, "Zoned block device support is not enabled");
3306                 err = -EOPNOTSUPP;
3307                 goto free_sb_buf;
3308         }
3309 #endif
3310         default_options(sbi);
3311         /* parse mount options */
3312         options = kstrdup((const char *)data, GFP_KERNEL);
3313         if (data && !options) {
3314                 err = -ENOMEM;
3315                 goto free_sb_buf;
3316         }
3317
3318         err = parse_options(sb, options);
3319         if (err)
3320                 goto free_options;
3321
3322         sbi->max_file_blocks = max_file_blocks();
3323         sb->s_maxbytes = sbi->max_file_blocks <<
3324                                 le32_to_cpu(raw_super->log_blocksize);
3325         sb->s_max_links = F2FS_LINK_MAX;
3326
3327         err = f2fs_setup_casefold(sbi);
3328         if (err)
3329                 goto free_options;
3330
3331 #ifdef CONFIG_QUOTA
3332         sb->dq_op = &f2fs_quota_operations;
3333         sb->s_qcop = &f2fs_quotactl_ops;
3334         sb->s_quota_types = QTYPE_MASK_USR | QTYPE_MASK_GRP | QTYPE_MASK_PRJ;
3335
3336         if (f2fs_sb_has_quota_ino(sbi)) {
3337                 for (i = 0; i < MAXQUOTAS; i++) {
3338                         if (f2fs_qf_ino(sbi->sb, i))
3339                                 sbi->nquota_files++;
3340                 }
3341         }
3342 #endif
3343
3344         sb->s_op = &f2fs_sops;
3345 #ifdef CONFIG_FS_ENCRYPTION
3346         sb->s_cop = &f2fs_cryptops;
3347 #endif
3348 #ifdef CONFIG_FS_VERITY
3349         sb->s_vop = &f2fs_verityops;
3350 #endif
3351         sb->s_xattr = f2fs_xattr_handlers;
3352         sb->s_export_op = &f2fs_export_ops;
3353         sb->s_magic = F2FS_SUPER_MAGIC;
3354         sb->s_time_gran = 1;
3355         sb->s_flags = (sb->s_flags & ~SB_POSIXACL) |
3356                 (test_opt(sbi, POSIX_ACL) ? SB_POSIXACL : 0);
3357         memcpy(&sb->s_uuid, raw_super->uuid, sizeof(raw_super->uuid));
3358         sb->s_iflags |= SB_I_CGROUPWB;
3359
3360         /* init f2fs-specific super block info */
3361         sbi->valid_super_block = valid_super_block;
3362         mutex_init(&sbi->gc_mutex);
3363         mutex_init(&sbi->writepages);
3364         mutex_init(&sbi->cp_mutex);
3365         mutex_init(&sbi->resize_mutex);
3366         init_rwsem(&sbi->node_write);
3367         init_rwsem(&sbi->node_change);
3368
3369         /* disallow all the data/node/meta page writes */
3370         set_sbi_flag(sbi, SBI_POR_DOING);
3371         spin_lock_init(&sbi->stat_lock);
3372
3373         /* init iostat info */
3374         spin_lock_init(&sbi->iostat_lock);
3375         sbi->iostat_enable = false;
3376
3377         for (i = 0; i < NR_PAGE_TYPE; i++) {
3378                 int n = (i == META) ? 1: NR_TEMP_TYPE;
3379                 int j;
3380
3381                 sbi->write_io[i] =
3382                         f2fs_kmalloc(sbi,
3383                                      array_size(n,
3384                                                 sizeof(struct f2fs_bio_info)),
3385                                      GFP_KERNEL);
3386                 if (!sbi->write_io[i]) {
3387                         err = -ENOMEM;
3388                         goto free_bio_info;
3389                 }
3390
3391                 for (j = HOT; j < n; j++) {
3392                         init_rwsem(&sbi->write_io[i][j].io_rwsem);
3393                         sbi->write_io[i][j].sbi = sbi;
3394                         sbi->write_io[i][j].bio = NULL;
3395                         spin_lock_init(&sbi->write_io[i][j].io_lock);
3396                         INIT_LIST_HEAD(&sbi->write_io[i][j].io_list);
3397                 }
3398         }
3399
3400         init_rwsem(&sbi->cp_rwsem);
3401         init_rwsem(&sbi->quota_sem);
3402         init_waitqueue_head(&sbi->cp_wait);
3403         init_sb_info(sbi);
3404
3405         err = init_percpu_info(sbi);
3406         if (err)
3407                 goto free_bio_info;
3408
3409         if (F2FS_IO_ALIGNED(sbi)) {
3410                 sbi->write_io_dummy =
3411                         mempool_create_page_pool(2 * (F2FS_IO_SIZE(sbi) - 1), 0);
3412                 if (!sbi->write_io_dummy) {
3413                         err = -ENOMEM;
3414                         goto free_percpu;
3415                 }
3416         }
3417
3418         /* get an inode for meta space */
3419         sbi->meta_inode = f2fs_iget(sb, F2FS_META_INO(sbi));
3420         if (IS_ERR(sbi->meta_inode)) {
3421                 f2fs_err(sbi, "Failed to read F2FS meta data inode");
3422                 err = PTR_ERR(sbi->meta_inode);
3423                 goto free_io_dummy;
3424         }
3425
3426         err = f2fs_get_valid_checkpoint(sbi);
3427         if (err) {
3428                 f2fs_err(sbi, "Failed to get valid F2FS checkpoint");
3429                 goto free_meta_inode;
3430         }
3431
3432         if (__is_set_ckpt_flags(F2FS_CKPT(sbi), CP_QUOTA_NEED_FSCK_FLAG))
3433                 set_sbi_flag(sbi, SBI_QUOTA_NEED_REPAIR);
3434         if (__is_set_ckpt_flags(F2FS_CKPT(sbi), CP_DISABLED_QUICK_FLAG)) {
3435                 set_sbi_flag(sbi, SBI_CP_DISABLED_QUICK);
3436                 sbi->interval_time[DISABLE_TIME] = DEF_DISABLE_QUICK_INTERVAL;
3437         }
3438
3439         if (__is_set_ckpt_flags(F2FS_CKPT(sbi), CP_FSCK_FLAG))
3440                 set_sbi_flag(sbi, SBI_NEED_FSCK);
3441
3442         /* Initialize device list */
3443         err = f2fs_scan_devices(sbi);
3444         if (err) {
3445                 f2fs_err(sbi, "Failed to find devices");
3446                 goto free_devices;
3447         }
3448
3449         sbi->total_valid_node_count =
3450                                 le32_to_cpu(sbi->ckpt->valid_node_count);
3451         percpu_counter_set(&sbi->total_valid_inode_count,
3452                                 le32_to_cpu(sbi->ckpt->valid_inode_count));
3453         sbi->user_block_count = le64_to_cpu(sbi->ckpt->user_block_count);
3454         sbi->total_valid_block_count =
3455                                 le64_to_cpu(sbi->ckpt->valid_block_count);
3456         sbi->last_valid_block_count = sbi->total_valid_block_count;
3457         sbi->reserved_blocks = 0;
3458         sbi->current_reserved_blocks = 0;
3459         limit_reserve_root(sbi);
3460         adjust_unusable_cap_perc(sbi);
3461
3462         for (i = 0; i < NR_INODE_TYPE; i++) {
3463                 INIT_LIST_HEAD(&sbi->inode_list[i]);
3464                 spin_lock_init(&sbi->inode_lock[i]);
3465         }
3466         mutex_init(&sbi->flush_lock);
3467
3468         f2fs_init_extent_cache_info(sbi);
3469
3470         f2fs_init_ino_entry_info(sbi);
3471
3472         f2fs_init_fsync_node_info(sbi);
3473
3474         /* setup f2fs internal modules */
3475         err = f2fs_build_segment_manager(sbi);
3476         if (err) {
3477                 f2fs_err(sbi, "Failed to initialize F2FS segment manager (%d)",
3478                          err);
3479                 goto free_sm;
3480         }
3481         err = f2fs_build_node_manager(sbi);
3482         if (err) {
3483                 f2fs_err(sbi, "Failed to initialize F2FS node manager (%d)",
3484                          err);
3485                 goto free_nm;
3486         }
3487
3488         err = adjust_reserved_segment(sbi);
3489         if (err)
3490                 goto free_nm;
3491
3492         /* For write statistics */
3493         if (sb->s_bdev->bd_part)
3494                 sbi->sectors_written_start =
3495                         (u64)part_stat_read(sb->s_bdev->bd_part,
3496                                             sectors[STAT_WRITE]);
3497
3498         /* Read accumulated write IO statistics if exists */
3499         seg_i = CURSEG_I(sbi, CURSEG_HOT_NODE);
3500         if (__exist_node_summaries(sbi))
3501                 sbi->kbytes_written =
3502                         le64_to_cpu(seg_i->journal->info.kbytes_written);
3503
3504         f2fs_build_gc_manager(sbi);
3505
3506         err = f2fs_build_stats(sbi);
3507         if (err)
3508                 goto free_nm;
3509
3510         /* get an inode for node space */
3511         sbi->node_inode = f2fs_iget(sb, F2FS_NODE_INO(sbi));
3512         if (IS_ERR(sbi->node_inode)) {
3513                 f2fs_err(sbi, "Failed to read node inode");
3514                 err = PTR_ERR(sbi->node_inode);
3515                 goto free_stats;
3516         }
3517
3518         /* read root inode and dentry */
3519         root = f2fs_iget(sb, F2FS_ROOT_INO(sbi));
3520         if (IS_ERR(root)) {
3521                 f2fs_err(sbi, "Failed to read root inode");
3522                 err = PTR_ERR(root);
3523                 goto free_node_inode;
3524         }
3525         if (!S_ISDIR(root->i_mode) || !root->i_blocks ||
3526                         !root->i_size || !root->i_nlink) {
3527                 iput(root);
3528                 err = -EINVAL;
3529                 goto free_node_inode;
3530         }
3531
3532         sb->s_root = d_make_root(root); /* allocate root dentry */
3533         if (!sb->s_root) {
3534                 err = -ENOMEM;
3535                 goto free_node_inode;
3536         }
3537
3538         err = f2fs_register_sysfs(sbi);
3539         if (err)
3540                 goto free_root_inode;
3541
3542 #ifdef CONFIG_QUOTA
3543         /* Enable quota usage during mount */
3544         if (f2fs_sb_has_quota_ino(sbi) && !f2fs_readonly(sb)) {
3545                 err = f2fs_enable_quotas(sb);
3546                 if (err)
3547                         f2fs_err(sbi, "Cannot turn on quotas: error %d", err);
3548         }
3549 #endif
3550         /* if there are nt orphan nodes free them */
3551         err = f2fs_recover_orphan_inodes(sbi);
3552         if (err)
3553                 goto free_meta;
3554
3555         if (unlikely(is_set_ckpt_flags(sbi, CP_DISABLED_FLAG)))
3556                 goto reset_checkpoint;
3557
3558         /* recover fsynced data */
3559         if (!test_opt(sbi, DISABLE_ROLL_FORWARD) &&
3560                         !test_opt(sbi, NORECOVERY)) {
3561                 /*
3562                  * mount should be failed, when device has readonly mode, and
3563                  * previous checkpoint was not done by clean system shutdown.
3564                  */
3565                 if (f2fs_hw_is_readonly(sbi)) {
3566                         if (!is_set_ckpt_flags(sbi, CP_UMOUNT_FLAG)) {
3567                                 err = -EROFS;
3568                                 f2fs_err(sbi, "Need to recover fsync data, but write access unavailable");
3569                                 goto free_meta;
3570                         }
3571                         f2fs_info(sbi, "write access unavailable, skipping recovery");
3572                         goto reset_checkpoint;
3573                 }
3574
3575                 if (need_fsck)
3576                         set_sbi_flag(sbi, SBI_NEED_FSCK);
3577
3578                 if (skip_recovery)
3579                         goto reset_checkpoint;
3580
3581                 err = f2fs_recover_fsync_data(sbi, false);
3582                 if (err < 0) {
3583                         if (err != -ENOMEM)
3584                                 skip_recovery = true;
3585                         need_fsck = true;
3586                         f2fs_err(sbi, "Cannot recover all fsync data errno=%d",
3587                                  err);
3588                         goto free_meta;
3589                 }
3590         } else {
3591                 err = f2fs_recover_fsync_data(sbi, true);
3592
3593                 if (!f2fs_readonly(sb) && err > 0) {
3594                         err = -EINVAL;
3595                         f2fs_err(sbi, "Need to recover fsync data");
3596                         goto free_meta;
3597                 }
3598         }
3599 reset_checkpoint:
3600         /* f2fs_recover_fsync_data() cleared this already */
3601         clear_sbi_flag(sbi, SBI_POR_DOING);
3602
3603         if (test_opt(sbi, DISABLE_CHECKPOINT)) {
3604                 err = f2fs_disable_checkpoint(sbi);
3605                 if (err)
3606                         goto sync_free_meta;
3607         } else if (is_set_ckpt_flags(sbi, CP_DISABLED_FLAG)) {
3608                 f2fs_enable_checkpoint(sbi);
3609         }
3610
3611         /*
3612          * If filesystem is not mounted as read-only then
3613          * do start the gc_thread.
3614          */
3615         if (test_opt(sbi, BG_GC) && !f2fs_readonly(sb)) {
3616                 /* After POR, we can run background GC thread.*/
3617                 err = f2fs_start_gc_thread(sbi);
3618                 if (err)
3619                         goto sync_free_meta;
3620         }
3621         kvfree(options);
3622
3623         /* recover broken superblock */
3624         if (recovery) {
3625                 err = f2fs_commit_super(sbi, true);
3626                 f2fs_info(sbi, "Try to recover %dth superblock, ret: %d",
3627                           sbi->valid_super_block ? 1 : 2, err);
3628         }
3629
3630         f2fs_join_shrinker(sbi);
3631
3632         f2fs_tuning_parameters(sbi);
3633
3634         f2fs_notice(sbi, "Mounted with checkpoint version = %llx",
3635                     cur_cp_version(F2FS_CKPT(sbi)));
3636         f2fs_update_time(sbi, CP_TIME);
3637         f2fs_update_time(sbi, REQ_TIME);
3638         clear_sbi_flag(sbi, SBI_CP_DISABLED_QUICK);
3639         return 0;
3640
3641 sync_free_meta:
3642         /* safe to flush all the data */
3643         sync_filesystem(sbi->sb);
3644         retry_cnt = 0;
3645
3646 free_meta:
3647 #ifdef CONFIG_QUOTA
3648         f2fs_truncate_quota_inode_pages(sb);
3649         if (f2fs_sb_has_quota_ino(sbi) && !f2fs_readonly(sb))
3650                 f2fs_quota_off_umount(sbi->sb);
3651 #endif
3652         /*
3653          * Some dirty meta pages can be produced by f2fs_recover_orphan_inodes()
3654          * failed by EIO. Then, iput(node_inode) can trigger balance_fs_bg()
3655          * followed by f2fs_write_checkpoint() through f2fs_write_node_pages(), which
3656          * falls into an infinite loop in f2fs_sync_meta_pages().
3657          */
3658         truncate_inode_pages_final(META_MAPPING(sbi));
3659         /* evict some inodes being cached by GC */
3660         evict_inodes(sb);
3661         f2fs_unregister_sysfs(sbi);
3662 free_root_inode:
3663         dput(sb->s_root);
3664         sb->s_root = NULL;
3665 free_node_inode:
3666         f2fs_release_ino_entry(sbi, true);
3667         truncate_inode_pages_final(NODE_MAPPING(sbi));
3668         iput(sbi->node_inode);
3669         sbi->node_inode = NULL;
3670 free_stats:
3671         f2fs_destroy_stats(sbi);
3672 free_nm:
3673         f2fs_destroy_node_manager(sbi);
3674 free_sm:
3675         f2fs_destroy_segment_manager(sbi);
3676 free_devices:
3677         destroy_device_list(sbi);
3678         kvfree(sbi->ckpt);
3679 free_meta_inode:
3680         make_bad_inode(sbi->meta_inode);
3681         iput(sbi->meta_inode);
3682         sbi->meta_inode = NULL;
3683 free_io_dummy:
3684         mempool_destroy(sbi->write_io_dummy);
3685 free_percpu:
3686         destroy_percpu_info(sbi);
3687 free_bio_info:
3688         for (i = 0; i < NR_PAGE_TYPE; i++)
3689                 kvfree(sbi->write_io[i]);
3690
3691 #ifdef CONFIG_UNICODE
3692         utf8_unload(sbi->s_encoding);
3693 #endif
3694 free_options:
3695 #ifdef CONFIG_QUOTA
3696         for (i = 0; i < MAXQUOTAS; i++)
3697                 kvfree(F2FS_OPTION(sbi).s_qf_names[i]);
3698 #endif
3699         kvfree(options);
3700 free_sb_buf:
3701         kvfree(raw_super);
3702 free_sbi:
3703         if (sbi->s_chksum_driver)
3704                 crypto_free_shash(sbi->s_chksum_driver);
3705         kvfree(sbi);
3706
3707         /* give only one another chance */
3708         if (retry_cnt > 0 && skip_recovery) {
3709                 retry_cnt--;
3710                 shrink_dcache_sb(sb);
3711                 goto try_onemore;
3712         }
3713         return err;
3714 }
3715
3716 static struct dentry *f2fs_mount(struct file_system_type *fs_type, int flags,
3717                         const char *dev_name, void *data)
3718 {
3719         return mount_bdev(fs_type, flags, dev_name, data, f2fs_fill_super);
3720 }
3721
3722 static void kill_f2fs_super(struct super_block *sb)
3723 {
3724         if (sb->s_root) {
3725                 struct f2fs_sb_info *sbi = F2FS_SB(sb);
3726
3727                 set_sbi_flag(sbi, SBI_IS_CLOSE);
3728                 f2fs_stop_gc_thread(sbi);
3729                 f2fs_stop_discard_thread(sbi);
3730
3731                 if (is_sbi_flag_set(sbi, SBI_IS_DIRTY) ||
3732                                 !is_set_ckpt_flags(sbi, CP_UMOUNT_FLAG)) {
3733                         struct cp_control cpc = {
3734                                 .reason = CP_UMOUNT,
3735                         };
3736                         f2fs_write_checkpoint(sbi, &cpc);
3737                 }
3738
3739                 if (is_sbi_flag_set(sbi, SBI_IS_RECOVERED) && f2fs_readonly(sb))
3740                         sb->s_flags &= ~SB_RDONLY;
3741         }
3742         kill_block_super(sb);
3743 }
3744
3745 static struct file_system_type f2fs_fs_type = {
3746         .owner          = THIS_MODULE,
3747         .name           = "f2fs",
3748         .mount          = f2fs_mount,
3749         .kill_sb        = kill_f2fs_super,
3750         .fs_flags       = FS_REQUIRES_DEV,
3751 };
3752 MODULE_ALIAS_FS("f2fs");
3753
3754 static int __init init_inodecache(void)
3755 {
3756         f2fs_inode_cachep = kmem_cache_create("f2fs_inode_cache",
3757                         sizeof(struct f2fs_inode_info), 0,
3758                         SLAB_RECLAIM_ACCOUNT|SLAB_ACCOUNT, NULL);
3759         if (!f2fs_inode_cachep)
3760                 return -ENOMEM;
3761         return 0;
3762 }
3763
3764 static void destroy_inodecache(void)
3765 {
3766         /*
3767          * Make sure all delayed rcu free inodes are flushed before we
3768          * destroy cache.
3769          */
3770         rcu_barrier();
3771         kmem_cache_destroy(f2fs_inode_cachep);
3772 }
3773
3774 static int __init init_f2fs_fs(void)
3775 {
3776         int err;
3777
3778         if (PAGE_SIZE != F2FS_BLKSIZE) {
3779                 printk("F2FS not supported on PAGE_SIZE(%lu) != %d\n",
3780                                 PAGE_SIZE, F2FS_BLKSIZE);
3781                 return -EINVAL;
3782         }
3783
3784         f2fs_build_trace_ios();
3785
3786         err = init_inodecache();
3787         if (err)
3788                 goto fail;
3789         err = f2fs_create_node_manager_caches();
3790         if (err)
3791                 goto free_inodecache;
3792         err = f2fs_create_segment_manager_caches();
3793         if (err)
3794                 goto free_node_manager_caches;
3795         err = f2fs_create_checkpoint_caches();
3796         if (err)
3797                 goto free_segment_manager_caches;
3798         err = f2fs_create_extent_cache();
3799         if (err)
3800                 goto free_checkpoint_caches;
3801         err = f2fs_init_sysfs();
3802         if (err)
3803                 goto free_extent_cache;
3804         err = register_shrinker(&f2fs_shrinker_info);
3805         if (err)
3806                 goto free_sysfs;
3807         err = register_filesystem(&f2fs_fs_type);
3808         if (err)
3809                 goto free_shrinker;
3810         f2fs_create_root_stats();
3811         err = f2fs_init_post_read_processing();
3812         if (err)
3813                 goto free_root_stats;
3814         return 0;
3815
3816 free_root_stats:
3817         f2fs_destroy_root_stats();
3818         unregister_filesystem(&f2fs_fs_type);
3819 free_shrinker:
3820         unregister_shrinker(&f2fs_shrinker_info);
3821 free_sysfs:
3822         f2fs_exit_sysfs();
3823 free_extent_cache:
3824         f2fs_destroy_extent_cache();
3825 free_checkpoint_caches:
3826         f2fs_destroy_checkpoint_caches();
3827 free_segment_manager_caches:
3828         f2fs_destroy_segment_manager_caches();
3829 free_node_manager_caches:
3830         f2fs_destroy_node_manager_caches();
3831 free_inodecache:
3832         destroy_inodecache();
3833 fail:
3834         return err;
3835 }
3836
3837 static void __exit exit_f2fs_fs(void)
3838 {
3839         f2fs_destroy_post_read_processing();
3840         f2fs_destroy_root_stats();
3841         unregister_filesystem(&f2fs_fs_type);
3842         unregister_shrinker(&f2fs_shrinker_info);
3843         f2fs_exit_sysfs();
3844         f2fs_destroy_extent_cache();
3845         f2fs_destroy_checkpoint_caches();
3846         f2fs_destroy_segment_manager_caches();
3847         f2fs_destroy_node_manager_caches();
3848         destroy_inodecache();
3849         f2fs_destroy_trace_ios();
3850 }
3851
3852 module_init(init_f2fs_fs)
3853 module_exit(exit_f2fs_fs)
3854
3855 MODULE_AUTHOR("Samsung Electronics's Praesto Team");
3856 MODULE_DESCRIPTION("Flash Friendly File System");
3857 MODULE_LICENSE("GPL");
3858 MODULE_SOFTDEP("pre: crc32");
3859