no need for list_for_each_entry_safe()/resetting with superblock list
[firefly-linux-kernel-4.4.55.git] / fs / nilfs2 / super.c
1 /*
2  * super.c - NILFS module and super block management.
3  *
4  * Copyright (C) 2005-2008 Nippon Telegraph and Telephone Corporation.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  * Written by Ryusuke Konishi <ryusuke@osrg.net>
21  */
22 /*
23  *  linux/fs/ext2/super.c
24  *
25  * Copyright (C) 1992, 1993, 1994, 1995
26  * Remy Card (card@masi.ibp.fr)
27  * Laboratoire MASI - Institut Blaise Pascal
28  * Universite Pierre et Marie Curie (Paris VI)
29  *
30  *  from
31  *
32  *  linux/fs/minix/inode.c
33  *
34  *  Copyright (C) 1991, 1992  Linus Torvalds
35  *
36  *  Big-endian to little-endian byte-swapping/bitmaps by
37  *        David S. Miller (davem@caip.rutgers.edu), 1995
38  */
39
40 #include <linux/module.h>
41 #include <linux/string.h>
42 #include <linux/slab.h>
43 #include <linux/init.h>
44 #include <linux/blkdev.h>
45 #include <linux/parser.h>
46 #include <linux/random.h>
47 #include <linux/crc32.h>
48 #include <linux/smp_lock.h>
49 #include <linux/vfs.h>
50 #include <linux/writeback.h>
51 #include <linux/kobject.h>
52 #include <linux/exportfs.h>
53 #include <linux/seq_file.h>
54 #include <linux/mount.h>
55 #include "nilfs.h"
56 #include "mdt.h"
57 #include "alloc.h"
58 #include "page.h"
59 #include "cpfile.h"
60 #include "ifile.h"
61 #include "dat.h"
62 #include "segment.h"
63 #include "segbuf.h"
64
65 MODULE_AUTHOR("NTT Corp.");
66 MODULE_DESCRIPTION("A New Implementation of the Log-structured Filesystem "
67                    "(NILFS)");
68 MODULE_LICENSE("GPL");
69
70 struct kmem_cache *nilfs_inode_cachep;
71 struct kmem_cache *nilfs_transaction_cachep;
72 struct kmem_cache *nilfs_segbuf_cachep;
73 struct kmem_cache *nilfs_btree_path_cache;
74
75 static int nilfs_remount(struct super_block *sb, int *flags, char *data);
76
77 /**
78  * nilfs_error() - report failure condition on a filesystem
79  *
80  * nilfs_error() sets an ERROR_FS flag on the superblock as well as
81  * reporting an error message.  It should be called when NILFS detects
82  * incoherences or defects of meta data on disk.  As for sustainable
83  * errors such as a single-shot I/O error, nilfs_warning() or the printk()
84  * function should be used instead.
85  *
86  * The segment constructor must not call this function because it can
87  * kill itself.
88  */
89 void nilfs_error(struct super_block *sb, const char *function,
90                  const char *fmt, ...)
91 {
92         struct nilfs_sb_info *sbi = NILFS_SB(sb);
93         va_list args;
94
95         va_start(args, fmt);
96         printk(KERN_CRIT "NILFS error (device %s): %s: ", sb->s_id, function);
97         vprintk(fmt, args);
98         printk("\n");
99         va_end(args);
100
101         if (!(sb->s_flags & MS_RDONLY)) {
102                 struct the_nilfs *nilfs = sbi->s_nilfs;
103
104                 down_write(&nilfs->ns_sem);
105                 if (!(nilfs->ns_mount_state & NILFS_ERROR_FS)) {
106                         nilfs->ns_mount_state |= NILFS_ERROR_FS;
107                         nilfs->ns_sbp[0]->s_state |=
108                                 cpu_to_le16(NILFS_ERROR_FS);
109                         nilfs_commit_super(sbi, 1);
110                 }
111                 up_write(&nilfs->ns_sem);
112
113                 if (nilfs_test_opt(sbi, ERRORS_RO)) {
114                         printk(KERN_CRIT "Remounting filesystem read-only\n");
115                         sb->s_flags |= MS_RDONLY;
116                 }
117         }
118
119         if (nilfs_test_opt(sbi, ERRORS_PANIC))
120                 panic("NILFS (device %s): panic forced after error\n",
121                       sb->s_id);
122 }
123
124 void nilfs_warning(struct super_block *sb, const char *function,
125                    const char *fmt, ...)
126 {
127         va_list args;
128
129         va_start(args, fmt);
130         printk(KERN_WARNING "NILFS warning (device %s): %s: ",
131                sb->s_id, function);
132         vprintk(fmt, args);
133         printk("\n");
134         va_end(args);
135 }
136
137
138 struct inode *nilfs_alloc_inode_common(struct the_nilfs *nilfs)
139 {
140         struct nilfs_inode_info *ii;
141
142         ii = kmem_cache_alloc(nilfs_inode_cachep, GFP_NOFS);
143         if (!ii)
144                 return NULL;
145         ii->i_bh = NULL;
146         ii->i_state = 0;
147         ii->vfs_inode.i_version = 1;
148         nilfs_btnode_cache_init(&ii->i_btnode_cache, nilfs->ns_bdi);
149         return &ii->vfs_inode;
150 }
151
152 struct inode *nilfs_alloc_inode(struct super_block *sb)
153 {
154         return nilfs_alloc_inode_common(NILFS_SB(sb)->s_nilfs);
155 }
156
157 void nilfs_destroy_inode(struct inode *inode)
158 {
159         kmem_cache_free(nilfs_inode_cachep, NILFS_I(inode));
160 }
161
162 static int nilfs_sync_super(struct nilfs_sb_info *sbi, int dupsb)
163 {
164         struct the_nilfs *nilfs = sbi->s_nilfs;
165         int err;
166         int barrier_done = 0;
167
168         if (nilfs_test_opt(sbi, BARRIER)) {
169                 set_buffer_ordered(nilfs->ns_sbh[0]);
170                 barrier_done = 1;
171         }
172  retry:
173         set_buffer_dirty(nilfs->ns_sbh[0]);
174         err = sync_dirty_buffer(nilfs->ns_sbh[0]);
175         if (err == -EOPNOTSUPP && barrier_done) {
176                 nilfs_warning(sbi->s_super, __func__,
177                               "barrier-based sync failed. "
178                               "disabling barriers\n");
179                 nilfs_clear_opt(sbi, BARRIER);
180                 barrier_done = 0;
181                 clear_buffer_ordered(nilfs->ns_sbh[0]);
182                 goto retry;
183         }
184         if (unlikely(err)) {
185                 printk(KERN_ERR
186                        "NILFS: unable to write superblock (err=%d)\n", err);
187                 if (err == -EIO && nilfs->ns_sbh[1]) {
188                         nilfs_fall_back_super_block(nilfs);
189                         goto retry;
190                 }
191         } else {
192                 struct nilfs_super_block *sbp = nilfs->ns_sbp[0];
193
194                 /*
195                  * The latest segment becomes trailable from the position
196                  * written in superblock.
197                  */
198                 clear_nilfs_discontinued(nilfs);
199
200                 /* update GC protection for recent segments */
201                 if (nilfs->ns_sbh[1]) {
202                         sbp = NULL;
203                         if (dupsb) {
204                                 set_buffer_dirty(nilfs->ns_sbh[1]);
205                                 if (!sync_dirty_buffer(nilfs->ns_sbh[1]))
206                                         sbp = nilfs->ns_sbp[1];
207                         }
208                 }
209                 if (sbp) {
210                         spin_lock(&nilfs->ns_last_segment_lock);
211                         nilfs->ns_prot_seq = le64_to_cpu(sbp->s_last_seq);
212                         spin_unlock(&nilfs->ns_last_segment_lock);
213                 }
214         }
215
216         return err;
217 }
218
219 int nilfs_commit_super(struct nilfs_sb_info *sbi, int dupsb)
220 {
221         struct the_nilfs *nilfs = sbi->s_nilfs;
222         struct nilfs_super_block **sbp = nilfs->ns_sbp;
223         sector_t nfreeblocks;
224         time_t t;
225         int err;
226
227         /* nilfs->sem must be locked by the caller. */
228         if (sbp[0]->s_magic != cpu_to_le16(NILFS_SUPER_MAGIC)) {
229                 if (sbp[1] && sbp[1]->s_magic == cpu_to_le16(NILFS_SUPER_MAGIC))
230                         nilfs_swap_super_block(nilfs);
231                 else {
232                         printk(KERN_CRIT "NILFS: superblock broke on dev %s\n",
233                                sbi->s_super->s_id);
234                         return -EIO;
235                 }
236         }
237         err = nilfs_count_free_blocks(nilfs, &nfreeblocks);
238         if (unlikely(err)) {
239                 printk(KERN_ERR "NILFS: failed to count free blocks\n");
240                 return err;
241         }
242         spin_lock(&nilfs->ns_last_segment_lock);
243         sbp[0]->s_last_seq = cpu_to_le64(nilfs->ns_last_seq);
244         sbp[0]->s_last_pseg = cpu_to_le64(nilfs->ns_last_pseg);
245         sbp[0]->s_last_cno = cpu_to_le64(nilfs->ns_last_cno);
246         spin_unlock(&nilfs->ns_last_segment_lock);
247
248         t = get_seconds();
249         nilfs->ns_sbwtime[0] = t;
250         sbp[0]->s_free_blocks_count = cpu_to_le64(nfreeblocks);
251         sbp[0]->s_wtime = cpu_to_le64(t);
252         sbp[0]->s_sum = 0;
253         sbp[0]->s_sum = cpu_to_le32(crc32_le(nilfs->ns_crc_seed,
254                                              (unsigned char *)sbp[0],
255                                              nilfs->ns_sbsize));
256         if (dupsb && sbp[1]) {
257                 memcpy(sbp[1], sbp[0], nilfs->ns_sbsize);
258                 nilfs->ns_sbwtime[1] = t;
259         }
260         clear_nilfs_sb_dirty(nilfs);
261         return nilfs_sync_super(sbi, dupsb);
262 }
263
264 static void nilfs_put_super(struct super_block *sb)
265 {
266         struct nilfs_sb_info *sbi = NILFS_SB(sb);
267         struct the_nilfs *nilfs = sbi->s_nilfs;
268
269         lock_kernel();
270
271         nilfs_detach_segment_constructor(sbi);
272
273         if (!(sb->s_flags & MS_RDONLY)) {
274                 down_write(&nilfs->ns_sem);
275                 nilfs->ns_sbp[0]->s_state = cpu_to_le16(nilfs->ns_mount_state);
276                 nilfs_commit_super(sbi, 1);
277                 up_write(&nilfs->ns_sem);
278         }
279         down_write(&nilfs->ns_super_sem);
280         if (nilfs->ns_current == sbi)
281                 nilfs->ns_current = NULL;
282         up_write(&nilfs->ns_super_sem);
283
284         nilfs_detach_checkpoint(sbi);
285         put_nilfs(sbi->s_nilfs);
286         sbi->s_super = NULL;
287         sb->s_fs_info = NULL;
288         nilfs_put_sbinfo(sbi);
289
290         unlock_kernel();
291 }
292
293 static int nilfs_sync_fs(struct super_block *sb, int wait)
294 {
295         struct nilfs_sb_info *sbi = NILFS_SB(sb);
296         struct the_nilfs *nilfs = sbi->s_nilfs;
297         int err = 0;
298
299         /* This function is called when super block should be written back */
300         if (wait)
301                 err = nilfs_construct_segment(sb);
302
303         down_write(&nilfs->ns_sem);
304         if (nilfs_sb_dirty(nilfs))
305                 nilfs_commit_super(sbi, 1);
306         up_write(&nilfs->ns_sem);
307
308         return err;
309 }
310
311 int nilfs_attach_checkpoint(struct nilfs_sb_info *sbi, __u64 cno)
312 {
313         struct the_nilfs *nilfs = sbi->s_nilfs;
314         struct nilfs_checkpoint *raw_cp;
315         struct buffer_head *bh_cp;
316         int err;
317
318         down_write(&nilfs->ns_super_sem);
319         list_add(&sbi->s_list, &nilfs->ns_supers);
320         up_write(&nilfs->ns_super_sem);
321
322         sbi->s_ifile = nilfs_ifile_new(sbi, nilfs->ns_inode_size);
323         if (!sbi->s_ifile)
324                 return -ENOMEM;
325
326         down_read(&nilfs->ns_segctor_sem);
327         err = nilfs_cpfile_get_checkpoint(nilfs->ns_cpfile, cno, 0, &raw_cp,
328                                           &bh_cp);
329         up_read(&nilfs->ns_segctor_sem);
330         if (unlikely(err)) {
331                 if (err == -ENOENT || err == -EINVAL) {
332                         printk(KERN_ERR
333                                "NILFS: Invalid checkpoint "
334                                "(checkpoint number=%llu)\n",
335                                (unsigned long long)cno);
336                         err = -EINVAL;
337                 }
338                 goto failed;
339         }
340         err = nilfs_read_inode_common(sbi->s_ifile, &raw_cp->cp_ifile_inode);
341         if (unlikely(err))
342                 goto failed_bh;
343         atomic_set(&sbi->s_inodes_count, le64_to_cpu(raw_cp->cp_inodes_count));
344         atomic_set(&sbi->s_blocks_count, le64_to_cpu(raw_cp->cp_blocks_count));
345
346         nilfs_cpfile_put_checkpoint(nilfs->ns_cpfile, cno, bh_cp);
347         return 0;
348
349  failed_bh:
350         nilfs_cpfile_put_checkpoint(nilfs->ns_cpfile, cno, bh_cp);
351  failed:
352         nilfs_mdt_destroy(sbi->s_ifile);
353         sbi->s_ifile = NULL;
354
355         down_write(&nilfs->ns_super_sem);
356         list_del_init(&sbi->s_list);
357         up_write(&nilfs->ns_super_sem);
358
359         return err;
360 }
361
362 void nilfs_detach_checkpoint(struct nilfs_sb_info *sbi)
363 {
364         struct the_nilfs *nilfs = sbi->s_nilfs;
365
366         nilfs_mdt_destroy(sbi->s_ifile);
367         sbi->s_ifile = NULL;
368         down_write(&nilfs->ns_super_sem);
369         list_del_init(&sbi->s_list);
370         up_write(&nilfs->ns_super_sem);
371 }
372
373 static int nilfs_statfs(struct dentry *dentry, struct kstatfs *buf)
374 {
375         struct super_block *sb = dentry->d_sb;
376         struct nilfs_sb_info *sbi = NILFS_SB(sb);
377         struct the_nilfs *nilfs = sbi->s_nilfs;
378         u64 id = huge_encode_dev(sb->s_bdev->bd_dev);
379         unsigned long long blocks;
380         unsigned long overhead;
381         unsigned long nrsvblocks;
382         sector_t nfreeblocks;
383         int err;
384
385         /*
386          * Compute all of the segment blocks
387          *
388          * The blocks before first segment and after last segment
389          * are excluded.
390          */
391         blocks = nilfs->ns_blocks_per_segment * nilfs->ns_nsegments
392                 - nilfs->ns_first_data_block;
393         nrsvblocks = nilfs->ns_nrsvsegs * nilfs->ns_blocks_per_segment;
394
395         /*
396          * Compute the overhead
397          *
398          * When distributing meta data blocks outside segment structure,
399          * We must count them as the overhead.
400          */
401         overhead = 0;
402
403         err = nilfs_count_free_blocks(nilfs, &nfreeblocks);
404         if (unlikely(err))
405                 return err;
406
407         buf->f_type = NILFS_SUPER_MAGIC;
408         buf->f_bsize = sb->s_blocksize;
409         buf->f_blocks = blocks - overhead;
410         buf->f_bfree = nfreeblocks;
411         buf->f_bavail = (buf->f_bfree >= nrsvblocks) ?
412                 (buf->f_bfree - nrsvblocks) : 0;
413         buf->f_files = atomic_read(&sbi->s_inodes_count);
414         buf->f_ffree = 0; /* nilfs_count_free_inodes(sb); */
415         buf->f_namelen = NILFS_NAME_LEN;
416         buf->f_fsid.val[0] = (u32)id;
417         buf->f_fsid.val[1] = (u32)(id >> 32);
418
419         return 0;
420 }
421
422 static int nilfs_show_options(struct seq_file *seq, struct vfsmount *vfs)
423 {
424         struct super_block *sb = vfs->mnt_sb;
425         struct nilfs_sb_info *sbi = NILFS_SB(sb);
426
427         if (!nilfs_test_opt(sbi, BARRIER))
428                 seq_printf(seq, ",nobarrier");
429         if (nilfs_test_opt(sbi, SNAPSHOT))
430                 seq_printf(seq, ",cp=%llu",
431                            (unsigned long long int)sbi->s_snapshot_cno);
432         if (nilfs_test_opt(sbi, ERRORS_PANIC))
433                 seq_printf(seq, ",errors=panic");
434         if (nilfs_test_opt(sbi, ERRORS_CONT))
435                 seq_printf(seq, ",errors=continue");
436         if (nilfs_test_opt(sbi, STRICT_ORDER))
437                 seq_printf(seq, ",order=strict");
438         if (nilfs_test_opt(sbi, NORECOVERY))
439                 seq_printf(seq, ",norecovery");
440         if (nilfs_test_opt(sbi, DISCARD))
441                 seq_printf(seq, ",discard");
442
443         return 0;
444 }
445
446 static const struct super_operations nilfs_sops = {
447         .alloc_inode    = nilfs_alloc_inode,
448         .destroy_inode  = nilfs_destroy_inode,
449         .dirty_inode    = nilfs_dirty_inode,
450         /* .write_inode    = nilfs_write_inode, */
451         /* .put_inode      = nilfs_put_inode, */
452         /* .drop_inode    = nilfs_drop_inode, */
453         .evict_inode    = nilfs_evict_inode,
454         .put_super      = nilfs_put_super,
455         /* .write_super    = nilfs_write_super, */
456         .sync_fs        = nilfs_sync_fs,
457         /* .write_super_lockfs */
458         /* .unlockfs */
459         .statfs         = nilfs_statfs,
460         .remount_fs     = nilfs_remount,
461         /* .umount_begin */
462         .show_options = nilfs_show_options
463 };
464
465 static struct inode *
466 nilfs_nfs_get_inode(struct super_block *sb, u64 ino, u32 generation)
467 {
468         struct inode *inode;
469
470         if (ino < NILFS_FIRST_INO(sb) && ino != NILFS_ROOT_INO &&
471             ino != NILFS_SKETCH_INO)
472                 return ERR_PTR(-ESTALE);
473
474         inode = nilfs_iget(sb, ino);
475         if (IS_ERR(inode))
476                 return ERR_CAST(inode);
477         if (generation && inode->i_generation != generation) {
478                 iput(inode);
479                 return ERR_PTR(-ESTALE);
480         }
481
482         return inode;
483 }
484
485 static struct dentry *
486 nilfs_fh_to_dentry(struct super_block *sb, struct fid *fid, int fh_len,
487                    int fh_type)
488 {
489         return generic_fh_to_dentry(sb, fid, fh_len, fh_type,
490                                     nilfs_nfs_get_inode);
491 }
492
493 static struct dentry *
494 nilfs_fh_to_parent(struct super_block *sb, struct fid *fid, int fh_len,
495                    int fh_type)
496 {
497         return generic_fh_to_parent(sb, fid, fh_len, fh_type,
498                                     nilfs_nfs_get_inode);
499 }
500
501 static const struct export_operations nilfs_export_ops = {
502         .fh_to_dentry = nilfs_fh_to_dentry,
503         .fh_to_parent = nilfs_fh_to_parent,
504         .get_parent = nilfs_get_parent,
505 };
506
507 enum {
508         Opt_err_cont, Opt_err_panic, Opt_err_ro,
509         Opt_nobarrier, Opt_snapshot, Opt_order, Opt_norecovery,
510         Opt_discard, Opt_err,
511 };
512
513 static match_table_t tokens = {
514         {Opt_err_cont, "errors=continue"},
515         {Opt_err_panic, "errors=panic"},
516         {Opt_err_ro, "errors=remount-ro"},
517         {Opt_nobarrier, "nobarrier"},
518         {Opt_snapshot, "cp=%u"},
519         {Opt_order, "order=%s"},
520         {Opt_norecovery, "norecovery"},
521         {Opt_discard, "discard"},
522         {Opt_err, NULL}
523 };
524
525 static int parse_options(char *options, struct super_block *sb)
526 {
527         struct nilfs_sb_info *sbi = NILFS_SB(sb);
528         char *p;
529         substring_t args[MAX_OPT_ARGS];
530         int option;
531
532         if (!options)
533                 return 1;
534
535         while ((p = strsep(&options, ",")) != NULL) {
536                 int token;
537                 if (!*p)
538                         continue;
539
540                 token = match_token(p, tokens, args);
541                 switch (token) {
542                 case Opt_nobarrier:
543                         nilfs_clear_opt(sbi, BARRIER);
544                         break;
545                 case Opt_order:
546                         if (strcmp(args[0].from, "relaxed") == 0)
547                                 /* Ordered data semantics */
548                                 nilfs_clear_opt(sbi, STRICT_ORDER);
549                         else if (strcmp(args[0].from, "strict") == 0)
550                                 /* Strict in-order semantics */
551                                 nilfs_set_opt(sbi, STRICT_ORDER);
552                         else
553                                 return 0;
554                         break;
555                 case Opt_err_panic:
556                         nilfs_write_opt(sbi, ERROR_MODE, ERRORS_PANIC);
557                         break;
558                 case Opt_err_ro:
559                         nilfs_write_opt(sbi, ERROR_MODE, ERRORS_RO);
560                         break;
561                 case Opt_err_cont:
562                         nilfs_write_opt(sbi, ERROR_MODE, ERRORS_CONT);
563                         break;
564                 case Opt_snapshot:
565                         if (match_int(&args[0], &option) || option <= 0)
566                                 return 0;
567                         if (!(sb->s_flags & MS_RDONLY))
568                                 return 0;
569                         sbi->s_snapshot_cno = option;
570                         nilfs_set_opt(sbi, SNAPSHOT);
571                         break;
572                 case Opt_norecovery:
573                         nilfs_set_opt(sbi, NORECOVERY);
574                         break;
575                 case Opt_discard:
576                         nilfs_set_opt(sbi, DISCARD);
577                         break;
578                 default:
579                         printk(KERN_ERR
580                                "NILFS: Unrecognized mount option \"%s\"\n", p);
581                         return 0;
582                 }
583         }
584         return 1;
585 }
586
587 static inline void
588 nilfs_set_default_options(struct nilfs_sb_info *sbi,
589                           struct nilfs_super_block *sbp)
590 {
591         sbi->s_mount_opt =
592                 NILFS_MOUNT_ERRORS_RO | NILFS_MOUNT_BARRIER;
593 }
594
595 static int nilfs_setup_super(struct nilfs_sb_info *sbi)
596 {
597         struct the_nilfs *nilfs = sbi->s_nilfs;
598         struct nilfs_super_block *sbp = nilfs->ns_sbp[0];
599         int max_mnt_count = le16_to_cpu(sbp->s_max_mnt_count);
600         int mnt_count = le16_to_cpu(sbp->s_mnt_count);
601
602         /* nilfs->sem must be locked by the caller. */
603         if (nilfs->ns_mount_state & NILFS_ERROR_FS) {
604                 printk(KERN_WARNING
605                        "NILFS warning: mounting fs with errors\n");
606 #if 0
607         } else if (max_mnt_count >= 0 && mnt_count >= max_mnt_count) {
608                 printk(KERN_WARNING
609                        "NILFS warning: maximal mount count reached\n");
610 #endif
611         }
612         if (!max_mnt_count)
613                 sbp->s_max_mnt_count = cpu_to_le16(NILFS_DFL_MAX_MNT_COUNT);
614
615         sbp->s_mnt_count = cpu_to_le16(mnt_count + 1);
616         sbp->s_state = cpu_to_le16(le16_to_cpu(sbp->s_state) & ~NILFS_VALID_FS);
617         sbp->s_mtime = cpu_to_le64(get_seconds());
618         return nilfs_commit_super(sbi, 1);
619 }
620
621 struct nilfs_super_block *nilfs_read_super_block(struct super_block *sb,
622                                                  u64 pos, int blocksize,
623                                                  struct buffer_head **pbh)
624 {
625         unsigned long long sb_index = pos;
626         unsigned long offset;
627
628         offset = do_div(sb_index, blocksize);
629         *pbh = sb_bread(sb, sb_index);
630         if (!*pbh)
631                 return NULL;
632         return (struct nilfs_super_block *)((char *)(*pbh)->b_data + offset);
633 }
634
635 int nilfs_store_magic_and_option(struct super_block *sb,
636                                  struct nilfs_super_block *sbp,
637                                  char *data)
638 {
639         struct nilfs_sb_info *sbi = NILFS_SB(sb);
640
641         sb->s_magic = le16_to_cpu(sbp->s_magic);
642
643         /* FS independent flags */
644 #ifdef NILFS_ATIME_DISABLE
645         sb->s_flags |= MS_NOATIME;
646 #endif
647
648         nilfs_set_default_options(sbi, sbp);
649
650         sbi->s_resuid = le16_to_cpu(sbp->s_def_resuid);
651         sbi->s_resgid = le16_to_cpu(sbp->s_def_resgid);
652         sbi->s_interval = le32_to_cpu(sbp->s_c_interval);
653         sbi->s_watermark = le32_to_cpu(sbp->s_c_block_max);
654
655         return !parse_options(data, sb) ? -EINVAL : 0 ;
656 }
657
658 /**
659  * nilfs_fill_super() - initialize a super block instance
660  * @sb: super_block
661  * @data: mount options
662  * @silent: silent mode flag
663  * @nilfs: the_nilfs struct
664  *
665  * This function is called exclusively by nilfs->ns_mount_mutex.
666  * So, the recovery process is protected from other simultaneous mounts.
667  */
668 static int
669 nilfs_fill_super(struct super_block *sb, void *data, int silent,
670                  struct the_nilfs *nilfs)
671 {
672         struct nilfs_sb_info *sbi;
673         struct inode *root;
674         __u64 cno;
675         int err;
676
677         sbi = kzalloc(sizeof(*sbi), GFP_KERNEL);
678         if (!sbi)
679                 return -ENOMEM;
680
681         sb->s_fs_info = sbi;
682
683         get_nilfs(nilfs);
684         sbi->s_nilfs = nilfs;
685         sbi->s_super = sb;
686         atomic_set(&sbi->s_count, 1);
687
688         err = init_nilfs(nilfs, sbi, (char *)data);
689         if (err)
690                 goto failed_sbi;
691
692         spin_lock_init(&sbi->s_inode_lock);
693         INIT_LIST_HEAD(&sbi->s_dirty_files);
694         INIT_LIST_HEAD(&sbi->s_list);
695
696         /*
697          * Following initialization is overlapped because
698          * nilfs_sb_info structure has been cleared at the beginning.
699          * But we reserve them to keep our interest and make ready
700          * for the future change.
701          */
702         get_random_bytes(&sbi->s_next_generation,
703                          sizeof(sbi->s_next_generation));
704         spin_lock_init(&sbi->s_next_gen_lock);
705
706         sb->s_op = &nilfs_sops;
707         sb->s_export_op = &nilfs_export_ops;
708         sb->s_root = NULL;
709         sb->s_time_gran = 1;
710         sb->s_bdi = nilfs->ns_bdi;
711
712         err = load_nilfs(nilfs, sbi);
713         if (err)
714                 goto failed_sbi;
715
716         cno = nilfs_last_cno(nilfs);
717
718         if (sb->s_flags & MS_RDONLY) {
719                 if (nilfs_test_opt(sbi, SNAPSHOT)) {
720                         down_read(&nilfs->ns_segctor_sem);
721                         err = nilfs_cpfile_is_snapshot(nilfs->ns_cpfile,
722                                                        sbi->s_snapshot_cno);
723                         up_read(&nilfs->ns_segctor_sem);
724                         if (err < 0) {
725                                 if (err == -ENOENT)
726                                         err = -EINVAL;
727                                 goto failed_sbi;
728                         }
729                         if (!err) {
730                                 printk(KERN_ERR
731                                        "NILFS: The specified checkpoint is "
732                                        "not a snapshot "
733                                        "(checkpoint number=%llu).\n",
734                                        (unsigned long long)sbi->s_snapshot_cno);
735                                 err = -EINVAL;
736                                 goto failed_sbi;
737                         }
738                         cno = sbi->s_snapshot_cno;
739                 }
740         }
741
742         err = nilfs_attach_checkpoint(sbi, cno);
743         if (err) {
744                 printk(KERN_ERR "NILFS: error loading a checkpoint"
745                        " (checkpoint number=%llu).\n", (unsigned long long)cno);
746                 goto failed_sbi;
747         }
748
749         if (!(sb->s_flags & MS_RDONLY)) {
750                 err = nilfs_attach_segment_constructor(sbi);
751                 if (err)
752                         goto failed_checkpoint;
753         }
754
755         root = nilfs_iget(sb, NILFS_ROOT_INO);
756         if (IS_ERR(root)) {
757                 printk(KERN_ERR "NILFS: get root inode failed\n");
758                 err = PTR_ERR(root);
759                 goto failed_segctor;
760         }
761         if (!S_ISDIR(root->i_mode) || !root->i_blocks || !root->i_size) {
762                 iput(root);
763                 printk(KERN_ERR "NILFS: corrupt root inode.\n");
764                 err = -EINVAL;
765                 goto failed_segctor;
766         }
767         sb->s_root = d_alloc_root(root);
768         if (!sb->s_root) {
769                 iput(root);
770                 printk(KERN_ERR "NILFS: get root dentry failed\n");
771                 err = -ENOMEM;
772                 goto failed_segctor;
773         }
774
775         if (!(sb->s_flags & MS_RDONLY)) {
776                 down_write(&nilfs->ns_sem);
777                 nilfs_setup_super(sbi);
778                 up_write(&nilfs->ns_sem);
779         }
780
781         down_write(&nilfs->ns_super_sem);
782         if (!nilfs_test_opt(sbi, SNAPSHOT))
783                 nilfs->ns_current = sbi;
784         up_write(&nilfs->ns_super_sem);
785
786         return 0;
787
788  failed_segctor:
789         nilfs_detach_segment_constructor(sbi);
790
791  failed_checkpoint:
792         nilfs_detach_checkpoint(sbi);
793
794  failed_sbi:
795         put_nilfs(nilfs);
796         sb->s_fs_info = NULL;
797         nilfs_put_sbinfo(sbi);
798         return err;
799 }
800
801 static int nilfs_remount(struct super_block *sb, int *flags, char *data)
802 {
803         struct nilfs_sb_info *sbi = NILFS_SB(sb);
804         struct nilfs_super_block *sbp;
805         struct the_nilfs *nilfs = sbi->s_nilfs;
806         unsigned long old_sb_flags;
807         struct nilfs_mount_options old_opts;
808         int was_snapshot, err;
809
810         lock_kernel();
811
812         down_write(&nilfs->ns_super_sem);
813         old_sb_flags = sb->s_flags;
814         old_opts.mount_opt = sbi->s_mount_opt;
815         old_opts.snapshot_cno = sbi->s_snapshot_cno;
816         was_snapshot = nilfs_test_opt(sbi, SNAPSHOT);
817
818         if (!parse_options(data, sb)) {
819                 err = -EINVAL;
820                 goto restore_opts;
821         }
822         sb->s_flags = (sb->s_flags & ~MS_POSIXACL);
823
824         err = -EINVAL;
825         if (was_snapshot) {
826                 if (!(*flags & MS_RDONLY)) {
827                         printk(KERN_ERR "NILFS (device %s): cannot remount "
828                                "snapshot read/write.\n",
829                                sb->s_id);
830                         goto restore_opts;
831                 } else if (sbi->s_snapshot_cno != old_opts.snapshot_cno) {
832                         printk(KERN_ERR "NILFS (device %s): cannot "
833                                "remount to a different snapshot.\n",
834                                sb->s_id);
835                         goto restore_opts;
836                 }
837         } else {
838                 if (nilfs_test_opt(sbi, SNAPSHOT)) {
839                         printk(KERN_ERR "NILFS (device %s): cannot change "
840                                "a regular mount to a snapshot.\n",
841                                sb->s_id);
842                         goto restore_opts;
843                 }
844         }
845
846         if (!nilfs_valid_fs(nilfs)) {
847                 printk(KERN_WARNING "NILFS (device %s): couldn't "
848                        "remount because the filesystem is in an "
849                        "incomplete recovery state.\n", sb->s_id);
850                 goto restore_opts;
851         }
852
853         if ((*flags & MS_RDONLY) == (sb->s_flags & MS_RDONLY))
854                 goto out;
855         if (*flags & MS_RDONLY) {
856                 /* Shutting down the segment constructor */
857                 nilfs_detach_segment_constructor(sbi);
858                 sb->s_flags |= MS_RDONLY;
859
860                 /*
861                  * Remounting a valid RW partition RDONLY, so set
862                  * the RDONLY flag and then mark the partition as valid again.
863                  */
864                 down_write(&nilfs->ns_sem);
865                 sbp = nilfs->ns_sbp[0];
866                 if (!(sbp->s_state & le16_to_cpu(NILFS_VALID_FS)) &&
867                     (nilfs->ns_mount_state & NILFS_VALID_FS))
868                         sbp->s_state = cpu_to_le16(nilfs->ns_mount_state);
869                 sbp->s_mtime = cpu_to_le64(get_seconds());
870                 nilfs_commit_super(sbi, 1);
871                 up_write(&nilfs->ns_sem);
872         } else {
873                 /*
874                  * Mounting a RDONLY partition read-write, so reread and
875                  * store the current valid flag.  (It may have been changed
876                  * by fsck since we originally mounted the partition.)
877                  */
878                 sb->s_flags &= ~MS_RDONLY;
879
880                 err = nilfs_attach_segment_constructor(sbi);
881                 if (err)
882                         goto restore_opts;
883
884                 down_write(&nilfs->ns_sem);
885                 nilfs_setup_super(sbi);
886                 up_write(&nilfs->ns_sem);
887         }
888  out:
889         up_write(&nilfs->ns_super_sem);
890         unlock_kernel();
891         return 0;
892
893  restore_opts:
894         sb->s_flags = old_sb_flags;
895         sbi->s_mount_opt = old_opts.mount_opt;
896         sbi->s_snapshot_cno = old_opts.snapshot_cno;
897         up_write(&nilfs->ns_super_sem);
898         unlock_kernel();
899         return err;
900 }
901
902 struct nilfs_super_data {
903         struct block_device *bdev;
904         struct nilfs_sb_info *sbi;
905         __u64 cno;
906         int flags;
907 };
908
909 /**
910  * nilfs_identify - pre-read mount options needed to identify mount instance
911  * @data: mount options
912  * @sd: nilfs_super_data
913  */
914 static int nilfs_identify(char *data, struct nilfs_super_data *sd)
915 {
916         char *p, *options = data;
917         substring_t args[MAX_OPT_ARGS];
918         int option, token;
919         int ret = 0;
920
921         do {
922                 p = strsep(&options, ",");
923                 if (p != NULL && *p) {
924                         token = match_token(p, tokens, args);
925                         if (token == Opt_snapshot) {
926                                 if (!(sd->flags & MS_RDONLY))
927                                         ret++;
928                                 else {
929                                         ret = match_int(&args[0], &option);
930                                         if (!ret) {
931                                                 if (option > 0)
932                                                         sd->cno = option;
933                                                 else
934                                                         ret++;
935                                         }
936                                 }
937                         }
938                         if (ret)
939                                 printk(KERN_ERR
940                                        "NILFS: invalid mount option: %s\n", p);
941                 }
942                 if (!options)
943                         break;
944                 BUG_ON(options == data);
945                 *(options - 1) = ',';
946         } while (!ret);
947         return ret;
948 }
949
950 static int nilfs_set_bdev_super(struct super_block *s, void *data)
951 {
952         struct nilfs_super_data *sd = data;
953
954         s->s_bdev = sd->bdev;
955         s->s_dev = s->s_bdev->bd_dev;
956         return 0;
957 }
958
959 static int nilfs_test_bdev_super(struct super_block *s, void *data)
960 {
961         struct nilfs_super_data *sd = data;
962
963         return sd->sbi && s->s_fs_info == (void *)sd->sbi;
964 }
965
966 static int
967 nilfs_get_sb(struct file_system_type *fs_type, int flags,
968              const char *dev_name, void *data, struct vfsmount *mnt)
969 {
970         struct nilfs_super_data sd;
971         struct super_block *s;
972         fmode_t mode = FMODE_READ;
973         struct the_nilfs *nilfs;
974         int err, need_to_close = 1;
975
976         if (!(flags & MS_RDONLY))
977                 mode |= FMODE_WRITE;
978
979         sd.bdev = open_bdev_exclusive(dev_name, mode, fs_type);
980         if (IS_ERR(sd.bdev))
981                 return PTR_ERR(sd.bdev);
982
983         /*
984          * To get mount instance using sget() vfs-routine, NILFS needs
985          * much more information than normal filesystems to identify mount
986          * instance.  For snapshot mounts, not only a mount type (ro-mount
987          * or rw-mount) but also a checkpoint number is required.
988          */
989         sd.cno = 0;
990         sd.flags = flags;
991         if (nilfs_identify((char *)data, &sd)) {
992                 err = -EINVAL;
993                 goto failed;
994         }
995
996         nilfs = find_or_create_nilfs(sd.bdev);
997         if (!nilfs) {
998                 err = -ENOMEM;
999                 goto failed;
1000         }
1001
1002         mutex_lock(&nilfs->ns_mount_mutex);
1003
1004         if (!sd.cno) {
1005                 /*
1006                  * Check if an exclusive mount exists or not.
1007                  * Snapshot mounts coexist with a current mount
1008                  * (i.e. rw-mount or ro-mount), whereas rw-mount and
1009                  * ro-mount are mutually exclusive.
1010                  */
1011                 down_read(&nilfs->ns_super_sem);
1012                 if (nilfs->ns_current &&
1013                     ((nilfs->ns_current->s_super->s_flags ^ flags)
1014                      & MS_RDONLY)) {
1015                         up_read(&nilfs->ns_super_sem);
1016                         err = -EBUSY;
1017                         goto failed_unlock;
1018                 }
1019                 up_read(&nilfs->ns_super_sem);
1020         }
1021
1022         /*
1023          * Find existing nilfs_sb_info struct
1024          */
1025         sd.sbi = nilfs_find_sbinfo(nilfs, !(flags & MS_RDONLY), sd.cno);
1026
1027         /*
1028          * Get super block instance holding the nilfs_sb_info struct.
1029          * A new instance is allocated if no existing mount is present or
1030          * existing instance has been unmounted.
1031          */
1032         s = sget(fs_type, nilfs_test_bdev_super, nilfs_set_bdev_super, &sd);
1033         if (sd.sbi)
1034                 nilfs_put_sbinfo(sd.sbi);
1035
1036         if (IS_ERR(s)) {
1037                 err = PTR_ERR(s);
1038                 goto failed_unlock;
1039         }
1040
1041         if (!s->s_root) {
1042                 char b[BDEVNAME_SIZE];
1043
1044                 /* New superblock instance created */
1045                 s->s_flags = flags;
1046                 s->s_mode = mode;
1047                 strlcpy(s->s_id, bdevname(sd.bdev, b), sizeof(s->s_id));
1048                 sb_set_blocksize(s, block_size(sd.bdev));
1049
1050                 err = nilfs_fill_super(s, data, flags & MS_SILENT ? 1 : 0,
1051                                        nilfs);
1052                 if (err)
1053                         goto cancel_new;
1054
1055                 s->s_flags |= MS_ACTIVE;
1056                 need_to_close = 0;
1057         }
1058
1059         mutex_unlock(&nilfs->ns_mount_mutex);
1060         put_nilfs(nilfs);
1061         if (need_to_close)
1062                 close_bdev_exclusive(sd.bdev, mode);
1063         simple_set_mnt(mnt, s);
1064         return 0;
1065
1066  failed_unlock:
1067         mutex_unlock(&nilfs->ns_mount_mutex);
1068         put_nilfs(nilfs);
1069  failed:
1070         close_bdev_exclusive(sd.bdev, mode);
1071
1072         return err;
1073
1074  cancel_new:
1075         /* Abandoning the newly allocated superblock */
1076         mutex_unlock(&nilfs->ns_mount_mutex);
1077         put_nilfs(nilfs);
1078         deactivate_locked_super(s);
1079         /*
1080          * deactivate_locked_super() invokes close_bdev_exclusive().
1081          * We must finish all post-cleaning before this call;
1082          * put_nilfs() needs the block device.
1083          */
1084         return err;
1085 }
1086
1087 struct file_system_type nilfs_fs_type = {
1088         .owner    = THIS_MODULE,
1089         .name     = "nilfs2",
1090         .get_sb   = nilfs_get_sb,
1091         .kill_sb  = kill_block_super,
1092         .fs_flags = FS_REQUIRES_DEV,
1093 };
1094
1095 static void nilfs_inode_init_once(void *obj)
1096 {
1097         struct nilfs_inode_info *ii = obj;
1098
1099         INIT_LIST_HEAD(&ii->i_dirty);
1100 #ifdef CONFIG_NILFS_XATTR
1101         init_rwsem(&ii->xattr_sem);
1102 #endif
1103         nilfs_btnode_cache_init_once(&ii->i_btnode_cache);
1104         ii->i_bmap = (struct nilfs_bmap *)&ii->i_bmap_union;
1105         inode_init_once(&ii->vfs_inode);
1106 }
1107
1108 static void nilfs_segbuf_init_once(void *obj)
1109 {
1110         memset(obj, 0, sizeof(struct nilfs_segment_buffer));
1111 }
1112
1113 static void nilfs_destroy_cachep(void)
1114 {
1115         if (nilfs_inode_cachep)
1116                 kmem_cache_destroy(nilfs_inode_cachep);
1117         if (nilfs_transaction_cachep)
1118                 kmem_cache_destroy(nilfs_transaction_cachep);
1119         if (nilfs_segbuf_cachep)
1120                 kmem_cache_destroy(nilfs_segbuf_cachep);
1121         if (nilfs_btree_path_cache)
1122                 kmem_cache_destroy(nilfs_btree_path_cache);
1123 }
1124
1125 static int __init nilfs_init_cachep(void)
1126 {
1127         nilfs_inode_cachep = kmem_cache_create("nilfs2_inode_cache",
1128                         sizeof(struct nilfs_inode_info), 0,
1129                         SLAB_RECLAIM_ACCOUNT, nilfs_inode_init_once);
1130         if (!nilfs_inode_cachep)
1131                 goto fail;
1132
1133         nilfs_transaction_cachep = kmem_cache_create("nilfs2_transaction_cache",
1134                         sizeof(struct nilfs_transaction_info), 0,
1135                         SLAB_RECLAIM_ACCOUNT, NULL);
1136         if (!nilfs_transaction_cachep)
1137                 goto fail;
1138
1139         nilfs_segbuf_cachep = kmem_cache_create("nilfs2_segbuf_cache",
1140                         sizeof(struct nilfs_segment_buffer), 0,
1141                         SLAB_RECLAIM_ACCOUNT, nilfs_segbuf_init_once);
1142         if (!nilfs_segbuf_cachep)
1143                 goto fail;
1144
1145         nilfs_btree_path_cache = kmem_cache_create("nilfs2_btree_path_cache",
1146                         sizeof(struct nilfs_btree_path) * NILFS_BTREE_LEVEL_MAX,
1147                         0, 0, NULL);
1148         if (!nilfs_btree_path_cache)
1149                 goto fail;
1150
1151         return 0;
1152
1153 fail:
1154         nilfs_destroy_cachep();
1155         return -ENOMEM;
1156 }
1157
1158 static int __init init_nilfs_fs(void)
1159 {
1160         int err;
1161
1162         err = nilfs_init_cachep();
1163         if (err)
1164                 goto fail;
1165
1166         err = register_filesystem(&nilfs_fs_type);
1167         if (err)
1168                 goto free_cachep;
1169
1170         printk(KERN_INFO "NILFS version 2 loaded\n");
1171         return 0;
1172
1173 free_cachep:
1174         nilfs_destroy_cachep();
1175 fail:
1176         return err;
1177 }
1178
1179 static void __exit exit_nilfs_fs(void)
1180 {
1181         nilfs_destroy_cachep();
1182         unregister_filesystem(&nilfs_fs_type);
1183 }
1184
1185 module_init(init_nilfs_fs)
1186 module_exit(exit_nilfs_fs)