f2fs: check upper bound of ino value in f2fs_nfs_get_inode
[firefly-linux-kernel-4.4.55.git] / fs / f2fs / super.c
1 /*
2  * fs/f2fs/super.c
3  *
4  * Copyright (c) 2012 Samsung Electronics Co., Ltd.
5  *             http://www.samsung.com/
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License version 2 as
9  * published by the Free Software Foundation.
10  */
11 #include <linux/module.h>
12 #include <linux/init.h>
13 #include <linux/fs.h>
14 #include <linux/statfs.h>
15 #include <linux/buffer_head.h>
16 #include <linux/backing-dev.h>
17 #include <linux/kthread.h>
18 #include <linux/parser.h>
19 #include <linux/mount.h>
20 #include <linux/seq_file.h>
21 #include <linux/proc_fs.h>
22 #include <linux/random.h>
23 #include <linux/exportfs.h>
24 #include <linux/blkdev.h>
25 #include <linux/f2fs_fs.h>
26 #include <linux/sysfs.h>
27
28 #include "f2fs.h"
29 #include "node.h"
30 #include "segment.h"
31 #include "xattr.h"
32 #include "gc.h"
33
34 #define CREATE_TRACE_POINTS
35 #include <trace/events/f2fs.h>
36
37 static struct proc_dir_entry *f2fs_proc_root;
38 static struct kmem_cache *f2fs_inode_cachep;
39 static struct kset *f2fs_kset;
40
41 enum {
42         Opt_gc_background,
43         Opt_disable_roll_forward,
44         Opt_discard,
45         Opt_noheap,
46         Opt_user_xattr,
47         Opt_nouser_xattr,
48         Opt_acl,
49         Opt_noacl,
50         Opt_active_logs,
51         Opt_disable_ext_identify,
52         Opt_inline_xattr,
53         Opt_inline_data,
54         Opt_err,
55 };
56
57 static match_table_t f2fs_tokens = {
58         {Opt_gc_background, "background_gc=%s"},
59         {Opt_disable_roll_forward, "disable_roll_forward"},
60         {Opt_discard, "discard"},
61         {Opt_noheap, "no_heap"},
62         {Opt_user_xattr, "user_xattr"},
63         {Opt_nouser_xattr, "nouser_xattr"},
64         {Opt_acl, "acl"},
65         {Opt_noacl, "noacl"},
66         {Opt_active_logs, "active_logs=%u"},
67         {Opt_disable_ext_identify, "disable_ext_identify"},
68         {Opt_inline_xattr, "inline_xattr"},
69         {Opt_inline_data, "inline_data"},
70         {Opt_err, NULL},
71 };
72
73 /* Sysfs support for f2fs */
74 enum {
75         GC_THREAD,      /* struct f2fs_gc_thread */
76         SM_INFO,        /* struct f2fs_sm_info */
77         F2FS_SBI,       /* struct f2fs_sb_info */
78 };
79
80 struct f2fs_attr {
81         struct attribute attr;
82         ssize_t (*show)(struct f2fs_attr *, struct f2fs_sb_info *, char *);
83         ssize_t (*store)(struct f2fs_attr *, struct f2fs_sb_info *,
84                          const char *, size_t);
85         int struct_type;
86         int offset;
87 };
88
89 static unsigned char *__struct_ptr(struct f2fs_sb_info *sbi, int struct_type)
90 {
91         if (struct_type == GC_THREAD)
92                 return (unsigned char *)sbi->gc_thread;
93         else if (struct_type == SM_INFO)
94                 return (unsigned char *)SM_I(sbi);
95         else if (struct_type == F2FS_SBI)
96                 return (unsigned char *)sbi;
97         return NULL;
98 }
99
100 static ssize_t f2fs_sbi_show(struct f2fs_attr *a,
101                         struct f2fs_sb_info *sbi, char *buf)
102 {
103         unsigned char *ptr = NULL;
104         unsigned int *ui;
105
106         ptr = __struct_ptr(sbi, a->struct_type);
107         if (!ptr)
108                 return -EINVAL;
109
110         ui = (unsigned int *)(ptr + a->offset);
111
112         return snprintf(buf, PAGE_SIZE, "%u\n", *ui);
113 }
114
115 static ssize_t f2fs_sbi_store(struct f2fs_attr *a,
116                         struct f2fs_sb_info *sbi,
117                         const char *buf, size_t count)
118 {
119         unsigned char *ptr;
120         unsigned long t;
121         unsigned int *ui;
122         ssize_t ret;
123
124         ptr = __struct_ptr(sbi, a->struct_type);
125         if (!ptr)
126                 return -EINVAL;
127
128         ui = (unsigned int *)(ptr + a->offset);
129
130         ret = kstrtoul(skip_spaces(buf), 0, &t);
131         if (ret < 0)
132                 return ret;
133         *ui = t;
134         return count;
135 }
136
137 static ssize_t f2fs_attr_show(struct kobject *kobj,
138                                 struct attribute *attr, char *buf)
139 {
140         struct f2fs_sb_info *sbi = container_of(kobj, struct f2fs_sb_info,
141                                                                 s_kobj);
142         struct f2fs_attr *a = container_of(attr, struct f2fs_attr, attr);
143
144         return a->show ? a->show(a, sbi, buf) : 0;
145 }
146
147 static ssize_t f2fs_attr_store(struct kobject *kobj, struct attribute *attr,
148                                                 const char *buf, size_t len)
149 {
150         struct f2fs_sb_info *sbi = container_of(kobj, struct f2fs_sb_info,
151                                                                         s_kobj);
152         struct f2fs_attr *a = container_of(attr, struct f2fs_attr, attr);
153
154         return a->store ? a->store(a, sbi, buf, len) : 0;
155 }
156
157 static void f2fs_sb_release(struct kobject *kobj)
158 {
159         struct f2fs_sb_info *sbi = container_of(kobj, struct f2fs_sb_info,
160                                                                 s_kobj);
161         complete(&sbi->s_kobj_unregister);
162 }
163
164 #define F2FS_ATTR_OFFSET(_struct_type, _name, _mode, _show, _store, _offset) \
165 static struct f2fs_attr f2fs_attr_##_name = {                   \
166         .attr = {.name = __stringify(_name), .mode = _mode },   \
167         .show   = _show,                                        \
168         .store  = _store,                                       \
169         .struct_type = _struct_type,                            \
170         .offset = _offset                                       \
171 }
172
173 #define F2FS_RW_ATTR(struct_type, struct_name, name, elname)    \
174         F2FS_ATTR_OFFSET(struct_type, name, 0644,               \
175                 f2fs_sbi_show, f2fs_sbi_store,                  \
176                 offsetof(struct struct_name, elname))
177
178 F2FS_RW_ATTR(GC_THREAD, f2fs_gc_kthread, gc_min_sleep_time, min_sleep_time);
179 F2FS_RW_ATTR(GC_THREAD, f2fs_gc_kthread, gc_max_sleep_time, max_sleep_time);
180 F2FS_RW_ATTR(GC_THREAD, f2fs_gc_kthread, gc_no_gc_sleep_time, no_gc_sleep_time);
181 F2FS_RW_ATTR(GC_THREAD, f2fs_gc_kthread, gc_idle, gc_idle);
182 F2FS_RW_ATTR(SM_INFO, f2fs_sm_info, reclaim_segments, rec_prefree_segments);
183 F2FS_RW_ATTR(SM_INFO, f2fs_sm_info, max_small_discards, max_discards);
184 F2FS_RW_ATTR(SM_INFO, f2fs_sm_info, ipu_policy, ipu_policy);
185 F2FS_RW_ATTR(SM_INFO, f2fs_sm_info, min_ipu_util, min_ipu_util);
186 F2FS_RW_ATTR(F2FS_SBI, f2fs_sb_info, max_victim_search, max_victim_search);
187 F2FS_RW_ATTR(F2FS_SBI, f2fs_sb_info, dir_level, dir_level);
188
189 #define ATTR_LIST(name) (&f2fs_attr_##name.attr)
190 static struct attribute *f2fs_attrs[] = {
191         ATTR_LIST(gc_min_sleep_time),
192         ATTR_LIST(gc_max_sleep_time),
193         ATTR_LIST(gc_no_gc_sleep_time),
194         ATTR_LIST(gc_idle),
195         ATTR_LIST(reclaim_segments),
196         ATTR_LIST(max_small_discards),
197         ATTR_LIST(ipu_policy),
198         ATTR_LIST(min_ipu_util),
199         ATTR_LIST(max_victim_search),
200         ATTR_LIST(dir_level),
201         NULL,
202 };
203
204 static const struct sysfs_ops f2fs_attr_ops = {
205         .show   = f2fs_attr_show,
206         .store  = f2fs_attr_store,
207 };
208
209 static struct kobj_type f2fs_ktype = {
210         .default_attrs  = f2fs_attrs,
211         .sysfs_ops      = &f2fs_attr_ops,
212         .release        = f2fs_sb_release,
213 };
214
215 void f2fs_msg(struct super_block *sb, const char *level, const char *fmt, ...)
216 {
217         struct va_format vaf;
218         va_list args;
219
220         va_start(args, fmt);
221         vaf.fmt = fmt;
222         vaf.va = &args;
223         printk("%sF2FS-fs (%s): %pV\n", level, sb->s_id, &vaf);
224         va_end(args);
225 }
226
227 static void init_once(void *foo)
228 {
229         struct f2fs_inode_info *fi = (struct f2fs_inode_info *) foo;
230
231         inode_init_once(&fi->vfs_inode);
232 }
233
234 static int parse_options(struct super_block *sb, char *options)
235 {
236         struct f2fs_sb_info *sbi = F2FS_SB(sb);
237         substring_t args[MAX_OPT_ARGS];
238         char *p, *name;
239         int arg = 0;
240
241         if (!options)
242                 return 0;
243
244         while ((p = strsep(&options, ",")) != NULL) {
245                 int token;
246                 if (!*p)
247                         continue;
248                 /*
249                  * Initialize args struct so we know whether arg was
250                  * found; some options take optional arguments.
251                  */
252                 args[0].to = args[0].from = NULL;
253                 token = match_token(p, f2fs_tokens, args);
254
255                 switch (token) {
256                 case Opt_gc_background:
257                         name = match_strdup(&args[0]);
258
259                         if (!name)
260                                 return -ENOMEM;
261                         if (!strncmp(name, "on", 2))
262                                 set_opt(sbi, BG_GC);
263                         else if (!strncmp(name, "off", 3))
264                                 clear_opt(sbi, BG_GC);
265                         else {
266                                 kfree(name);
267                                 return -EINVAL;
268                         }
269                         kfree(name);
270                         break;
271                 case Opt_disable_roll_forward:
272                         set_opt(sbi, DISABLE_ROLL_FORWARD);
273                         break;
274                 case Opt_discard:
275                         set_opt(sbi, DISCARD);
276                         break;
277                 case Opt_noheap:
278                         set_opt(sbi, NOHEAP);
279                         break;
280 #ifdef CONFIG_F2FS_FS_XATTR
281                 case Opt_user_xattr:
282                         set_opt(sbi, XATTR_USER);
283                         break;
284                 case Opt_nouser_xattr:
285                         clear_opt(sbi, XATTR_USER);
286                         break;
287                 case Opt_inline_xattr:
288                         set_opt(sbi, INLINE_XATTR);
289                         break;
290 #else
291                 case Opt_user_xattr:
292                         f2fs_msg(sb, KERN_INFO,
293                                 "user_xattr options not supported");
294                         break;
295                 case Opt_nouser_xattr:
296                         f2fs_msg(sb, KERN_INFO,
297                                 "nouser_xattr options not supported");
298                         break;
299                 case Opt_inline_xattr:
300                         f2fs_msg(sb, KERN_INFO,
301                                 "inline_xattr options not supported");
302                         break;
303 #endif
304 #ifdef CONFIG_F2FS_FS_POSIX_ACL
305                 case Opt_acl:
306                         set_opt(sbi, POSIX_ACL);
307                         break;
308                 case Opt_noacl:
309                         clear_opt(sbi, POSIX_ACL);
310                         break;
311 #else
312                 case Opt_acl:
313                         f2fs_msg(sb, KERN_INFO, "acl options not supported");
314                         break;
315                 case Opt_noacl:
316                         f2fs_msg(sb, KERN_INFO, "noacl options not supported");
317                         break;
318 #endif
319                 case Opt_active_logs:
320                         if (args->from && match_int(args, &arg))
321                                 return -EINVAL;
322                         if (arg != 2 && arg != 4 && arg != NR_CURSEG_TYPE)
323                                 return -EINVAL;
324                         sbi->active_logs = arg;
325                         break;
326                 case Opt_disable_ext_identify:
327                         set_opt(sbi, DISABLE_EXT_IDENTIFY);
328                         break;
329                 case Opt_inline_data:
330                         set_opt(sbi, INLINE_DATA);
331                         break;
332                 default:
333                         f2fs_msg(sb, KERN_ERR,
334                                 "Unrecognized mount option \"%s\" or missing value",
335                                 p);
336                         return -EINVAL;
337                 }
338         }
339         return 0;
340 }
341
342 static struct inode *f2fs_alloc_inode(struct super_block *sb)
343 {
344         struct f2fs_inode_info *fi;
345
346         fi = kmem_cache_alloc(f2fs_inode_cachep, GFP_F2FS_ZERO);
347         if (!fi)
348                 return NULL;
349
350         init_once((void *) fi);
351
352         /* Initialize f2fs-specific inode info */
353         fi->vfs_inode.i_version = 1;
354         atomic_set(&fi->dirty_dents, 0);
355         fi->i_current_depth = 1;
356         fi->i_advise = 0;
357         rwlock_init(&fi->ext.ext_lock);
358
359         set_inode_flag(fi, FI_NEW_INODE);
360
361         if (test_opt(F2FS_SB(sb), INLINE_XATTR))
362                 set_inode_flag(fi, FI_INLINE_XATTR);
363
364         /* Will be used by directory only */
365         fi->i_dir_level = F2FS_SB(sb)->dir_level;
366
367         return &fi->vfs_inode;
368 }
369
370 static int f2fs_drop_inode(struct inode *inode)
371 {
372         /*
373          * This is to avoid a deadlock condition like below.
374          * writeback_single_inode(inode)
375          *  - f2fs_write_data_page
376          *    - f2fs_gc -> iput -> evict
377          *       - inode_wait_for_writeback(inode)
378          */
379         if (!inode_unhashed(inode) && inode->i_state & I_SYNC)
380                 return 0;
381         return generic_drop_inode(inode);
382 }
383
384 /*
385  * f2fs_dirty_inode() is called from __mark_inode_dirty()
386  *
387  * We should call set_dirty_inode to write the dirty inode through write_inode.
388  */
389 static void f2fs_dirty_inode(struct inode *inode, int flags)
390 {
391         set_inode_flag(F2FS_I(inode), FI_DIRTY_INODE);
392 }
393
394 static void f2fs_i_callback(struct rcu_head *head)
395 {
396         struct inode *inode = container_of(head, struct inode, i_rcu);
397         kmem_cache_free(f2fs_inode_cachep, F2FS_I(inode));
398 }
399
400 static void f2fs_destroy_inode(struct inode *inode)
401 {
402         call_rcu(&inode->i_rcu, f2fs_i_callback);
403 }
404
405 static void f2fs_put_super(struct super_block *sb)
406 {
407         struct f2fs_sb_info *sbi = F2FS_SB(sb);
408
409         if (sbi->s_proc) {
410                 remove_proc_entry("segment_info", sbi->s_proc);
411                 remove_proc_entry(sb->s_id, f2fs_proc_root);
412         }
413         kobject_del(&sbi->s_kobj);
414
415         f2fs_destroy_stats(sbi);
416         stop_gc_thread(sbi);
417
418         /* We don't need to do checkpoint when it's clean */
419         if (sbi->s_dirty && get_pages(sbi, F2FS_DIRTY_NODES))
420                 write_checkpoint(sbi, true);
421
422         iput(sbi->node_inode);
423         iput(sbi->meta_inode);
424
425         /* destroy f2fs internal modules */
426         destroy_node_manager(sbi);
427         destroy_segment_manager(sbi);
428
429         kfree(sbi->ckpt);
430         kobject_put(&sbi->s_kobj);
431         wait_for_completion(&sbi->s_kobj_unregister);
432
433         sb->s_fs_info = NULL;
434         brelse(sbi->raw_super_buf);
435         kfree(sbi);
436 }
437
438 int f2fs_sync_fs(struct super_block *sb, int sync)
439 {
440         struct f2fs_sb_info *sbi = F2FS_SB(sb);
441
442         trace_f2fs_sync_fs(sb, sync);
443
444         if (!sbi->s_dirty && !get_pages(sbi, F2FS_DIRTY_NODES))
445                 return 0;
446
447         if (sync) {
448                 mutex_lock(&sbi->gc_mutex);
449                 write_checkpoint(sbi, false);
450                 mutex_unlock(&sbi->gc_mutex);
451         } else {
452                 f2fs_balance_fs(sbi);
453         }
454
455         return 0;
456 }
457
458 static int f2fs_freeze(struct super_block *sb)
459 {
460         int err;
461
462         if (f2fs_readonly(sb))
463                 return 0;
464
465         err = f2fs_sync_fs(sb, 1);
466         return err;
467 }
468
469 static int f2fs_unfreeze(struct super_block *sb)
470 {
471         return 0;
472 }
473
474 static int f2fs_statfs(struct dentry *dentry, struct kstatfs *buf)
475 {
476         struct super_block *sb = dentry->d_sb;
477         struct f2fs_sb_info *sbi = F2FS_SB(sb);
478         u64 id = huge_encode_dev(sb->s_bdev->bd_dev);
479         block_t total_count, user_block_count, start_count, ovp_count;
480
481         total_count = le64_to_cpu(sbi->raw_super->block_count);
482         user_block_count = sbi->user_block_count;
483         start_count = le32_to_cpu(sbi->raw_super->segment0_blkaddr);
484         ovp_count = SM_I(sbi)->ovp_segments << sbi->log_blocks_per_seg;
485         buf->f_type = F2FS_SUPER_MAGIC;
486         buf->f_bsize = sbi->blocksize;
487
488         buf->f_blocks = total_count - start_count;
489         buf->f_bfree = buf->f_blocks - valid_user_blocks(sbi) - ovp_count;
490         buf->f_bavail = user_block_count - valid_user_blocks(sbi);
491
492         buf->f_files = sbi->total_node_count;
493         buf->f_ffree = sbi->total_node_count - valid_inode_count(sbi);
494
495         buf->f_namelen = F2FS_NAME_LEN;
496         buf->f_fsid.val[0] = (u32)id;
497         buf->f_fsid.val[1] = (u32)(id >> 32);
498
499         return 0;
500 }
501
502 static int f2fs_show_options(struct seq_file *seq, struct dentry *root)
503 {
504         struct f2fs_sb_info *sbi = F2FS_SB(root->d_sb);
505
506         if (!(root->d_sb->s_flags & MS_RDONLY) && test_opt(sbi, BG_GC))
507                 seq_printf(seq, ",background_gc=%s", "on");
508         else
509                 seq_printf(seq, ",background_gc=%s", "off");
510         if (test_opt(sbi, DISABLE_ROLL_FORWARD))
511                 seq_puts(seq, ",disable_roll_forward");
512         if (test_opt(sbi, DISCARD))
513                 seq_puts(seq, ",discard");
514         if (test_opt(sbi, NOHEAP))
515                 seq_puts(seq, ",no_heap_alloc");
516 #ifdef CONFIG_F2FS_FS_XATTR
517         if (test_opt(sbi, XATTR_USER))
518                 seq_puts(seq, ",user_xattr");
519         else
520                 seq_puts(seq, ",nouser_xattr");
521         if (test_opt(sbi, INLINE_XATTR))
522                 seq_puts(seq, ",inline_xattr");
523 #endif
524 #ifdef CONFIG_F2FS_FS_POSIX_ACL
525         if (test_opt(sbi, POSIX_ACL))
526                 seq_puts(seq, ",acl");
527         else
528                 seq_puts(seq, ",noacl");
529 #endif
530         if (test_opt(sbi, DISABLE_EXT_IDENTIFY))
531                 seq_puts(seq, ",disable_ext_identify");
532         if (test_opt(sbi, INLINE_DATA))
533                 seq_puts(seq, ",inline_data");
534         seq_printf(seq, ",active_logs=%u", sbi->active_logs);
535
536         return 0;
537 }
538
539 static int segment_info_seq_show(struct seq_file *seq, void *offset)
540 {
541         struct super_block *sb = seq->private;
542         struct f2fs_sb_info *sbi = F2FS_SB(sb);
543         unsigned int total_segs =
544                         le32_to_cpu(sbi->raw_super->segment_count_main);
545         int i;
546
547         for (i = 0; i < total_segs; i++) {
548                 seq_printf(seq, "%u", get_valid_blocks(sbi, i, 1));
549                 if ((i % 10) == 9 || i == (total_segs - 1))
550                         seq_putc(seq, '\n');
551                 else
552                         seq_putc(seq, ' ');
553         }
554
555         return 0;
556 }
557
558 static int segment_info_open_fs(struct inode *inode, struct file *file)
559 {
560         return single_open(file, segment_info_seq_show, PDE_DATA(inode));
561 }
562
563 static const struct file_operations f2fs_seq_segment_info_fops = {
564         .owner = THIS_MODULE,
565         .open = segment_info_open_fs,
566         .read = seq_read,
567         .llseek = seq_lseek,
568         .release = single_release,
569 };
570
571 static int f2fs_remount(struct super_block *sb, int *flags, char *data)
572 {
573         struct f2fs_sb_info *sbi = F2FS_SB(sb);
574         struct f2fs_mount_info org_mount_opt;
575         int err, active_logs;
576
577         /*
578          * Save the old mount options in case we
579          * need to restore them.
580          */
581         org_mount_opt = sbi->mount_opt;
582         active_logs = sbi->active_logs;
583
584         /* parse mount options */
585         err = parse_options(sb, data);
586         if (err)
587                 goto restore_opts;
588
589         /*
590          * Previous and new state of filesystem is RO,
591          * so no point in checking GC conditions.
592          */
593         if ((sb->s_flags & MS_RDONLY) && (*flags & MS_RDONLY))
594                 goto skip;
595
596         /*
597          * We stop the GC thread if FS is mounted as RO
598          * or if background_gc = off is passed in mount
599          * option. Also sync the filesystem.
600          */
601         if ((*flags & MS_RDONLY) || !test_opt(sbi, BG_GC)) {
602                 if (sbi->gc_thread) {
603                         stop_gc_thread(sbi);
604                         f2fs_sync_fs(sb, 1);
605                 }
606         } else if (test_opt(sbi, BG_GC) && !sbi->gc_thread) {
607                 err = start_gc_thread(sbi);
608                 if (err)
609                         goto restore_opts;
610         }
611 skip:
612         /* Update the POSIXACL Flag */
613          sb->s_flags = (sb->s_flags & ~MS_POSIXACL) |
614                 (test_opt(sbi, POSIX_ACL) ? MS_POSIXACL : 0);
615         return 0;
616
617 restore_opts:
618         sbi->mount_opt = org_mount_opt;
619         sbi->active_logs = active_logs;
620         return err;
621 }
622
623 static struct super_operations f2fs_sops = {
624         .alloc_inode    = f2fs_alloc_inode,
625         .drop_inode     = f2fs_drop_inode,
626         .destroy_inode  = f2fs_destroy_inode,
627         .write_inode    = f2fs_write_inode,
628         .dirty_inode    = f2fs_dirty_inode,
629         .show_options   = f2fs_show_options,
630         .evict_inode    = f2fs_evict_inode,
631         .put_super      = f2fs_put_super,
632         .sync_fs        = f2fs_sync_fs,
633         .freeze_fs      = f2fs_freeze,
634         .unfreeze_fs    = f2fs_unfreeze,
635         .statfs         = f2fs_statfs,
636         .remount_fs     = f2fs_remount,
637 };
638
639 static struct inode *f2fs_nfs_get_inode(struct super_block *sb,
640                 u64 ino, u32 generation)
641 {
642         struct f2fs_sb_info *sbi = F2FS_SB(sb);
643         struct inode *inode;
644
645         if (unlikely(ino < F2FS_ROOT_INO(sbi)))
646                 return ERR_PTR(-ESTALE);
647         if (unlikely(ino >= NM_I(sbi)->max_nid))
648                 return ERR_PTR(-ESTALE);
649
650         /*
651          * f2fs_iget isn't quite right if the inode is currently unallocated!
652          * However f2fs_iget currently does appropriate checks to handle stale
653          * inodes so everything is OK.
654          */
655         inode = f2fs_iget(sb, ino);
656         if (IS_ERR(inode))
657                 return ERR_CAST(inode);
658         if (unlikely(generation && inode->i_generation != generation)) {
659                 /* we didn't find the right inode.. */
660                 iput(inode);
661                 return ERR_PTR(-ESTALE);
662         }
663         return inode;
664 }
665
666 static struct dentry *f2fs_fh_to_dentry(struct super_block *sb, struct fid *fid,
667                 int fh_len, int fh_type)
668 {
669         return generic_fh_to_dentry(sb, fid, fh_len, fh_type,
670                                     f2fs_nfs_get_inode);
671 }
672
673 static struct dentry *f2fs_fh_to_parent(struct super_block *sb, struct fid *fid,
674                 int fh_len, int fh_type)
675 {
676         return generic_fh_to_parent(sb, fid, fh_len, fh_type,
677                                     f2fs_nfs_get_inode);
678 }
679
680 static const struct export_operations f2fs_export_ops = {
681         .fh_to_dentry = f2fs_fh_to_dentry,
682         .fh_to_parent = f2fs_fh_to_parent,
683         .get_parent = f2fs_get_parent,
684 };
685
686 static loff_t max_file_size(unsigned bits)
687 {
688         loff_t result = (DEF_ADDRS_PER_INODE - F2FS_INLINE_XATTR_ADDRS);
689         loff_t leaf_count = ADDRS_PER_BLOCK;
690
691         /* two direct node blocks */
692         result += (leaf_count * 2);
693
694         /* two indirect node blocks */
695         leaf_count *= NIDS_PER_BLOCK;
696         result += (leaf_count * 2);
697
698         /* one double indirect node block */
699         leaf_count *= NIDS_PER_BLOCK;
700         result += leaf_count;
701
702         result <<= bits;
703         return result;
704 }
705
706 static int sanity_check_raw_super(struct super_block *sb,
707                         struct f2fs_super_block *raw_super)
708 {
709         unsigned int blocksize;
710
711         if (F2FS_SUPER_MAGIC != le32_to_cpu(raw_super->magic)) {
712                 f2fs_msg(sb, KERN_INFO,
713                         "Magic Mismatch, valid(0x%x) - read(0x%x)",
714                         F2FS_SUPER_MAGIC, le32_to_cpu(raw_super->magic));
715                 return 1;
716         }
717
718         /* Currently, support only 4KB page cache size */
719         if (F2FS_BLKSIZE != PAGE_CACHE_SIZE) {
720                 f2fs_msg(sb, KERN_INFO,
721                         "Invalid page_cache_size (%lu), supports only 4KB\n",
722                         PAGE_CACHE_SIZE);
723                 return 1;
724         }
725
726         /* Currently, support only 4KB block size */
727         blocksize = 1 << le32_to_cpu(raw_super->log_blocksize);
728         if (blocksize != F2FS_BLKSIZE) {
729                 f2fs_msg(sb, KERN_INFO,
730                         "Invalid blocksize (%u), supports only 4KB\n",
731                         blocksize);
732                 return 1;
733         }
734
735         if (le32_to_cpu(raw_super->log_sectorsize) !=
736                                         F2FS_LOG_SECTOR_SIZE) {
737                 f2fs_msg(sb, KERN_INFO, "Invalid log sectorsize");
738                 return 1;
739         }
740         if (le32_to_cpu(raw_super->log_sectors_per_block) !=
741                                         F2FS_LOG_SECTORS_PER_BLOCK) {
742                 f2fs_msg(sb, KERN_INFO, "Invalid log sectors per block");
743                 return 1;
744         }
745         return 0;
746 }
747
748 static int sanity_check_ckpt(struct f2fs_sb_info *sbi)
749 {
750         unsigned int total, fsmeta;
751         struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi);
752         struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
753
754         total = le32_to_cpu(raw_super->segment_count);
755         fsmeta = le32_to_cpu(raw_super->segment_count_ckpt);
756         fsmeta += le32_to_cpu(raw_super->segment_count_sit);
757         fsmeta += le32_to_cpu(raw_super->segment_count_nat);
758         fsmeta += le32_to_cpu(ckpt->rsvd_segment_count);
759         fsmeta += le32_to_cpu(raw_super->segment_count_ssa);
760
761         if (unlikely(fsmeta >= total))
762                 return 1;
763
764         if (unlikely(is_set_ckpt_flags(ckpt, CP_ERROR_FLAG))) {
765                 f2fs_msg(sbi->sb, KERN_ERR, "A bug case: need to run fsck");
766                 return 1;
767         }
768         return 0;
769 }
770
771 static void init_sb_info(struct f2fs_sb_info *sbi)
772 {
773         struct f2fs_super_block *raw_super = sbi->raw_super;
774         int i;
775
776         sbi->log_sectors_per_block =
777                 le32_to_cpu(raw_super->log_sectors_per_block);
778         sbi->log_blocksize = le32_to_cpu(raw_super->log_blocksize);
779         sbi->blocksize = 1 << sbi->log_blocksize;
780         sbi->log_blocks_per_seg = le32_to_cpu(raw_super->log_blocks_per_seg);
781         sbi->blocks_per_seg = 1 << sbi->log_blocks_per_seg;
782         sbi->segs_per_sec = le32_to_cpu(raw_super->segs_per_sec);
783         sbi->secs_per_zone = le32_to_cpu(raw_super->secs_per_zone);
784         sbi->total_sections = le32_to_cpu(raw_super->section_count);
785         sbi->total_node_count =
786                 (le32_to_cpu(raw_super->segment_count_nat) / 2)
787                         * sbi->blocks_per_seg * NAT_ENTRY_PER_BLOCK;
788         sbi->root_ino_num = le32_to_cpu(raw_super->root_ino);
789         sbi->node_ino_num = le32_to_cpu(raw_super->node_ino);
790         sbi->meta_ino_num = le32_to_cpu(raw_super->meta_ino);
791         sbi->cur_victim_sec = NULL_SECNO;
792         sbi->max_victim_search = DEF_MAX_VICTIM_SEARCH;
793
794         for (i = 0; i < NR_COUNT_TYPE; i++)
795                 atomic_set(&sbi->nr_pages[i], 0);
796
797         sbi->dir_level = DEF_DIR_LEVEL;
798 }
799
800 /*
801  * Read f2fs raw super block.
802  * Because we have two copies of super block, so read the first one at first,
803  * if the first one is invalid, move to read the second one.
804  */
805 static int read_raw_super_block(struct super_block *sb,
806                         struct f2fs_super_block **raw_super,
807                         struct buffer_head **raw_super_buf)
808 {
809         int block = 0;
810
811 retry:
812         *raw_super_buf = sb_bread(sb, block);
813         if (!*raw_super_buf) {
814                 f2fs_msg(sb, KERN_ERR, "Unable to read %dth superblock",
815                                 block + 1);
816                 if (block == 0) {
817                         block++;
818                         goto retry;
819                 } else {
820                         return -EIO;
821                 }
822         }
823
824         *raw_super = (struct f2fs_super_block *)
825                 ((char *)(*raw_super_buf)->b_data + F2FS_SUPER_OFFSET);
826
827         /* sanity checking of raw super */
828         if (sanity_check_raw_super(sb, *raw_super)) {
829                 brelse(*raw_super_buf);
830                 f2fs_msg(sb, KERN_ERR,
831                         "Can't find valid F2FS filesystem in %dth superblock",
832                                                                 block + 1);
833                 if (block == 0) {
834                         block++;
835                         goto retry;
836                 } else {
837                         return -EINVAL;
838                 }
839         }
840
841         return 0;
842 }
843
844 static int f2fs_fill_super(struct super_block *sb, void *data, int silent)
845 {
846         struct f2fs_sb_info *sbi;
847         struct f2fs_super_block *raw_super;
848         struct buffer_head *raw_super_buf;
849         struct inode *root;
850         long err = -EINVAL;
851         int i;
852
853         /* allocate memory for f2fs-specific super block info */
854         sbi = kzalloc(sizeof(struct f2fs_sb_info), GFP_KERNEL);
855         if (!sbi)
856                 return -ENOMEM;
857
858         /* set a block size */
859         if (unlikely(!sb_set_blocksize(sb, F2FS_BLKSIZE))) {
860                 f2fs_msg(sb, KERN_ERR, "unable to set blocksize");
861                 goto free_sbi;
862         }
863
864         err = read_raw_super_block(sb, &raw_super, &raw_super_buf);
865         if (err)
866                 goto free_sbi;
867
868         sb->s_fs_info = sbi;
869         /* init some FS parameters */
870         sbi->active_logs = NR_CURSEG_TYPE;
871
872         set_opt(sbi, BG_GC);
873
874 #ifdef CONFIG_F2FS_FS_XATTR
875         set_opt(sbi, XATTR_USER);
876 #endif
877 #ifdef CONFIG_F2FS_FS_POSIX_ACL
878         set_opt(sbi, POSIX_ACL);
879 #endif
880         /* parse mount options */
881         err = parse_options(sb, (char *)data);
882         if (err)
883                 goto free_sb_buf;
884
885         sb->s_maxbytes = max_file_size(le32_to_cpu(raw_super->log_blocksize));
886         sb->s_max_links = F2FS_LINK_MAX;
887         get_random_bytes(&sbi->s_next_generation, sizeof(u32));
888
889         sb->s_op = &f2fs_sops;
890         sb->s_xattr = f2fs_xattr_handlers;
891         sb->s_export_op = &f2fs_export_ops;
892         sb->s_magic = F2FS_SUPER_MAGIC;
893         sb->s_time_gran = 1;
894         sb->s_flags = (sb->s_flags & ~MS_POSIXACL) |
895                 (test_opt(sbi, POSIX_ACL) ? MS_POSIXACL : 0);
896         memcpy(sb->s_uuid, raw_super->uuid, sizeof(raw_super->uuid));
897
898         /* init f2fs-specific super block info */
899         sbi->sb = sb;
900         sbi->raw_super = raw_super;
901         sbi->raw_super_buf = raw_super_buf;
902         mutex_init(&sbi->gc_mutex);
903         mutex_init(&sbi->writepages);
904         mutex_init(&sbi->cp_mutex);
905         mutex_init(&sbi->node_write);
906         sbi->por_doing = false;
907         spin_lock_init(&sbi->stat_lock);
908
909         mutex_init(&sbi->read_io.io_mutex);
910         sbi->read_io.sbi = sbi;
911         sbi->read_io.bio = NULL;
912         for (i = 0; i < NR_PAGE_TYPE; i++) {
913                 mutex_init(&sbi->write_io[i].io_mutex);
914                 sbi->write_io[i].sbi = sbi;
915                 sbi->write_io[i].bio = NULL;
916         }
917
918         init_rwsem(&sbi->cp_rwsem);
919         init_waitqueue_head(&sbi->cp_wait);
920         init_sb_info(sbi);
921
922         /* get an inode for meta space */
923         sbi->meta_inode = f2fs_iget(sb, F2FS_META_INO(sbi));
924         if (IS_ERR(sbi->meta_inode)) {
925                 f2fs_msg(sb, KERN_ERR, "Failed to read F2FS meta data inode");
926                 err = PTR_ERR(sbi->meta_inode);
927                 goto free_sb_buf;
928         }
929
930         err = get_valid_checkpoint(sbi);
931         if (err) {
932                 f2fs_msg(sb, KERN_ERR, "Failed to get valid F2FS checkpoint");
933                 goto free_meta_inode;
934         }
935
936         /* sanity checking of checkpoint */
937         err = -EINVAL;
938         if (sanity_check_ckpt(sbi)) {
939                 f2fs_msg(sb, KERN_ERR, "Invalid F2FS checkpoint");
940                 goto free_cp;
941         }
942
943         sbi->total_valid_node_count =
944                                 le32_to_cpu(sbi->ckpt->valid_node_count);
945         sbi->total_valid_inode_count =
946                                 le32_to_cpu(sbi->ckpt->valid_inode_count);
947         sbi->user_block_count = le64_to_cpu(sbi->ckpt->user_block_count);
948         sbi->total_valid_block_count =
949                                 le64_to_cpu(sbi->ckpt->valid_block_count);
950         sbi->last_valid_block_count = sbi->total_valid_block_count;
951         sbi->alloc_valid_block_count = 0;
952         INIT_LIST_HEAD(&sbi->dir_inode_list);
953         spin_lock_init(&sbi->dir_inode_lock);
954
955         init_orphan_info(sbi);
956
957         /* setup f2fs internal modules */
958         err = build_segment_manager(sbi);
959         if (err) {
960                 f2fs_msg(sb, KERN_ERR,
961                         "Failed to initialize F2FS segment manager");
962                 goto free_sm;
963         }
964         err = build_node_manager(sbi);
965         if (err) {
966                 f2fs_msg(sb, KERN_ERR,
967                         "Failed to initialize F2FS node manager");
968                 goto free_nm;
969         }
970
971         build_gc_manager(sbi);
972
973         /* get an inode for node space */
974         sbi->node_inode = f2fs_iget(sb, F2FS_NODE_INO(sbi));
975         if (IS_ERR(sbi->node_inode)) {
976                 f2fs_msg(sb, KERN_ERR, "Failed to read node inode");
977                 err = PTR_ERR(sbi->node_inode);
978                 goto free_nm;
979         }
980
981         /* if there are nt orphan nodes free them */
982         recover_orphan_inodes(sbi);
983
984         /* read root inode and dentry */
985         root = f2fs_iget(sb, F2FS_ROOT_INO(sbi));
986         if (IS_ERR(root)) {
987                 f2fs_msg(sb, KERN_ERR, "Failed to read root inode");
988                 err = PTR_ERR(root);
989                 goto free_node_inode;
990         }
991         if (!S_ISDIR(root->i_mode) || !root->i_blocks || !root->i_size) {
992                 err = -EINVAL;
993                 goto free_root_inode;
994         }
995
996         sb->s_root = d_make_root(root); /* allocate root dentry */
997         if (!sb->s_root) {
998                 err = -ENOMEM;
999                 goto free_root_inode;
1000         }
1001
1002         err = f2fs_build_stats(sbi);
1003         if (err)
1004                 goto free_root_inode;
1005
1006         if (f2fs_proc_root)
1007                 sbi->s_proc = proc_mkdir(sb->s_id, f2fs_proc_root);
1008
1009         if (sbi->s_proc)
1010                 proc_create_data("segment_info", S_IRUGO, sbi->s_proc,
1011                                  &f2fs_seq_segment_info_fops, sb);
1012
1013         if (test_opt(sbi, DISCARD)) {
1014                 struct request_queue *q = bdev_get_queue(sb->s_bdev);
1015                 if (!blk_queue_discard(q))
1016                         f2fs_msg(sb, KERN_WARNING,
1017                                         "mounting with \"discard\" option, but "
1018                                         "the device does not support discard");
1019         }
1020
1021         sbi->s_kobj.kset = f2fs_kset;
1022         init_completion(&sbi->s_kobj_unregister);
1023         err = kobject_init_and_add(&sbi->s_kobj, &f2fs_ktype, NULL,
1024                                                         "%s", sb->s_id);
1025         if (err)
1026                 goto free_proc;
1027
1028         /* recover fsynced data */
1029         if (!test_opt(sbi, DISABLE_ROLL_FORWARD)) {
1030                 err = recover_fsync_data(sbi);
1031                 if (err)
1032                         f2fs_msg(sb, KERN_ERR,
1033                                 "Cannot recover all fsync data errno=%ld", err);
1034         }
1035
1036         /*
1037          * If filesystem is not mounted as read-only then
1038          * do start the gc_thread.
1039          */
1040         if (!(sb->s_flags & MS_RDONLY)) {
1041                 /* After POR, we can run background GC thread.*/
1042                 err = start_gc_thread(sbi);
1043                 if (err)
1044                         goto free_kobj;
1045         }
1046         return 0;
1047
1048 free_kobj:
1049         kobject_del(&sbi->s_kobj);
1050 free_proc:
1051         if (sbi->s_proc) {
1052                 remove_proc_entry("segment_info", sbi->s_proc);
1053                 remove_proc_entry(sb->s_id, f2fs_proc_root);
1054         }
1055         f2fs_destroy_stats(sbi);
1056 free_root_inode:
1057         dput(sb->s_root);
1058         sb->s_root = NULL;
1059 free_node_inode:
1060         iput(sbi->node_inode);
1061 free_nm:
1062         destroy_node_manager(sbi);
1063 free_sm:
1064         destroy_segment_manager(sbi);
1065 free_cp:
1066         kfree(sbi->ckpt);
1067 free_meta_inode:
1068         make_bad_inode(sbi->meta_inode);
1069         iput(sbi->meta_inode);
1070 free_sb_buf:
1071         brelse(raw_super_buf);
1072 free_sbi:
1073         kfree(sbi);
1074         return err;
1075 }
1076
1077 static struct dentry *f2fs_mount(struct file_system_type *fs_type, int flags,
1078                         const char *dev_name, void *data)
1079 {
1080         return mount_bdev(fs_type, flags, dev_name, data, f2fs_fill_super);
1081 }
1082
1083 static struct file_system_type f2fs_fs_type = {
1084         .owner          = THIS_MODULE,
1085         .name           = "f2fs",
1086         .mount          = f2fs_mount,
1087         .kill_sb        = kill_block_super,
1088         .fs_flags       = FS_REQUIRES_DEV,
1089 };
1090 MODULE_ALIAS_FS("f2fs");
1091
1092 static int __init init_inodecache(void)
1093 {
1094         f2fs_inode_cachep = f2fs_kmem_cache_create("f2fs_inode_cache",
1095                         sizeof(struct f2fs_inode_info));
1096         if (!f2fs_inode_cachep)
1097                 return -ENOMEM;
1098         return 0;
1099 }
1100
1101 static void destroy_inodecache(void)
1102 {
1103         /*
1104          * Make sure all delayed rcu free inodes are flushed before we
1105          * destroy cache.
1106          */
1107         rcu_barrier();
1108         kmem_cache_destroy(f2fs_inode_cachep);
1109 }
1110
1111 static int __init init_f2fs_fs(void)
1112 {
1113         int err;
1114
1115         err = init_inodecache();
1116         if (err)
1117                 goto fail;
1118         err = create_node_manager_caches();
1119         if (err)
1120                 goto free_inodecache;
1121         err = create_segment_manager_caches();
1122         if (err)
1123                 goto free_node_manager_caches;
1124         err = create_gc_caches();
1125         if (err)
1126                 goto free_segment_manager_caches;
1127         err = create_checkpoint_caches();
1128         if (err)
1129                 goto free_gc_caches;
1130         f2fs_kset = kset_create_and_add("f2fs", NULL, fs_kobj);
1131         if (!f2fs_kset) {
1132                 err = -ENOMEM;
1133                 goto free_checkpoint_caches;
1134         }
1135         err = register_filesystem(&f2fs_fs_type);
1136         if (err)
1137                 goto free_kset;
1138         f2fs_create_root_stats();
1139         f2fs_proc_root = proc_mkdir("fs/f2fs", NULL);
1140         return 0;
1141
1142 free_kset:
1143         kset_unregister(f2fs_kset);
1144 free_checkpoint_caches:
1145         destroy_checkpoint_caches();
1146 free_gc_caches:
1147         destroy_gc_caches();
1148 free_segment_manager_caches:
1149         destroy_segment_manager_caches();
1150 free_node_manager_caches:
1151         destroy_node_manager_caches();
1152 free_inodecache:
1153         destroy_inodecache();
1154 fail:
1155         return err;
1156 }
1157
1158 static void __exit exit_f2fs_fs(void)
1159 {
1160         remove_proc_entry("fs/f2fs", NULL);
1161         f2fs_destroy_root_stats();
1162         unregister_filesystem(&f2fs_fs_type);
1163         destroy_checkpoint_caches();
1164         destroy_gc_caches();
1165         destroy_segment_manager_caches();
1166         destroy_node_manager_caches();
1167         destroy_inodecache();
1168         kset_unregister(f2fs_kset);
1169 }
1170
1171 module_init(init_f2fs_fs)
1172 module_exit(exit_f2fs_fs)
1173
1174 MODULE_AUTHOR("Samsung Electronics's Praesto Team");
1175 MODULE_DESCRIPTION("Flash Friendly File System");
1176 MODULE_LICENSE("GPL");