nilfs2: simplify life cycle management of nilfs object
[cascardo/linux.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/vfs.h>
49 #include <linux/writeback.h>
50 #include <linux/kobject.h>
51 #include <linux/seq_file.h>
52 #include <linux/mount.h>
53 #include "nilfs.h"
54 #include "export.h"
55 #include "mdt.h"
56 #include "alloc.h"
57 #include "btree.h"
58 #include "btnode.h"
59 #include "page.h"
60 #include "cpfile.h"
61 #include "ifile.h"
62 #include "dat.h"
63 #include "segment.h"
64 #include "segbuf.h"
65
66 MODULE_AUTHOR("NTT Corp.");
67 MODULE_DESCRIPTION("A New Implementation of the Log-structured Filesystem "
68                    "(NILFS)");
69 MODULE_LICENSE("GPL");
70
71 struct kmem_cache *nilfs_inode_cachep;
72 struct kmem_cache *nilfs_transaction_cachep;
73 struct kmem_cache *nilfs_segbuf_cachep;
74 struct kmem_cache *nilfs_btree_path_cache;
75
76 static int nilfs_remount(struct super_block *sb, int *flags, char *data);
77
78 static void nilfs_set_error(struct nilfs_sb_info *sbi)
79 {
80         struct the_nilfs *nilfs = sbi->s_nilfs;
81         struct nilfs_super_block **sbp;
82
83         down_write(&nilfs->ns_sem);
84         if (!(nilfs->ns_mount_state & NILFS_ERROR_FS)) {
85                 nilfs->ns_mount_state |= NILFS_ERROR_FS;
86                 sbp = nilfs_prepare_super(sbi, 0);
87                 if (likely(sbp)) {
88                         sbp[0]->s_state |= cpu_to_le16(NILFS_ERROR_FS);
89                         if (sbp[1])
90                                 sbp[1]->s_state |= cpu_to_le16(NILFS_ERROR_FS);
91                         nilfs_commit_super(sbi, NILFS_SB_COMMIT_ALL);
92                 }
93         }
94         up_write(&nilfs->ns_sem);
95 }
96
97 /**
98  * nilfs_error() - report failure condition on a filesystem
99  *
100  * nilfs_error() sets an ERROR_FS flag on the superblock as well as
101  * reporting an error message.  It should be called when NILFS detects
102  * incoherences or defects of meta data on disk.  As for sustainable
103  * errors such as a single-shot I/O error, nilfs_warning() or the printk()
104  * function should be used instead.
105  *
106  * The segment constructor must not call this function because it can
107  * kill itself.
108  */
109 void nilfs_error(struct super_block *sb, const char *function,
110                  const char *fmt, ...)
111 {
112         struct nilfs_sb_info *sbi = NILFS_SB(sb);
113         va_list args;
114
115         va_start(args, fmt);
116         printk(KERN_CRIT "NILFS error (device %s): %s: ", sb->s_id, function);
117         vprintk(fmt, args);
118         printk("\n");
119         va_end(args);
120
121         if (!(sb->s_flags & MS_RDONLY)) {
122                 nilfs_set_error(sbi);
123
124                 if (nilfs_test_opt(sbi, ERRORS_RO)) {
125                         printk(KERN_CRIT "Remounting filesystem read-only\n");
126                         sb->s_flags |= MS_RDONLY;
127                 }
128         }
129
130         if (nilfs_test_opt(sbi, ERRORS_PANIC))
131                 panic("NILFS (device %s): panic forced after error\n",
132                       sb->s_id);
133 }
134
135 void nilfs_warning(struct super_block *sb, const char *function,
136                    const char *fmt, ...)
137 {
138         va_list args;
139
140         va_start(args, fmt);
141         printk(KERN_WARNING "NILFS warning (device %s): %s: ",
142                sb->s_id, function);
143         vprintk(fmt, args);
144         printk("\n");
145         va_end(args);
146 }
147
148
149 struct inode *nilfs_alloc_inode_common(struct the_nilfs *nilfs)
150 {
151         struct nilfs_inode_info *ii;
152
153         ii = kmem_cache_alloc(nilfs_inode_cachep, GFP_NOFS);
154         if (!ii)
155                 return NULL;
156         ii->i_bh = NULL;
157         ii->i_state = 0;
158         ii->i_cno = 0;
159         ii->vfs_inode.i_version = 1;
160         nilfs_btnode_cache_init(&ii->i_btnode_cache, nilfs->ns_bdi);
161         return &ii->vfs_inode;
162 }
163
164 struct inode *nilfs_alloc_inode(struct super_block *sb)
165 {
166         return nilfs_alloc_inode_common(NILFS_SB(sb)->s_nilfs);
167 }
168
169 void nilfs_destroy_inode(struct inode *inode)
170 {
171         struct nilfs_mdt_info *mdi = NILFS_MDT(inode);
172
173         if (mdi) {
174                 kfree(mdi->mi_bgl); /* kfree(NULL) is safe */
175                 kfree(mdi);
176         }
177         kmem_cache_free(nilfs_inode_cachep, NILFS_I(inode));
178 }
179
180 static int nilfs_sync_super(struct nilfs_sb_info *sbi, int flag)
181 {
182         struct the_nilfs *nilfs = sbi->s_nilfs;
183         int err;
184
185  retry:
186         set_buffer_dirty(nilfs->ns_sbh[0]);
187
188         if (nilfs_test_opt(sbi, BARRIER)) {
189                 err = __sync_dirty_buffer(nilfs->ns_sbh[0],
190                                           WRITE_SYNC | WRITE_BARRIER);
191                 if (err == -EOPNOTSUPP) {
192                         nilfs_warning(sbi->s_super, __func__,
193                                       "barrier-based sync failed. "
194                                       "disabling barriers\n");
195                         nilfs_clear_opt(sbi, BARRIER);
196                         goto retry;
197                 }
198         } else {
199                 err = sync_dirty_buffer(nilfs->ns_sbh[0]);
200         }
201
202         if (unlikely(err)) {
203                 printk(KERN_ERR
204                        "NILFS: unable to write superblock (err=%d)\n", err);
205                 if (err == -EIO && nilfs->ns_sbh[1]) {
206                         /*
207                          * sbp[0] points to newer log than sbp[1],
208                          * so copy sbp[0] to sbp[1] to take over sbp[0].
209                          */
210                         memcpy(nilfs->ns_sbp[1], nilfs->ns_sbp[0],
211                                nilfs->ns_sbsize);
212                         nilfs_fall_back_super_block(nilfs);
213                         goto retry;
214                 }
215         } else {
216                 struct nilfs_super_block *sbp = nilfs->ns_sbp[0];
217
218                 nilfs->ns_sbwcount++;
219
220                 /*
221                  * The latest segment becomes trailable from the position
222                  * written in superblock.
223                  */
224                 clear_nilfs_discontinued(nilfs);
225
226                 /* update GC protection for recent segments */
227                 if (nilfs->ns_sbh[1]) {
228                         if (flag == NILFS_SB_COMMIT_ALL) {
229                                 set_buffer_dirty(nilfs->ns_sbh[1]);
230                                 if (sync_dirty_buffer(nilfs->ns_sbh[1]) < 0)
231                                         goto out;
232                         }
233                         if (le64_to_cpu(nilfs->ns_sbp[1]->s_last_cno) <
234                             le64_to_cpu(nilfs->ns_sbp[0]->s_last_cno))
235                                 sbp = nilfs->ns_sbp[1];
236                 }
237
238                 spin_lock(&nilfs->ns_last_segment_lock);
239                 nilfs->ns_prot_seq = le64_to_cpu(sbp->s_last_seq);
240                 spin_unlock(&nilfs->ns_last_segment_lock);
241         }
242  out:
243         return err;
244 }
245
246 void nilfs_set_log_cursor(struct nilfs_super_block *sbp,
247                           struct the_nilfs *nilfs)
248 {
249         sector_t nfreeblocks;
250
251         /* nilfs->ns_sem must be locked by the caller. */
252         nilfs_count_free_blocks(nilfs, &nfreeblocks);
253         sbp->s_free_blocks_count = cpu_to_le64(nfreeblocks);
254
255         spin_lock(&nilfs->ns_last_segment_lock);
256         sbp->s_last_seq = cpu_to_le64(nilfs->ns_last_seq);
257         sbp->s_last_pseg = cpu_to_le64(nilfs->ns_last_pseg);
258         sbp->s_last_cno = cpu_to_le64(nilfs->ns_last_cno);
259         spin_unlock(&nilfs->ns_last_segment_lock);
260 }
261
262 struct nilfs_super_block **nilfs_prepare_super(struct nilfs_sb_info *sbi,
263                                                int flip)
264 {
265         struct the_nilfs *nilfs = sbi->s_nilfs;
266         struct nilfs_super_block **sbp = nilfs->ns_sbp;
267
268         /* nilfs->ns_sem must be locked by the caller. */
269         if (sbp[0]->s_magic != cpu_to_le16(NILFS_SUPER_MAGIC)) {
270                 if (sbp[1] &&
271                     sbp[1]->s_magic == cpu_to_le16(NILFS_SUPER_MAGIC)) {
272                         memcpy(sbp[0], sbp[1], nilfs->ns_sbsize);
273                 } else {
274                         printk(KERN_CRIT "NILFS: superblock broke on dev %s\n",
275                                sbi->s_super->s_id);
276                         return NULL;
277                 }
278         } else if (sbp[1] &&
279                    sbp[1]->s_magic != cpu_to_le16(NILFS_SUPER_MAGIC)) {
280                         memcpy(sbp[1], sbp[0], nilfs->ns_sbsize);
281         }
282
283         if (flip && sbp[1])
284                 nilfs_swap_super_block(nilfs);
285
286         return sbp;
287 }
288
289 int nilfs_commit_super(struct nilfs_sb_info *sbi, int flag)
290 {
291         struct the_nilfs *nilfs = sbi->s_nilfs;
292         struct nilfs_super_block **sbp = nilfs->ns_sbp;
293         time_t t;
294
295         /* nilfs->ns_sem must be locked by the caller. */
296         t = get_seconds();
297         nilfs->ns_sbwtime = t;
298         sbp[0]->s_wtime = cpu_to_le64(t);
299         sbp[0]->s_sum = 0;
300         sbp[0]->s_sum = cpu_to_le32(crc32_le(nilfs->ns_crc_seed,
301                                              (unsigned char *)sbp[0],
302                                              nilfs->ns_sbsize));
303         if (flag == NILFS_SB_COMMIT_ALL && sbp[1]) {
304                 sbp[1]->s_wtime = sbp[0]->s_wtime;
305                 sbp[1]->s_sum = 0;
306                 sbp[1]->s_sum = cpu_to_le32(crc32_le(nilfs->ns_crc_seed,
307                                             (unsigned char *)sbp[1],
308                                             nilfs->ns_sbsize));
309         }
310         clear_nilfs_sb_dirty(nilfs);
311         return nilfs_sync_super(sbi, flag);
312 }
313
314 /**
315  * nilfs_cleanup_super() - write filesystem state for cleanup
316  * @sbi: nilfs_sb_info to be unmounted or degraded to read-only
317  *
318  * This function restores state flags in the on-disk super block.
319  * This will set "clean" flag (i.e. NILFS_VALID_FS) unless the
320  * filesystem was not clean previously.
321  */
322 int nilfs_cleanup_super(struct nilfs_sb_info *sbi)
323 {
324         struct nilfs_super_block **sbp;
325         int flag = NILFS_SB_COMMIT;
326         int ret = -EIO;
327
328         sbp = nilfs_prepare_super(sbi, 0);
329         if (sbp) {
330                 sbp[0]->s_state = cpu_to_le16(sbi->s_nilfs->ns_mount_state);
331                 nilfs_set_log_cursor(sbp[0], sbi->s_nilfs);
332                 if (sbp[1] && sbp[0]->s_last_cno == sbp[1]->s_last_cno) {
333                         /*
334                          * make the "clean" flag also to the opposite
335                          * super block if both super blocks point to
336                          * the same checkpoint.
337                          */
338                         sbp[1]->s_state = sbp[0]->s_state;
339                         flag = NILFS_SB_COMMIT_ALL;
340                 }
341                 ret = nilfs_commit_super(sbi, flag);
342         }
343         return ret;
344 }
345
346 static void nilfs_put_super(struct super_block *sb)
347 {
348         struct nilfs_sb_info *sbi = NILFS_SB(sb);
349         struct the_nilfs *nilfs = sbi->s_nilfs;
350
351         nilfs_detach_segment_constructor(sbi);
352
353         if (!(sb->s_flags & MS_RDONLY)) {
354                 down_write(&nilfs->ns_sem);
355                 nilfs_cleanup_super(sbi);
356                 up_write(&nilfs->ns_sem);
357         }
358
359         destroy_nilfs(nilfs);
360         sbi->s_super = NULL;
361         sb->s_fs_info = NULL;
362         kfree(sbi);
363 }
364
365 static int nilfs_sync_fs(struct super_block *sb, int wait)
366 {
367         struct nilfs_sb_info *sbi = NILFS_SB(sb);
368         struct the_nilfs *nilfs = sbi->s_nilfs;
369         struct nilfs_super_block **sbp;
370         int err = 0;
371
372         /* This function is called when super block should be written back */
373         if (wait)
374                 err = nilfs_construct_segment(sb);
375
376         down_write(&nilfs->ns_sem);
377         if (nilfs_sb_dirty(nilfs)) {
378                 sbp = nilfs_prepare_super(sbi, nilfs_sb_will_flip(nilfs));
379                 if (likely(sbp)) {
380                         nilfs_set_log_cursor(sbp[0], nilfs);
381                         nilfs_commit_super(sbi, NILFS_SB_COMMIT);
382                 }
383         }
384         up_write(&nilfs->ns_sem);
385
386         return err;
387 }
388
389 int nilfs_attach_checkpoint(struct nilfs_sb_info *sbi, __u64 cno, int curr_mnt,
390                             struct nilfs_root **rootp)
391 {
392         struct the_nilfs *nilfs = sbi->s_nilfs;
393         struct nilfs_root *root;
394         struct nilfs_checkpoint *raw_cp;
395         struct buffer_head *bh_cp;
396         int err = -ENOMEM;
397
398         root = nilfs_find_or_create_root(
399                 nilfs, curr_mnt ? NILFS_CPTREE_CURRENT_CNO : cno);
400         if (!root)
401                 return err;
402
403         if (root->ifile)
404                 goto reuse; /* already attached checkpoint */
405
406         root->ifile = nilfs_ifile_new(sbi, nilfs->ns_inode_size);
407         if (!root->ifile)
408                 goto failed;
409
410         down_read(&nilfs->ns_segctor_sem);
411         err = nilfs_cpfile_get_checkpoint(nilfs->ns_cpfile, cno, 0, &raw_cp,
412                                           &bh_cp);
413         up_read(&nilfs->ns_segctor_sem);
414         if (unlikely(err)) {
415                 if (err == -ENOENT || err == -EINVAL) {
416                         printk(KERN_ERR
417                                "NILFS: Invalid checkpoint "
418                                "(checkpoint number=%llu)\n",
419                                (unsigned long long)cno);
420                         err = -EINVAL;
421                 }
422                 goto failed;
423         }
424         err = nilfs_read_inode_common(root->ifile, &raw_cp->cp_ifile_inode);
425         if (unlikely(err))
426                 goto failed_bh;
427
428         atomic_set(&root->inodes_count, le64_to_cpu(raw_cp->cp_inodes_count));
429         atomic_set(&root->blocks_count, le64_to_cpu(raw_cp->cp_blocks_count));
430
431         nilfs_cpfile_put_checkpoint(nilfs->ns_cpfile, cno, bh_cp);
432
433  reuse:
434         *rootp = root;
435         return 0;
436
437  failed_bh:
438         nilfs_cpfile_put_checkpoint(nilfs->ns_cpfile, cno, bh_cp);
439  failed:
440         nilfs_put_root(root);
441
442         return err;
443 }
444
445 static int nilfs_statfs(struct dentry *dentry, struct kstatfs *buf)
446 {
447         struct super_block *sb = dentry->d_sb;
448         struct nilfs_root *root = NILFS_I(dentry->d_inode)->i_root;
449         struct the_nilfs *nilfs = root->nilfs;
450         u64 id = huge_encode_dev(sb->s_bdev->bd_dev);
451         unsigned long long blocks;
452         unsigned long overhead;
453         unsigned long nrsvblocks;
454         sector_t nfreeblocks;
455         int err;
456
457         /*
458          * Compute all of the segment blocks
459          *
460          * The blocks before first segment and after last segment
461          * are excluded.
462          */
463         blocks = nilfs->ns_blocks_per_segment * nilfs->ns_nsegments
464                 - nilfs->ns_first_data_block;
465         nrsvblocks = nilfs->ns_nrsvsegs * nilfs->ns_blocks_per_segment;
466
467         /*
468          * Compute the overhead
469          *
470          * When distributing meta data blocks outside segment structure,
471          * We must count them as the overhead.
472          */
473         overhead = 0;
474
475         err = nilfs_count_free_blocks(nilfs, &nfreeblocks);
476         if (unlikely(err))
477                 return err;
478
479         buf->f_type = NILFS_SUPER_MAGIC;
480         buf->f_bsize = sb->s_blocksize;
481         buf->f_blocks = blocks - overhead;
482         buf->f_bfree = nfreeblocks;
483         buf->f_bavail = (buf->f_bfree >= nrsvblocks) ?
484                 (buf->f_bfree - nrsvblocks) : 0;
485         buf->f_files = atomic_read(&root->inodes_count);
486         buf->f_ffree = 0; /* nilfs_count_free_inodes(sb); */
487         buf->f_namelen = NILFS_NAME_LEN;
488         buf->f_fsid.val[0] = (u32)id;
489         buf->f_fsid.val[1] = (u32)(id >> 32);
490
491         return 0;
492 }
493
494 static int nilfs_show_options(struct seq_file *seq, struct vfsmount *vfs)
495 {
496         struct super_block *sb = vfs->mnt_sb;
497         struct nilfs_sb_info *sbi = NILFS_SB(sb);
498         struct nilfs_root *root = NILFS_I(vfs->mnt_root->d_inode)->i_root;
499
500         if (!nilfs_test_opt(sbi, BARRIER))
501                 seq_puts(seq, ",nobarrier");
502         if (root->cno != NILFS_CPTREE_CURRENT_CNO)
503                 seq_printf(seq, ",cp=%llu", (unsigned long long)root->cno);
504         if (nilfs_test_opt(sbi, ERRORS_PANIC))
505                 seq_puts(seq, ",errors=panic");
506         if (nilfs_test_opt(sbi, ERRORS_CONT))
507                 seq_puts(seq, ",errors=continue");
508         if (nilfs_test_opt(sbi, STRICT_ORDER))
509                 seq_puts(seq, ",order=strict");
510         if (nilfs_test_opt(sbi, NORECOVERY))
511                 seq_puts(seq, ",norecovery");
512         if (nilfs_test_opt(sbi, DISCARD))
513                 seq_puts(seq, ",discard");
514
515         return 0;
516 }
517
518 static const struct super_operations nilfs_sops = {
519         .alloc_inode    = nilfs_alloc_inode,
520         .destroy_inode  = nilfs_destroy_inode,
521         .dirty_inode    = nilfs_dirty_inode,
522         /* .write_inode    = nilfs_write_inode, */
523         /* .put_inode      = nilfs_put_inode, */
524         /* .drop_inode    = nilfs_drop_inode, */
525         .evict_inode    = nilfs_evict_inode,
526         .put_super      = nilfs_put_super,
527         /* .write_super    = nilfs_write_super, */
528         .sync_fs        = nilfs_sync_fs,
529         /* .write_super_lockfs */
530         /* .unlockfs */
531         .statfs         = nilfs_statfs,
532         .remount_fs     = nilfs_remount,
533         /* .umount_begin */
534         .show_options = nilfs_show_options
535 };
536
537 enum {
538         Opt_err_cont, Opt_err_panic, Opt_err_ro,
539         Opt_barrier, Opt_nobarrier, Opt_snapshot, Opt_order, Opt_norecovery,
540         Opt_discard, Opt_nodiscard, Opt_err,
541 };
542
543 static match_table_t tokens = {
544         {Opt_err_cont, "errors=continue"},
545         {Opt_err_panic, "errors=panic"},
546         {Opt_err_ro, "errors=remount-ro"},
547         {Opt_barrier, "barrier"},
548         {Opt_nobarrier, "nobarrier"},
549         {Opt_snapshot, "cp=%u"},
550         {Opt_order, "order=%s"},
551         {Opt_norecovery, "norecovery"},
552         {Opt_discard, "discard"},
553         {Opt_nodiscard, "nodiscard"},
554         {Opt_err, NULL}
555 };
556
557 static int parse_options(char *options, struct super_block *sb, int is_remount)
558 {
559         struct nilfs_sb_info *sbi = NILFS_SB(sb);
560         char *p;
561         substring_t args[MAX_OPT_ARGS];
562         int option;
563
564         if (!options)
565                 return 1;
566
567         while ((p = strsep(&options, ",")) != NULL) {
568                 int token;
569                 if (!*p)
570                         continue;
571
572                 token = match_token(p, tokens, args);
573                 switch (token) {
574                 case Opt_barrier:
575                         nilfs_set_opt(sbi, BARRIER);
576                         break;
577                 case Opt_nobarrier:
578                         nilfs_clear_opt(sbi, BARRIER);
579                         break;
580                 case Opt_order:
581                         if (strcmp(args[0].from, "relaxed") == 0)
582                                 /* Ordered data semantics */
583                                 nilfs_clear_opt(sbi, STRICT_ORDER);
584                         else if (strcmp(args[0].from, "strict") == 0)
585                                 /* Strict in-order semantics */
586                                 nilfs_set_opt(sbi, STRICT_ORDER);
587                         else
588                                 return 0;
589                         break;
590                 case Opt_err_panic:
591                         nilfs_write_opt(sbi, ERROR_MODE, ERRORS_PANIC);
592                         break;
593                 case Opt_err_ro:
594                         nilfs_write_opt(sbi, ERROR_MODE, ERRORS_RO);
595                         break;
596                 case Opt_err_cont:
597                         nilfs_write_opt(sbi, ERROR_MODE, ERRORS_CONT);
598                         break;
599                 case Opt_snapshot:
600                         if (match_int(&args[0], &option) || option <= 0)
601                                 return 0;
602                         if (is_remount) {
603                                 printk(KERN_ERR
604                                        "NILFS: \"%s\" option is invalid "
605                                        "for remount.\n", p);
606                                 return 0;
607                         }
608                         break;
609                 case Opt_norecovery:
610                         nilfs_set_opt(sbi, NORECOVERY);
611                         break;
612                 case Opt_discard:
613                         nilfs_set_opt(sbi, DISCARD);
614                         break;
615                 case Opt_nodiscard:
616                         nilfs_clear_opt(sbi, DISCARD);
617                         break;
618                 default:
619                         printk(KERN_ERR
620                                "NILFS: Unrecognized mount option \"%s\"\n", p);
621                         return 0;
622                 }
623         }
624         return 1;
625 }
626
627 static inline void
628 nilfs_set_default_options(struct nilfs_sb_info *sbi,
629                           struct nilfs_super_block *sbp)
630 {
631         sbi->s_mount_opt =
632                 NILFS_MOUNT_ERRORS_RO | NILFS_MOUNT_BARRIER;
633 }
634
635 static int nilfs_setup_super(struct nilfs_sb_info *sbi)
636 {
637         struct the_nilfs *nilfs = sbi->s_nilfs;
638         struct nilfs_super_block **sbp;
639         int max_mnt_count;
640         int mnt_count;
641
642         /* nilfs->ns_sem must be locked by the caller. */
643         sbp = nilfs_prepare_super(sbi, 0);
644         if (!sbp)
645                 return -EIO;
646
647         max_mnt_count = le16_to_cpu(sbp[0]->s_max_mnt_count);
648         mnt_count = le16_to_cpu(sbp[0]->s_mnt_count);
649
650         if (nilfs->ns_mount_state & NILFS_ERROR_FS) {
651                 printk(KERN_WARNING
652                        "NILFS warning: mounting fs with errors\n");
653 #if 0
654         } else if (max_mnt_count >= 0 && mnt_count >= max_mnt_count) {
655                 printk(KERN_WARNING
656                        "NILFS warning: maximal mount count reached\n");
657 #endif
658         }
659         if (!max_mnt_count)
660                 sbp[0]->s_max_mnt_count = cpu_to_le16(NILFS_DFL_MAX_MNT_COUNT);
661
662         sbp[0]->s_mnt_count = cpu_to_le16(mnt_count + 1);
663         sbp[0]->s_state =
664                 cpu_to_le16(le16_to_cpu(sbp[0]->s_state) & ~NILFS_VALID_FS);
665         sbp[0]->s_mtime = cpu_to_le64(get_seconds());
666         /* synchronize sbp[1] with sbp[0] */
667         memcpy(sbp[1], sbp[0], nilfs->ns_sbsize);
668         return nilfs_commit_super(sbi, NILFS_SB_COMMIT_ALL);
669 }
670
671 struct nilfs_super_block *nilfs_read_super_block(struct super_block *sb,
672                                                  u64 pos, int blocksize,
673                                                  struct buffer_head **pbh)
674 {
675         unsigned long long sb_index = pos;
676         unsigned long offset;
677
678         offset = do_div(sb_index, blocksize);
679         *pbh = sb_bread(sb, sb_index);
680         if (!*pbh)
681                 return NULL;
682         return (struct nilfs_super_block *)((char *)(*pbh)->b_data + offset);
683 }
684
685 int nilfs_store_magic_and_option(struct super_block *sb,
686                                  struct nilfs_super_block *sbp,
687                                  char *data)
688 {
689         struct nilfs_sb_info *sbi = NILFS_SB(sb);
690
691         sb->s_magic = le16_to_cpu(sbp->s_magic);
692
693         /* FS independent flags */
694 #ifdef NILFS_ATIME_DISABLE
695         sb->s_flags |= MS_NOATIME;
696 #endif
697
698         nilfs_set_default_options(sbi, sbp);
699
700         sbi->s_resuid = le16_to_cpu(sbp->s_def_resuid);
701         sbi->s_resgid = le16_to_cpu(sbp->s_def_resgid);
702         sbi->s_interval = le32_to_cpu(sbp->s_c_interval);
703         sbi->s_watermark = le32_to_cpu(sbp->s_c_block_max);
704
705         return !parse_options(data, sb, 0) ? -EINVAL : 0 ;
706 }
707
708 int nilfs_check_feature_compatibility(struct super_block *sb,
709                                       struct nilfs_super_block *sbp)
710 {
711         __u64 features;
712
713         features = le64_to_cpu(sbp->s_feature_incompat) &
714                 ~NILFS_FEATURE_INCOMPAT_SUPP;
715         if (features) {
716                 printk(KERN_ERR "NILFS: couldn't mount because of unsupported "
717                        "optional features (%llx)\n",
718                        (unsigned long long)features);
719                 return -EINVAL;
720         }
721         features = le64_to_cpu(sbp->s_feature_compat_ro) &
722                 ~NILFS_FEATURE_COMPAT_RO_SUPP;
723         if (!(sb->s_flags & MS_RDONLY) && features) {
724                 printk(KERN_ERR "NILFS: couldn't mount RDWR because of "
725                        "unsupported optional features (%llx)\n",
726                        (unsigned long long)features);
727                 return -EINVAL;
728         }
729         return 0;
730 }
731
732 static int nilfs_get_root_dentry(struct super_block *sb,
733                                  struct nilfs_root *root,
734                                  struct dentry **root_dentry)
735 {
736         struct inode *inode;
737         struct dentry *dentry;
738         int ret = 0;
739
740         inode = nilfs_iget(sb, root, NILFS_ROOT_INO);
741         if (IS_ERR(inode)) {
742                 printk(KERN_ERR "NILFS: get root inode failed\n");
743                 ret = PTR_ERR(inode);
744                 goto out;
745         }
746         if (!S_ISDIR(inode->i_mode) || !inode->i_blocks || !inode->i_size) {
747                 iput(inode);
748                 printk(KERN_ERR "NILFS: corrupt root inode.\n");
749                 ret = -EINVAL;
750                 goto out;
751         }
752
753         if (root->cno == NILFS_CPTREE_CURRENT_CNO) {
754                 dentry = d_find_alias(inode);
755                 if (!dentry) {
756                         dentry = d_alloc_root(inode);
757                         if (!dentry) {
758                                 iput(inode);
759                                 ret = -ENOMEM;
760                                 goto failed_dentry;
761                         }
762                 } else {
763                         iput(inode);
764                 }
765         } else {
766                 dentry = d_obtain_alias(inode);
767                 if (IS_ERR(dentry)) {
768                         ret = PTR_ERR(dentry);
769                         goto failed_dentry;
770                 }
771         }
772         *root_dentry = dentry;
773  out:
774         return ret;
775
776  failed_dentry:
777         printk(KERN_ERR "NILFS: get root dentry failed\n");
778         goto out;
779 }
780
781 static int nilfs_attach_snapshot(struct super_block *s, __u64 cno,
782                                  struct dentry **root_dentry)
783 {
784         struct the_nilfs *nilfs = NILFS_SB(s)->s_nilfs;
785         struct nilfs_root *root;
786         int ret;
787
788         down_read(&nilfs->ns_segctor_sem);
789         ret = nilfs_cpfile_is_snapshot(nilfs->ns_cpfile, cno);
790         up_read(&nilfs->ns_segctor_sem);
791         if (ret < 0) {
792                 ret = (ret == -ENOENT) ? -EINVAL : ret;
793                 goto out;
794         } else if (!ret) {
795                 printk(KERN_ERR "NILFS: The specified checkpoint is "
796                        "not a snapshot (checkpoint number=%llu).\n",
797                        (unsigned long long)cno);
798                 ret = -EINVAL;
799                 goto out;
800         }
801
802         ret = nilfs_attach_checkpoint(NILFS_SB(s), cno, false, &root);
803         if (ret) {
804                 printk(KERN_ERR "NILFS: error loading snapshot "
805                        "(checkpoint number=%llu).\n",
806                (unsigned long long)cno);
807                 goto out;
808         }
809         ret = nilfs_get_root_dentry(s, root, root_dentry);
810         nilfs_put_root(root);
811  out:
812         return ret;
813 }
814
815 static int nilfs_tree_was_touched(struct dentry *root_dentry)
816 {
817         return atomic_read(&root_dentry->d_count) > 1;
818 }
819
820 /**
821  * nilfs_try_to_shrink_tree() - try to shrink dentries of a checkpoint
822  * @root_dentry: root dentry of the tree to be shrunk
823  *
824  * This function returns true if the tree was in-use.
825  */
826 static int nilfs_try_to_shrink_tree(struct dentry *root_dentry)
827 {
828         if (have_submounts(root_dentry))
829                 return true;
830         shrink_dcache_parent(root_dentry);
831         return nilfs_tree_was_touched(root_dentry);
832 }
833
834 /**
835  * nilfs_fill_super() - initialize a super block instance
836  * @sb: super_block
837  * @data: mount options
838  * @silent: silent mode flag
839  *
840  * This function is called exclusively by nilfs->ns_mount_mutex.
841  * So, the recovery process is protected from other simultaneous mounts.
842  */
843 static int
844 nilfs_fill_super(struct super_block *sb, void *data, int silent)
845 {
846         struct the_nilfs *nilfs;
847         struct nilfs_sb_info *sbi;
848         struct nilfs_root *fsroot;
849         __u64 cno;
850         int err;
851
852         sbi = kzalloc(sizeof(*sbi), GFP_KERNEL);
853         if (!sbi)
854                 return -ENOMEM;
855
856         sb->s_fs_info = sbi;
857         sbi->s_super = sb;
858
859         nilfs = alloc_nilfs(sb->s_bdev);
860         if (!nilfs) {
861                 err = -ENOMEM;
862                 goto failed_sbi;
863         }
864         sbi->s_nilfs = nilfs;
865
866         err = init_nilfs(nilfs, sbi, (char *)data);
867         if (err)
868                 goto failed_nilfs;
869
870         spin_lock_init(&sbi->s_inode_lock);
871         INIT_LIST_HEAD(&sbi->s_dirty_files);
872
873         /*
874          * Following initialization is overlapped because
875          * nilfs_sb_info structure has been cleared at the beginning.
876          * But we reserve them to keep our interest and make ready
877          * for the future change.
878          */
879         get_random_bytes(&sbi->s_next_generation,
880                          sizeof(sbi->s_next_generation));
881         spin_lock_init(&sbi->s_next_gen_lock);
882
883         sb->s_op = &nilfs_sops;
884         sb->s_export_op = &nilfs_export_ops;
885         sb->s_root = NULL;
886         sb->s_time_gran = 1;
887         sb->s_bdi = nilfs->ns_bdi;
888
889         err = load_nilfs(nilfs, sbi);
890         if (err)
891                 goto failed_nilfs;
892
893         cno = nilfs_last_cno(nilfs);
894         err = nilfs_attach_checkpoint(sbi, cno, true, &fsroot);
895         if (err) {
896                 printk(KERN_ERR "NILFS: error loading last checkpoint "
897                        "(checkpoint number=%llu).\n", (unsigned long long)cno);
898                 goto failed_nilfs;
899         }
900
901         if (!(sb->s_flags & MS_RDONLY)) {
902                 err = nilfs_attach_segment_constructor(sbi, fsroot);
903                 if (err)
904                         goto failed_checkpoint;
905         }
906
907         err = nilfs_get_root_dentry(sb, fsroot, &sb->s_root);
908         if (err)
909                 goto failed_segctor;
910
911         nilfs_put_root(fsroot);
912
913         if (!(sb->s_flags & MS_RDONLY)) {
914                 down_write(&nilfs->ns_sem);
915                 nilfs_setup_super(sbi);
916                 up_write(&nilfs->ns_sem);
917         }
918
919         return 0;
920
921  failed_segctor:
922         nilfs_detach_segment_constructor(sbi);
923
924  failed_checkpoint:
925         nilfs_put_root(fsroot);
926
927  failed_nilfs:
928         destroy_nilfs(nilfs);
929
930  failed_sbi:
931         sb->s_fs_info = NULL;
932         kfree(sbi);
933         return err;
934 }
935
936 static int nilfs_remount(struct super_block *sb, int *flags, char *data)
937 {
938         struct nilfs_sb_info *sbi = NILFS_SB(sb);
939         struct the_nilfs *nilfs = sbi->s_nilfs;
940         unsigned long old_sb_flags;
941         struct nilfs_mount_options old_opts;
942         int err;
943
944         old_sb_flags = sb->s_flags;
945         old_opts.mount_opt = sbi->s_mount_opt;
946
947         if (!parse_options(data, sb, 1)) {
948                 err = -EINVAL;
949                 goto restore_opts;
950         }
951         sb->s_flags = (sb->s_flags & ~MS_POSIXACL);
952
953         err = -EINVAL;
954
955         if (!nilfs_valid_fs(nilfs)) {
956                 printk(KERN_WARNING "NILFS (device %s): couldn't "
957                        "remount because the filesystem is in an "
958                        "incomplete recovery state.\n", sb->s_id);
959                 goto restore_opts;
960         }
961
962         if ((*flags & MS_RDONLY) == (sb->s_flags & MS_RDONLY))
963                 goto out;
964         if (*flags & MS_RDONLY) {
965                 /* Shutting down the segment constructor */
966                 nilfs_detach_segment_constructor(sbi);
967                 sb->s_flags |= MS_RDONLY;
968
969                 /*
970                  * Remounting a valid RW partition RDONLY, so set
971                  * the RDONLY flag and then mark the partition as valid again.
972                  */
973                 down_write(&nilfs->ns_sem);
974                 nilfs_cleanup_super(sbi);
975                 up_write(&nilfs->ns_sem);
976         } else {
977                 __u64 features;
978                 struct nilfs_root *root;
979
980                 /*
981                  * Mounting a RDONLY partition read-write, so reread and
982                  * store the current valid flag.  (It may have been changed
983                  * by fsck since we originally mounted the partition.)
984                  */
985                 down_read(&nilfs->ns_sem);
986                 features = le64_to_cpu(nilfs->ns_sbp[0]->s_feature_compat_ro) &
987                         ~NILFS_FEATURE_COMPAT_RO_SUPP;
988                 up_read(&nilfs->ns_sem);
989                 if (features) {
990                         printk(KERN_WARNING "NILFS (device %s): couldn't "
991                                "remount RDWR because of unsupported optional "
992                                "features (%llx)\n",
993                                sb->s_id, (unsigned long long)features);
994                         err = -EROFS;
995                         goto restore_opts;
996                 }
997
998                 sb->s_flags &= ~MS_RDONLY;
999
1000                 root = NILFS_I(sb->s_root->d_inode)->i_root;
1001                 err = nilfs_attach_segment_constructor(sbi, root);
1002                 if (err)
1003                         goto restore_opts;
1004
1005                 down_write(&nilfs->ns_sem);
1006                 nilfs_setup_super(sbi);
1007                 up_write(&nilfs->ns_sem);
1008         }
1009  out:
1010         return 0;
1011
1012  restore_opts:
1013         sb->s_flags = old_sb_flags;
1014         sbi->s_mount_opt = old_opts.mount_opt;
1015         return err;
1016 }
1017
1018 struct nilfs_super_data {
1019         struct block_device *bdev;
1020         struct nilfs_sb_info *sbi;
1021         __u64 cno;
1022         int flags;
1023 };
1024
1025 /**
1026  * nilfs_identify - pre-read mount options needed to identify mount instance
1027  * @data: mount options
1028  * @sd: nilfs_super_data
1029  */
1030 static int nilfs_identify(char *data, struct nilfs_super_data *sd)
1031 {
1032         char *p, *options = data;
1033         substring_t args[MAX_OPT_ARGS];
1034         int option, token;
1035         int ret = 0;
1036
1037         do {
1038                 p = strsep(&options, ",");
1039                 if (p != NULL && *p) {
1040                         token = match_token(p, tokens, args);
1041                         if (token == Opt_snapshot) {
1042                                 if (!(sd->flags & MS_RDONLY))
1043                                         ret++;
1044                                 else {
1045                                         ret = match_int(&args[0], &option);
1046                                         if (!ret) {
1047                                                 if (option > 0)
1048                                                         sd->cno = option;
1049                                                 else
1050                                                         ret++;
1051                                         }
1052                                 }
1053                         }
1054                         if (ret)
1055                                 printk(KERN_ERR
1056                                        "NILFS: invalid mount option: %s\n", p);
1057                 }
1058                 if (!options)
1059                         break;
1060                 BUG_ON(options == data);
1061                 *(options - 1) = ',';
1062         } while (!ret);
1063         return ret;
1064 }
1065
1066 static int nilfs_set_bdev_super(struct super_block *s, void *data)
1067 {
1068         s->s_bdev = data;
1069         s->s_dev = s->s_bdev->bd_dev;
1070         return 0;
1071 }
1072
1073 static int nilfs_test_bdev_super(struct super_block *s, void *data)
1074 {
1075         return (void *)s->s_bdev == data;
1076 }
1077
1078 static int
1079 nilfs_get_sb(struct file_system_type *fs_type, int flags,
1080              const char *dev_name, void *data, struct vfsmount *mnt)
1081 {
1082         struct nilfs_super_data sd;
1083         struct super_block *s;
1084         fmode_t mode = FMODE_READ;
1085         struct dentry *root_dentry;
1086         int err, s_new = false;
1087
1088         if (!(flags & MS_RDONLY))
1089                 mode |= FMODE_WRITE;
1090
1091         sd.bdev = open_bdev_exclusive(dev_name, mode, fs_type);
1092         if (IS_ERR(sd.bdev))
1093                 return PTR_ERR(sd.bdev);
1094
1095         sd.cno = 0;
1096         sd.flags = flags;
1097         if (nilfs_identify((char *)data, &sd)) {
1098                 err = -EINVAL;
1099                 goto failed;
1100         }
1101
1102         s = sget(fs_type, nilfs_test_bdev_super, nilfs_set_bdev_super, sd.bdev);
1103         if (IS_ERR(s)) {
1104                 err = PTR_ERR(s);
1105                 goto failed;
1106         }
1107
1108         if (!s->s_root) {
1109                 char b[BDEVNAME_SIZE];
1110
1111                 s_new = true;
1112
1113                 /* New superblock instance created */
1114                 s->s_flags = flags;
1115                 s->s_mode = mode;
1116                 strlcpy(s->s_id, bdevname(sd.bdev, b), sizeof(s->s_id));
1117                 sb_set_blocksize(s, block_size(sd.bdev));
1118
1119                 err = nilfs_fill_super(s, data, flags & MS_SILENT ? 1 : 0);
1120                 if (err)
1121                         goto failed_super;
1122
1123                 s->s_flags |= MS_ACTIVE;
1124         } else if (!sd.cno) {
1125                 int busy = false;
1126
1127                 if (nilfs_tree_was_touched(s->s_root)) {
1128                         busy = nilfs_try_to_shrink_tree(s->s_root);
1129                         if (busy && (flags ^ s->s_flags) & MS_RDONLY) {
1130                                 printk(KERN_ERR "NILFS: the device already "
1131                                        "has a %s mount.\n",
1132                                        (s->s_flags & MS_RDONLY) ?
1133                                        "read-only" : "read/write");
1134                                 err = -EBUSY;
1135                                 goto failed_super;
1136                         }
1137                 }
1138                 if (!busy) {
1139                         /*
1140                          * Try remount to setup mount states if the current
1141                          * tree is not mounted and only snapshots use this sb.
1142                          */
1143                         err = nilfs_remount(s, &flags, data);
1144                         if (err)
1145                                 goto failed_super;
1146                 }
1147         }
1148
1149         if (sd.cno) {
1150                 err = nilfs_attach_snapshot(s, sd.cno, &root_dentry);
1151                 if (err)
1152                         goto failed_super;
1153         } else {
1154                 root_dentry = dget(s->s_root);
1155         }
1156
1157         if (!s_new)
1158                 close_bdev_exclusive(sd.bdev, mode);
1159
1160         mnt->mnt_sb = s;
1161         mnt->mnt_root = root_dentry;
1162         return 0;
1163
1164  failed_super:
1165         deactivate_locked_super(s);
1166
1167  failed:
1168         if (!s_new)
1169                 close_bdev_exclusive(sd.bdev, mode);
1170         return err;
1171 }
1172
1173 struct file_system_type nilfs_fs_type = {
1174         .owner    = THIS_MODULE,
1175         .name     = "nilfs2",
1176         .get_sb   = nilfs_get_sb,
1177         .kill_sb  = kill_block_super,
1178         .fs_flags = FS_REQUIRES_DEV,
1179 };
1180
1181 static void nilfs_inode_init_once(void *obj)
1182 {
1183         struct nilfs_inode_info *ii = obj;
1184
1185         INIT_LIST_HEAD(&ii->i_dirty);
1186 #ifdef CONFIG_NILFS_XATTR
1187         init_rwsem(&ii->xattr_sem);
1188 #endif
1189         nilfs_btnode_cache_init_once(&ii->i_btnode_cache);
1190         ii->i_bmap = &ii->i_bmap_data;
1191         inode_init_once(&ii->vfs_inode);
1192 }
1193
1194 static void nilfs_segbuf_init_once(void *obj)
1195 {
1196         memset(obj, 0, sizeof(struct nilfs_segment_buffer));
1197 }
1198
1199 static void nilfs_destroy_cachep(void)
1200 {
1201         if (nilfs_inode_cachep)
1202                 kmem_cache_destroy(nilfs_inode_cachep);
1203         if (nilfs_transaction_cachep)
1204                 kmem_cache_destroy(nilfs_transaction_cachep);
1205         if (nilfs_segbuf_cachep)
1206                 kmem_cache_destroy(nilfs_segbuf_cachep);
1207         if (nilfs_btree_path_cache)
1208                 kmem_cache_destroy(nilfs_btree_path_cache);
1209 }
1210
1211 static int __init nilfs_init_cachep(void)
1212 {
1213         nilfs_inode_cachep = kmem_cache_create("nilfs2_inode_cache",
1214                         sizeof(struct nilfs_inode_info), 0,
1215                         SLAB_RECLAIM_ACCOUNT, nilfs_inode_init_once);
1216         if (!nilfs_inode_cachep)
1217                 goto fail;
1218
1219         nilfs_transaction_cachep = kmem_cache_create("nilfs2_transaction_cache",
1220                         sizeof(struct nilfs_transaction_info), 0,
1221                         SLAB_RECLAIM_ACCOUNT, NULL);
1222         if (!nilfs_transaction_cachep)
1223                 goto fail;
1224
1225         nilfs_segbuf_cachep = kmem_cache_create("nilfs2_segbuf_cache",
1226                         sizeof(struct nilfs_segment_buffer), 0,
1227                         SLAB_RECLAIM_ACCOUNT, nilfs_segbuf_init_once);
1228         if (!nilfs_segbuf_cachep)
1229                 goto fail;
1230
1231         nilfs_btree_path_cache = kmem_cache_create("nilfs2_btree_path_cache",
1232                         sizeof(struct nilfs_btree_path) * NILFS_BTREE_LEVEL_MAX,
1233                         0, 0, NULL);
1234         if (!nilfs_btree_path_cache)
1235                 goto fail;
1236
1237         return 0;
1238
1239 fail:
1240         nilfs_destroy_cachep();
1241         return -ENOMEM;
1242 }
1243
1244 static int __init init_nilfs_fs(void)
1245 {
1246         int err;
1247
1248         err = nilfs_init_cachep();
1249         if (err)
1250                 goto fail;
1251
1252         err = register_filesystem(&nilfs_fs_type);
1253         if (err)
1254                 goto free_cachep;
1255
1256         printk(KERN_INFO "NILFS version 2 loaded\n");
1257         return 0;
1258
1259 free_cachep:
1260         nilfs_destroy_cachep();
1261 fail:
1262         return err;
1263 }
1264
1265 static void __exit exit_nilfs_fs(void)
1266 {
1267         nilfs_destroy_cachep();
1268         unregister_filesystem(&nilfs_fs_type);
1269 }
1270
1271 module_init(init_nilfs_fs)
1272 module_exit(exit_nilfs_fs)